Skip to content

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

feat(frontend): migrate project plan detail to react (#20081)

boojackb001f2b9d756
diff --git a/docs/plans/2026-04-13-project-plan-detail-react-migration.md b/docs/plans/2026-04-13-project-plan-detail-react-migration.md
new file mode 100644
index 0000000000..cb81d4f831
--- /dev/null
+++ b/docs/plans/2026-04-13-project-plan-detail-react-migration.md
@@ -0,0 +1,355 @@
+# Project Plan Detail React Migration
+
+## Goal
+
+Migrate `planRoutes` / `planDetailComponent` from Vue to React with Vue parity as the default target:
+
+- layout parity
+- interaction parity
+- style parity
+- no product-behavior changes without explicit confirmation
+
+Vue reference implementation stays in place during the migration.
+
+## Route Scope
+
+- `PROJECT_V1_ROUTE_PLAN_DETAIL`
+- `PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS`
+- `PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL`
+- legacy rollout redirects that resolve into the routes above
+
+## Inventory
+
+### Route Entry
+
+- `frontend/src/router/dashboard/projectV1.ts`
+- `frontend/src/router/dashboard/projectV1RouteHelpers.ts`
+
+### Vue Page Entry
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanDetailLayout.vue`
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanDetailPage.vue`
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanDetailHeader.vue`
+
+### Page-Level Vue Logic
+
+- `frontend/src/components/Plan/logic/context.ts`
+- `frontend/src/components/Plan/logic/base.ts`
+- `frontend/src/components/Plan/logic/sidebar.ts`
+- `frontend/src/components/Plan/logic/useEditorState.ts`
+- `frontend/src/components/Plan/logic/useNavigationGuard.ts`
+- `frontend/src/components/Plan/PollerProvider.vue`
+- `frontend/src/components/Plan/logic/poller/poller.ts`
+- `frontend/src/components/Plan/logic/poller/utils.ts`
+- `frontend/src/components/Plan/logic/initialize/index.ts`
+- `frontend/src/components/Plan/logic/initialize/create.ts`
+- `frontend/src/components/Plan/logic/initialize/util.ts`
+
+### Page Structure / Layout
+
+- `frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailViewportVars.ts`
+- `frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailDesktopLayout.ts`
+- `frontend/src/components/Plan/components/PlanDetailPage/useActivePhase.ts`
+- `frontend/src/components/Plan/components/PlanDetailPage/usePhaseState.ts`
+- `frontend/src/components/Plan/components/PlanDetailPage/usePhaseSummaries.ts`
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanDetailDesktopColumn.vue`
+- `frontend/src/components/Plan/components/PlanDetailPage/StickySidePanel.vue`
+- `frontend/src/layouts/common.ts`
+
+### Changes Branch
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanSectionChanges.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/*.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/context.ts`
+- `frontend/src/components/Plan/components/StatementSection/*.vue`
+- `frontend/src/components/Plan/components/StatementSection/*.ts`
+- `frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue`
+- `frontend/src/components/Plan/components/ChecksView/*.vue`
+- `frontend/src/components/Plan/components/Configuration/**/*.vue`
+- `frontend/src/components/Plan/components/Configuration/**/*.ts`
+- `frontend/src/components/Plan/components/AddSpecDrawer.vue`
+- `frontend/src/components/Plan/components/common/*.vue`
+- `frontend/src/components/Plan/components/common/validateSpec.ts`
+
+### Review Branch
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanSectionReview.vue`
+- `frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/*.vue`
+- `frontend/src/components/Plan/components/IssueReviewView/Sidebar/ApprovalFlowSection/*.ts`
+- `frontend/src/store/modules/v1/issueComment.ts`
+
+### Deploy Branch
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanSectionDeploy.vue`
+- `frontend/src/components/Plan/components/PlanDetailPage/DeployFutureAction.vue`
+- `frontend/src/components/Plan/components/PlanDetailPage/TaskDetailPanel.vue`
+- `frontend/src/components/RolloutV1/components/Stage/*.vue`
+- `frontend/src/components/RolloutV1/components/Stage/*.ts`
+- `frontend/src/components/RolloutV1/components/Task/*.vue`
+- `frontend/src/components/RolloutV1/components/Task/*.ts`
+- `frontend/src/components/RolloutV1/components/TaskRun/**/*.vue`
+- `frontend/src/components/RolloutV1/components/TaskRun/**/*.ts`
+- `frontend/src/store/modules/v1/taskRunLog.ts`
+
+### Sidebar / Metadata
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanMetadataSidebar.vue`
+- `frontend/src/components/Plan/components/PlanCheckStatusCount.vue`
+- `frontend/src/components/Plan/components/RefreshIndicator.vue`
+
+### Shared High-Risk Capabilities
+
+- Monaco editor and LSP:
+ - `frontend/src/components/MonacoEditor/**`
+ - `frontend/src/react/components/monaco/**`
+- Markdown editor:
+ - `frontend/src/components/MarkdownEditor/**`
+- Schema editor:
+ - `frontend/src/components/SchemaEditorLite/**`
+- Drawer / table / button:
+ - `frontend/src/components/v2/Container/**`
+ - `frontend/src/react/components/ui/button.tsx`
+ - `frontend/src/react/components/ui/sheet.tsx`
+ - `frontend/src/react/components/ui/table.tsx`
+
+## Migration Order
+
+1. React route entry
+2. Page skeleton
+3. Content branches
+4. Leaf components
+5. Shared capability wiring
+6. Visual parity pass
+
+## Execution Checklist
+
+- [x] Inventory Vue route/page tree to leaf nodes
+- [x] Record non-goals and parity constraints
+- [x] Switch route entry to React and keep Vue files as reference
+- [x] Build React page skeleton: header/content/sidebar/detail-panel/scroll model
+- [x] Recreate route-driven phase expansion and task detail panel state
+- [x] Recreate initialize/load state for existing plan and create-plan flow
+- [x] Recreate polling and manual refresh without assuming rollout/plan always exist
+- [x] Migrate changes branch shell
+- [x] Migrate review branch shell
+- [x] Migrate deploy branch shell
+- [ ] Migrate changes leaf components
+- [ ] Migrate deploy/task detail leaf components
+- [ ] Migrate sidebar metadata
+- [ ] Migrate high-risk editor integrations deliberately
+- [x] Run `pnpm --dir frontend fix`
+- [x] Run `pnpm --dir frontend check`
+- [x] Run `pnpm --dir frontend type-check`
+- [x] Run `pnpm --dir frontend test`
+
+## Explicit Non-Goals
+
+- Delete Vue reference implementation
+- Change global shared component behavior for this page migration
+- Add new product capabilities outside Vue parity
+- Optimize workflows that are not already present on the Vue page
+- Treat Monaco / task-run-log / schema-editor as ordinary UI leaves
+
+## Current Batch
+
+Batch 1 target:
+
+- switch route entry to React
+- implement React skeleton and route/query-driven shell
+- keep deeper content leaves as follow-up work
+
+Batch 2 progress:
+
+- changes branch now renders React spec tabs, targets, statement editor/release view, checks, and readonly option summary
+- changes branch tabs/content container/all-targets drawer now follow Vue `SpecListSection` and `SpecDetailView` layout more closely
+- create-plan statement editing now works against local sheet state
+- navigation guard now respects editing scopes in the React page
+- sidebar now shows created-by/time, status, checks summary, issue labels, rollout stages, and refresh state
+- deploy task detail now shows stage/environment, target database, latest task run log, and task run history
+- sidebar approval flow is now wired in React, including re-request review and candidate display
+- task detail now supports task-level RUN / SKIP / CANCEL actions in React
+- changes branch now supports add spec, delete spec, and target selector sheets in React
+- changes branch readonly option summary is now partially editable in React
+- deploy branch now supports stage-level RUN / SKIP / CANCEL actions in React
+- task detail now includes a session tab and single-task rollback flow in React
+- header now supports title/description editing, create plan, ready-for-review, and close/reopen in React
+- create-plan change specs now support draft SQL checks in React
+- review branch now uses split approval-flow composition so page review section and sidebar no longer fight over layout
+- deploy branch has been extracted into `frontend/src/react/pages/project/plan-detail/components/deploy/`
+- deploy stage/task shell now follows Vue structure more closely:
+ - stage navigation bar
+ - stage content view
+ - task list
+ - task toolbar
+ - task item
+ - stage content sidebar
+- deploy desktop inline detail panel and mobile drawer now follow Vue desktop/drawer layout more closely
+- pending tasks preview / create rollout flow is now wired in React
+- task run history/session/rollback leaves now match Vue behavior more closely:
+ - Postgres session tab visibility matches Vue
+ - task run comment troubleshoot link is wired
+ - rollback sheet supports multi-task preview/create flow
+ - rollback create permission is enforced
+- rollout/task status stringification is now safe to call from React without Vue `useI18n()` runtime errors
+
+Batch 3 behavior parity pass:
+
+- future review/deploy phase content now renders instead of only summary text
+- phase collapsed summaries now use Vue-equivalent i18n summaries for changes, review, and deploy
+- ready-for-review now matches Vue warning acknowledgement and post-create navigation behavior
+- sidebar status mapping now follows Vue review/rollout status rules
+- task row/detail quick actions now respect rollout permissions before displaying
+- task row/detail statements now fetch missing sheets and show truncation hints
+
+Changes branch parity pass:
+
+- SQL advice markers are now wired into the React statement editor for existing-plan checks and create-plan draft checks
+- draft SQL checks now expose formatted plan check runs back to the statement editor
+- checks summary/grouping/draft transform logic has been extracted into tested React helpers
+- target database-group inline/overflow behavior and options visibility logic have tested helpers
+- options row spacing/label styling and target chip density have been brought closer to Vue
+- selected spec fallback, all-target filtering, and database-group route params now use tested React helpers
+- database-group target display now follows Vue's plain-name plus external-link behavior more closely
+- persisted and draft checks now share the same tested grouping/summary helpers
+- excluded by current instruction:
+ - Schema Editor drawer
+ - expanded editor modal
+
+Batch 3 remaining focus:
+
+- deploy visual parity pass against Vue tailwind
+- remaining `StageNavigationBar` / `StageContentView` spacing rhythm
+- remaining `TaskToolbar` / `TaskItem` / `StageTimeline` row-level parity
+- final residual-gap sweep before calling deploy branch done
+
+## Residual Gaps After Batch 1
+
+- full editable header parity:
+ - major interactions exist
+ - visual/detail parity still pending
+- full changes branch parity:
+- create-plan SQL check parity is now present
+- full checks/configuration parity
+- deploy action parity
+- deploy action parity:
+ - task-level run/skip/cancel exists
+ - stage-level run/skip/cancel exists
+ - pending task preview/create rollout now exists
+ - broader rollout actions still need final parity sweep
+- task detail log/session/rollback parity:
+ - session tab exists
+ - single-task rollback exists
+ - multi-task rollback flow now exists
+ - task history/session tables still need final visual parity sweep
+- metadata sidebar parity:
+ - approval flow present, but still not pixel/interaction identical to Vue
+- visual spacing/sticky behavior parity
+- no Vue-to-React leaf replacement yet for Monaco / markdown / schema editor / task-run log
+
+## Focused Plan: `PlanDetailChangesBranch.tsx`
+
+This phase is scoped to the React changes branch only:
+
+- `frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx`
+- `frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx`
+- `frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx`
+- `frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx`
+
+The goal is to finish this branch to Vue parity before moving back to header/sidebar/deploy cleanup.
+
+### Vue References To Match
+
+- `frontend/src/components/Plan/components/PlanDetailPage/PlanSectionChanges.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/SpecDetailView.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/SpecListSection.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/TargetListSection.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/TargetsSelectorDrawer.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/AllTargetsDrawer.vue`
+- `frontend/src/components/Plan/components/SpecDetailView/DatabaseGroupTargetDisplay.vue`
+- `frontend/src/components/Plan/components/StatementSection/StatementSection.vue`
+- `frontend/src/components/Plan/components/StatementSection/EditorView/EditorView.vue`
+- `frontend/src/components/Plan/components/StatementSection/ReleaseView/ReleaseView.vue`
+- `frontend/src/components/Plan/components/PlanCheckSection/PlanCheckSection.vue`
+- `frontend/src/components/Plan/components/SQLCheckV1Section/SQLCheckV1Section.vue`
+- `frontend/src/components/Plan/components/IssueReviewView/DatabaseChangeView/OptionsSection.vue`
+
+### Execution Order
+
+1. Container parity
+2. Targets parity
+3. SQL parity
+4. Checks parity
+5. Options parity
+6. Drawer/modal parity
+7. Edge-case parity
+8. Visual tailwind pass
+
+### Detailed Checklist
+
+- [ ] Tabs and container parity
+ - match `SpecListSection.vue` line-tab rhythm exactly
+ - match suffix action placement for `Add Change`
+ - match content container padding/scrolling from `SpecDetailView.vue`
+ - keep route-driven selected spec behavior identical
+
+- [ ] Targets section parity
+ - match title row typography and button size
+ - match warning alert spacing and child row density
+ - match target chip height, padding, font size, icon spacing, environment text color
+ - finish database-group target parity:
+ - header row
+ - flat child chip layout
+ - `n more` behavior
+ - external link behavior
+ - match empty/loading/view-all states
+
+- [ ] SQL section parity
+ - match title row typography, button sizing, and wrapping
+ - match oversized-sheet warning spacing and action placement
+ - match Monaco container border radius, height, and surrounding whitespace
+ - match readonly/edit mode toolbar behavior
+ - match release-view card spacing and typography
+ - SQL advice markers are wired
+ - excluded for now:
+ - Schema Editor drawer
+ - expanded editor modal
+ - do not change Monaco/LSP behavior beyond parity needs
+
+- [ ] Checks section parity
+ - match title row spacing and run button size
+ - match status badge density, icons, labels, and selected state
+ - match affected-rows badge styling
+ - match draft checks and persisted checks presentation separately
+ - match checks drawer/sheet grouping, card spacing, and empty state
+
+- [ ] Options section parity
+ - match title style exactly
+ - match per-item label color and baseline
+ - match switch/select height and alignment
+ - match horizontal/vertical spacing across wrap points
+ - preserve current behavior for planless/create-plan/read-only/oversized-sheet cases
+
+- [ ] Selector/drawer parity
+ - match target selector tabs, table spacing, and footer button rhythm
+ - match all-targets drawer width, header spacing, search spacing, and chip list density
+ - avoid changing global `sheet`, `select`, or `button` behavior
+
+- [ ] Edge-case verification
+ - verify Vue behavior first for each suspected bug
+ - verify create-plan vs existing-plan behavior separately
+ - verify release-backed spec vs sheet-backed spec separately
+ - verify database-group targets and plain database targets separately
+ - verify no-plan / no-rollout / no-check-result states remain reachable and correct
+
+### Acceptance Criteria
+
+- Every section in the React changes branch maps 1:1 to the Vue section it replaces
+- Section titles use the same hierarchy and color intent as Vue
+- Control sizes and vertical rhythm are consistent across `targets`, `sql`, `checks`, and `options`
+- Database-group targets use the same layout model as Vue, not an improvised tree UI
+- Draft checks and persisted checks preserve their distinct Vue behavior
+- No new product capability is added in this branch
+- `pnpm --dir frontend fix`
+- `pnpm --dir frontend check`
+- `pnpm --dir frontend type-check`
+- `pnpm --dir frontend test`
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/DeployFutureAction.vue b/frontend/src/components/Plan/components/PlanDetailPage/DeployFutureAction.vue
deleted file mode 100644
index 0121334697..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/DeployFutureAction.vue
+++ /dev/null
@@ -1,215 +0,0 @@
-<template>
- <div class="mt-1.5">
- <p class="text-sm text-control-placeholder">
- {{ $t("plan.phase.deploy-description") }}
- </p>
-
- <ul class="mt-2.5 max-w-[28rem] space-y-1">
- <li
- v-for="item in requirementItems"
- :key="item.key"
- class="flex items-start gap-2 py-1"
- >
- <div class="flex items-start gap-2 min-w-0">
- <component
- :is="item.icon"
- class="mt-0.5 h-3.5 w-3.5 shrink-0"
- :class="item.iconClass"
- />
- <div class="min-w-0">
- <div class="flex items-center gap-1.5 flex-wrap">
- <span class="text-xs font-medium text-control">
- {{ item.label }}
- </span>
- <span
- v-if="item.required"
- class="text-[10px] font-medium text-error/80"
- >
- *
- </span>
- <span
- class="text-[11px] font-medium"
- :class="item.statusClass"
- >
- {{ item.tagLabel }}
- </span>
- </div>
- <p class="mt-0.5 text-[11px] text-control-placeholder">
- {{ item.description }}
- </p>
- </div>
- </div>
- </li>
- </ul>
-
- <div
- v-if="showManualCreateRolloutHint"
- class="mt-3 flex max-w-[28rem] flex-col items-start gap-y-2"
- >
- <p class="text-xs text-control-placeholder">
- {{ manualCreateRolloutDescription }}
- </p>
- <NButton
- v-if="canCreateRollout"
- secondary
- strong
- size="small"
- @click="showRolloutCreatePanel = true"
- >
- {{ $t("plan.phase.create-rollout-action") }}
- </NButton>
- </div>
-
- <RolloutCreatePanel
- :show="showRolloutCreatePanel"
- :context="actionContext"
- @close="showRolloutCreatePanel = false"
- @confirm="showRolloutCreatePanel = false"
- />
- </div>
-</template>
-
-<script setup lang="ts">
-import {
- CheckCircle2Icon,
- CircleAlertIcon,
- Clock3Icon,
- MinusCircleIcon,
-} from "lucide-vue-next";
-import { NButton } from "naive-ui";
-import { computed, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import { useCurrentProjectV1 } from "@/store";
-import { State } from "@/types/proto-es/v1/common_pb";
-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
-import { usePlanContext } from "../../logic";
-import RolloutCreatePanel from "../HeaderSection/Actions/create/RolloutCreatePanel.vue";
-import { useActionRegistry } from "../HeaderSection/Actions/registry/useActionRegistry";
-
-const { plan, issue } = usePlanContext();
-const { context: actionContext } = useActionRegistry();
-const { project } = useCurrentProjectV1();
-const { t } = useI18n();
-
-const showRolloutCreatePanel = ref(false);
-
-const canCreateRollout = computed(() => {
- if (!issue.value) return false;
- if (plan.value.hasRollout) return false;
- if (plan.value.state !== State.ACTIVE) return false;
- if (issue.value.status !== IssueStatus.OPEN) return false;
- if (!actionContext.value.permissions.createRollout) return false;
- return true;
-});
-
-const showManualCreateRolloutHint = computed(() => {
- if (!issue.value) return false;
- if (plan.value.hasRollout) return false;
- if (plan.value.state !== State.ACTIVE) return false;
- if (issue.value.status !== IssueStatus.OPEN) return false;
- if (
- project.value.requireIssueApproval &&
- !actionContext.value.issueApproved
- ) {
- return false;
- }
- if (
- project.value.requirePlanCheckNoError &&
- actionContext.value.validation.planChecksFailed
- ) {
- return false;
- }
- return (
- !project.value.requireIssueApproval ||
- !project.value.requirePlanCheckNoError
- );
-});
-
-const manualCreateRolloutDescription = computed(() => {
- if (actionContext.value.permissions.createRollout) {
- return t("plan.phase.deploy-manual-create-description");
- }
- return t("plan.phase.deploy-manual-create-description-readonly");
-});
-
-const requirementItems = computed(() => {
- const approvalItem = project.value.requireIssueApproval
- ? actionContext.value.issueApproved
- ? {
- key: "approval",
- label: t("plan.phase.deploy-approval-must-complete"),
- description: t("plan.phase.deploy-approval-ready"),
- tagLabel: t("common.done"),
- statusClass: "text-success",
- icon: CheckCircle2Icon,
- iconClass: "text-success/80",
- required: true,
- }
- : {
- key: "approval",
- label: t("plan.phase.deploy-approval-must-complete"),
- description: t("plan.phase.deploy-approval-pending"),
- tagLabel: t("common.pending"),
- statusClass: "text-warning",
- icon: Clock3Icon,
- iconClass: "text-warning/80",
- required: true,
- }
- : {
- key: "approval",
- label: t("plan.phase.deploy-approval-must-complete"),
- description: t("plan.phase.deploy-approval-optional"),
- tagLabel: t("common.optional"),
- statusClass: "text-control-placeholder",
- icon: MinusCircleIcon,
- iconClass: "text-control-placeholder",
- required: false,
- };
-
- const checksItem = project.value.requirePlanCheckNoError
- ? actionContext.value.validation.planChecksRunning
- ? {
- key: "checks",
- label: t("plan.phase.deploy-checks-must-pass"),
- description: t("plan.phase.deploy-checks-running"),
- tagLabel: t("common.in-progress"),
- statusClass: "text-warning",
- icon: Clock3Icon,
- iconClass: "text-warning/80",
- required: true,
- }
- : actionContext.value.validation.planChecksFailed
- ? {
- key: "checks",
- label: t("plan.phase.deploy-checks-must-pass"),
- description: t("plan.phase.deploy-checks-blocked"),
- tagLabel: t("common.failed"),
- statusClass: "text-error",
- icon: CircleAlertIcon,
- iconClass: "text-error/80",
- required: true,
- }
- : {
- key: "checks",
- label: t("plan.phase.deploy-checks-must-pass"),
- description: t("plan.phase.deploy-checks-ready"),
- tagLabel: t("common.done"),
- statusClass: "text-success",
- icon: CheckCircle2Icon,
- iconClass: "text-success/80",
- required: true,
- }
- : {
- key: "checks",
- label: t("plan.phase.deploy-checks-must-pass"),
- description: t("plan.phase.deploy-checks-optional"),
- tagLabel: t("common.optional"),
- statusClass: "text-control-placeholder",
- icon: MinusCircleIcon,
- iconClass: "text-control-placeholder",
- required: false,
- };
-
- return [checksItem, approvalItem];
-});
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailDesktopColumn.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailDesktopColumn.vue
deleted file mode 100644
index 3b8847c150..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailDesktopColumn.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <component
- :is="props.tag"
- class="min-w-0 border-l bg-white"
- :style="columnStyle"
- >
- <StickySidePanel>
- <template v-if="$slots.header" #header>
- <slot name="header" />
- </template>
- <slot />
- </StickySidePanel>
- </component>
-</template>
-
-<script setup lang="ts">
-import type { CSSProperties } from "vue";
-import { computed } from "vue";
-import StickySidePanel from "./StickySidePanel.vue";
-import { PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR } from "./usePlanDetailViewportVars";
-
-const props = withDefaults(
- defineProps<{
- tag?: "aside" | "div";
- }>(),
- {
- tag: "div",
- }
-);
-
-const columnStyle = computed<CSSProperties>(() => ({
- minHeight: `var(${PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR})`,
-}));
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailHeader.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailHeader.vue
deleted file mode 100644
index 62395371ef..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailHeader.vue
+++ /dev/null
@@ -1,187 +0,0 @@
-<template>
- <div class="py-2 px-2 sm:px-4">
- <div class="flex flex-row items-center justify-between gap-2">
- <!-- Status tags (closed/done) -->
- <NTag v-if="isClosed" round type="default">
- <template #icon>
- <BanIcon class="w-4 h-4" />
- </template>
- {{ $t("common.closed") }}
- </NTag>
-
- <!-- Title -->
- <TitleInput />
-
- <!-- Actions -->
- <div class="flex items-center gap-x-2">
- <!-- Create plan (when creating) -->
- <CreateButton v-if="isCreating" />
-
- <!-- Submit for Review (plan exists, no issue yet) -->
- <template v-else>
- <CreateIssueButton
- v-if="showSubmitForReview"
- :disabled="submitDisabled"
- :disabled-reason="submitDisabledReason"
- />
-
- <!-- Close / Reopen plan (no issue, no rollout) -->
- <NButton
- v-if="showClosePlan"
- size="medium"
- @click="handleClosePlan"
- >
- {{ $t("common.close") }}
- </NButton>
- <NButton
- v-if="showReopenPlan"
- size="medium"
- @click="handleReopenPlan"
- >
- {{ $t("common.reopen") }}
- </NButton>
- </template>
-
- <!-- Sidebar toggle for small screens -->
- <NButton
- v-if="showSidebarToggle"
- quaternary
- size="medium"
- @click="mobileSidebarOpen = true"
- >
- <template #icon>
- <MenuIcon class="w-5 h-5" />
- </template>
- </NButton>
- </div>
- </div>
- <DescriptionSection v-if="showDescription" />
- </div>
-</template>
-
-<script setup lang="ts">
-import { clone, create } from "@bufbuild/protobuf";
-import { BanIcon, MenuIcon } from "lucide-vue-next";
-import { NButton, NTag, useDialog } from "naive-ui";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { planServiceClientConnect } from "@/connect";
-import { pushNotification } from "@/store";
-import { State } from "@/types/proto-es/v1/common_pb";
-import {
- PlanSchema,
- UpdatePlanRequestSchema,
-} from "@/types/proto-es/v1/plan_service_pb";
-import { isValidPlanName } from "@/utils";
-import { emitPlanStatusChanged, usePlanContext } from "../../logic";
-import { useSidebarContext } from "../../logic/sidebar";
-import { useEditorState } from "../../logic/useEditorState";
-import {
- CreateButton,
- CreateIssueButton,
-} from "../HeaderSection/Actions/create";
-import DescriptionSection from "../HeaderSection/DescriptionSection.vue";
-import TitleInput from "../HeaderSection/TitleInput.vue";
-
-const { t } = useI18n();
-const dialog = useDialog();
-
-const { isCreating, plan, events } = usePlanContext();
-const editorState = useEditorState();
-const { mode: sidebarMode, mobileSidebarOpen } = useSidebarContext();
-
-const isClosed = computed(() => {
- return plan.value.state === State.DELETED;
-});
-
-const showDescription = computed(() => {
- if (isCreating.value) return true;
- return isValidPlanName(plan.value.name);
-});
-
-const showSidebarToggle = computed(() => {
- return sidebarMode.value === "MOBILE";
-});
-
-// Submit for Review: visible when plan exists, no issue, plan is active
-const showSubmitForReview = computed(() => {
- return (
- isValidPlanName(plan.value.name) &&
- !plan.value.issue &&
- plan.value.state === State.ACTIVE
- );
-});
-
-const submitDisabled = computed(() => editorState.isEditing.value);
-const submitDisabledReason = computed(() =>
- submitDisabled.value
- ? t("plan.editor.save-changes-before-continuing")
- : undefined
-);
-
-// Close plan: visible when plan exists, active, no issue/rollout
-const showClosePlan = computed(() => {
- return (
- isValidPlanName(plan.value.name) &&
- !plan.value.issue &&
- !plan.value.hasRollout &&
- plan.value.state === State.ACTIVE
- );
-});
-
-// Reopen plan: visible when plan is closed, no issue/rollout
-const showReopenPlan = computed(() => {
- return (
- isValidPlanName(plan.value.name) &&
- !plan.value.issue &&
- !plan.value.hasRollout &&
- plan.value.state === State.DELETED
- );
-});
-
-const updatePlanState = async (state: State) => {
- try {
- const planPatch = clone(PlanSchema, plan.value);
- planPatch.state = state;
- const request = create(UpdatePlanRequestSchema, {
- plan: planPatch,
- updateMask: { paths: ["state"] },
- });
- const updated = await planServiceClientConnect.updatePlan(request);
- Object.assign(plan.value, updated);
- emitPlanStatusChanged(events);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.failed"),
- description: String(error),
- });
- }
-};
-
-const handleClosePlan = () => {
- dialog.warning({
- title: t("common.close"),
- content: t("plan.state.close-confirm"),
- positiveText: t("common.confirm"),
- negativeText: t("common.cancel"),
- onPositiveClick: () => updatePlanState(State.DELETED),
- });
-};
-
-const handleReopenPlan = () => {
- dialog.info({
- title: t("common.reopen"),
- content: t("plan.state.reopen-confirm"),
- positiveText: t("common.confirm"),
- negativeText: t("common.cancel"),
- onPositiveClick: () => updatePlanState(State.ACTIVE),
- });
-};
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailLayout.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailLayout.vue
deleted file mode 100644
index 185bfe198a..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailLayout.vue
+++ /dev/null
@@ -1,152 +0,0 @@
-<template>
- <div
- ref="containerRef"
- class="relative bg-gray-50 [overflow-x:clip]"
- :style="viewportVars"
- >
- <template v-if="ready">
- <PollerProvider>
- <div
- class="flex min-h-full flex-col"
- :style="{
- minHeight: `var(${PLAN_DETAIL_LAYOUT_MIN_HEIGHT_VAR})`,
- }"
- >
- <div
- ref="headerRef"
- class="shrink-0 border-b bg-white"
- >
- <PlanDetailHeader />
- </div>
-
- <PlanDetailPage :spec-id="props.specId" />
- </div>
- </PollerProvider>
- </template>
- <div
- v-else
- class="flex min-h-[16rem] w-full flex-col items-center justify-center"
- >
- <NSpin />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NSpin } from "naive-ui";
-import { computed, ref, toRef, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { onBeforeRouteLeave, onBeforeRouteUpdate, useRouter } from "vue-router";
-import {
- providePlanContext,
- useBasePlanContext,
- useInitializePlan,
-} from "@/components/Plan";
-import { provideSidebarContext } from "@/components/Plan/logic/sidebar";
-import { useNavigationGuard } from "@/components/Plan/logic/useNavigationGuard";
-import PollerProvider from "@/components/Plan/PollerProvider.vue";
-import { useProjectByName } from "@/store";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-import { getIssueRoute, setDocumentTitle } from "@/utils";
-import PlanDetailHeader from "./PlanDetailHeader.vue";
-import PlanDetailPage from "./PlanDetailPage.vue";
-import {
- PLAN_DETAIL_LAYOUT_MIN_HEIGHT_VAR,
- usePlanDetailViewportVars,
-} from "./usePlanDetailViewportVars";
-
-const props = defineProps<{
- projectId: string;
- planId: string;
- specId?: string;
-}>();
-
-const { t } = useI18n();
-const router = useRouter();
-const {
- isCreating,
- plan,
- planCheckRuns,
- issue,
- rollout,
- taskRuns,
- isInitializing,
-} = useInitializePlan(toRef(props, "projectId"), toRef(props, "planId"));
-
-const planBaseContext = useBasePlanContext({ isCreating, plan, issue });
-const containerRef = ref<HTMLElement>();
-const headerRef = ref<HTMLElement>();
-const { viewportVars } = usePlanDetailViewportVars(headerRef);
-
-const ready = computed(() => {
- return !!plan.value && !isInitializing.value;
-});
-
-const { confirmNavigation } = useNavigationGuard();
-
-providePlanContext({
- isCreating,
- plan,
- planCheckRuns,
- issue,
- rollout,
- taskRuns,
- ...planBaseContext,
-});
-
-provideSidebarContext(containerRef);
-
-const projectName = computed(() => `${projectNamePrefix}${props.projectId}`);
-const { project } = useProjectByName(projectName);
-
-const shouldRedirectToIssueDetail = computed(() => {
- if (!issue.value?.name) {
- return false;
- }
- if (plan.value.specs.length === 0) {
- return false;
- }
- return plan.value.specs.every((spec) => {
- return (
- spec.config?.case === "createDatabaseConfig" ||
- spec.config?.case === "exportDataConfig"
- );
- });
-});
-
-watch(
- [isCreating, ready, () => plan.value?.title, () => project.value.title],
- () => {
- if (isCreating.value) {
- setDocumentTitle(t("plan.new-plan"), project.value.title);
- } else if (ready.value && plan.value?.title) {
- setDocumentTitle(plan.value.title, project.value.title);
- }
- },
- { immediate: true }
-);
-
-watch(
- [ready, shouldRedirectToIssueDetail, () => issue.value?.name],
- ([isReady, shouldRedirect, issueName]) => {
- if (!isReady) return;
-
- if (issueName && shouldRedirect) {
- void router.replace(getIssueRoute({ name: issueName }));
- }
- },
- { immediate: true }
-);
-
-const handleRouteNavigation = async (
- _to: unknown,
- _from: unknown,
- next: (proceed?: boolean) => void
-) => {
- const canNavigate = await confirmNavigation();
- next(canNavigate);
-};
-
-onBeforeRouteLeave(handleRouteNavigation);
-onBeforeRouteUpdate(handleRouteNavigation);
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailPage.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailPage.vue
deleted file mode 100644
index febda2fad3..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanDetailPage.vue
+++ /dev/null
@@ -1,280 +0,0 @@
-<template>
- <div
- class="min-h-0 bg-gray-50 flex flex-col lg:grid"
- :style="desktopLayoutStyle"
- >
- <!-- Left column: timeline phases -->
- <div class="min-w-0">
- <div class="flex min-w-0 flex-col pl-2 pr-4 pb-6 pt-4 xl:pr-8 2xl:pr-12">
- <!-- Changes -->
- <PlanPhaseItem
- :label="$t('plan.navigator.changes')"
- :status="phases[0].status"
- :expanded="isExpanded('changes')"
- collapsible
- :badge="phases[0].badge"
- :line-class="phases[0].lineClass"
- @toggle="togglePhase('changes')"
- @select-phase="expandPhase('changes')"
- >
- <template #icon>
- <CodeIcon class="w-3 h-3 md:w-4 md:h-4 text-white" />
- </template>
- <template #collapsed>
- <p v-if="changesSummary" class="text-sm text-control truncate mt-0.5">
- {{ changesSummary }}
- </p>
- </template>
- <PlanSectionChanges :initial-spec-id="props.specId ?? ''" />
- </PlanPhaseItem>
-
- <!-- Review -->
- <PlanPhaseItem
- :label="$t('plan.navigator.review')"
- :status="phases[1].status"
- :expanded="isExpanded('review')"
- collapsible
- :badge="phases[1].badge"
- :line-class="phases[1].lineClass"
- @toggle="togglePhase('review')"
- @select-phase="expandPhase('review')"
- >
- <template #icon>
- <MessagesSquareIcon class="w-3 h-3 md:w-4 md:h-4 text-white" />
- </template>
- <template #future>
- <p class="text-sm text-control-placeholder mt-0.5">
- {{ $t("plan.phase.review-description") }}
- </p>
- </template>
- <template #collapsed>
- <p v-if="reviewSummary" class="text-sm text-control truncate mt-0.5">
- {{ reviewSummary }}
- </p>
- </template>
- <PlanSectionReview />
- </PlanPhaseItem>
-
- <!-- Deploy -->
- <PlanPhaseItem
- :label="$t('plan.navigator.deploy')"
- :status="phases[2].status"
- :expanded="isExpanded('deploy')"
- collapsible
- :badge="phases[2].badge"
- :is-last="true"
- @toggle="togglePhase('deploy')"
- @select-phase="expandPhase('deploy')"
- >
- <template #icon>
- <RocketIcon class="w-3 h-3 md:w-4 md:h-4 text-white" />
- </template>
- <template #future>
- <DeployFutureAction />
- </template>
- <template #collapsed>
- <p v-if="deploySummary" class="text-sm text-control truncate mt-0.5">
- {{ deploySummary }}
- </p>
- </template>
- <PlanSectionDeploy />
- </PlanPhaseItem>
- </div>
- </div>
-
- <!-- Right column: sidebar (lg+) -->
- <PlanDetailDesktopColumn v-if="showDesktopSidebar" tag="aside">
- <PlanMetadataSidebar class="p-4" />
- </PlanDetailDesktopColumn>
-
- <!-- Task detail panel: inline (xl+) -->
- <PlanDetailDesktopColumn v-if="showInlineDetailPanel">
- <template #header>
- <div class="flex items-center justify-between border-b px-4 py-2">
- <span class="textinfolabel">{{ $t("common.detail") }}</span>
- <NButton size="tiny" quaternary @click="closeDetailPanel">
- <template #icon>
- <XIcon class="w-4 h-4" />
- </template>
- {{ $t("common.close") }}
- </NButton>
- </div>
- </template>
-
- <TaskDetailPanel
- v-if="detailPanel"
- :task="detailPanel.task"
- @close="closeDetailPanel"
- />
- </PlanDetailDesktopColumn>
-
- <!-- Task detail panel: drawer (< xl) -->
- <NDrawer
- v-if="showTaskDrawer"
- :show="!!detailPanel"
- placement="right"
- :width="PLAN_DETAIL_TASK_DRAWER_WIDTH"
- @update:show="(val: boolean) => !val && closeDetailPanel()"
- >
- <NDrawerContent closable @close="closeDetailPanel">
- <TaskDetailPanel
- v-if="detailPanel"
- :task="detailPanel.task"
- @close="closeDetailPanel"
- />
- </NDrawerContent>
- </NDrawer>
-
- <!-- Sidebar drawer (< lg) -->
- <NDrawer
- v-if="showSidebarDrawer"
- :show="mobileSidebarOpen"
- placement="right"
- :width="PLAN_DETAIL_METADATA_DRAWER_WIDTH"
- @update:show="(val: boolean) => (mobileSidebarOpen = val)"
- >
- <NDrawerContent closable @close="mobileSidebarOpen = false">
- <PlanMetadataSidebar />
- </NDrawerContent>
- </NDrawer>
- </div>
-</template>
-
-<script setup lang="ts">
-import {
- CodeIcon,
- MessagesSquareIcon,
- RocketIcon,
- XIcon,
-} from "lucide-vue-next";
-import { NButton, NDrawer, NDrawerContent } from "naive-ui";
-import { computed, ref, watch } from "vue";
-import { useRoute, useRouter } from "vue-router";
-import {
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
-} from "@/router/dashboard/projectV1";
-import {
- getRouteQueryString,
- PLAN_DETAIL_PHASE_DEPLOY,
-} from "@/router/dashboard/projectV1RouteHelpers";
-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";
-import { usePlanContext } from "../../logic";
-import { useSidebarContext } from "../../logic/sidebar";
-import DeployFutureAction from "./DeployFutureAction.vue";
-import PlanDetailDesktopColumn from "./PlanDetailDesktopColumn.vue";
-import PlanMetadataSidebar from "./PlanMetadataSidebar.vue";
-import PlanPhaseItem from "./PlanPhaseItem.vue";
-import PlanSectionChanges from "./PlanSectionChanges.vue";
-import PlanSectionDeploy from "./PlanSectionDeploy.vue";
-import PlanSectionReview from "./PlanSectionReview.vue";
-import TaskDetailPanel from "./TaskDetailPanel.vue";
-import { type PhaseType, useActivePhase } from "./useActivePhase";
-import { usePhaseState } from "./usePhaseState";
-import { usePhaseSummaries } from "./usePhaseSummaries";
-import {
- PLAN_DETAIL_METADATA_DRAWER_WIDTH,
- PLAN_DETAIL_TASK_DRAWER_WIDTH,
- usePlanDetailDesktopLayout,
-} from "./usePlanDetailDesktopLayout";
-
-const props = defineProps<{
- specId?: string;
-}>();
-
-const route = useRoute();
-const router = useRouter();
-const { isCreating, plan, issue, rollout } = usePlanContext();
-const {
- mode: sidebarMode,
- containerWidth,
- desktopSidebarWidth,
- mobileSidebarOpen,
-} = useSidebarContext();
-const { isExpanded, togglePhase, expandPhase, syncExpandedPhases } =
- useActivePhase();
-
-const routeDrivenExpandedPhases = computed<PhaseType[]>(() => {
- if (
- route.name === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||
- route.name === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL
- ) {
- return ["changes"];
- }
-
- const routePhase = getRouteQueryString(route.query.phase);
- const routeStageId = getRouteQueryString(route.query.stageId);
- const routeTaskId = getRouteQueryString(route.query.taskId);
- if (routePhase === PLAN_DETAIL_PHASE_DEPLOY || routeStageId || routeTaskId) {
- return ["deploy"];
- }
-
- return [];
-});
-
-watch(
- [routeDrivenExpandedPhases] as const,
- ([phases]) => {
- syncExpandedPhases(phases);
- },
- { immediate: true }
-);
-
-const { phases } = usePhaseState(isCreating, issue, rollout);
-const { changesSummary, reviewSummary, deploySummary } = usePhaseSummaries(
- plan,
- issue,
- rollout
-);
-
-// Task detail panel — driven by ?taskId query param
-const detailPanel = ref<{ task: Task } | null>(null);
-const hasDetailPanel = computed(() => !!detailPanel.value);
-const {
- desktopLayoutStyle,
- showDesktopSidebar,
- showInlineDetailPanel,
- showTaskDrawer,
- showSidebarDrawer,
-} = usePlanDetailDesktopLayout({
- sidebarMode,
- containerWidth,
- desktopSidebarWidth,
- hasDetailPanel,
-});
-
-// Reactively open/close panel based on query params
-watch(
- [() => getRouteQueryString(route.query.taskId), rollout] as const,
- ([taskId, r]) => {
- if (!taskId) {
- detailPanel.value = null;
- return;
- }
- if (!taskId || !r) return;
- for (const stage of r.stages) {
- const task = stage.tasks.find((t) => t.name.endsWith(`/${taskId}`));
- if (task) {
- detailPanel.value = { task };
- return;
- }
- }
- detailPanel.value = null;
- },
- { immediate: true }
-);
-
-const closeDetailPanel = () => {
- detailPanel.value = null;
- const routePhase = getRouteQueryString(route.query.phase);
- const stageId = getRouteQueryString(route.query.stageId);
- if (route.query.taskId) {
- router.replace({
- query: {
- ...(routePhase ? { phase: routePhase } : {}),
- ...(stageId ? { stageId } : {}),
- },
- });
- }
-};
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanMetadataSidebar.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanMetadataSidebar.vue
deleted file mode 100644
index 900d8012d3..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanMetadataSidebar.vue
+++ /dev/null
@@ -1,237 +0,0 @@
-<template>
- <div class="w-full shrink-0 flex flex-col text-sm">
- <!-- Plan group: Created by + Refresh + Status + Checks -->
- <div class="flex flex-col gap-3 pb-3">
- <div v-if="!isCreating" class="flex flex-col">
- <p class="text-xs text-control-placeholder">
- {{ $t("plan.sidebar.created-by-at", { user: creatorEmail, time: createdTimeDisplay }) }}
- </p>
- </div>
- <div>
- <h4 class="textinfolabel mb-1">{{ $t("common.status") }}</h4>
- <div class="flex items-center gap-2">
- <div class="w-2.5 h-2.5 rounded-full" :class="statusInfo.dotClass" />
- <span class="text-sm font-medium text-main">{{ statusInfo.label }}</span>
- </div>
- </div>
- <div v-if="hasAnyChecks">
- <h4 class="textinfolabel mb-1">{{ $t("plan.navigator.checks") }}</h4>
- <PlanCheckStatusCount :plan="plan" />
- </div>
- </div>
-
- <!-- Issue group: Approval flow + link + Labels -->
- <div v-if="issue" class="flex flex-col gap-3 py-3 border-t">
- <ApprovalFlowSection :issue="issue" :has-rollout="!!rollout" />
- <IssueLabels
- :project="project"
- :value="issue.labels || []"
- :disabled="!allowChangeLabels"
- @update:value="onIssueLabelsUpdate"
- />
- </div>
-
- <!-- Rollout group: Stages -->
- <div v-if="rollout && rollout.stages.length > 0" class="flex flex-col gap-3 py-3 border-t">
- <h4 class="textinfolabel">{{ $t("rollout.stage.self", 2) }}</h4>
- <div
- v-for="stage in rollout.stages"
- :key="stage.name"
- class="flex items-center gap-2"
- >
- <TaskStatus :status="getStageStatus(stage)" size="small" disabled />
- <EnvironmentV1Name
- :environment="environmentStore.getEnvironmentByName(stage.environment)"
- :link="false"
- />
- <span class="text-control-placeholder">
- ({{ completedTaskCount(stage) }}/{{ stage.tasks.length }})
- </span>
- </div>
- </div>
-
- <!-- Placeholder when no issue yet -->
- <div v-if="!issue" class="pt-3 border-t">
- <p class="text-sm text-control-placeholder">
- {{ $t("plan.sidebar.future-sections-hint") }}
- </p>
- </div>
-
- <div v-if="!isCreating" class="pt-1">
- <RefreshIndicator />
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { clone, create } from "@bufbuild/protobuf";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import IssueLabels from "@/components/IssueV1/components/Sidebar/IssueLabels.vue";
-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";
-import { EnvironmentV1Name } from "@/components/v2";
-import { issueServiceClientConnect } from "@/connect";
-import {
- extractUserEmail,
- pushNotification,
- useCurrentProjectV1,
- useEnvironmentV1Store,
-} from "@/store";
-import { getTimeForPbTimestampProtoEs } from "@/types";
-import { State } from "@/types/proto-es/v1/common_pb";
-import {
- Issue_ApprovalStatus,
- IssueSchema,
- IssueStatus,
- UpdateIssueRequestSchema,
-} from "@/types/proto-es/v1/issue_service_pb";
-import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";
-import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
-import {
- getRolloutStatus,
- getStageStatus,
- hasProjectPermissionV2,
-} from "@/utils";
-import { humanizeTs } from "@/utils/util";
-import { usePlanCheckStatus, usePlanContext } from "../../logic";
-import { useResourcePoller } from "../../logic/poller";
-import ApprovalFlowSection from "../IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalFlowSection.vue";
-import PlanCheckStatusCount from "../PlanCheckStatusCount.vue";
-import RefreshIndicator from "../RefreshIndicator.vue";
-
-const { t } = useI18n();
-const { isCreating, plan, issue, rollout } = usePlanContext();
-const { project } = useCurrentProjectV1();
-const { refreshResources } = useResourcePoller();
-const environmentStore = useEnvironmentV1Store();
-const { hasAnyStatus: hasAnyChecks } = usePlanCheckStatus(plan);
-
-// --- Status ---
-
-type StatusInfo = { label: string; dotClass: string };
-
-const getReviewStatusInfo = (): StatusInfo => {
- if (!issue.value) {
- return { label: t("common.draft"), dotClass: "bg-control-placeholder" };
- }
-
- if (issue.value.status === IssueStatus.DONE) {
- return { label: t("common.approved"), dotClass: "bg-success" };
- }
-
- switch (issue.value.approvalStatus) {
- case Issue_ApprovalStatus.APPROVED:
- case Issue_ApprovalStatus.SKIPPED:
- return { label: t("common.approved"), dotClass: "bg-success" };
- case Issue_ApprovalStatus.REJECTED:
- return { label: t("common.rejected"), dotClass: "bg-warning" };
- default:
- return { label: t("common.in-review"), dotClass: "bg-accent" };
- }
-};
-
-const getRolloutStatusInfo = (): StatusInfo => {
- if (!rollout.value) {
- return getReviewStatusInfo();
- }
-
- const hasCompletedTasks = rollout.value.stages
- .flatMap((stage) => stage.tasks)
- .some(
- (task) =>
- task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
- );
-
- switch (getRolloutStatus(rollout.value)) {
- case Task_Status.DONE:
- case Task_Status.SKIPPED:
- return { label: t("common.done"), dotClass: "bg-success" };
- case Task_Status.FAILED:
- return { label: t("common.failed"), dotClass: "bg-error" };
- case Task_Status.RUNNING:
- case Task_Status.PENDING:
- return { label: t("common.deploying"), dotClass: "bg-accent" };
- case Task_Status.CANCELED:
- return {
- label: t("common.canceled"),
- dotClass: "bg-control-placeholder",
- };
- case Task_Status.NOT_STARTED:
- if (hasCompletedTasks) {
- return { label: t("common.deploying"), dotClass: "bg-accent" };
- }
- return {
- label: t("common.not-started"),
- dotClass: "bg-control-placeholder",
- };
- default:
- return {
- label: t("common.not-started"),
- dotClass: "bg-control-placeholder",
- };
- }
-};
-
-const statusInfo = computed<StatusInfo>(() => {
- if (isCreating.value) {
- return { label: t("common.creating"), dotClass: "bg-control-placeholder" };
- }
- if (plan.value.state === State.DELETED) {
- return { label: t("common.closed"), dotClass: "bg-control-placeholder" };
- }
- if (issue.value?.status === IssueStatus.CANCELED) {
- return { label: t("common.closed"), dotClass: "bg-control-placeholder" };
- }
- if (rollout.value) {
- return getRolloutStatusInfo();
- }
- return getReviewStatusInfo();
-});
-
-// --- Creator / Created ---
-
-const creatorEmail = computed(() => extractUserEmail(plan.value.creator));
-
-const createdTimeDisplay = computed(() => {
- const ts = getTimeForPbTimestampProtoEs(plan.value.createTime, 0);
- if (!ts) return "";
- return humanizeTs(ts / 1000);
-});
-
-// --- Labels ---
-
-const allowChangeLabels = computed(() => {
- if (!issue.value || issue.value.status !== IssueStatus.OPEN) return false;
- return hasProjectPermissionV2(project.value, "bb.issues.update");
-});
-
-const onIssueLabelsUpdate = async (labels: string[]) => {
- if (!issue.value) return;
- try {
- const issuePatch = clone(IssueSchema, issue.value);
- issuePatch.labels = labels;
- const request = create(UpdateIssueRequestSchema, {
- issue: issuePatch,
- updateMask: { paths: ["labels"] },
- });
- await issueServiceClientConnect.updateIssue(request);
- refreshResources(["issue"], true);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } catch {
- // Ignore — label update is non-critical
- }
-};
-
-// --- Stages ---
-
-const completedTaskCount = (stage: Stage) => {
- return stage.tasks.filter(
- (task) =>
- task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
- ).length;
-};
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanPhaseItem.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanPhaseItem.vue
deleted file mode 100644
index 13a030750d..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanPhaseItem.vue
+++ /dev/null
@@ -1,115 +0,0 @@
-<template>
- <div class="flex" :class="isLast ? 'mb-48' : ''">
- <!-- Timeline column: dot + connecting line -->
- <div class="flex flex-col items-center w-10 md:w-16 shrink-0">
- <div
- class="flex items-center justify-center w-5 h-5 md:w-7 md:h-7 shrink-0 cursor-pointer mt-0.5"
- @click="$emit('select-phase')"
- >
- <div class="w-5 h-5 md:w-7 md:h-7 rounded-full flex items-center justify-center" :class="dotClass">
- <template v-if="status !== 'future'">
- <slot name="icon">
- <CheckIcon v-if="status === 'completed'" class="w-3 h-3 md:w-4 md:h-4 text-white" />
- <BanIcon v-else-if="status === 'closed'" class="w-3 h-3 md:w-4 md:h-4 text-white" />
- <div v-else-if="status === 'active'" class="w-2 h-2 md:w-2.5 md:h-2.5 rounded-full bg-white" />
- </slot>
- </template>
- </div>
- </div>
- <div
- v-if="!isLast"
- class="flex-1 min-h-[16px]"
- :class="lineClass"
- />
- </div>
-
- <!-- Content column -->
- <div class="flex-1 min-w-0 pb-4">
- <!-- Future -->
- <div v-if="status === 'future'" class="py-0.5">
- <span class="textlabel uppercase text-control-placeholder">
- {{ label }}
- </span>
- <slot name="future" />
- </div>
-
- <!-- Collapsed -->
- <div
- v-else-if="!expanded"
- class="cursor-pointer py-0.5"
- @click="$emit('toggle')"
- >
- <div class="flex items-center gap-2">
- <span class="textlabel uppercase">{{ label }}</span>
- <NTag v-if="badge" size="small" round :type="badge.type">
- {{ badge.label }}
- </NTag>
- <div class="flex-1" />
- <span class="text-[11px] text-control-placeholder shrink-0">
- {{ $t("plan.phase.show-details") }}
- </span>
- </div>
- <slot name="collapsed" />
- </div>
-
- <!-- Expanded -->
- <div v-else class="flex flex-col">
- <div
- class="flex items-center gap-2 py-0.5"
- :class="collapsible ? 'cursor-pointer' : ''"
- @click="collapsible && $emit('toggle')"
- >
- <span class="textlabel uppercase text-accent">{{ label }}</span>
- <NTag v-if="badge" size="small" round :type="badge.type">
- {{ badge.label }}
- </NTag>
- <div class="flex-1" />
- <span
- v-if="collapsible"
- class="text-[11px] text-control-placeholder shrink-0"
- >
- {{ $t("plan.phase.hide-details") }}
- </span>
- </div>
- <div class="mt-1 bg-white rounded-lg border overflow-hidden">
- <slot />
- </div>
- </div>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { BanIcon, CheckIcon } from "lucide-vue-next";
-import { NTag } from "naive-ui";
-import { computed } from "vue";
-import type { PhaseBadge } from "./usePhaseState";
-
-const props = defineProps<{
- label: string;
- status: "completed" | "closed" | "active" | "future";
- expanded: boolean;
- collapsible?: boolean;
- badge?: PhaseBadge;
- lineClass?: string;
- isLast?: boolean;
-}>();
-
-const dotClass = computed(() => {
- switch (props.status) {
- case "completed":
- return "bg-success";
- case "closed":
- return "bg-control-placeholder";
- case "active":
- return "bg-accent ring-[3px] ring-accent/20";
- default:
- return "border-2 border-dashed border-control-border";
- }
-});
-
-defineEmits<{
- (event: "toggle"): void;
- (event: "select-phase"): void;
-}>();
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionChanges.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionChanges.vue
deleted file mode 100644
index e8586f5aa3..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionChanges.vue
+++ /dev/null
@@ -1,66 +0,0 @@
-<template>
- <div class="w-full flex-1 flex flex-col">
- <SpecDetailView />
- </div>
-</template>
-
-<script setup lang="ts">
-import { computed, ref, watch } from "vue";
-import { usePlanContext } from "../../logic";
-import { SpecDetailView } from "../index";
-import { provideSelectedSpec } from "../SpecDetailView/context";
-
-const props = withDefaults(
- defineProps<{
- initialSpecId?: string;
- }>(),
- { initialSpecId: "" }
-);
-
-const { plan } = usePlanContext();
-
-// Injection-based spec selection
-const selectedSpecId = ref<string>(props.initialSpecId);
-
-watch(
- () => props.initialSpecId,
- (specId) => {
- if (specId) {
- selectedSpecId.value = specId;
- return;
- }
- if (!selectedSpecId.value && plan.value.specs.length > 0) {
- selectedSpecId.value = plan.value.specs[0].id;
- }
- },
- { immediate: true }
-);
-
-watch(
- () => plan.value.specs,
- (specs) => {
- if (specs.length === 0) {
- selectedSpecId.value = "";
- return;
- }
-
- const hasSelectedSpec = specs.some(
- (spec) => spec.id === selectedSpecId.value
- );
- if (!hasSelectedSpec) {
- selectedSpecId.value = props.initialSpecId || specs[0].id;
- }
- },
- { immediate: true }
-);
-
-const selectedSpecRef = computed(() => {
- const spec = plan.value.specs.find((s) => s.id === selectedSpecId.value);
- return spec ?? plan.value.specs[0];
-});
-
-const setSelectedSpecId = (specId: string) => {
- selectedSpecId.value = specId;
-};
-provideSelectedSpec(selectedSpecRef, setSelectedSpecId);
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionDeploy.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionDeploy.vue
deleted file mode 100644
index 907b548e21..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionDeploy.vue
+++ /dev/null
@@ -1,161 +0,0 @@
-<template>
- <div class="flex flex-col">
- <template v-if="rollout">
- <!-- Empty state -->
- <div v-if="!hasStages" class="flex flex-col items-center justify-center py-10 gap-4">
- <p class="text-control-placeholder">{{ $t("rollout.no-tasks-created") }}</p>
- <NButton v-if="hasPendingTasks" type="primary" @click="showPreviewDrawer = true">
- {{ $t("rollout.pending-tasks-preview.action") }}
- </NButton>
- </div>
-
- <!-- Stages + Tasks -->
- <template v-else>
- <StageNavigationBar
- :selected-stage-id="selectedStage?.name"
- :rollout="rollout"
- :has-pending-tasks="hasPendingTasks"
- @select-stage="handleStageSelect"
- @open-preview="showPreviewDrawer = true"
- />
-
- <StageContentView
- :selected-stage="selectedStage"
- :rollout="rollout"
- :is-stage-created="() => true"
- @run-stage="handleRunStage"
- @create-stage="handleCreateStage"
- />
- </template>
-
- <PendingTasksPreviewDrawer
- :show="showPreviewDrawer"
- :plan="plan"
- :rollout="rollout"
- :project-name="project.name"
- @close="showPreviewDrawer = false"
- @created="handleTasksCreated"
- />
-
- <TaskRolloutActionPanel
- v-if="showStageActionPanel && stageActionTarget"
- :show="showStageActionPanel"
- :action="stageAction"
- :target="stageActionTarget"
- @close="showStageActionPanel = false"
- @confirm="handleStageActionConfirmed"
- />
- </template>
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import { NButton } from "naive-ui";
-import { computed, type Ref, ref } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRoute, useRouter } from "vue-router";
-import StageContentView from "@/components/RolloutV1/components/Stage/StageContentView.vue";
-import StageNavigationBar from "@/components/RolloutV1/components/Stage/StageNavigationBar.vue";
-import { useStageSelection } from "@/components/RolloutV1/components/Stage/useStageSelection";
-import PendingTasksPreviewDrawer from "@/components/RolloutV1/components/Task/PendingTasksPreviewDrawer.vue";
-import type { TargetType } from "@/components/RolloutV1/components/Task/TaskRolloutActionPanel.vue";
-import TaskRolloutActionPanel from "@/components/RolloutV1/components/Task/TaskRolloutActionPanel.vue";
-import { useExpectedTaskCount } from "@/components/RolloutV1/components/Task/useExpectedTaskCount";
-import { useTaskInstancePreload } from "@/components/RolloutV1/components/Task/useTaskInstancePreload";
-import { rolloutServiceClientConnect } from "@/connect";
-import {
- buildPlanDeployRouteFromPlanName,
- getRouteQueryString,
-} from "@/router/dashboard/projectV1RouteHelpers";
-import { pushNotification, useCurrentProjectV1 } from "@/store";
-import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";
-import {
- CreateRolloutRequestSchema,
- type Stage,
-} from "@/types/proto-es/v1/rollout_service_pb";
-import { extractPlanNameFromRolloutName } from "@/utils";
-import { emitPlanStatusChanged, usePlanContext } from "../../logic";
-
-const { t } = useI18n();
-const route = useRoute();
-const router = useRouter();
-const { plan, rollout, events } = usePlanContext();
-const { project } = useCurrentProjectV1();
-
-const hasStages = computed(() => (rollout.value?.stages.length ?? 0) > 0);
-
-const routeStageId = computed<string | undefined>(() => {
- return getRouteQueryString(route.query.stageId);
-});
-const { selectedStage } = useStageSelection(
- computed(() => rollout.value?.stages ?? []),
- routeStageId,
- rollout as Ref<Rollout>
-);
-
-useTaskInstancePreload(() =>
- selectedStage.value ? [selectedStage.value] : []
-);
-
-const { expectedTaskCount } = useExpectedTaskCount(plan);
-const hasPendingTasks = computed(() => {
- if (!rollout.value) return false;
- const actualCount = rollout.value.stages.flatMap((s) => s.tasks).length;
- return expectedTaskCount.value > actualCount;
-});
-
-const showPreviewDrawer = ref(false);
-const showStageActionPanel = ref(false);
-const stageAction = ref<"RUN" | "SKIP" | "CANCEL">("RUN");
-const stageActionTarget = ref<TargetType | null>(null);
-
-const handleStageSelect = (stage: Stage) => {
- const stageId = stage.name.split("/").pop();
- router.push(
- buildPlanDeployRouteFromPlanName(plan.value.name, {
- stageId,
- })
- );
-};
-
-const handleRunStage = (stage: Stage) => {
- stageAction.value = "RUN";
- stageActionTarget.value = { type: "tasks", stage };
- showStageActionPanel.value = true;
-};
-
-const handleCreateStage = async (stage: Stage) => {
- if (!rollout.value) return;
- try {
- const request = create(CreateRolloutRequestSchema, {
- parent: extractPlanNameFromRolloutName(rollout.value.name),
- target: stage.environment,
- });
- await rolloutServiceClientConnect.createRollout(request);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.created"),
- });
- events.emit("status-changed", { eager: true });
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.error"),
- description: String(error),
- });
- }
-};
-
-const handleStageActionConfirmed = () => {
- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });
- showStageActionPanel.value = false;
- stageActionTarget.value = null;
-};
-
-const handleTasksCreated = () => {
- emitPlanStatusChanged(events);
-};
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionReview.vue b/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionReview.vue
deleted file mode 100644
index 08458e380c..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/PlanSectionReview.vue
+++ /dev/null
@@ -1,170 +0,0 @@
-<template>
- <div class="flex flex-col">
- <!-- State: Checking (generating approval flow) -->
- <div
- v-if="issue.approvalStatus === Issue_ApprovalStatus.CHECKING"
- class="flex items-center gap-x-2 text-sm text-control-placeholder p-4"
- >
- <BBSpin :size="16" />
- <span>{{ $t("custom-approval.issue-review.generating-approval-flow") }}</span>
- </div>
-
- <!-- State: Skipped (no approval required) -->
- <div
- v-else-if="issue.approvalStatus === Issue_ApprovalStatus.SKIPPED || approvalSteps.length === 0"
- class="text-sm text-control-placeholder p-4"
- >
- {{ $t("custom-approval.approval-flow.skip") }}
- </div>
-
- <!-- State: Has approval flow -->
- <template v-else>
- <!-- Rejection banner -->
- <NAlert
- v-if="issue.approvalStatus === Issue_ApprovalStatus.REJECTED && lastRejection"
- type="warning"
- size="small"
- class="mx-4 mt-3"
- :title="`${$t('custom-approval.issue-review.rejected-by')} ${lastRejection.creator}`"
- >
- <span v-if="lastRejection.comment">{{ lastRejection.comment }}</span>
- </NAlert>
-
- <!-- Approval steps timeline -->
- <div class="px-4 py-3">
- <h3 class="textinfolabel">{{ $t("issue.approval-flow.self") }}</h3>
- <NTimeline size="large" class="pl-1 pt-3">
- <ApprovalStepItem
- v-for="(step, index) in approvalSteps"
- :key="index"
- :step="step"
- :step-index="index"
- :step-number="index + 1"
- :issue="issue"
- :readonly="plan.hasRollout"
- />
- </NTimeline>
- </div>
-
- <!-- Footer: rule + actions -->
- <div class="flex items-center gap-x-2 px-4 py-2.5 border-t text-sm text-control-placeholder">
- <RiskLevelIcon
- :risk-level="issue.riskLevel"
- :title="approvalTemplate?.title?.trim()"
- class="shrink-0"
- />
- <span v-if="riskLevelText">{{ riskLevelText }}</span>
- <span v-if="ruleText && riskLevelText">·</span>
- <span v-if="ruleText" class="truncate min-w-0">{{ ruleText }}</span>
- <div class="flex-1" />
- <RouterLink
- :to="issueRoute"
- class="text-accent hover:underline"
- active-class=""
- exact-active-class=""
- >
- {{ $t("common.issue") }} #{{ issueUID }} ·
- {{ $t("plan.view-discussion") }} →
- </RouterLink>
- </div>
- </template>
- </div>
-</template>
-
-<script setup lang="ts">
-import { create } from "@bufbuild/protobuf";
-import { NAlert, NTimeline } from "naive-ui";
-import { computed, watchEffect } from "vue";
-import { useI18n } from "vue-i18n";
-import { RouterLink } from "vue-router";
-import { BBSpin } from "@/bbkit";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
-import {
- getIssueCommentType,
- IssueCommentType,
- useIssueCommentStore,
-} from "@/store/modules/v1/issueComment";
-import { RiskLevel } from "@/types/proto-es/v1/common_pb";
-import {
- Issue_ApprovalStatus,
- ListIssueCommentsRequestSchema,
-} from "@/types/proto-es/v1/issue_service_pb";
-import { extractIssueUID, extractProjectResourceName } from "@/utils";
-import { usePlanContextWithIssue } from "../../logic/context";
-import ApprovalStepItem from "../IssueReviewView/Sidebar/ApprovalFlowSection/ApprovalStepItem.vue";
-import RiskLevelIcon from "../IssueReviewView/Sidebar/ApprovalFlowSection/RiskLevelIcon.vue";
-
-const { t } = useI18n();
-const { plan, issue } = usePlanContextWithIssue();
-const issueCommentStore = useIssueCommentStore();
-
-// Approval data
-const approvalTemplate = computed(() => issue.value.approvalTemplate);
-const approvalSteps = computed(() => approvalTemplate.value?.flow?.roles ?? []);
-
-const issueUID = computed(() => extractIssueUID(issue.value.name));
-const issueRoute = computed(() => ({
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: {
- projectId: extractProjectResourceName(plan.value.name),
- issueId: issueUID.value,
- },
-}));
-
-const riskLevelText = computed(() => {
- switch (issue.value.riskLevel) {
- case RiskLevel.LOW:
- return t("issue.risk-level.low");
- case RiskLevel.MODERATE:
- return t("issue.risk-level.moderate");
- case RiskLevel.HIGH:
- return t("issue.risk-level.high");
- default:
- return "";
- }
-});
-
-const ruleText = computed(() => {
- const parts: string[] = [];
- const title = approvalTemplate.value?.title?.trim();
- const desc = approvalTemplate.value?.description?.trim();
- if (title) parts.push(title);
- if (desc) parts.push(desc);
- return parts.join(" — ");
-});
-
-// Fetch comments
-watchEffect(async () => {
- if (!issue.value?.name) return;
- try {
- await issueCommentStore.listIssueComments(
- create(ListIssueCommentsRequestSchema, {
- parent: issue.value.name,
- pageSize: 100,
- })
- );
- } catch {
- // Ignore — comments are non-critical
- }
-});
-
-const comments = computed(
- () => issueCommentStore.getIssueComments(issue.value.name) ?? []
-);
-
-const lastRejection = computed(() => {
- if (issue.value.approvalStatus !== Issue_ApprovalStatus.REJECTED) {
- return undefined;
- }
- for (let i = comments.value.length - 1; i >= 0; i--) {
- const comment = comments.value[i];
- if (getIssueCommentType(comment) === IssueCommentType.APPROVAL) {
- const approval = comment.event?.value;
- if (approval && "status" in approval) {
- return { creator: comment.creator, comment: comment.comment || "" };
- }
- }
- }
- return undefined;
-});
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/StickySidePanel.vue b/frontend/src/components/Plan/components/PlanDetailPage/StickySidePanel.vue
deleted file mode 100644
index b85cb78e87..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/StickySidePanel.vue
+++ /dev/null
@@ -1,17 +0,0 @@
-<template>
- <div class="sticky top-0 flex flex-col bg-white" :style="panelStyle">
- <slot name="header" />
- <div class="min-h-0 flex-1 overflow-y-auto overscroll-y-contain">
- <slot />
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { computed } from "vue";
-import { PLAN_DETAIL_VIEWPORT_HEIGHT_VAR } from "./usePlanDetailViewportVars";
-
-const panelStyle = computed(() => ({
- maxHeight: `var(${PLAN_DETAIL_VIEWPORT_HEIGHT_VAR})`,
-}));
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/TaskDetailPanel.vue b/frontend/src/components/Plan/components/PlanDetailPage/TaskDetailPanel.vue
deleted file mode 100644
index b3ed44a65d..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/TaskDetailPanel.vue
+++ /dev/null
@@ -1,170 +0,0 @@
-<template>
- <div class="flex flex-col gap-y-4 p-4">
- <!-- Header: Stage + Status + Database + Scheduled time -->
- <div class="flex flex-col gap-y-3">
- <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
- <div class="flex flex-row items-center gap-x-3 flex-wrap">
- <TaskStatus :status="task.status" />
- <NTag v-if="stageTitle" round>
- {{ stageTitle }}
- </NTag>
- <DatabaseDisplay :database="database.name" size="large" />
- <NTooltip v-if="task.runTime && task.status === Task_Status.PENDING">
- <template #trigger>
- <NTag round size="small">
- <div class="flex items-center gap-1">
- <CalendarClockIcon class="w-3.5 h-3.5 opacity-80" />
- <span class="text-xs">{{ scheduledTimeDisplay }}</span>
- </div>
- </NTag>
- </template>
- {{ $t("task.scheduled-time") }}
- </NTooltip>
- </div>
-
- <!-- Actions -->
- <div v-if="stage" class="flex items-center gap-x-2">
- <TaskStatusActions
- :task="task"
- :stage="stage"
- @action-confirmed="handleTaskActionConfirmed"
- />
- <TaskRollbackButton
- v-if="rollbackableTaskRun"
- :task="task"
- :task-run="rollbackableTaskRun"
- :rollout="rollout"
- />
- </div>
- </div>
- </div>
-
- <!-- Latest Task Run Detail -->
- <div v-if="latestTaskRun" class="flex flex-col gap-2">
- <span class="textlabel uppercase">{{ $t("task-run.latest-logs") }}</span>
- <TaskRunDetail :task-run="latestTaskRun" :database="database" />
- </div>
-
- <!-- Task Runs History -->
- <div v-if="taskRunsForTask.length > 0" class="flex flex-col gap-2">
- <span class="textlabel uppercase">{{ $t("task-run.history") }}</span>
- <TaskRunTable :task-runs="taskRunsForTask" />
- </div>
-
- <!-- SQL Statement -->
- <div v-if="statement" class="flex flex-col gap-2">
- <span class="textlabel uppercase">{{ $t("common.statement") }}</span>
- <MonacoEditor
- class="border rounded-[3px] text-sm overflow-hidden"
- :content="statement"
- :readonly="true"
- :auto-height="{ min: 200, max: 480 }"
- />
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { last } from "lodash-es";
-import { CalendarClockIcon } from "lucide-vue-next";
-import { NTag, NTooltip } from "naive-ui";
-import { computed, watch } from "vue";
-import { MonacoEditor } from "@/components/MonacoEditor";
-import DatabaseDisplay from "@/components/Plan/components/common/DatabaseDisplay.vue";
-import TaskRollbackButton from "@/components/RolloutV1/components/Task/TaskRollbackButton.vue";
-import TaskStatus from "@/components/RolloutV1/components/Task/TaskStatus.vue";
-import TaskStatusActions from "@/components/RolloutV1/components/Task/TaskStatusActions.vue";
-import TaskRunDetail from "@/components/RolloutV1/components/TaskRun/TaskRunDetail.vue";
-import TaskRunTable from "@/components/RolloutV1/components/TaskRun/TaskRunTable.vue";
-import {
- taskRunNamePrefix,
- useCurrentProjectV1,
- useEnvironmentV1Store,
- useSheetV1Store,
-} from "@/store";
-import { getTimeForPbTimestampProtoEs } from "@/types";
-import type { Task } from "@/types/proto-es/v1/rollout_service_pb";
-import {
- Task_Status,
- TaskRun_Status,
-} from "@/types/proto-es/v1/rollout_service_pb";
-import { databaseForTask, getSheetStatement, sheetNameOfTaskV1 } from "@/utils";
-import { humanizeTs } from "@/utils/util";
-import { emitPlanStatusChanged, usePlanContextWithRollout } from "../../logic";
-
-const props = defineProps<{
- task: Task;
-}>();
-
-defineEmits<{
- (event: "close"): void;
-}>();
-
-const { project } = useCurrentProjectV1();
-const { rollout, taskRuns: allTaskRuns, events } = usePlanContextWithRollout();
-const sheetStore = useSheetV1Store();
-const environmentStore = useEnvironmentV1Store();
-
-const database = computed(() => databaseForTask(project.value, props.task));
-
-const stage = computed(() => {
- return rollout.value.stages.find((s) =>
- s.tasks.some((t) => t.name === props.task.name)
- );
-});
-
-const stageTitle = computed(() => {
- if (!stage.value?.environment) return "";
- return (
- environmentStore.getEnvironmentByName(stage.value.environment)?.title ?? ""
- );
-});
-
-const scheduledTimeDisplay = computed(() => {
- const ts = getTimeForPbTimestampProtoEs(props.task.runTime, 0);
- if (!ts) return "";
- return humanizeTs(ts / 1000);
-});
-
-const taskRunsForTask = computed(() => {
- return allTaskRuns.value.filter((run) =>
- run.name.startsWith(`${props.task.name}/${taskRunNamePrefix}`)
- );
-});
-
-const latestTaskRun = computed(() => last(taskRunsForTask.value));
-
-const rollbackableTaskRun = computed(() => {
- if (
- latestTaskRun.value &&
- latestTaskRun.value.status === TaskRun_Status.DONE &&
- latestTaskRun.value.hasPriorBackup
- ) {
- return latestTaskRun.value;
- }
- return undefined;
-});
-
-const statement = computed(() => {
- const sheet = sheetStore.getSheetByName(sheetNameOfTaskV1(props.task));
- if (sheet) return getSheetStatement(sheet);
- return "";
-});
-
-watch(
- () => sheetNameOfTaskV1(props.task),
- async (sheetName) => {
- if (!sheetName) return;
- try {
- await sheetStore.getOrFetchSheetByName(sheetName);
- } catch {
- // Ignore — sheet fetch is non-critical for panel display
- }
- },
- { immediate: true }
-);
-
-const handleTaskActionConfirmed = () => {
- emitPlanStatusChanged(events, { refreshMode: "fast-follow" });
-};
-</script>
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/index.ts b/frontend/src/components/Plan/components/PlanDetailPage/index.ts
deleted file mode 100644
index 12b01a0832..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { default as PlanDetailPage } from "./PlanDetailPage.vue";
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/useActivePhase.ts b/frontend/src/components/Plan/components/PlanDetailPage/useActivePhase.ts
deleted file mode 100644
index e884e0aa2e..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/useActivePhase.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { ref } from "vue";
-
-export type PhaseType = "changes" | "review" | "deploy";
-
-const DEFAULT_EXPANDED_PHASES: PhaseType[] = ["changes", "review", "deploy"];
-
-export const useActivePhase = () => {
- const manualExpanded = ref(new Set<PhaseType>(DEFAULT_EXPANDED_PHASES));
- const isExpanded = (phase: PhaseType): boolean => {
- return manualExpanded.value.has(phase);
- };
-
- const togglePhase = (phase: PhaseType) => {
- const next = new Set(manualExpanded.value);
- if (next.has(phase)) {
- next.delete(phase);
- } else {
- next.add(phase);
- }
- manualExpanded.value = next;
- };
-
- // For programmatic expansion (e.g., route query ?section=deploy)
- const expandPhase = (phase: PhaseType) => {
- const next = new Set(manualExpanded.value);
- next.add(phase);
- manualExpanded.value = next;
- };
-
- const syncExpandedPhases = (phases: PhaseType[]) => {
- if (phases.length === 0) return;
-
- const next = new Set(manualExpanded.value);
- for (const phase of phases) {
- next.add(phase);
- }
- manualExpanded.value = next;
- };
-
- return {
- isExpanded,
- togglePhase,
- expandPhase,
- syncExpandedPhases,
- };
-};
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/usePhaseState.ts b/frontend/src/components/Plan/components/PlanDetailPage/usePhaseState.ts
deleted file mode 100644
index 07f14f85d8..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/usePhaseState.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import type { TagProps } from "naive-ui";
-import { computed, type Ref } from "vue";
-import { useI18n } from "vue-i18n";
-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
-import {
- Issue_ApprovalStatus,
- IssueStatus,
-} from "@/types/proto-es/v1/issue_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 { PhaseType } from "./useActivePhase";
-
-export type PhaseStatus = "completed" | "closed" | "active" | "future";
-
-export interface PhaseBadge {
- label: string;
- type: TagProps["type"];
-}
-
-export interface PhaseConfig {
- status: PhaseStatus;
- badge?: PhaseBadge;
- lineClass: string;
-}
-
-export const usePhaseState = (
- isCreating: Ref<boolean>,
- issue: Ref<Issue | undefined>,
- rollout: Ref<Rollout | undefined>
-) => {
- const { t } = useI18n();
-
- const statusMap = computed<Record<PhaseType, PhaseStatus>>(() => {
- const creating = isCreating.value;
- const hasIssue = !!issue.value;
- const hasRollout = !!rollout.value;
- const isIssueClosed =
- issue.value?.status === IssueStatus.CANCELED ||
- issue.value?.status === IssueStatus.DONE;
- const allTasks = rollout.value?.stages.flatMap((s) => s.tasks) ?? [];
- const allDone =
- allTasks.length > 0 &&
- allTasks.every(
- (task) =>
- task.status === Task_Status.DONE ||
- task.status === Task_Status.SKIPPED
- );
-
- let review: PhaseStatus = "future";
- if (hasIssue) {
- if (issue.value?.status === IssueStatus.CANCELED) {
- review = "closed";
- } else {
- review = hasRollout || isIssueClosed ? "completed" : "active";
- }
- }
-
- return {
- changes: creating || (!hasIssue && !hasRollout) ? "active" : "completed",
- review,
- deploy: hasRollout ? (allDone ? "completed" : "active") : "future",
- };
- });
-
- // Badges
-
- const changesBadge = computed<PhaseBadge | undefined>(() => {
- if (statusMap.value.changes !== "active") return undefined;
- if (isCreating.value) return undefined;
- return { label: t("common.draft"), type: "default" };
- });
-
- const reviewBadge = computed<PhaseBadge | undefined>(() => {
- if (!issue.value) return undefined;
- if (issue.value.status === IssueStatus.CANCELED) {
- return { label: t("common.closed"), type: "default" };
- }
- // Show badge for both active and completed review phases
- if (statusMap.value.review === "future") return undefined;
- const map: Partial<
- Record<Issue_ApprovalStatus, { label: string; type: TagProps["type"] }>
- > = {
- [Issue_ApprovalStatus.APPROVED]: {
- label: t("issue.table.approved"),
- type: "success",
- },
- [Issue_ApprovalStatus.SKIPPED]: {
- label: t("common.skipped"),
- type: "default",
- },
- [Issue_ApprovalStatus.REJECTED]: {
- label: t("common.rejected"),
- type: "warning",
- },
- [Issue_ApprovalStatus.PENDING]: {
- label: t("common.under-review"),
- type: "info",
- },
- };
- // If review phase is completed but approval was not explicitly approved/skipped,
- // the approval was bypassed by manual rollout creation — show "Skipped"
- if (
- statusMap.value.review === "completed" &&
- issue.value.approvalStatus !== Issue_ApprovalStatus.APPROVED &&
- issue.value.approvalStatus !== Issue_ApprovalStatus.SKIPPED
- ) {
- return { label: t("common.skipped"), type: "default" };
- }
- return map[issue.value.approvalStatus];
- });
-
- const deployBadge = computed<PhaseBadge | undefined>(() => {
- if (statusMap.value.deploy !== "active" || !rollout.value) return undefined;
- const allTasks = rollout.value.stages.flatMap((s) => s.tasks);
- const hasCompletedTasks = allTasks.some(
- (task) =>
- task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
- );
- if (allTasks.some((task) => task.status === Task_Status.FAILED))
- return { label: t("common.failed"), type: "error" };
- if (
- allTasks.some(
- (task) =>
- task.status === Task_Status.RUNNING ||
- task.status === Task_Status.PENDING
- ) ||
- hasCompletedTasks
- )
- return { label: t("common.in-progress"), type: "info" };
- return { label: t("common.not-started"), type: "default" };
- });
-
- // Line colors
-
- const lineClass = (from: PhaseType, to: PhaseType): string => {
- const f = statusMap.value[from];
- const s = statusMap.value[to];
- if (f === "closed" || s === "closed")
- return "border-l-2 border-dashed border-control-border";
- if (f === "completed" && s === "completed")
- return "border-l-2 border-success";
- if (f === "completed" && s === "active") return "border-l-2 border-success";
- if (f === "active") return "border-l-2 border-dashed border-accent";
- return "border-l-2 border-dashed border-control-border";
- };
-
- // Assembled array (indexed: 0=changes, 1=review, 2=deploy)
-
- const phases = computed<[PhaseConfig, PhaseConfig, PhaseConfig]>(() => [
- {
- status: statusMap.value.changes,
- badge: changesBadge.value,
- lineClass: lineClass("changes", "review"),
- },
- {
- status: statusMap.value.review,
- badge: reviewBadge.value,
- lineClass: lineClass("review", "deploy"),
- },
- {
- status: statusMap.value.deploy,
- badge: deployBadge.value,
- lineClass: "",
- },
- ]);
-
- return { phases };
-};
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/usePhaseSummaries.ts b/frontend/src/components/Plan/components/PlanDetailPage/usePhaseSummaries.ts
deleted file mode 100644
index be1b9caa9c..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/usePhaseSummaries.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { uniq } from "lodash-es";
-import { computed, type Ref } from "vue";
-import { useI18n } from "vue-i18n";
-import { extractUserEmail } from "@/store";
-import { isValidDatabaseGroupName } from "@/types";
-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 { targetsForSpec } from "../../logic/plan";
-import { usePlanCheckStatus } from "../../logic/usePlanCheckStatus";
-
-export const usePhaseSummaries = (
- plan: Ref<Plan>,
- issue: Ref<Issue | undefined>,
- rollout: Ref<Rollout | undefined>
-) => {
- const { t } = useI18n();
- const { statusSummary } = usePlanCheckStatus(plan);
-
- const changesSummary = computed(() => {
- const parts: string[] = [];
-
- const specCount = plan.value.specs.length;
- parts.push(t("plan.summary.n-changes", { n: specCount }));
-
- const targets = uniq(plan.value.specs.flatMap(targetsForSpec));
- if (targets.length > 0) {
- const dbGroupCount = targets.filter(isValidDatabaseGroupName).length;
- const dbCount = targets.length - dbGroupCount;
- const targetParts: string[] = [];
- if (dbCount > 0) {
- targetParts.push(t("plan.summary.n-databases", { n: dbCount }));
- }
- if (dbGroupCount > 0) {
- targetParts.push(
- t("plan.summary.n-database-groups", { n: dbGroupCount })
- );
- }
- parts.push(targetParts.join(` ${t("common.and")} `));
- }
-
- const checks = statusSummary.value;
- if (checks.total > 0) {
- const checkParts: string[] = [];
- if (checks.success > 0)
- checkParts.push(t("plan.summary.n-passed", { n: checks.success }));
- if (checks.warning > 0)
- checkParts.push(t("plan.summary.n-warning", { n: checks.warning }));
- if (checks.error > 0)
- checkParts.push(t("plan.summary.n-error", { n: checks.error }));
- parts.push(checkParts.join(", "));
- }
-
- return parts.join(" · ");
- });
-
- const reviewSummary = computed(() => {
- if (!issue.value) return "";
- const roles = issue.value.approvalTemplate?.flow?.roles ?? [];
- const approvers = issue.value.approvers;
- const parts: string[] = [];
-
- if (roles.length > 0) {
- parts.push(
- t("plan.summary.n-of-m-approved", {
- n: approvers.length,
- m: roles.length,
- })
- );
- }
-
- if (approvers.length > 0) {
- const last = approvers[approvers.length - 1];
- const name = extractUserEmail(last.principal).split("@")[0];
- parts.push(t("plan.summary.last-approved-by", { name }));
- }
-
- return parts.join(" · ");
- });
-
- const deploySummary = computed(() => {
- if (!rollout.value) return "";
- const allTasks = rollout.value.stages.flatMap((s) => s.tasks);
- const total = allTasks.length;
- const completed = allTasks.filter(
- (task) =>
- task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
- ).length;
- return t("plan.summary.n-of-m-tasks", { n: completed, m: total });
- });
-
- return { changesSummary, reviewSummary, deploySummary };
-};
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailDesktopLayout.ts b/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailDesktopLayout.ts
deleted file mode 100644
index 011de6c9ab..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailDesktopLayout.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import type { CSSProperties, Ref } from "vue";
-import { computed } from "vue";
-import { PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR } from "./usePlanDetailViewportVars";
-
-export const PLAN_DETAIL_XL_BREAKPOINT = 1280;
-export const PLAN_DETAIL_TASK_DRAWER_WIDTH = 640;
-export const PLAN_DETAIL_METADATA_DRAWER_WIDTH = 320;
-
-export const usePlanDetailDesktopLayout = ({
- sidebarMode,
- containerWidth,
- desktopSidebarWidth,
- hasDetailPanel,
-}: {
- sidebarMode: Readonly<Ref<string>>;
- containerWidth: Readonly<Ref<number>>;
- desktopSidebarWidth: Readonly<Ref<number>>;
- hasDetailPanel: Readonly<Ref<boolean>>;
-}) => {
- const supportsInlineDetailPanel = computed(() => {
- return (
- sidebarMode.value === "DESKTOP" &&
- containerWidth.value >= PLAN_DETAIL_XL_BREAKPOINT
- );
- });
-
- const showDesktopSidebar = computed(() => {
- return sidebarMode.value === "DESKTOP" && !hasDetailPanel.value;
- });
-
- const showInlineDetailPanel = computed(() => {
- return hasDetailPanel.value && supportsInlineDetailPanel.value;
- });
-
- const showTaskDrawer = computed(() => {
- return (
- hasDetailPanel.value &&
- !showInlineDetailPanel.value &&
- sidebarMode.value !== "NONE"
- );
- });
-
- const showSidebarDrawer = computed(() => {
- return sidebarMode.value === "MOBILE";
- });
-
- const desktopLayoutStyle = computed<CSSProperties>(() => {
- const baseStyle: CSSProperties = {
- minHeight: `var(${PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR})`,
- };
-
- if (sidebarMode.value !== "DESKTOP") {
- return baseStyle;
- }
-
- if (showInlineDetailPanel.value) {
- return {
- ...baseStyle,
- gridTemplateColumns: "minmax(0, 1fr) minmax(0, 50%)",
- };
- }
-
- if (showDesktopSidebar.value) {
- return {
- ...baseStyle,
- gridTemplateColumns: `minmax(0, 1fr) ${desktopSidebarWidth.value}px`,
- };
- }
-
- return baseStyle;
- });
-
- return {
- desktopLayoutStyle,
- showDesktopSidebar,
- showInlineDetailPanel,
- showTaskDrawer,
- showSidebarDrawer,
- };
-};
diff --git a/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailViewportVars.ts b/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailViewportVars.ts
deleted file mode 100644
index a2d1d249b3..0000000000
--- a/frontend/src/components/Plan/components/PlanDetailPage/usePlanDetailViewportVars.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useElementSize } from "@vueuse/core";
-import { computed, type Ref } from "vue";
-import { useBodyLayoutContext } from "@/layouts/common";
-
-export const PLAN_DETAIL_VIEWPORT_HEIGHT_VAR =
- "--bb-plan-detail-viewport-height";
-export const PLAN_DETAIL_LAYOUT_MIN_HEIGHT_VAR =
- "--bb-plan-detail-layout-min-height";
-export const PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR =
- "--bb-plan-detail-content-min-height";
-
-export const usePlanDetailViewportVars = (
- headerRef: Ref<HTMLElement | undefined>
-) => {
- const { mainContainerRef } = useBodyLayoutContext();
- const { height: mainContainerHeight } = useElementSize(mainContainerRef);
- const { height: headerHeight } = useElementSize(headerRef);
-
- const viewportVars = computed(() => {
- if (!mainContainerHeight.value) {
- return undefined;
- }
-
- const contentMinHeight = Math.max(
- mainContainerHeight.value - headerHeight.value,
- 0
- );
-
- return {
- [PLAN_DETAIL_VIEWPORT_HEIGHT_VAR]: `${mainContainerHeight.value}px`,
- [PLAN_DETAIL_LAYOUT_MIN_HEIGHT_VAR]: `${mainContainerHeight.value}px`,
- [PLAN_DETAIL_CONTENT_MIN_HEIGHT_VAR]: `${contentMinHeight}px`,
- };
- });
-
- return {
- viewportVars,
- };
-};
diff --git a/frontend/src/react/components/ui/select.tsx b/frontend/src/react/components/ui/select.tsx
index 23335931fc..6125fd2e87 100644
--- a/frontend/src/react/components/ui/select.tsx
+++ b/frontend/src/react/components/ui/select.tsx
@@ -19,7 +19,7 @@ const selectTriggerVariants = cva(
variants: {
size: {
xs: "h-6 px-2 text-xs leading-4",
- sm: "h-8 px-3 text-xs leading-4",
+ sm: "h-8 px-3 text-sm leading-5",
md: "h-9 px-3 text-sm leading-5",
lg: "h-10 px-3 text-sm leading-5",
},
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index c03b515176..30d9066a3a 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -210,6 +210,7 @@
"archive-resource": "Archive {{type}}",
"archived": "Archived",
"back": "Back",
+ "bypassed": "Bypassed",
"cancel": "Cancel",
"cannot-undo-this-action": "You cannot undo this action",
"changelog": "Changelog",
@@ -249,10 +250,12 @@
"deny": "Deny",
"description": "Description",
"deselect-all": "Deselect all",
+ "detail": "Detail",
"detailed-guide": "detailed guide",
"disable": "Disable",
"discard-changes": "Discard changes",
"dismiss": "Dismiss",
+ "done": "Done",
"download": "Download",
"draft": "Draft",
"duration": "Duration",
@@ -309,6 +312,7 @@
"name": "Name",
"next": "Next",
"no-data": "No data",
+ "not-started": "Not started",
"ok": "OK",
"operations": "Operations",
"optional": "Optional",
@@ -323,6 +327,7 @@
"projects": "Projects",
"read-only": "Read-only",
"reason": "Reason",
+ "refresh": "Refresh",
"regenerate": "Regenerate",
"reject": "Reject",
"rejected": "Rejected",
@@ -343,12 +348,14 @@
"self": "Role"
},
"rollback": "Rollback",
+ "rollout": "Rollout",
"rows": {
"n-rows": "{{n}} rows",
"self": "rows"
},
"rows-per-page": "Rows per page",
"run": "Run",
+ "running": "Running",
"save": "Save",
"schema": "Schema",
"scope": "Scope",
@@ -405,9 +412,11 @@
"common.add": "Add",
"common.admin": "Admin",
"common.all": "All",
+ "common.and": "and",
"common.archive": "Archive",
"common.archived": "Archived",
"common.cancel": "Cancel",
+ "common.canceled": "Canceled",
"common.cannot-undo-this-action": "You cannot undo this action",
"common.catalog": "Catalog",
"common.close": "Close",
@@ -427,12 +436,15 @@
"common.delete": "Delete",
"common.delete-resource": "Delete {{type}}",
"common.deleted": "Deleted",
+ "common.deploying": "Deploying",
"common.detail": "Detail",
"common.detailed-guide": "detailed guide",
"common.edit": "Edit",
"common.edited": "edited",
"common.environment": "Environment",
"common.import": "Import",
+ "common.in-progress": "In progress",
+ "common.in-review": "In Review",
"common.issue": "Issue",
"common.key": "Key",
"common.labels": "Labels",
@@ -457,12 +469,14 @@
"common.remaining": "remaining",
"common.remove": "Remove",
"common.removed": "Removed",
+ "common.reopen": "Reopen",
"common.restore": "Restore",
"common.retry": "Retry",
"common.role.self": "Role",
"common.rollout": "Rollout",
"common.save": "Save",
"common.sensitive-placeholder": "Sensitive - write only",
+ "common.show-less": "Show less",
"common.show-more": "Show more",
"common.skip": "Skip",
"common.success": "Success",
@@ -1339,6 +1353,8 @@
"upload-sql": "Upload SQL",
"waiting-approval": "Waiting for Approval"
},
+ "issue.action-anyway": "{{action}} anyway",
+ "issue.checks-warning-hint": "Some checks did not pass. Continue anyway only if this is expected.",
"issue.comment-editor.nothing-to-preview": "Nothing to preview",
"issue.comment-editor.preview": "Preview",
"issue.comment-editor.toolbar.bold": "Insert bold text",
@@ -1347,6 +1363,7 @@
"issue.comment-editor.toolbar.header": "Insert heading text",
"issue.comment-editor.toolbar.link": "Insert a link",
"issue.comment-editor.write": "Write",
+ "issue.create-rollout": "Create Rollout",
"issue.data-export.format": "Format",
"issue.data-export.limits": "Limits",
"issue.data-export.options": "Options",
@@ -1357,6 +1374,7 @@
"issue.review.self": "Review",
"issue.statement-from-sheet-warning": "This statement is loaded from a large sheet. Preview may be truncated.",
"issue.task-run.logs": "Logs",
+ "issue.task-run.session": "Session",
"issue.transaction-mode.label": "Transaction Mode",
"issue.upload-sql-file-max-size-exceeded": "Max file size ({size}) exceeded.",
"label": {
@@ -1416,39 +1434,80 @@
"save-changes-before-continuing": "Please save or cancel your changes before continuing"
},
"navigator": {
+ "changes": "Changes",
+ "deploy": "Deploy",
"review": "Review"
},
"new-plan": "New Plan",
"plans": "Plans",
+ "sidebar": {
+ "created-by-at": "Created by {{user}} · {{time}}",
+ "future-sections-hint": "Review, labels, and rollout details appear after submission"
+ },
"subtitle": "Draft database changes and run pre-checks before creating an issue for approval.",
"targets": {
"title": "Targets"
}
},
+ "plan.add-spec": "Add Change",
"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",
"plan.checks.started": "Plan checks started",
+ "plan.description.placeholder": "Add description",
+ "plan.ghost.requirements-not-met": "Ghost requirements not met: {{databases}}",
"plan.go-to-plan-page": "Go to plan page",
"plan.isolation-level.read-committed": "Read Committed",
"plan.isolation-level.read-uncommitted": "Read Uncommitted",
"plan.isolation-level.repeatable-read": "Repeatable Read",
"plan.isolation-level.self": "Isolation Level",
"plan.isolation-level.serializable": "Serializable",
+ "plan.labels-required-for-review": "Labels are required before review",
"plan.navigator.checks": "Checks",
"plan.navigator.statement-empty": "Statement is empty",
+ "plan.options.no-options-available": "No options available",
"plan.options.self": "Options",
"plan.overview.no-checks": "No checks",
+ "plan.phase.create-rollout-action": "Manually create rollout",
+ "plan.phase.deploy-approval-must-complete": "Approval flow must be done.",
+ "plan.phase.deploy-approval-optional": "Approval can be bypassed based on the current project settings.",
+ "plan.phase.deploy-approval-pending": "Finish the approval flow before rollout can proceed automatically.",
+ "plan.phase.deploy-approval-ready": "Approval is complete for this plan.",
+ "plan.phase.deploy-checks-blocked": "Failed checks are blocking automatic rollout creation.",
+ "plan.phase.deploy-checks-must-pass": "Checks must pass.",
+ "plan.phase.deploy-checks-optional": "Failed checks won't block manual rollout in this project.",
+ "plan.phase.deploy-checks-ready": "Checks are ready for automatic rollout creation.",
+ "plan.phase.deploy-checks-running": "Wait for running checks to finish before automatic rollout can proceed.",
+ "plan.phase.deploy-description": "Bytebase will automatically create the rollout when all checks pass and the issue is approved.",
+ "plan.phase.deploy-manual-create-description": "Based on the current project settings, you can also create the rollout manually.",
+ "plan.phase.deploy-manual-create-description-readonly": "User with Create Rollout permission can create the rollout manually.",
+ "plan.phase.hide-details": "Hide details",
+ "plan.phase.review-description": "Submit for review to proceed",
+ "plan.phase.show-details": "Show details",
+ "plan.pre-backup.requirements-not-met": "Pre-backup requirements not met: {{databases}}",
"plan.ready-for-review": "Ready for Review",
"plan.run": "Run checks",
"plan.select-isolation-level": "Select isolation level",
+ "plan.select-targets": "Select Targets",
"plan.spec.change": "Change",
"plan.spec.type.database-change": "Database Change",
+ "plan.state.close-confirm": "Close this plan?",
+ "plan.state.reopen-confirm": "Reopen this plan?",
+ "plan.summary.last-approved-by": "Last approved by {{name}}",
+ "plan.summary.n-changes": "{{n}} changes",
+ "plan.summary.n-database-groups": "{{n}} database groups",
+ "plan.summary.n-databases": "{{n}} databases",
+ "plan.summary.n-error": "{{n}} error",
+ "plan.summary.n-of-m-approved": "{{n}} of {{m}} approved",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} tasks",
+ "plan.summary.n-passed": "{{n}} passed",
+ "plan.summary.n-warning": "{{n}} warning",
"plan.targets.no-targets-found": "No targets found",
"plan.targets.non-env-warning.one": "{{count}} database will be excluded from rollout because it has no effective environment:",
"plan.targets.non-env-warning.other": "{{count}} databases will be excluded from rollout because they have no effective environment:",
"plan.targets.title": "Targets",
"plan.targets.view-all": "View all ({{count}})",
+ "plan.view-discussion": "View discussion",
"policy": {
"environment-tier": {
"description": "The environment will appear differently from other environments.",
@@ -1710,12 +1769,28 @@
}
},
"rollout": {
+ "no-stages": "No stages available",
+ "no-tasks-created": "No tasks created yet",
+ "pending-tasks-preview": {
+ "action": "Preview",
+ "description": "The following tasks have not been created yet.",
+ "no-pending-tasks": "No pending tasks",
+ "task-count_one": "{{count}} task",
+ "task-count_other": "{{count}} tasks",
+ "title": "Pending Tasks"
+ },
"stage": {
+ "confirm-create": "Confirm to create tasks for this stage?",
+ "run-stage": "Run Tasks",
"self_one": "Stage",
"self_other": "Stages"
},
"task-execution-errors": "Task execution errors"
},
+ "rollout.bypass-stage-requirements": "Bypass warnings",
+ "rollout.task.no-tasks": "No tasks in this stage",
+ "rollout.task.selected-count": "{{count}} task selected",
+ "rollout.task.statement-truncated-hint": "Statement truncated due to large size.",
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -3282,7 +3357,13 @@
"skipped": "Skipped"
}
},
- "task-run.history": "Execution History",
+ "task-run.blocked-sessions": "Blocked Sessions",
+ "task-run.blocked-sessions-description": "The sessions that are blocked by the current session",
+ "task-run.blocking-sessions": "Blocking Sessions",
+ "task-run.blocking-sessions-description": "The sessions that are blocking the current session",
+ "task-run.history": "History",
+ "task-run.latest": "Latest",
+ "task-run.latest-logs": "Latest Logs",
"task-run.log-detail.backing-up": "Backing up...",
"task-run.log-detail.backup-completed": "completed ({{count}} tables)",
"task-run.log-detail.completed": "Completed",
@@ -3303,6 +3384,10 @@
"task-run.log-viewer.multiple-replicas-notice": "Server restart detected during execution. Logs are grouped by replica.",
"task-run.log-viewer.replica-n": "Replica #{{n}}",
"task-run.log-viewer.summary": "{{sections}} sections · {{entries}} entries",
+ "task-run.no-session-found": "No session found",
+ "task-run.rollback.available": "{{count}} rollback available",
+ "task-run.rollback.no-statement-generated": "No statement generated",
+ "task-run.rollback.preview-statement.description": "Review the generated rollback statements before creating the rollback plan.",
"task-run.status.enqueued": "Waiting for execution.",
"task-run.status.enqueued-with-rollout-time": "Waiting to execute after {{time}}.",
"task-run.status.waiting-max-tasks-per-rollout": "Waiting for other tasks to finish. Maximum running tasks limit per rollout has been reached. Last report at {{time}}.",
@@ -3313,8 +3398,18 @@
"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",
+ "task.no-selectable-tasks": "No selectable tasks",
+ "task.no-skippable-tasks": "No skippable tasks",
+ "task.no-tasks-selected": "No tasks selected",
"task.online-migration.self": "Online migration",
+ "task.only-showing-latest-n-runs": "Only showing latest {{n}} runs",
"task.prior-backup": "Prior backup",
+ "task.run-history": "Run History",
+ "task.scheduled-time": "Scheduled time",
+ "task.select-task": "Select Task",
"two-factor": {
"description": "Two-factor authentication provides an extra layer of security for member accounts. When signing in, you will be required to enter the security code generated by your Authenticator App.",
"disable": {
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index e527e47ea3..1eca5c7e65 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -210,6 +210,7 @@
"archive-resource": "Archive {{type}}",
"archived": "Archivada",
"back": "Volver",
+ "bypassed": "Omitido",
"cancel": "Cancelar",
"cannot-undo-this-action": "No se puede deshacer esta acción",
"changelog": "Changelog",
@@ -249,10 +250,12 @@
"deny": "Denegar",
"description": "Descripción",
"deselect-all": "Deselect all",
+ "detail": "Detalle",
"detailed-guide": "guía detallada",
"disable": "Disable",
"discard-changes": "Descartar cambios",
"dismiss": "Descartar",
+ "done": "Hecho",
"download": "Descargar",
"draft": "Borrador",
"duration": "Duration",
@@ -309,6 +312,7 @@
"name": "Nombre",
"next": "Siguiente",
"no-data": "Sin datos",
+ "not-started": "No iniciado",
"ok": "OK",
"operations": "Operaciones",
"optional": "Optional",
@@ -323,6 +327,7 @@
"projects": "Proyectos",
"read-only": "Solo lectura",
"reason": "Razón",
+ "refresh": "Actualizar",
"regenerate": "Regenerar",
"reject": "Reject",
"rejected": "Rechazado",
@@ -343,12 +348,14 @@
"self": "Rol"
},
"rollback": "Retroceder",
+ "rollout": "Despliegue",
"rows": {
"n-rows": "{{n}} filas",
"self": "filas"
},
"rows-per-page": "Filas por página",
"run": "Run",
+ "running": "En ejecución",
"save": "Guardar",
"schema": "Esquema",
"scope": "Alcance",
@@ -405,9 +412,11 @@
"common.add": "Agregar",
"common.admin": "Admin",
"common.all": "Todos",
+ "common.and": "y",
"common.archive": "Archivo",
"common.archived": "Archivada",
"common.cancel": "Cancelar",
+ "common.canceled": "Cancelado",
"common.cannot-undo-this-action": "No se puede deshacer esta acción",
"common.catalog": "Catálogo",
"common.close": "Cerrar",
@@ -427,12 +436,15 @@
"common.delete": "Eliminar",
"common.delete-resource": "Delete {{type}}",
"common.deleted": "Eliminado",
+ "common.deploying": "Desplegando",
"common.detail": "Detail",
"common.detailed-guide": "guía detallada",
"common.edit": "Editar",
"common.edited": "edited",
"common.environment": "Entorno",
"common.import": "Importar",
+ "common.in-progress": "En progreso",
+ "common.in-review": "En revisión",
"common.issue": "Issue",
"common.key": "Clave",
"common.labels": "Etiquetas",
@@ -457,12 +469,14 @@
"common.remaining": "restantes",
"common.remove": "Eliminar",
"common.removed": "Eliminado",
+ "common.reopen": "Reabrir",
"common.restore": "Restaurar",
"common.retry": "Reintentar",
"common.role.self": "Rol",
"common.rollout": "Implementar",
"common.save": "Guardar",
"common.sensitive-placeholder": "Sensible - solo escritura",
+ "common.show-less": "Mostrar menos",
"common.show-more": "Mostrar más",
"common.skip": "Omitir",
"common.success": "Éxito",
@@ -1339,6 +1353,8 @@
"upload-sql": "Upload SQL",
"waiting-approval": "A la espera de la aprobación"
},
+ "issue.action-anyway": "{{action}} de todos modos",
+ "issue.checks-warning-hint": "Algunas verificaciones no pasaron. Continúa solo si es esperado.",
"issue.comment-editor.nothing-to-preview": "Nothing to preview",
"issue.comment-editor.preview": "Preview",
"issue.comment-editor.toolbar.bold": "Insert bold text",
@@ -1347,6 +1363,7 @@
"issue.comment-editor.toolbar.header": "Insert heading text",
"issue.comment-editor.toolbar.link": "Insert a link",
"issue.comment-editor.write": "Write",
+ "issue.create-rollout": "Crear rollout",
"issue.data-export.format": "Formato",
"issue.data-export.limits": "Límites",
"issue.data-export.options": "Opciones",
@@ -1357,6 +1374,7 @@
"issue.review.self": "Review",
"issue.statement-from-sheet-warning": "This statement is loaded from a large sheet. Preview may be truncated.",
"issue.task-run.logs": "Registros",
+ "issue.task-run.session": "Sesión",
"issue.transaction-mode.label": "Modo de transacción",
"issue.upload-sql-file-max-size-exceeded": "Se ha excedido el tamaño máximo del archivo ({size}).",
"label": {
@@ -1416,39 +1434,80 @@
"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."
},
"navigator": {
+ "changes": "Cambios",
+ "deploy": "Desplegar",
"review": "Revisión"
},
"new-plan": "Nuevo plan",
"plans": "Planes",
+ "sidebar": {
+ "created-by-at": "Creado por {{user}} · {{time}}",
+ "future-sections-hint": "La revisión, las etiquetas y el despliegue aparecen después del envío"
+ },
"subtitle": "Redactar cambios en la base de datos y ejecutar comprobaciones previas antes de crear un problema para su aprobación.",
"targets": {
"title": "Objetivos"
}
},
+ "plan.add-spec": "Agregar cambio",
"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",
"plan.checks.started": "Se iniciaron las verificaciones del plan",
+ "plan.description.placeholder": "Agregar descripción",
+ "plan.ghost.requirements-not-met": "Los requisitos de Ghost no se cumplen para: {{databases}}",
"plan.go-to-plan-page": "Ir a la página del plan",
"plan.isolation-level.read-committed": "Lectura confirmada",
"plan.isolation-level.read-uncommitted": "Lectura no confirmada",
"plan.isolation-level.repeatable-read": "Lectura repetible",
"plan.isolation-level.self": "Nivel de Aislamiento",
"plan.isolation-level.serializable": "Serializable",
+ "plan.labels-required-for-review": "Se requieren etiquetas antes de la revisión",
"plan.navigator.checks": "Verificaciones",
"plan.navigator.statement-empty": "La sentencia está vacía",
+ "plan.options.no-options-available": "No hay opciones disponibles",
"plan.options.self": "Opciones",
"plan.overview.no-checks": "Sin verificaciones",
+ "plan.phase.create-rollout-action": "Crear rollout manualmente",
+ "plan.phase.deploy-approval-must-complete": "El flujo de aprobación debe completarse.",
+ "plan.phase.deploy-approval-optional": "La aprobación puede omitirse según la configuración actual del proyecto.",
+ "plan.phase.deploy-approval-pending": "Completa el flujo de aprobación antes de que el rollout pueda continuar automáticamente.",
+ "plan.phase.deploy-approval-ready": "La aprobación ya está completa para este plan.",
+ "plan.phase.deploy-checks-blocked": "Las verificaciones fallidas están bloqueando la creación automática del rollout.",
+ "plan.phase.deploy-checks-must-pass": "Las comprobaciones deben aprobarse.",
+ "plan.phase.deploy-checks-optional": "Las verificaciones fallidas no bloquearán el rollout manual en este proyecto.",
+ "plan.phase.deploy-checks-ready": "Las verificaciones ya permiten la creación automática del rollout.",
+ "plan.phase.deploy-checks-running": "Espera a que terminen las verificaciones en ejecución antes de que el rollout automático pueda continuar.",
+ "plan.phase.deploy-description": "Bytebase creará automáticamente el rollout cuando todas las comprobaciones pasen y el issue esté aprobado.",
+ "plan.phase.deploy-manual-create-description": "Según la configuración actual del proyecto, también puede crear el rollout manualmente.",
+ "plan.phase.deploy-manual-create-description-readonly": "Un usuario con el permiso Create Rollout puede crear el rollout manualmente.",
+ "plan.phase.hide-details": "Ocultar detalles",
+ "plan.phase.review-description": "Envíe para revisión para continuar",
+ "plan.phase.show-details": "Mostrar detalles",
+ "plan.pre-backup.requirements-not-met": "Los requisitos de copia previa no se cumplen para: {{databases}}",
"plan.ready-for-review": "Listo para revisión",
"plan.run": "Volver a verificar",
"plan.select-isolation-level": "Seleccionar nivel de aislamiento",
+ "plan.select-targets": "Seleccionar destinos",
"plan.spec.change": "Cambio",
"plan.spec.type.database-change": "Cambio de base de datos",
+ "plan.state.close-confirm": "¿Cerrar este plan?",
+ "plan.state.reopen-confirm": "¿Reabrir este plan?",
+ "plan.summary.last-approved-by": "Última aprobación por {{name}}",
+ "plan.summary.n-changes": "{{n}} cambios",
+ "plan.summary.n-database-groups": "{{n}} grupos de bases de datos",
+ "plan.summary.n-databases": "{{n}} bases de datos",
+ "plan.summary.n-error": "{{n}} error",
+ "plan.summary.n-of-m-approved": "{{n}} de {{m}} aprobadas",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} tareas",
+ "plan.summary.n-passed": "{{n}} aprobadas",
+ "plan.summary.n-warning": "{{n}} advertencia",
"plan.targets.no-targets-found": "No se encontraron objetivos",
"plan.targets.non-env-warning.one": "{{count}} base de datos se excluirá del despliegue porque no tiene un entorno efectivo:",
"plan.targets.non-env-warning.other": "{{count}} bases de datos se excluirán del despliegue porque no tienen un entorno efectivo:",
"plan.targets.title": "Objetivos",
"plan.targets.view-all": "Ver todo ({{count}})",
+ "plan.view-discussion": "Ver discusión",
"policy": {
"environment-tier": {
"description": "El entorno aparecerá de manera diferente a otros entornos.",
@@ -1710,12 +1769,28 @@
}
},
"rollout": {
+ "no-stages": "No hay etapas disponibles",
+ "no-tasks-created": "Aún no se han creado tareas",
+ "pending-tasks-preview": {
+ "action": "Vista previa",
+ "description": "Las siguientes tareas aún no se han creado.",
+ "no-pending-tasks": "No hay tareas pendientes",
+ "task-count_one": "{{count}} tarea",
+ "task-count_other": "{{count}} tareas",
+ "title": "Tareas pendientes"
+ },
"stage": {
+ "confirm-create": "¿Confirmas la creación de tareas para esta etapa?",
+ "run-stage": "Ejecutar tareas",
"self_one": "Etapa",
"self_other": "Etapas"
},
"task-execution-errors": "Errores de ejecución de tareas"
},
+ "rollout.bypass-stage-requirements": "Omitir advertencias",
+ "rollout.task.no-tasks": "No hay tareas en esta etapa",
+ "rollout.task.selected-count": "{{count}} tarea seleccionada",
+ "rollout.task.statement-truncated-hint": "Declaración truncada debido al gran tamaño.",
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -3282,7 +3357,13 @@
"skipped": "Omitido"
}
},
- "task-run.history": "Historial de ejecución",
+ "task-run.blocked-sessions": "Sesiones bloqueadas",
+ "task-run.blocked-sessions-description": "Las sesiones que están bloqueadas por la sesión actual.",
+ "task-run.blocking-sessions": "Sesiones bloqueantes",
+ "task-run.blocking-sessions-description": "Las sesiones que están bloqueando la sesión actual.",
+ "task-run.history": "Historial",
+ "task-run.latest": "Último",
+ "task-run.latest-logs": "Últimos registros",
"task-run.log-detail.backing-up": "haciendo copia de seguridad...",
"task-run.log-detail.backup-completed": "completadas ({{count}} tablas)",
"task-run.log-detail.completed": "Completado",
@@ -3303,18 +3384,32 @@
"task-run.log-viewer.multiple-replicas-notice": "Se detectó un reinicio del servidor durante la ejecución. Los registros están agrupados por réplica.",
"task-run.log-viewer.replica-n": "Réplica #{{n}}",
"task-run.log-viewer.summary": "{{sections}} secciones · {{entries}} entradas",
+ "task-run.no-session-found": "No se encontró sesión",
+ "task-run.rollback.available": "{{count}} rollback disponible",
+ "task-run.rollback.no-statement-generated": "No se generó ninguna sentencia",
+ "task-run.rollback.preview-statement.description": "Revisa las sentencias de rollback generadas antes de crear el plan de rollback.",
"task-run.status.enqueued": "Esperando a ser ejecutada.",
"task-run.status.enqueued-with-rollout-time": "Esperando para ejecutar después de {{time}}.",
"task-run.status.waiting-max-tasks-per-rollout": "Esperando a que terminen otras tareas. Se ha alcanzado el límite máximo de tareas en ejecución por despliegue. Último informe a las {{time}}.",
"task.affected-rows": "Filas afectadas",
- "task.check-type.affected-rows.description": "Estimated by statistical information.",
- "task.check-type.affected-rows.self": "Affected rows",
+ "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",
+ "task.no-selectable-tasks": "No hay tareas seleccionables",
+ "task.no-skippable-tasks": "No hay tareas que se puedan omitir",
+ "task.no-tasks-selected": "No hay tareas seleccionadas",
"task.online-migration.self": "Migración en línea",
+ "task.only-showing-latest-n-runs": "Solo se muestran las últimas {{n}} ejecuciones",
"task.prior-backup": "Respaldo previo",
+ "task.run-history": "Historial de ejecución",
+ "task.scheduled-time": "Hora programada",
+ "task.select-task": "Seleccionar tarea",
"two-factor": {
"description": "La autenticación de dos factores proporciona una capa adicional de seguridad para las cuentas de los miembros. Al iniciar sesión, se te pedirá que ingreses el código de seguridad generado por tu aplicación de autenticación.",
"disable": {
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 1946b829a0..775a70173f 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -210,6 +210,7 @@
"archive-resource": "Archive {{type}}",
"archived": "アーカイブ済み",
"back": "戻る",
+ "bypassed": "バイパス済み",
"cancel": "キャンセル",
"cannot-undo-this-action": "この操作は元に戻せません",
"changelog": "Changelog",
@@ -249,10 +250,12 @@
"deny": "拒否",
"description": "説明",
"deselect-all": "Deselect all",
+ "detail": "詳細",
"detailed-guide": "詳細ガイド",
"disable": "Disable",
"discard-changes": "変更をキャンセルする",
"dismiss": "閉じる",
+ "done": "完了",
"download": "ダウンロード",
"draft": "下書き",
"duration": "Duration",
@@ -309,6 +312,7 @@
"name": "名前",
"next": "次のステップ",
"no-data": "データなし",
+ "not-started": "未開始",
"ok": "わかりました",
"operations": "操作",
"optional": "Optional",
@@ -323,6 +327,7 @@
"projects": "プロジェクト",
"read-only": "読み取り専用",
"reason": "理由",
+ "refresh": "リフレッシュ",
"regenerate": "再生する",
"reject": "Reject",
"rejected": "却下",
@@ -343,12 +348,14 @@
"self": "ロール"
},
"rollback": "ロールバック",
+ "rollout": "ロールアウト",
"rows": {
"n-rows": "{{n}} 行",
"self": "行"
},
"rows-per-page": "ページあたりの行数",
"run": "Run",
+ "running": "実行中",
"save": "保存",
"schema": "スキーマ",
"scope": "スコープ",
@@ -405,9 +412,11 @@
"common.add": "追加",
"common.admin": "管理者",
"common.all": "全て",
+ "common.and": "と",
"common.archive": "アーカイブ",
"common.archived": "アーカイブ済み",
"common.cancel": "キャンセル",
+ "common.canceled": "キャンセル",
"common.cannot-undo-this-action": "この操作は元に戻せません",
"common.catalog": "カタログ",
"common.close": "閉じる",
@@ -427,12 +436,15 @@
"common.delete": "消去",
"common.delete-resource": "Delete {{type}}",
"common.deleted": "削除されました",
+ "common.deploying": "デプロイ中",
"common.detail": "Detail",
"common.detailed-guide": "詳細ガイド",
"common.edit": "編集",
"common.edited": "edited",
"common.environment": "環境",
"common.import": "インポート",
+ "common.in-progress": "進行中",
+ "common.in-review": "レビュー中",
"common.issue": "Issue",
"common.key": "キー",
"common.labels": "ラベル",
@@ -457,12 +469,14 @@
"common.remaining": "残り",
"common.remove": "削除",
"common.removed": "削除されました",
+ "common.reopen": "再開",
"common.restore": "復元する",
"common.retry": "再試行",
"common.role.self": "ロール",
"common.rollout": "リリース",
"common.save": "保存",
"common.sensitive-placeholder": "機密データ - 書き込みのみ",
+ "common.show-less": "折りたたむ",
"common.show-more": "もっと見る",
"common.skip": "スキップ",
"common.success": "成功",
@@ -1339,6 +1353,8 @@
"upload-sql": "Upload SQL",
"waiting-approval": "承認待ち"
},
+ "issue.action-anyway": "まだ {{action}} が必要です",
+ "issue.checks-warning-hint": "一部のチェックが未通過です。想定どおりの場合のみ続行してください。",
"issue.comment-editor.nothing-to-preview": "Nothing to preview",
"issue.comment-editor.preview": "Preview",
"issue.comment-editor.toolbar.bold": "Insert bold text",
@@ -1347,6 +1363,7 @@
"issue.comment-editor.toolbar.header": "Insert heading text",
"issue.comment-editor.toolbar.link": "Insert a link",
"issue.comment-editor.write": "Write",
+ "issue.create-rollout": "ロールアウトを作成",
"issue.data-export.format": "形式",
"issue.data-export.limits": "制限",
"issue.data-export.options": "オプション",
@@ -1357,6 +1374,7 @@
"issue.review.self": "Review",
"issue.statement-from-sheet-warning": "This statement is loaded from a large sheet. Preview may be truncated.",
"issue.task-run.logs": "ログ",
+ "issue.task-run.session": "セッション",
"issue.transaction-mode.label": "トランザクションモード",
"issue.upload-sql-file-max-size-exceeded": "アップロード ファイルのサイズは {size} を超えることはできません。",
"label": {
@@ -1416,39 +1434,80 @@
"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"
},
"navigator": {
+ "changes": "変更点",
+ "deploy": "デプロイ",
"review": "レビュー"
},
"new-plan": "プランの作成",
"plans": "プラン",
+ "sidebar": {
+ "created-by-at": "{{user}} が作成 · {{time}}",
+ "future-sections-hint": "送信後にレビュー、ラベル、デプロイ情報が表示されます"
+ },
"subtitle": "承認のためにイシューを作成する前に、データベースの変更を下書きし、事前チェックを実行します。",
"targets": {
"title": "ターゲット"
}
},
+ "plan.add-spec": "変更を追加",
"plan.checks.failed-to-run": "プランチェックの実行に失敗しました",
- "plan.checks.no-check-results": "チェック結果がありません",
- "plan.checks.no-results-match-filters": "フィルターに一致する結果がありません",
+ "plan.checks.no-check-results": "チェック結果はありません",
+ "plan.checks.no-results-match-filters": "フィルターに一致する結果はありません",
"plan.checks.started": "プランチェックを開始しました",
+ "plan.description.placeholder": "説明を追加",
+ "plan.ghost.requirements-not-met": "次のデータベースは Ghost の要件を満たしていません: {{databases}}",
"plan.go-to-plan-page": "プランページへ移動",
"plan.isolation-level.read-committed": "コミット済み読み取り",
"plan.isolation-level.read-uncommitted": "未コミット読み取り",
"plan.isolation-level.repeatable-read": "反復可能読み取り",
"plan.isolation-level.self": "分離レベル",
"plan.isolation-level.serializable": "直列化可能",
+ "plan.labels-required-for-review": "レビュー前にラベルが必要です",
"plan.navigator.checks": "チェック",
"plan.navigator.statement-empty": "ステートメントが空です",
+ "plan.options.no-options-available": "利用可能なオプションはありません",
"plan.options.self": "オプション",
"plan.overview.no-checks": "チェックなし",
+ "plan.phase.create-rollout-action": "手動でロールアウトを作成",
+ "plan.phase.deploy-approval-must-complete": "承認フローが完了している必要があります。",
+ "plan.phase.deploy-approval-optional": "現在のプロジェクト設定では、承認フローをスキップできます。",
+ "plan.phase.deploy-approval-pending": "ロールアウトを自動的に進める前に承認フローを完了してください。",
+ "plan.phase.deploy-approval-ready": "このプランの承認は完了しています。",
+ "plan.phase.deploy-checks-blocked": "失敗したチェックによりロールアウトの自動作成が止まっています。",
+ "plan.phase.deploy-checks-must-pass": "チェックに合格する必要があります。",
+ "plan.phase.deploy-checks-optional": "このプロジェクトでは、チェック失敗は手動ロールアウトを妨げません。",
+ "plan.phase.deploy-checks-ready": "チェックはロールアウトの自動作成が可能な状態です。",
+ "plan.phase.deploy-checks-running": "実行中のチェックが終わるまで、ロールアウトの自動作成は続行されません。",
+ "plan.phase.deploy-description": "すべてのチェックが通過し、Issue が承認されると、Bytebase は自動的にロールアウトを作成します。",
+ "plan.phase.deploy-manual-create-description": "現在のプロジェクト設定に応じて、ロールアウトを手動で作成することもできます。",
+ "plan.phase.deploy-manual-create-description-readonly": "Create Rollout 権限を持つユーザーがロールアウトを手動で作成できます。",
+ "plan.phase.hide-details": "詳細を隠す",
+ "plan.phase.review-description": "続行するにはレビューに提出してください",
+ "plan.phase.show-details": "詳細を表示",
+ "plan.pre-backup.requirements-not-met": "次のデータベースは事前バックアップ要件を満たしていません: {{databases}}",
"plan.ready-for-review": "レビュー準備完了",
"plan.run": "再チェック",
"plan.select-isolation-level": "分離レベルを選択",
+ "plan.select-targets": "対象を選択",
"plan.spec.change": "変更",
"plan.spec.type.database-change": "データベース変更",
+ "plan.state.close-confirm": "このプランを閉じますか?",
+ "plan.state.reopen-confirm": "このプランを再開きますか?",
+ "plan.summary.last-approved-by": "{{name}} が最後に承認",
+ "plan.summary.n-changes": "{{n}} 件の変更",
+ "plan.summary.n-database-groups": "{{n}} 個のデータベースグループ",
+ "plan.summary.n-databases": "{{n}} 個のデータベース",
+ "plan.summary.n-error": "{{n}} 件のエラー",
+ "plan.summary.n-of-m-approved": "{{m}} 件中 {{n}} 件承認済み",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} タスク",
+ "plan.summary.n-passed": "{{n}} 件合格",
+ "plan.summary.n-warning": "{{n}} 件の警告",
"plan.targets.no-targets-found": "対象が見つかりません",
"plan.targets.non-env-warning.one": "有効な環境がないため、{{count}} 件のデータベースはロールアウトから除外されます:",
"plan.targets.non-env-warning.other": "有効な環境がないため、{{count}} 件のデータベースはロールアウトから除外されます:",
"plan.targets.title": "対象",
"plan.targets.view-all": "すべて表示 ({{count}})",
+ "plan.view-discussion": "ディスカッションを見る",
"policy": {
"environment-tier": {
"description": "この環境を他の環境とは異なって見えるようにします。",
@@ -1710,12 +1769,28 @@
}
},
"rollout": {
+ "no-stages": "利用可能なステージはありません",
+ "no-tasks-created": "まだタスクが作成されていません",
+ "pending-tasks-preview": {
+ "action": "プレビュー",
+ "description": "次のタスクはまだ作成されていません。",
+ "no-pending-tasks": "保留中のタスクはありません",
+ "task-count_one": "{{count}} 件のタスク",
+ "task-count_other": "{{count}} 件のタスク",
+ "title": "保留中のタスク"
+ },
"stage": {
+ "confirm-create": "このステージのタスクを作成しますか?",
+ "run-stage": "タスクを実行",
"self_one": "ステージ",
"self_other": "ステージ"
},
"task-execution-errors": "タスク実行エラー"
},
+ "rollout.bypass-stage-requirements": "警告をバイパス",
+ "rollout.task.no-tasks": "このステージにはタスクがありません",
+ "rollout.task.selected-count": "{{count}} 件のタスクを選択中",
+ "rollout.task.statement-truncated-hint": "サイズが大きいため、ステートメントは切り捨てられました。",
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -3282,7 +3357,13 @@
"skipped": "スキップ"
}
},
- "task-run.history": "実行履歴",
+ "task-run.blocked-sessions": "ブロックされたセッション",
+ "task-run.blocked-sessions-description": "現在のセッションによってブロックされているセッション",
+ "task-run.blocking-sessions": "ブロッキングセッション",
+ "task-run.blocking-sessions-description": "現在のセッションをブロックしているセッション",
+ "task-run.history": "履歴",
+ "task-run.latest": "最新",
+ "task-run.latest-logs": "最新ログ",
"task-run.log-detail.backing-up": "バックアップ中...",
"task-run.log-detail.backup-completed": "完了しました({{count}} テーブル)",
"task-run.log-detail.completed": "完了しました",
@@ -3303,18 +3384,32 @@
"task-run.log-viewer.multiple-replicas-notice": "実行中にサーバーの再起動が検出されました。ログはレプリカごとにグループ化されています。",
"task-run.log-viewer.replica-n": "レプリカ #{{n}}",
"task-run.log-viewer.summary": "{{sections}} セクション · {{entries}} エントリ",
+ "task-run.no-session-found": "セッションが見つかりません",
+ "task-run.rollback.available": "{{count}} 件のロールバックが利用可能",
+ "task-run.rollback.no-statement-generated": "文は生成されませんでした",
+ "task-run.rollback.preview-statement.description": "ロールバックプランを作成する前に生成されたロールバック文を確認してください。",
"task-run.status.enqueued": "実行を待っています。",
"task-run.status.enqueued-with-rollout-time": "{{time}} の後に実行される予定です。",
"task-run.status.waiting-max-tasks-per-rollout": "他のタスクが完了するのを待っています。ロールアウトごとの最大実行タスク数制限に達しました。最後の報告は {{time}} です。",
"task.affected-rows": "影響を受けた行数",
- "task.check-type.affected-rows.description": "Estimated by statistical information.",
- "task.check-type.affected-rows.self": "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": "実行可能なタスクはありません",
+ "task.no-selectable-tasks": "選択可能なタスクはありません",
+ "task.no-skippable-tasks": "スキップ可能なタスクはありません",
+ "task.no-tasks-selected": "タスクが選択されていません",
"task.online-migration.self": "オンラインでの大規模なテーブル変更",
+ "task.only-showing-latest-n-runs": "最新の {{n}} 実行のみを表示",
"task.prior-backup": "影響を受けるデータの事前バックアップ",
+ "task.run-history": "実行履歴",
+ "task.scheduled-time": "スケジュール時刻",
+ "task.select-task": "タスクを選択",
"two-factor": {
"description": "2 要素認証は、システム メンバーに追加のセキュリティ層を提供します。ログインするとき、ユーザーは認証アプリケーションによって生成されたセキュリティ コードを入力する必要があります。",
"disable": {
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index d2b91deecd..5361c2b512 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -210,6 +210,7 @@
"archive-resource": "Archive {{type}}",
"archived": "Đã lưu trữ",
"back": "Quay lại",
+ "bypassed": "Đã bỏ qua",
"cancel": "Hủy",
"cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.",
"changelog": "Changelog",
@@ -249,10 +250,12 @@
"deny": "Từ chối",
"description": "Mô tả",
"deselect-all": "Deselect all",
+ "detail": "Chi tiết",
"detailed-guide": "Hướng dẫn chi tiết",
"disable": "Disable",
"discard-changes": "Hủy thay đổi",
"dismiss": "Loại bỏ",
+ "done": "Hoàn tất",
"download": "Tải xuống",
"draft": "Bản nháp",
"duration": "Duration",
@@ -309,6 +312,7 @@
"name": "Tên",
"next": "Tiếp theo",
"no-data": "Không có dữ liệu",
+ "not-started": "Chưa bắt đầu",
"ok": "OK",
"operations": "Các thao tác",
"optional": "Optional",
@@ -323,6 +327,7 @@
"projects": "Dự án",
"read-only": "Chỉ đọc",
"reason": "Lý do",
+ "refresh": "Làm mới",
"regenerate": "Tạo lại",
"reject": "Reject",
"rejected": "Đã từ chối",
@@ -343,12 +348,14 @@
"self": "Vai trò"
},
"rollback": "Hoàn tác",
+ "rollout": "Triển khai",
"rows": {
"n-rows": "{{n}} dòng",
"self": "dòng"
},
"rows-per-page": "Số dòng mỗi trang",
"run": "Run",
+ "running": "Đang chạy",
"save": "Lưu",
"schema": "Schema",
"scope": "Phạm vi",
@@ -405,9 +412,11 @@
"common.add": "Thêm",
"common.admin": "Quản trị viên",
"common.all": "Tất cả",
+ "common.and": "và",
"common.archive": "Lưu trữ",
"common.archived": "Đã lưu trữ",
"common.cancel": "Hủy",
+ "common.canceled": "Đã hủy",
"common.cannot-undo-this-action": "Bạn không thể hoàn tác hành động này.",
"common.catalog": "Danh mục",
"common.close": "Đóng",
@@ -427,12 +436,15 @@
"common.delete": "Xóa",
"common.delete-resource": "Delete {{type}}",
"common.deleted": "Đã xóa",
+ "common.deploying": "Đang triển khai",
"common.detail": "Detail",
"common.detailed-guide": "Hướng dẫn chi tiết",
"common.edit": "Chỉnh sửa",
"common.edited": "edited",
"common.environment": "Môi trường",
"common.import": "Nhập",
+ "common.in-progress": "Đang thực hiện",
+ "common.in-review": "Đang xem xét",
"common.issue": "Issue",
"common.key": "Khóa",
"common.labels": "Nhãn",
@@ -457,12 +469,14 @@
"common.remaining": "còn lại",
"common.remove": "Xóa",
"common.removed": "LOẠI BỎ",
+ "common.reopen": "Mở lại",
"common.restore": "Khôi phục",
"common.retry": "Thử lại",
"common.role.self": "Vai trò",
"common.rollout": "Triển khai",
"common.save": "Lưu",
"common.sensitive-placeholder": "Nhạy cảm - Chỉ ghi",
+ "common.show-less": "Thu gọn",
"common.show-more": "Hiển thị thêm",
"common.skip": "Bỏ qua",
"common.success": "Thành công",
@@ -1339,6 +1353,8 @@
"upload-sql": "Upload SQL",
"waiting-approval": "Đang chờ phê duyệt"
},
+ "issue.action-anyway": "{{action}} bằng mọi cách",
+ "issue.checks-warning-hint": "Một số kiểm tra chưa đạt. Chỉ tiếp tục nếu đó là điều đã được dự kiến.",
"issue.comment-editor.nothing-to-preview": "Nothing to preview",
"issue.comment-editor.preview": "Preview",
"issue.comment-editor.toolbar.bold": "Insert bold text",
@@ -1347,6 +1363,7 @@
"issue.comment-editor.toolbar.header": "Insert heading text",
"issue.comment-editor.toolbar.link": "Insert a link",
"issue.comment-editor.write": "Write",
+ "issue.create-rollout": "Tạo rollout",
"issue.data-export.format": "Định dạng",
"issue.data-export.limits": "Giới hạn",
"issue.data-export.options": "Tùy chọn",
@@ -1357,6 +1374,7 @@
"issue.review.self": "Review",
"issue.statement-from-sheet-warning": "This statement is loaded from a large sheet. Preview may be truncated.",
"issue.task-run.logs": "Nhật ký",
+ "issue.task-run.session": "Phiên",
"issue.transaction-mode.label": "Chế độ giao dịch",
"issue.upload-sql-file-max-size-exceeded": "Vượt quá kích thước tệp tối đa ({size}).",
"label": {
@@ -1416,39 +1434,80 @@
"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"
},
"navigator": {
+ "changes": "Thay đổi",
+ "deploy": "Triển khai",
"review": "Xem xét"
},
"new-plan": "Kế hoạch mới",
"plans": "Kế hoạch",
+ "sidebar": {
+ "created-by-at": "Tạo bởi {{user}} · {{time}}",
+ "future-sections-hint": "Sau khi gửi sẽ hiển thị review, nhãn và thông tin triển khai"
+ },
"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.",
"targets": {
"title": "Mục tiêu"
}
},
- "plan.checks.failed-to-run": "Không thể chạy các kiểm tra của kế hoạch",
+ "plan.add-spec": "Thêm thay đổi",
+ "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ả nào khớp với bộ lọc",
+ "plan.checks.no-results-match-filters": "Không có kết quả khớp với bộ lọc",
"plan.checks.started": "Đã bắt đầu kiểm tra kế hoạch",
+ "plan.description.placeholder": "Thêm mô tả",
+ "plan.ghost.requirements-not-met": "Các cơ sở dữ liệu sau không đáp ứng yêu cầu Ghost: {{databases}}",
"plan.go-to-plan-page": "Đi tới trang kế hoạch",
"plan.isolation-level.read-committed": "Đọc đã cam kết",
"plan.isolation-level.read-uncommitted": "Đọc chưa cam kết",
"plan.isolation-level.repeatable-read": "Đọc lặp lại",
"plan.isolation-level.self": "Mức Độ Cô Lập",
"plan.isolation-level.serializable": "Tuần tự hóa",
+ "plan.labels-required-for-review": "Cần có nhãn trước khi review",
"plan.navigator.checks": "Kiểm tra",
"plan.navigator.statement-empty": "Câu lệnh đang trống",
+ "plan.options.no-options-available": "Không có tùy chọn nào khả dụng",
"plan.options.self": "Tùy chọn",
"plan.overview.no-checks": "Không có kiểm tra",
+ "plan.phase.create-rollout-action": "Tạo rollout thủ công",
+ "plan.phase.deploy-approval-must-complete": "Luồng phê duyệt phải hoàn tất.",
+ "plan.phase.deploy-approval-optional": "Có thể bỏ qua luồng phê duyệt theo cấu hình dự án hiện tại.",
+ "plan.phase.deploy-approval-pending": "Hoàn tất luồng phê duyệt trước khi rollout có thể tiếp tục tự động.",
+ "plan.phase.deploy-approval-ready": "Phê duyệt cho kế hoạch này đã hoàn tất.",
+ "plan.phase.deploy-checks-blocked": "Các kiểm tra lỗi đang chặn việc tạo rollout tự động.",
+ "plan.phase.deploy-checks-must-pass": "Các kiểm tra phải đạt.",
+ "plan.phase.deploy-checks-optional": "Các kiểm tra lỗi sẽ không chặn rollout thủ công trong dự án này.",
+ "plan.phase.deploy-checks-ready": "Các kiểm tra đã sẵn sàng để tạo rollout tự động.",
+ "plan.phase.deploy-checks-running": "Hãy chờ các kiểm tra đang chạy hoàn tất trước khi rollout tự động có thể tiếp tục.",
+ "plan.phase.deploy-description": "Bytebase sẽ tự động tạo rollout khi tất cả kiểm tra đều đạt và issue đã được phê duyệt.",
+ "plan.phase.deploy-manual-create-description": "Dựa trên cài đặt dự án hiện tại, bạn cũng có thể tạo rollout thủ công.",
+ "plan.phase.deploy-manual-create-description-readonly": "Người dùng có quyền Create Rollout có thể tạo rollout thủ công.",
+ "plan.phase.hide-details": "Ẩn chi tiết",
+ "plan.phase.review-description": "Gửi để xem xét để tiếp tục",
+ "plan.phase.show-details": "Hiển thị chi tiết",
+ "plan.pre-backup.requirements-not-met": "Các cơ sở dữ liệu sau không đáp ứng yêu cầu sao lưu trước: {{databases}}",
"plan.ready-for-review": "Sẵn sàng để xem xét",
"plan.run": "Kiểm tra lại",
"plan.select-isolation-level": "Chọn mức độ cô lập",
+ "plan.select-targets": "Chọn mục tiêu",
"plan.spec.change": "Thay đổi",
"plan.spec.type.database-change": "Thay đổi cơ sở dữ liệu",
+ "plan.state.close-confirm": "Đóng kế hoạch này?",
+ "plan.state.reopen-confirm": "Mở lại kế hoạch này?",
+ "plan.summary.last-approved-by": "Phê duyệt gần nhất bởi {{name}}",
+ "plan.summary.n-changes": "{{n}} thay đổi",
+ "plan.summary.n-database-groups": "{{n}} nhóm cơ sở dữ liệu",
+ "plan.summary.n-databases": "{{n}} cơ sở dữ liệu",
+ "plan.summary.n-error": "{{n}} lỗi",
+ "plan.summary.n-of-m-approved": "{{n}} trên {{m}} đã được phê duyệt",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} tác vụ",
+ "plan.summary.n-passed": "{{n}} đã vượt qua",
+ "plan.summary.n-warning": "{{n}} cảnh báo",
"plan.targets.no-targets-found": "Không tìm thấy mục tiêu",
"plan.targets.non-env-warning.one": "{{count}} cơ sở dữ liệu sẽ bị loại khỏi rollout vì không có môi trường hiệu lực:",
"plan.targets.non-env-warning.other": "{{count}} cơ sở dữ liệu sẽ bị loại khỏi rollout vì không có môi trường hiệu lực:",
"plan.targets.title": "Mục tiêu",
"plan.targets.view-all": "Xem tất cả ({{count}})",
+ "plan.view-discussion": "Xem thảo luận",
"policy": {
"environment-tier": {
"description": "Môi trường sẽ xuất hiện khác với các môi trường khác.",
@@ -1710,12 +1769,28 @@
}
},
"rollout": {
+ "no-stages": "Không có giai đoạn nào",
+ "no-tasks-created": "Chưa có tác vụ nào được tạo",
+ "pending-tasks-preview": {
+ "action": "Xem trước",
+ "description": "Các tác vụ sau vẫn chưa được tạo.",
+ "no-pending-tasks": "Không có tác vụ chờ tạo",
+ "task-count_one": "{{count}} tác vụ",
+ "task-count_other": "{{count}} tác vụ",
+ "title": "Tác vụ chờ"
+ },
"stage": {
+ "confirm-create": "Xác nhận tạo tác vụ cho giai đoạn này?",
+ "run-stage": "Chạy tác vụ",
"self_one": "Giai đoạn",
"self_other": "Các giai đoạn"
},
"task-execution-errors": "Lỗi thực hiện tác vụ"
},
+ "rollout.bypass-stage-requirements": "Bỏ qua cảnh báo",
+ "rollout.task.no-tasks": "Không có tác vụ trong giai đoạn này",
+ "rollout.task.selected-count": "Đã chọn {{count}} tác vụ",
+ "rollout.task.statement-truncated-hint": "Câu lệnh bị cắt bớt do kích thước lớn.",
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -3282,7 +3357,13 @@
"skipped": "Đã bỏ qua"
}
},
- "task-run.history": "Lịch sử thực thi",
+ "task-run.blocked-sessions": "Phiên bị chặn",
+ "task-run.blocked-sessions-description": "Các phiên bị chặn bởi phiên hiện tại",
+ "task-run.blocking-sessions": "Phiên chặn",
+ "task-run.blocking-sessions-description": "Các phiên đang chặn phiên hiện tại",
+ "task-run.history": "Lịch sử",
+ "task-run.latest": "Mới nhất",
+ "task-run.latest-logs": "Nhật ký mới nhất",
"task-run.log-detail.backing-up": "đang sao lưu...",
"task-run.log-detail.backup-completed": "đã hoàn thành ({{count}} bảng)",
"task-run.log-detail.completed": "Đã hoàn thành",
@@ -3303,18 +3384,32 @@
"task-run.log-viewer.multiple-replicas-notice": "Phát hiện khởi động lại máy chủ trong quá trình thực thi. Nhật ký được nhóm theo bản sao.",
"task-run.log-viewer.replica-n": "Bản sao #{{n}}",
"task-run.log-viewer.summary": "{{sections}} phần · {{entries}} mục",
+ "task-run.no-session-found": "Không tìm thấy phiên",
+ "task-run.rollback.available": "Có {{count}} mục có thể hoàn tác",
+ "task-run.rollback.no-statement-generated": "Không tạo được câu lệnh",
+ "task-run.rollback.preview-statement.description": "Xem lại các câu lệnh hoàn tác đã tạo trước khi tạo kế hoạch hoàn tác.",
"task-run.status.enqueued": "Đang chờ thực thi.",
"task-run.status.enqueued-with-rollout-time": "Đang chờ thực thi sau {{time}}.",
"task-run.status.waiting-max-tasks-per-rollout": "Đang chờ các tác vụ khác hoàn thành. Đã đạt đến giới hạn số lượng tác vụ đang chạy tối đa cho mỗi lần triển khai. Báo cáo gần nhất lúc {{time}}.",
"task.affected-rows": "Hàng bị ảnh hưởng",
- "task.check-type.affected-rows.description": "Estimated by statistical information.",
- "task.check-type.affected-rows.self": "Affected rows",
+ "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",
+ "task.no-selectable-tasks": "Không có tác vụ nào có thể chọn",
+ "task.no-skippable-tasks": "Không có nhiệm vụ nào có thể bỏ qua",
+ "task.no-tasks-selected": "Không có nhiệm vụ nào được chọn",
"task.online-migration.self": "Di chuyển trực tuyến",
+ "task.only-showing-latest-n-runs": "Chỉ hiển thị {{n}} lần chạy gần nhất",
"task.prior-backup": "Sao lưu trước",
+ "task.run-history": "Lịch sử chạy",
+ "task.scheduled-time": "Thời gian đã lên lịch",
+ "task.select-task": "Chọn tác vụ",
"two-factor": {
"description": "Xác thực hai yếu tố cung cấp một lớp bảo mật bổ sung cho các tài khoản thành viên. Khi đăng nhập, bạn sẽ được yêu cầu nhập mã bảo mật do Ứng dụng xác thực của bạn tạo.",
"disable": {
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 37a0415dd0..975c48c443 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -210,6 +210,7 @@
"archive-resource": "归档{{type}}",
"archived": "已归档",
"back": "返回",
+ "bypassed": "已绕过",
"cancel": "取消",
"cannot-undo-this-action": "这个操作无法撤销",
"changelog": "变更历史",
@@ -249,10 +250,12 @@
"deny": "拒绝",
"description": "描述",
"deselect-all": "Deselect all",
+ "detail": "详情",
"detailed-guide": "详细指南",
"disable": "禁用",
"discard-changes": "取消修改",
"dismiss": "关闭",
+ "done": "完成",
"download": "下载",
"draft": "草稿",
"duration": "Duration",
@@ -309,6 +312,7 @@
"name": "名称",
"next": "下一步",
"no-data": "无数据",
+ "not-started": "未开始",
"ok": "OK",
"operations": "操作",
"optional": "Optional",
@@ -323,6 +327,7 @@
"projects": "项目",
"read-only": "只读",
"reason": "理由",
+ "refresh": "刷新",
"regenerate": "重新生成",
"reject": "驳回",
"rejected": "已拒绝",
@@ -343,12 +348,14 @@
"self": "角色"
},
"rollback": "回滚",
+ "rollout": "部署",
"rows": {
"n-rows": "{{n}} 行",
"self": "行"
},
"rows-per-page": "每页行数",
"run": "Run",
+ "running": "进行中",
"save": "保存",
"schema": "模式",
"scope": "范围",
@@ -405,9 +412,11 @@
"common.add": "添加",
"common.admin": "管理员",
"common.all": "全部",
+ "common.and": "和",
"common.archive": "归档",
"common.archived": "已归档",
"common.cancel": "取消",
+ "common.canceled": "已取消",
"common.cannot-undo-this-action": "这个操作无法撤销",
"common.catalog": "Catalog",
"common.close": "关闭",
@@ -427,13 +436,16 @@
"common.delete": "删除",
"common.delete-resource": "删除{{type}}",
"common.deleted": "已删除",
+ "common.deploying": "部署中",
"common.detail": "Detail",
"common.detailed-guide": "详细指南",
"common.edit": "编辑",
"common.edited": "edited",
"common.environment": "环境",
"common.import": "导入",
- "common.issue": "Issue",
+ "common.in-progress": "进行中",
+ "common.in-review": "审批中",
+ "common.issue": "工单",
"common.key": "键",
"common.labels": "标签",
"common.learn-more": "了解更多",
@@ -457,12 +469,14 @@
"common.remaining": "剩余",
"common.remove": "删除",
"common.removed": "已移除",
+ "common.reopen": "重新打开",
"common.restore": "恢复",
"common.retry": "重试",
"common.role.self": "角色",
"common.rollout": "发布",
"common.save": "保存",
"common.sensitive-placeholder": "敏感数据 - 仅写入",
+ "common.show-less": "收起",
"common.show-more": "显示更多",
"common.skip": "跳过",
"common.success": "成功",
@@ -1339,6 +1353,8 @@
"upload-sql": "上传 SQL",
"waiting-approval": "等待审批"
},
+ "issue.action-anyway": "仍要{{action}}",
+ "issue.checks-warning-hint": "部分检查未通过。仅在符合预期时继续。",
"issue.comment-editor.nothing-to-preview": "暂无预览",
"issue.comment-editor.preview": "预览",
"issue.comment-editor.toolbar.bold": "插入粗体文本",
@@ -1347,6 +1363,7 @@
"issue.comment-editor.toolbar.header": "插入标题",
"issue.comment-editor.toolbar.link": "插入链接",
"issue.comment-editor.write": "编辑",
+ "issue.create-rollout": "创建发布",
"issue.data-export.format": "格式",
"issue.data-export.limits": "限制",
"issue.data-export.options": "选项",
@@ -1357,6 +1374,7 @@
"issue.review.self": "评审",
"issue.statement-from-sheet-warning": "该 SQL 来自较大的 Sheet,预览内容可能已截断。",
"issue.task-run.logs": "日志",
+ "issue.task-run.session": "会话",
"issue.transaction-mode.label": "事务模式",
"issue.upload-sql-file-max-size-exceeded": "上传文件大小不能超过 {size}。",
"label": {
@@ -1416,39 +1434,80 @@
"save-changes-before-continuing": "请保存或取消更改,然后再继续"
},
"navigator": {
+ "changes": "变更项",
+ "deploy": "部署",
"review": "审批"
},
"new-plan": "创建变更计划",
"plans": "变更计划",
+ "sidebar": {
+ "created-by-at": "由 {{user}} 创建 · {{time}}",
+ "future-sections-hint": "提交后会显示审批、标签和部署信息"
+ },
"subtitle": "草拟数据库变更并运行预检查,然后创建工单以请求审批。",
"targets": {
"title": "目标库"
}
},
- "plan.checks.failed-to-run": "执行计划检查失败",
- "plan.checks.no-check-results": "没有检查结果",
- "plan.checks.no-results-match-filters": "没有结果匹配当前筛选条件",
- "plan.checks.started": "计划检查已启动",
+ "plan.add-spec": "添加变更",
+ "plan.checks.failed-to-run": "运行计划检查失败",
+ "plan.checks.no-check-results": "暂无检查结果",
+ "plan.checks.no-results-match-filters": "没有符合筛选条件的结果",
+ "plan.checks.started": "已开始计划检查",
+ "plan.description.placeholder": "添加描述",
+ "plan.ghost.requirements-not-met": "以下数据库不满足 Ghost 要求:{{databases}}",
"plan.go-to-plan-page": "前往计划页面",
"plan.isolation-level.read-committed": "已提交读",
"plan.isolation-level.read-uncommitted": "未提交读",
"plan.isolation-level.repeatable-read": "可重复读",
"plan.isolation-level.self": "隔离级别",
"plan.isolation-level.serializable": "串行化",
+ "plan.labels-required-for-review": "提交评审前必须设置标签",
"plan.navigator.checks": "检查",
"plan.navigator.statement-empty": "语句为空",
+ "plan.options.no-options-available": "暂无可配置项",
"plan.options.self": "配置项",
"plan.overview.no-checks": "没有检查",
+ "plan.phase.create-rollout-action": "手动创建发布",
+ "plan.phase.deploy-approval-must-complete": "审批流必须完成。",
+ "plan.phase.deploy-approval-optional": "根据当前项目设置,审批流可以被绕过。",
+ "plan.phase.deploy-approval-pending": "在系统自动创建发布前,需要先完成审批流。",
+ "plan.phase.deploy-approval-ready": "该计划的审批已完成。",
+ "plan.phase.deploy-checks-blocked": "未通过的检查正在阻止系统自动创建发布。",
+ "plan.phase.deploy-checks-must-pass": "检查必须通过。",
+ "plan.phase.deploy-checks-optional": "在当前项目中,未通过的检查不会阻止手动创建发布。",
+ "plan.phase.deploy-checks-ready": "检查结果已满足系统自动创建发布的条件。",
+ "plan.phase.deploy-checks-running": "请等待运行中的检查完成,系统才能继续自动创建发布。",
+ "plan.phase.deploy-description": "当所有检查都通过且工单审批完成后,Bytebase 会自动创建发布。",
+ "plan.phase.deploy-manual-create-description": "根据当前项目设置,你也可以手动创建发布。",
+ "plan.phase.deploy-manual-create-description-readonly": "拥有“创建发布”权限的用户可以手动创建发布。",
+ "plan.phase.hide-details": "隐藏详情",
+ "plan.phase.review-description": "提交审批以继续",
+ "plan.phase.show-details": "显示详情",
+ "plan.pre-backup.requirements-not-met": "以下数据库不满足预备份要求:{{databases}}",
"plan.ready-for-review": "准备提交评审",
"plan.run": "重新检查",
"plan.select-isolation-level": "选择隔离级别",
+ "plan.select-targets": "选择目标",
"plan.spec.change": "变更",
"plan.spec.type.database-change": "数据库变更",
+ "plan.state.close-confirm": "确认关闭这个计划?",
+ "plan.state.reopen-confirm": "确认重新打开这个计划?",
+ "plan.summary.last-approved-by": "最后由 {{name}} 审批",
+ "plan.summary.n-changes": "{{n}} 个变更",
+ "plan.summary.n-database-groups": "{{n}} 个数据库组",
+ "plan.summary.n-databases": "{{n}} 个数据库",
+ "plan.summary.n-error": "{{n}} 错误",
+ "plan.summary.n-of-m-approved": "{{n}}/{{m}} 已审批",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} 任务",
+ "plan.summary.n-passed": "{{n}} 通过",
+ "plan.summary.n-warning": "{{n}} 警告",
"plan.targets.no-targets-found": "未找到目标",
"plan.targets.non-env-warning.one": "{{count}} 个数据库因为没有生效环境,将不会进入发布:",
"plan.targets.non-env-warning.other": "{{count}} 个数据库因为没有生效环境,将不会进入发布:",
"plan.targets.title": "目标",
"plan.targets.view-all": "查看全部 ({{count}})",
+ "plan.view-discussion": "查看讨论",
"policy": {
"environment-tier": {
"description": "使该环境在显示上不同于其他环境。",
@@ -1710,12 +1769,28 @@
}
},
"rollout": {
+ "no-stages": "暂无阶段",
+ "no-tasks-created": "尚未创建任务",
+ "pending-tasks-preview": {
+ "action": "预览",
+ "description": "以下任务尚未创建。",
+ "no-pending-tasks": "没有待创建任务",
+ "task-count_one": "{{count}} 个任务",
+ "task-count_other": "{{count}} 个任务",
+ "title": "待创建任务"
+ },
"stage": {
+ "confirm-create": "确认创建此阶段的任务?",
+ "run-stage": "运行任务",
"self_one": "阶段",
"self_other": "阶段"
},
"task-execution-errors": "任务执行错误"
},
+ "rollout.bypass-stage-requirements": "绕过警告",
+ "rollout.task.no-tasks": "此阶段没有任务",
+ "rollout.task.selected-count": "已选择 {{count}} 个任务",
+ "rollout.task.statement-truncated-hint": "由于语句过长,已被截断。",
"schema-editor": {
"actions": {
"add-column": "Add column",
@@ -3282,7 +3357,13 @@
"skipped": "已跳过"
}
},
- "task-run.history": "执行历史",
+ "task-run.blocked-sessions": "被阻塞会话",
+ "task-run.blocked-sessions-description": "当前会话阻塞了以下会话",
+ "task-run.blocking-sessions": "阻塞会话",
+ "task-run.blocking-sessions-description": "当前会话被以下会话阻塞",
+ "task-run.history": "历史",
+ "task-run.latest": "最新",
+ "task-run.latest-logs": "最新日志",
"task-run.log-detail.backing-up": "备份中...",
"task-run.log-detail.backup-completed": "已完成({{count}} 个表)",
"task-run.log-detail.completed": "已完成",
@@ -3303,6 +3384,10 @@
"task-run.log-viewer.multiple-replicas-notice": "检测到执行期间服务重启,日志按副本分组显示。",
"task-run.log-viewer.replica-n": "副本 #{{n}}",
"task-run.log-viewer.summary": "{{sections}} 个分组 · {{entries}} 条记录",
+ "task-run.no-session-found": "未找到会话",
+ "task-run.rollback.available": "有 {{count}} 个可回滚任务",
+ "task-run.rollback.no-statement-generated": "未生成语句",
+ "task-run.rollback.preview-statement.description": "在创建回滚计划前先检查生成的回滚语句。",
"task-run.status.enqueued": "等待执行。",
"task-run.status.enqueued-with-rollout-time": "等待执行,{{time}} 后执行。",
"task-run.status.waiting-max-tasks-per-rollout": "正在等待其他任务完成。已达到每次发布的最大运行任务数限制。上次报告时间:{{time}}。",
@@ -3313,8 +3398,18 @@
"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": "没有可运行的任务",
+ "task.no-selectable-tasks": "没有可选择的任务",
+ "task.no-skippable-tasks": "没有可跳过的任务",
+ "task.no-tasks-selected": "未选择任何任务",
"task.online-migration.self": "在线大表变更",
+ "task.only-showing-latest-n-runs": "仅显示最近 {{n}} 条记录",
"task.prior-backup": "预备份受影响数据",
+ "task.run-history": "执行历史",
+ "task.scheduled-time": "计划执行时间",
+ "task.select-task": "选择任务",
"two-factor": {
"description": "双重认证为系统成员提供了一个额外的安全层。在登录时,用户需要输入由认证器应用程序生成的安全代码。",
"disable": {
diff --git a/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx
new file mode 100644
index 0000000000..c219b2f129
--- /dev/null
+++ b/frontend/src/react/pages/project/ProjectPlanDetailPage.tsx
@@ -0,0 +1,600 @@
+import { Code2, Loader2, MessageSquareMore, Rocket, X } from "lucide-react";
+import type { CSSProperties, ReactNode } from "react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogFooter,
+ AlertDialogTitle,
+} from "@/react/components/ui/alert-dialog";
+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 { cn } from "@/react/lib/utils";
+import {
+ Issue_ApprovalStatus,
+ IssueStatus,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { DeployBranch } from "./plan-detail/components/deploy/DeployBranch";
+import { DeployTaskDetailPanel } from "./plan-detail/components/deploy/DeployTaskDetailPanel";
+import { PlanDetailReviewApprovalFlow } from "./plan-detail/components/PlanDetailApprovalFlow";
+import { PlanDetailChangesBranch } from "./plan-detail/components/PlanDetailChangesBranch";
+import { PlanDetailDeployFuture } from "./plan-detail/components/PlanDetailDeployFuture";
+import { PlanDetailHeader } from "./plan-detail/components/PlanDetailHeader";
+import { PlanDetailMetadataSidebar } from "./plan-detail/components/PlanDetailMetadataSidebar";
+import {
+ PlanDetailProvider,
+ usePlanDetailContext,
+} from "./plan-detail/context/PlanDetailContext";
+import {
+ SIDEBAR_WIDTH_NARROW_PX,
+ usePlanDetailPage,
+ WIDE_SIDEBAR_BREAKPOINT_PX,
+} from "./plan-detail/hooks/usePlanDetailPage";
+import {
+ buildChangesSummary,
+ buildDeploySummary,
+ buildReviewSummary,
+} from "./plan-detail/utils/phaseSummary";
+
+export function ProjectPlanDetailPage({
+ projectId,
+ planId,
+ routeName,
+ routeQuery,
+ specId,
+}: {
+ projectId: string;
+ planId: string;
+ routeName?: string;
+ routeQuery?: Record<string, unknown>;
+ specId?: string;
+}) {
+ const { t } = useTranslation();
+ const [pageHost, setPageHost] = useState<HTMLDivElement | null>(null);
+ const [selectedSpecId, setSelectedSpecId] = useState(specId ?? "");
+ const page = usePlanDetailPage({
+ projectId,
+ planId,
+ routeName,
+ routeQuery,
+ specId,
+ pageHost,
+ });
+ const selectedTask = useMemo(() => {
+ if (!page.routeTaskId || !page.rollout) {
+ return undefined;
+ }
+ for (const stage of page.rollout.stages) {
+ const task = stage.tasks.find((item) =>
+ item.name.endsWith(`/${page.routeTaskId}`)
+ );
+ if (task) {
+ return task;
+ }
+ }
+ return undefined;
+ }, [page.rollout, page.routeTaskId]);
+ const supportsInlineDetailPanel =
+ page.sidebarMode === "DESKTOP" &&
+ page.containerWidth >= WIDE_SIDEBAR_BREAKPOINT_PX;
+ const showDesktopSidebar = page.sidebarMode === "DESKTOP" && !selectedTask;
+ const showDesktopDetail = supportsInlineDetailPanel && !!selectedTask;
+ const showTaskDrawer =
+ !!selectedTask && !showDesktopDetail && page.sidebarMode !== "NONE";
+ const showMobileSidebar = page.sidebarMode === "MOBILE";
+
+ const desktopSidebarStyle = useMemo(
+ () => ({
+ width: `${page.desktopSidebarWidth || SIDEBAR_WIDTH_NARROW_PX}px`,
+ }),
+ [page.desktopSidebarWidth]
+ );
+ const desktopLayoutStyle = useMemo<CSSProperties>(() => {
+ const baseStyle: CSSProperties = {
+ minHeight: "calc(100vh - 4rem)",
+ };
+
+ if (page.sidebarMode !== "DESKTOP") {
+ return baseStyle;
+ }
+
+ if (showDesktopDetail) {
+ return {
+ ...baseStyle,
+ gridTemplateColumns: "minmax(0, 1fr) minmax(0, 50%)",
+ };
+ }
+
+ if (showDesktopSidebar) {
+ return {
+ ...baseStyle,
+ gridTemplateColumns: `minmax(0, 1fr) ${page.desktopSidebarWidth || SIDEBAR_WIDTH_NARROW_PX}px`,
+ };
+ }
+
+ return baseStyle;
+ }, [
+ page.desktopSidebarWidth,
+ page.sidebarMode,
+ showDesktopDetail,
+ showDesktopSidebar,
+ ]);
+ const phaseConfigs = useMemo(() => {
+ const hasIssue = !!page.issue;
+ const hasRollout = !!page.rollout;
+ const isIssueClosed =
+ page.issue?.status === IssueStatus.CANCELED ||
+ page.issue?.status === IssueStatus.DONE;
+ const allTasks = page.rollout?.stages.flatMap((stage) => stage.tasks) ?? [];
+ const allDone =
+ allTasks.length > 0 &&
+ allTasks.every(
+ (task) =>
+ task.status === Task_Status.DONE ||
+ task.status === Task_Status.SKIPPED
+ );
+
+ let review: "completed" | "closed" | "active" | "future" = "future";
+ if (hasIssue) {
+ if (page.issue?.status === IssueStatus.CANCELED) {
+ review = "closed";
+ } else {
+ review = hasRollout || isIssueClosed ? "completed" : "active";
+ }
+ }
+
+ const changesStatus: "completed" | "closed" | "active" | "future" =
+ page.isCreating || (!hasIssue && !hasRollout) ? "active" : "completed";
+ const deployStatus: "completed" | "closed" | "active" | "future" =
+ hasRollout ? (allDone ? "completed" : "active") : "future";
+
+ const changesBadge =
+ changesStatus === "active" && !page.isCreating
+ ? { label: t("common.draft"), variant: "default" as const }
+ : undefined;
+ const reviewBadge = (() => {
+ if (!page.issue) return undefined;
+ if (page.issue.status === IssueStatus.CANCELED) {
+ return { label: t("common.closed"), variant: "default" as const };
+ }
+ if (review === "future") return undefined;
+ if (
+ review === "completed" &&
+ page.issue.approvalStatus === Issue_ApprovalStatus.PENDING
+ ) {
+ return { label: t("common.bypassed"), variant: "default" as const };
+ }
+ switch (page.issue.approvalStatus) {
+ case Issue_ApprovalStatus.APPROVED:
+ return {
+ label: t("issue.table.approved"),
+ variant: "success" as const,
+ };
+ case Issue_ApprovalStatus.SKIPPED:
+ return { label: t("common.skipped"), variant: "default" as const };
+ case Issue_ApprovalStatus.REJECTED:
+ return { label: t("common.rejected"), variant: "warning" as const };
+ case Issue_ApprovalStatus.PENDING:
+ return {
+ label: t("common.under-review"),
+ variant: "secondary" as const,
+ };
+ default:
+ return undefined;
+ }
+ })();
+ const deployBadge = (() => {
+ if (deployStatus !== "active" || !page.rollout) return undefined;
+ const hasCompletedTasks = allTasks.some(
+ (task) =>
+ task.status === Task_Status.DONE ||
+ task.status === Task_Status.SKIPPED
+ );
+ if (allTasks.some((task) => task.status === Task_Status.FAILED)) {
+ return { label: t("common.failed"), variant: "destructive" as const };
+ }
+ if (
+ allTasks.some(
+ (task) =>
+ task.status === Task_Status.RUNNING ||
+ task.status === Task_Status.PENDING
+ ) ||
+ hasCompletedTasks
+ ) {
+ return {
+ label: t("common.in-progress"),
+ variant: "secondary" as const,
+ };
+ }
+ return { label: t("common.not-started"), variant: "default" as const };
+ })();
+
+ const lineClass = (
+ from: "completed" | "closed" | "active" | "future",
+ to: "completed" | "closed" | "active" | "future"
+ ) => {
+ if (from === "closed" || to === "closed")
+ return "border-l-2 border-dashed border-control-border";
+ if (from === "completed" && to === "completed")
+ return "border-l-2 border-success";
+ if (from === "completed" && to === "active")
+ return "border-l-2 border-success";
+ if (from === "active") return "border-l-2 border-dashed border-accent";
+ return "border-l-2 border-dashed border-control-border";
+ };
+
+ return {
+ changes: {
+ status: changesStatus,
+ badge: changesBadge,
+ lineClass: lineClass(changesStatus, review),
+ },
+ review: {
+ status: review,
+ badge: reviewBadge,
+ lineClass: lineClass(review, deployStatus),
+ },
+ deploy: {
+ status: deployStatus,
+ badge: deployBadge,
+ lineClass: "",
+ },
+ };
+ }, [page.isCreating, page.issue, page.rollout, t]);
+
+ useEffect(() => {
+ if (specId) {
+ setSelectedSpecId(specId);
+ return;
+ }
+ if (!selectedSpecId && page.plan.specs.length > 0) {
+ setSelectedSpecId(page.plan.specs[0].id);
+ }
+ }, [page.plan.specs, selectedSpecId, specId]);
+
+ return (
+ <PlanDetailProvider value={page}>
+ <div
+ ref={setPageHost}
+ className="relative h-full overflow-x-hidden bg-gray-50"
+ >
+ <div
+ className={cn(
+ "flex min-h-full flex-col",
+ page.ready ? "" : "invisible pointer-events-none"
+ )}
+ >
+ <header className="shrink-0 border-b bg-white">
+ <PlanDetailHeader />
+ </header>
+
+ <div
+ className="min-h-0 flex flex-1 flex-col lg:grid"
+ style={desktopLayoutStyle}
+ >
+ <main className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-col gap-y-3 pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
+ <PhaseSection
+ badge={phaseConfigs.changes.badge}
+ expanded={page.activePhases.has("changes")}
+ icon={<Code2 className="h-4 w-4 text-white" />}
+ lineClass={phaseConfigs.changes.lineClass}
+ label={t("plan.navigator.changes")}
+ onSelect={() => page.expandPhase("changes")}
+ status={phaseConfigs.changes.status}
+ onToggle={() => page.togglePhase("changes")}
+ summary={buildChangesSummary(page.plan, t)}
+ >
+ <PlanDetailChangesBranch
+ onSelectedSpecIdChange={setSelectedSpecId}
+ selectedSpecId={selectedSpecId}
+ />
+ </PhaseSection>
+
+ <PhaseSection
+ badge={phaseConfigs.review.badge}
+ expanded={page.activePhases.has("review")}
+ icon={<MessageSquareMore className="h-4 w-4 text-white" />}
+ lineClass={phaseConfigs.review.lineClass}
+ label={t("plan.navigator.review")}
+ onSelect={() => page.expandPhase("review")}
+ status={phaseConfigs.review.status}
+ onToggle={() => page.togglePhase("review")}
+ summary={buildReviewSummary(page.issue, t)}
+ future={
+ <p className="mt-0.5 text-sm text-control-placeholder">
+ {t("plan.phase.review-description")}
+ </p>
+ }
+ >
+ <ReviewBranch />
+ </PhaseSection>
+
+ <PhaseSection
+ badge={phaseConfigs.deploy.badge}
+ expanded={page.activePhases.has("deploy")}
+ icon={<Rocket className="h-4 w-4 text-white" />}
+ isLast
+ label={t("plan.navigator.deploy")}
+ status={phaseConfigs.deploy.status}
+ onSelect={() => page.expandPhase("deploy")}
+ onToggle={() => page.togglePhase("deploy")}
+ summary={buildDeploySummary(page.rollout, t)}
+ future={<PlanDetailDeployFuture />}
+ >
+ <DeployBranch
+ selectedTask={selectedTask}
+ onCloseTaskPanel={page.closeTaskPanel}
+ />
+ </PhaseSection>
+ </div>
+ </main>
+
+ {showDesktopSidebar && (
+ <DesktopColumn tag="aside" style={desktopSidebarStyle}>
+ <div className="p-4">
+ <PlanDetailMetadataSidebar />
+ </div>
+ </DesktopColumn>
+ )}
+
+ {showDesktopDetail && selectedTask && (
+ <DesktopColumn
+ header={
+ <div className="flex items-center justify-between border-b bg-white px-4 py-2">
+ <span className="textinfolabel">{t("common.detail")}</span>
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={page.closeTaskPanel}
+ >
+ <X className="h-4 w-4" />
+ {t("common.close")}
+ </Button>
+ </div>
+ }
+ >
+ <DeployTaskDetailPanel task={selectedTask} />
+ </DesktopColumn>
+ )}
+ </div>
+ </div>
+
+ {!page.ready && (
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-y-3 bg-white">
+ <Loader2 className="h-8 w-8 animate-spin text-accent" />
+ <div className="text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ </div>
+ )}
+
+ <Sheet
+ onOpenChange={page.setMobileSidebarOpen}
+ open={showMobileSidebar && page.mobileSidebarOpen}
+ >
+ <SheetContent
+ className="w-[20rem] max-w-[calc(100vw-2rem)]"
+ width="standard"
+ >
+ <SheetHeader>
+ <SheetTitle>{t("common.detail")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="p-4">
+ <PlanDetailMetadataSidebar />
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+
+ <Sheet
+ onOpenChange={(open) => {
+ if (!open) {
+ page.closeTaskPanel();
+ }
+ }}
+ open={showTaskDrawer}
+ >
+ <SheetContent
+ className="w-[40rem] max-w-[calc(100vw-2rem)]"
+ width="wide"
+ >
+ <SheetHeader>
+ <SheetTitle>{t("common.detail")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="px-0 py-0">
+ {selectedTask ? (
+ <DeployTaskDetailPanel task={selectedTask} />
+ ) : null}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+
+ <AlertDialog
+ open={page.pendingLeaveConfirm}
+ onOpenChange={(open) => {
+ if (!open) {
+ page.resolveLeaveConfirm(false);
+ }
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogTitle>
+ {t("common.leave-without-saving")}
+ </AlertDialogTitle>
+ <AlertDialogFooter>
+ <Button
+ variant="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>
+ </PlanDetailProvider>
+ );
+}
+
+function PhaseSection({
+ badge,
+ label,
+ lineClass,
+ icon,
+ future,
+ isLast = false,
+ expanded,
+ status,
+ summary,
+ children,
+ onToggle,
+ onSelect,
+}: {
+ badge?: {
+ label: string;
+ variant: "default" | "secondary" | "warning" | "success" | "destructive";
+ };
+ label: string;
+ lineClass?: string;
+ icon: ReactNode;
+ future?: ReactNode;
+ isLast?: boolean;
+ expanded: boolean;
+ status: "completed" | "closed" | "active" | "future";
+ summary?: string;
+ children: ReactNode;
+ onToggle: () => void;
+ onSelect: () => void;
+}) {
+ const { t } = useTranslation();
+ const dotClass =
+ status === "completed"
+ ? "bg-success"
+ : status === "closed"
+ ? "bg-control-placeholder"
+ : status === "active"
+ ? "bg-accent ring-[3px] ring-accent/20"
+ : "border-2 border-dashed border-control-border";
+
+ return (
+ <div className={cn("flex", isLast && "mb-48")}>
+ <div className="flex w-10 shrink-0 flex-col items-center md:w-16">
+ <div
+ className="mt-0.5 flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center md:h-7 md:w-7"
+ onClick={onSelect}
+ >
+ <div
+ className={cn(
+ "flex h-5 w-5 items-center justify-center rounded-full md:h-7 md:w-7",
+ dotClass
+ )}
+ >
+ {status !== "future" ? icon : null}
+ </div>
+ </div>
+ {!isLast && <div className={cn("flex-1 min-h-[16px]", lineClass)} />}
+ </div>
+
+ <div className="min-w-0 flex-1 pb-4">
+ {status === "future" ? (
+ <div className="py-0.5">
+ <span className="textlabel uppercase text-control-placeholder">
+ {label}
+ </span>
+ {future ?? (
+ <div className="mt-0.5 text-sm text-control-placeholder">
+ {summary}
+ </div>
+ )}
+ </div>
+ ) : !expanded ? (
+ <div className="cursor-pointer py-0.5" onClick={onToggle}>
+ <div className="flex items-center gap-2">
+ <span className="textlabel uppercase">{label}</span>
+ {badge && <Badge variant={badge.variant}>{badge.label}</Badge>}
+ <div className="flex-1" />
+ <span className="shrink-0 text-[11px] text-control-placeholder">
+ {summary ? t("plan.phase.show-details") : ""}
+ </span>
+ </div>
+ {summary && (
+ <div className="mt-0.5 text-sm text-control">{summary}</div>
+ )}
+ </div>
+ ) : (
+ <div className="flex flex-col">
+ <div
+ className="flex items-center gap-2 py-0.5 cursor-pointer"
+ onClick={onToggle}
+ >
+ <span className="textlabel uppercase text-accent">{label}</span>
+ {badge && <Badge variant={badge.variant}>{badge.label}</Badge>}
+ <div className="flex-1" />
+ <span className="shrink-0 text-[11px] text-control-placeholder">
+ {t("plan.phase.hide-details")}
+ </span>
+ </div>
+ <div className="mt-1 overflow-hidden rounded-lg border bg-white">
+ {children}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function ReviewBranch() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+
+ if (!page.issue) {
+ return (
+ <div className="p-4 text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ <PlanDetailReviewApprovalFlow />
+ </div>
+ );
+}
+
+function DesktopColumn({
+ children,
+ header,
+ style,
+ tag: Tag = "div",
+}: {
+ children: ReactNode;
+ header?: ReactNode;
+ style?: CSSProperties;
+ tag?: "aside" | "div";
+}) {
+ return (
+ <Tag className="min-w-0 border-l bg-white" style={style}>
+ <div className="sticky top-0 flex max-h-[calc(100vh-4rem)] min-h-[calc(100vh-4rem)] flex-col overflow-hidden">
+ {header ? <div className="shrink-0">{header}</div> : null}
+ <div className="min-h-0 flex-1 overflow-y-auto">{children}</div>
+ </div>
+ </Tag>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx
new file mode 100644
index 0000000000..a7d0cdb63d
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx
@@ -0,0 +1,351 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ Issue_ApprovalStatus,
+ Issue_Approver_Status,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { PlanDetailProvider } from "../context/PlanDetailContext";
+import type { PlanDetailPageState } from "../hooks/usePlanDetailPage";
+import { PlanDetailReviewApprovalFlow } from "./PlanDetailApprovalFlow";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ comments: [] as Array<{
+ comment?: string;
+ creator: string;
+ event?: { case?: string };
+ }>,
+ getIssueComments: vi.fn(() => mocks.comments),
+ listIssueComments: vi.fn(async () => ({ issueComments: mocks.comments })),
+ requestIssue: vi.fn(async () => ({})),
+ routerPush: vi.fn(),
+ useTranslation: vi.fn(() => ({
+ t: (key: string) => key,
+ })),
+ getOrFetchProjectByName: vi.fn(async () => ({})),
+ getOrFetchProjectIamPolicy: vi.fn(async () => ({})),
+ getProjectByName: vi.fn(() => ({ allowSelfApproval: false })),
+ getProjectIamPolicy: vi.fn(() => ({ bindings: [] })),
+ batchGetOrFetchGroups: vi.fn(async () => []),
+ batchGetOrFetchUsers: vi.fn(async () => []),
+ getOrFetchUserByIdentifier: vi.fn(async () => undefined),
+ pushNotification: vi.fn(),
+ currentUserStore: {
+ value: { email: "[email protected]", name: "users/me" },
+ },
+ groupStore: {
+ batchGetOrFetchGroups: vi.fn(async () => []),
+ },
+ projectIamPolicyStore: {
+ getOrFetchProjectIamPolicy: vi.fn(async () => ({})),
+ getProjectIamPolicy: vi.fn(() => ({ bindings: [] })),
+ },
+ projectStore: {
+ getOrFetchProjectByName: vi.fn(async () => ({})),
+ getProjectByName: vi.fn(() => ({ allowSelfApproval: false })),
+ },
+ roleStore: {
+ roleList: [
+ {
+ name: "roles/PROJECT_OWNER",
+ title: "Project Owner",
+ },
+ ],
+ },
+ workspaceStore: {
+ roleMapToUsers: new Map(),
+ },
+ userStore: {
+ batchGetOrFetchUsers: vi.fn(async () => []),
+ getOrFetchUserByIdentifier: vi.fn(async () => undefined),
+ },
+ issueCommentStore: {
+ getIssueComments: vi.fn(() => mocks.comments),
+ listIssueComments: vi.fn(async () => ({ issueComments: mocks.comments })),
+ },
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/router", () => ({
+ router: {
+ push: mocks.routerPush,
+ },
+}));
+
+vi.mock("@/react/components/FeatureBadge", () => ({
+ FeatureBadge: () => <span data-testid="feature-badge">feature</span>,
+}));
+
+vi.mock("@/connect", () => ({
+ issueServiceClientConnect: {
+ requestIssue: mocks.requestIssue,
+ },
+}));
+
+vi.mock("@/store", () => ({
+ pushNotification: mocks.pushNotification,
+ useCurrentUserV1: () => mocks.currentUserStore,
+ useGroupStore: () => mocks.groupStore,
+ useProjectIamPolicyStore: () => mocks.projectIamPolicyStore,
+ useProjectV1Store: () => mocks.projectStore,
+ useRoleStore: () => mocks.roleStore,
+ useWorkspaceV1Store: () => mocks.workspaceStore,
+ useUserStore: () => mocks.userStore,
+}));
+
+vi.mock("@/store/modules/v1/common", () => ({
+ projectNamePrefix: "projects/",
+ roleNamePrefix: "roles/",
+ userNamePrefix: "users/",
+}));
+
+vi.mock("@/store/modules/v1/issueComment", () => ({
+ IssueCommentType: {
+ APPROVAL: "APPROVAL",
+ },
+ getIssueCommentType: (comment: { event?: { case?: string } }) =>
+ comment.event?.case === "approval" ? "APPROVAL" : "USER_COMMENT",
+ useIssueCommentStore: () => mocks.issueCommentStore,
+}));
+
+const renderIntoContainer = (element: ReactElement) => {
+ const container = document.createElement("div");
+ const root = createRoot(container);
+
+ return {
+ container,
+ render: () => {
+ act(() => {
+ root.render(element);
+ });
+ },
+ unmount: () =>
+ act(() => {
+ root.unmount();
+ }),
+ };
+};
+
+const makePageState = ({
+ issue,
+ readonly = false,
+}: {
+ issue?: Issue;
+ readonly?: boolean;
+}): PlanDetailPageState =>
+ ({
+ activePhases: new Set(["review"]),
+ closeTaskPanel: vi.fn(),
+ containerWidth: 0,
+ desktopSidebarWidth: 0,
+ expandPhase: vi.fn(),
+ isCreating: false,
+ isEditing: false,
+ isInitializing: false,
+ isRefreshing: false,
+ issue,
+ lastRefreshTime: 0,
+ mobileSidebarOpen: false,
+ pageKey: "projects/p1/plans/1",
+ patchState: vi.fn(),
+ plan: { creator: "users/me", name: "projects/p1/plans/1" },
+ planCheckRuns: [],
+ planId: "1",
+ projectId: "p1",
+ projectTitle: "Project 1",
+ readonly,
+ ready: true,
+ refreshState: vi.fn(async () => undefined),
+ rollout: undefined,
+ routeName: undefined,
+ routePhase: undefined,
+ routeStageId: undefined,
+ routeTaskId: undefined,
+ selectedTaskName: undefined,
+ setEditing: vi.fn(),
+ setMobileSidebarOpen: vi.fn(),
+ sidebarMode: "NONE",
+ specId: undefined,
+ taskRuns: [],
+ togglePhase: vi.fn(),
+ }) as unknown as PlanDetailPageState;
+
+const makeIssue = ({
+ approvalStatus,
+ approvers = [],
+ roles = ["roles/PROJECT_OWNER"],
+ creator = "users/me",
+}: {
+ approvalStatus: Issue_ApprovalStatus;
+ approvers?: Array<Record<string, unknown>>;
+ roles?: string[];
+ creator?: string;
+}): Issue =>
+ ({
+ approvalStatus,
+ approvalTemplate: {
+ description: "Sensitive databases",
+ flow: {
+ roles,
+ },
+ title: "Prod policy",
+ },
+ approvers,
+ creator,
+ name: "projects/p1/issues/123",
+ riskLevel: 2,
+ }) as unknown as Issue;
+
+beforeEach(() => {
+ mocks.comments = [];
+ mocks.issueCommentStore.getIssueComments.mockClear();
+ mocks.issueCommentStore.listIssueComments.mockClear();
+ mocks.requestIssue.mockClear();
+ mocks.routerPush.mockClear();
+ mocks.pushNotification.mockClear();
+ mocks.groupStore.batchGetOrFetchGroups.mockClear();
+ mocks.projectIamPolicyStore.getOrFetchProjectIamPolicy.mockClear();
+ mocks.projectIamPolicyStore.getProjectIamPolicy.mockClear();
+ mocks.projectStore.getOrFetchProjectByName.mockClear();
+ mocks.projectStore.getProjectByName.mockClear();
+ mocks.userStore.batchGetOrFetchUsers.mockClear();
+ mocks.userStore.getOrFetchUserByIdentifier.mockClear();
+});
+
+describe("PlanDetailApprovalFlow", () => {
+ test("renders generating row for checking approval flow", () => {
+ const issue = makeIssue({
+ approvalStatus: Issue_ApprovalStatus.CHECKING,
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <PlanDetailProvider value={makePageState({ issue })}>
+ <PlanDetailReviewApprovalFlow />
+ </PlanDetailProvider>
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ "custom-approval.issue-review.generating-approval-flow"
+ );
+ expect(container.textContent).not.toContain("issue.approval-flow.self");
+ expect(container.textContent).not.toContain("plan.view-discussion");
+
+ unmount();
+ });
+
+ test("renders skip placeholder when approval flow is skipped", () => {
+ const issue = makeIssue({
+ approvalStatus: Issue_ApprovalStatus.SKIPPED,
+ roles: [],
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <PlanDetailProvider value={makePageState({ issue })}>
+ <PlanDetailReviewApprovalFlow />
+ </PlanDetailProvider>
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ "custom-approval.approval-flow.skip"
+ );
+ expect(container.textContent).not.toContain("issue.approval-flow.self");
+
+ unmount();
+ });
+
+ test("renders timeline header and footer link for pending approval", () => {
+ const issue = makeIssue({
+ approvalStatus: Issue_ApprovalStatus.PENDING,
+ approvers: [
+ {
+ principal: "users/approver",
+ status: Issue_Approver_Status.PENDING,
+ },
+ ],
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <PlanDetailProvider value={makePageState({ issue })}>
+ <PlanDetailReviewApprovalFlow />
+ </PlanDetailProvider>
+ );
+
+ render();
+
+ expect(container.textContent).toContain("issue.approval-flow.self");
+ expect(container.textContent).toContain("common.under-review");
+ expect(container.textContent).toContain(
+ "common.issue #123 · plan.view-discussion"
+ );
+
+ const footerButton = [...container.querySelectorAll("button")].find(
+ (button) =>
+ button.textContent?.includes("common.issue #123 · plan.view-discussion")
+ );
+ expect(footerButton).toBeTruthy();
+
+ act(() => {
+ footerButton?.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+
+ expect(mocks.routerPush).toHaveBeenCalledWith(
+ expect.objectContaining({
+ params: {
+ issueId: "123",
+ projectId: "p1",
+ },
+ })
+ );
+
+ unmount();
+ });
+
+ test("renders rejection banner and re-request action when allowed", () => {
+ mocks.comments = [
+ {
+ comment: "Needs more work",
+ creator: "[email protected]",
+ event: { case: "approval" },
+ },
+ ];
+ const issue = makeIssue({
+ approvalStatus: Issue_ApprovalStatus.REJECTED,
+ approvers: [
+ {
+ principal: "users/approver",
+ status: Issue_Approver_Status.REJECTED,
+ },
+ ],
+ creator: "users/[email protected]",
+ });
+ const { container, render, unmount } = renderIntoContainer(
+ <PlanDetailProvider value={makePageState({ issue })}>
+ <PlanDetailReviewApprovalFlow />
+ </PlanDetailProvider>
+ );
+
+ render();
+
+ expect(container.textContent).toContain(
+ "custom-approval.issue-review.rejected-by [email protected]"
+ );
+ expect(container.textContent).toContain("Needs more work");
+ expect(container.textContent).toContain(
+ "custom-approval.issue-review.re-request-review"
+ );
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
new file mode 100644
index 0000000000..028969f663
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx
@@ -0,0 +1,846 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ RotateCcw,
+ ShieldAlert,
+ ShieldCheck,
+ ThumbsUp,
+ User,
+ X,
+} from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect } from "@/connect";
+import { FeatureBadge } from "@/react/components/FeatureBadge";
+import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
+import {
+ pushNotification,
+ useCurrentUserV1,
+ useGroupStore,
+ useProjectIamPolicyStore,
+ useProjectV1Store,
+ useUserStore,
+} from "@/store";
+import { projectNamePrefix, userNamePrefix } from "@/store/modules/v1/common";
+import {
+ getIssueCommentType,
+ IssueCommentType,
+ useIssueCommentStore,
+} from "@/store/modules/v1/issueComment";
+import { RiskLevel, State } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ Issue_ApprovalStatus,
+ Issue_Approver_Status,
+ ListIssueCommentsRequestSchema,
+ RequestIssueRequestSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import type { User as UserMessage } from "@/types/proto-es/v1/user_service_pb";
+import {
+ AccountType,
+ getAccountTypeByEmail,
+ groupBindingPrefix,
+} from "@/types/v1/user";
+import {
+ displayRoleTitle,
+ ensureUserFullName,
+ isBindingPolicyExpired,
+ memberMapToRolesInProjectIAM,
+} from "@/utils";
+import { extractIssueUID } from "@/utils/v1/issue/issue";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+
+type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";
+
+export function PlanDetailSidebarApprovalFlow() {
+ return <PlanDetailApprovalFlowContent mode="sidebar" />;
+}
+
+export function PlanDetailReviewApprovalFlow() {
+ return <PlanDetailApprovalFlowContent mode="review" />;
+}
+
+export function PlanDetailApprovalFlow() {
+ return <PlanDetailSidebarApprovalFlow />;
+}
+
+function PlanDetailApprovalFlowContent({
+ mode,
+}: {
+ mode: "review" | "sidebar";
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const projectStore = useProjectV1Store();
+ const projectIamPolicyStore = useProjectIamPolicyStore();
+ const issueCommentStore = useIssueCommentStore();
+ const projectName = `${projectNamePrefix}${page.projectId}`;
+ const issue = page.issue;
+
+ useEffect(() => {
+ void projectStore
+ .getOrFetchProjectByName(projectName)
+ .catch(() => undefined);
+ void projectIamPolicyStore
+ .getOrFetchProjectIamPolicy(projectName)
+ .catch(() => undefined);
+ }, [projectIamPolicyStore, projectName, projectStore]);
+
+ useEffect(() => {
+ if (mode !== "review") {
+ return;
+ }
+ if (!issue?.name) {
+ return;
+ }
+ void issueCommentStore
+ .listIssueComments(
+ create(ListIssueCommentsRequestSchema, {
+ parent: issue.name,
+ pageSize: 100,
+ })
+ )
+ .catch(() => undefined);
+ }, [issue?.name, issueCommentStore, mode]);
+
+ if (!issue) {
+ return null;
+ }
+
+ const approvalSteps = issue.approvalTemplate?.flow?.roles ?? [];
+ const statusTag = getStatusTag(issue, approvalSteps.length, t);
+ const comments = issueCommentStore.getIssueComments(issue.name);
+ const lastRejection = useMemo(() => {
+ if (issue.approvalStatus !== Issue_ApprovalStatus.REJECTED) {
+ return undefined;
+ }
+ for (let i = comments.length - 1; i >= 0; i--) {
+ const comment = comments[i];
+ if (getIssueCommentType(comment) === IssueCommentType.APPROVAL) {
+ return {
+ comment: comment.comment || "",
+ creator: comment.creator,
+ };
+ }
+ }
+ return undefined;
+ }, [comments, issue.approvalStatus]);
+ const issueUID = extractIssueUID(issue.name);
+ const riskLevelText =
+ issue.riskLevel === RiskLevel.LOW
+ ? t("issue.risk-level.low")
+ : issue.riskLevel === RiskLevel.MODERATE
+ ? t("issue.risk-level.moderate")
+ : issue.riskLevel === RiskLevel.HIGH
+ ? t("issue.risk-level.high")
+ : "";
+ const ruleText = [
+ issue.approvalTemplate?.title?.trim(),
+ issue.approvalTemplate?.description?.trim(),
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+ if (issue.approvalStatus === Issue_ApprovalStatus.CHECKING) {
+ if (mode === "review") {
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">
+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />
+ <span>
+ {t("custom-approval.issue-review.generating-approval-flow")}
+ </span>
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div>
+ <div className="flex w-full flex-row flex-wrap items-center gap-2">
+ <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>
+ <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />
+ <ApprovalRiskLevelIcon
+ riskLevel={issue.riskLevel}
+ title={issue.approvalTemplate?.title?.trim()}
+ />
+ </div>
+ <div className="mt-2 flex items-center gap-x-2 text-sm text-control-placeholder">
+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />
+ <span>
+ {t("custom-approval.issue-review.generating-approval-flow")}
+ </span>
+ </div>
+ </div>
+ );
+ }
+
+ if (
+ issue.approvalStatus === Issue_ApprovalStatus.SKIPPED ||
+ approvalSteps.length === 0
+ ) {
+ if (mode === "review") {
+ return (
+ <div className="flex flex-col">
+ <div className="p-4 text-sm text-control-placeholder">
+ {t("custom-approval.approval-flow.skip")}
+ </div>
+ </div>
+ );
+ }
+ return (
+ <div>
+ <div className="flex w-full flex-row flex-wrap items-center gap-2">
+ <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>
+ <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />
+ <ApprovalRiskLevelIcon
+ riskLevel={issue.riskLevel}
+ title={issue.approvalTemplate?.title?.trim()}
+ />
+ </div>
+ <div className="mt-2 flex items-center gap-x-1 text-sm text-control-placeholder">
+ {t("custom-approval.approval-flow.skip")}
+ </div>
+ </div>
+ );
+ }
+
+ if (mode === "sidebar") {
+ return (
+ <div>
+ <div className="flex w-full flex-row flex-wrap items-center gap-2">
+ <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>
+ <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />
+ <ApprovalRiskLevelIcon
+ riskLevel={issue.riskLevel}
+ title={issue.approvalTemplate?.title?.trim()}
+ />
+ <div className="grow" />
+ {statusTag && (
+ <span
+ className={cn(
+ "inline-flex items-center rounded-full px-2 py-0.5 text-xs",
+ statusTag.className
+ )}
+ >
+ {statusTag.label}
+ </span>
+ )}
+ </div>
+
+ <div className="mt-2">
+ <div className="mt-1 flex flex-col gap-y-4 pl-1">
+ {approvalSteps.map((step, index) => (
+ <ApprovalStepItem
+ key={`${step}-${index}`}
+ issue={issue}
+ readonly={page.readonly}
+ step={step}
+ stepIndex={index}
+ stepNumber={index + 1}
+ totalSteps={approvalSteps.length}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ {issue.approvalStatus === Issue_ApprovalStatus.REJECTED &&
+ lastRejection && (
+ <div className="mx-4 mt-3 rounded-sm border border-warning bg-warning/10 px-3 py-2 text-sm text-warning">
+ <div className="font-medium">
+ {t("custom-approval.issue-review.rejected-by")}{" "}
+ {lastRejection.creator}
+ </div>
+ {lastRejection.comment && (
+ <div className="mt-1">{lastRejection.comment}</div>
+ )}
+ </div>
+ )}
+
+ <div className="px-4 py-3">
+ <div className="flex w-full flex-row flex-wrap items-center gap-2">
+ <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>
+ <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />
+ <ApprovalRiskLevelIcon
+ riskLevel={issue.riskLevel}
+ title={issue.approvalTemplate?.title?.trim()}
+ />
+ <div className="grow" />
+ {statusTag && (
+ <span
+ className={cn(
+ "inline-flex items-center rounded-full px-2 py-0.5 text-xs",
+ statusTag.className
+ )}
+ >
+ {statusTag.label}
+ </span>
+ )}
+ </div>
+
+ <div className="mt-2">
+ <div className="mt-1 flex flex-col gap-y-4 pl-1">
+ {approvalSteps.map((step, index) => (
+ <ApprovalStepItem
+ key={`${step}-${index}`}
+ issue={issue}
+ readonly={page.readonly}
+ step={step}
+ stepIndex={index}
+ stepNumber={index + 1}
+ totalSteps={approvalSteps.length}
+ />
+ ))}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-x-2 border-t px-4 py-2.5 text-sm text-control-placeholder">
+ <ApprovalRiskLevelIcon
+ riskLevel={issue.riskLevel}
+ title={issue.approvalTemplate?.title?.trim()}
+ />
+ {riskLevelText && <span>{riskLevelText}</span>}
+ {riskLevelText && ruleText && <span>·</span>}
+ {ruleText && <span className="min-w-0 truncate">{ruleText}</span>}
+ <div className="flex-1" />
+ <button
+ className="text-accent hover:underline"
+ onClick={() =>
+ void router.push({
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: {
+ issueId: issueUID,
+ projectId: page.projectId,
+ },
+ })
+ }
+ type="button"
+ >
+ {t("common.issue")} #{issueUID} · {t("plan.view-discussion")} →
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function ApprovalStepItem({
+ issue,
+ readonly,
+ step,
+ stepIndex,
+ stepNumber,
+ totalSteps,
+}: {
+ issue: Issue;
+ readonly: boolean;
+ step: string;
+ stepIndex: number;
+ stepNumber: number;
+ totalSteps: number;
+}) {
+ const { t } = useTranslation();
+ const {
+ canReRequest,
+ handleReRequestReview,
+ potentialApprovers,
+ reRequesting,
+ roleName,
+ showSelfApprovalTip,
+ status,
+ stepApprover,
+ } = useApprovalStep(issue, step, stepIndex);
+
+ return (
+ <div className="relative pl-9">
+ {stepIndex < totalSteps - 1 && (
+ <div className="absolute left-[13px] top-7 bottom-[-16px] w-px bg-control-border" />
+ )}
+
+ <div
+ className={cn(
+ "absolute left-0 top-0 z-10 flex h-7 w-7 items-center justify-center rounded-full",
+ status === "approved"
+ ? "bg-success"
+ : status === "rejected"
+ ? "bg-warning"
+ : status === "current"
+ ? "bg-accent"
+ : "bg-control-bg"
+ )}
+ >
+ {status === "approved" ? (
+ <ThumbsUp className="h-3.5 w-3.5 text-white" />
+ ) : status === "rejected" ? (
+ <X className="h-3.5 w-3.5 text-white" />
+ ) : status === "current" ? (
+ <User className="h-3.5 w-3.5 text-white" />
+ ) : (
+ <span className="text-xs font-medium text-gray-600">
+ {stepNumber}
+ </span>
+ )}
+ </div>
+
+ <div>
+ <div className="text-sm font-medium text-gray-900">{roleName}</div>
+ <div className="mt-1 text-sm text-gray-600">
+ {status === "approved" && (
+ <div className="flex flex-row items-center gap-1">
+ <span className="text-xs">
+ {t("custom-approval.issue-review.approved-by")}
+ </span>
+ {stepApprover?.principal && (
+ <ApprovalUserText candidate={stepApprover.principal} />
+ )}
+ </div>
+ )}
+
+ {status === "rejected" && (
+ <div className="flex flex-col gap-1">
+ <div className="flex flex-row items-center gap-1">
+ <span className="text-xs">
+ {t("custom-approval.issue-review.rejected-by")}
+ </span>
+ {stepApprover?.principal && (
+ <ApprovalUserText candidate={stepApprover.principal} />
+ )}
+ </div>
+ {canReRequest && !readonly && (
+ <div className="mt-1">
+ <Button
+ className="gap-x-1.5 border border-accent/30 bg-accent/10 text-accent hover:bg-accent/15"
+ disabled={reRequesting}
+ onClick={() => {
+ void handleReRequestReview();
+ }}
+ size="xs"
+ variant="ghost"
+ >
+ <RotateCcw className="h-3 w-3" />
+ {t("custom-approval.issue-review.re-request-review")}
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+
+ {status === "current" && !readonly && (
+ <div className="flex flex-col gap-1">
+ <PotentialApprovers users={potentialApprovers} />
+ {showSelfApprovalTip && (
+ <div className="rounded-sm border border-yellow-600 bg-yellow-50 px-1 py-0.5 text-xs text-yellow-600">
+ {t("custom-approval.issue-review.self-approval-not-allowed")}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function ApprovalUserText({ candidate }: { candidate: string }) {
+ const userStore = useUserStore();
+ const [user, setUser] = useState<UserMessage>();
+
+ useEffect(() => {
+ let canceled = false;
+
+ const load = async () => {
+ const next = await userStore.getOrFetchUserByIdentifier({
+ identifier: candidate,
+ });
+ if (canceled || !next) return;
+ if (
+ getAccountTypeByEmail(next.email) !== AccountType.USER ||
+ next.state !== State.ACTIVE
+ ) {
+ setUser(undefined);
+ return;
+ }
+ setUser(next);
+ };
+
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [candidate, userStore]);
+
+ if (!user) return null;
+
+ const displayName = user.title || user.email.split("@")[0];
+ return (
+ <span className="inline-flex items-center gap-1">
+ <span
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-medium text-white"
+ style={{ backgroundColor: getAvatarColor(displayName) }}
+ >
+ {getInitials(displayName)}
+ </span>
+ <span className="text-xs text-control">{displayName}</span>
+ </span>
+ );
+}
+
+function PotentialApprovers({ users }: { users: UserMessage[] }) {
+ const { t } = useTranslation();
+
+ if (users.length === 0) return null;
+
+ if (users.length <= 3) {
+ return (
+ <div className="flex flex-col items-start gap-1">
+ {users.map((user) => (
+ <ApprovalCandidateRow key={user.name} user={user} />
+ ))}
+ </div>
+ );
+ }
+
+ const visibleUsers = users.slice(0, 3);
+ const names = visibleUsers
+ .map((user) => user.title || user.email.split("@")[0])
+ .join(", ");
+ const remainingCount = users.length - visibleUsers.length;
+
+ return (
+ <Tooltip
+ content={
+ <div className="flex max-w-xs flex-col gap-y-1">
+ {users.map((user) => (
+ <ApprovalCandidateRow key={user.name} showEmail user={user} />
+ ))}
+ </div>
+ }
+ side="bottom"
+ >
+ <span className="cursor-pointer text-xs text-control-light hover:text-accent">
+ {t("custom-approval.issue-review.and-n-other-users", {
+ count: remainingCount,
+ names,
+ })}
+ </span>
+ </Tooltip>
+ );
+}
+
+function ApprovalCandidateRow({
+ showEmail = false,
+ user,
+}: {
+ showEmail?: boolean;
+ user: UserMessage;
+}) {
+ const { t } = useTranslation();
+ const currentUser = useCurrentUserV1().value;
+ const displayName = user.title || user.email.split("@")[0];
+ const isCurrentUser = currentUser?.name === user.name;
+
+ return (
+ <div className="inline-flex items-center gap-1.5">
+ <span
+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-medium text-white"
+ style={{ backgroundColor: getAvatarColor(displayName) }}
+ >
+ {getInitials(displayName)}
+ </span>
+ <span className="text-xs text-control">{displayName}</span>
+ {isCurrentUser && (
+ <span className="rounded-full bg-success/10 px-1.5 py-0.5 text-[10px] text-success">
+ {t("common.you")}
+ </span>
+ )}
+ {showEmail && (
+ <span className="text-xs text-control-light">{user.email}</span>
+ )}
+ </div>
+ );
+}
+
+function ApprovalRiskLevelIcon({
+ riskLevel,
+ title,
+}: {
+ riskLevel: RiskLevel;
+ title?: string;
+}) {
+ const { t } = useTranslation();
+
+ if (riskLevel === RiskLevel.RISK_LEVEL_UNSPECIFIED) {
+ return null;
+ }
+
+ const riskLevelText =
+ riskLevel === RiskLevel.LOW
+ ? t("issue.risk-level.low")
+ : riskLevel === RiskLevel.MODERATE
+ ? t("issue.risk-level.moderate")
+ : t("issue.risk-level.high");
+
+ return (
+ <Tooltip
+ content={
+ <div className="flex flex-col gap-1">
+ <div>
+ <span>{riskLevelText}</span>
+ <span className="ml-1 opacity-60">
+ ({t("issue.risk-level.self")})
+ </span>
+ </div>
+ {title && <div className="text-sm opacity-80">{title}</div>}
+ </div>
+ }
+ >
+ {riskLevel === RiskLevel.LOW ? (
+ <ShieldCheck className="h-4 w-4 text-success" />
+ ) : riskLevel === RiskLevel.MODERATE ? (
+ <ShieldAlert className="h-4 w-4 text-warning" />
+ ) : (
+ <ShieldAlert className="h-4 w-4 text-error" />
+ )}
+ </Tooltip>
+ );
+}
+
+function getStatusTag(
+ issue: Issue,
+ approvalStepCount: number,
+ t: ReturnType<typeof useTranslation>["t"]
+) {
+ if (approvalStepCount === 0) {
+ return undefined;
+ }
+ if (issue.approvalStatus === Issue_ApprovalStatus.APPROVED) {
+ return {
+ className: "bg-success/10 text-success",
+ label: t("issue.table.approved"),
+ };
+ }
+ if (issue.approvalStatus === Issue_ApprovalStatus.REJECTED) {
+ return {
+ className: "bg-warning/10 text-warning",
+ label: t("common.rejected"),
+ };
+ }
+ if (issue.approvalStatus === Issue_ApprovalStatus.PENDING) {
+ return {
+ className: "bg-accent/10 text-accent",
+ label: t("common.under-review"),
+ };
+ }
+ return undefined;
+}
+
+function useApprovalStep(issue: Issue, step: string, stepIndex: number) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState } = page;
+ const currentUser = useCurrentUserV1().value;
+ const groupStore = useGroupStore();
+ const projectStore = useProjectV1Store();
+ const projectIamPolicyStore = useProjectIamPolicyStore();
+ const userStore = useUserStore();
+ const [potentialApprovers, setPotentialApprovers] = useState<UserMessage[]>(
+ []
+ );
+ const [reRequesting, setReRequesting] = useState(false);
+ const projectName = `${projectNamePrefix}${page.projectId}`;
+ const currentUserEmail = currentUser?.email ?? "";
+ const project = projectStore.getProjectByName(projectName);
+ const stepApprover = issue.approvers[stepIndex];
+
+ const status = useMemo<ApprovalStepStatus>(() => {
+ if (stepApprover?.status === Issue_Approver_Status.APPROVED) {
+ return "approved";
+ }
+ if (stepApprover?.status === Issue_Approver_Status.REJECTED) {
+ return "rejected";
+ }
+ for (let i = 0; i < stepIndex; i++) {
+ const previousApprover = issue.approvers[i];
+ if (
+ !previousApprover ||
+ (previousApprover.status !== Issue_Approver_Status.APPROVED &&
+ previousApprover.status !== Issue_Approver_Status.REJECTED)
+ ) {
+ return "pending";
+ }
+ if (previousApprover.status === Issue_Approver_Status.REJECTED) {
+ return "pending";
+ }
+ }
+ return "current";
+ }, [issue.approvers, stepApprover, stepIndex]);
+
+ const roleName = useMemo(() => {
+ return step
+ ? displayRoleTitle(step)
+ : t("custom-approval.approval-flow.node.approver");
+ }, [step, t]);
+
+ const canReRequest = useMemo(() => {
+ return (
+ issue.creator === `${userNamePrefix}${currentUserEmail}` &&
+ stepApprover?.status === Issue_Approver_Status.REJECTED
+ );
+ }, [currentUserEmail, issue.creator, stepApprover?.status]);
+
+ const groupNamesKey = useMemo(() => {
+ const policy = projectIamPolicyStore.getProjectIamPolicy(projectName);
+ const names: string[] = [];
+ for (const binding of policy.bindings) {
+ if (binding.role !== step || isBindingPolicyExpired(binding)) continue;
+ for (const member of binding.members) {
+ if (member.startsWith(groupBindingPrefix)) {
+ names.push(member);
+ }
+ }
+ }
+ return [...new Set(names)].sort().join("\u0000");
+ }, [projectIamPolicyStore, projectName, step]);
+ const groupNames = useMemo(
+ () => (groupNamesKey ? groupNamesKey.split("\u0000") : []),
+ [groupNamesKey]
+ );
+
+ useEffect(() => {
+ void groupStore.batchGetOrFetchGroups(groupNames).catch(() => undefined);
+ }, [groupNames, groupStore]);
+
+ const candidateEmailsKey = useMemo(() => {
+ const policy = projectIamPolicyStore.getProjectIamPolicy(projectName);
+ const memberMap = memberMapToRolesInProjectIAM(policy, step);
+ const candidates: string[] = [];
+ for (const fullname of memberMap.keys()) {
+ if (fullname.startsWith(userNamePrefix)) {
+ candidates.push(fullname);
+ }
+ }
+ return [...new Set(candidates)].sort().join("\u0000");
+ }, [projectIamPolicyStore, projectName, step]);
+ const candidateEmails = useMemo(
+ () => (candidateEmailsKey ? candidateEmailsKey.split("\u0000") : []),
+ [candidateEmailsKey]
+ );
+
+ const isCurrentUserInCandidates = useMemo(
+ () => candidateEmails.includes(`${userNamePrefix}${currentUserEmail}`),
+ [candidateEmails, currentUserEmail]
+ );
+
+ const filteredCandidateEmails = useMemo(() => {
+ if (
+ !project.allowSelfApproval &&
+ issue.creator === `${userNamePrefix}${currentUserEmail}`
+ ) {
+ return candidateEmails.filter(
+ (candidate) => candidate !== `${userNamePrefix}${currentUserEmail}`
+ );
+ }
+ return candidateEmails;
+ }, [
+ candidateEmails,
+ currentUserEmail,
+ issue.creator,
+ project.allowSelfApproval,
+ ]);
+
+ const showSelfApprovalTip = useMemo(() => {
+ return (
+ status === "current" &&
+ !project.allowSelfApproval &&
+ issue.creator === `${userNamePrefix}${currentUserEmail}` &&
+ isCurrentUserInCandidates
+ );
+ }, [
+ currentUserEmail,
+ isCurrentUserInCandidates,
+ issue.creator,
+ project.allowSelfApproval,
+ status,
+ ]);
+
+ useEffect(() => {
+ let canceled = false;
+
+ const load = async () => {
+ if (status !== "current" || filteredCandidateEmails.length === 0) {
+ setPotentialApprovers([]);
+ return;
+ }
+
+ const users = await userStore.batchGetOrFetchUsers(
+ filteredCandidateEmails.map(ensureUserFullName)
+ );
+ if (canceled) return;
+
+ const next = users
+ .filter(
+ (user) =>
+ user &&
+ user.state === State.ACTIVE &&
+ getAccountTypeByEmail(user.email) === AccountType.USER
+ )
+ .sort((left, right) => {
+ if (left.email === currentUserEmail) return -1;
+ if (right.email === currentUserEmail) return 1;
+ return left.title.localeCompare(right.title);
+ });
+ setPotentialApprovers(next);
+ };
+
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [currentUserEmail, filteredCandidateEmails, status, userStore]);
+
+ const handleReRequestReview = async () => {
+ if (reRequesting) return;
+
+ try {
+ setReRequesting(true);
+ const response = await issueServiceClientConnect.requestIssue(
+ create(RequestIssueRequestSchema, { name: issue.name })
+ );
+ patchState({ issue: response });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("custom-approval.issue-review.re-request-review-success"),
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setReRequesting(false);
+ }
+ };
+
+ return {
+ canReRequest,
+ handleReRequestReview,
+ potentialApprovers,
+ reRequesting,
+ roleName,
+ showSelfApprovalTip,
+ status,
+ stepApprover,
+ };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
new file mode 100644
index 0000000000..660599e44a
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChangesBranch.tsx
@@ -0,0 +1,1799 @@
+import { clone, create } from "@bufbuild/protobuf";
+import {
+ CheckCircle,
+ ChevronRight,
+ DatabaseIcon,
+ EllipsisVertical,
+ ExternalLink,
+ FolderTree,
+ Loader2,
+ XCircle,
+} from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { v4 as uuidv4 } from "uuid";
+import {
+ instanceRoleServiceClientConnect,
+ planServiceClientConnect,
+} from "@/connect";
+import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";
+import { EngineIconPath } from "@/react/components/instance/constants";
+import { Alert } from "@/react/components/ui/alert";
+import { Badge } from "@/react/components/ui/badge";
+import { Button } from "@/react/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
+import { SearchInput } from "@/react/components/ui/search-input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { Switch } from "@/react/components/ui/switch";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useSessionPageSize } from "@/react/hooks/useSessionPageSize";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import {
+ PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+} from "@/router/dashboard/projectV1";
+import {
+ getProjectNameAndDatabaseGroupName,
+ pushNotification,
+ useCurrentUserV1,
+ useDatabaseV1Store,
+ useDBGroupStore,
+ useEnvironmentV1Store,
+ useProjectV1Store,
+ useSheetV1Store,
+} from "@/store";
+import {
+ isValidDatabaseGroupName,
+ isValidDatabaseName,
+ isValidReleaseName,
+} from "@/types";
+import { Engine, State } from "@/types/proto-es/v1/common_pb";
+import type { DatabaseGroup } from "@/types/proto-es/v1/database_group_service_pb";
+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { SyncStatus } from "@/types/proto-es/v1/database_service_pb";
+import { ListInstanceRolesRequestSchema } from "@/types/proto-es/v1/instance_role_service_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ type Plan_Spec,
+ Plan_SpecSchema,
+ type PlanCheckRun,
+ PlanSchema,
+ UpdatePlanRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ extractDatabaseResourceName,
+ getDatabaseEnvironment,
+ getDefaultTransactionMode,
+ getInstanceResource,
+ hasProjectPermissionV2,
+} from "@/utils";
+import { getStatementSize } from "@/utils/sheet";
+import { extractDatabaseGroupName } from "@/utils/v1/databaseGroup";
+import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
+import {
+ extractSheetUID,
+ getSheetStatement,
+ setSheetStatement as setLocalSheetStatement,
+} from "@/utils/v1/sheet";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidation";
+import {
+ getDefaultGhostConfig,
+ getGhostConfig as getGhostConfigFromStatement,
+ updateGhostConfig,
+ updateIsolationLevel,
+ updateRoleSetter,
+ updateTransactionMode,
+} from "../utils/directiveUtils";
+import { getLocalSheetByName, getNextLocalSheetUID } from "../utils/localSheet";
+import {
+ allowGhostForDatabase,
+ getPlanOptionVisibility,
+} from "../utils/options";
+import { planCheckRunListForSpec } from "../utils/planCheck";
+import { getSelectedSpec, getSpecTitle } from "../utils/spec";
+import { updateSpecSheetWithStatement } from "../utils/specMutation";
+import {
+ filterPlanTargets,
+ getDatabaseGroupRouteParams,
+ splitInlineDatabases,
+} from "../utils/targets";
+import { PlanDetailChecks } from "./PlanDetailChecks";
+import { PlanDetailDraftChecks } from "./PlanDetailDraftChecks";
+import { PlanDetailStatementSection } from "./PlanDetailStatementSection";
+import { PlanDetailTabItem, PlanDetailTabStrip } from "./PlanDetailTabStrip";
+
+const DEFAULT_VISIBLE_TARGETS = 20;
+const EMPTY_SELECT_VALUE = "__empty__";
+
+const pushSpecDetailRoute = (
+ projectId: string,
+ planId: string,
+ specId: string
+) =>
+ router.push({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: { planId, projectId, specId },
+ });
+
+type IsolationLevel =
+ | "READ_UNCOMMITTED"
+ | "READ_COMMITTED"
+ | "REPEATABLE_READ"
+ | "SERIALIZABLE";
+
+const BACKUP_AVAILABLE_ENGINES = [
+ Engine.MYSQL,
+ Engine.TIDB,
+ Engine.MSSQL,
+ Engine.ORACLE,
+ Engine.POSTGRES,
+];
+
+export function PlanDetailChangesBranch({
+ selectedSpecId,
+ onSelectedSpecIdChange,
+}: {
+ selectedSpecId: string;
+ onSelectedSpecIdChange: (specId: string) => void;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState } = page;
+ const currentUser = useCurrentUserV1().value;
+ const projectStore = useProjectV1Store();
+ const project = projectStore.getProjectByName(`projects/${page.projectId}`);
+ const sheetStore = useSheetV1Store();
+ const [showAddSpecSheet, setShowAddSpecSheet] = useState(false);
+ const [showTargetSelectorSheet, setShowTargetSelectorSheet] = useState(false);
+ const [draftCheckRunsBySpecId, setDraftCheckRunsBySpecId] = useState<
+ Record<string, PlanCheckRun[]>
+ >({});
+ const { emptySpecIdSet } = usePlanDetailSpecValidation(page.plan.specs ?? []);
+ const specs = page.plan.specs ?? [];
+ const selectedSpec = useMemo(() => {
+ return getSelectedSpec({ selectedSpecId, specs });
+ }, [selectedSpecId, specs]);
+ const canModifySpecs = useMemo(() => {
+ if (page.plan.state === State.DELETED) return false;
+ if (page.readonly) return false;
+ if (page.isCreating) return true;
+ return (
+ !page.plan.hasRollout &&
+ (page.plan.creator === currentUser.name ||
+ hasProjectPermissionV2(project, "bb.plans.update"))
+ );
+ }, [
+ currentUser.name,
+ page.isCreating,
+ page.plan.creator,
+ page.plan.hasRollout,
+ page.plan.state,
+ page.readonly,
+ project,
+ ]);
+
+ const commitSpecs = useCallback(
+ async (nextSpecs: Plan_Spec[]) => {
+ const planPatch = clone(PlanSchema, page.plan);
+ planPatch.specs = nextSpecs;
+
+ if (page.isCreating) {
+ patchState({ plan: planPatch });
+ return planPatch;
+ }
+
+ const response = await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["specs"] },
+ })
+ );
+ patchState({ plan: response });
+ return response;
+ },
+ [page.isCreating, page.plan, patchState]
+ );
+
+ const handleSpecCreate = async (targets: string[]) => {
+ try {
+ const sheetUID = getNextLocalSheetUID();
+ const localSheet = getLocalSheetByName(
+ `${project.name}/sheets/${sheetUID}`
+ );
+ const spec = create(Plan_SpecSchema, {
+ id: uuidv4(),
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, {
+ sheet: localSheet.name,
+ targets,
+ }),
+ },
+ });
+
+ if (!page.isCreating) {
+ const createdSheet = await sheetStore.createSheet(
+ project.name,
+ localSheet
+ );
+ if (spec.config.case === "changeDatabaseConfig") {
+ spec.config.value.sheet = createdSheet.name;
+ }
+ }
+
+ await commitSpecs([...page.plan.specs, spec]);
+ onSelectedSpecIdChange(spec.id);
+ void pushSpecDetailRoute(page.projectId, page.planId, spec.id);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ setShowAddSpecSheet(false);
+ return;
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ return;
+ }
+ };
+
+ 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 nextSpecs = page.plan.specs.filter(
+ (spec) => spec.id !== targetSpec.id
+ );
+ const fallbackSpec = nextSpecs[0];
+ try {
+ await commitSpecs(nextSpecs);
+ if (fallbackSpec) {
+ onSelectedSpecIdChange(fallbackSpec.id);
+ void pushSpecDetailRoute(page.projectId, page.planId, fallbackSpec.id);
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ }
+ };
+
+ const handleTargetsUpdate = async (targets: string[]) => {
+ if (!selectedSpec) return;
+ const nextSpecs = page.plan.specs.map((spec) => {
+ if (spec.id !== selectedSpec.id) return spec;
+ const patched = clone(Plan_SpecSchema, spec);
+ if (
+ patched.config.case === "changeDatabaseConfig" ||
+ patched.config.case === "exportDataConfig"
+ ) {
+ patched.config.value.targets = targets;
+ }
+ return patched;
+ });
+ try {
+ await commitSpecs(nextSpecs);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ setShowTargetSelectorSheet(false);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ }
+ };
+
+ useEffect(() => {
+ if (selectedSpec && selectedSpec.id !== selectedSpecId) {
+ onSelectedSpecIdChange(selectedSpec.id);
+ }
+ }, [onSelectedSpecIdChange, selectedSpec, selectedSpecId]);
+
+ if (!selectedSpec) {
+ return (
+ <div className="rounded-md border bg-white px-4 py-3 text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ );
+ }
+
+ const specHasRelease =
+ selectedSpec.config.case === "changeDatabaseConfig" &&
+ isValidReleaseName(selectedSpec.config.value.release);
+ const currentTargets =
+ selectedSpec.config.case === "changeDatabaseConfig"
+ ? (selectedSpec.config.value.targets ?? [])
+ : selectedSpec.config.case === "exportDataConfig"
+ ? (selectedSpec.config.value.targets ?? [])
+ : [];
+
+ return (
+ <div className="flex w-full flex-1 flex-col">
+ <PlanDetailTabStrip
+ action={
+ canModifySpecs ? (
+ <Button
+ onClick={() => setShowAddSpecSheet(true)}
+ size="xs"
+ variant="outline"
+ >
+ {t("plan.add-spec")}
+ </Button>
+ ) : undefined
+ }
+ >
+ {specs.map((spec, index) => {
+ const isSelected = selectedSpec.id === spec.id;
+ return (
+ <PlanDetailTabItem
+ key={spec.id}
+ action={
+ canModifySpecs && specs.length > 1 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={cn(
+ "mr-2 inline-flex h-6 w-6 shrink-0 cursor-pointer items-center justify-center rounded-xs text-control-light outline-hidden transition-colors hover:bg-control-bg hover:text-control focus-visible:ring-2 focus-visible:ring-accent"
+ )}
+ >
+ <EllipsisVertical className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ className="text-error"
+ onClick={() => void handleDeleteSpec(spec)}
+ >
+ {t("common.delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : undefined
+ }
+ onSelect={() => {
+ onSelectedSpecIdChange(spec.id);
+ void pushSpecDetailRoute(page.projectId, page.planId, spec.id);
+ }}
+ selected={isSelected}
+ >
+ <span
+ className={cn(
+ "flex items-center gap-1 text-sm font-medium transition-colors",
+ isSelected ? "" : "text-control-light hover:text-control"
+ )}
+ >
+ <span className="opacity-80">{index + 1}.</span>
+ <span>{getSpecTitle(spec, t)}</span>
+ {emptySpecIdSet.has(spec.id) && (
+ <Tooltip content={t("plan.navigator.statement-empty")}>
+ <span className="text-error">*</span>
+ </Tooltip>
+ )}
+ </span>
+ </PlanDetailTabItem>
+ );
+ })}
+ </PlanDetailTabStrip>
+
+ <div className="flex flex-1 flex-col overflow-y-auto px-4 py-4">
+ <div className="flex flex-col gap-y-4">
+ <TargetsSection
+ allowEdit={canModifySpecs}
+ onEdit={() => setShowTargetSelectorSheet(true)}
+ selectedSpec={selectedSpec}
+ />
+ <PlanDetailStatementSection
+ planCheckRuns={
+ page.isCreating
+ ? (draftCheckRunsBySpecId[selectedSpec.id] ?? [])
+ : planCheckRunListForSpec(page.planCheckRuns, selectedSpec)
+ }
+ spec={selectedSpec}
+ />
+ {!specHasRelease &&
+ (page.isCreating ? (
+ selectedSpec.config.case === "changeDatabaseConfig" ? (
+ <PlanDetailDraftChecks
+ selectedSpec={selectedSpec}
+ onPlanCheckRunsChange={(runs) =>
+ setDraftCheckRunsBySpecId((prev) => ({
+ ...prev,
+ [selectedSpec.id]: runs,
+ }))
+ }
+ />
+ ) : null
+ ) : (
+ <PlanDetailChecks selectedSpec={selectedSpec} />
+ ))}
+ {!specHasRelease && <OptionsSection selectedSpec={selectedSpec} />}
+ </div>
+ </div>
+
+ <TargetSelectorSheet
+ currentTargets={currentTargets}
+ onConfirm={handleTargetsUpdate}
+ onOpenChange={setShowTargetSelectorSheet}
+ open={showTargetSelectorSheet}
+ projectName={project.name}
+ />
+
+ <TargetSelectorSheet
+ currentTargets={[]}
+ onConfirm={handleSpecCreate}
+ onOpenChange={setShowAddSpecSheet}
+ open={showAddSpecSheet}
+ projectName={project.name}
+ title={t("plan.add-spec")}
+ />
+ </div>
+ );
+}
+
+function OptionsSection({ selectedSpec }: { selectedSpec: Plan_Spec }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, refreshState } = page;
+ const currentUser = useCurrentUserV1().value;
+ const projectStore = useProjectV1Store();
+ const project = projectStore.getProjectByName(`projects/${page.projectId}`);
+ const databaseStore = useDatabaseV1Store();
+ const dbGroupStore = useDBGroupStore();
+ const sheetStore = useSheetV1Store();
+ const [sheetStatement, setSheetStatementValue] = useState("");
+ const [isSheetOversize, setIsSheetOversize] = useState(false);
+ const [instanceRoles, setInstanceRoles] = useState<string[]>([]);
+
+ const targets = useMemo(() => {
+ if (selectedSpec.config?.case === "changeDatabaseConfig") {
+ return selectedSpec.config.value.targets ?? [];
+ }
+ return [];
+ }, [selectedSpec]);
+ const databases = useVueState(() =>
+ targets
+ .flatMap((target) => {
+ if (isValidDatabaseName(target)) {
+ return [databaseStore.getDatabaseByName(target)];
+ }
+ if (isValidDatabaseGroupName(target)) {
+ const dbGroup = dbGroupStore.getDBGroupByName(
+ target,
+ DatabaseGroupView.FULL
+ );
+ return (dbGroup.matchedDatabases ?? []).map((database) =>
+ databaseStore.getDatabaseByName(database.name)
+ );
+ }
+ return [];
+ })
+ .filter((database) => isValidDatabaseName(database.name))
+ );
+ const firstDatabaseName = databases[0]?.name ?? "";
+ const instanceName = firstDatabaseName
+ ? extractDatabaseResourceName(firstDatabaseName).instance
+ : "";
+
+ const parsed = useMemo(
+ () => parseStatement(sheetStatement),
+ [sheetStatement]
+ );
+ const selectedRole = parsed.role ?? "";
+ const selectedIsolation = parsed.isolationLevel ?? "";
+ const transactionModeChecked =
+ parsed.transactionMode !== undefined
+ ? parsed.transactionMode === "on"
+ : getDefaultTransactionMode();
+ const ghostEnabled = parsed.ghostEnabled;
+ const preBackupEnabled =
+ selectedSpec.config?.case === "changeDatabaseConfig"
+ ? Boolean(selectedSpec.config.value.enablePriorBackup)
+ : false;
+ const isSheetBasedDatabaseChange =
+ selectedSpec.config?.case === "changeDatabaseConfig" &&
+ !selectedSpec.config.value.release;
+
+ const {
+ shouldShow,
+ showGhost,
+ showInstanceRole,
+ showIsolationLevel,
+ showPreBackup,
+ showTransactionMode,
+ } = useMemo(
+ () =>
+ getPlanOptionVisibility({
+ databases,
+ isChangeDatabaseConfig:
+ selectedSpec.config?.case === "changeDatabaseConfig",
+ isSheetBasedDatabaseChange,
+ }),
+ [databases, isSheetBasedDatabaseChange, selectedSpec.config?.case]
+ );
+ const allowChange = useMemo(() => {
+ if (page.readonly) return false;
+ if (page.plan.hasRollout) return false;
+ if (page.isCreating) return true;
+ return (
+ page.plan.creator === currentUser.name ||
+ hasProjectPermissionV2(project, "bb.plans.update")
+ );
+ }, [
+ currentUser.name,
+ page.isCreating,
+ page.plan.creator,
+ page.plan.hasRollout,
+ page.readonly,
+ project,
+ ]);
+ const instanceRoleOptions = useMemo(() => {
+ const roles = !selectedRole
+ ? instanceRoles
+ : instanceRoles.includes(selectedRole)
+ ? instanceRoles
+ : [selectedRole, ...instanceRoles];
+ return roles.map((role) => ({ label: role, value: role }));
+ }, [instanceRoles, selectedRole]);
+ const oversizeTooltip = isSheetOversize
+ ? t("issue.options-disabled-due-to-oversize")
+ : undefined;
+
+ useEffect(() => {
+ if (targets.length === 0) {
+ return;
+ }
+ void fetchTargets(targets, dbGroupStore, databaseStore);
+ }, [databaseStore, dbGroupStore, targets]);
+
+ useEffect(() => {
+ let canceled = false;
+ const sheetName = sheetNameOfSpec(selectedSpec);
+ if (!sheetName) {
+ setSheetStatementValue("");
+ setIsSheetOversize(false);
+ return;
+ }
+ const load = async () => {
+ const uid = extractSheetUID(sheetName);
+ const sheet = uid.startsWith("-")
+ ? getLocalSheetByName(sheetName)
+ : await sheetStore.getOrFetchSheetByName(sheetName);
+ if (!sheet || canceled) return;
+ const statement = getSheetStatement(sheet);
+ setSheetStatementValue(statement);
+ setIsSheetOversize(getStatementSize(statement) < sheet.contentSize);
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [selectedSpec, sheetStore]);
+
+ useEffect(() => {
+ let canceled = false;
+ if (!showInstanceRole || !instanceName) {
+ setInstanceRoles((prev) => (prev.length === 0 ? prev : []));
+ return;
+ }
+ const load = async () => {
+ try {
+ const response =
+ await instanceRoleServiceClientConnect.listInstanceRoles(
+ create(ListInstanceRolesRequestSchema, { parent: instanceName })
+ );
+ if (!canceled) {
+ setInstanceRoles(response.roles.map((role) => role.roleName));
+ }
+ } catch {
+ if (!canceled) setInstanceRoles([]);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [instanceName, showInstanceRole]);
+
+ const persistStatement = useCallback(
+ async (nextStatement: string) => {
+ const sheetName = sheetNameOfSpec(selectedSpec);
+ if (!sheetName) return;
+
+ if (page.isCreating) {
+ const sheet = getLocalSheetByName(sheetName);
+ setLocalSheetStatement(sheet, nextStatement);
+ setSheetStatementState(nextStatement);
+ return;
+ }
+
+ await updateSpecSheetWithStatement(
+ page.plan,
+ selectedSpec,
+ nextStatement
+ );
+ setSheetStatementState(nextStatement);
+ await refreshState();
+ },
+ [page.isCreating, page.plan, refreshState, selectedSpec]
+ );
+
+ const setSheetStatementState = (statement: string) => {
+ setSheetStatementValue(statement);
+ setIsSheetOversize(false);
+ };
+
+ const updatePreBackup = async (enabled: boolean) => {
+ if (selectedSpec.config.case !== "changeDatabaseConfig") return;
+ const planPatch = clone(PlanSchema, page.plan);
+ const spec = planPatch.specs.find((item) => item.id === selectedSpec.id);
+ if (!spec || spec.config.case !== "changeDatabaseConfig") return;
+ spec.config.value.enablePriorBackup = enabled;
+
+ if (page.isCreating) {
+ patchState({ plan: planPatch });
+ return;
+ }
+
+ const response = await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["specs"] },
+ })
+ );
+ patchState({ plan: response });
+ };
+
+ const currentGhostConfig = getGhostConfigFromStatement(sheetStatement);
+ const ghostIssueDatabases = useMemo(() => {
+ return databases.filter((db) => {
+ const instance = getInstanceResource(db);
+ return (
+ !allowGhostForDatabase(instance.engine, instance.engineVersion) ||
+ !db.backupAvailable
+ );
+ });
+ }, [databases]);
+ const preBackupIssueDatabases = useMemo(() => {
+ return databases.filter((db) => {
+ const instance = getInstanceResource(db);
+ return (
+ !BACKUP_AVAILABLE_ENGINES.includes(instance.engine) ||
+ !db.backupAvailable
+ );
+ });
+ }, [databases]);
+ const ghostTooltip = !allowChange
+ ? t("common.read-only")
+ : isSheetOversize
+ ? t("issue.options-disabled-due-to-oversize")
+ : !ghostEnabled && ghostIssueDatabases.length > 0
+ ? t("plan.ghost.requirements-not-met", {
+ databases: ghostIssueDatabases
+ .map((db) => extractDatabaseResourceName(db.name).databaseName)
+ .join(", "),
+ })
+ : undefined;
+ const preBackupTooltip = !allowChange
+ ? t("common.read-only")
+ : !preBackupEnabled && preBackupIssueDatabases.length > 0
+ ? t("plan.pre-backup.requirements-not-met", {
+ databases: preBackupIssueDatabases
+ .map((db) => extractDatabaseResourceName(db.name).databaseName)
+ .join(", "),
+ })
+ : undefined;
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <h3 className="textlabel uppercase">{t("plan.options.self")}</h3>
+ {shouldShow ? (
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <div
+ className={cn(
+ "flex min-h-8 items-center gap-2",
+ !showInstanceRole && "hidden"
+ )}
+ >
+ <span className="inline-flex h-8 shrink-0 items-center whitespace-nowrap text-sm text-control-placeholder">
+ {t("common.role.self")}
+ </span>
+ <Tooltip
+ content={
+ (!allowChange ? t("common.read-only") : oversizeTooltip) ?? ""
+ }
+ >
+ <div>
+ <Select
+ disabled={!allowChange || isSheetOversize}
+ onValueChange={(value) => {
+ void persistStatement(
+ updateRoleSetter(sheetStatement, value || undefined)
+ );
+ }}
+ value={selectedRole}
+ >
+ <SelectTrigger className="w-44" size="sm">
+ <SelectValue>
+ {instanceRoleOptions.find(
+ (option) => option.value === selectedRole
+ )?.label || t("instance.select-database-user")}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {instanceRoleOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </Tooltip>
+ </div>
+ <div
+ className={cn(
+ "flex min-h-8 items-center gap-2",
+ !showTransactionMode && "hidden"
+ )}
+ >
+ <span className="inline-flex h-8 shrink-0 items-center whitespace-nowrap text-sm text-control-placeholder">
+ {t("issue.transaction-mode.label")}
+ </span>
+ <Tooltip content={oversizeTooltip}>
+ <div>
+ <Switch
+ checked={transactionModeChecked}
+ disabled={!allowChange || isSheetOversize}
+ onCheckedChange={(checked) => {
+ void persistStatement(
+ updateTransactionMode(
+ sheetStatement,
+ checked ? "on" : "off"
+ )
+ );
+ }}
+ size="sm"
+ />
+ </div>
+ </Tooltip>
+ </div>
+ <div
+ className={cn(
+ "flex min-h-8 items-center gap-2",
+ !showIsolationLevel && "hidden"
+ )}
+ >
+ <span className="inline-flex h-8 shrink-0 items-center whitespace-nowrap text-sm text-control-placeholder">
+ {t("plan.isolation-level.self")}
+ </span>
+ <Tooltip
+ content={
+ (!allowChange ? t("common.read-only") : oversizeTooltip) ?? ""
+ }
+ >
+ <div>
+ <Select
+ disabled={!allowChange || isSheetOversize}
+ onValueChange={(value) => {
+ void persistStatement(
+ updateIsolationLevel(
+ sheetStatement,
+ value === EMPTY_SELECT_VALUE
+ ? undefined
+ : (value as IsolationLevel) || undefined
+ )
+ );
+ }}
+ value={selectedIsolation || EMPTY_SELECT_VALUE}
+ >
+ <SelectTrigger className="w-44" size="sm">
+ <SelectValue>
+ {[
+ {
+ label: t("plan.isolation-level.read-uncommitted"),
+ value: "READ_UNCOMMITTED",
+ },
+ {
+ label: t("plan.isolation-level.read-committed"),
+ value: "READ_COMMITTED",
+ },
+ {
+ label: t("plan.isolation-level.repeatable-read"),
+ value: "REPEATABLE_READ",
+ },
+ {
+ label: t("plan.isolation-level.serializable"),
+ value: "SERIALIZABLE",
+ },
+ ].find((option) => option.value === selectedIsolation)
+ ?.label || t("plan.select-isolation-level")}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={EMPTY_SELECT_VALUE}>
+ {t("plan.select-isolation-level")}
+ </SelectItem>
+ <SelectItem value="READ_UNCOMMITTED">
+ {t("plan.isolation-level.read-uncommitted")}
+ </SelectItem>
+ <SelectItem value="READ_COMMITTED">
+ {t("plan.isolation-level.read-committed")}
+ </SelectItem>
+ <SelectItem value="REPEATABLE_READ">
+ {t("plan.isolation-level.repeatable-read")}
+ </SelectItem>
+ <SelectItem value="SERIALIZABLE">
+ {t("plan.isolation-level.serializable")}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ </Tooltip>
+ </div>
+ <div
+ className={cn(
+ "flex min-h-8 items-center gap-2",
+ !showPreBackup && "hidden"
+ )}
+ >
+ <span className="inline-flex h-8 shrink-0 items-center whitespace-nowrap text-sm text-control-placeholder">
+ {t("task.prior-backup")}
+ </span>
+ <Tooltip content={preBackupTooltip ?? ""}>
+ <div>
+ <Switch
+ checked={preBackupEnabled}
+ disabled={
+ !allowChange ||
+ (!preBackupEnabled && preBackupIssueDatabases.length > 0)
+ }
+ onCheckedChange={(checked) => {
+ void updatePreBackup(checked);
+ }}
+ size="sm"
+ />
+ </div>
+ </Tooltip>
+ </div>
+ <div
+ className={cn(
+ "flex min-h-8 items-center gap-2",
+ !showGhost && "hidden"
+ )}
+ >
+ <span className="inline-flex h-8 shrink-0 items-center whitespace-nowrap text-sm text-control-placeholder">
+ {t("task.online-migration.self")}
+ </span>
+ <Tooltip content={ghostTooltip ?? ""}>
+ <div>
+ <Switch
+ checked={ghostEnabled}
+ disabled={
+ !allowChange ||
+ isSheetOversize ||
+ (!ghostEnabled && ghostIssueDatabases.length > 0)
+ }
+ onCheckedChange={(checked) => {
+ void persistStatement(
+ updateGhostConfig(
+ sheetStatement,
+ checked
+ ? (currentGhostConfig ?? getDefaultGhostConfig())
+ : undefined
+ )
+ );
+ }}
+ size="sm"
+ />
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm text-control-light">
+ {t("plan.options.no-options-available")}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function TargetsSection({
+ allowEdit,
+ onEdit,
+ selectedSpec,
+}: {
+ allowEdit: boolean;
+ onEdit: () => void;
+ selectedSpec: Plan_Spec;
+}) {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const dbGroupStore = useDBGroupStore();
+ const [showAllTargetsDialog, setShowAllTargetsDialog] = useState(false);
+ const [searchText, setSearchText] = useState("");
+ const [isLoadingTargets, setIsLoadingTargets] = useState(false);
+ const [isLoadingAllTargets, setIsLoadingAllTargets] = useState(false);
+
+ const targets = useMemo(() => {
+ if (selectedSpec.config?.case === "changeDatabaseConfig") {
+ return selectedSpec.config.value.targets ?? [];
+ }
+ return [];
+ }, [selectedSpec]);
+ const visibleTargets = useMemo(
+ () => targets.slice(0, Math.min(DEFAULT_VISIBLE_TARGETS, targets.length)),
+ [targets]
+ );
+ const nonEnvDatabaseNames = useMemo(() => {
+ if (isLoadingTargets) return [];
+ return targets
+ .flatMap((target) => {
+ if (!isValidDatabaseGroupName(target)) return [target];
+ return (
+ dbGroupStore
+ .getDBGroupByName(target)
+ .matchedDatabases?.map((database) => database.name) ?? []
+ );
+ })
+ .filter(
+ (name) => !databaseStore.getDatabaseByName(name).effectiveEnvironment
+ );
+ }, [databaseStore, dbGroupStore, isLoadingTargets, targets]);
+ const filteredTargets = useMemo(
+ () =>
+ filterPlanTargets({
+ getDatabaseDisplayName: (target) => {
+ if (!isValidDatabaseName(target)) return target;
+ const database = databaseStore.getDatabaseByName(target);
+ return extractDatabaseResourceName(database.name).databaseName;
+ },
+ query: searchText,
+ targets,
+ }),
+ [databaseStore, searchText, targets]
+ );
+ const nonEnvWarning =
+ nonEnvDatabaseNames.length === 1
+ ? t("plan.targets.non-env-warning.one", {
+ count: nonEnvDatabaseNames.length,
+ })
+ : t("plan.targets.non-env-warning.other", {
+ count: nonEnvDatabaseNames.length,
+ });
+
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ if (targets.length === 0) {
+ setIsLoadingTargets(false);
+ return;
+ }
+ setIsLoadingTargets(true);
+ try {
+ await fetchTargets(visibleTargets, dbGroupStore, databaseStore);
+ } finally {
+ if (!canceled) setIsLoadingTargets(false);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [databaseStore, dbGroupStore, targets, visibleTargets]);
+
+ useEffect(() => {
+ if (!showAllTargetsDialog) return;
+ let canceled = false;
+ setSearchText("");
+ const load = async () => {
+ setIsLoadingAllTargets(true);
+ try {
+ await fetchTargets(targets, dbGroupStore, databaseStore);
+ } finally {
+ if (!canceled) setIsLoadingAllTargets(false);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [databaseStore, dbGroupStore, showAllTargetsDialog, targets]);
+
+ return (
+ <>
+ <div className="flex flex-col gap-y-1">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-1">
+ <span className="textlabel uppercase">
+ {t("plan.targets.title")}
+ </span>
+ {targets.length > 1 && (
+ <span className="textlabel text-control-light">
+ ({targets.length})
+ </span>
+ )}
+ </div>
+ {allowEdit && (
+ <Button onClick={onEdit} size="xs" variant="outline">
+ {t("common.edit")}
+ </Button>
+ )}
+ </div>
+ {!isLoadingTargets && nonEnvDatabaseNames.length > 0 && (
+ <Alert className="px-3 py-2" variant="warning">
+ <div>{nonEnvWarning}</div>
+ <div className="mt-1 flex flex-col gap-1 text-sm">
+ {nonEnvDatabaseNames.map((name) => (
+ <div key={name} className="flex items-center gap-2">
+ <span className="h-1 w-1 shrink-0 rounded-full bg-current" />
+ <DatabaseTarget target={name} />
+ </div>
+ ))}
+ </div>
+ </Alert>
+ )}
+ {isLoadingTargets ? (
+ <div className="flex items-center justify-center py-2">
+ <div className="h-5 w-5 animate-spin rounded-full border-2 border-control-border border-t-accent" />
+ </div>
+ ) : targets.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-2">
+ {visibleTargets.map((target) =>
+ isValidDatabaseName(target) ? (
+ <div
+ key={target}
+ className="inline-flex cursor-default items-center gap-x-1 rounded-lg border px-2 py-1"
+ >
+ <DatabaseTarget showEnvironment target={target} />
+ </div>
+ ) : isValidDatabaseGroupName(target) ? (
+ <div key={target} className="rounded-lg border px-2 py-1">
+ <DatabaseGroupTarget className="py-1" target={target} />
+ </div>
+ ) : (
+ <div
+ key={target}
+ className="inline-flex cursor-default items-center gap-x-1 rounded-lg border px-2 py-1"
+ >
+ <span className="text-sm text-control-placeholder">
+ {target}
+ </span>
+ </div>
+ )
+ )}
+ {targets.length > DEFAULT_VISIBLE_TARGETS && (
+ <Button
+ className="h-7 px-2"
+ onClick={() => setShowAllTargetsDialog(true)}
+ size="xs"
+ type="button"
+ variant="ghost"
+ >
+ {t("plan.targets.view-all", { count: targets.length })}
+ </Button>
+ )}
+ </div>
+ ) : (
+ <div className="py-1 text-sm text-control-light">
+ {t("plan.targets.no-targets-found")}
+ </div>
+ )}
+ </div>
+
+ <Sheet open={showAllTargetsDialog} onOpenChange={setShowAllTargetsDialog}>
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>
+ {t("plan.targets.title")} ({targets.length})
+ </SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4 px-4 pb-4">
+ <SearchInput
+ placeholder={t("common.search")}
+ value={searchText}
+ onChange={(event) => setSearchText(event.target.value)}
+ />
+ <div className="flex-1 overflow-hidden">
+ {isLoadingAllTargets ? (
+ <div className="flex h-full items-center justify-center">
+ <div className="h-5 w-5 animate-spin rounded-full border-2 border-control-border border-t-accent" />
+ </div>
+ ) : filteredTargets.length > 0 ? (
+ <div className="h-full overflow-y-auto">
+ <div className="flex flex-wrap gap-2">
+ {filteredTargets.map((target) =>
+ isValidDatabaseName(target) ? (
+ <div
+ key={target}
+ className="inline-flex cursor-default items-center gap-x-1 rounded-lg border px-2 py-1 transition-all"
+ >
+ <DatabaseTarget showEnvironment target={target} />
+ </div>
+ ) : isValidDatabaseGroupName(target) ? (
+ <div
+ key={target}
+ className="rounded-lg border px-2 py-1 transition-all"
+ >
+ <DatabaseGroupTarget target={target} />
+ </div>
+ ) : (
+ <div
+ key={target}
+ className="inline-flex cursor-default items-center gap-x-1 rounded-lg border px-2 py-1 transition-all"
+ >
+ <span className="text-sm">{target}</span>
+ </div>
+ )
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="flex h-full items-center justify-center text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
+
+function TargetSelectorSheet({
+ currentTargets,
+ onConfirm,
+ onOpenChange,
+ open,
+ projectName,
+ title,
+}: {
+ currentTargets: string[];
+ onConfirm: (targets: string[]) => void | Promise<void>;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+ projectName: string;
+ title?: string;
+}) {
+ const { t } = useTranslation();
+ const [changeSource, setChangeSource] = useState<"DATABASE" | "GROUP">(
+ "DATABASE"
+ );
+ const [selectedDatabaseNames, setSelectedDatabaseNames] = useState<
+ Set<string>
+ >(new Set());
+ const [selectedDatabaseGroup, setSelectedDatabaseGroup] = useState<
+ string | undefined
+ >();
+
+ useEffect(() => {
+ if (!open) {
+ return;
+ }
+ const firstTarget = currentTargets[0];
+ if (firstTarget && isValidDatabaseGroupName(firstTarget)) {
+ setChangeSource("GROUP");
+ setSelectedDatabaseGroup(firstTarget);
+ setSelectedDatabaseNames(new Set());
+ return;
+ }
+ setChangeSource("DATABASE");
+ setSelectedDatabaseNames(new Set(currentTargets));
+ setSelectedDatabaseGroup(undefined);
+ }, [currentTargets, open]);
+
+ const canSubmit =
+ changeSource === "DATABASE"
+ ? selectedDatabaseNames.size > 0
+ : Boolean(selectedDatabaseGroup);
+
+ return (
+ <Sheet onOpenChange={onOpenChange} open={open}>
+ <SheetContent className="w-screen sm:w-[80vw]" width="wide">
+ <SheetHeader>
+ <SheetTitle>{title ?? t("plan.select-targets")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ <DatabaseAndGroupSelector
+ changeSource={changeSource}
+ onChangeSourceChange={setChangeSource}
+ onSelectedDatabaseGroupChange={setSelectedDatabaseGroup}
+ onSelectedDatabaseNamesChange={setSelectedDatabaseNames}
+ projectName={projectName}
+ selectedDatabaseGroup={selectedDatabaseGroup}
+ selectedDatabaseNames={selectedDatabaseNames}
+ />
+ </SheetBody>
+ <SheetFooter>
+ <Button onClick={() => onOpenChange(false)} variant="ghost">
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={!canSubmit}
+ onClick={() =>
+ void onConfirm(
+ changeSource === "DATABASE"
+ ? [...selectedDatabaseNames]
+ : selectedDatabaseGroup
+ ? [selectedDatabaseGroup]
+ : []
+ )
+ }
+ >
+ {t("common.confirm")}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function DatabaseAndGroupSelector({
+ projectName,
+ changeSource,
+ onChangeSourceChange,
+ selectedDatabaseNames,
+ onSelectedDatabaseNamesChange,
+ selectedDatabaseGroup,
+ onSelectedDatabaseGroupChange,
+}: {
+ projectName: string;
+ changeSource: "DATABASE" | "GROUP";
+ onChangeSourceChange: (source: "DATABASE" | "GROUP") => void;
+ selectedDatabaseNames: Set<string>;
+ onSelectedDatabaseNamesChange: (names: Set<string>) => void;
+ selectedDatabaseGroup: string | undefined;
+ onSelectedDatabaseGroupChange: (name: string | undefined) => void;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ <div className="flex border-b border-control-border">
+ <button
+ type="button"
+ className={cn(
+ "border-b-2 -mb-px px-4 py-2 text-sm font-medium transition-colors",
+ changeSource === "DATABASE"
+ ? "border-accent text-accent"
+ : "border-transparent text-control-light hover:text-control"
+ )}
+ onClick={() => onChangeSourceChange("DATABASE")}
+ >
+ <span className="inline-flex items-center gap-x-1.5">
+ <DatabaseIcon className="size-4" />
+ {t("common.databases")}
+ </span>
+ </button>
+ <button
+ type="button"
+ className={cn(
+ "border-b-2 -mb-px px-4 py-2 text-sm font-medium transition-colors",
+ changeSource === "GROUP"
+ ? "border-accent text-accent"
+ : "border-transparent text-control-light hover:text-control"
+ )}
+ onClick={() => onChangeSourceChange("GROUP")}
+ >
+ <span className="inline-flex items-center gap-x-1.5">
+ <FolderTree className="size-4" />
+ {t("common.database-group")}
+ </span>
+ </button>
+ </div>
+
+ {changeSource === "DATABASE" ? (
+ <DatabaseSelector
+ onSelectedNamesChange={onSelectedDatabaseNamesChange}
+ projectName={projectName}
+ selectedNames={selectedDatabaseNames}
+ />
+ ) : (
+ <DatabaseGroupSelector
+ onSelectedGroupChange={onSelectedDatabaseGroupChange}
+ projectName={projectName}
+ selectedGroup={selectedDatabaseGroup}
+ />
+ )}
+ </div>
+ );
+}
+
+function DatabaseSelector({
+ projectName,
+ selectedNames,
+ onSelectedNamesChange,
+}: {
+ projectName: string;
+ selectedNames: Set<string>;
+ onSelectedNamesChange: (names: Set<string>) => void;
+}) {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const [databases, setDatabases] = useState<Database[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [hasMore, setHasMore] = useState(false);
+ const [isFetchingMore, setIsFetchingMore] = useState(false);
+ const [query, setQuery] = useState("");
+ const [pageSize] = useSessionPageSize("bb.plan-detail-db-selector");
+ const nextPageTokenRef = useRef("");
+ const fetchIdRef = useRef(0);
+
+ const doFetch = useCallback(
+ async (isRefresh: boolean) => {
+ const currentFetchId = ++fetchIdRef.current;
+ if (isRefresh) {
+ setLoading(true);
+ } else {
+ setIsFetchingMore(true);
+ }
+ try {
+ const token = isRefresh ? "" : nextPageTokenRef.current;
+ const result = await databaseStore.fetchDatabases({
+ parent: projectName,
+ pageSize,
+ pageToken: token || undefined,
+ filter: { query },
+ });
+ if (currentFetchId !== fetchIdRef.current) return;
+ setDatabases((prev) =>
+ isRefresh ? result.databases : [...prev, ...result.databases]
+ );
+ nextPageTokenRef.current = result.nextPageToken;
+ setHasMore(Boolean(result.nextPageToken));
+ } finally {
+ if (currentFetchId === fetchIdRef.current) {
+ setLoading(false);
+ setIsFetchingMore(false);
+ }
+ }
+ },
+ [databaseStore, pageSize, projectName, query]
+ );
+
+ useEffect(() => {
+ const timer = setTimeout(() => void doFetch(true), 300);
+ return () => clearTimeout(timer);
+ }, [doFetch]);
+
+ const toggleDatabase = (name: string) => {
+ const next = new Set(selectedNames);
+ if (next.has(name)) next.delete(name);
+ else next.add(name);
+ onSelectedNamesChange(next);
+ };
+
+ const allSelected =
+ databases.length > 0 && databases.every((db) => selectedNames.has(db.name));
+ const someSelected =
+ databases.some((db) => selectedNames.has(db.name)) && !allSelected;
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <SearchInput
+ placeholder={t("database.filter-database")}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ />
+
+ {loading ? (
+ <div className="flex justify-center py-8 text-control-light">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ ) : databases.length === 0 ? (
+ <div className="flex justify-center py-8 text-control-light">
+ {t("common.no-data")}
+ </div>
+ ) : (
+ <>
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b text-left text-control-light">
+ <th className="w-8 py-2 pr-2">
+ <input
+ type="checkbox"
+ checked={allSelected}
+ ref={(el) => {
+ if (el) el.indeterminate = someSelected;
+ }}
+ onChange={() =>
+ onSelectedNamesChange(
+ allSelected
+ ? new Set()
+ : new Set(databases.map((db) => db.name))
+ )
+ }
+ className="accent-accent"
+ />
+ </th>
+ <th className="py-2 pr-4 font-medium">
+ {t("common.database")}
+ </th>
+ <th className="py-2 pr-4 font-medium">
+ {t("common.instance")}
+ </th>
+ <th className="py-2 pr-4 font-medium">
+ {t("common.environment")}
+ </th>
+ <th className="py-2 pr-4 font-medium whitespace-nowrap">
+ {t("common.status")}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {databases.map((db) => {
+ const { databaseName } = extractDatabaseResourceName(db.name);
+ const inst = getInstanceResource(db);
+ const env = getDatabaseEnvironment(db);
+ const isSelected = selectedNames.has(db.name);
+ return (
+ <tr
+ key={db.name}
+ className={cn(
+ "cursor-pointer border-b hover:bg-control-bg",
+ isSelected && "bg-accent/5"
+ )}
+ onClick={() => toggleDatabase(db.name)}
+ >
+ <td className="py-2 pr-2">
+ <input
+ type="checkbox"
+ checked={isSelected}
+ readOnly
+ className="accent-accent"
+ />
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex items-center gap-x-1.5">
+ {inst && EngineIconPath[inst.engine] && (
+ <img
+ className="size-4 shrink-0"
+ src={EngineIconPath[inst.engine]}
+ alt=""
+ />
+ )}
+ <span>{databaseName}</span>
+ </div>
+ </td>
+ <td className="py-2 pr-4">{inst?.title}</td>
+ <td className="py-2 pr-4">
+ {env && <EnvironmentLabel environmentName={env.name} />}
+ </td>
+ <td className="py-2 pr-4">
+ {db.syncStatus === SyncStatus.FAILED ? (
+ <XCircle className="size-4 text-error" />
+ ) : (
+ <CheckCircle className="size-4 text-success" />
+ )}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ {hasMore && (
+ <div className="flex justify-center">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={isFetchingMore}
+ onClick={() => void doFetch(false)}
+ >
+ {isFetchingMore ? t("common.loading") : t("common.load-more")}
+ </Button>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
+
+function DatabaseGroupSelector({
+ projectName,
+ selectedGroup,
+ onSelectedGroupChange,
+}: {
+ projectName: string;
+ selectedGroup: string | undefined;
+ onSelectedGroupChange: (name: string | undefined) => void;
+}) {
+ const { t } = useTranslation();
+ const dbGroupStore = useDBGroupStore();
+ const [groups, setGroups] = useState<DatabaseGroup[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ setLoading(true);
+ dbGroupStore
+ .fetchDBGroupListByProjectName(projectName, DatabaseGroupView.BASIC)
+ .then((result) => setGroups(result))
+ .finally(() => setLoading(false));
+ }, [dbGroupStore, projectName]);
+
+ if (loading) {
+ return (
+ <div className="flex justify-center py-8 text-control-light">
+ <Loader2 className="size-5 animate-spin" />
+ </div>
+ );
+ }
+
+ if (groups.length === 0) {
+ return (
+ <div className="flex justify-center py-8 text-control-light">
+ {t("common.no-data")}
+ </div>
+ );
+ }
+
+ return (
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b text-left text-control-light">
+ <th className="w-8 py-2 pr-2" />
+ <th className="py-2 pr-4 font-medium">
+ {t("common.database-group")}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {groups.map((group) => {
+ const isSelected = selectedGroup === group.name;
+ return (
+ <tr
+ key={group.name}
+ className={cn(
+ "cursor-pointer border-b hover:bg-control-bg",
+ isSelected && "bg-accent/5"
+ )}
+ onClick={() =>
+ onSelectedGroupChange(isSelected ? undefined : group.name)
+ }
+ >
+ <td className="py-2 pr-2">
+ <input
+ type="radio"
+ checked={isSelected}
+ readOnly
+ className="accent-accent"
+ />
+ </td>
+ <td className="py-2 pr-4">
+ <div className="flex items-center gap-x-1.5">
+ <FolderTree className="size-4 shrink-0 text-control-light" />
+ <span>{extractDatabaseGroupName(group.name)}</span>
+ </div>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ );
+}
+
+export function DatabaseTarget({
+ showEnvironment = false,
+ target,
+}: {
+ showEnvironment?: boolean;
+ target: string;
+}) {
+ const environmentStore = useEnvironmentV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const database = databaseStore.getDatabaseByName(target);
+ const environment = database.effectiveEnvironment
+ ? environmentStore.getEnvironmentByName(database.effectiveEnvironment)
+ : undefined;
+ const instance = getInstanceResource(database);
+ const databaseName = extractDatabaseResourceName(database.name).databaseName;
+ const instanceName = instance.title;
+
+ return (
+ <div className="flex min-w-0 items-center truncate text-sm">
+ <img
+ alt=""
+ className="mr-1 h-4 w-4 shrink-0"
+ src={EngineIconPath[instance.engine]}
+ />
+ {showEnvironment && environment?.title && (
+ <span className="mr-1 truncate text-control-placeholder">
+ {environment.title}
+ </span>
+ )}
+ <span className="truncate text-control-light">{instanceName}</span>
+ <ChevronRight className="h-4 w-4 shrink-0 text-control-light/80" />
+ <span className="truncate text-control">{databaseName}</span>
+ </div>
+ );
+}
+
+export function DatabaseGroupTarget({
+ className,
+ target,
+}: {
+ className?: string;
+ target: string;
+}) {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const dbGroupStore = useDBGroupStore();
+ const dbGroup = dbGroupStore.getDBGroupByName(target, DatabaseGroupView.FULL);
+ const matchedDatabases = dbGroup.matchedDatabases ?? [];
+ const { extraDatabases, inlineDatabases } =
+ splitInlineDatabases(matchedDatabases);
+ const groupName = extractDatabaseGroupName(target);
+
+ useEffect(() => {
+ const load = async () => {
+ const group = await dbGroupStore.getOrFetchDBGroupByName(target, {
+ view: DatabaseGroupView.FULL,
+ silent: true,
+ });
+ const databaseNames =
+ group.matchedDatabases?.map((database) => database.name) ?? [];
+ if (databaseNames.length > 0) {
+ await databaseStore.batchGetOrFetchDatabases(databaseNames);
+ }
+ };
+ void load();
+ }, [databaseStore, dbGroupStore, target]);
+
+ const route = {
+ name: PROJECT_V1_ROUTE_DATABASE_GROUP_DETAIL,
+ params: getDatabaseGroupRouteParams({
+ databaseGroupName: getProjectNameAndDatabaseGroupName(target)[1],
+ projectName: getProjectNameAndDatabaseGroupName(target)[0],
+ }),
+ };
+ const showExternalLink = isValidDatabaseGroupName(dbGroup.name);
+
+ return (
+ <div className={cn("flex w-full flex-col gap-2", className)}>
+ <div className="flex items-center gap-x-2">
+ <FolderTree className="h-5 w-5 shrink-0 text-control" />
+ <Badge className="px-2 py-0 text-xs font-medium" variant="default">
+ {t("common.database-group")}
+ </Badge>
+ <span className="min-w-0 truncate text-sm text-control">
+ {groupName}
+ </span>
+ {showExternalLink && (
+ <a
+ className="flex items-center opacity-60 hover:opacity-100"
+ href={router.resolve(route).href}
+ rel="noreferrer"
+ target="_blank"
+ >
+ <ExternalLink className="h-4 w-4" />
+ </a>
+ )}
+ </div>
+ {matchedDatabases.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2 pl-7">
+ {inlineDatabases.map((database) => (
+ <div
+ key={database.name}
+ className="inline-flex cursor-default items-center gap-x-1 rounded-lg border bg-gray-50 px-2 py-1 transition-all"
+ >
+ <DatabaseTarget showEnvironment target={database.name} />
+ </div>
+ ))}
+ {extraDatabases.length > 0 && (
+ <Tooltip
+ content={
+ <div className="flex max-h-64 flex-col gap-y-1 overflow-y-auto py-1">
+ {extraDatabases.map((database) => (
+ <div key={database.name} className="py-1">
+ <DatabaseTarget showEnvironment target={database.name} />
+ </div>
+ ))}
+ </div>
+ }
+ >
+ <span className="cursor-pointer text-xs text-accent">
+ {t("common.n-more", { n: extraDatabases.length })}
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function parseStatement(statement: string): {
+ transactionMode?: "on" | "off";
+ isolationLevel?: IsolationLevel;
+ ghostEnabled: boolean;
+ role?: string;
+} {
+ const transactionMode = statement
+ .match(/^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/im)?.[1]
+ ?.toLowerCase() as "on" | "off" | undefined;
+ const isolationLevel = statement
+ .match(
+ /^\s*--\s*txn-isolation\s*=\s*(READ\s+UNCOMMITTED|READ\s+COMMITTED|REPEATABLE\s+READ|SERIALIZABLE)\s*$/im
+ )?.[1]
+ ?.toUpperCase()
+ .replace(/\s+/g, "_") as IsolationLevel | undefined;
+ const ghostEnabled =
+ /^\s*--\s*gh-ost\s*=\s*(\{[^}]*\})\s*(?:\/\*.*\*\/)?\s*$/im.test(statement);
+ const role = statement.match(
+ /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/
+ )?.[1];
+ return {
+ ghostEnabled,
+ isolationLevel,
+ role,
+ transactionMode,
+ };
+}
+
+async function fetchTargets(
+ targets: string[],
+ dbGroupStore: ReturnType<typeof useDBGroupStore>,
+ databaseStore: ReturnType<typeof useDatabaseV1Store>
+) {
+ await Promise.all(
+ targets.map(async (target) => {
+ if (isValidDatabaseName(target)) {
+ await databaseStore.getOrFetchDatabaseByName(target, true);
+ return;
+ }
+ if (isValidDatabaseGroupName(target)) {
+ const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(target, {
+ silent: true,
+ view: DatabaseGroupView.FULL,
+ });
+ const databaseNames =
+ dbGroup.matchedDatabases?.map((database) => database.name) ?? [];
+ if (databaseNames.length > 0) {
+ await databaseStore.batchGetOrFetchDatabases(databaseNames);
+ }
+ }
+ })
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx
new file mode 100644
index 0000000000..260c13b18a
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailChecks.tsx
@@ -0,0 +1,511 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ AlertCircle,
+ CheckCircle,
+ CircleQuestionMark,
+ FileCode,
+ Loader2,
+ Play,
+ SearchCode,
+ Shield,
+ XCircle,
+} from "lucide-react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { planServiceClientConnect } 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 { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import {
+ projectNamePrefix,
+ pushNotification,
+ useCurrentUserV1,
+ useProjectV1Store,
+} from "@/store";
+import { extractUserEmail } from "@/store/modules/v1/common";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ GetPlanCheckRunRequestSchema,
+ GetPlanRequestSchema,
+ type PlanCheckRun,
+ type PlanCheckRun_Result,
+ PlanCheckRun_Result_Type,
+ RunPlanChecksRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import { extractDatabaseResourceName } from "@/utils/v1/database";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+import {
+ getFilteredResultGroups,
+ getPlanCheckSummary,
+ type PlanCheckSummary,
+ planCheckRunListForSpec,
+} from "../utils/planCheck";
+
+const PAGE_SIZE = 10;
+
+export function PlanDetailChecks({
+ selectedSpec,
+}: {
+ selectedSpec: Plan_Spec;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState } = page;
+ const projectStore = useProjectV1Store();
+ const currentUser = useCurrentUserV1().value;
+ const [isRunningChecks, setIsRunningChecks] = useState(false);
+ const [selectedResultStatus, setSelectedResultStatus] = useState<
+ Advice_Level | undefined
+ >();
+ const projectName = `${projectNamePrefix}${page.projectId}`;
+ const project = projectStore.getProjectByName(projectName);
+ const filteredPlanCheckRuns = useMemo(
+ () => planCheckRunListForSpec(page.planCheckRuns, selectedSpec),
+ [page.planCheckRuns, selectedSpec]
+ );
+ const summary = useMemo(
+ () => getPlanCheckSummary(filteredPlanCheckRuns),
+ [filteredPlanCheckRuns]
+ );
+ 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 () => {
+ const nextPlan = await planServiceClientConnect.getPlan(
+ create(GetPlanRequestSchema, {
+ name: page.plan.name,
+ })
+ );
+
+ let nextPlanCheckRuns: PlanCheckRun[] = [];
+ try {
+ const response = await planServiceClientConnect.getPlanCheckRun(
+ create(GetPlanCheckRunRequestSchema, {
+ name: `${page.plan.name}/planCheckRun`,
+ })
+ );
+ nextPlanCheckRuns = [response];
+ } catch {
+ nextPlanCheckRuns = [];
+ }
+
+ 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 (
+ <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>
+ {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 min-w-0 flex-wrap items-center gap-2 text-sm">
+ {summary.total > 0 ? (
+ <StatusCount
+ selectedStatus={selectedResultStatus}
+ summary={summary}
+ onSelectStatus={setSelectedResultStatus}
+ />
+ ) : (
+ <span className="text-sm text-control-placeholder">
+ {t("plan.overview.no-checks")}
+ </span>
+ )}
+ </div>
+
+ <ChecksDialog
+ onClose={() => setSelectedResultStatus(undefined)}
+ open={selectedResultStatus !== undefined}
+ planCheckRuns={filteredPlanCheckRuns}
+ refreshChecks={refreshChecks}
+ status={selectedResultStatus}
+ />
+ </div>
+ );
+}
+
+function StatusCount({
+ onSelectStatus,
+ selectedStatus,
+ summary,
+}: {
+ onSelectStatus: (status: Advice_Level | undefined) => void;
+ selectedStatus?: Advice_Level;
+ summary: PlanCheckSummary;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex min-w-0 flex-wrap items-center gap-3 text-sm">
+ {summary.running > 0 && (
+ <div className="flex items-center gap-1 text-control">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ <span>{t("common.running")}</span>
+ </div>
+ )}
+ {[
+ {
+ count: summary.error,
+ icon: <XCircle className="h-5 w-5" />,
+ status: Advice_Level.ERROR,
+ textClass: "text-error",
+ },
+ {
+ count: summary.warning,
+ icon: <AlertCircle className="h-5 w-5" />,
+ status: Advice_Level.WARNING,
+ textClass: "text-warning",
+ },
+ {
+ count: summary.success,
+ icon: <CheckCircle className="h-5 w-5" />,
+ status: Advice_Level.SUCCESS,
+ textClass: "text-success",
+ },
+ ]
+ .filter((item) => item.count > 0)
+ .map((item) => (
+ <button
+ key={item.status}
+ className={cn(
+ "flex items-center gap-1",
+ item.textClass,
+ selectedStatus === item.status
+ ? "rounded-lg bg-gray-100 px-2 py-1"
+ : selectedStatus !== undefined
+ ? "px-2 py-1"
+ : ""
+ )}
+ onClick={() =>
+ onSelectStatus(
+ selectedStatus === item.status ? undefined : item.status
+ )
+ }
+ type="button"
+ >
+ {item.icon}
+ <span>
+ {item.status === Advice_Level.ERROR
+ ? t("common.error")
+ : item.status === Advice_Level.WARNING
+ ? t("common.warning")
+ : t("common.success")}
+ </span>
+ <span>{item.count}</span>
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function ChecksDialog({
+ onClose,
+ open,
+ planCheckRuns,
+ refreshChecks,
+ status,
+}: {
+ onClose: () => void;
+ open: boolean;
+ planCheckRuns: PlanCheckRun[];
+ refreshChecks: () => Promise<PlanCheckRun[]>;
+ status?: Advice_Level;
+}) {
+ const { t } = useTranslation();
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const [selectedStatus, setSelectedStatus] = useState<
+ Advice_Level | undefined
+ >(status);
+ const [displayCount, setDisplayCount] = useState(PAGE_SIZE);
+ const summary = useMemo(
+ () => getPlanCheckSummary(planCheckRuns),
+ [planCheckRuns]
+ );
+
+ useEffect(() => {
+ if (!open) return;
+ setSelectedStatus(status);
+ setDisplayCount(PAGE_SIZE);
+ const refresh = async () => {
+ try {
+ setIsRefreshing(true);
+ await refreshChecks();
+ } finally {
+ setIsRefreshing(false);
+ }
+ };
+ void refresh();
+ }, [open, refreshChecks, status]);
+
+ const filteredResultGroups = useMemo(() => {
+ return getFilteredResultGroups({
+ includeRunFailure: true,
+ planCheckRuns,
+ runFailureContent: t("common.failed"),
+ runFailureTitle: t("common.failed"),
+ selectedStatus,
+ });
+ }, [planCheckRuns, selectedStatus, t]);
+
+ const displayedResultGroups = filteredResultGroups.slice(0, displayCount);
+ const remainingCount = Math.max(
+ filteredResultGroups.length - displayCount,
+ 0
+ );
+
+ 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 && (
+ <StatusCount
+ selectedStatus={selectedStatus}
+ summary={summary}
+ onSelectStatus={setSelectedStatus}
+ />
+ )}
+ {filteredResultGroups.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-12 text-control-light">
+ {isRefreshing ? (
+ <Loader2 className="mb-4 h-12 w-12 animate-spin opacity-50" />
+ ) : (
+ <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) => (
+ <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">
+ {checkTypeIcon(group.type)}
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">
+ {checkTypeLabel(group.type, t)}
+ </span>
+ {checkTypeDescription(group.type, t) && (
+ <Tooltip
+ content={checkTypeDescription(group.type, t)}
+ >
+ <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>
+ <div className="min-w-0 max-w-[50%] text-sm text-control-light">
+ {group.target ? (
+ <span className="truncate">
+ {
+ extractDatabaseResourceName(group.target)
+ .databaseName
+ }
+ </span>
+ ) : null}
+ </div>
+ </div>
+ <div className="flex flex-col gap-y-2 pl-8">
+ {group.results.map((result, index) => (
+ <CheckResultCard
+ key={`${group.key}-${index}`}
+ result={result}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ {remainingCount > 0 && (
+ <div className="flex justify-center py-4">
+ <button
+ className="text-sm text-accent hover:underline"
+ onClick={() =>
+ setDisplayCount((count) => count + PAGE_SIZE)
+ }
+ type="button"
+ >
+ {t("common.load-more")} ({remainingCount})
+ </button>
+ </div>
+ )}
+ </>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+function CheckResultCard({ 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;
+
+ 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">{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>
+ );
+}
+
+function checkTypeIcon(type: PlanCheckRun_Result_Type) {
+ const className = "h-5 w-5 text-control-light";
+ switch (type) {
+ case PlanCheckRun_Result_Type.STATEMENT_ADVISE:
+ return <SearchCode className={className} />;
+ case PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT:
+ return <FileCode className={className} />;
+ case PlanCheckRun_Result_Type.GHOST_SYNC:
+ return <Shield className={className} />;
+ default:
+ return <FileCode className={className} />;
+ }
+}
+
+function checkTypeLabel(
+ type: PlanCheckRun_Result_Type,
+ t: (key: string) => string
+) {
+ switch (type) {
+ case PlanCheckRun_Result_Type.STATEMENT_ADVISE:
+ return t("task.check-type.sql-review.self");
+ case PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT:
+ return t("task.check-type.affected-rows.self");
+ case PlanCheckRun_Result_Type.GHOST_SYNC:
+ return t("task.online-migration.self");
+ default:
+ return t("plan.navigator.checks");
+ }
+}
+
+function checkTypeDescription(
+ type: PlanCheckRun_Result_Type,
+ t: (key: string) => string
+) {
+ switch (type) {
+ case PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT:
+ return t("task.check-type.affected-rows.description");
+ default:
+ return "";
+ }
+}
+
+function statusIcon(status: Advice_Level) {
+ switch (status) {
+ case Advice_Level.ERROR:
+ return <XCircle className="h-4 w-4 text-error" />;
+ case Advice_Level.WARNING:
+ return <AlertCircle className="h-4 w-4 text-warning" />;
+ default:
+ return <CheckCircle className="h-4 w-4 text-success" />;
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
new file mode 100644
index 0000000000..8f695a56e2
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx
@@ -0,0 +1,432 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ CheckCircle2,
+ CircleAlert,
+ Clock3,
+ Loader2,
+ MinusCircle,
+} from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { Alert, AlertTitle } from "@/react/components/ui/alert";
+import { Button } from "@/react/components/ui/button";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { router } from "@/router";
+import { buildPlanDeployRouteFromRolloutName } from "@/router/dashboard/projectV1RouteHelpers";
+import { pushNotification } from "@/store";
+import { State } from "@/types/proto-es/v1/common_pb";
+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
+import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+import { isApprovalCompleted } from "../../issue-detail/utils/approval";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+
+export function PlanDetailDeployFuture() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [creatingRollout, setCreatingRollout] = useState(false);
+ const [rolloutConfirmOpen, setRolloutConfirmOpen] = useState(false);
+ const [bypassWarnings, setBypassWarnings] = useState(false);
+
+ const planChecksFailed = useMemo(() => {
+ const counts = page.plan.planCheckRunStatusCount ?? {};
+ return (
+ (counts[Advice_Level[Advice_Level.ERROR]] ?? 0) > 0 ||
+ (counts.FAILED ?? 0) > 0
+ );
+ }, [page.plan.planCheckRunStatusCount]);
+ const planChecksRunning = useMemo(() => {
+ const counts = page.plan.planCheckRunStatusCount ?? {};
+ return (counts.RUNNING ?? 0) > 0;
+ }, [page.plan.planCheckRunStatusCount]);
+ const issueApproved = isApprovalCompleted(page.issue);
+ const canCreateRollout = Boolean(
+ page.issue &&
+ !page.plan.hasRollout &&
+ page.plan.state === State.ACTIVE &&
+ page.issue.status === IssueStatus.OPEN &&
+ page.projectCanCreateRollout
+ );
+ const showManualCreateRolloutHint = Boolean(
+ page.issue &&
+ !page.plan.hasRollout &&
+ page.plan.state === State.ACTIVE &&
+ page.issue.status === IssueStatus.OPEN &&
+ !(page.projectRequireIssueApproval && !issueApproved) &&
+ !(page.projectRequirePlanCheckNoError && planChecksFailed) &&
+ (!page.projectRequireIssueApproval ||
+ !page.projectRequirePlanCheckNoError)
+ );
+ const manualCreateRolloutDescription = canCreateRollout
+ ? t("plan.phase.deploy-manual-create-description")
+ : t("plan.phase.deploy-manual-create-description-readonly");
+ const errorMessages = useMemo(() => {
+ const messages: string[] = [];
+ if (!page.projectCanCreateRollout) {
+ messages.push(
+ t("common.missing-required-permission", {
+ permissions: "bb.rollouts.create",
+ })
+ );
+ }
+ if (page.projectRequireIssueApproval && !issueApproved) {
+ messages.push(
+ t("project.settings.issue-related.require-issue-approval.description")
+ );
+ }
+ if (page.projectRequirePlanCheckNoError && planChecksFailed) {
+ messages.push(
+ t(
+ "project.settings.issue-related.require-plan-check-no-error.description"
+ )
+ );
+ }
+ return messages;
+ }, [
+ issueApproved,
+ page.projectCanCreateRollout,
+ page.projectRequireIssueApproval,
+ page.projectRequirePlanCheckNoError,
+ planChecksFailed,
+ t,
+ ]);
+ const warningMessages = useMemo(() => {
+ const messages: string[] = [];
+ if (!page.projectRequireIssueApproval && !issueApproved) {
+ messages.push(
+ t("project.settings.issue-related.require-issue-approval.description")
+ );
+ }
+ if (planChecksRunning) {
+ messages.push(
+ t(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"
+ )
+ );
+ } else if (!page.projectRequirePlanCheckNoError && planChecksFailed) {
+ messages.push(
+ t(
+ "project.settings.issue-related.require-plan-check-no-error.description"
+ )
+ );
+ }
+ return messages;
+ }, [
+ issueApproved,
+ page.projectRequireIssueApproval,
+ page.projectRequirePlanCheckNoError,
+ planChecksFailed,
+ planChecksRunning,
+ t,
+ ]);
+ const createRolloutDisabled =
+ creatingRollout ||
+ errorMessages.length > 0 ||
+ (warningMessages.length > 0 && !bypassWarnings);
+
+ const createRollout = async () => {
+ if (creatingRollout) return;
+ try {
+ setCreatingRollout(true);
+ const createdRollout = await rolloutServiceClientConnect.createRollout(
+ create(CreateRolloutRequestSchema, {
+ parent: page.plan.name,
+ })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.created"),
+ });
+ await page.refreshState();
+ setRolloutConfirmOpen(false);
+ void router.push(
+ buildPlanDeployRouteFromRolloutName(createdRollout.name)
+ );
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setCreatingRollout(false);
+ }
+ };
+
+ const requirementItems = [
+ page.projectRequirePlanCheckNoError
+ ? planChecksRunning
+ ? {
+ key: "checks",
+ label: t("plan.phase.deploy-checks-must-pass"),
+ description: t("plan.phase.deploy-checks-running"),
+ tagLabel: t("common.in-progress"),
+ statusClass: "text-warning",
+ icon: Clock3,
+ iconClass: "text-warning/80",
+ required: true,
+ }
+ : planChecksFailed
+ ? {
+ key: "checks",
+ label: t("plan.phase.deploy-checks-must-pass"),
+ description: t("plan.phase.deploy-checks-blocked"),
+ tagLabel: t("common.failed"),
+ statusClass: "text-error",
+ icon: CircleAlert,
+ iconClass: "text-error/80",
+ required: true,
+ }
+ : {
+ key: "checks",
+ label: t("plan.phase.deploy-checks-must-pass"),
+ description: t("plan.phase.deploy-checks-ready"),
+ tagLabel: t("common.done"),
+ statusClass: "text-success",
+ icon: CheckCircle2,
+ iconClass: "text-success/80",
+ required: true,
+ }
+ : {
+ key: "checks",
+ label: t("plan.phase.deploy-checks-must-pass"),
+ description: t("plan.phase.deploy-checks-optional"),
+ tagLabel: t("common.optional"),
+ statusClass: "text-control-placeholder",
+ icon: MinusCircle,
+ iconClass: "text-control-placeholder",
+ required: false,
+ },
+ page.projectRequireIssueApproval
+ ? issueApproved
+ ? {
+ key: "approval",
+ label: t("plan.phase.deploy-approval-must-complete"),
+ description: t("plan.phase.deploy-approval-ready"),
+ tagLabel: t("common.done"),
+ statusClass: "text-success",
+ icon: CheckCircle2,
+ iconClass: "text-success/80",
+ required: true,
+ }
+ : {
+ key: "approval",
+ label: t("plan.phase.deploy-approval-must-complete"),
+ description: t("plan.phase.deploy-approval-pending"),
+ tagLabel: t("common.pending"),
+ statusClass: "text-warning",
+ icon: Clock3,
+ iconClass: "text-warning/80",
+ required: true,
+ }
+ : {
+ key: "approval",
+ label: t("plan.phase.deploy-approval-must-complete"),
+ description: t("plan.phase.deploy-approval-optional"),
+ tagLabel: t("common.optional"),
+ statusClass: "text-control-placeholder",
+ icon: MinusCircle,
+ iconClass: "text-control-placeholder",
+ required: false,
+ },
+ ];
+
+ return (
+ <div className="mt-1.5">
+ <p className="text-sm text-control-placeholder">
+ {t("plan.phase.deploy-description")}
+ </p>
+
+ {page.issue && (
+ <ul className="mt-2.5 max-w-[28rem] space-y-1">
+ {requirementItems.map((item) => {
+ const Icon = item.icon;
+ return (
+ <li key={item.key} className="flex items-start gap-2 py-1">
+ <div className="flex min-w-0 items-start gap-2">
+ <Icon
+ className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${item.iconClass}`}
+ />
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-xs font-medium text-control">
+ {item.label}
+ </span>
+ {item.required && (
+ <span className="text-[10px] font-medium text-error/80">
+ *
+ </span>
+ )}
+ <span
+ className={`text-[11px] font-medium ${item.statusClass}`}
+ >
+ {item.tagLabel}
+ </span>
+ </div>
+ <p className="mt-0.5 text-[11px] text-control-placeholder">
+ {item.description}
+ </p>
+ </div>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ {showManualCreateRolloutHint && (
+ <div className="mt-3 flex max-w-[28rem] flex-col items-start gap-y-2">
+ <p className="text-xs text-control-placeholder">
+ {manualCreateRolloutDescription}
+ </p>
+ {canCreateRollout && (
+ <Button
+ disabled={creatingRollout}
+ onClick={() => setRolloutConfirmOpen(true)}
+ size="sm"
+ variant="outline"
+ >
+ {t("plan.phase.create-rollout-action")}
+ </Button>
+ )}
+ </div>
+ )}
+
+ <Sheet
+ onOpenChange={(open) => {
+ setRolloutConfirmOpen(open);
+ if (!open) {
+ setBypassWarnings(false);
+ }
+ }}
+ open={rolloutConfirmOpen}
+ >
+ <SheetContent
+ className="w-[28rem] max-w-[calc(100vw-2rem)]"
+ width="standard"
+ >
+ <SheetHeader>
+ <SheetTitle>{t("issue.create-rollout")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ {errorMessages.length > 0 ? (
+ <Alert variant="error">
+ <AlertTitle>{t("common.error")}</AlertTitle>
+ <ul className="mt-2 list-inside list-disc text-sm">
+ {errorMessages.map((message) => (
+ <li key={message}>{message}</li>
+ ))}
+ </ul>
+ </Alert>
+ ) : warningMessages.length > 0 ? (
+ <Alert variant="warning">
+ <AlertTitle>{t("common.warning")}</AlertTitle>
+ <ul className="mt-2 list-inside list-disc text-sm">
+ {warningMessages.map((message) => (
+ <li key={message}>{message}</li>
+ ))}
+ </ul>
+ </Alert>
+ ) : null}
+
+ {page.issue && (
+ <div className="flex flex-col gap-y-2">
+ <span className="font-medium text-control">
+ {t("plan.navigator.review")}
+ </span>
+ <span className="text-sm text-control-light">
+ {issueApproved
+ ? t("plan.phase.deploy-approval-ready")
+ : t("plan.phase.deploy-approval-pending")}
+ </span>
+ </div>
+ )}
+
+ <PlanCheckStatusSummary
+ planChecksFailed={planChecksFailed}
+ planChecksRunning={planChecksRunning}
+ />
+ </SheetBody>
+ <SheetFooter className="justify-between">
+ {warningMessages.length > 0 && errorMessages.length === 0 ? (
+ <label className="flex items-center gap-x-2 text-sm text-control">
+ <input
+ checked={bypassWarnings}
+ className="accent-accent"
+ disabled={creatingRollout}
+ onChange={(event) => setBypassWarnings(event.target.checked)}
+ type="checkbox"
+ />
+ <span>{t("rollout.bypass-stage-requirements")}</span>
+ </label>
+ ) : (
+ <div />
+ )}
+ <div className="flex items-center gap-x-2">
+ <Button
+ onClick={() => setRolloutConfirmOpen(false)}
+ variant="ghost"
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={createRolloutDisabled}
+ onClick={() => void createRollout()}
+ >
+ {creatingRollout && (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ )}
+ {t("common.confirm")}
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ </div>
+ );
+}
+
+function PlanCheckStatusSummary({
+ planChecksFailed,
+ planChecksRunning,
+}: {
+ planChecksFailed: boolean;
+ planChecksRunning: boolean;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const statusCount = page.plan.planCheckRunStatusCount ?? {};
+ const hasAnyChecks = Object.values(statusCount).some((count) => count > 0);
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <span className="font-medium text-control">
+ {t("plan.navigator.checks")}
+ </span>
+ {hasAnyChecks ? (
+ <div className="flex flex-wrap items-center gap-2 text-sm text-control-light">
+ {planChecksRunning && <span>{t("common.running")}</span>}
+ {planChecksFailed ? (
+ <span className="text-error">{t("common.failed")}</span>
+ ) : (
+ <span className="text-success">{t("common.done")}</span>
+ )}
+ </div>
+ ) : (
+ <span className="text-sm text-control-placeholder">
+ {t("plan.overview.no-checks")}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
new file mode 100644
index 0000000000..b5b448235c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDraftChecks.tsx
@@ -0,0 +1,417 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ AlertCircle,
+ CheckCircle,
+ CircleQuestionMark,
+ FileCode,
+ Play,
+ SearchCode,
+ XCircle,
+} from "lucide-react";
+import { useEffect, 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 { 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";
+
+export function PlanDetailDraftChecks({
+ onPlanCheckRunsChange,
+ selectedSpec,
+}: {
+ onPlanCheckRunsChange?: (runs: PlanCheckRun[]) => void;
+ selectedSpec: Plan_Spec;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [isRunningChecks, setIsRunningChecks] = useState(false);
+ const [selectedResultStatus, setSelectedResultStatus] = useState<
+ Advice_Level | undefined
+ >();
+ const [checkResults, setCheckResults] = useState<
+ CheckReleaseResponse_CheckResult[] | undefined
+ >(undefined);
+
+ const statement = useMemo(() => {
+ if (selectedSpec.config.case !== "changeDatabaseConfig") return "";
+ const sheet = getLocalSheetByName(selectedSpec.config.value.sheet);
+ return getSheetStatement(sheet);
+ }, [selectedSpec]);
+
+ const formattedCheckRuns = useMemo(
+ () => transformReleaseCheckResultsToPlanCheckRuns(checkResults ?? []),
+ [checkResults]
+ );
+ const summary = useMemo(
+ () => getPlanCheckSummary(formattedCheckRuns),
+ [formattedCheckRuns]
+ );
+ const affectedRows = useMemo(() => {
+ return (checkResults ?? []).reduce(
+ (acc, result) => acc + result.affectedRows,
+ 0n
+ );
+ }, [checkResults]);
+
+ useEffect(() => {
+ onPlanCheckRunsChange?.(formattedCheckRuns);
+ }, [formattedCheckRuns, onPlanCheckRunsChange]);
+
+ const runChecks = async () => {
+ if (selectedSpec.config.case !== "changeDatabaseConfig") return;
+ setIsRunningChecks(true);
+ try {
+ const response = await releaseServiceClientConnect.checkRelease(
+ create(CheckReleaseRequestSchema, {
+ parent: `projects/${extractProjectResourceName(page.plan.name)}`,
+ release: {
+ type: Release_Type.VERSIONED,
+ files: [
+ {
+ version: "0",
+ statement: new TextEncoder().encode(statement),
+ },
+ ],
+ },
+ targets: selectedSpec.config.value.targets ?? [],
+ })
+ );
+ setCheckResults(response.results || []);
+ 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);
+ }
+ };
+
+ 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;
+
+ 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>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
new file mode 100644
index 0000000000..5001647bb2
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
@@ -0,0 +1,744 @@
+import { clone, create } from "@bufbuild/protobuf";
+import { Ban, ChevronUp, Loader2, Menu, Plus } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect, planServiceClientConnect } from "@/connect";
+import {
+ type IssueLabel,
+ IssueLabelSelect,
+} from "@/react/components/IssueLabelSelect";
+import { MarkdownEditor } from "@/react/components/MarkdownEditor";
+import { Button } from "@/react/components/ui/button";
+import { useClickOutside } from "@/react/hooks/useClickOutside";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import {
+ PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL,
+} from "@/router/dashboard/projectV1";
+import { pushNotification, useSheetV1Store } from "@/store";
+import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ CreateIssueRequestSchema,
+ Issue_Type,
+ IssueSchema,
+ IssueStatus,
+ UpdateIssueRequestSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ CreatePlanRequestSchema,
+ PlanSchema,
+ UpdatePlanRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ extractIssueUID,
+ extractPlanUID,
+ extractProjectResourceName,
+ extractSheetUID,
+ hasProjectPermissionV2,
+} from "@/utils";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidation";
+import {
+ getCreateIssueBlockingErrors,
+ getCreateIssueConfirmErrors,
+ hasChecksWarning,
+ shouldStayOnPlanDetailPage,
+} from "../utils/header";
+import { getLocalSheetByName } from "../utils/localSheet";
+
+export function PlanDetailHeader() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, setEditing } = page;
+ const sheetStore = useSheetV1Store();
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const [title, setTitle] = useState(page.plan.title);
+ const [description, setDescription] = useState(page.plan.description);
+ const [editingTitle, setEditingTitle] = useState(false);
+ const [editingDescription, setEditingDescription] = useState(false);
+ const [showFullDescription, setShowFullDescription] = useState(false);
+ const [updating, setUpdating] = useState(false);
+ const [showReviewPopover, setShowReviewPopover] = useState(false);
+ const [selectedLabels, setSelectedLabels] = useState<string[]>([]);
+ const [checksWarningAcknowledged, setChecksWarningAcknowledged] =
+ useState(false);
+ const [submittingReview, setSubmittingReview] = useState(false);
+ const reviewPopoverRef = useRef<HTMLDivElement>(null);
+ const { emptySpecIdSet } = usePlanDetailSpecValidation(page.plan.specs ?? []);
+
+ useEffect(() => {
+ const nextTitle = page.issue?.title ?? page.plan.title;
+ setTitle((prev) => (prev === nextTitle ? prev : nextTitle));
+ }, [page.issue?.title, page.plan.title]);
+
+ useEffect(() => {
+ setDescription((prev) =>
+ prev === page.plan.description ? prev : page.plan.description
+ );
+ }, [page.plan.description]);
+
+ const allowTitleEdit = useMemo(() => {
+ if (page.readonly) return false;
+ if (page.isCreating) return true;
+ if (!page.issue && page.plan.hasRollout) return false;
+ if (page.issue) {
+ return hasProjectPermissionV2(project, "bb.issues.update");
+ }
+ return (
+ page.plan.creator === currentUser.name ||
+ hasProjectPermissionV2(project, "bb.plans.update")
+ );
+ }, [
+ currentUser.name,
+ page.isCreating,
+ page.issue,
+ page.plan.creator,
+ page.plan.hasRollout,
+ page.readonly,
+ project,
+ ]);
+
+ const allowDescriptionEdit = useMemo(() => {
+ if (page.readonly) return false;
+ if (page.isCreating) return true;
+ if (!page.issue && page.plan.hasRollout) return false;
+ return (
+ page.plan.creator === currentUser.name ||
+ hasProjectPermissionV2(project, "bb.plans.update")
+ );
+ }, [
+ currentUser.name,
+ page.isCreating,
+ page.issue,
+ page.plan.creator,
+ page.plan.hasRollout,
+ page.readonly,
+ project,
+ ]);
+
+ const showSubmitForReview =
+ !!page.plan.name &&
+ !page.isCreating &&
+ !page.plan.issue &&
+ page.plan.state === State.ACTIVE;
+ const showClosePlan =
+ !page.isCreating &&
+ !page.plan.issue &&
+ !page.plan.hasRollout &&
+ page.plan.state === State.ACTIVE;
+ const showReopenPlan =
+ !page.isCreating &&
+ !page.plan.issue &&
+ !page.plan.hasRollout &&
+ page.plan.state === State.DELETED;
+
+ const submitDisabled = page.isEditing;
+ const submitDisabledReason = submitDisabled
+ ? t("plan.editor.save-changes-before-continuing")
+ : undefined;
+
+ const saveTitle = async () => {
+ if (page.isCreating) {
+ patchState({
+ plan: {
+ ...page.plan,
+ title,
+ },
+ });
+ setEditingTitle(false);
+ setEditing("title", false);
+ return;
+ }
+
+ try {
+ setUpdating(true);
+ if (page.issue) {
+ const issuePatch = create(IssueSchema, {
+ ...page.issue,
+ title,
+ });
+ const response = await issueServiceClientConnect.updateIssue(
+ create(UpdateIssueRequestSchema, {
+ issue: issuePatch,
+ updateMask: { paths: ["title"] },
+ })
+ );
+ patchState({ issue: response });
+ } else {
+ const planPatch = create(PlanSchema, {
+ ...page.plan,
+ title,
+ });
+ const response = await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["title"] },
+ })
+ );
+ patchState({ plan: response });
+ }
+ } catch (error) {
+ setTitle(page.issue?.title ?? page.plan.title);
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setUpdating(false);
+ setEditingTitle(false);
+ setEditing("title", false);
+ }
+ };
+
+ const saveDescription = async () => {
+ if (page.isCreating) {
+ patchState({
+ plan: {
+ ...page.plan,
+ description,
+ },
+ });
+ setEditingDescription(false);
+ setEditing("description", false);
+ return;
+ }
+
+ let saved = false;
+ try {
+ setUpdating(true);
+ const planPatch = create(PlanSchema, {
+ ...page.plan,
+ description,
+ });
+ const response = await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["description"] },
+ })
+ );
+ patchState({ plan: response });
+ saved = true;
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setUpdating(false);
+ if (saved) {
+ setEditingDescription(false);
+ setEditing("description", false);
+ }
+ }
+ };
+
+ const updatePlanState = async (state: State) => {
+ try {
+ const planPatch = clone(PlanSchema, page.plan);
+ planPatch.state = state;
+ const updated = await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["state"] },
+ })
+ );
+ patchState({ plan: updated });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ }
+ };
+
+ const createSheets = async () => {
+ for (const spec of page.plan.specs) {
+ let config = null;
+ if (spec.config?.case === "changeDatabaseConfig")
+ config = spec.config.value;
+ else if (spec.config?.case === "exportDataConfig")
+ config = spec.config.value;
+ if (!config) continue;
+ const uid = extractSheetUID(config.sheet);
+ if (uid.startsWith("-")) {
+ const local = getLocalSheetByName(config.sheet);
+ const createdSheet = await sheetStore.createSheet(project.name, local);
+ config.sheet = createdSheet.name;
+ }
+ }
+ };
+
+ const handleCreatePlan = async () => {
+ try {
+ setUpdating(true);
+ await createSheets();
+ const createdPlan = await planServiceClientConnect.createPlan(
+ create(CreatePlanRequestSchema, {
+ parent: project.name,
+ plan: page.plan,
+ })
+ );
+ page.bypassLeaveGuardOnce();
+ void router.replace({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(createdPlan.name),
+ planId: extractPlanUID(createdPlan.name),
+ },
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setUpdating(false);
+ }
+ };
+
+ const createIssueBlockingErrors = useMemo(
+ () =>
+ getCreateIssueBlockingErrors({
+ emptySpecCount: emptySpecIdSet.size,
+ plan: page.plan,
+ project,
+ t,
+ }),
+ [emptySpecIdSet.size, page.plan, project, t]
+ );
+ const showChecksWarning = useMemo(
+ () => hasChecksWarning(page.plan),
+ [page.plan]
+ );
+ const createIssueConfirmErrors = useMemo(
+ () =>
+ getCreateIssueConfirmErrors({
+ blockingErrors: createIssueBlockingErrors,
+ checksWarningAcknowledged,
+ project,
+ selectedLabelCount: selectedLabels.length,
+ showChecksWarning,
+ t,
+ }),
+ [
+ checksWarningAcknowledged,
+ createIssueBlockingErrors,
+ project,
+ selectedLabels.length,
+ showChecksWarning,
+ t,
+ ]
+ );
+
+ const resetReviewPopoverDraft = () => {
+ setSelectedLabels([]);
+ setChecksWarningAcknowledged(false);
+ };
+
+ const handleReviewPopoverOpenChange = (open: boolean) => {
+ setShowReviewPopover(open);
+ if (!open) {
+ resetReviewPopoverDraft();
+ }
+ };
+
+ useClickOutside(reviewPopoverRef, showReviewPopover, () =>
+ handleReviewPopoverOpenChange(false)
+ );
+
+ const isDescriptionLong =
+ (description?.length ?? 0) > 150 ||
+ (description?.split("\n").length ?? 0) > 3;
+
+ const handleCreateIssue = async () => {
+ if (createIssueConfirmErrors.length > 0) return;
+ try {
+ setSubmittingReview(true);
+ const createdIssue = await issueServiceClientConnect.createIssue(
+ create(CreateIssueRequestSchema, {
+ parent: project.name,
+ issue: create(IssueSchema, {
+ creator: `users/${currentUser.email}`,
+ labels: selectedLabels,
+ plan: page.plan.name,
+ status: IssueStatus.OPEN,
+ type: page.plan.specs.some(
+ (spec) => spec.config?.case === "exportDataConfig"
+ )
+ ? Issue_Type.DATABASE_EXPORT
+ : Issue_Type.DATABASE_CHANGE,
+ }),
+ })
+ );
+ handleReviewPopoverOpenChange(false);
+ patchState({
+ issue: createdIssue,
+ plan: {
+ ...page.plan,
+ issue: createdIssue.name,
+ },
+ });
+ if (shouldStayOnPlanDetailPage(page.plan)) {
+ await page.refreshState();
+ return;
+ }
+ void router.push({
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(page.plan.name),
+ issueId: extractIssueUID(createdIssue.name),
+ },
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setSubmittingReview(false);
+ }
+ };
+
+ return (
+ <div className="px-2 py-2 sm:px-4">
+ <div className="flex flex-row items-center justify-between gap-2">
+ {page.plan.state === State.DELETED && (
+ <span className="inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 text-sm text-control">
+ <Ban className="h-4 w-4" />
+ {t("common.closed")}
+ </span>
+ )}
+ <div className="min-w-0 flex-1">
+ <input
+ className={cn(
+ "h-9 w-full bg-transparent text-[18px] font-bold text-main outline-hidden",
+ editingTitle
+ ? "border border-control-border px-3"
+ : "border border-transparent px-0",
+ !allowTitleEdit && "cursor-default"
+ )}
+ disabled={!allowTitleEdit || updating}
+ maxLength={200}
+ onBlur={() => void saveTitle()}
+ onChange={(e) => {
+ setTitle(e.target.value);
+ if (page.isCreating) {
+ patchState({
+ plan: { ...page.plan, title: e.target.value },
+ });
+ }
+ }}
+ onFocus={() => {
+ if (!allowTitleEdit) return;
+ setEditingTitle(true);
+ setEditing("title", true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.currentTarget.blur();
+ }
+ }}
+ placeholder={t("common.untitled")}
+ value={title}
+ />
+ </div>
+
+ <div className="flex shrink-0 items-center gap-x-2">
+ {page.isCreating ? (
+ <Button
+ disabled={
+ updating || !page.plan.title.trim() || emptySpecIdSet.size > 0
+ }
+ onClick={() => void handleCreatePlan()}
+ >
+ {updating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+ {t("common.create")}
+ </Button>
+ ) : (
+ <>
+ {showSubmitForReview && (
+ <div className="relative" ref={reviewPopoverRef}>
+ <Button
+ disabled={submitDisabled}
+ onClick={() => handleReviewPopoverOpenChange(true)}
+ title={submitDisabledReason}
+ >
+ {t("plan.ready-for-review")}
+ </Button>
+ {showReviewPopover && (
+ <div className="absolute right-0 top-full z-40 mt-2 w-[min(28rem,calc(100vw-2rem))] rounded-sm border border-control-border bg-white px-4 py-4 shadow-lg">
+ <ReadyForReviewPopoverContent
+ checksWarningAcknowledged={checksWarningAcknowledged}
+ confirmErrors={createIssueConfirmErrors}
+ forceIssueLabels={project.forceIssueLabels}
+ issueLabels={project.issueLabels ?? []}
+ onCancel={() => handleReviewPopoverOpenChange(false)}
+ onChecksWarningAcknowledgedChange={
+ setChecksWarningAcknowledged
+ }
+ onConfirm={() => void handleCreateIssue()}
+ onSelectedLabelsChange={setSelectedLabels}
+ selectedLabels={selectedLabels}
+ showChecksWarning={showChecksWarning}
+ submitting={submittingReview}
+ />
+ </div>
+ )}
+ </div>
+ )}
+ {showClosePlan && (
+ <Button
+ onClick={() => {
+ if (window.confirm(t("plan.state.close-confirm"))) {
+ void updatePlanState(State.DELETED);
+ }
+ }}
+ variant="outline"
+ >
+ {t("common.close")}
+ </Button>
+ )}
+ {showReopenPlan && (
+ <Button
+ onClick={() => {
+ if (window.confirm(t("plan.state.reopen-confirm"))) {
+ void updatePlanState(State.ACTIVE);
+ }
+ }}
+ variant="outline"
+ >
+ {t("common.reopen")}
+ </Button>
+ )}
+ </>
+ )}
+ {page.sidebarMode === "MOBILE" && (
+ <Button
+ onClick={() => page.setMobileSidebarOpen(true)}
+ size="icon"
+ variant="ghost"
+ >
+ <Menu className="h-5 w-5" />
+ </Button>
+ )}
+ </div>
+ </div>
+
+ <div className="min-w-0">
+ {editingDescription ? (
+ <div className="py-2">
+ <div className="flex items-center justify-between">
+ <span className="text-base font-medium">
+ {t("common.description")}
+ </span>
+ <div className="flex items-center gap-2">
+ {!page.isCreating ? (
+ <Button
+ onClick={() => void saveDescription()}
+ size="xs"
+ variant="outline"
+ >
+ {t("common.save")}
+ </Button>
+ ) : (
+ <Button
+ onClick={() => {
+ setDescription(page.plan.description);
+ setEditingDescription(false);
+ setEditing("description", false);
+ }}
+ size="xs"
+ variant="ghost"
+ >
+ <ChevronUp className="mr-1 h-4 w-4" />
+ {t("common.collapse")}
+ </Button>
+ )}
+ {!page.isCreating && (
+ <Button
+ onClick={() => {
+ setDescription(page.plan.description);
+ setEditingDescription(false);
+ setEditing("description", false);
+ }}
+ size="xs"
+ variant="ghost"
+ >
+ {t("common.cancel")}
+ </Button>
+ )}
+ </div>
+ </div>
+ <textarea
+ className="mt-2 min-h-28 w-full rounded-sm border border-control-border px-3 py-2 text-sm outline-hidden"
+ onChange={(e) => {
+ setDescription(e.target.value);
+ if (page.isCreating) {
+ patchState({
+ plan: { ...page.plan, description: e.target.value },
+ });
+ }
+ }}
+ value={description}
+ />
+ </div>
+ ) : description ? (
+ <div className="mt-1">
+ <div
+ aria-disabled={!allowDescriptionEdit}
+ className={cn(
+ "relative w-full rounded-md border border-transparent px-2 py-1 text-left text-sm text-control-light transition-all duration-200",
+ !showFullDescription && "max-h-[4.5rem] overflow-hidden",
+ allowDescriptionEdit && "cursor-pointer hover:border-gray-200"
+ )}
+ onClick={() => {
+ if (!allowDescriptionEdit) return;
+ setEditingDescription(true);
+ setEditing("description", true);
+ }}
+ onKeyDown={(event) => {
+ if (!allowDescriptionEdit) return;
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ setEditingDescription(true);
+ setEditing("description", true);
+ }}
+ role={allowDescriptionEdit ? "button" : undefined}
+ tabIndex={allowDescriptionEdit ? 0 : undefined}
+ >
+ <div className="pointer-events-none">
+ <MarkdownEditor content={description} mode="preview" />
+ </div>
+ {!showFullDescription && isDescriptionLong && (
+ <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-6 bg-gradient-to-t from-white to-transparent" />
+ )}
+ </div>
+ {isDescriptionLong && (
+ <button
+ className="mt-1 px-2 text-xs text-control-placeholder hover:text-control"
+ onClick={(event) => {
+ event.stopPropagation();
+ setShowFullDescription((value) => !value);
+ }}
+ type="button"
+ >
+ {showFullDescription
+ ? t("common.show-less")
+ : t("common.show-more")}
+ </button>
+ )}
+ </div>
+ ) : allowDescriptionEdit ? (
+ <Button
+ onClick={() => {
+ setEditingDescription(true);
+ setEditing("description", true);
+ }}
+ size="xs"
+ variant="ghost"
+ className="italic opacity-60"
+ >
+ <Plus className="mr-1 h-4 w-4" />
+ {t("plan.description.placeholder")}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+function ReadyForReviewPopoverContent({
+ checksWarningAcknowledged,
+ confirmErrors,
+ forceIssueLabels,
+ issueLabels,
+ onCancel,
+ onChecksWarningAcknowledgedChange,
+ onConfirm,
+ onSelectedLabelsChange,
+ selectedLabels,
+ showChecksWarning,
+ submitting,
+}: {
+ checksWarningAcknowledged: boolean;
+ confirmErrors: string[];
+ forceIssueLabels: boolean;
+ issueLabels: IssueLabel[];
+ onCancel: () => void;
+ onChecksWarningAcknowledgedChange: (checked: boolean) => void;
+ onConfirm: () => void;
+ onSelectedLabelsChange: (labels: string[]) => void;
+ selectedLabels: string[];
+ showChecksWarning: boolean;
+ submitting: boolean;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ {showChecksWarning && (
+ <div className="rounded-sm border border-warning/30 bg-warning/10 px-3 py-2 text-sm text-warning">
+ {t("issue.checks-warning-hint")}
+ </div>
+ )}
+ <IssueLabelSelect
+ labels={issueLabels}
+ onChange={onSelectedLabelsChange}
+ required={forceIssueLabels}
+ selected={selectedLabels}
+ />
+ {showChecksWarning && (
+ <label className="flex items-center gap-x-2 text-sm text-control">
+ <input
+ checked={checksWarningAcknowledged}
+ className="accent-accent"
+ onChange={(event) =>
+ onChecksWarningAcknowledgedChange(event.target.checked)
+ }
+ type="checkbox"
+ />
+ <span>
+ {t("issue.action-anyway", {
+ action: t("common.confirm"),
+ })}
+ </span>
+ </label>
+ )}
+ {confirmErrors.length > 0 && (
+ <div className="whitespace-pre-line rounded-sm border border-error/30 bg-error/5 px-3 py-2 text-sm text-error">
+ {confirmErrors.join("\n")}
+ </div>
+ )}
+ <div className="flex justify-start gap-x-2 pt-1">
+ <Button
+ disabled={confirmErrors.length > 0 || submitting}
+ onClick={onConfirm}
+ size="sm"
+ >
+ {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t("common.confirm")}
+ </Button>
+ <Button onClick={onCancel} size="sm" variant="ghost">
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
new file mode 100644
index 0000000000..9546c33060
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailMetadataSidebar.tsx
@@ -0,0 +1,389 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ AlertCircle,
+ CheckCircle,
+ Loader2,
+ RefreshCw,
+ XCircle,
+} from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect } from "@/connect";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import {
+ extractUserEmail,
+ pushNotification,
+ useEnvironmentV1Store,
+} from "@/store";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import {
+ IssueSchema,
+ IssueStatus,
+ UpdateIssueRequestSchema,
+} from "@/types/proto-es/v1/issue_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ formatAbsoluteDateTime,
+ getStageStatus,
+ hasProjectPermissionV2,
+ humanizeTs,
+} from "@/utils";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+import { getPlanDetailSidebarStatusInfo } from "../utils/sidebarStatus";
+import { PlanDetailSidebarApprovalFlow } from "./PlanDetailApprovalFlow";
+
+export function PlanDetailMetadataSidebar() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, refreshState } = page;
+ const environmentStore = useEnvironmentV1Store();
+ const project = page.project;
+ const [now, setNow] = useState(Date.now());
+
+ useEffect(() => {
+ const timer = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(timer);
+ }, []);
+
+ const creatorEmail = useMemo(
+ () => extractUserEmail(page.plan.creator),
+ [page.plan.creator]
+ );
+ const createdTimeDisplay = useMemo(() => {
+ const ts = getTimeForPbTimestampProtoEs(page.plan.createTime, 0);
+ if (!ts) return "";
+ void now;
+ return humanizeTs(ts / 1000);
+ }, [now, page.plan.createTime]);
+ const statusInfo = useMemo(() => {
+ return getPlanDetailSidebarStatusInfo({
+ isCreating: page.isCreating,
+ issue: page.issue,
+ planState: page.plan.state,
+ rollout: page.rollout,
+ 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 allowChangeLabels = useMemo(() => {
+ if (!project || !page.issue || page.issue.status !== IssueStatus.OPEN) {
+ return false;
+ }
+ return hasProjectPermissionV2(project, "bb.issues.update");
+ }, [page.issue, project]);
+ const lastRefreshDisplay = useMemo(() => {
+ if (!page.lastRefreshTime) return "";
+ void now;
+ const diff = Date.now() - page.lastRefreshTime;
+ if (diff < 3_600_000) {
+ return humanizeTs(Math.floor(page.lastRefreshTime / 1000));
+ }
+ return formatAbsoluteDateTime(page.lastRefreshTime);
+ }, [now, page.lastRefreshTime]);
+
+ return (
+ <div className="flex w-full shrink-0 flex-col text-sm">
+ <div className="flex flex-col gap-3 pb-3">
+ {!page.isCreating && (
+ <div className="flex flex-col">
+ <p className="text-xs text-control-placeholder">
+ {t("plan.sidebar.created-by-at", {
+ time: createdTimeDisplay,
+ user: creatorEmail,
+ })}
+ </p>
+ </div>
+ )}
+
+ <div>
+ <h4 className="mb-1 textinfolabel">{t("common.status")}</h4>
+ <div className="flex items-center gap-2">
+ <div
+ className={cn("h-2.5 w-2.5 rounded-full", statusInfo.dotClass)}
+ />
+ <span className="text-sm font-medium text-main">
+ {statusInfo.label}
+ </span>
+ </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>
+ )}
+ </div>
+
+ {page.issue && (
+ <div className="flex flex-col gap-3 border-t py-3">
+ <PlanDetailSidebarApprovalFlow />
+ <IssueLabelsSection
+ issueLabels={project?.issueLabels ?? []}
+ labels={page.issue.labels || []}
+ allowChange={allowChangeLabels}
+ onUpdate={async (labels) => {
+ const issuePatch = create(IssueSchema, page.issue);
+ issuePatch.labels = labels;
+ try {
+ const response = await issueServiceClientConnect.updateIssue(
+ create(UpdateIssueRequestSchema, {
+ issue: issuePatch,
+ updateMask: { paths: ["labels"] },
+ })
+ );
+ patchState({ issue: response });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ }
+ }}
+ />
+ </div>
+ )}
+
+ {page.rollout && page.rollout.stages.length > 0 && (
+ <div className="flex flex-col gap-3 border-t py-3">
+ <h4 className="textinfolabel">
+ {t("rollout.stage.self", { count: 2 })}
+ </h4>
+ {page.rollout.stages.map((stage) => {
+ const completed = stage.tasks.filter(
+ (task) =>
+ task.status === Task_Status.DONE ||
+ task.status === Task_Status.SKIPPED
+ ).length;
+ const env = environmentStore.getEnvironmentByName(
+ stage.environment
+ );
+ const stageStatus = getStageStatus(stage);
+ return (
+ <div key={stage.name} className="flex items-center gap-2">
+ <StageStatusDot status={stageStatus} />
+ <span className="text-main">{env.title}</span>
+ <span className="text-control-placeholder">
+ ({completed}/{stage.tasks.length})
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {!page.issue && (
+ <div className="border-t pt-3">
+ <p className="text-sm text-control-placeholder">
+ {t("plan.sidebar.future-sections-hint")}
+ </p>
+ </div>
+ )}
+
+ {!page.isCreating && (
+ <div className="pt-1">
+ <div className="hidden items-center gap-2 sm:flex">
+ {lastRefreshDisplay && (
+ <Tooltip content={formatAbsoluteDateTime(page.lastRefreshTime)}>
+ <span className="text-xs text-gray-400">
+ {lastRefreshDisplay}
+ </span>
+ </Tooltip>
+ )}
+ <Button
+ className="opacity-60"
+ disabled={page.isRefreshing}
+ onClick={() => void refreshState()}
+ size="xs"
+ variant="ghost"
+ >
+ <RefreshCw
+ className={cn("h-3 w-3", page.isRefreshing && "animate-spin")}
+ />
+ <span>{t("common.refresh")}</span>
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function IssueLabelsSection({
+ allowChange,
+ issueLabels,
+ labels,
+ onUpdate,
+}: {
+ allowChange: boolean;
+ issueLabels: Array<{ color: string; value: string }>;
+ labels: string[];
+ onUpdate: (labels: string[]) => Promise<void>;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [isUpdating, setIsUpdating] = useState(false);
+
+ const options = useMemo(
+ () =>
+ issueLabels.map((label) => ({
+ color: label.color,
+ value: label.value,
+ })),
+ [issueLabels]
+ );
+
+ const toggleLabel = async (value: string) => {
+ const next = labels.includes(value)
+ ? labels.filter((label) => label !== value)
+ : [...labels, value];
+ try {
+ setIsUpdating(true);
+ await onUpdate(next);
+ } finally {
+ setIsUpdating(false);
+ }
+ };
+
+ return (
+ <div className="flex flex-col gap-y-1">
+ <div className="flex items-center gap-x-1 textinfolabel">
+ <span>{t("issue.labels")}</span>
+ </div>
+ <div className="relative">
+ <button
+ className={cn(
+ "flex min-h-9 w-full items-center justify-between gap-2 rounded-sm border border-control-border bg-white px-3 py-1.5 text-left text-sm transition-colors",
+ allowChange && !isUpdating && "hover:bg-control-bg",
+ open && "border-accent shadow-[0_0_0_1px_var(--color-accent)]",
+ (!allowChange || isUpdating) && "cursor-not-allowed opacity-60"
+ )}
+ disabled={!allowChange || isUpdating}
+ onClick={() => setOpen((current) => !current)}
+ type="button"
+ >
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
+ {labels.length > 0 ? (
+ labels.map((value) => {
+ const option = options.find((item) => item.value === value);
+ return (
+ <span
+ key={value}
+ className="inline-flex items-center gap-1 rounded-xs bg-control-bg px-1.5 py-0.5 text-xs"
+ >
+ <span
+ className="size-2.5 shrink-0 rounded-sm"
+ style={{ backgroundColor: option?.color }}
+ />
+ <span className="truncate">{value}</span>
+ </span>
+ );
+ })
+ ) : (
+ <span className="text-control-placeholder">
+ {t("common.select")}
+ </span>
+ )}
+ </div>
+ </button>
+
+ {open && (
+ <div className="absolute z-50 mt-1 w-full overflow-hidden rounded-sm border border-control-border bg-white shadow-lg">
+ <div className="max-h-60 overflow-y-auto">
+ {options.length === 0 ? (
+ <div className="px-3 py-6 text-sm text-control-placeholder">
+ {t("common.no-data")}
+ </div>
+ ) : (
+ options.map((option) => {
+ const isSelected = labels.includes(option.value);
+ return (
+ <button
+ key={option.value}
+ className="flex w-full items-center gap-x-2 px-3 py-2 text-left text-sm transition-colors hover:bg-control-bg"
+ disabled={isUpdating}
+ onClick={() => void toggleLabel(option.value)}
+ type="button"
+ >
+ <input
+ checked={isSelected}
+ className="accent-accent"
+ readOnly
+ type="checkbox"
+ />
+ <span
+ className="size-4 shrink-0 rounded-sm"
+ style={{ backgroundColor: option.color }}
+ />
+ <span>{option.value}</span>
+ </button>
+ );
+ })
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function StageStatusDot({ status }: { status: Task_Status }) {
+ const dotClass =
+ status === Task_Status.DONE || status === Task_Status.SKIPPED
+ ? "bg-success"
+ : status === Task_Status.FAILED
+ ? "bg-error"
+ : status === Task_Status.RUNNING || status === Task_Status.PENDING
+ ? "bg-accent"
+ : "bg-control-placeholder";
+ return <div className={cn("h-2.5 w-2.5 rounded-full", dotClass)} />;
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx
new file mode 100644
index 0000000000..a343c0074c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailRollbackSheet.tsx
@@ -0,0 +1,380 @@
+import { create } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
+import { DatabaseBackup, Loader2 } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { v4 as uuidv4 } from "uuid";
+import {
+ planServiceClientConnect,
+ rolloutServiceClientConnect,
+} from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import { ReadonlyMonaco } from "@/react/components/monaco";
+import { Alert } from "@/react/components/ui/alert";
+import { Badge } from "@/react/components/ui/badge";
+import { Button } from "@/react/components/ui/button";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/router/dashboard/projectV1";
+import { pushNotification, useProjectV1Store, useSheetV1Store } from "@/store";
+import {
+ CreatePlanRequestSchema,
+ Plan_ChangeDatabaseConfigSchema,
+ Plan_SpecSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ PreviewTaskRunRollbackRequestSchema,
+ type Task,
+ type TaskRun,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
+import {
+ extractPlanUID,
+ extractPlanUIDFromRolloutName,
+ extractProjectResourceName,
+ hasProjectPermissionV2,
+} from "@/utils";
+import { DatabaseTarget } from "./PlanDetailChangesBranch";
+
+export function PlanDetailRollbackSheet({
+ open,
+ onOpenChange,
+ projectName,
+ rolloutName,
+ items,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ projectName: string;
+ rolloutName: string;
+ items: Array<{
+ task: Task;
+ taskRun: TaskRun;
+ }>;
+}) {
+ const { t } = useTranslation();
+ const sheetStore = useSheetV1Store();
+ const projectStore = useProjectV1Store();
+ const normalizedProjectName = projectName.startsWith("projects/")
+ ? projectName
+ : `projects/${projectName}`;
+ const project = projectStore.getProjectByName(normalizedProjectName);
+ const [loading, setLoading] = useState(false);
+ const [selectedTaskRunNames, setSelectedTaskRunNames] = useState<string[]>(
+ []
+ );
+ const [previews, setPreviews] = useState<
+ Array<{
+ task: Task;
+ taskRun: TaskRun;
+ statement?: string;
+ error?: string;
+ }>
+ >([]);
+ const [step, setStep] = useState<1 | 2>(1);
+
+ useEffect(() => {
+ if (!open) {
+ setStep(1);
+ setPreviews([]);
+ setSelectedTaskRunNames([]);
+ return;
+ }
+ if (items.length === 1) {
+ setSelectedTaskRunNames([items[0].taskRun.name]);
+ }
+ }, [items, open]);
+
+ useEffect(() => {
+ if (!open || items.length !== 1 || step !== 1) {
+ return;
+ }
+ const only = items[0];
+ void (async () => {
+ try {
+ setLoading(true);
+ const response =
+ await rolloutServiceClientConnect.previewTaskRunRollback(
+ create(PreviewTaskRunRollbackRequestSchema, {
+ name: only.taskRun.name,
+ }),
+ {
+ contextValues: createContextValues().set(silentContextKey, true),
+ }
+ );
+ setPreviews([
+ {
+ task: only.task,
+ taskRun: only.taskRun,
+ statement: response.statement,
+ },
+ ]);
+ setStep(2);
+ } catch (error) {
+ setPreviews([
+ {
+ task: only.task,
+ taskRun: only.taskRun,
+ error: String(error),
+ },
+ ]);
+ setStep(2);
+ } finally {
+ setLoading(false);
+ }
+ })();
+ }, [items, open, step]);
+
+ const selectedItems = useMemo(
+ () =>
+ items.filter((item) => selectedTaskRunNames.includes(item.taskRun.name)),
+ [items, selectedTaskRunNames]
+ );
+
+ const canCreate = useMemo(() => {
+ return (
+ !loading &&
+ previews.length > 0 &&
+ previews.every((preview) => !preview.error) &&
+ previews.some((preview) => preview.statement) &&
+ hasProjectPermissionV2(project, "bb.plans.create")
+ );
+ }, [loading, previews, project]);
+
+ return (
+ <Sheet onOpenChange={onOpenChange} open={open}>
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>{t("common.rollback")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ <div className="flex items-center gap-x-2">
+ <Badge variant={step === 1 ? "secondary" : "default"}>
+ {t("task.select-task")}
+ </Badge>
+ <Badge variant={step === 2 ? "secondary" : "default"}>
+ {t("task-run.rollback.preview-statement.description")}
+ </Badge>
+ </div>
+ {step === 1 ? (
+ <div className="space-y-3">
+ <div className="text-sm text-control-light">
+ {t("task.select-task")}
+ </div>
+ <div className="overflow-hidden rounded-sm border">
+ {items.map((item) => {
+ const checked = selectedTaskRunNames.includes(
+ item.taskRun.name
+ );
+ return (
+ <label
+ key={item.taskRun.name}
+ className="flex cursor-pointer items-center gap-3 border-b border-control-border px-3 py-2 last:border-b-0 hover:bg-gray-50"
+ >
+ <input
+ checked={checked}
+ className="accent-accent"
+ onChange={(event) => {
+ setSelectedTaskRunNames((prev) => {
+ if (event.target.checked) {
+ return [...prev, item.taskRun.name];
+ }
+ return prev.filter(
+ (name) => name !== item.taskRun.name
+ );
+ });
+ }}
+ type="checkbox"
+ />
+ <div className="min-w-0 space-y-1">
+ <div className="min-w-0 text-sm font-medium text-main">
+ <DatabaseTarget
+ showEnvironment
+ target={item.task.target}
+ />
+ </div>
+ <div className="text-xs text-control-light">
+ {item.taskRun.name}
+ </div>
+ </div>
+ </label>
+ );
+ })}
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-4">
+ <Alert variant="info">
+ {t("task-run.rollback.preview-statement.description")}
+ </Alert>
+ {loading ? (
+ <div className="flex items-center justify-center py-8 text-control-light">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ </div>
+ ) : (
+ previews.map((preview) => (
+ <div key={preview.taskRun.name} className="space-y-2">
+ <div className="text-sm font-medium text-main">
+ <DatabaseTarget
+ showEnvironment
+ target={preview.task.target}
+ />
+ </div>
+ {preview.error ? (
+ <div className="rounded-md border border-error/30 bg-error/5 p-3 text-sm text-error">
+ {preview.error}
+ </div>
+ ) : preview.statement ? (
+ <ReadonlyMonaco
+ className="relative h-auto max-h-[320px] min-h-[120px]"
+ content={preview.statement}
+ language="sql"
+ />
+ ) : (
+ <div className="flex items-center justify-center rounded-md border bg-gray-50 p-8">
+ <div className="flex flex-col items-center gap-y-2 text-center">
+ <DatabaseBackup className="h-6 w-6 text-gray-400" />
+ <p className="text-sm text-gray-500">
+ {t("task-run.rollback.no-statement-generated")}
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+ )}
+ </SheetBody>
+ <SheetFooter>
+ {step === 1 ? (
+ <Button onClick={() => onOpenChange(false)} variant="ghost">
+ {t("common.cancel")}
+ </Button>
+ ) : (
+ <Button onClick={() => setStep(1)} variant="ghost">
+ {t("common.back")}
+ </Button>
+ )}
+ {step === 1 ? (
+ <Button
+ disabled={selectedItems.length === 0}
+ onClick={async () => {
+ try {
+ setLoading(true);
+ const nextPreviews: Array<{
+ task: Task;
+ taskRun: TaskRun;
+ statement?: string;
+ error?: string;
+ }> = selectedItems.map((item) => ({
+ task: item.task,
+ taskRun: item.taskRun,
+ }));
+ for (const preview of nextPreviews) {
+ try {
+ const response =
+ await rolloutServiceClientConnect.previewTaskRunRollback(
+ create(PreviewTaskRunRollbackRequestSchema, {
+ name: preview.taskRun.name,
+ }),
+ {
+ contextValues: createContextValues().set(
+ silentContextKey,
+ true
+ ),
+ }
+ );
+ preview.statement = response.statement;
+ } catch (err) {
+ preview.error = String(err);
+ }
+ }
+ setPreviews(nextPreviews);
+ setStep(2);
+ } finally {
+ setLoading(false);
+ }
+ }}
+ >
+ {t("common.next")}
+ </Button>
+ ) : null}
+ <Button
+ disabled={step !== 2 || !canCreate}
+ onClick={async () => {
+ if (previews.length === 0) return;
+ try {
+ setLoading(true);
+ const specs = [];
+ for (const preview of previews) {
+ if (!preview.statement) continue;
+ const sheet = await sheetStore.createSheet(
+ projectName,
+ create(SheetSchema, {
+ name: `${projectName}/sheets/${uuidv4()}`,
+ content: new TextEncoder().encode(preview.statement),
+ })
+ );
+ specs.push(
+ create(Plan_SpecSchema, {
+ id: uuidv4(),
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, {
+ targets: [preview.task.target],
+ sheet: sheet.name,
+ }),
+ },
+ })
+ );
+ }
+ const plan = create(PlanSchema, {
+ name: `${projectName}/plans/${uuidv4()}`,
+ title: `Rollback for rollout#${extractPlanUIDFromRolloutName(
+ rolloutName
+ )}`,
+ description: `This plan is created to rollback ${previews.length} task(s) in rollout #${extractPlanUIDFromRolloutName(rolloutName)}`,
+ specs,
+ });
+ const createdPlan = await planServiceClientConnect.createPlan(
+ create(CreatePlanRequestSchema, {
+ parent: projectName,
+ plan,
+ })
+ );
+ void router.push({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(projectName),
+ planId: extractPlanUID(createdPlan.name),
+ },
+ });
+ } catch (err) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(err),
+ });
+ } finally {
+ setLoading(false);
+ }
+ }}
+ >
+ {loading && <Loader2 className="h-4 w-4 animate-spin" />}
+ {t("common.confirm")}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
new file mode 100644
index 0000000000..7c5b2da0b0
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailStatementSection.tsx
@@ -0,0 +1,646 @@
+import { clone, create } from "@bufbuild/protobuf";
+import dayjs from "dayjs";
+import { ExternalLink, Loader2, Package, Upload } from "lucide-react";
+import { type ChangeEvent, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ planServiceClientConnect,
+ releaseServiceClientConnect,
+ sheetServiceClientConnect,
+} from "@/connect";
+import { MonacoEditor, ReadonlyMonaco } from "@/react/components/monaco";
+import { Alert } from "@/react/components/ui/alert";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import { pushNotification, useDatabaseV1Store, useSheetV1Store } from "@/store";
+import {
+ getDateForPbTimestampProtoEs,
+ isValidDatabaseName,
+ isValidReleaseName,
+ languageOfEngineV1,
+} from "@/types";
+import { VCSType } from "@/types/proto-es/v1/common_pb";
+import {
+ type Plan_Spec,
+ type PlanCheckRun,
+ PlanSchema,
+ UpdatePlanRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ GetReleaseRequestSchema,
+ type Release,
+ Release_Type,
+} from "@/types/proto-es/v1/release_service_pb";
+import { GetSheetRequestSchema } from "@/types/proto-es/v1/sheet_service_pb";
+import { extractDatabaseResourceName, hasProjectPermissionV2 } from "@/utils";
+import { getStatementSize, MAX_UPLOAD_FILE_SIZE_MB } from "@/utils/sheet";
+import { getInstanceResource } from "@/utils/v1/database";
+import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
+import {
+ extractSheetUID,
+ getSheetStatement,
+ setSheetStatement,
+} from "@/utils/v1/sheet";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+import {
+ createEmptyLocalSheet,
+ getLocalSheetByName,
+} from "../utils/localSheet";
+import { getSQLAdviceMarkers } from "../utils/sqlAdvice";
+
+const MAX_DISPLAYED_RELEASE_FILES = 4;
+
+export function PlanDetailStatementSection({
+ className,
+ planCheckRuns = [],
+ spec,
+}: {
+ className?: string;
+ planCheckRuns?: PlanCheckRun[];
+ spec: Plan_Spec;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, setEditing } = page;
+ const sheetStore = useSheetV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const releaseName =
+ spec.config?.case === "changeDatabaseConfig"
+ ? spec.config.value.release
+ : "";
+ const sheetName = useMemo(() => sheetNameOfSpec(spec), [spec]);
+ const [release, setRelease] = useState<Release>();
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSheetOversize, setIsSheetOversize] = useState(false);
+ const [isDownloading, setIsDownloading] = useState(false);
+ const [isEditing, setIsEditing] = useState(page.isCreating);
+ const [isSaving, setIsSaving] = useState(false);
+ const [statement, setStatement] = useState("");
+ const [draftStatement, setDraftStatement] = useState("");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const editingScope = useMemo(() => `statement:${spec.id}`, [spec.id]);
+ const targetDatabaseName = useMemo(() => {
+ if (
+ spec.config?.case !== "changeDatabaseConfig" &&
+ spec.config?.case !== "exportDataConfig"
+ ) {
+ return "";
+ }
+ return (spec.config.value.targets ?? []).find(isValidDatabaseName) ?? "";
+ }, [spec]);
+ const language = useMemo(() => {
+ if (!targetDatabaseName) return "sql";
+ const database = databaseStore.getDatabaseByName(targetDatabaseName);
+ return languageOfEngineV1(getInstanceResource(database).engine);
+ }, [databaseStore, targetDatabaseName]);
+ const autoCompleteContext = useMemo(() => {
+ if (!targetDatabaseName) return undefined;
+ return {
+ instance: extractDatabaseResourceName(targetDatabaseName).instance,
+ database: targetDatabaseName,
+ scene: "all" as const,
+ };
+ }, [targetDatabaseName]);
+ const statementTitle =
+ language === "sql" ? t("common.sql") : t("common.statement");
+ const displayedStatement = isEditing ? draftStatement : statement;
+ const isEmpty = displayedStatement.trim() === "";
+ const markers = useMemo(
+ () => getSQLAdviceMarkers(planCheckRuns),
+ [planCheckRuns]
+ );
+
+ useEffect(() => {
+ if (!isEditing) {
+ setDraftStatement(statement);
+ }
+ }, [isEditing, statement]);
+
+ useEffect(() => {
+ setEditing(editingScope, isEditing);
+ return () => setEditing(editingScope, false);
+ }, [editingScope, isEditing, setEditing]);
+
+ useEffect(() => {
+ setIsEditing(page.isCreating);
+ setDraftStatement("");
+ }, [page.isCreating, spec.id]);
+
+ useEffect(() => {
+ let canceled = false;
+
+ const load = async () => {
+ if (isValidReleaseName(releaseName)) {
+ try {
+ setIsLoading(true);
+ const nextRelease = await releaseServiceClientConnect.getRelease(
+ create(GetReleaseRequestSchema, { name: releaseName })
+ );
+ if (!canceled) {
+ setRelease(nextRelease);
+ }
+ } catch {
+ if (!canceled) {
+ setRelease(undefined);
+ }
+ } finally {
+ if (!canceled) setIsLoading(false);
+ }
+ return;
+ }
+
+ if (!sheetName) {
+ setStatement("");
+ setDraftStatement("");
+ setRelease(undefined);
+ setIsSheetOversize(false);
+ return;
+ }
+
+ try {
+ setIsLoading(true);
+ const uid = extractSheetUID(sheetName);
+ const sheet = uid.startsWith("-")
+ ? getLocalSheetByName(sheetName)
+ : await sheetStore.getOrFetchSheetByName(sheetName);
+ if (!sheet || canceled) return;
+ const nextStatement = getSheetStatement(sheet);
+ setStatement(nextStatement);
+ setDraftStatement(nextStatement);
+ setIsSheetOversize(getStatementSize(nextStatement) < sheet.contentSize);
+ } finally {
+ if (!canceled) setIsLoading(false);
+ }
+ };
+
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [releaseName, sheetName, sheetStore]);
+
+ if (isValidReleaseName(releaseName)) {
+ return (
+ <PlanDetailReleaseStatement
+ className={className}
+ isLoading={isLoading}
+ release={release}
+ releaseName={releaseName}
+ />
+ );
+ }
+
+ const canModifyStatement = Boolean(
+ !page.readonly &&
+ !page.plan.hasRollout &&
+ sheetName &&
+ project &&
+ (page.isCreating ||
+ currentUser.name === page.plan.creator ||
+ hasProjectPermissionV2(project, "bb.plans.update"))
+ );
+ const canEdit = canModifyStatement && !isSheetOversize && !page.isCreating;
+ const hasChanges = page.isCreating
+ ? draftStatement !== statement
+ : isEditing && draftStatement !== statement;
+ const canSave =
+ !isSaving &&
+ !isLoading &&
+ Boolean(sheetName) &&
+ draftStatement.trim() !== "" &&
+ hasChanges;
+
+ const updateLocalStatement = (nextStatement: string) => {
+ if (!sheetName) return;
+ const sheet = getLocalSheetByName(sheetName);
+ setSheetStatement(sheet, nextStatement);
+ setStatement(nextStatement);
+ setDraftStatement(nextStatement);
+ setIsSheetOversize(false);
+ if (page.isCreating) {
+ patchState({ plan: clone(PlanSchema, page.plan) });
+ }
+ };
+
+ const handleUploadClick = () => inputRef.current?.click();
+
+ const handleFileUpload = async (event: ChangeEvent<HTMLInputElement>) => {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) return;
+ if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("issue.upload-sql-file-max-size-exceeded", {
+ size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,
+ }),
+ });
+ return;
+ }
+ const nextStatement = await file.text();
+ if (isSheetOversize && statement.trim() !== "") {
+ const confirmed = window.confirm(t("issue.overwrite-current-statement"));
+ if (!confirmed) return;
+ }
+ if (page.isCreating) {
+ updateLocalStatement(nextStatement);
+ return;
+ }
+ setDraftStatement(nextStatement);
+ setIsEditing(true);
+ };
+
+ const patchPlanStatement = (nextSheetName: string) => {
+ const planPatch = clone(PlanSchema, page.plan);
+ const specToPatch = planPatch.specs.find(
+ (candidate) => candidate.id === spec.id
+ );
+ if (!specToPatch) return undefined;
+ if (
+ specToPatch.config?.case !== "changeDatabaseConfig" &&
+ specToPatch.config?.case !== "exportDataConfig"
+ ) {
+ return undefined;
+ }
+ specToPatch.config.value.sheet = nextSheetName;
+ return planPatch;
+ };
+
+ const handleSave = async () => {
+ if (!project || !sheetName || !canSave) return;
+
+ if (page.isCreating) {
+ updateLocalStatement(draftStatement);
+ return;
+ }
+
+ try {
+ setIsSaving(true);
+ const sheet = createEmptyLocalSheet();
+ setSheetStatement(sheet, draftStatement);
+ const createdSheet = await sheetStore.createSheet(project.name, sheet);
+ const nextPlan = patchPlanStatement(createdSheet.name);
+ if (!nextPlan) return;
+ const request = create(UpdatePlanRequestSchema, {
+ plan: nextPlan,
+ updateMask: { paths: ["specs"] },
+ });
+ const response = await planServiceClientConnect.updatePlan(request);
+ page.patchState({ plan: response });
+ setStatement(draftStatement);
+ setIsEditing(false);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ void page.refreshState();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ const downloadSheet = async () => {
+ if (!sheetName) return;
+ try {
+ setIsDownloading(true);
+ const uid = extractSheetUID(sheetName);
+ const content = uid.startsWith("-")
+ ? statement
+ : new TextDecoder().decode(
+ (
+ await sheetServiceClientConnect.getSheet(
+ create(GetSheetRequestSchema, {
+ name: sheetName,
+ raw: true,
+ })
+ )
+ ).content
+ );
+ const filename = `${sheetName.split("/").pop() || "sheet"}.sql`;
+ const blob = new Blob([content], { type: "text/plain" });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = filename;
+ document.body.appendChild(anchor);
+ anchor.click();
+ document.body.removeChild(anchor);
+ URL.revokeObjectURL(url);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setIsDownloading(false);
+ }
+ };
+
+ const editorContent = page.isCreating ? statement : draftStatement;
+
+ return (
+ <div className={cn("flex flex-col gap-y-1", className)}>
+ <div className="flex items-start justify-between gap-2">
+ <div
+ className={cn(
+ "flex items-center gap-x-1 textlabel uppercase",
+ isEmpty && "text-red-600"
+ )}
+ >
+ <span>{statementTitle}</span>
+ {isEmpty && <span className="text-error">*</span>}
+ </div>
+ <input
+ ref={inputRef}
+ accept=".sql,.txt,application/sql,text/plain"
+ className="hidden"
+ onChange={(event) => void handleFileUpload(event)}
+ type="file"
+ />
+ <div className="flex flex-wrap items-center justify-end gap-x-2 gap-y-2">
+ {(canModifyStatement || isEditing) && (
+ <div className="flex flex-wrap items-center justify-end gap-x-2 gap-y-2">
+ <Button onClick={handleUploadClick} size="xs" variant="outline">
+ <Upload className="h-3.5 w-3.5" />
+ {t("issue.upload-sql")}
+ </Button>
+ {!isEditing ? (
+ canEdit ? (
+ <Button
+ onClick={() => setIsEditing(true)}
+ size="xs"
+ variant="outline"
+ >
+ {t("common.edit")}
+ </Button>
+ ) : null
+ ) : !page.isCreating ? (
+ <>
+ <Button
+ disabled={!canSave}
+ onClick={() => void handleSave()}
+ size="xs"
+ variant="outline"
+ >
+ {isSaving && (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ )}
+ {t("common.save")}
+ </Button>
+ <Button
+ onClick={() => {
+ setDraftStatement(statement);
+ setIsEditing(false);
+ }}
+ size="xs"
+ variant="ghost"
+ >
+ {t("common.cancel")}
+ </Button>
+ </>
+ ) : null}
+ </div>
+ )}
+ </div>
+ </div>
+ {isSheetOversize && (
+ <Alert variant="warning">
+ <div className="flex items-center justify-between gap-x-4">
+ <span>{t("issue.statement-from-sheet-warning")}</span>
+ {sheetName && (
+ <Button
+ disabled={isDownloading}
+ onClick={() => void downloadSheet()}
+ size="xs"
+ variant="outline"
+ >
+ {isDownloading && (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ )}
+ {t("common.download")}
+ </Button>
+ )}
+ </div>
+ </Alert>
+ )}
+ {isLoading ? (
+ <div className="rounded-md border border-control-border bg-white px-4 py-3 text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ ) : statement || draftStatement || isEditing ? (
+ <div className="relative">
+ {isEditing ? (
+ <MonacoEditor
+ advices={page.isCreating ? markers : []}
+ autoCompleteContext={autoCompleteContext}
+ className="relative h-auto max-h-[600px] min-h-[120px]"
+ content={editorContent}
+ language={language}
+ onChange={(nextStatement) => {
+ if (page.isCreating) {
+ updateLocalStatement(nextStatement);
+ return;
+ }
+ setDraftStatement(nextStatement);
+ }}
+ />
+ ) : (
+ <ReadonlyMonaco
+ advices={markers}
+ className="relative h-auto max-h-[600px] min-h-[120px]"
+ content={statement}
+ language={language}
+ />
+ )}
+ </div>
+ ) : (
+ <div className="rounded-md border border-control-border bg-white px-4 py-3 text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function PlanDetailReleaseStatement({
+ className,
+ isLoading,
+ release,
+ releaseName,
+}: {
+ className?: string;
+ isLoading: boolean;
+ release?: Release;
+ releaseName: string;
+}) {
+ const { t } = useTranslation();
+ const releaseTitle = useMemo(() => {
+ const name = release?.name || releaseName;
+ const parts = name.split("/");
+ return parts[parts.length - 1] || name;
+ }, [release?.name, releaseName]);
+ const displayedFiles =
+ release?.files.slice(0, MAX_DISPLAYED_RELEASE_FILES) ?? [];
+ const createdTime = release?.createTime
+ ? dayjs(getDateForPbTimestampProtoEs(release.createTime)).format(
+ "YYYY-MM-DD HH:mm:ss"
+ )
+ : undefined;
+
+ return (
+ <div className={cn("flex h-full flex-col gap-y-2", className)}>
+ <Alert className="border-0" variant="info">
+ {t("release.change-tip")}
+ </Alert>
+ <div className="flex items-center justify-between gap-x-2">
+ <div className="flex items-center gap-x-1 text-base font-medium">
+ <Package className="h-4 w-4" />
+ <span>{releaseTitle}</span>
+ </div>
+ {isValidReleaseName(release?.name ?? "") && (
+ <a
+ className="inline-flex items-center gap-x-1 text-sm text-accent hover:underline"
+ href={`/${release?.name}`}
+ rel="noreferrer"
+ target="_blank"
+ >
+ <span>{t("common.view")}</span>
+ <ExternalLink className="h-4 w-4" />
+ </a>
+ )}
+ </div>
+ {isLoading ? (
+ <div className="rounded-md border border-control-border bg-gray-50 p-4">
+ <div className="flex items-center gap-x-2 text-sm text-gray-600">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span>{t("common.loading")}</span>
+ </div>
+ </div>
+ ) : release ? (
+ <div className="rounded-md border border-control-border bg-gray-50 px-4 py-3">
+ <div className="flex flex-col gap-y-3">
+ <div>
+ <div className="text-sm font-medium text-main">
+ {releaseTitle}
+ </div>
+ <div className="mt-1 text-xs text-control-light">
+ {release.name}
+ </div>
+ </div>
+ {release.files.length > 0 && (
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center justify-between">
+ <div className="text-sm font-medium text-control">
+ {t("release.files")} ({release.files.length})
+ </div>
+ {release.files.length > MAX_DISPLAYED_RELEASE_FILES &&
+ isValidReleaseName(release.name) && (
+ <a
+ className="text-sm text-accent hover:underline"
+ href={`/${release.name}`}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {t("release.view-all-files")}
+ </a>
+ )}
+ </div>
+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-3">
+ {displayedFiles.map((file) => (
+ <div
+ key={file.path}
+ className="flex items-center justify-between rounded-sm bg-white p-2 text-xs"
+ >
+ <div className="mr-2 min-w-0 flex-1">
+ <div className="truncate font-medium">{file.path}</div>
+ <div className="text-control-light">{file.version}</div>
+ </div>
+ <div className="shrink-0 rounded-sm bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800">
+ {getReleaseFileTypeText(release.type, t)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ {release.vcsSource && (
+ <div className="flex flex-col gap-y-1">
+ <div className="text-sm font-medium text-control">
+ {t("release.vcs-source")}
+ </div>
+ <div className="text-xs">
+ <span className="text-control-light">
+ {getVCSTypeText(release.vcsSource.vcsType, t)}:
+ </span>
+ {release.vcsSource.url && (
+ <a
+ className="ml-1 text-accent hover:underline"
+ href={release.vcsSource.url}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {release.vcsSource.url}
+ </a>
+ )}
+ </div>
+ </div>
+ )}
+ {createdTime && (
+ <div className="text-xs text-control-light">{createdTime}</div>
+ )}
+ </div>
+ </div>
+ ) : (
+ <div className="rounded-md border border-error/20 bg-red-50/20 p-4">
+ <div className="text-sm text-red-600">{t("release.not-found")}</div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function getReleaseFileTypeText(
+ fileType: Release_Type,
+ t: (key: string, options?: Record<string, unknown>) => string
+) {
+ switch (fileType) {
+ case Release_Type.VERSIONED:
+ return t("release.file-type.versioned");
+ case Release_Type.DECLARATIVE:
+ return t("release.file-type.declarative");
+ default:
+ return t("release.file-type.unspecified");
+ }
+}
+
+function getVCSTypeText(
+ vcsType: VCSType,
+ t: (key: string, options?: Record<string, unknown>) => string
+) {
+ switch (vcsType) {
+ case VCSType.GITHUB:
+ return "GitHub";
+ case VCSType.GITLAB:
+ return "GitLab";
+ case VCSType.BITBUCKET:
+ return "Bitbucket";
+ case VCSType.AZURE_DEVOPS:
+ return "Azure DevOps";
+ default:
+ return t("release.vcs-type.unspecified");
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx
new file mode 100644
index 0000000000..8d6aca6743
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTabStrip.tsx
@@ -0,0 +1,54 @@
+import type { ReactNode } from "react";
+import { cn } from "@/react/lib/utils";
+
+export function PlanDetailTabStrip({
+ action,
+ children,
+}: {
+ action?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <div className="relative bg-white pt-3">
+ <div className="absolute bottom-0 w-full border-b border-b-gray-200 leading-0" />
+ <div className="flex items-center justify-between gap-x-4">
+ <div className="flex min-w-0 flex-1 items-center overflow-x-auto px-4">
+ {children}
+ </div>
+ {action && <div className="shrink-0 px-4">{action}</div>}
+ </div>
+ </div>
+ );
+}
+
+export function PlanDetailTabItem({
+ action,
+ children,
+ onSelect,
+ selected,
+}: {
+ action?: ReactNode;
+ children: ReactNode;
+ onSelect: () => void;
+ selected: boolean;
+}) {
+ return (
+ <div
+ className={cn(
+ "relative flex shrink-0 items-center rounded-t-lg border transition-all",
+ selected
+ ? "border-gray-200 border-b-transparent bg-white"
+ : "border-b-gray-200 border-transparent hover:opacity-80"
+ )}
+ >
+ <button
+ className="flex min-h-9 shrink-0 items-center gap-2 px-4 py-2 text-left"
+ onClick={onSelect}
+ type="button"
+ >
+ {children}
+ </button>
+ {action}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx
new file mode 100644
index 0000000000..1e6af17dde
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRolloutActionPanel.tsx
@@ -0,0 +1,737 @@
+import { create } from "@bufbuild/protobuf";
+import { TimestampSchema } from "@bufbuild/protobuf/wkt";
+import { Check, FastForward, Loader2, Pause, X } from "lucide-react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { EngineIconPath } from "@/react/components/instance/constants";
+import { Button } from "@/react/components/ui/button";
+import { Input } from "@/react/components/ui/input";
+import { RadioGroup, RadioGroupItem } from "@/react/components/ui/radio-group";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { Textarea } from "@/react/components/ui/textarea";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import {
+ pushNotification,
+ useCurrentUserV1,
+ useDatabaseV1Store,
+ useEnvironmentV1Store,
+ useProjectV1Store,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";
+import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ BatchCancelTaskRunsRequestSchema,
+ BatchRunTasksRequestSchema,
+ BatchSkipTasksRequestSchema,
+ ListTaskRunsRequestSchema,
+ Task_Status,
+ Task_Type,
+ TaskRun_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ extractDatabaseResourceName,
+ extractInstanceResourceName,
+ extractStageUID,
+} from "@/utils";
+import {
+ CANCELABLE_TASK_STATUSES,
+ canRolloutTasks,
+ preloadRolloutPermissionContext,
+ RUNNABLE_TASK_STATUSES,
+} from "../../issue-detail/utils/rollout";
+import { usePlanDetailContext } from "../context/PlanDetailContext";
+
+const DEFAULT_RUN_DELAY_MS = 60 * 60 * 1000;
+
+export type PlanDetailTaskRolloutAction = "RUN" | "SKIP" | "CANCEL";
+
+export type PlanDetailTaskRolloutTarget = {
+ type: "tasks";
+ tasks?: Task[];
+ stage?: Stage;
+};
+
+const pluralizedLabel = (raw: string, count: number): string => {
+ const [singular, plural] = raw.split("|").map((part) => part.trim());
+ if (!plural) return singular;
+ return count === 1 ? singular : plural;
+};
+
+export function PlanDetailTaskRolloutActionPanel({
+ action,
+ onConfirm,
+ onOpenChange,
+ open,
+ target,
+}: {
+ action?: PlanDetailTaskRolloutAction;
+ onConfirm?: () => Promise<void> | void;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+ target: PlanDetailTaskRolloutTarget;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const projectStore = useProjectV1Store();
+ const currentUser = useCurrentUserV1().value;
+ const projectName = `${projectNamePrefix}${page.projectId}`;
+ const project = projectStore.getProjectByName(projectName);
+ const [loading, setLoading] = useState(false);
+ const [permissionLoading, setPermissionLoading] = useState(false);
+ const [canRun, setCanRun] = useState(true);
+ const [comment, setComment] = useState("");
+ const [runTimeInMS, setRunTimeInMS] = useState<number | undefined>();
+ const [skipPriorBackup, setSkipPriorBackup] = useState(false);
+
+ const allRolloutTasks = useMemo(
+ () => page.rollout?.stages.flatMap((stage) => stage.tasks) ?? [],
+ [page.rollout]
+ );
+ const rolloutType = useMemo(() => {
+ if (
+ allRolloutTasks.every((task) => task.type === Task_Type.DATABASE_CREATE)
+ ) {
+ return "DATABASE_CREATE";
+ }
+ if (
+ allRolloutTasks.every((task) => task.type === Task_Type.DATABASE_EXPORT)
+ ) {
+ return "DATABASE_EXPORT";
+ }
+ return "DATABASE_CHANGE";
+ }, [allRolloutTasks]);
+ const isDatabaseCreateOrExport =
+ rolloutType === "DATABASE_CREATE" || rolloutType === "DATABASE_EXPORT";
+ const baseTasks = useMemo(() => {
+ if (target.tasks) {
+ return target.tasks;
+ }
+ if (isDatabaseCreateOrExport) {
+ return allRolloutTasks;
+ }
+ return target.stage?.tasks ?? [];
+ }, [allRolloutTasks, isDatabaseCreateOrExport, target.stage, target.tasks]);
+ const eligibleTasks = useMemo(() => {
+ if (action === "RUN" || action === "SKIP") {
+ return baseTasks.filter((task) =>
+ RUNNABLE_TASK_STATUSES.includes(task.status)
+ );
+ }
+ if (action === "CANCEL") {
+ return baseTasks.filter((task) =>
+ CANCELABLE_TASK_STATUSES.includes(task.status)
+ );
+ }
+ return [];
+ }, [action, baseTasks]);
+ const hasPriorBackupTasks = useMemo(() => {
+ return eligibleTasks.some((task) => {
+ const spec = page.plan.specs.find((item) => item.id === task.specId);
+ return (
+ spec?.config.case === "changeDatabaseConfig" &&
+ spec.config.value.enablePriorBackup
+ );
+ });
+ }, [eligibleTasks, page.plan.specs]);
+ const showStageInfo = !isDatabaseCreateOrExport;
+ const showTaskInfo = rolloutType !== "DATABASE_CREATE";
+ const taskCountSuffix = useMemo(() => {
+ if (
+ eligibleTasks.length <= 1 ||
+ !showStageInfo ||
+ !target.stage?.tasks.length
+ ) {
+ return "";
+ }
+ const total = target.stage.tasks.length;
+ return eligibleTasks.length === total
+ ? String(eligibleTasks.length)
+ : `${eligibleTasks.length} / ${total}`;
+ }, [eligibleTasks.length, showStageInfo, target.stage?.tasks.length]);
+
+ useEffect(() => {
+ if (!open) {
+ setComment("");
+ setRunTimeInMS(undefined);
+ setSkipPriorBackup(false);
+ return;
+ }
+
+ let canceled = false;
+ const prepare = async () => {
+ setPermissionLoading(true);
+ setCanRun(false);
+ await preloadRolloutPermissionContext({
+ environment: target.stage?.environment,
+ projectName: project?.name ?? "",
+ tasks: eligibleTasks,
+ });
+ if (canceled) return;
+ setCanRun(
+ project
+ ? canRolloutTasks({
+ currentUser,
+ environment: target.stage?.environment,
+ issue: page.issue,
+ project,
+ tasks: eligibleTasks,
+ })
+ : false
+ );
+ setPermissionLoading(false);
+ };
+
+ void prepare();
+ return () => {
+ canceled = true;
+ };
+ }, [
+ currentUser,
+ eligibleTasks,
+ open,
+ page.issue,
+ project,
+ target.stage?.environment,
+ ]);
+
+ useEffect(() => {
+ if (!open) return;
+ const runTimes = new Set(
+ eligibleTasks.map((task) => task.runTime).filter(Boolean)
+ );
+ if (runTimes.size !== 1) return;
+ const runTime = [...runTimes][0];
+ if (!runTime) return;
+ setRunTimeInMS(Number(runTime.seconds) * 1000 + runTime.nanos / 1000000);
+ }, [eligibleTasks, open]);
+
+ const validationErrors = useMemo(() => {
+ const errors: string[] = [];
+ if (eligibleTasks.length === 0) {
+ errors.push(t("common.no-data"));
+ }
+ if (!canRun) {
+ errors.push(
+ page.issue?.type === Issue_Type.DATABASE_EXPORT
+ ? t("task.data-export-creator-only")
+ : t("task.no-permission")
+ );
+ }
+ if (
+ action === "RUN" &&
+ runTimeInMS !== undefined &&
+ runTimeInMS <= Date.now()
+ ) {
+ errors.push(t("task.error.scheduled-time-must-be-in-the-future"));
+ }
+ return errors;
+ }, [action, canRun, eligibleTasks.length, page.issue?.type, runTimeInMS, t]);
+
+ const handleConfirm = useCallback(async () => {
+ if (!page.rollout || !action || validationErrors.length > 0) {
+ return;
+ }
+
+ try {
+ setLoading(true);
+ if (action === "RUN") {
+ await runTasks({
+ rolloutName: page.rollout.name,
+ runTimeInMS,
+ skipPriorBackup,
+ tasks: eligibleTasks,
+ });
+ } else if (action === "SKIP") {
+ await skipTasks({
+ comment,
+ rolloutName: page.rollout.name,
+ tasks: eligibleTasks,
+ });
+ } else {
+ await cancelTasks({
+ rolloutName: page.rollout.name,
+ tasks: eligibleTasks,
+ });
+ }
+ await onConfirm?.();
+ onOpenChange(false);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setLoading(false);
+ }
+ }, [
+ action,
+ comment,
+ eligibleTasks,
+ onConfirm,
+ onOpenChange,
+ page.rollout,
+ runTimeInMS,
+ skipPriorBackup,
+ t,
+ validationErrors.length,
+ ]);
+
+ if (!action) {
+ return null;
+ }
+
+ const title =
+ action === "RUN"
+ ? pluralizedLabel(t("task.run-task"), eligibleTasks.length)
+ : action === "SKIP"
+ ? pluralizedLabel(t("task.skip-task"), eligibleTasks.length)
+ : pluralizedLabel(t("task.cancel-task"), eligibleTasks.length);
+ const confirmButtonText =
+ action === "RUN"
+ ? t("common.run")
+ : action === "SKIP"
+ ? t("common.skip")
+ : t("common.cancel");
+
+ return (
+ <Sheet onOpenChange={onOpenChange} open={open}>
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>{title}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="relative">
+ <div className="flex h-full flex-col gap-y-4 px-1">
+ {validationErrors.length > 0 && (
+ <div className="rounded-xs border border-error/30 bg-error/5 px-4 py-3">
+ <div className="mb-1 font-medium text-error">
+ {t("rollout.task-execution-errors")}
+ </div>
+ <ul className="flex list-inside list-disc flex-col gap-y-1 text-sm text-error">
+ {validationErrors.map((error) => (
+ <li key={error}>{error}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {showStageInfo && target.stage?.environment && (
+ <div className="flex shrink-0 flex-row items-center justify-start gap-x-2 overflow-y-hidden">
+ <label className="font-medium text-control">
+ {t("common.stage")}
+ </label>
+ <PlanDetailStageEnvironment
+ environmentName={target.stage.environment}
+ />
+ </div>
+ )}
+
+ {showTaskInfo && (
+ <div className="flex shrink-0 flex-col gap-y-1">
+ <label className="text-control">
+ <span className="font-medium">{t("common.task")}</span>
+ {taskCountSuffix && (
+ <span className="opacity-80"> ({taskCountSuffix})</span>
+ )}
+ </label>
+ <div className="max-h-64 overflow-y-auto">
+ <ul className="flex flex-col gap-y-2 text-sm">
+ {eligibleTasks.map((task) => (
+ <li
+ className="flex h-8 items-center gap-x-2"
+ key={task.name}
+ >
+ <PlanDetailTaskStatus status={task.status} />
+ <PlanDetailTaskDatabaseName task={task} />
+ </li>
+ ))}
+ </ul>
+ </div>
+ </div>
+ )}
+
+ {action === "RUN" && (
+ <div className="flex flex-col">
+ <h3 className="mb-1 font-medium text-control">
+ {t("task.execution-time")}
+ </h3>
+ <RadioGroup
+ className="flex! flex-col gap-2 sm:flex-row sm:gap-4"
+ onValueChange={(value) =>
+ setRunTimeInMS(
+ value === "immediate"
+ ? undefined
+ : Date.now() + DEFAULT_RUN_DELAY_MS
+ )
+ }
+ value={runTimeInMS === undefined ? "immediate" : "scheduled"}
+ >
+ <RadioGroupItem value="immediate">
+ {t("task.run-immediately.self")}
+ </RadioGroupItem>
+ <RadioGroupItem value="scheduled">
+ {t("task.schedule-for-later.self")}
+ </RadioGroupItem>
+ </RadioGroup>
+ <div className="mt-1 text-sm text-control-light">
+ {runTimeInMS === undefined
+ ? t("task.run-immediately.description")
+ : t("task.schedule-for-later.description")}
+ </div>
+ {runTimeInMS !== undefined && (
+ <Input
+ className="mt-2"
+ onChange={(event) =>
+ setRunTimeInMS(
+ parseDatetimeLocalValue(event.target.value)
+ )
+ }
+ placeholder={t("task.select-scheduled-time")}
+ type="datetime-local"
+ value={formatDatetimeLocalValue(runTimeInMS)}
+ />
+ )}
+ </div>
+ )}
+
+ {action === "RUN" && hasPriorBackupTasks && (
+ <div className="flex flex-col">
+ <label className="inline-flex items-center gap-x-2 text-sm">
+ <input
+ checked={skipPriorBackup}
+ className="h-4 w-4 rounded border-control-border"
+ onChange={(event) =>
+ setSkipPriorBackup(event.target.checked)
+ }
+ type="checkbox"
+ />
+ <span>{t("task.skip-prior-backup")}</span>
+ </label>
+ <div className="ml-6 text-sm text-control-light">
+ {t("task.skip-prior-backup-description")}
+ </div>
+ </div>
+ )}
+
+ {action === "SKIP" && page.issue && (
+ <div className="flex shrink-0 flex-col gap-y-1">
+ <p className="font-medium text-control">{t("common.reason")}</p>
+ <Textarea
+ className="min-h-28"
+ maxLength={1000}
+ onChange={(event) => setComment(event.target.value)}
+ placeholder={t("issue.leave-a-comment")}
+ value={comment}
+ />
+ </div>
+ )}
+ </div>
+
+ {(loading || permissionLoading) && (
+ <div className="absolute inset-0 flex items-center justify-center bg-white/50">
+ <Loader2 className="h-6 w-6 animate-spin text-control" />
+ </div>
+ )}
+ </SheetBody>
+ <SheetFooter>
+ <Button onClick={() => onOpenChange(false)} variant="ghost">
+ {t("common.close")}
+ </Button>
+ <Tooltip
+ content={
+ validationErrors.length > 0 ? (
+ <ul className="flex list-inside list-disc flex-col gap-y-1">
+ {validationErrors.map((error) => (
+ <li key={error}>{error}</li>
+ ))}
+ </ul>
+ ) : null
+ }
+ >
+ <div>
+ <Button
+ disabled={permissionLoading || validationErrors.length > 0}
+ onClick={() => void handleConfirm()}
+ >
+ {loading && <Loader2 className="h-4 w-4 animate-spin" />}
+ {confirmButtonText}
+ </Button>
+ </div>
+ </Tooltip>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
+
+async function runTasks({
+ rolloutName,
+ runTimeInMS,
+ skipPriorBackup,
+ tasks,
+}: {
+ rolloutName: string;
+ runTimeInMS?: number;
+ skipPriorBackup: boolean;
+ tasks: Task[];
+}) {
+ const tasksByStage = groupTasksByStage(tasks);
+ for (const [stageId, stageTasks] of tasksByStage) {
+ const request = create(BatchRunTasksRequestSchema, {
+ parent: `${rolloutName}/stages/${stageId}`,
+ tasks: stageTasks.map((task) => task.name),
+ });
+ if (runTimeInMS !== undefined) {
+ request.runTime = create(TimestampSchema, {
+ seconds: BigInt(Math.floor(runTimeInMS / 1000)),
+ nanos: (runTimeInMS % 1000) * 1000000,
+ });
+ }
+ request.skipPriorBackup = skipPriorBackup;
+ await rolloutServiceClientConnect.batchRunTasks(request);
+ }
+}
+
+async function skipTasks({
+ comment,
+ rolloutName,
+ tasks,
+}: {
+ comment: string;
+ rolloutName: string;
+ tasks: Task[];
+}) {
+ const tasksByStage = groupTasksByStage(tasks);
+ for (const [stageId, stageTasks] of tasksByStage) {
+ await rolloutServiceClientConnect.batchSkipTasks(
+ create(BatchSkipTasksRequestSchema, {
+ parent: `${rolloutName}/stages/${stageId}`,
+ reason: comment,
+ tasks: stageTasks.map((task) => task.name),
+ })
+ );
+ }
+}
+
+async function cancelTasks({
+ rolloutName,
+ tasks,
+}: {
+ rolloutName: string;
+ tasks: Task[];
+}) {
+ const tasksByStage = groupTasksByStage(tasks);
+ const cancelableRuns = new Map<string, string[]>();
+ for (const [stageId, stageTasks] of tasksByStage) {
+ const taskNames = new Set(stageTasks.map((task) => task.name));
+ const response = await rolloutServiceClientConnect.listTaskRuns(
+ create(ListTaskRunsRequestSchema, {
+ parent: `${rolloutName}/stages/${stageId}/tasks/-`,
+ })
+ );
+ const runs = response.taskRuns
+ .filter((run) => {
+ const taskName = run.name.split("/taskRuns/")[0];
+ return (
+ taskNames.has(taskName) &&
+ (run.status === TaskRun_Status.PENDING ||
+ run.status === TaskRun_Status.RUNNING)
+ );
+ })
+ .map((run) => run.name);
+ if (runs.length > 0) {
+ cancelableRuns.set(`${rolloutName}/stages/${stageId}`, runs);
+ }
+ }
+
+ await Promise.all(
+ [...cancelableRuns.entries()].map(([stageName, taskRuns]) =>
+ rolloutServiceClientConnect.batchCancelTaskRuns(
+ create(BatchCancelTaskRunsRequestSchema, {
+ parent: `${stageName}/tasks/-`,
+ taskRuns,
+ })
+ )
+ )
+ );
+}
+
+function groupTasksByStage(tasks: Task[]) {
+ const grouped = new Map<string, Task[]>();
+ for (const task of tasks) {
+ const stageId = extractStageUID(task.name);
+ if (!stageId) continue;
+ if (!grouped.has(stageId)) {
+ grouped.set(stageId, []);
+ }
+ grouped.get(stageId)?.push(task);
+ }
+ return grouped;
+}
+
+function formatDatetimeLocalValue(value?: number) {
+ if (value === undefined) return "";
+ const date = new Date(value);
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, "0");
+ const day = String(date.getDate()).padStart(2, "0");
+ const hours = String(date.getHours()).padStart(2, "0");
+ const minutes = String(date.getMinutes()).padStart(2, "0");
+ return `${year}-${month}-${day}T${hours}:${minutes}`;
+}
+
+function parseDatetimeLocalValue(value: string) {
+ return value ? new Date(value).getTime() : undefined;
+}
+
+function PlanDetailTaskDatabaseName({ task }: { task: Task }) {
+ if (task.target) {
+ return <PlanDetailDatabaseTarget target={task.target} />;
+ }
+ return <span className="truncate">{task.name.split("/").at(-1)}</span>;
+}
+
+function PlanDetailDatabaseTarget({ target }: { target: string }) {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const environmentStore = useEnvironmentV1Store();
+ const database = databaseStore.getDatabaseByName(target);
+ const environment = environmentStore.getEnvironmentByName(
+ database.effectiveEnvironment ??
+ database.instanceResource?.environment ??
+ ""
+ );
+ const instance = database.instanceResource;
+ const engineIcon = instance ? EngineIconPath[instance.engine] : "";
+ const { databaseName } = extractDatabaseResourceName(target);
+ const instanceTitle =
+ instance?.title ||
+ extractInstanceResourceName(target) ||
+ t("common.unknown");
+
+ return (
+ <div className="flex min-w-0 items-center truncate text-sm">
+ {engineIcon && (
+ <img alt="" className="mr-1 inline-block h-4 w-4" src={engineIcon} />
+ )}
+ <span className="mr-1 truncate text-gray-400">{environment.title}</span>
+ <span className="truncate text-gray-600">{instanceTitle}</span>
+ <span className="mx-1 shrink-0 text-gray-500 opacity-60">›</span>
+ <span className="truncate text-gray-800">{databaseName}</span>
+ </div>
+ );
+}
+
+function PlanDetailStageEnvironment({
+ environmentName,
+}: {
+ environmentName: string;
+}) {
+ const environmentStore = useEnvironmentV1Store();
+ const environment = environmentStore.getEnvironmentByName(environmentName);
+
+ return (
+ <span className="text-sm text-control">
+ {environment.title || environmentName.split("/").at(-1)}
+ </span>
+ );
+}
+
+function PlanDetailTaskStatus({ status }: { status: Task_Status }) {
+ const { t } = useTranslation();
+ const label = taskStatusLabel(t, status);
+ return (
+ <Tooltip content={label}>
+ <div
+ aria-label={label}
+ className={cn(
+ "relative flex h-5 w-5 shrink-0 select-none items-center justify-center overflow-hidden rounded-full",
+ taskStatusClassName(status)
+ )}
+ >
+ {status === Task_Status.NOT_STARTED && (
+ <span className="h-1/2 w-1/2 rounded-full bg-control" />
+ )}
+ {status === Task_Status.PENDING && <Pause className="h-3/4 w-3/4" />}
+ {status === Task_Status.RUNNING && (
+ <div className="relative flex h-1/2 w-1/2 overflow-visible">
+ <span
+ className="absolute z-0 h-full w-full animate-ping-slow rounded-full"
+ style={{ backgroundColor: "rgba(37, 99, 235, 0.5)" }}
+ />
+ <span className="z-1 h-full w-full rounded-full bg-info" />
+ </div>
+ )}
+ {status === Task_Status.SKIPPED && (
+ <FastForward className="h-3/4 w-3/4" />
+ )}
+ {status === Task_Status.DONE && <Check className="h-3/4 w-3/4" />}
+ {status === Task_Status.FAILED && (
+ <span className="rounded-full text-base font-medium">!</span>
+ )}
+ {status === Task_Status.CANCELED && (
+ <span className="text-base leading-none">-</span>
+ )}
+ {status !== Task_Status.CANCELED &&
+ status !== Task_Status.FAILED &&
+ status !== Task_Status.DONE &&
+ status !== Task_Status.SKIPPED &&
+ status !== Task_Status.RUNNING &&
+ status !== Task_Status.PENDING &&
+ status !== Task_Status.NOT_STARTED && <X className="h-3/4 w-3/4" />}
+ </div>
+ </Tooltip>
+ );
+}
+
+function taskStatusClassName(status: Task_Status) {
+ switch (status) {
+ case Task_Status.NOT_STARTED:
+ return "border-2 border-control bg-white";
+ case Task_Status.PENDING:
+ case Task_Status.RUNNING:
+ return "border-2 border-info bg-white text-info";
+ case Task_Status.SKIPPED:
+ return "border-2 border-control-light bg-white text-gray-600";
+ case Task_Status.DONE:
+ return "bg-success text-white";
+ case Task_Status.FAILED:
+ return "bg-error text-white";
+ case Task_Status.CANCELED:
+ return "border-2 border-control-light bg-white text-control-light";
+ default:
+ return "border border-dashed border-control bg-white";
+ }
+}
+
+function taskStatusLabel(t: (key: string) => string, status: Task_Status) {
+ switch (status) {
+ case Task_Status.NOT_STARTED:
+ return t("task.status.not-started");
+ case Task_Status.PENDING:
+ return t("task.status.pending");
+ case Task_Status.RUNNING:
+ return t("task.status.running");
+ case Task_Status.SKIPPED:
+ return t("task.status.skipped");
+ case Task_Status.DONE:
+ return t("task.status.done");
+ case Task_Status.FAILED:
+ return t("task.status.failed");
+ case Task_Status.CANCELED:
+ return t("task.status.canceled");
+ default:
+ return t("task.status.not-started");
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsx
new file mode 100644
index 0000000000..cdf0ab860f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunDetail.tsx
@@ -0,0 +1,67 @@
+import { RefreshCcw } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { TaskRunLogViewer } from "@/react/components/task-run-log";
+import { Button } from "@/react/components/ui/button";
+import {
+ Tabs,
+ TabsList,
+ TabsPanel,
+ TabsTrigger,
+} from "@/react/components/ui/tabs";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { PlanDetailTaskRunSession } from "./PlanDetailTaskRunSession";
+
+export function PlanDetailTaskRunDetail({
+ databaseEngine,
+ taskRun,
+}: {
+ databaseEngine?: Engine;
+ taskRun: TaskRun;
+}) {
+ const { t } = useTranslation();
+ const [detailKey, setDetailKey] = useState(0);
+ const showSessionTab = databaseEngine === Engine.POSTGRES;
+ const showRefreshButton = taskRun.status === TaskRun_Status.RUNNING;
+
+ return (
+ <Tabs defaultValue="logs">
+ <TabsList className="gap-x-6">
+ <TabsTrigger value="logs">{t("issue.task-run.logs")}</TabsTrigger>
+ {showSessionTab && (
+ <TabsTrigger value="session">
+ {t("issue.task-run.session")}
+ </TabsTrigger>
+ )}
+ </TabsList>
+ {showRefreshButton && (
+ <div className="mt-2 flex justify-end">
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => setDetailKey((value) => value + 1)}
+ >
+ <RefreshCcw className="h-3.5 w-3.5" />
+ {t("common.refresh")}
+ </Button>
+ </div>
+ )}
+ <TabsPanel value="logs">
+ <TaskRunLogViewer
+ key={`logs-${taskRun.name}-${detailKey}`}
+ taskRunName={taskRun.name}
+ />
+ </TabsPanel>
+ {showSessionTab && (
+ <TabsPanel value="session">
+ <PlanDetailTaskRunSession
+ key={`session-${taskRun.name}-${detailKey}`}
+ taskRun={taskRun}
+ />
+ </TabsPanel>
+ )}
+ </Tabs>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx
new file mode 100644
index 0000000000..ae42768361
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunSession.tsx
@@ -0,0 +1,183 @@
+import { create } from "@bufbuild/protobuf";
+import { createContextValues } from "@connectrpc/connect";
+import { AlignHorizontalJustifyStart, Loader2 } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { silentContextKey } from "@/connect/context-key";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/react/components/ui/table";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import {
+ GetTaskRunSessionRequestSchema,
+ type TaskRun,
+ TaskRun_Status,
+ type TaskRunSession_Postgres,
+ type TaskRunSession_Postgres_Session,
+} from "@/types/proto-es/v1/rollout_service_pb";
+
+export function PlanDetailTaskRunSession({ taskRun }: { taskRun: TaskRun }) {
+ const { t } = useTranslation();
+ const [loading, setLoading] = useState(false);
+ const [session, setSession] = useState<TaskRunSession_Postgres | undefined>();
+
+ useEffect(() => {
+ let canceled = false;
+
+ const load = async () => {
+ if (taskRun.status !== TaskRun_Status.RUNNING) {
+ setSession(undefined);
+ return;
+ }
+
+ try {
+ setLoading(true);
+ const response = await rolloutServiceClientConnect.getTaskRunSession(
+ create(GetTaskRunSessionRequestSchema, {
+ parent: taskRun.name,
+ }),
+ {
+ contextValues: createContextValues().set(silentContextKey, true),
+ }
+ );
+ if (canceled) {
+ return;
+ }
+ if (response.session.case === "postgres") {
+ setSession(response.session.value);
+ } else {
+ setSession(undefined);
+ }
+ } finally {
+ if (!canceled) {
+ setLoading(false);
+ }
+ }
+ };
+
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [taskRun.name, taskRun.status]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-8 text-control-light">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ </div>
+ );
+ }
+
+ if (!session?.session) {
+ return (
+ <div className="rounded-md border bg-gray-50 p-3 text-sm text-control-light">
+ {t("task-run.no-session-found")}
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex w-full flex-col gap-y-2">
+ <SessionTable rows={[session.session]} />
+ <div>
+ <div className="flex items-center justify-start gap-x-1 pt-2">
+ <span className="textlabel">{t("task-run.blocking-sessions")}</span>
+ <span className="textinfolabel">
+ ({t("task-run.blocking-sessions-description")})
+ </span>
+ </div>
+ <div className="mt-2">
+ <SessionTable rows={session.blockingSessions} />
+ </div>
+ </div>
+ {session.blockedSessions.length > 0 && (
+ <div>
+ <div className="flex items-center justify-start gap-x-2 pt-2">
+ <AlignHorizontalJustifyStart className="h-4 w-4 opacity-80" />
+ <span className="textlabel">{t("task-run.blocked-sessions")}</span>
+ <span className="textinfolabel">
+ {t("task-run.blocked-sessions-description")}
+ </span>
+ </div>
+ <div className="mt-2">
+ <SessionTable rows={session.blockedSessions} />
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SessionTable({ rows }: { rows: TaskRunSession_Postgres_Session[] }) {
+ const normalizedRows = useMemo(() => rows ?? [], [rows]);
+
+ if (normalizedRows.length === 0) {
+ return (
+ <div className="rounded-md border bg-gray-50 p-3 text-sm text-control-light">
+ -
+ </div>
+ );
+ }
+
+ return (
+ <div className="overflow-auto rounded-sm border">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="hover:bg-transparent">
+ <TableHead className="w-20">pid</TableHead>
+ <TableHead className="w-28">blocked_by_pids</TableHead>
+ <TableHead className="min-w-[256px]">query</TableHead>
+ <TableHead className="w-28">state</TableHead>
+ <TableHead className="w-28">wait_event_type</TableHead>
+ <TableHead className="w-28">wait_event</TableHead>
+ <TableHead className="w-28">datname</TableHead>
+ <TableHead className="w-28">usename</TableHead>
+ <TableHead className="w-36">application_name</TableHead>
+ <TableHead className="w-28">client_addr</TableHead>
+ <TableHead className="w-24">client_port</TableHead>
+ <TableHead className="w-40">backend_start</TableHead>
+ <TableHead className="w-40">xact_start</TableHead>
+ <TableHead className="w-40">query_start</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {normalizedRows.map((row) => (
+ <TableRow key={`${row.pid}-${row.queryStart?.seconds ?? 0}`}>
+ <TableCell>{row.pid}</TableCell>
+ <TableCell>{row.blockedByPids.join(", ") || "-"}</TableCell>
+ <TableCell className="truncate">{row.query || "-"}</TableCell>
+ <TableCell>{row.state || "-"}</TableCell>
+ <TableCell>{row.waitEventType || "-"}</TableCell>
+ <TableCell>{row.waitEvent || "-"}</TableCell>
+ <TableCell>{row.datname || "-"}</TableCell>
+ <TableCell>{row.usename || "-"}</TableCell>
+ <TableCell>{row.applicationName || "-"}</TableCell>
+ <TableCell>{row.clientAddr || "-"}</TableCell>
+ <TableCell>{row.clientPort || "-"}</TableCell>
+ <TableCell>{formatSessionTime(row.backendStart)}</TableCell>
+ <TableCell>{formatSessionTime(row.xactStart)}</TableCell>
+ <TableCell>{formatSessionTime(row.queryStart)}</TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ );
+}
+
+function formatSessionTime(
+ ts: TaskRunSession_Postgres_Session["queryStart"] | undefined
+) {
+ const date = getDateForPbTimestampProtoEs(ts);
+ if (!date) {
+ return "-";
+ }
+ return date.toISOString().replace("T", " ").replace("Z", " UTC");
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsx
new file mode 100644
index 0000000000..133d6bc7b0
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailTaskRunTable.tsx
@@ -0,0 +1,338 @@
+import { create } from "@bufbuild/protobuf";
+import { DurationSchema } from "@bufbuild/protobuf/wkt";
+import { Check, Minus } from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { EllipsisText } from "@/react/components/ui/ellipsis-text";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/react/components/ui/table";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useDatabaseV1Store } from "@/store";
+import {
+ getDateForPbTimestampProtoEs,
+ getTimeForPbTimestampProtoEs,
+} from "@/types";
+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ formatAbsoluteDateTime,
+ humanizeDate,
+ humanizeDurationV1,
+} from "@/utils";
+import { PlanDetailTaskRunDetail } from "./PlanDetailTaskRunDetail";
+
+export function PlanDetailTaskRunTable({
+ databaseName,
+ taskRuns,
+ selectedTaskRunName,
+ onSelectTaskRun,
+}: {
+ databaseName?: string;
+ taskRuns: TaskRun[];
+ selectedTaskRunName?: string;
+ onSelectTaskRun?: (taskRunName: string) => void;
+}) {
+ const { t } = useTranslation();
+ const databaseStore = useDatabaseV1Store();
+ const [detailTaskRun, setDetailTaskRun] = useState<TaskRun | undefined>();
+ const sortedTaskRuns = useMemo(() => {
+ return [...taskRuns].sort((left, right) => {
+ const leftTime = left.createTime ? Number(left.createTime.seconds) : 0;
+ const rightTime = right.createTime ? Number(right.createTime.seconds) : 0;
+ return rightTime - leftTime;
+ });
+ }, [taskRuns]);
+ const database = databaseName
+ ? databaseStore.getDatabaseByName(databaseName)
+ : undefined;
+
+ return (
+ <>
+ <div className="overflow-auto rounded-sm border">
+ <Table className="table-fixed">
+ <TableHeader>
+ <TableRow className="hover:bg-transparent">
+ <TableHead className="sticky top-0 z-10 w-9 bg-gray-50 px-2" />
+ <TableHead className="sticky top-0 z-10 bg-gray-50">
+ {t("common.detail")}
+ </TableHead>
+ <TableHead className="sticky top-0 z-10 w-36 bg-gray-50">
+ {t("task.created")}
+ </TableHead>
+ <TableHead className="sticky top-0 z-10 w-36 bg-gray-50">
+ {t("task.started")}
+ </TableHead>
+ <TableHead className="sticky top-0 z-10 w-28 bg-gray-50 pr-6 whitespace-nowrap text-sm">
+ {t("task.execution-time")}
+ </TableHead>
+ {!onSelectTaskRun && (
+ <TableHead className="sticky top-0 z-10 w-24 bg-gray-50 pr-4" />
+ )}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {sortedTaskRuns.map((taskRun) => (
+ <TableRow
+ key={taskRun.name}
+ className={[
+ onSelectTaskRun ? "cursor-pointer" : "",
+ selectedTaskRunName === taskRun.name
+ ? "bg-accent/5 hover:bg-accent/5"
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ onClick={() => onSelectTaskRun?.(taskRun.name)}
+ >
+ <TableCell className="px-2">
+ <TaskRunStatusIcon status={taskRun.status} />
+ </TableCell>
+ <TableCell className="min-w-0 pr-2">
+ <TaskRunComment taskRun={taskRun} />
+ </TableCell>
+ <TableCell>
+ <TaskRunDateCell date={taskRun.createTime} />
+ </TableCell>
+ <TableCell>
+ <TaskRunDateCell date={taskRun.startTime} />
+ </TableCell>
+ <TableCell className="pr-6 whitespace-nowrap">
+ <span className="whitespace-nowrap text-sm text-control">
+ {executionDurationOfTaskRun(taskRun)
+ ? humanizeDurationV1(executionDurationOfTaskRun(taskRun))
+ : "-"}
+ </span>
+ </TableCell>
+ {!onSelectTaskRun && (
+ <TableCell className="pr-4">
+ {shouldShowDetailButton(taskRun) ? (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => setDetailTaskRun(taskRun)}
+ >
+ {t("common.detail")}
+ </Button>
+ ) : null}
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+
+ <Sheet
+ onOpenChange={(open) => {
+ if (!open) {
+ setDetailTaskRun(undefined);
+ }
+ }}
+ open={Boolean(detailTaskRun)}
+ >
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>{t("common.detail")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ {detailTaskRun && (
+ <PlanDetailTaskRunDetail
+ databaseEngine={database?.instanceResource?.engine}
+ taskRun={detailTaskRun}
+ />
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
+
+function TaskRunStatusIcon({ status }: { status: TaskRun_Status }) {
+ const { t } = useTranslation();
+ const classes = (() => {
+ switch (status) {
+ case TaskRun_Status.PENDING:
+ return "border-2 border-info bg-white text-info";
+ case TaskRun_Status.RUNNING:
+ return "border-2 border-info bg-white text-info";
+ case TaskRun_Status.DONE:
+ return "bg-success text-white";
+ case TaskRun_Status.FAILED:
+ return "bg-error text-white";
+ case TaskRun_Status.CANCELED:
+ return "border-2 border-gray-400 bg-white text-gray-400";
+ default:
+ return "";
+ }
+ })();
+
+ return (
+ <Tooltip content={taskRunStatusLabel(t, status)}>
+ <div
+ className={[
+ "relative flex h-5 w-5 shrink-0 items-center justify-center rounded-full select-none",
+ classes,
+ ].join(" ")}
+ >
+ {status === TaskRun_Status.PENDING && (
+ <span className="h-1.5 w-1.5 rounded-full bg-info" />
+ )}
+ {status === TaskRun_Status.RUNNING && (
+ <div className="relative flex h-2.5 w-2.5 overflow-visible">
+ <span className="absolute z-0 h-full w-full animate-ping-slow rounded-full bg-blue-600/50" />
+ <span className="z-1 h-full w-full rounded-full bg-info" />
+ </div>
+ )}
+ {status === TaskRun_Status.DONE && <Check className="h-4 w-4" />}
+ {status === TaskRun_Status.FAILED && (
+ <span className="text-base font-medium text-white">!</span>
+ )}
+ {status === TaskRun_Status.CANCELED && <Minus className="h-4 w-4" />}
+ </div>
+ </Tooltip>
+ );
+}
+
+function TaskRunComment({ taskRun }: { taskRun: TaskRun }) {
+ const { t } = useTranslation();
+ const earliestAllowedTime = taskRun.runTime
+ ? getTimeForPbTimestampProtoEs(taskRun.runTime)
+ : null;
+
+ const comment = (() => {
+ if (taskRun.status === TaskRun_Status.PENDING) {
+ if (earliestAllowedTime) {
+ return t("task-run.status.enqueued-with-rollout-time", {
+ time: formatAbsoluteDateTime(earliestAllowedTime),
+ });
+ }
+ return t("task-run.status.enqueued");
+ }
+ if (taskRun.status === TaskRun_Status.RUNNING && taskRun.schedulerInfo) {
+ const cause = taskRun.schedulerInfo.waitingCause;
+ if (cause?.cause?.case === "parallelTasksLimit") {
+ return t("task-run.status.waiting-max-tasks-per-rollout", {
+ time: formatAbsoluteDateTime(
+ getTimeForPbTimestampProtoEs(taskRun.schedulerInfo.reportTime)
+ ),
+ });
+ }
+ }
+ return taskRun.detail || "-";
+ })();
+
+ const commentLink =
+ taskRun.status === TaskRun_Status.FAILED && comment.includes("version")
+ ? {
+ link: "https://docs.bytebase.com/change-database/troubleshoot/?source=console#duplicate-version",
+ title: t("common.troubleshoot"),
+ }
+ : undefined;
+
+ return (
+ <div className="flex flex-col gap-y-0.5 xl:flex-row xl:items-center xl:gap-x-1">
+ <div className="min-w-0 flex-1">
+ <EllipsisText className="line-clamp-1" text={comment} />
+ </div>
+ {commentLink && (
+ <a
+ className="normal-link shrink-0"
+ href={commentLink.link}
+ rel="noopener noreferrer"
+ target="_blank"
+ >
+ {commentLink.title}
+ </a>
+ )}
+ </div>
+ );
+}
+
+function TaskRunDateCell({
+ date,
+}: {
+ date?: Parameters<typeof getDateForPbTimestampProtoEs>[0];
+}) {
+ if (!date) {
+ return <span className="text-control-light">-</span>;
+ }
+
+ const parsedDate = getDateForPbTimestampProtoEs(date);
+ if (!parsedDate) {
+ return <span className="text-control-light">-</span>;
+ }
+
+ return (
+ <Tooltip content={formatAbsoluteDateTime(parsedDate.getTime())}>
+ <span className="text-sm text-control">{humanizeDate(parsedDate)}</span>
+ </Tooltip>
+ );
+}
+
+function executionDurationOfTaskRun(taskRun: TaskRun) {
+ const { startTime, updateTime } = taskRun;
+ if (!startTime || !updateTime) {
+ return undefined;
+ }
+ if (Number(startTime.seconds) === 0) {
+ return undefined;
+ }
+ if (taskRun.status === TaskRun_Status.RUNNING) {
+ const elapsedMS = Date.now() - getTimeForPbTimestampProtoEs(startTime);
+ return create(DurationSchema, {
+ nanos: (elapsedMS % 1000) * 1e6,
+ seconds: BigInt(Math.floor(elapsedMS / 1000)),
+ });
+ }
+ const elapsedMS =
+ getTimeForPbTimestampProtoEs(updateTime) -
+ getTimeForPbTimestampProtoEs(startTime);
+ return create(DurationSchema, {
+ nanos: (elapsedMS % 1000) * 1e6,
+ seconds: BigInt(Math.floor(elapsedMS / 1000)),
+ });
+}
+
+function taskRunStatusLabel(
+ t: ReturnType<typeof useTranslation>["t"],
+ status: TaskRun_Status
+) {
+ switch (status) {
+ case TaskRun_Status.PENDING:
+ return t("task.status.pending");
+ case TaskRun_Status.RUNNING:
+ return t("task.status.running");
+ case TaskRun_Status.DONE:
+ return t("task.status.done");
+ case TaskRun_Status.FAILED:
+ return t("task.status.failed");
+ case TaskRun_Status.CANCELED:
+ return t("task.status.canceled");
+ default:
+ return String(status);
+ }
+}
+
+function shouldShowDetailButton(taskRun: TaskRun) {
+ return [
+ TaskRun_Status.RUNNING,
+ TaskRun_Status.DONE,
+ TaskRun_Status.FAILED,
+ TaskRun_Status.CANCELED,
+ ].includes(taskRun.status);
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
new file mode 100644
index 0000000000..46caa5faad
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
@@ -0,0 +1,186 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { router } from "@/router";
+import { useProjectV1Store } from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import type { Rollout, Task } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { generateRolloutPreview } from "../../utils/rolloutPreview";
+import { DeployPendingTasksSection } from "./DeployPendingTasksSection";
+import { DeployStageList } from "./DeployStageCard";
+import { DeployStageContentView } from "./DeployStageContentView";
+import type { DeployBranchProps, PendingTaskGroup } from "./types";
+
+async function loadPendingGroups(
+ plan: Plan,
+ rollout: Rollout | undefined,
+ projectName: string
+): Promise<PendingTaskGroup[]> {
+ const preview = await generateRolloutPreview(plan, projectName);
+ const existing = new Set<string>();
+ for (const stage of rollout?.stages ?? []) {
+ for (const task of stage.tasks) {
+ existing.add(`${task.target}:${task.specId}`);
+ }
+ }
+ const groups = new Map<string, Task[]>();
+ for (const stage of preview.stages) {
+ for (const task of stage.tasks) {
+ const key = `${task.target}:${task.specId}`;
+ if (existing.has(key)) continue;
+ const tasks = groups.get(stage.environment) ?? [];
+ tasks.push(task);
+ groups.set(stage.environment, tasks);
+ }
+ }
+ return Array.from(groups.entries()).map(([environment, tasks]) => ({
+ environment,
+ tasks,
+ }));
+}
+
+export function DeployBranch({
+ selectedTask,
+ onCloseTaskPanel: _onCloseTaskPanel,
+}: DeployBranchProps) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const projectStore = useProjectV1Store();
+ const project = useMemo(
+ () =>
+ projectStore.getProjectByName(`${projectNamePrefix}${page.projectId}`),
+ [page.projectId, projectStore]
+ );
+ const projectName = `projects/${page.projectId}`;
+ const [pendingOpen, setPendingOpen] = useState(false);
+ const [pendingGroups, setPendingGroups] = useState<PendingTaskGroup[]>([]);
+ const rolloutKey =
+ page.rollout?.stages
+ .map(
+ (stage) =>
+ `${stage.name}:${stage.tasks.map((task) => `${task.target}:${task.specId}`).join(",")}`
+ )
+ .join("|") ?? "";
+ const planKey = `${page.plan.name}:${page.plan.specs.map((spec) => spec.id).join(",")}`;
+ const selectedStage = useMemo(() => {
+ if (!page.rollout?.stages.length) return undefined;
+ if (selectedTask) {
+ return page.rollout.stages.find((stage) =>
+ stage.tasks.some((task) => task.name === selectedTask.name)
+ );
+ }
+ if (page.routeStageId) {
+ return page.rollout.stages.find((stage) =>
+ stage.name.endsWith(`/${page.routeStageId}`)
+ );
+ }
+ const firstIncomplete = page.rollout.stages.find((stage) =>
+ stage.tasks.some(
+ (task) =>
+ task.status !== Task_Status.DONE &&
+ task.status !== Task_Status.SKIPPED
+ )
+ );
+ return firstIncomplete ?? page.rollout.stages[0];
+ }, [page.rollout?.stages, page.routeStageId, selectedTask]);
+
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ try {
+ const groups = await loadPendingGroups(
+ page.plan,
+ page.rollout,
+ projectName
+ );
+ if (!canceled) setPendingGroups(groups);
+ } catch {
+ if (!canceled) setPendingGroups([]);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [planKey, projectName, rolloutKey]);
+
+ const hasPendingTasks = pendingGroups.length > 0;
+ const canCreateRollout =
+ !page.readonly && hasProjectPermissionV2(project, "bb.rollouts.create");
+
+ if (!page.rollout) {
+ return null;
+ }
+
+ if (page.rollout.stages.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-4 py-10">
+ <p className="text-control-placeholder">
+ {t("rollout.no-tasks-created")}
+ </p>
+ {hasPendingTasks && canCreateRollout && (
+ <Button onClick={() => setPendingOpen(true)} size="sm">
+ {t("rollout.pending-tasks-preview.action")}
+ </Button>
+ )}
+ <DeployPendingTasksSection
+ onCreated={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={setPendingOpen}
+ open={pendingOpen}
+ plan={page.plan}
+ projectName={projectName}
+ rollout={page.rollout}
+ />
+ </div>
+ );
+ }
+
+ if (!selectedStage) {
+ return (
+ <div className="flex items-center justify-center py-12">
+ <p className="text-gray-500">{t("rollout.no-stages")}</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col">
+ <DeployStageList
+ hasPendingTasks={hasPendingTasks}
+ onOpenPreview={() => setPendingOpen(true)}
+ onSelectStage={(stage) => {
+ void router.push({
+ query: {
+ phase: "deploy",
+ stageId: stage.name.split("/").pop(),
+ },
+ });
+ }}
+ rollout={page.rollout}
+ selectedStageId={selectedStage.name}
+ />
+
+ <DeployStageContentView
+ selectedTaskName={selectedTask?.name}
+ stage={selectedStage}
+ />
+
+ <DeployPendingTasksSection
+ onCreated={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={setPendingOpen}
+ open={pendingOpen}
+ plan={page.plan}
+ projectName={projectName}
+ rollout={page.rollout}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx
new file mode 100644
index 0000000000..2d6cb67434
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployLatestTaskRunInfo.tsx
@@ -0,0 +1,121 @@
+import type { Timestamp } from "@bufbuild/protobuf/wkt";
+import {
+ CheckCircle2,
+ Circle,
+ Clock3,
+ LoaderCircle,
+ User,
+ XCircle,
+} from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { TaskRunLogViewer } from "@/react/components/task-run-log";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { formatAbsoluteDateTime, humanizeDate } from "@/utils";
+
+export function DeployLatestTaskRunInfo({
+ duration,
+ executorEmail,
+ status,
+ taskRunName,
+ updateTime,
+}: {
+ duration?: string;
+ executorEmail?: string;
+ status: Task_Status;
+ taskRunName?: string;
+ updateTime?: Timestamp;
+}) {
+ const { t } = useTranslation();
+ const updateDate = getDateForPbTimestampProtoEs(updateTime);
+ const statusConfig =
+ status === Task_Status.RUNNING
+ ? {
+ className: "text-blue-600",
+ icon: LoaderCircle,
+ label: t("task.status.running"),
+ spinning: true,
+ }
+ : status === Task_Status.DONE
+ ? {
+ className: "text-green-600",
+ icon: CheckCircle2,
+ label: t("task.status.done"),
+ spinning: false,
+ }
+ : status === Task_Status.FAILED
+ ? {
+ className: "text-red-600",
+ icon: XCircle,
+ label: t("task.status.failed"),
+ spinning: false,
+ }
+ : {
+ className: "text-gray-500",
+ icon: Circle,
+ label:
+ status === Task_Status.SKIPPED
+ ? t("task.status.skipped")
+ : status === Task_Status.CANCELED
+ ? t("task.status.canceled")
+ : status === Task_Status.PENDING
+ ? t("task.status.pending")
+ : t("task.status.not-started"),
+ spinning: false,
+ };
+ const StatusIcon = statusConfig.icon;
+
+ return (
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
+ <span className="shrink-0 font-medium text-gray-700">
+ {t("task-run.latest")}
+ </span>
+ <span className="text-gray-300">·</span>
+ <span
+ className={`flex shrink-0 items-center gap-x-1 ${statusConfig.className}`}
+ >
+ <StatusIcon
+ className={`h-4 w-4 ${statusConfig.spinning ? "animate-spin" : ""}`}
+ />
+ <span>{statusConfig.label}</span>
+ </span>
+ {updateDate && (
+ <>
+ <span className="text-gray-300">·</span>
+ <Tooltip content={formatAbsoluteDateTime(updateDate.getTime())}>
+ <span className="shrink-0 text-gray-500">
+ {humanizeDate(updateDate)}
+ </span>
+ </Tooltip>
+ </>
+ )}
+ {executorEmail && (
+ <>
+ <span className="text-gray-300">·</span>
+ <Tooltip content={t("task.executed-by")}>
+ <span className="flex shrink-0 items-center gap-x-1 text-gray-500">
+ <User className="h-3.5 w-3.5" />
+ <span className="truncate">{executorEmail}</span>
+ </span>
+ </Tooltip>
+ </>
+ )}
+ {duration && (
+ <>
+ <span className="text-gray-300">·</span>
+ <Tooltip content={t("common.duration")}>
+ <span className="flex shrink-0 items-center gap-x-1 text-gray-500">
+ <Clock3 className="h-3.5 w-3.5" />
+ {duration}
+ </span>
+ </Tooltip>
+ </>
+ )}
+ </div>
+
+ {taskRunName && <TaskRunLogViewer taskRunName={taskRunName} />}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployPendingTasksSection.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployPendingTasksSection.tsx
new file mode 100644
index 0000000000..1b0ecfa5ca
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployPendingTasksSection.tsx
@@ -0,0 +1,239 @@
+import { create } from "@bufbuild/protobuf";
+import { ChevronDown, ChevronRight, Loader2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { Button } from "@/react/components/ui/button";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { pushNotification } from "@/store";
+import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ CreateRolloutRequestSchema,
+ type Rollout,
+ type Task,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ extractEnvironmentResourceName,
+ extractPlanNameFromRolloutName,
+} from "@/utils";
+import { generateRolloutPreview } from "../../utils/rolloutPreview";
+import {
+ DatabaseGroupTarget,
+ DatabaseTarget,
+} from "../PlanDetailChangesBranch";
+import type { PendingTaskGroup } from "./types";
+
+async function buildPendingTaskGroups(
+ plan: Plan,
+ rollout: Rollout | undefined,
+ projectName: string
+): Promise<PendingTaskGroup[]> {
+ const preview = await generateRolloutPreview(plan, projectName);
+ const existingTasks = new Set<string>();
+ for (const stage of rollout?.stages ?? []) {
+ for (const task of stage.tasks) {
+ existingTasks.add(`${task.target}:${task.specId}`);
+ }
+ }
+ const groups = new Map<string, Task[]>();
+ for (const stage of preview.stages) {
+ for (const task of stage.tasks) {
+ const key = `${task.target}:${task.specId}`;
+ if (existingTasks.has(key)) continue;
+ const tasks = groups.get(stage.environment) ?? [];
+ tasks.push(task);
+ groups.set(stage.environment, tasks);
+ }
+ }
+ return Array.from(groups.entries()).map(([environment, tasks]) => ({
+ environment,
+ tasks,
+ }));
+}
+
+export function DeployPendingTasksSection({
+ onCreated,
+ open,
+ onOpenChange,
+ plan,
+ projectName,
+ rollout,
+}: {
+ onCreated: () => Promise<void> | void;
+ onOpenChange: (open: boolean) => void;
+ open: boolean;
+ plan: Plan;
+ projectName: string;
+ rollout?: Rollout;
+}) {
+ const { t } = useTranslation();
+ const [creatingEnv, setCreatingEnv] = useState<string | null>(null);
+ const [expandedEnvs, setExpandedEnvs] = useState<Set<string>>(new Set());
+ const [groups, setGroups] = useState<PendingTaskGroup[]>([]);
+ const [loading, setLoading] = useState(false);
+ const rolloutKey =
+ rollout?.stages
+ .map(
+ (stage) =>
+ `${stage.name}:${stage.tasks.map((task) => `${task.target}:${task.specId}`).join(",")}`
+ )
+ .join("|") ?? "";
+ const planKey = `${plan.name}:${plan.specs.map((spec) => spec.id).join(",")}`;
+
+ useEffect(() => {
+ if (!open) return;
+ let canceled = false;
+ const load = async () => {
+ setLoading(true);
+ try {
+ const next = await buildPendingTaskGroups(plan, rollout, projectName);
+ if (canceled) return;
+ setGroups(next);
+ setExpandedEnvs(new Set(next.map((group) => group.environment)));
+ } finally {
+ if (!canceled) setLoading(false);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [open, planKey, projectName, rolloutKey]);
+
+ const hasPendingTasks = groups.length > 0;
+ const rolloutParent = rollout
+ ? extractPlanNameFromRolloutName(rollout.name)
+ : plan.name;
+
+ const toggleEnv = (env: string) => {
+ setExpandedEnvs((prev) => {
+ const next = new Set(prev);
+ if (next.has(env)) next.delete(env);
+ else next.add(env);
+ return next;
+ });
+ };
+
+ return (
+ <Sheet onOpenChange={onOpenChange} open={open}>
+ <SheetContent
+ className="w-[25rem] max-w-[calc(100vw-2rem)]"
+ width="standard"
+ >
+ <SheetHeader>
+ <SheetTitle>{t("rollout.pending-tasks-preview.title")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ <p className="text-sm text-control-light">
+ {t("rollout.pending-tasks-preview.description")}
+ </p>
+
+ {loading ? (
+ <div className="flex justify-center py-8 text-control-light">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ </div>
+ ) : !hasPendingTasks ? (
+ <p className="py-8 text-center text-control-light">
+ {t("rollout.pending-tasks-preview.no-pending-tasks")}
+ </p>
+ ) : (
+ <div className="space-y-4">
+ {groups.map((group) => (
+ <div key={group.environment} className="rounded-lg border">
+ <div className="flex items-center gap-2 bg-gray-50 px-3 py-2">
+ <button
+ className="flex flex-1 items-center gap-2 text-left"
+ onClick={() => toggleEnv(group.environment)}
+ type="button"
+ >
+ {expandedEnvs.has(group.environment) ? (
+ <ChevronDown className="h-4 w-4 text-gray-500" />
+ ) : (
+ <ChevronRight className="h-4 w-4 text-gray-500" />
+ )}
+ <span className="font-medium">
+ {extractEnvironmentResourceName(group.environment)}
+ </span>
+ <span className="text-xs text-control-light">
+ {t("rollout.pending-tasks-preview.task-count", {
+ count: group.tasks.length,
+ })}
+ </span>
+ </button>
+ <Button
+ disabled={Boolean(creatingEnv)}
+ onClick={async () => {
+ try {
+ setCreatingEnv(group.environment);
+ await rolloutServiceClientConnect.createRollout(
+ create(CreateRolloutRequestSchema, {
+ parent: rolloutParent,
+ target: group.environment,
+ })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.success"),
+ });
+ await onCreated();
+ setGroups((prev) =>
+ prev.filter(
+ (item) => item.environment !== group.environment
+ )
+ );
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ } finally {
+ setCreatingEnv(null);
+ }
+ }}
+ size="xs"
+ >
+ {creatingEnv === group.environment && (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ )}
+ {t("common.create")}
+ </Button>
+ </div>
+ {expandedEnvs.has(group.environment) && (
+ <ul className="space-y-1 px-3 py-2">
+ {group.tasks.map((task) => (
+ <li key={`${task.target}:${task.specId}`}>
+ {isValidDatabaseName(task.target) ? (
+ <DatabaseTarget
+ showEnvironment
+ target={task.target}
+ />
+ ) : isValidDatabaseGroupName(task.target) ? (
+ <DatabaseGroupTarget target={task.target} />
+ ) : (
+ <span className="text-sm text-control">
+ {task.target}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployReleaseInfoCard.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployReleaseInfoCard.tsx
new file mode 100644
index 0000000000..3e1de132b2
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployReleaseInfoCard.tsx
@@ -0,0 +1,210 @@
+import dayjs from "dayjs";
+import { ExternalLink, Loader2, Package } from "lucide-react";
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { cn } from "@/react/lib/utils";
+import { useReleaseByName } from "@/store/modules/release";
+import { getDateForPbTimestampProtoEs, isValidReleaseName } from "@/types";
+import { State, VCSType } from "@/types/proto-es/v1/common_pb";
+import { Release_Type } from "@/types/proto-es/v1/release_service_pb";
+
+export function DeployReleaseInfoCard({
+ className,
+ compact = true,
+ releaseName,
+}: {
+ className?: string;
+ compact?: boolean;
+ releaseName: string;
+}) {
+ const { t } = useTranslation();
+ const { release, ready } = useReleaseByName(releaseName);
+ const releaseValue = release.value;
+ const isDeleted = releaseValue?.state === State.DELETED;
+ const maxDisplayedFiles = compact ? 4 : 6;
+ const releaseTitle = useMemo(() => {
+ const name = releaseValue?.name || releaseName;
+ const parts = name.split("/");
+ return parts[parts.length - 1] || name;
+ }, [releaseName, releaseValue?.name]);
+ const displayedFiles = releaseValue?.files?.slice(0, maxDisplayedFiles) ?? [];
+
+ if (!ready.value) {
+ return (
+ <div className={cn("flex flex-col gap-y-2", className)}>
+ <div className="rounded-md border bg-gray-50 p-2">
+ <div className="flex items-center gap-x-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ <span className="text-xs text-gray-600">{t("common.loading")}</span>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ if (!isValidReleaseName(releaseValue?.name ?? "")) {
+ return (
+ <div className={cn("flex flex-col gap-y-2", className)}>
+ <div className="rounded-md border bg-red-50 p-2">
+ <div className="text-xs text-red-600">{t("release.not-found")}</div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className={cn("flex flex-col gap-y-2", className)}>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-x-2 text-sm font-medium">
+ <Package className="h-4 w-4" />
+ <span
+ className={cn(
+ !compact && "text-base",
+ isDeleted && "text-control-light line-through"
+ )}
+ >
+ {releaseTitle}
+ </span>
+ </div>
+ <a
+ className="inline-flex items-center gap-x-1 text-xs text-accent hover:underline"
+ href={`/${releaseValue.name}`}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {t("common.view")}
+ <ExternalLink className="h-3 w-3" />
+ </a>
+ </div>
+
+ <div
+ className={cn(
+ "rounded-md border bg-gray-50",
+ compact ? "px-3 py-2" : "px-4 py-3"
+ )}
+ >
+ <div className={cn("flex flex-col", compact ? "gap-y-2" : "gap-y-3")}>
+ <div className="flex items-start justify-between">
+ <div>
+ <h3 className="text-sm font-medium text-gray-900">
+ {releaseTitle}
+ </h3>
+ </div>
+ </div>
+
+ {releaseValue.files && releaseValue.files.length > 0 && (
+ <div className="flex flex-col gap-y-1">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-medium text-gray-700">
+ {t("release.files")} ({releaseValue.files.length})
+ </h4>
+ {releaseValue.files.length > maxDisplayedFiles && (
+ <a
+ className="text-xs text-accent hover:underline"
+ href={`/${releaseValue.name}`}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {t("release.view-all-files")}
+ </a>
+ )}
+ </div>
+ <div
+ className={cn(
+ "grid w-full gap-1",
+ compact
+ ? "grid-cols-1 sm:grid-cols-2"
+ : "grid-cols-1 gap-2 sm:grid-cols-2 md:grid-cols-3"
+ )}
+ >
+ {displayedFiles.map((file) => (
+ <div
+ key={file.path}
+ className={cn(
+ "flex w-full items-center justify-between rounded-sm bg-white text-xs",
+ compact ? "p-1.5" : "p-2"
+ )}
+ >
+ <div className="mr-2 min-w-0 flex-1">
+ <div className="truncate font-medium">{file.path}</div>
+ <div className="text-gray-500">{file.version}</div>
+ </div>
+ <div
+ className={cn(
+ "inline-flex shrink-0 items-center rounded-sm bg-blue-100 text-xs text-blue-800",
+ compact ? "px-1 py-0.5" : "px-1.5 py-0.5"
+ )}
+ >
+ {getReleaseFileTypeText(releaseValue.type, t)}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {releaseValue.vcsSource && (
+ <div className="flex flex-col gap-y-0.5">
+ <h4 className="text-xs font-medium text-gray-700">
+ {t("release.vcs-source")}
+ </h4>
+ <div className="text-xs">
+ <span className="text-gray-500">
+ {getVCSTypeText(releaseValue.vcsSource.vcsType, t)}:
+ </span>
+ {releaseValue.vcsSource.url && (
+ <a
+ className="ml-1 text-blue-600 hover:text-blue-800"
+ href={releaseValue.vcsSource.url}
+ rel="noreferrer"
+ target="_blank"
+ >
+ {releaseValue.vcsSource.url}
+ </a>
+ )}
+ </div>
+ </div>
+ )}
+
+ <div className="text-xs text-gray-500">
+ {dayjs(
+ getDateForPbTimestampProtoEs(releaseValue.createTime)
+ ).format("YYYY-MM-DD HH:mm:ss")}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function getReleaseFileTypeText(
+ fileType: Release_Type,
+ t: (key: string, options?: Record<string, unknown>) => string
+) {
+ switch (fileType) {
+ case Release_Type.VERSIONED:
+ return t("release.file-type.versioned");
+ case Release_Type.DECLARATIVE:
+ return t("release.file-type.declarative");
+ default:
+ return t("release.file-type.unspecified");
+ }
+}
+
+function getVCSTypeText(
+ vcsType: VCSType,
+ t: (key: string, options?: Record<string, unknown>) => string
+) {
+ switch (vcsType) {
+ case VCSType.GITHUB:
+ return "GitHub";
+ case VCSType.GITLAB:
+ return "GitLab";
+ case VCSType.BITBUCKET:
+ return "Bitbucket";
+ case VCSType.AZURE_DEVOPS:
+ return "Azure DevOps";
+ default:
+ return t("release.vcs-type.unspecified");
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
new file mode 100644
index 0000000000..2ec2cce102
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
@@ -0,0 +1,127 @@
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ type Stage,
+ Task_Status,
+ TaskRun_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
+import {
+ type PlanDetailTaskRolloutAction,
+ PlanDetailTaskRolloutActionPanel,
+} from "../PlanDetailTaskRolloutActionPanel";
+import type { RollbackItem } from "./types";
+
+export function DeployStageActionSection({ stage }: { stage: Stage }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [actionOpen, setActionOpen] = useState(false);
+ const [action, setAction] = useState<PlanDetailTaskRolloutAction | undefined>(
+ undefined
+ );
+ const [rollbackOpen, setRollbackOpen] = useState(false);
+
+ const rollbackItems = useMemo<RollbackItem[]>(() => {
+ return stage.tasks
+ .map((task) => {
+ const taskRun = page.taskRuns.find(
+ (run) =>
+ run.name.startsWith(`${task.name}/taskRuns/`) &&
+ run.status === TaskRun_Status.DONE &&
+ run.hasPriorBackup
+ );
+ return taskRun ? { task, taskRun } : undefined;
+ })
+ .filter((item): item is RollbackItem => Boolean(item));
+ }, [page.taskRuns, stage.tasks]);
+
+ const actionItems = [
+ {
+ key: "RUN" as const,
+ label: t("common.run"),
+ visible: stage.tasks.some((task) =>
+ [
+ Task_Status.NOT_STARTED,
+ Task_Status.CANCELED,
+ Task_Status.FAILED,
+ ].includes(task.status)
+ ),
+ },
+ {
+ key: "SKIP" as const,
+ label: t("common.skip"),
+ visible: stage.tasks.some((task) =>
+ [
+ Task_Status.NOT_STARTED,
+ Task_Status.CANCELED,
+ Task_Status.FAILED,
+ ].includes(task.status)
+ ),
+ },
+ {
+ key: "CANCEL" as const,
+ label: t("common.cancel"),
+ visible: stage.tasks.some((task) =>
+ [Task_Status.PENDING, Task_Status.RUNNING].includes(task.status)
+ ),
+ },
+ ].filter((item) => item.visible);
+
+ return (
+ <>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-2">
+ {actionItems.map((item) => (
+ <Button
+ key={`${stage.name}-${item.key}`}
+ onClick={() => {
+ setAction(item.key);
+ setActionOpen(true);
+ }}
+ size="xs"
+ variant="outline"
+ >
+ {item.label}
+ </Button>
+ ))}
+ {rollbackItems.length > 0 && (
+ <Button
+ onClick={() => setRollbackOpen(true)}
+ size="xs"
+ variant="outline"
+ >
+ {t("task-run.rollback.available", { count: rollbackItems.length })}
+ </Button>
+ )}
+ </div>
+
+ {action && (
+ <PlanDetailTaskRolloutActionPanel
+ action={action}
+ onConfirm={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={(open) => {
+ setActionOpen(open);
+ if (!open) {
+ setAction(undefined);
+ }
+ }}
+ open={actionOpen}
+ target={{ type: "tasks", stage }}
+ />
+ )}
+
+ {rollbackItems.length > 0 && (
+ <PlanDetailRollbackSheet
+ items={rollbackItems}
+ onOpenChange={setRollbackOpen}
+ open={rollbackOpen}
+ projectName={`projects/${page.projectId}`}
+ rolloutName={page.rollout?.name ?? ""}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageCard.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageCard.tsx
new file mode 100644
index 0000000000..116330a59d
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageCard.tsx
@@ -0,0 +1,81 @@
+import { ArrowRight, Eye } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import { useEnvironmentV1Store } from "@/store";
+import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { getStageStatus } from "@/utils";
+import { PlanDetailTabItem, PlanDetailTabStrip } from "../PlanDetailTabStrip";
+
+function StageProgressCard({ stage }: { stage: Stage }) {
+ const environmentStore = useEnvironmentV1Store();
+ const env = environmentStore.getEnvironmentByName(stage.environment);
+ const completed = stage.tasks.filter(
+ (task) =>
+ task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
+ ).length;
+ const stageStatus = getStageStatus(stage);
+ const dotClass =
+ stageStatus === Task_Status.DONE || stageStatus === Task_Status.SKIPPED
+ ? "bg-success"
+ : stageStatus === Task_Status.FAILED
+ ? "bg-error"
+ : stageStatus === Task_Status.RUNNING ||
+ stageStatus === Task_Status.PENDING
+ ? "bg-accent"
+ : "bg-control-placeholder";
+
+ return (
+ <div className="flex items-center gap-2">
+ <span className={cn("h-2 w-2 rounded-full", dotClass)} />
+ <span className="text-sm font-medium text-main">{env.title}</span>
+ <span className="text-xs text-control-light">
+ ({completed}/{stage.tasks.length})
+ </span>
+ </div>
+ );
+}
+
+export function DeployStageList({
+ hasPendingTasks,
+ onOpenPreview,
+ onSelectStage,
+ rollout,
+ selectedStageId,
+}: {
+ hasPendingTasks: boolean;
+ onOpenPreview: () => void;
+ onSelectStage: (stage: Stage) => void;
+ rollout: Rollout;
+ selectedStageId?: string;
+}) {
+ const { t } = useTranslation();
+
+ return (
+ <PlanDetailTabStrip
+ action={
+ hasPendingTasks ? (
+ <Button onClick={onOpenPreview} size="sm">
+ <Eye className="h-4 w-4" />
+ {t("rollout.pending-tasks-preview.action")}
+ </Button>
+ ) : undefined
+ }
+ >
+ {rollout.stages.map((stage, index) => (
+ <div key={stage.name} className="flex items-center">
+ <PlanDetailTabItem
+ onSelect={() => onSelectStage(stage)}
+ selected={selectedStageId === stage.name}
+ >
+ <StageProgressCard stage={stage} />
+ </PlanDetailTabItem>
+ {index < rollout.stages.length - 1 && (
+ <ArrowRight className="mx-2 h-4 w-4 shrink-0 text-gray-400" />
+ )}
+ </div>
+ ))}
+ </PlanDetailTabStrip>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx
new file mode 100644
index 0000000000..e69802ceaa
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentSidebar.tsx
@@ -0,0 +1,249 @@
+import { DatabaseBackup } from "lucide-react";
+import { 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 { router } from "@/router";
+import { useUserStore } from "@/store";
+import { getDateForPbTimestampProtoEs } from "@/types";
+import {
+ type Stage,
+ Task_Status,
+ TaskRun_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { extractDatabaseResourceName, humanizeDate } from "@/utils";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
+import { PlanDetailTaskRunTable } from "../PlanDetailTaskRunTable";
+import { DeployTaskStatus } from "./DeployTaskStatus";
+import { getTaskRunDuration } from "./taskRunUtils";
+import type { RollbackItem } from "./types";
+
+const MAX_DISPLAY_ITEMS = 10;
+
+export function DeployStageContentSidebar({ stage }: { stage: Stage }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const userStore = useUserStore();
+ const [rollbackOpen, setRollbackOpen] = useState(false);
+ const [detailOpen, setDetailOpen] = useState(false);
+ const [creatorTitleByRun, setCreatorTitleByRun] = useState<
+ Record<string, string>
+ >({});
+
+ const stageTaskRuns = useMemo(() => {
+ const taskNames = new Set(stage.tasks.map((task) => task.name));
+ return page.taskRuns.filter((taskRun) => {
+ const taskName = taskRun.name.replace(/\/taskRuns\/[^/]+$/, "");
+ return taskNames.has(taskName);
+ });
+ }, [page.taskRuns, stage.tasks]);
+
+ const sortedTaskRuns = useMemo(() => {
+ return [...stageTaskRuns].sort((left, right) => {
+ const leftTime = left.updateTime ? Number(left.updateTime.seconds) : 0;
+ const rightTime = right.updateTime ? Number(right.updateTime.seconds) : 0;
+ return rightTime - leftTime;
+ });
+ }, [stageTaskRuns]);
+
+ const displayedTaskRuns = sortedTaskRuns.slice(0, MAX_DISPLAY_ITEMS);
+ const displayedTaskRunsKey = displayedTaskRuns
+ .map((taskRun) => `${taskRun.name}:${taskRun.creator}`)
+ .join("|");
+
+ useEffect(() => {
+ const creators = displayedTaskRuns
+ .map((taskRun) => taskRun.creator)
+ .filter((creator): creator is string => Boolean(creator));
+ if (creators.length === 0) {
+ setCreatorTitleByRun({});
+ return;
+ }
+
+ let canceled = false;
+ void userStore.batchGetOrFetchUsers(creators).then(() => {
+ if (canceled) return;
+ const next = Object.fromEntries(
+ displayedTaskRuns.map((taskRun) => {
+ const creator = taskRun.creator;
+ const user = creator
+ ? userStore.getUserByIdentifier(creator)
+ : undefined;
+ return [
+ taskRun.name,
+ user?.title ||
+ user?.email ||
+ creator.match(/users\/([^/]+)/)?.[1] ||
+ "",
+ ];
+ })
+ );
+ setCreatorTitleByRun(next);
+ });
+
+ return () => {
+ canceled = true;
+ };
+ }, [displayedTaskRunsKey, userStore]);
+
+ const rollbackItems = useMemo<RollbackItem[]>(() => {
+ return stage.tasks
+ .map((task) => {
+ const taskRun = page.taskRuns.find(
+ (run) =>
+ run.name.startsWith(`${task.name}/taskRuns/`) &&
+ run.status === TaskRun_Status.DONE &&
+ run.hasPriorBackup
+ );
+ return taskRun ? { task, taskRun } : undefined;
+ })
+ .filter((item): item is RollbackItem => Boolean(item));
+ }, [page.taskRuns, stage.tasks]);
+
+ return (
+ <>
+ <div className="w-full px-4 py-2">
+ {rollbackItems.length > 0 && (
+ <div className="pb-2">
+ <Button
+ className="px-0 text-control hover:bg-transparent"
+ onClick={() => setRollbackOpen(true)}
+ size="sm"
+ variant="ghost"
+ >
+ <DatabaseBackup className="h-4 w-4" />
+ {t("task-run.rollback.available", {
+ count: rollbackItems.length,
+ })}
+ </Button>
+ </div>
+ )}
+
+ {stageTaskRuns.length > 0 && (
+ <div>
+ <div className="flex items-center justify-between px-3 py-2">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-gray-700">
+ {t("task.run-history")}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-col gap-y-2 overflow-y-auto px-3 pb-3 pt-1">
+ {displayedTaskRuns.map((taskRun) => {
+ const taskName = taskRun.name.replace(/\/taskRuns\/[^/]+$/, "");
+ const task = stage.tasks.find((item) => item.name === taskName);
+ const target = task?.target
+ ? extractDatabaseResourceName(task.target)
+ : undefined;
+ const creatorTitle = creatorTitleByRun[taskRun.name] ?? "";
+ const duration = getTaskRunDuration(taskRun);
+ const updateDate = taskRun.updateTime
+ ? getDateForPbTimestampProtoEs(taskRun.updateTime)
+ : undefined;
+ return (
+ <div key={taskRun.name} className="flex items-start gap-2">
+ <div className="pt-0.5">
+ <DeployTaskStatus
+ size="small"
+ status={
+ taskRun.status === TaskRun_Status.DONE
+ ? Task_Status.DONE
+ : taskRun.status === TaskRun_Status.FAILED
+ ? Task_Status.FAILED
+ : taskRun.status === TaskRun_Status.RUNNING
+ ? Task_Status.RUNNING
+ : taskRun.status === TaskRun_Status.PENDING
+ ? Task_Status.PENDING
+ : Task_Status.CANCELED
+ }
+ />
+ </div>
+ <div className="-mt-0.5 min-w-0 flex-1 px-1 py-0.5">
+ <button
+ className="truncate text-left text-sm leading-4 text-gray-700 hover:underline"
+ onClick={() => {
+ if (!task) return;
+ void router.push({
+ query: {
+ phase: "deploy",
+ stageId: stage.name.split("/").pop(),
+ taskId: task.name.split("/").pop(),
+ },
+ });
+ }}
+ type="button"
+ >
+ {target?.instance ? (
+ <span className="text-gray-500">
+ {target.instance}
+ <span className="mx-0.5 text-gray-400">/</span>
+ </span>
+ ) : null}
+ <span>
+ {target?.databaseName ?? task?.target ?? ""}
+ </span>
+ </button>
+ {taskRun.status === TaskRun_Status.FAILED &&
+ taskRun.detail && (
+ <button
+ className="mt-0.5 line-clamp-3 text-left text-xs text-error hover:underline"
+ onClick={() => setDetailOpen(true)}
+ type="button"
+ >
+ {taskRun.detail}
+ </button>
+ )}
+ <div className="mt-0.5 flex items-center gap-1 text-xs text-gray-400">
+ <span>
+ {updateDate ? humanizeDate(updateDate) : "-"}
+ </span>
+ {creatorTitle && <span>· {creatorTitle}</span>}
+ {duration && <span>· {duration}</span>}
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ {sortedTaskRuns.length > MAX_DISPLAY_ITEMS && (
+ <div className="text-left text-xs text-gray-400">
+ {t("task.only-showing-latest-n-runs", {
+ n: MAX_DISPLAY_ITEMS,
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+
+ {rollbackItems.length > 0 && (
+ <PlanDetailRollbackSheet
+ items={rollbackItems}
+ onOpenChange={setRollbackOpen}
+ open={rollbackOpen}
+ projectName={`projects/${page.projectId}`}
+ rolloutName={page.rollout?.name ?? ""}
+ />
+ )}
+
+ <Sheet onOpenChange={setDetailOpen} open={detailOpen}>
+ <SheetContent width="wide">
+ <SheetHeader>
+ <SheetTitle>{t("common.detail")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody>
+ <PlanDetailTaskRunTable taskRuns={sortedTaskRuns} />
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
new file mode 100644
index 0000000000..1e3a72dbbd
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
@@ -0,0 +1,167 @@
+import { create } from "@bufbuild/protobuf";
+import { Play, Plus } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { Button } from "@/react/components/ui/button";
+import { pushNotification } from "@/store";
+import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ CreateRolloutRequestSchema,
+ Task_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ canRolloutTasks,
+ preloadRolloutPermissionContext,
+ RUNNABLE_TASK_STATUSES,
+} from "../../../issue-detail/utils/rollout";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { PlanDetailTaskRolloutActionPanel } from "../PlanDetailTaskRolloutActionPanel";
+import { DeployStageContentSidebar } from "./DeployStageContentSidebar";
+import { DeployTaskFilter } from "./DeployTaskFilter";
+import { DeployTaskList } from "./DeployTaskList";
+
+export function DeployStageContentView({
+ selectedTaskName,
+ stage,
+}: {
+ selectedTaskName?: string;
+ stage: Stage;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const [filterStatuses, setFilterStatuses] = useState<Task_Status[]>([]);
+ const [rolloutPermissionReady, setRolloutPermissionReady] = useState(false);
+ const [runStageOpen, setRunStageOpen] = useState(false);
+ const stageTaskKey = stage.tasks.map((task) => task.name).join("|");
+
+ const isStageCreated = stage.tasks.length > 0;
+
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ if (!isStageCreated) {
+ setRolloutPermissionReady(true);
+ return;
+ }
+ setRolloutPermissionReady(false);
+ await preloadRolloutPermissionContext({
+ environment: stage.environment,
+ projectName: project.name,
+ tasks: stage.tasks,
+ });
+ if (!canceled) setRolloutPermissionReady(true);
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [isStageCreated, project.name, stage.environment, stageTaskKey]);
+
+ const canRunStage =
+ rolloutPermissionReady &&
+ isStageCreated &&
+ stage.tasks.some((task) => RUNNABLE_TASK_STATUSES.includes(task.status)) &&
+ canRolloutTasks({
+ currentUser,
+ environment: stage.environment,
+ issue: page.issue,
+ project,
+ tasks: stage.tasks,
+ });
+
+ const filteredTasks =
+ filterStatuses.length > 0
+ ? stage.tasks.filter((task) => filterStatuses.includes(task.status))
+ : stage.tasks;
+
+ return (
+ <div className="w-full">
+ <div className="px-4">
+ <div className="flex w-full flex-row items-center justify-between gap-2 py-4">
+ <div className="flex flex-row items-center gap-3">
+ {isStageCreated && (
+ <DeployTaskFilter
+ onChange={setFilterStatuses}
+ selectedStatuses={filterStatuses}
+ stage={stage}
+ />
+ )}
+ </div>
+
+ <div className="flex shrink-0 items-center gap-x-2">
+ {isStageCreated ? (
+ <Button
+ disabled={!canRunStage}
+ size="sm"
+ onClick={() => setRunStageOpen(true)}
+ >
+ <Play className="h-4 w-4" />
+ {t("rollout.stage.run-stage")}
+ </Button>
+ ) : (
+ <Button
+ onClick={async () => {
+ const confirmed = window.confirm(
+ t("rollout.stage.confirm-create")
+ );
+ if (!confirmed) return;
+ try {
+ await rolloutServiceClientConnect.createRollout(
+ create(CreateRolloutRequestSchema, {
+ parent: page.plan.name,
+ target: stage.environment,
+ })
+ );
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.created"),
+ });
+ await page.refreshState();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.error"),
+ description: String(error),
+ });
+ }
+ }}
+ size="sm"
+ >
+ <Plus className="h-4 w-4" />
+ {t("common.create")}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex flex-col">
+ <DeployTaskList
+ readonly={!isStageCreated}
+ selectedTaskName={selectedTaskName}
+ stage={{
+ ...stage,
+ tasks: filteredTasks,
+ }}
+ />
+
+ {isStageCreated && <DeployStageContentSidebar stage={stage} />}
+ </div>
+
+ <PlanDetailTaskRolloutActionPanel
+ action="RUN"
+ onConfirm={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={setRunStageOpen}
+ open={runStageOpen}
+ target={{ type: "tasks", stage }}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx
new file mode 100644
index 0000000000..4867cee765
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskDetailPanel.tsx
@@ -0,0 +1,280 @@
+import { CalendarClock, EllipsisVertical, Undo2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ReadonlyMonaco } from "@/react/components/monaco";
+import { Button } from "@/react/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useEnvironmentV1Store } from "@/store";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import type { Task } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ Task_Status,
+ TaskRun_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { databaseForTask, humanizeTs } from "@/utils";
+import {
+ isReleaseBasedTask,
+ releaseNameOfTaskV1,
+} from "@/utils/v1/issue/rollout";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { DatabaseTarget } from "../PlanDetailChangesBranch";
+import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
+import {
+ type PlanDetailTaskRolloutAction,
+ PlanDetailTaskRolloutActionPanel,
+} from "../PlanDetailTaskRolloutActionPanel";
+import { PlanDetailTaskRunDetail } from "../PlanDetailTaskRunDetail";
+import { PlanDetailTaskRunTable } from "../PlanDetailTaskRunTable";
+import { DeployReleaseInfoCard } from "./DeployReleaseInfoCard";
+import { DeployTaskStatus } from "./DeployTaskStatus";
+import { useDeployTaskActions } from "./taskActions";
+import { useDeployTaskStatement } from "./useDeployTaskStatement";
+
+export function DeployTaskDetailPanel({ task }: { task: Task }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const environmentStore = useEnvironmentV1Store();
+ const project = page.project;
+ const taskRuns = useMemo(
+ () =>
+ page.taskRuns
+ .filter((taskRun) => taskRun.name.startsWith(`${task.name}/taskRuns/`))
+ .sort((left, right) => {
+ const leftTime = left.createTime
+ ? Number(left.createTime.seconds)
+ : 0;
+ const rightTime = right.createTime
+ ? Number(right.createTime.seconds)
+ : 0;
+ return rightTime - leftTime;
+ }),
+ [page.taskRuns, task.name]
+ );
+ const latestTaskRun = taskRuns[0];
+ const [taskActionOpen, setTaskActionOpen] = useState(false);
+ const [taskAction, setTaskAction] = useState<
+ PlanDetailTaskRolloutAction | undefined
+ >(undefined);
+ const [rollbackOpen, setRollbackOpen] = useState(false);
+ const database = useMemo(
+ () => databaseForTask(project, task, page.plan),
+ [page.plan, project, task]
+ );
+ const stage = useMemo(
+ () =>
+ page.rollout?.stages.find((candidate) =>
+ candidate.tasks.some((item) => item.name === task.name)
+ ),
+ [page.rollout?.stages, task.name]
+ );
+ const stageTitle = stage?.environment
+ ? environmentStore.getEnvironmentByName(stage.environment).title
+ : "";
+ const scheduledTimeDisplay = useMemo(() => {
+ const ts = getTimeForPbTimestampProtoEs(task.runTime, 0);
+ if (!ts) return "";
+ return humanizeTs(ts / 1000);
+ }, [task.runTime]);
+ const isReleaseTask = useMemo(() => isReleaseBasedTask(task), [task]);
+ const {
+ isLoading: isStatementLoading,
+ isTruncated,
+ statement,
+ } = useDeployTaskStatement({
+ enabled: !isReleaseTask,
+ task,
+ });
+ const releaseName = useMemo(() => releaseNameOfTaskV1(task), [task]);
+ const rollbackableTaskRun =
+ latestTaskRun &&
+ latestTaskRun.status === TaskRun_Status.DONE &&
+ latestTaskRun.hasPriorBackup
+ ? latestTaskRun
+ : undefined;
+ const { canCancel, canRun, canSkip } = useDeployTaskActions({ stage, task });
+ const primaryActionLabel =
+ task.status === Task_Status.FAILED ? t("common.retry") : t("common.run");
+
+ return (
+ <div className="space-y-4 p-4">
+ <div className="flex flex-col gap-y-3">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="flex flex-row flex-wrap items-center gap-x-3 gap-y-2">
+ <DeployTaskStatus size="large" status={task.status} />
+ {stageTitle && (
+ <span className="rounded-full bg-control-bg px-2 py-0.5 text-xs text-control">
+ {stageTitle}
+ </span>
+ )}
+ <div className="min-w-0 text-xl">
+ <DatabaseTarget showEnvironment target={database.name} />
+ </div>
+ {scheduledTimeDisplay && task.status === Task_Status.PENDING && (
+ <Tooltip
+ content={
+ <div className="flex flex-col gap-y-1">
+ <div className="text-sm opacity-80">
+ {t("task.scheduled-time")}
+ </div>
+ <div className="whitespace-nowrap text-sm">
+ {scheduledTimeDisplay}
+ </div>
+ </div>
+ }
+ >
+ <span className="inline-flex items-center gap-1 rounded-full bg-control-bg px-2 py-0.5 text-xs text-control">
+ <CalendarClock className="h-3.5 w-3.5 opacity-80" />
+ <span>{scheduledTimeDisplay}</span>
+ </span>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className="flex justify-start sm:justify-end">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-2">
+ {canRun && (
+ <Button
+ onClick={() => {
+ setTaskAction("RUN");
+ setTaskActionOpen(true);
+ }}
+ size="sm"
+ >
+ {primaryActionLabel}
+ </Button>
+ )}
+ {(canSkip || canCancel) && (
+ <DropdownMenu>
+ <DropdownMenuTrigger className="inline-flex h-8 items-center justify-center rounded-xs px-1 text-sm text-control outline-hidden hover:bg-control-bg focus-visible:ring-2 focus-visible:ring-accent">
+ <EllipsisVertical className="h-4 w-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {canSkip && (
+ <DropdownMenuItem
+ onClick={() => {
+ setTaskAction("SKIP");
+ setTaskActionOpen(true);
+ }}
+ >
+ {t("common.skip")}
+ </DropdownMenuItem>
+ )}
+ {canCancel && (
+ <DropdownMenuItem
+ onClick={() => {
+ setTaskAction("CANCEL");
+ setTaskActionOpen(true);
+ }}
+ >
+ {t("common.cancel")}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ {rollbackableTaskRun && (
+ <Button onClick={() => setRollbackOpen(true)} size="sm">
+ <Undo2 className="h-4 w-4" />
+ {t("common.rollback")}
+ </Button>
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {latestTaskRun && (
+ <div className="flex w-full flex-col gap-2">
+ <span className="textlabel uppercase">
+ {t("task-run.latest-logs")}
+ </span>
+ <PlanDetailTaskRunDetail
+ databaseEngine={database.instanceResource?.engine}
+ taskRun={latestTaskRun}
+ />
+ </div>
+ )}
+
+ {taskRuns.length > 0 && (
+ <div className="space-y-2">
+ <span className="textlabel uppercase">{t("task-run.history")}</span>
+ <PlanDetailTaskRunTable
+ databaseName={database.name}
+ taskRuns={taskRuns}
+ />
+ </div>
+ )}
+
+ {!isReleaseTask && (
+ <div className="flex min-h-0 flex-1 flex-col gap-2">
+ <span className="textlabel uppercase">{t("common.statement")}</span>
+ <div className="rounded-sm border bg-white p-3">
+ {isStatementLoading ? (
+ <div className="text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ ) : statement ? (
+ <>
+ <ReadonlyMonaco
+ className="relative h-auto max-h-[420px] min-h-[160px]"
+ content={statement}
+ language="sql"
+ />
+ {isTruncated && (
+ <div className="mt-2 text-xs text-gray-500">
+ {t("rollout.task.statement-truncated-hint")}
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {isReleaseTask && releaseName && (
+ <DeployReleaseInfoCard
+ className="w-full"
+ compact
+ releaseName={releaseName}
+ />
+ )}
+
+ {stage && taskAction && (
+ <PlanDetailTaskRolloutActionPanel
+ action={taskAction}
+ onConfirm={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={(open) => {
+ setTaskActionOpen(open);
+ if (!open) {
+ setTaskAction(undefined);
+ }
+ }}
+ open={taskActionOpen}
+ target={{ type: "tasks", stage, tasks: [task] }}
+ />
+ )}
+
+ {rollbackableTaskRun && (
+ <PlanDetailRollbackSheet
+ items={[{ task, taskRun: rollbackableTaskRun }]}
+ onOpenChange={setRollbackOpen}
+ open={rollbackOpen}
+ projectName={project.name}
+ rolloutName={page.rollout?.name ?? ""}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx
new file mode 100644
index 0000000000..3836738927
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskFilter.tsx
@@ -0,0 +1,64 @@
+import { useTranslation } from "react-i18next";
+import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { stringifyTaskStatus } from "@/utils";
+import { DeployTaskStatus } from "./DeployTaskStatus";
+
+const TASK_STATUS_FILTERS = [
+ Task_Status.NOT_STARTED,
+ Task_Status.PENDING,
+ Task_Status.RUNNING,
+ Task_Status.DONE,
+ Task_Status.FAILED,
+ Task_Status.CANCELED,
+ Task_Status.SKIPPED,
+];
+
+export function DeployTaskFilter({
+ selectedStatuses,
+ onChange,
+ stage,
+}: {
+ selectedStatuses: Task_Status[];
+ onChange: (statuses: Task_Status[]) => void;
+ stage: Stage;
+}) {
+ const { t } = useTranslation();
+ const getTaskCount = (status: Task_Status) =>
+ stage.tasks.filter((task) => task.status === status).length;
+
+ return (
+ <div className="flex flex-row items-center gap-1">
+ {TASK_STATUS_FILTERS.map((status) => {
+ const count = getTaskCount(status);
+ if (count <= 0) return null;
+ const checked = selectedStatuses.includes(status);
+ return (
+ <button
+ key={status}
+ className={[
+ "inline-flex items-center gap-1 rounded-full border px-2 py-1",
+ checked
+ ? "border-accent bg-accent/10"
+ : "border-control-border bg-white",
+ ].join(" ")}
+ onClick={() => {
+ onChange(
+ checked
+ ? selectedStatuses.filter((item) => item !== status)
+ : [...selectedStatuses, status]
+ );
+ }}
+ type="button"
+ >
+ <DeployTaskStatus size="small" status={status} />
+ <span className="select-none text-sm">
+ {stringifyTaskStatus(status, t)}
+ </span>
+ <span className="select-none text-sm font-medium">{count}</span>
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx
new file mode 100644
index 0000000000..59cc99b8fc
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskItem.tsx
@@ -0,0 +1,371 @@
+import {
+ ArrowUpRight,
+ ChevronDown,
+ ChevronRight,
+ LoaderCircle,
+ Play,
+ SkipForward,
+ X,
+} from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ReadonlyMonaco } from "@/react/components/monaco";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import { getTimeForPbTimestampProtoEs } from "@/types";
+import {
+ type Stage,
+ type Task,
+ Task_Status,
+ TaskRun_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { humanizeTs } from "@/utils";
+import {
+ isReleaseBasedTask,
+ releaseNameOfTaskV1,
+} from "@/utils/v1/issue/rollout";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { DatabaseTarget } from "../PlanDetailChangesBranch";
+import { PlanDetailRollbackSheet } from "../PlanDetailRollbackSheet";
+import {
+ type PlanDetailTaskRolloutAction,
+ PlanDetailTaskRolloutActionPanel,
+} from "../PlanDetailTaskRolloutActionPanel";
+import { DeployLatestTaskRunInfo } from "./DeployLatestTaskRunInfo";
+import { DeployReleaseInfoCard } from "./DeployReleaseInfoCard";
+import { DeployTaskStatus } from "./DeployTaskStatus";
+import { useDeployTaskActions } from "./taskActions";
+import { getTaskRunDuration } from "./taskRunUtils";
+import { useDeployTaskStatement } from "./useDeployTaskStatement";
+
+export function DeployTaskItem({
+ active,
+ isExpanded,
+ isSelected,
+ isSelectable,
+ onToggleExpand,
+ onToggleSelect,
+ readonly,
+ stageId,
+ stage,
+ task,
+}: {
+ active: boolean;
+ isExpanded: boolean;
+ isSelected: boolean;
+ isSelectable: boolean;
+ onToggleExpand: () => void;
+ onToggleSelect: () => void;
+ readonly: boolean;
+ stageId: string;
+ stage: Stage;
+ task: Task;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const taskRunsForTask = useMemo(
+ () =>
+ page.taskRuns.filter((run) =>
+ run.name.startsWith(`${task.name}/taskRuns/`)
+ ),
+ [page.taskRuns, task.name]
+ );
+ const latestTaskRun = taskRunsForTask[taskRunsForTask.length - 1];
+ const [action, setAction] = useState<
+ PlanDetailTaskRolloutAction | undefined
+ >();
+ const [actionOpen, setActionOpen] = useState(false);
+ const [rollbackOpen, setRollbackOpen] = useState(false);
+ const isReleaseTask = isReleaseBasedTask(task);
+ const {
+ isLoading: isStatementLoading,
+ isTruncated,
+ statement,
+ } = useDeployTaskStatement({
+ enabled: isExpanded && !isReleaseTask,
+ task,
+ });
+ const releaseName = releaseNameOfTaskV1(task);
+ const { canCancel, canRun, canSkip } = useDeployTaskActions({
+ stage,
+ task,
+ });
+ const rollbackableTaskRun =
+ latestTaskRun &&
+ latestTaskRun.status === TaskRun_Status.DONE &&
+ latestTaskRun.hasPriorBackup
+ ? latestTaskRun
+ : undefined;
+ const scheduledTime =
+ task.runTime && task.status === Task_Status.PENDING
+ ? humanizeTs(getTimeForPbTimestampProtoEs(task.runTime, 0) / 1000)
+ : "";
+ const timingDisplay = latestTaskRun ? getTaskRunDuration(latestTaskRun) : "";
+ const executorEmail =
+ latestTaskRun?.creator.match(/users\/([^/]+)/)?.[1] ?? "";
+ const collapsedContextInfo =
+ task.status === Task_Status.DONE ? timingDisplay : "";
+ const collapsedStatusText =
+ latestTaskRun?.detail ||
+ task.skippedReason ||
+ (task.status === Task_Status.FAILED
+ ? t("task.status.failed")
+ : task.status === Task_Status.SKIPPED
+ ? t("task.status.skipped")
+ : "");
+ const actionItems = [
+ {
+ key: "RUN" as const,
+ label:
+ task.status === Task_Status.FAILED
+ ? t("common.retry")
+ : t("common.run"),
+ visible: canRun,
+ },
+ {
+ key: "SKIP" as const,
+ label: t("common.skip"),
+ visible: canSkip,
+ },
+ {
+ key: "CANCEL" as const,
+ label: t("common.cancel"),
+ visible: canCancel,
+ },
+ ].filter((item) => item.visible);
+ const showHeaderActions =
+ isExpanded && (actionItems.length > 0 || Boolean(rollbackableTaskRun));
+
+ return (
+ <>
+ <div
+ className={cn(
+ "group relative rounded-lg border bg-white transition-all",
+ active && "border-accent bg-accent/5"
+ )}
+ >
+ <div
+ className={
+ isExpanded ? "space-y-3 py-4 pl-3 pr-4" : "py-2.5 pl-3 pr-4"
+ }
+ >
+ <div className="flex items-center justify-between gap-x-3">
+ <div className="flex min-w-0 flex-1 items-center gap-x-2">
+ <input
+ checked={isSelected}
+ className="shrink-0 accent-accent"
+ disabled={!isSelectable}
+ onChange={() => onToggleSelect()}
+ onClick={(event) => event.stopPropagation()}
+ type="checkbox"
+ />
+ <DeployTaskStatus
+ size={isExpanded ? "large" : "small"}
+ status={task.status}
+ />
+ <div className="flex min-w-0 items-center gap-x-2">
+ <div className="min-w-0">
+ <DatabaseTarget target={task.target} />
+ </div>
+ {isExpanded && !readonly && (
+ <button
+ className="flex shrink-0 items-center gap-x-1 text-xs text-accent transition-opacity hover:opacity-80"
+ onClick={() => {
+ void router.push({
+ query: {
+ phase: "deploy",
+ stageId,
+ taskId: task.name.split("/").pop(),
+ },
+ });
+ }}
+ type="button"
+ >
+ <ArrowUpRight className="h-4 w-4" />
+ <span>{t("common.view-details")}</span>
+ </button>
+ )}
+ {isExpanded && scheduledTime && (
+ <span className="flex shrink-0 items-center gap-x-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-600">
+ <LoaderCircle className="h-3 w-3 animate-spin" />
+ {scheduledTime}
+ </span>
+ )}
+ </div>
+ {!isExpanded && (
+ <div className="ml-auto shrink-0 text-xs text-gray-500">
+ {scheduledTime ? (
+ <span className="flex items-center gap-x-1 text-blue-600">
+ <LoaderCircle className="h-3 w-3 animate-spin" />
+ {scheduledTime}
+ </span>
+ ) : task.status === Task_Status.RUNNING && timingDisplay ? (
+ <span className="flex items-center gap-x-1 text-blue-600">
+ <LoaderCircle className="h-3 w-3 animate-spin" />
+ {timingDisplay}
+ </span>
+ ) : collapsedContextInfo ? (
+ <span>{collapsedContextInfo}</span>
+ ) : null}
+ </div>
+ )}
+ </div>
+
+ {showHeaderActions && (
+ <div className="flex shrink-0 items-center gap-x-2">
+ {actionItems.map((item) => (
+ <Button
+ key={item.key}
+ onClick={() => {
+ setAction(item.key);
+ setActionOpen(true);
+ }}
+ size="xs"
+ variant={item.key === "RUN" ? "default" : "outline"}
+ >
+ {item.key === "RUN" && <Play className="h-3 w-3" />}
+ {item.key === "SKIP" && <SkipForward className="h-3 w-3" />}
+ {item.key === "CANCEL" && <X className="h-3 w-3" />}
+ {item.label}
+ </Button>
+ ))}
+ {rollbackableTaskRun && (
+ <Button
+ onClick={() => setRollbackOpen(true)}
+ size="xs"
+ variant="outline"
+ >
+ {t("common.rollback")}
+ </Button>
+ )}
+ </div>
+ )}
+
+ {!readonly && (
+ <button
+ className={
+ isExpanded
+ ? "self-start rounded p-1 hover:bg-gray-100"
+ : "rounded p-1 hover:bg-gray-100"
+ }
+ onClick={onToggleExpand}
+ type="button"
+ >
+ {isExpanded ? (
+ <ChevronDown className="h-4 w-4 text-gray-500" />
+ ) : (
+ <ChevronRight className="h-4 w-4 text-gray-500" />
+ )}
+ </button>
+ )}
+ </div>
+
+ {!isExpanded && collapsedStatusText && (
+ <div className="mt-1 flex items-center gap-x-2 text-xs">
+ {latestTaskRun?.createTime && (
+ <span className="rounded-full border bg-gray-50 px-2 py-0.5 text-gray-500">
+ {humanizeTs(
+ getTimeForPbTimestampProtoEs(latestTaskRun.createTime, 0) /
+ 1000
+ )}
+ </span>
+ )}
+ <span
+ className={cn(
+ "cursor-pointer truncate",
+ task.status === Task_Status.FAILED
+ ? "text-error"
+ : "italic text-gray-500"
+ )}
+ onClick={onToggleExpand}
+ >
+ {collapsedStatusText}
+ </span>
+ </div>
+ )}
+
+ {isExpanded && (
+ <div className="space-y-3">
+ {!isReleaseTask ? (
+ <div>
+ <div className="mb-1 text-sm font-medium text-gray-700">
+ {t("common.statement")}
+ </div>
+ {isStatementLoading ? (
+ <div className="rounded-sm border p-3 text-sm text-control-light">
+ {t("common.loading")}
+ </div>
+ ) : statement ? (
+ <>
+ <ReadonlyMonaco
+ className={cn(
+ "relative max-h-64 min-h-[120px] overflow-hidden text-sm",
+ isTruncated && "rounded-b-none"
+ )}
+ content={statement}
+ language="sql"
+ />
+ {isTruncated && (
+ <div className="rounded-b border border-t-0 bg-gray-50 px-3 py-1.5 text-xs text-gray-500">
+ {t("rollout.task.statement-truncated-hint")}
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="rounded-sm border p-3 text-sm text-control-light">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+ ) : releaseName ? (
+ <DeployReleaseInfoCard compact releaseName={releaseName} />
+ ) : null}
+
+ {latestTaskRun && (
+ <DeployLatestTaskRunInfo
+ duration={
+ task.status !== Task_Status.PENDING
+ ? timingDisplay
+ : undefined
+ }
+ executorEmail={executorEmail}
+ status={task.status}
+ taskRunName={latestTaskRun.name}
+ updateTime={latestTaskRun.updateTime}
+ />
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+
+ {action && (
+ <PlanDetailTaskRolloutActionPanel
+ action={action}
+ onConfirm={async () => {
+ await page.refreshState();
+ }}
+ onOpenChange={(open) => {
+ setActionOpen(open);
+ if (!open) {
+ setAction(undefined);
+ }
+ }}
+ open={actionOpen}
+ target={{ type: "tasks", tasks: [task], stage }}
+ />
+ )}
+
+ {rollbackableTaskRun && (
+ <PlanDetailRollbackSheet
+ items={[{ task, taskRun: rollbackableTaskRun }]}
+ onOpenChange={setRollbackOpen}
+ open={rollbackOpen}
+ projectName={`projects/${page.projectId}`}
+ rolloutName={page.rollout?.name ?? ""}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx
new file mode 100644
index 0000000000..6ed2b2efb0
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskList.tsx
@@ -0,0 +1,148 @@
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import { DeployTaskItem } from "./DeployTaskItem";
+import { DeployTaskToolbar } from "./DeployTaskToolbar";
+import { isDeployTaskSelectable } from "./taskActionState";
+
+const DEFAULT_PAGE_SIZE = 20;
+
+export function DeployTaskList({
+ selectedTaskName,
+ stage,
+ readonly = false,
+}: {
+ selectedTaskName?: string;
+ stage: Stage;
+ readonly?: boolean;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [displayedTaskCount, setDisplayedTaskCount] =
+ useState(DEFAULT_PAGE_SIZE);
+ const [expandedTaskNames, setExpandedTaskNames] = useState<Set<string>>(
+ new Set()
+ );
+ const [selectedTaskNames, setSelectedTaskNames] = useState<Set<string>>(
+ new Set()
+ );
+ const filteredTasks = stage.tasks;
+ const visibleTasks = filteredTasks.slice(0, displayedTaskCount);
+ const hasMoreTasks = filteredTasks.length > displayedTaskCount;
+ const remainingTasksCount = filteredTasks.length - displayedTaskCount;
+ const selectedTasks = useMemo(
+ () => filteredTasks.filter((task) => selectedTaskNames.has(task.name)),
+ [filteredTasks, selectedTaskNames]
+ );
+ const taskNamesKey = filteredTasks.map((task) => task.name).join(",");
+
+ useEffect(() => {
+ setDisplayedTaskCount(DEFAULT_PAGE_SIZE);
+ }, [taskNamesKey]);
+
+ useEffect(() => {
+ setExpandedTaskNames(() => {
+ if (filteredTasks.length === 0) {
+ return new Set();
+ }
+ return new Set([filteredTasks[0].name]);
+ });
+ }, [taskNamesKey]);
+
+ useEffect(() => {
+ setSelectedTaskNames((prev) => {
+ const remaining = [...prev].filter((taskName) =>
+ filteredTasks.some((task) => task.name === taskName)
+ );
+ if (remaining.length === prev.size) {
+ return prev;
+ }
+ return new Set(remaining);
+ });
+ }, [taskNamesKey]);
+
+ const toggleExpand = (task: Task) => {
+ setExpandedTaskNames((prev) => {
+ const next = new Set(prev);
+ if (next.has(task.name)) next.delete(task.name);
+ else next.add(task.name);
+ return next;
+ });
+ };
+ const toggleSelect = (task: Task) => {
+ setSelectedTaskNames((prev) => {
+ const next = new Set(prev);
+ if (next.has(task.name)) next.delete(task.name);
+ else next.add(task.name);
+ return next;
+ });
+ };
+
+ return (
+ <div className="w-full">
+ {!readonly && (
+ <DeployTaskToolbar
+ allTasks={filteredTasks}
+ onActionComplete={async () => {
+ await page.refreshState();
+ }}
+ onClearSelection={() => setSelectedTaskNames(new Set())}
+ onSelectAll={() =>
+ setSelectedTaskNames(
+ new Set(
+ filteredTasks
+ .filter((task) => isDeployTaskSelectable(task))
+ .map((task) => task.name)
+ )
+ )
+ }
+ selectedTasks={selectedTasks}
+ stage={stage}
+ />
+ )}
+
+ <div className="task-list space-y-3 px-4 py-3">
+ {visibleTasks.map((task) => (
+ <DeployTaskItem
+ active={selectedTaskName === task.name}
+ key={task.name}
+ isExpanded={expandedTaskNames.has(task.name)}
+ isSelected={selectedTaskNames.has(task.name)}
+ isSelectable={!readonly && isDeployTaskSelectable(task)}
+ onToggleExpand={() => toggleExpand(task)}
+ onToggleSelect={() => toggleSelect(task)}
+ readonly={readonly}
+ stageId={stage.name.split("/").pop() ?? ""}
+ stage={stage}
+ task={task}
+ />
+ ))}
+
+ {filteredTasks.length === 0 && (
+ <div className="py-8 text-center text-gray-500">
+ {t("rollout.task.no-tasks")}
+ </div>
+ )}
+
+ {hasMoreTasks && (
+ <div className="flex justify-start">
+ <Button
+ onClick={() =>
+ setDisplayedTaskCount((count) =>
+ Math.min(count + DEFAULT_PAGE_SIZE, filteredTasks.length)
+ )
+ }
+ size="xs"
+ variant="ghost"
+ >
+ {t("common.show-more")} ({remainingTasksCount}{" "}
+ {t("common.remaining")})
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx
new file mode 100644
index 0000000000..a444034efd
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskRow.tsx
@@ -0,0 +1,67 @@
+import { X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import { type Task } from "@/types/proto-es/v1/rollout_service_pb";
+import { stringifyTaskStatus } from "@/utils";
+import { DeployTaskStatus } from "./DeployTaskStatus";
+
+export function DeployTaskRow({
+ active,
+ onCloseTaskPanel,
+ stageId,
+ task,
+}: {
+ active: boolean;
+ onCloseTaskPanel: () => void;
+ stageId: string;
+ task: Task;
+}) {
+ const { t } = useTranslation();
+ const taskId = task.name.split("/").pop();
+
+ return (
+ <button
+ className={cn(
+ "flex w-full items-center justify-between rounded border px-3 py-2 text-left text-sm",
+ active
+ ? "border-accent bg-accent/5"
+ : "border-control-border hover:bg-gray-50"
+ )}
+ onClick={() => {
+ void router.push({
+ query: {
+ phase: "deploy",
+ stageId,
+ taskId,
+ },
+ });
+ }}
+ type="button"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <DeployTaskStatus size="small" status={task.status} />
+ <div className="min-w-0">
+ <div className="truncate text-main">{task.name}</div>
+ <div className="text-xs text-control-light">
+ {stringifyTaskStatus(task.status, t)}
+ </div>
+ </div>
+ </div>
+ {active && (
+ <Button
+ aria-label={t("common.close")}
+ size="sm"
+ variant="ghost"
+ onClick={(event) => {
+ event.stopPropagation();
+ onCloseTaskPanel();
+ }}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </button>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskStatus.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskStatus.tsx
new file mode 100644
index 0000000000..91de0969cf
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskStatus.tsx
@@ -0,0 +1,78 @@
+import { CircleDotDashed, FastForward, Pause } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { cn } from "@/react/lib/utils";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { stringifyTaskStatus } from "@/utils";
+
+export function DeployTaskStatus({
+ status,
+ size = "small",
+}: {
+ status: Task_Status;
+ size?: "tiny" | "small" | "medium" | "large";
+}) {
+ const { t } = useTranslation();
+ const classes =
+ size === "tiny"
+ ? "h-4 w-4"
+ : size === "small"
+ ? "h-5 w-5"
+ : size === "large"
+ ? "h-7 w-7"
+ : "h-6 w-6";
+
+ const statusLabel = stringifyTaskStatus(status, t);
+
+ return (
+ <Tooltip content={statusLabel}>
+ <div
+ className={cn(
+ "relative inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full select-none",
+ classes,
+ status === Task_Status.NOT_STARTED &&
+ "border-2 border-control bg-white",
+ (status === Task_Status.PENDING || status === Task_Status.RUNNING) &&
+ "border-2 border-accent bg-white text-accent",
+ status === Task_Status.SKIPPED &&
+ "border-2 border-control-light bg-white text-control-light",
+ status === Task_Status.DONE && "bg-success text-white",
+ status === Task_Status.FAILED && "bg-error text-white",
+ status === Task_Status.CANCELED &&
+ "border-2 border-control-light bg-white text-control-light"
+ )}
+ >
+ {status === Task_Status.STATUS_UNSPECIFIED && (
+ <CircleDotDashed className="h-full w-full" />
+ )}
+ {status === Task_Status.NOT_STARTED && (
+ <span className="h-1/2 w-1/2 rounded-full bg-control" />
+ )}
+ {status === Task_Status.PENDING && <Pause className="h-3/4 w-3/4" />}
+ {status === Task_Status.RUNNING && (
+ <div className="relative flex h-1/2 w-1/2 overflow-visible">
+ <span
+ aria-hidden="true"
+ className="absolute z-0 h-full w-full animate-ping rounded-full"
+ style={{ backgroundColor: "rgba(37, 99, 235, 0.5)" }}
+ />
+ <span
+ aria-hidden="true"
+ className="z-1 h-full w-full rounded-full bg-accent"
+ />
+ </div>
+ )}
+ {status === Task_Status.SKIPPED && (
+ <FastForward className="h-3/4 w-3/4" />
+ )}
+ {status === Task_Status.DONE && <span className="text-sm">✓</span>}
+ {status === Task_Status.FAILED && (
+ <span className="text-base font-medium">!</span>
+ )}
+ {status === Task_Status.CANCELED && (
+ <span className="text-base">−</span>
+ )}
+ </div>
+ </Tooltip>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx
new file mode 100644
index 0000000000..2e5e4abc9c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployTaskToolbar.tsx
@@ -0,0 +1,241 @@
+import { Play, SkipForward, X } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { Issue_Type } from "@/types/proto-es/v1/issue_service_pb";
+import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ CANCELABLE_TASK_STATUSES,
+ canRolloutTasks,
+ preloadRolloutPermissionContext,
+ RUNNABLE_TASK_STATUSES,
+} from "../../../issue-detail/utils/rollout";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import {
+ type PlanDetailTaskRolloutAction,
+ PlanDetailTaskRolloutActionPanel,
+} from "../PlanDetailTaskRolloutActionPanel";
+import { isDeployTaskSelectable } from "./taskActionState";
+
+export function DeployTaskToolbar({
+ allTasks,
+ selectedTasks,
+ stage,
+ onActionComplete,
+ onClearSelection,
+ onSelectAll,
+}: {
+ allTasks: Task[];
+ selectedTasks: Task[];
+ stage: Stage;
+ onActionComplete: () => Promise<void> | void;
+ onClearSelection: () => void;
+ onSelectAll: () => void;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const [showActionPanel, setShowActionPanel] = useState(false);
+ const [pendingAction, setPendingAction] = useState<
+ PlanDetailTaskRolloutAction | undefined
+ >(undefined);
+ const [permissionReady, setPermissionReady] = useState(false);
+ const checkboxRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ setPermissionReady(false);
+ await preloadRolloutPermissionContext({
+ environment: stage.environment,
+ projectName: project.name,
+ tasks: allTasks,
+ });
+ if (!canceled) setPermissionReady(true);
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [allTasks, project.name, stage.environment]);
+
+ const selectableTasks = allTasks.filter(isDeployTaskSelectable);
+ const canPerformTaskActions = permissionReady
+ ? canRolloutTasks({
+ currentUser,
+ environment: stage.environment,
+ issue: page.issue,
+ project,
+ tasks: selectedTasks,
+ })
+ : false;
+
+ const hasRunnableTasks = selectedTasks.some((task) =>
+ RUNNABLE_TASK_STATUSES.includes(task.status)
+ );
+ const hasSkippableTasks = selectedTasks.some((task) =>
+ RUNNABLE_TASK_STATUSES.includes(task.status)
+ );
+ const hasCancellableTasks = selectedTasks.some((task) =>
+ CANCELABLE_TASK_STATUSES.includes(task.status)
+ );
+
+ const getBaseDisabledTooltip = () => {
+ if (selectedTasks.length === 0) {
+ return t("task.no-tasks-selected");
+ }
+ if (!permissionReady) {
+ return "";
+ }
+ if (!canPerformTaskActions) {
+ if (
+ page.issue &&
+ page.issue.type === Issue_Type.DATABASE_EXPORT &&
+ page.issue.creator !== currentUser.name
+ ) {
+ return t("task.data-export-creator-only");
+ }
+ return t("task.no-permission");
+ }
+ return "";
+ };
+
+ const selectionCountText = t("rollout.task.selected-count", {
+ count: selectedTasks.length,
+ });
+
+ useEffect(() => {
+ if (checkboxRef.current) {
+ checkboxRef.current.indeterminate =
+ selectedTasks.length > 0 &&
+ selectedTasks.length < selectableTasks.length;
+ }
+ }, [selectableTasks.length, selectedTasks.length]);
+
+ return (
+ <>
+ <div className="sticky top-0 z-10 px-4">
+ <div className="flex items-center justify-between rounded-lg border border-blue-200 bg-blue-100 px-3 py-1">
+ <div className="flex items-center gap-x-3">
+ <Tooltip
+ content={
+ selectableTasks.length === 0
+ ? t("task.no-selectable-tasks")
+ : ""
+ }
+ >
+ <div>
+ <input
+ checked={
+ selectedTasks.length > 0 &&
+ selectedTasks.length === selectableTasks.length
+ }
+ className="accent-accent"
+ disabled={selectableTasks.length === 0}
+ ref={checkboxRef}
+ onChange={(event) => {
+ if (event.target.checked) onSelectAll();
+ else onClearSelection();
+ }}
+ type="checkbox"
+ />
+ </div>
+ </Tooltip>
+ <span className="text-sm text-blue-900">{selectionCountText}</span>
+ <div className="flex items-center gap-x-0.5">
+ <Tooltip
+ content={
+ !hasRunnableTasks
+ ? t("task.no-runnable-tasks")
+ : getBaseDisabledTooltip()
+ }
+ >
+ <div>
+ <Button
+ disabled={!hasRunnableTasks || !canPerformTaskActions}
+ onClick={() => {
+ setPendingAction("RUN");
+ setShowActionPanel(true);
+ }}
+ size="sm"
+ variant="ghost"
+ className="text-accent hover:bg-transparent"
+ >
+ <Play className="h-3.5 w-3.5" />
+ {t("common.run")}
+ </Button>
+ </div>
+ </Tooltip>
+ <Tooltip
+ content={
+ !hasSkippableTasks
+ ? t("task.no-skippable-tasks")
+ : getBaseDisabledTooltip()
+ }
+ >
+ <div>
+ <Button
+ disabled={!hasSkippableTasks || !canPerformTaskActions}
+ onClick={() => {
+ setPendingAction("SKIP");
+ setShowActionPanel(true);
+ }}
+ size="sm"
+ variant="ghost"
+ className="text-accent hover:bg-transparent"
+ >
+ <SkipForward className="h-3.5 w-3.5" />
+ {t("common.skip")}
+ </Button>
+ </div>
+ </Tooltip>
+ <Tooltip
+ content={
+ !hasCancellableTasks
+ ? t("task.no-cancelable-tasks")
+ : getBaseDisabledTooltip()
+ }
+ >
+ <div>
+ <Button
+ disabled={!hasCancellableTasks || !canPerformTaskActions}
+ onClick={() => {
+ setPendingAction("CANCEL");
+ setShowActionPanel(true);
+ }}
+ size="sm"
+ variant="ghost"
+ className="text-accent hover:bg-transparent"
+ >
+ <X className="h-3.5 w-3.5" />
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {pendingAction && (
+ <PlanDetailTaskRolloutActionPanel
+ action={pendingAction}
+ onConfirm={async () => {
+ await onActionComplete();
+ onClearSelection();
+ }}
+ onOpenChange={(open) => {
+ setShowActionPanel(open);
+ if (!open) {
+ setPendingAction(undefined);
+ }
+ }}
+ open={showActionPanel}
+ target={{ type: "tasks", tasks: selectedTasks, stage }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActionState.ts b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActionState.ts
new file mode 100644
index 0000000000..d2a3f48351
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActionState.ts
@@ -0,0 +1,50 @@
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+
+const RUNNABLE_TASK_STATUSES: Task_Status[] = [
+ Task_Status.NOT_STARTED,
+ Task_Status.CANCELED,
+ Task_Status.FAILED,
+];
+
+const CANCELABLE_TASK_STATUSES: Task_Status[] = [
+ Task_Status.PENDING,
+ Task_Status.RUNNING,
+];
+
+export interface DeployTaskActionState {
+ canCancel: boolean;
+ canRun: boolean;
+ canSkip: boolean;
+ hasActions: boolean;
+}
+
+export const getDeployTaskActionState = ({
+ canPerformActions,
+ status,
+}: {
+ canPerformActions: boolean;
+ status: Task_Status;
+}): DeployTaskActionState => {
+ const canRun = canPerformActions && RUNNABLE_TASK_STATUSES.includes(status);
+ const canSkip = canPerformActions && RUNNABLE_TASK_STATUSES.includes(status);
+ const canCancel =
+ canPerformActions && CANCELABLE_TASK_STATUSES.includes(status);
+
+ return {
+ canCancel,
+ canRun,
+ canSkip,
+ hasActions: canRun || canSkip || canCancel,
+ };
+};
+
+const ACTIONABLE_TASK_STATUSES = new Set<Task_Status>([
+ Task_Status.NOT_STARTED,
+ Task_Status.PENDING,
+ Task_Status.RUNNING,
+ Task_Status.FAILED,
+ Task_Status.CANCELED,
+]);
+
+export const isDeployTaskSelectable = (task: { status: Task_Status }) =>
+ ACTIONABLE_TASK_STATUSES.has(task.status);
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.test.tsx
new file mode 100644
index 0000000000..7a7b9173a9
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.test.tsx
@@ -0,0 +1,47 @@
+import { describe, expect, test } from "vitest";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { getDeployTaskActionState } from "./taskActionState";
+
+describe("deploy task action visibility", () => {
+ test("hides actions when permission is missing", () => {
+ expect(
+ getDeployTaskActionState({
+ canPerformActions: false,
+ status: Task_Status.NOT_STARTED,
+ })
+ ).toEqual({
+ canCancel: false,
+ canRun: false,
+ canSkip: false,
+ hasActions: false,
+ });
+ });
+
+ test("shows run and skip for runnable task statuses", () => {
+ expect(
+ getDeployTaskActionState({
+ canPerformActions: true,
+ status: Task_Status.FAILED,
+ })
+ ).toEqual({
+ canCancel: false,
+ canRun: true,
+ canSkip: true,
+ hasActions: true,
+ });
+ });
+
+ test("shows cancel for cancelable task statuses", () => {
+ expect(
+ getDeployTaskActionState({
+ canPerformActions: true,
+ status: Task_Status.RUNNING,
+ })
+ ).toEqual({
+ canCancel: true,
+ canRun: false,
+ canSkip: false,
+ hasActions: true,
+ });
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx
new file mode 100644
index 0000000000..c3ef915e17
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskActions.tsx
@@ -0,0 +1,64 @@
+import { useEffect, useMemo, useState } from "react";
+import type { Stage, Task } from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ canRolloutTasks,
+ preloadRolloutPermissionContext,
+} from "../../../issue-detail/utils/rollout";
+import { usePlanDetailContext } from "../../context/PlanDetailContext";
+import {
+ type DeployTaskActionState,
+ getDeployTaskActionState,
+} from "./taskActionState";
+
+export const useDeployTaskActions = ({
+ stage,
+ task,
+}: {
+ stage?: Stage;
+ task: Task;
+}): DeployTaskActionState & { permissionReady: boolean } => {
+ const page = usePlanDetailContext();
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const [permissionReady, setPermissionReady] = useState(false);
+
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ setPermissionReady(false);
+ await preloadRolloutPermissionContext({
+ environment: stage?.environment,
+ projectName: project.name,
+ tasks: [task],
+ });
+ if (!canceled) {
+ setPermissionReady(true);
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [project.name, stage?.environment, task]);
+
+ const canPerformActions = useMemo(() => {
+ if (!permissionReady || !stage) {
+ return false;
+ }
+ return canRolloutTasks({
+ currentUser,
+ environment: stage.environment,
+ issue: page.issue,
+ project,
+ tasks: [task],
+ });
+ }, [currentUser, page.issue, permissionReady, project, stage, task]);
+
+ return {
+ ...getDeployTaskActionState({
+ canPerformActions,
+ status: task.status,
+ }),
+ permissionReady,
+ };
+};
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.ts b/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.ts
new file mode 100644
index 0000000000..35684928a2
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/taskRunUtils.ts
@@ -0,0 +1,38 @@
+import type { TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+import { TaskRun_Status } from "@/types/proto-es/v1/rollout_service_pb";
+
+const formatDuration = (durationMs: number): string => {
+ const seconds = Math.floor(durationMs / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+
+ if (hours > 0) {
+ return `${hours}h ${minutes % 60}m`;
+ }
+ if (minutes > 0) {
+ return `${minutes}m ${seconds % 60}s`;
+ }
+ if (seconds > 0) {
+ return `${seconds}s`;
+ }
+ if (durationMs > 0) {
+ return `${Math.round(durationMs)}ms`;
+ }
+ return "< 1s";
+};
+
+export const getTaskRunDuration = (taskRun: TaskRun): string => {
+ if (taskRun.status === TaskRun_Status.PENDING || !taskRun.startTime) {
+ return "";
+ }
+ const endMs =
+ taskRun.status === TaskRun_Status.RUNNING
+ ? Date.now()
+ : taskRun.updateTime
+ ? Number(taskRun.updateTime.seconds) * 1000
+ : 0;
+ if (endMs === 0) {
+ return "";
+ }
+ return formatDuration(endMs - Number(taskRun.startTime.seconds) * 1000);
+};
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts b/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts
new file mode 100644
index 0000000000..793b37da13
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/types.ts
@@ -0,0 +1,20 @@
+import type { Task, TaskRun } from "@/types/proto-es/v1/rollout_service_pb";
+
+export type PendingTaskGroup = {
+ environment: string;
+ tasks: Task[];
+};
+
+export type RollbackItem = {
+ task: Task;
+ taskRun: TaskRun;
+};
+
+export type DeployBranchProps = {
+ selectedTask?: Task;
+ onCloseTaskPanel: () => void;
+};
+
+export type DeployTaskDetailPanelProps = {
+ task: Task;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx
new file mode 100644
index 0000000000..785ab20d6f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/useDeployTaskStatement.tsx
@@ -0,0 +1,57 @@
+import { useEffect, useMemo, useState } from "react";
+import { useSheetV1Store } from "@/store";
+import type { Task } from "@/types/proto-es/v1/rollout_service_pb";
+import { getStatementSize } from "@/utils/sheet";
+import { sheetNameOfTaskV1 } from "@/utils/v1/issue/rollout";
+import { getSheetStatement } from "@/utils/v1/sheet";
+
+export const useDeployTaskStatement = ({
+ enabled,
+ task,
+}: {
+ enabled: boolean;
+ task: Task;
+}) => {
+ const sheetStore = useSheetV1Store();
+ const sheetName = useMemo(() => sheetNameOfTaskV1(task), [task]);
+ const [statement, setStatement] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+ const [isTruncated, setIsTruncated] = useState(false);
+
+ useEffect(() => {
+ if (!enabled || !sheetName) {
+ setStatement("");
+ setIsTruncated(false);
+ setIsLoading(false);
+ return;
+ }
+
+ let canceled = false;
+ const load = async () => {
+ setIsLoading(true);
+ try {
+ let sheet = sheetStore.getSheetByName(sheetName);
+ if (!sheet) {
+ sheet = await sheetStore.getOrFetchSheetByName(sheetName);
+ }
+ if (!sheet) {
+ return;
+ }
+ if (canceled) return;
+ const nextStatement = getSheetStatement(sheet);
+ setStatement(nextStatement);
+ setIsTruncated(getStatementSize(nextStatement) < sheet.contentSize);
+ } finally {
+ if (!canceled) {
+ setIsLoading(false);
+ }
+ }
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [enabled, sheetName, sheetStore]);
+
+ return { isLoading, isTruncated, statement };
+};
diff --git a/frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx b/frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx
new file mode 100644
index 0000000000..b4ee4c6f59
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/context/PlanDetailContext.tsx
@@ -0,0 +1,28 @@
+import { createContext, type ReactNode, useContext } from "react";
+import type { PlanDetailPageState } from "../hooks/usePlanDetailPage";
+
+const PlanDetailContext = createContext<PlanDetailPageState | null>(null);
+
+export const PlanDetailProvider = ({
+ value,
+ children,
+}: {
+ value: PlanDetailPageState;
+ children: ReactNode;
+}) => {
+ return (
+ <PlanDetailContext.Provider value={value}>
+ {children}
+ </PlanDetailContext.Provider>
+ );
+};
+
+export const usePlanDetailContext = () => {
+ const context = useContext(PlanDetailContext);
+ if (!context) {
+ throw new Error(
+ "usePlanDetailContext must be used within PlanDetailProvider"
+ );
+ }
+ return context;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
new file mode 100644
index 0000000000..affff6c6c9
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailPage.ts
@@ -0,0 +1,733 @@
+import { create } from "@bufbuild/protobuf";
+import { Code, ConnectError } from "@connectrpc/connect";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ issueServiceClientConnect,
+ planServiceClientConnect,
+ projectServiceClientConnect,
+ rolloutServiceClientConnect,
+ userServiceClientConnect,
+} from "@/connect";
+import { router } from "@/router";
+import {
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
+} from "@/router/dashboard/projectV1";
+import {
+ getRouteQueryString,
+ PLAN_DETAIL_PHASE_DEPLOY,
+} from "@/router/dashboard/projectV1RouteHelpers";
+import {
+ WORKSPACE_ROUTE_403,
+ WORKSPACE_ROUTE_404,
+} from "@/router/dashboard/workspaceRoutes";
+import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ GetIssueRequestSchema,
+ type Issue,
+ IssueStatus,
+} from "@/types/proto-es/v1/issue_service_pb";
+import {
+ GetPlanCheckRunRequestSchema,
+ GetPlanRequestSchema,
+ type Plan,
+ type PlanCheckRun,
+} from "@/types/proto-es/v1/plan_service_pb";
+import {
+ GetProjectRequestSchema,
+ type Project,
+} from "@/types/proto-es/v1/project_service_pb";
+import {
+ GetRolloutRequestSchema,
+ ListTaskRunsRequestSchema,
+ type Rollout,
+ Task_Status,
+ type TaskRun,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import type { User } from "@/types/proto-es/v1/user_service_pb";
+import { unknownPlan } from "@/types/v1/issue/plan";
+import { unknownProject } from "@/types/v1/project";
+import { unknownUser } from "@/types/v1/user";
+import {
+ getIssueRoute,
+ getRolloutFromPlan,
+ hasProjectPermissionV2,
+ minmax,
+ setDocumentTitle,
+} from "@/utils";
+import { createPlanSkeleton } from "../utils/createPlan";
+
+const POLLER_INTERVAL = {
+ min: 1000,
+ max: 30000,
+ growth: 2,
+ jitter: 250,
+} as const;
+
+const PROJECT_NAME_PREFIX = "projects/";
+
+// Width below which the sidebar collapses into a mobile drawer.
+export const MOBILE_BREAKPOINT_PX = 780;
+// Width at or above which the sidebar widens.
+export const WIDE_SIDEBAR_BREAKPOINT_PX = 1280;
+export const SIDEBAR_WIDTH_NARROW_PX = 240;
+export const SIDEBAR_WIDTH_WIDE_PX = 336;
+
+export type PlanDetailSidebarMode = "NONE" | "DESKTOP" | "MOBILE";
+export type PlanDetailPhase = "changes" | "review" | "deploy";
+
+export interface PlanDetailPageSnapshot {
+ projectId: string;
+ planId: string;
+ specId?: string;
+ pageKey: string;
+ projectTitle: string;
+ projectRequireIssueApproval: boolean;
+ projectRequirePlanCheckNoError: boolean;
+ projectCanCreateRollout: boolean;
+ currentUser: User;
+ project: Project;
+ isCreating: boolean;
+ isInitializing: boolean;
+ ready: boolean;
+ readonly: boolean;
+ plan: Plan;
+ issue?: Issue;
+ rollout?: Rollout;
+ planCheckRuns: PlanCheckRun[];
+ taskRuns: TaskRun[];
+ sidebarMode: PlanDetailSidebarMode;
+ containerWidth: number;
+ desktopSidebarWidth: number;
+ mobileSidebarOpen: boolean;
+}
+
+export interface PlanDetailPageState extends PlanDetailPageSnapshot {
+ isEditing: boolean;
+ isRefreshing: boolean;
+ lastRefreshTime: number;
+ activePhases: Set<PlanDetailPhase>;
+ routeName?: string;
+ routePhase?: string;
+ routeStageId?: string;
+ routeTaskId?: string;
+ selectedTaskName?: string;
+ pendingLeaveConfirm: boolean;
+ patchState: (patch: Partial<PlanDetailPageSnapshot>) => void;
+ refreshState: () => Promise<void>;
+ bypassLeaveGuardOnce: () => void;
+ setEditing: (scope: string, editing: boolean) => void;
+ setMobileSidebarOpen: (open: boolean) => void;
+ togglePhase: (phase: PlanDetailPhase) => void;
+ expandPhase: (phase: PlanDetailPhase) => void;
+ closeTaskPanel: () => void;
+ resolveLeaveConfirm: (confirmed: boolean) => void;
+}
+
+const buildDefaultSnapshot = (
+ projectId: string,
+ planId: string,
+ specId?: string
+): PlanDetailPageSnapshot => ({
+ projectId,
+ planId,
+ specId,
+ pageKey: `${projectId}/${planId}/${specId ?? ""}`,
+ projectTitle: "",
+ projectRequireIssueApproval: true,
+ projectRequirePlanCheckNoError: true,
+ projectCanCreateRollout: false,
+ currentUser: unknownUser(),
+ project: unknownProject(),
+ isCreating: planId.toLowerCase() === "create",
+ isInitializing: true,
+ ready: false,
+ readonly: true,
+ plan: unknownPlan(),
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+ sidebarMode: "NONE",
+ containerWidth: 0,
+ desktopSidebarWidth: 0,
+ mobileSidebarOpen: false,
+});
+
+const applyDerivedState = (
+ snapshot: PlanDetailPageSnapshot
+): PlanDetailPageSnapshot => {
+ const readonly =
+ snapshot.plan.state === State.DELETED ||
+ (snapshot.issue ? snapshot.issue.status !== IssueStatus.OPEN : false);
+ return {
+ ...snapshot,
+ readonly,
+ ready: !snapshot.isInitializing && !!snapshot.plan.name,
+ };
+};
+
+const shouldRedirectToIssueDetail = (plan: Plan, issue?: Issue) => {
+ if (!issue?.name) {
+ return false;
+ }
+ if (plan.specs.length === 0) {
+ return false;
+ }
+ return plan.specs.every((spec) => {
+ return (
+ spec.config?.case === "createDatabaseConfig" ||
+ spec.config?.case === "exportDataConfig"
+ );
+ });
+};
+
+const fetchPlanDetailSnapshot = async (
+ projectId: string,
+ planId: string,
+ routeQuery: Record<string, unknown> = {}
+): Promise<Partial<PlanDetailPageSnapshot>> => {
+ const [project, currentUser] = await Promise.all([
+ projectServiceClientConnect.getProject(
+ create(GetProjectRequestSchema, {
+ name: `${PROJECT_NAME_PREFIX}${projectId}`,
+ })
+ ),
+ userServiceClientConnect.getCurrentUser({}),
+ ]);
+
+ if (planId.toLowerCase() === "create") {
+ const plan = await createPlanSkeleton(
+ project,
+ convertRouteQuery(routeQuery)
+ );
+ return {
+ currentUser,
+ plan,
+ project,
+ projectTitle: project.title,
+ projectCanCreateRollout: hasProjectPermissionV2(
+ project,
+ "bb.rollouts.create"
+ ),
+ projectRequireIssueApproval: project.requireIssueApproval,
+ projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+ };
+ }
+
+ const plan = await planServiceClientConnect.getPlan(
+ create(GetPlanRequestSchema, {
+ name: `${PROJECT_NAME_PREFIX}${projectId}/plans/${planId}`,
+ })
+ );
+
+ const [issue, planCheckRuns, rollout] = await Promise.all([
+ plan.issue
+ ? issueServiceClientConnect
+ .getIssue(create(GetIssueRequestSchema, { name: plan.issue }))
+ .catch(() => undefined)
+ : Promise.resolve(undefined),
+ planServiceClientConnect
+ .getPlanCheckRun(
+ create(GetPlanCheckRunRequestSchema, {
+ name: `${plan.name}/planCheckRun`,
+ })
+ )
+ .then((run) => [run] as PlanCheckRun[])
+ .catch(() => []),
+ plan.hasRollout
+ ? rolloutServiceClientConnect
+ .getRollout(
+ create(GetRolloutRequestSchema, {
+ name: getRolloutFromPlan(plan.name),
+ })
+ )
+ .catch(() => undefined)
+ : Promise.resolve(undefined),
+ ]);
+
+ const taskRuns =
+ rollout !== undefined
+ ? await rolloutServiceClientConnect
+ .listTaskRuns(
+ create(ListTaskRunsRequestSchema, {
+ parent: `${rollout.name}/stages/-/tasks/-`,
+ })
+ )
+ .then((response) => response.taskRuns)
+ .catch(() => [])
+ : [];
+
+ return {
+ currentUser,
+ plan,
+ project,
+ projectTitle: project.title,
+ projectCanCreateRollout: hasProjectPermissionV2(
+ project,
+ "bb.rollouts.create"
+ ),
+ projectRequireIssueApproval: project.requireIssueApproval,
+ projectRequirePlanCheckNoError: project.requirePlanCheckNoError,
+ issue,
+ rollout,
+ planCheckRuns,
+ taskRuns,
+ };
+};
+
+const defaultActivePhases = (): Set<PlanDetailPhase> =>
+ new Set<PlanDetailPhase>(["changes", "review", "deploy"]);
+
+const convertRouteQuery = (query: Record<string, unknown>) => {
+ const kv: Record<string, string> = {};
+ for (const [key, value] of Object.entries(query)) {
+ if (typeof value === "string") {
+ kv[key] = value;
+ }
+ }
+ return kv;
+};
+
+export const usePlanDetailPage = ({
+ projectId,
+ planId,
+ routeName,
+ routeQuery = {},
+ specId,
+ pageHost,
+}: {
+ projectId: string;
+ planId: string;
+ routeName?: string;
+ routeQuery?: Record<string, unknown>;
+ specId?: string;
+ pageHost: HTMLDivElement | null;
+}): PlanDetailPageState => {
+ const { t } = useTranslation();
+ const [snapshot, setSnapshot] = useState<PlanDetailPageSnapshot>(() =>
+ buildDefaultSnapshot(projectId, planId, specId)
+ );
+ const [activePhases, setActivePhases] = useState<Set<PlanDetailPhase>>(() =>
+ defaultActivePhases()
+ );
+ const [editingScopes, setEditingScopes] = useState<Record<string, true>>({});
+ const [isRefreshing, setIsRefreshing] = useState(false);
+ const [lastRefreshTime, setLastRefreshTime] = useState(0);
+ const [pendingLeaveConfirm, setPendingLeaveConfirm] = useState(false);
+ 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);
+ const isEditing = Object.keys(editingScopes).length > 0;
+
+ // routeQuery is a fresh object on every router navigation. Stash the latest
+ // value in a ref and depend only on the individual keys we actually consume,
+ // so the init/refresh/poll effects don't churn (and reset isInitializing)
+ // every time an unrelated query param like ?taskId changes.
+ const routeQueryRef = useRef(routeQuery);
+ routeQueryRef.current = routeQuery;
+ const routePhase = getRouteQueryString(routeQuery.phase as never);
+ const routeStageId = getRouteQueryString(routeQuery.stageId as never);
+ const routeTaskId = getRouteQueryString(routeQuery.taskId as never);
+
+ useEffect(() => {
+ latestSnapshotRef.current = snapshot;
+ }, [snapshot]);
+
+ const stopPolling = useCallback(() => {
+ if (!pollTimerRef.current) {
+ return;
+ }
+ window.clearTimeout(pollTimerRef.current);
+ pollTimerRef.current = undefined;
+ }, []);
+
+ const patchState = useCallback((patch: Partial<PlanDetailPageSnapshot>) => {
+ setSnapshot((prev) => applyDerivedState({ ...prev, ...patch }));
+ }, []);
+
+ const refreshState = useCallback(async () => {
+ try {
+ setIsRefreshing(true);
+ const current = latestSnapshotRef.current;
+ const patch = await fetchPlanDetailSnapshot(
+ current.projectId,
+ current.planId,
+ routeQueryRef.current
+ );
+ patchState(patch);
+ setLastRefreshTime(Date.now());
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [patchState]);
+
+ const setMobileSidebarOpen = useCallback(
+ (open: boolean) => {
+ patchState({ mobileSidebarOpen: open });
+ },
+ [patchState]
+ );
+
+ const setEditing = useCallback((scope: string, editing: boolean) => {
+ setEditingScopes((prev) => {
+ if (editing) {
+ if (prev[scope]) return prev;
+ return { ...prev, [scope]: true };
+ }
+ if (!prev[scope]) return prev;
+ const next = { ...prev };
+ delete next[scope];
+ return next;
+ });
+ }, []);
+
+ const bypassLeaveGuardOnce = useCallback(() => {
+ bypassLeaveGuardOnceRef.current = true;
+ }, []);
+
+ const togglePhase = useCallback((phase: PlanDetailPhase) => {
+ setActivePhases((prev) => {
+ const next = new Set(prev);
+ if (next.has(phase)) {
+ next.delete(phase);
+ } else {
+ next.add(phase);
+ }
+ return next;
+ });
+ }, []);
+
+ const expandPhase = useCallback((phase: PlanDetailPhase) => {
+ setActivePhases((prev) => new Set([...prev, phase]));
+ }, []);
+
+ const closeTaskPanel = useCallback(() => {
+ void router.replace({
+ query: {
+ ...(routePhase ? { phase: routePhase } : {}),
+ ...(routeStageId ? { stageId: routeStageId } : {}),
+ },
+ });
+ }, [routePhase, routeStageId]);
+
+ useEffect(() => {
+ setEditingScopes({});
+ patchState({
+ projectId,
+ planId,
+ specId,
+ pageKey: `${projectId}/${planId}/${specId ?? ""}`,
+ projectTitle: "",
+ isCreating: planId.toLowerCase() === "create",
+ isInitializing: true,
+ plan: unknownPlan(),
+ issue: undefined,
+ rollout: undefined,
+ planCheckRuns: [],
+ taskRuns: [],
+ });
+
+ let canceled = false;
+
+ const load = async () => {
+ try {
+ const patch = await fetchPlanDetailSnapshot(
+ projectId,
+ planId,
+ routeQueryRef.current
+ );
+ if (canceled) {
+ return;
+ }
+ patchState({
+ ...patch,
+ isInitializing: false,
+ specId,
+ });
+ } catch (error) {
+ if (canceled) {
+ return;
+ }
+ if (error instanceof ConnectError) {
+ if (error.code === Code.NotFound) {
+ void router.push({ name: WORKSPACE_ROUTE_404 });
+ } else if (error.code === Code.PermissionDenied) {
+ void router.push({ name: WORKSPACE_ROUTE_403 });
+ }
+ patchState({ isInitializing: false });
+ return;
+ }
+
+ patchState({ isInitializing: false });
+ throw error;
+ }
+ };
+
+ void load();
+
+ return () => {
+ canceled = true;
+ };
+ }, [patchState, planId, projectId, specId]);
+
+ const resolveLeaveConfirm = useCallback((confirmed: boolean) => {
+ const resolver = leaveResolverRef.current;
+ leaveResolverRef.current = null;
+ setPendingLeaveConfirm(false);
+ resolver?.(confirmed);
+ }, []);
+
+ useEffect(() => {
+ if (!isEditing) {
+ return;
+ }
+
+ const onBeforeUnload = (event: BeforeUnloadEvent) => {
+ event.returnValue = t("common.leave-without-saving");
+ event.preventDefault();
+ };
+ window.addEventListener("beforeunload", onBeforeUnload);
+ 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);
+ };
+ setPendingLeaveConfirm(true);
+ });
+
+ 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]);
+
+ useEffect(() => {
+ if (snapshot.isCreating) {
+ setDocumentTitle(t("plan.new-plan"), snapshot.projectTitle);
+ return;
+ }
+ if (snapshot.ready && snapshot.plan.title) {
+ setDocumentTitle(snapshot.plan.title, snapshot.projectTitle);
+ }
+ }, [
+ snapshot.isCreating,
+ snapshot.plan.title,
+ snapshot.projectTitle,
+ snapshot.ready,
+ t,
+ ]);
+
+ useEffect(() => {
+ if (
+ snapshot.ready &&
+ shouldRedirectToIssueDetail(snapshot.plan, snapshot.issue)
+ ) {
+ void router.replace(getIssueRoute({ name: snapshot.issue?.name ?? "" }));
+ }
+ }, [snapshot.issue, snapshot.plan, snapshot.ready]);
+
+ useEffect(() => {
+ if (
+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS ||
+ routeName === PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL
+ ) {
+ expandPhase("changes");
+ }
+ if (
+ routePhase === PLAN_DETAIL_PHASE_DEPLOY ||
+ routeStageId ||
+ routeTaskId
+ ) {
+ expandPhase("deploy");
+ }
+ }, [expandPhase, routeName, routePhase, routeStageId, routeTaskId]);
+
+ useEffect(() => {
+ if (!pageHost) {
+ patchState({
+ containerWidth: 0,
+ desktopSidebarWidth: 0,
+ mobileSidebarOpen: false,
+ sidebarMode: "NONE",
+ });
+ return;
+ }
+
+ const updateSidebar = () => {
+ const containerWidth = pageHost.getBoundingClientRect().width;
+ const sidebarMode: PlanDetailSidebarMode =
+ containerWidth === 0
+ ? "NONE"
+ : containerWidth < MOBILE_BREAKPOINT_PX
+ ? "MOBILE"
+ : "DESKTOP";
+ patchState({
+ containerWidth,
+ desktopSidebarWidth:
+ containerWidth < WIDE_SIDEBAR_BREAKPOINT_PX
+ ? SIDEBAR_WIDTH_NARROW_PX
+ : SIDEBAR_WIDTH_WIDE_PX,
+ mobileSidebarOpen:
+ sidebarMode === "MOBILE"
+ ? latestSnapshotRef.current.mobileSidebarOpen
+ : false,
+ sidebarMode,
+ });
+ };
+
+ updateSidebar();
+ const observer = new ResizeObserver(() => updateSidebar());
+ observer.observe(pageHost);
+
+ return () => observer.disconnect();
+ }, [pageHost, patchState]);
+
+ const isPlanDone = useMemo(() => {
+ if (!snapshot.rollout) {
+ return false;
+ }
+ const allTasks = snapshot.rollout.stages.flatMap((stage) => stage.tasks);
+ return (
+ allTasks.length > 0 &&
+ allTasks.every(
+ (task) =>
+ task.status === Task_Status.DONE ||
+ task.status === Task_Status.SKIPPED
+ )
+ );
+ }, [snapshot.rollout]);
+
+ useEffect(() => {
+ if (!snapshot.ready || snapshot.isCreating || isPlanDone) {
+ stopPolling();
+ return;
+ }
+
+ let canceled = false;
+
+ const poll = (interval: number) => {
+ stopPolling();
+ const nextInterval = minmax(
+ interval +
+ Math.floor(Math.random() * (POLLER_INTERVAL.jitter * 2 + 1)) -
+ POLLER_INTERVAL.jitter,
+ POLLER_INTERVAL.min,
+ POLLER_INTERVAL.max
+ );
+
+ pollTimerRef.current = window.setTimeout(async () => {
+ if (canceled) {
+ return;
+ }
+ await refreshState().catch(() => undefined);
+ if (canceled) {
+ return;
+ }
+ poll(
+ Math.min(nextInterval * POLLER_INTERVAL.growth, POLLER_INTERVAL.max)
+ );
+ }, nextInterval);
+ };
+
+ poll(POLLER_INTERVAL.min);
+
+ return () => {
+ canceled = true;
+ stopPolling();
+ };
+ }, [
+ isPlanDone,
+ refreshState,
+ snapshot.isCreating,
+ snapshot.ready,
+ stopPolling,
+ ]);
+
+ const selectedTaskName = useMemo(() => {
+ if (!routeTaskId || !snapshot.rollout) {
+ return undefined;
+ }
+ for (const stage of snapshot.rollout.stages) {
+ const task = stage.tasks.find((item) =>
+ item.name.endsWith(`/${routeTaskId}`)
+ );
+ if (task) {
+ return task.name;
+ }
+ }
+ return undefined;
+ }, [routeTaskId, snapshot.rollout]);
+
+ return useMemo(
+ () => ({
+ ...snapshot,
+ isEditing,
+ isRefreshing,
+ lastRefreshTime,
+ activePhases,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ selectedTaskName,
+ pendingLeaveConfirm,
+ bypassLeaveGuardOnce,
+ patchState,
+ refreshState,
+ setEditing,
+ setMobileSidebarOpen,
+ togglePhase,
+ expandPhase,
+ closeTaskPanel,
+ resolveLeaveConfirm,
+ }),
+ [
+ activePhases,
+ bypassLeaveGuardOnce,
+ closeTaskPanel,
+ isEditing,
+ isRefreshing,
+ lastRefreshTime,
+ patchState,
+ pendingLeaveConfirm,
+ refreshState,
+ resolveLeaveConfirm,
+ routeName,
+ routePhase,
+ routeStageId,
+ routeTaskId,
+ selectedTaskName,
+ setEditing,
+ setMobileSidebarOpen,
+ snapshot,
+ togglePhase,
+ expandPhase,
+ ]
+ );
+};
diff --git a/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts
new file mode 100644
index 0000000000..b70345830f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/hooks/usePlanDetailSpecValidation.ts
@@ -0,0 +1,78 @@
+import { useEffect, useState } from "react";
+import { useSheetV1Store } from "@/store";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { sheetNameOfSpec } from "@/utils/v1/issue/plan";
+import { extractSheetUID, getSheetStatement } from "@/utils/v1/sheet";
+import { getLocalSheetByName } from "../utils/localSheet";
+
+const checkSpecStatement = async (
+ spec: Plan_Spec,
+ sheetStore: ReturnType<typeof useSheetV1Store>
+): Promise<boolean> => {
+ if (
+ spec.config?.case !== "changeDatabaseConfig" &&
+ spec.config?.case !== "exportDataConfig"
+ ) {
+ return false;
+ }
+
+ if (
+ spec.config?.case === "changeDatabaseConfig" &&
+ spec.config.value.release
+ ) {
+ return false;
+ }
+
+ const sheetName = sheetNameOfSpec(spec);
+ if (!sheetName) {
+ return true;
+ }
+
+ try {
+ const uid = extractSheetUID(sheetName);
+ const sheet = uid.startsWith("-")
+ ? getLocalSheetByName(sheetName)
+ : await sheetStore.getOrFetchSheetByName(sheetName);
+ if (!sheet) {
+ return true;
+ }
+ return getSheetStatement(sheet).trim() === "";
+ } catch {
+ return false;
+ }
+};
+
+export function usePlanDetailSpecValidation(specs: Plan_Spec[]) {
+ const sheetStore = useSheetV1Store();
+ const [emptySpecIdSet, setEmptySpecIdSet] = useState<Set<string>>(
+ () => new Set()
+ );
+
+ useEffect(() => {
+ let canceled = false;
+
+ const validate = async () => {
+ const next = new Set<string>();
+ await Promise.all(
+ specs.map(async (spec) => {
+ if (await checkSpecStatement(spec, sheetStore)) {
+ next.add(spec.id);
+ }
+ })
+ );
+ if (!canceled) {
+ setEmptySpecIdSet(next);
+ }
+ };
+
+ void validate();
+
+ return () => {
+ canceled = true;
+ };
+ }, [sheetStore, specs]);
+
+ return {
+ emptySpecIdSet,
+ };
+}
diff --git a/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts b/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts
new file mode 100644
index 0000000000..6f5753c2db
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/createPlan.ts
@@ -0,0 +1,137 @@
+import { create } from "@bufbuild/protobuf";
+import { head } from "lodash-es";
+import { v4 as uuidv4 } from "uuid";
+import { useStorageStore } from "@/store";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ Plan_ChangeDatabaseConfigSchema,
+ Plan_SpecSchema,
+ PlanSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { extractSheetUID, setSheetStatement } from "@/utils";
+import { getLocalSheetByName, getNextLocalSheetUID } from "./localSheet";
+
+type PlanTemplate = "bb.plan.change-database";
+
+type InitialSQL = {
+ sqlMap?: Record<string, string>;
+ sql?: string;
+};
+
+const buildSpecForTargets = (
+ targets: string[],
+ project: Project,
+ sheetUID?: string
+) => {
+ const sheet = `${project.name}/sheets/${sheetUID ?? getNextLocalSheetUID()}`;
+ return create(Plan_SpecSchema, {
+ id: uuidv4(),
+ config: {
+ case: "changeDatabaseConfig",
+ value: create(Plan_ChangeDatabaseConfigSchema, {
+ enablePriorBackup: false,
+ sheet,
+ targets,
+ }),
+ },
+ });
+};
+
+const targetsForSpec = (spec: Plan_Spec): string[] => {
+ if (spec.config.case === "changeDatabaseConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ if (spec.config.case === "exportDataConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ return [];
+};
+
+const maybeSetInitialSQLForSpec = (spec: Plan_Spec, initialSQL: InitialSQL) => {
+ const sheet =
+ spec.config.case === "changeDatabaseConfig" ||
+ spec.config.case === "exportDataConfig"
+ ? spec.config.value.sheet
+ : "";
+ if (!sheet || !extractSheetUID(sheet).startsWith("-")) {
+ return;
+ }
+ const target = head(targetsForSpec(spec));
+ const sql = initialSQL.sqlMap?.[target || ""] ?? initialSQL.sql ?? "";
+ if (!sql) {
+ return;
+ }
+ setSheetStatement(getLocalSheetByName(sheet), sql);
+};
+
+const extractInitialSQLFromQuery = async (
+ query: Record<string, string>
+): Promise<InitialSQL> => {
+ const storageStore = useStorageStore();
+ if (query.sql) {
+ return { sql: query.sql };
+ }
+ if (query.sqlStorageKey) {
+ return {
+ sql: (await storageStore.get<string>(query.sqlStorageKey)) || "",
+ };
+ }
+ const sqlMapText = query.sqlMap;
+ if (sqlMapText) {
+ try {
+ const parsed = JSON.parse(sqlMapText);
+ if (typeof parsed === "object" && parsed !== null) {
+ return { sqlMap: parsed as Record<string, string> };
+ }
+ } catch {
+ // Fallback to single SQL below.
+ }
+ }
+ if (query.sqlMapStorageKey) {
+ return {
+ sqlMap:
+ (await storageStore.get<Record<string, string>>(
+ query.sqlMapStorageKey
+ )) || {},
+ };
+ }
+ return {};
+};
+
+export const createPlanSkeleton = async (
+ project: Project,
+ query: Record<string, string>
+) => {
+ const template = query.template as PlanTemplate | undefined;
+ if (!template || template !== "bb.plan.change-database") {
+ throw new Error(
+ "Only change-database plan creation is supported from the plan detail route."
+ );
+ }
+
+ const databaseNameList = (query.databaseList ?? "").split(",");
+ const targets = query.databaseGroupName
+ ? [query.databaseGroupName]
+ : databaseNameList;
+ const initialSQL = await extractInitialSQLFromQuery(query);
+ const plan = create(PlanSchema, {
+ description: query.description,
+ name: `${project.name}/plans/${getNextLocalSheetUID()}`,
+ title: query.name,
+ });
+
+ if (initialSQL.sqlMap && Object.keys(initialSQL.sqlMap).length > 0) {
+ for (const target of targets) {
+ const spec = buildSpecForTargets([target], project);
+ maybeSetInitialSQLForSpec(spec, initialSQL);
+ plan.specs.push(spec);
+ }
+ } else {
+ const spec = buildSpecForTargets(targets, project);
+ maybeSetInitialSQLForSpec(spec, initialSQL);
+ plan.specs = [spec];
+ }
+
+ return plan;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts
new file mode 100644
index 0000000000..5c72da7ce7
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/directiveUtils.ts
@@ -0,0 +1,252 @@
+/**
+ * Utilities for managing SQL directives and special statements in the editor.
+ *
+ * Directives are special comments that must appear at specific positions:
+ * - Transaction mode directive: Must be on line 1
+ * - Isolation level directive: Must be on line 2 (if txn-mode is on line 1)
+ *
+ * Special statements are SQL statements that get special handling:
+ * - SET ROLE statement: Can appear anywhere but is handled specially by backend
+ */
+
+// Transaction mode directive pattern
+const TXN_MODE_REGEX = /^\s*--\s*txn-mode\s*=\s*(on|off)\s*$/i;
+
+// Isolation level directive pattern
+const TXN_ISOLATION_REGEX =
+ /^\s*--\s*txn-isolation\s*=\s*(READ\s+UNCOMMITTED|READ\s+COMMITTED|REPEATABLE\s+READ|SERIALIZABLE)\s*$/i;
+
+// PostgreSQL role setter pattern
+// Matches PostgreSQL identifier rules: starts with letter/underscore, up to 63 chars
+const ROLE_SETTER_REGEX =
+ /\/\*\s*=== Bytebase Role Setter\. DO NOT EDIT\. === \*\/\s*SET ROLE ([a-zA-Z_][a-zA-Z0-9_]{0,62});/;
+
+// Ghost configuration directive pattern
+// Matches: -- gh-ost = {"key":"value",...} or -- gh-ost = {} /*comment*/
+const GHOST_DIRECTIVE_REGEX =
+ /^\s*--\s*gh-ost\s*=\s*(\{[^}]*\})\s*(?:\/\*.*\*\/)?\s*$/i;
+
+export type IsolationLevel =
+ | "READ_UNCOMMITTED"
+ | "READ_COMMITTED"
+ | "REPEATABLE_READ"
+ | "SERIALIZABLE";
+
+export interface ParsedStatement {
+ // Line 1 directive (currently only transaction mode)
+ transactionMode?: "on" | "off";
+ // Line 2 directive (isolation level, only valid when txn-mode is on)
+ isolationLevel?: IsolationLevel;
+ // Ghost configuration (JSON object with gh-ost flags)
+ ghostConfig?: Record<string, string>;
+ // Role setter block if present
+ roleSetterBlock?: string;
+ // The main SQL content (everything except directives and role setter)
+ mainContent: string;
+}
+
+/**
+ * Parses a SQL statement into its components.
+ */
+export function parseStatement(statement: string): ParsedStatement {
+ const lines = statement.split("\n");
+ const result: ParsedStatement = {
+ mainContent: "",
+ };
+
+ const directiveLines = new Set<number>();
+
+ // Scan lines from the top, stopping at first non-comment/non-empty line
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const trimmed = line.trim();
+
+ // Skip empty lines
+ if (trimmed === "") {
+ continue;
+ }
+
+ // If it's not a comment, stop scanning for directives
+ if (!trimmed.startsWith("--")) {
+ break;
+ }
+
+ // Check for transaction mode directive
+ const txnModeMatch = line.match(TXN_MODE_REGEX);
+ if (txnModeMatch) {
+ result.transactionMode = txnModeMatch[1].toLowerCase() as "on" | "off";
+ directiveLines.add(i);
+ continue;
+ }
+
+ // Check for isolation level directive
+ const isolationMatch = line.match(TXN_ISOLATION_REGEX);
+ if (isolationMatch) {
+ // Normalize the isolation level string
+ const isolation = isolationMatch[1].toUpperCase().replace(/\s+/g, "_");
+ result.isolationLevel = isolation as IsolationLevel;
+ directiveLines.add(i);
+ continue;
+ }
+
+ // Check for ghost directive
+ const ghostMatch = line.match(GHOST_DIRECTIVE_REGEX);
+ if (ghostMatch) {
+ try {
+ result.ghostConfig = JSON.parse(ghostMatch[1]);
+ } catch {
+ // Invalid JSON, treat as regular comment
+ }
+ directiveLines.add(i);
+ continue;
+ }
+ }
+
+ // Build remaining content without directive lines
+ const remainingLines = lines.filter((_, i) => !directiveLines.has(i));
+ const remainingContent = remainingLines.join("\n");
+
+ // Check for role setter block (can be anywhere in the remaining content)
+ const roleSetterMatch = remainingContent.match(ROLE_SETTER_REGEX);
+
+ if (roleSetterMatch) {
+ result.roleSetterBlock = roleSetterMatch[0];
+ // Remove the role setter block from the content
+ result.mainContent = remainingContent.replace(ROLE_SETTER_REGEX, "").trim();
+ } else {
+ result.mainContent = remainingContent.trim();
+ }
+
+ return result;
+}
+
+/**
+ * Rebuilds a SQL statement from its components, ensuring proper ordering.
+ * Directives are placed at the top, followed by role setter, then main content.
+ */
+export function buildStatement(components: ParsedStatement): string {
+ const parts: string[] = [];
+
+ // Add directives at the top (they can be in any order)
+ // Transaction mode directive (if present)
+ if (components.transactionMode !== undefined) {
+ parts.push(`-- txn-mode = ${components.transactionMode}`);
+ }
+
+ // Isolation level directive (if present and txn-mode is not explicitly off)
+ if (
+ components.isolationLevel !== undefined &&
+ components.transactionMode !== "off"
+ ) {
+ // Convert back from underscore to space format
+ const isolation = components.isolationLevel.replace(/_/g, " ");
+ parts.push(`-- txn-isolation = ${isolation}`);
+ }
+
+ // Ghost directive
+ if (components.ghostConfig !== undefined) {
+ if (Object.keys(components.ghostConfig).length === 0) {
+ parts.push(`-- gh-ost = {} /* using default config */`);
+ } else {
+ parts.push(
+ `-- gh-ost = ${JSON.stringify(
+ components.ghostConfig
+ )} /* merges with default config */`
+ );
+ }
+ }
+
+ // Role setter block (if present) - place it before main content
+ if (components.roleSetterBlock) {
+ parts.push(components.roleSetterBlock);
+ }
+
+ // Main SQL content
+ if (components.mainContent) {
+ parts.push(components.mainContent);
+ }
+
+ return parts.filter((part) => part.length > 0).join("\n");
+}
+
+/**
+ * Updates the transaction mode in a statement while preserving other components.
+ */
+export function updateTransactionMode(
+ statement: string,
+ mode: "on" | "off"
+): string {
+ const parsed = parseStatement(statement);
+ parsed.transactionMode = mode;
+ return buildStatement(parsed);
+}
+
+/**
+ * Updates the isolation level in a statement while preserving other components.
+ */
+export function updateIsolationLevel(
+ statement: string,
+ isolationLevel: IsolationLevel | undefined
+): string {
+ const parsed = parseStatement(statement);
+ parsed.isolationLevel = isolationLevel;
+ return buildStatement(parsed);
+}
+
+/**
+ * Updates the role setter in a statement while preserving other components.
+ */
+export function updateRoleSetter(
+ statement: string,
+ roleName: string | undefined
+): string {
+ const parsed = parseStatement(statement);
+
+ if (roleName) {
+ parsed.roleSetterBlock = `/* === Bytebase Role Setter. DO NOT EDIT. === */\nSET ROLE ${roleName};`;
+ } else {
+ parsed.roleSetterBlock = undefined;
+ }
+
+ return buildStatement(parsed);
+}
+
+/**
+ * Updates the ghost configuration in a statement while preserving other components.
+ * Pass undefined to remove ghost config, or an empty object {} to enable ghost with no flags.
+ */
+export function updateGhostConfig(
+ statement: string,
+ config: Record<string, string> | undefined
+): string {
+ const parsed = parseStatement(statement);
+ parsed.ghostConfig = config;
+ return buildStatement(parsed);
+}
+
+/**
+ * Gets the ghost configuration from a statement.
+ * Returns undefined if no ghost directive is present.
+ */
+export function getGhostConfig(
+ statement: string
+): Record<string, string> | undefined {
+ const parsed = parseStatement(statement);
+ return parsed.ghostConfig;
+}
+
+/**
+ * Checks if ghost is enabled for a statement (directive is present).
+ */
+export function isGhostEnabled(statement: string): boolean {
+ const parsed = parseStatement(statement);
+ return parsed.ghostConfig !== undefined;
+}
+
+/**
+ * Returns the default ghost configuration.
+ * Empty object {} means "use default config" - will be rendered as -- gh-ost = {} /*default config*\/
+ */
+export function getDefaultGhostConfig(): Record<string, string> {
+ return {};
+}
diff --git a/frontend/src/react/pages/project/plan-detail/utils/header.test.ts b/frontend/src/react/pages/project/plan-detail/utils/header.test.ts
new file mode 100644
index 0000000000..5ac9f881b6
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/header.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, test } from "vitest";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import {
+ getCreateIssueBlockingErrors,
+ getCreateIssueConfirmErrors,
+ hasChecksWarning,
+ shouldStayOnPlanDetailPage,
+} from "./header";
+
+const t = (key: string) => key;
+
+const makePlan = (cases: string[], statusCount = {}): Plan =>
+ ({
+ planCheckRunStatusCount: statusCount,
+ specs: cases.map((caseName) => ({
+ config: { case: caseName, value: {} },
+ })),
+ }) as unknown as Plan;
+
+describe("plan detail header create issue helpers", () => {
+ test("keeps database change plans on plan detail after issue creation", () => {
+ expect(shouldStayOnPlanDetailPage(makePlan(["changeDatabaseConfig"]))).toBe(
+ true
+ );
+ expect(shouldStayOnPlanDetailPage(makePlan(["exportDataConfig"]))).toBe(
+ false
+ );
+ expect(shouldStayOnPlanDetailPage(makePlan(["createDatabaseConfig"]))).toBe(
+ false
+ );
+ });
+
+ test("requires acknowledgement for non-blocking check warnings", () => {
+ const plan = makePlan(["changeDatabaseConfig"], { ERROR: 1 });
+ const project = {
+ enforceSqlReview: false,
+ forceIssueLabels: false,
+ } as Project;
+ const blockingErrors = getCreateIssueBlockingErrors({
+ emptySpecCount: 0,
+ plan,
+ project,
+ t,
+ });
+
+ expect(blockingErrors).toEqual([]);
+ expect(hasChecksWarning(plan)).toBe(true);
+ expect(
+ getCreateIssueConfirmErrors({
+ blockingErrors,
+ checksWarningAcknowledged: false,
+ project,
+ selectedLabelCount: 0,
+ showChecksWarning: true,
+ t,
+ })
+ ).toContain("issue.checks-warning-hint");
+ expect(
+ getCreateIssueConfirmErrors({
+ blockingErrors,
+ checksWarningAcknowledged: true,
+ project,
+ selectedLabelCount: 0,
+ showChecksWarning: true,
+ t,
+ })
+ ).toEqual([]);
+ });
+
+ test("keeps SQL review enforcement as a blocking error", () => {
+ const plan = makePlan(["changeDatabaseConfig"], { ERROR: 1 });
+ const project = {
+ enforceSqlReview: true,
+ forceIssueLabels: false,
+ } as Project;
+
+ expect(
+ getCreateIssueBlockingErrors({
+ emptySpecCount: 0,
+ plan,
+ project,
+ t,
+ })
+ ).toContain(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"
+ );
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/header.ts b/frontend/src/react/pages/project/plan-detail/utils/header.ts
new file mode 100644
index 0000000000..7c15d88b6b
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/header.ts
@@ -0,0 +1,92 @@
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+
+type T = (key: string, options?: Record<string, unknown>) => string;
+
+export const shouldStayOnPlanDetailPage = (plan: Plan): boolean => {
+ if (plan.specs.length === 0) {
+ return true;
+ }
+
+ return !plan.specs.every(
+ (spec) =>
+ spec.config?.case === "createDatabaseConfig" ||
+ spec.config?.case === "exportDataConfig"
+ );
+};
+
+export const hasChecksWarning = (plan: Plan): boolean => {
+ const statusCount = plan.planCheckRunStatusCount || {};
+ const hasError =
+ (statusCount.ERROR ?? 0) > 0 || (statusCount.FAILED ?? 0) > 0;
+ return (
+ hasError &&
+ plan.specs.length > 0 &&
+ plan.specs.every((spec) => spec.config?.case === "changeDatabaseConfig")
+ );
+};
+
+export const getCreateIssueBlockingErrors = ({
+ emptySpecCount,
+ plan,
+ project,
+ t,
+}: {
+ emptySpecCount: number;
+ plan: Plan;
+ project: Pick<Project, "enforceSqlReview">;
+ t: T;
+}): string[] => {
+ const errors: string[] = [];
+ const statusCount = plan.planCheckRunStatusCount || {};
+
+ if (emptySpecCount > 0) {
+ errors.push(t("plan.navigator.statement-empty"));
+ }
+ if ((statusCount.RUNNING ?? 0) > 0) {
+ errors.push(
+ t(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"
+ )
+ );
+ }
+ if (
+ ((statusCount.ERROR ?? 0) > 0 || (statusCount.FAILED ?? 0) > 0) &&
+ project.enforceSqlReview
+ ) {
+ errors.push(
+ t(
+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"
+ )
+ );
+ }
+
+ return errors;
+};
+
+export const getCreateIssueConfirmErrors = ({
+ checksWarningAcknowledged,
+ blockingErrors,
+ project,
+ selectedLabelCount,
+ showChecksWarning,
+ t,
+}: {
+ blockingErrors: string[];
+ checksWarningAcknowledged: boolean;
+ project: Pick<Project, "forceIssueLabels">;
+ selectedLabelCount: number;
+ showChecksWarning: boolean;
+ t: T;
+}): string[] => {
+ const errors = [...blockingErrors];
+
+ if (project.forceIssueLabels && selectedLabelCount === 0) {
+ errors.push(t("plan.labels-required-for-review"));
+ }
+ if (showChecksWarning && !checksWarningAcknowledged) {
+ errors.push(t("issue.checks-warning-hint"));
+ }
+
+ return errors;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts
new file mode 100644
index 0000000000..09e9aab6bd
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/localSheet.ts
@@ -0,0 +1,30 @@
+import { create } from "@bufbuild/protobuf";
+import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
+import { SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
+
+const state = {
+ uid: -101,
+};
+
+const localSheetsByName = new Map<string, Sheet>();
+
+export const createEmptyLocalSheet = () => {
+ return create(SheetSchema, {});
+};
+
+export const getNextLocalSheetUID = () => {
+ return String(state.uid--);
+};
+
+export const getLocalSheetByName = (name: string): Sheet => {
+ const existing = localSheetsByName.get(name);
+ if (existing) {
+ return existing;
+ }
+ const sheet = create(SheetSchema, {
+ ...createEmptyLocalSheet(),
+ name,
+ });
+ localSheetsByName.set(name, sheet);
+ return sheet;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/options.test.ts b/frontend/src/react/pages/project/plan-detail/utils/options.test.ts
new file mode 100644
index 0000000000..5595cfc4f4
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/options.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, test } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { getPlanOptionVisibility } from "./options";
+
+const databaseWithEngine = (engine: Engine, engineVersion = "") =>
+ ({
+ instanceResource: {
+ engine,
+ engineVersion,
+ },
+ }) as Database;
+
+describe("getPlanOptionVisibility", () => {
+ test("shows MySQL sheet-backed change options", () => {
+ expect(
+ getPlanOptionVisibility({
+ databases: [databaseWithEngine(Engine.MYSQL, "8.0.0")],
+ isChangeDatabaseConfig: true,
+ isSheetBasedDatabaseChange: true,
+ })
+ ).toMatchObject({
+ shouldShow: true,
+ showGhost: true,
+ showIsolationLevel: true,
+ showPreBackup: true,
+ showTransactionMode: true,
+ });
+ });
+
+ test("hides sheet-only options for release-backed specs", () => {
+ expect(
+ getPlanOptionVisibility({
+ databases: [databaseWithEngine(Engine.POSTGRES, "15.0")],
+ isChangeDatabaseConfig: true,
+ isSheetBasedDatabaseChange: false,
+ })
+ ).toMatchObject({
+ shouldShow: true,
+ showGhost: false,
+ showInstanceRole: false,
+ showPreBackup: true,
+ showTransactionMode: false,
+ });
+ });
+
+ test("hides all options until target databases are loaded", () => {
+ expect(
+ getPlanOptionVisibility({
+ databases: [],
+ isChangeDatabaseConfig: true,
+ isSheetBasedDatabaseChange: true,
+ })
+ ).toMatchObject({
+ shouldShow: false,
+ showGhost: false,
+ showInstanceRole: false,
+ showIsolationLevel: false,
+ showPreBackup: false,
+ showTransactionMode: false,
+ });
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/options.ts b/frontend/src/react/pages/project/plan-detail/utils/options.ts
new file mode 100644
index 0000000000..7a9e77f159
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/options.ts
@@ -0,0 +1,91 @@
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+
+const BACKUP_AVAILABLE_ENGINES = [
+ Engine.MYSQL,
+ Engine.TIDB,
+ Engine.MSSQL,
+ Engine.ORACLE,
+ Engine.POSTGRES,
+];
+
+export const getPlanOptionVisibility = ({
+ databases,
+ isSheetBasedDatabaseChange,
+ isChangeDatabaseConfig,
+}: {
+ databases: Database[];
+ isChangeDatabaseConfig: boolean;
+ isSheetBasedDatabaseChange: boolean;
+}) => {
+ const hasDatabases = databases.length > 0;
+ const showTransactionMode =
+ hasDatabases &&
+ isSheetBasedDatabaseChange &&
+ databases.every((database) =>
+ instanceSupportsTransactionMode(database.instanceResource?.engine)
+ );
+ const showInstanceRole =
+ hasDatabases &&
+ isSheetBasedDatabaseChange &&
+ databases.every(
+ (database) => database.instanceResource?.engine === Engine.POSTGRES
+ );
+ const showIsolationLevel =
+ hasDatabases &&
+ isSheetBasedDatabaseChange &&
+ databases.every((database) =>
+ [Engine.MYSQL, Engine.MARIADB, Engine.TIDB].includes(
+ database.instanceResource?.engine ?? Engine.ENGINE_UNSPECIFIED
+ )
+ );
+ const showPreBackup =
+ hasDatabases &&
+ isChangeDatabaseConfig &&
+ databases.every((database) =>
+ BACKUP_AVAILABLE_ENGINES.includes(
+ database.instanceResource?.engine ?? Engine.ENGINE_UNSPECIFIED
+ )
+ );
+ const showGhost =
+ hasDatabases &&
+ isSheetBasedDatabaseChange &&
+ databases.every((database) =>
+ allowGhostForDatabase(
+ database.instanceResource?.engine ?? Engine.ENGINE_UNSPECIFIED,
+ database.instanceResource?.engineVersion ?? ""
+ )
+ );
+
+ return {
+ showGhost,
+ showInstanceRole,
+ showIsolationLevel,
+ showPreBackup,
+ showTransactionMode,
+ shouldShow:
+ showTransactionMode ||
+ showInstanceRole ||
+ showIsolationLevel ||
+ showPreBackup ||
+ showGhost,
+ };
+};
+
+export function allowGhostForDatabase(engine: Engine, engineVersion: string) {
+ if (engine === Engine.MYSQL) return engineVersion >= "5.6.0";
+ if (engine === Engine.MARIADB) return engineVersion >= "10.6.0";
+ return false;
+}
+
+const instanceSupportsTransactionMode = (engine?: Engine): boolean => {
+ if (engine === undefined) return false;
+ return ![
+ Engine.MONGODB,
+ Engine.REDIS,
+ Engine.DYNAMODB,
+ Engine.COSMOSDB,
+ Engine.CASSANDRA,
+ Engine.ELASTICSEARCH,
+ ].includes(engine);
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.test.ts b/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.test.ts
new file mode 100644
index 0000000000..948bafb01f
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, test } from "vitest";
+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 {
+ buildChangesSummary,
+ buildDeploySummary,
+ buildReviewSummary,
+} from "./phaseSummary";
+
+const templates: Record<string, string> = {
+ "common.and": "and",
+ "plan.summary.last-approved-by": "Last approved by {{name}}",
+ "plan.summary.n-changes": "{{n}} changes",
+ "plan.summary.n-database-groups": "{{n}} database groups",
+ "plan.summary.n-databases": "{{n}} databases",
+ "plan.summary.n-error": "{{n}} error",
+ "plan.summary.n-of-m-approved": "{{n}} of {{m}} approved",
+ "plan.summary.n-of-m-tasks": "{{n}}/{{m}} tasks",
+ "plan.summary.n-passed": "{{n}} passed",
+ "plan.summary.n-warning": "{{n}} warning",
+};
+
+const t = (key: string, options?: Record<string, unknown>) => {
+ const template = templates[key] ?? key;
+ return Object.entries(options ?? {}).reduce(
+ (text, [name, value]) => text.replaceAll(`{{${name}}}`, String(value)),
+ template
+ );
+};
+
+describe("plan detail phase summaries", () => {
+ test("summarizes changes with targets and check counts", () => {
+ const plan = {
+ planCheckRunStatusCount: {
+ ERROR: 1,
+ FAILED: 1,
+ SUCCESS: 2,
+ WARNING: 1,
+ },
+ specs: [
+ {
+ config: {
+ case: "changeDatabaseConfig",
+ value: {
+ targets: [
+ "projects/p1/instances/i1/databases/db1",
+ "projects/p1/databaseGroups/group1",
+ ],
+ },
+ },
+ },
+ {
+ config: {
+ case: "changeDatabaseConfig",
+ value: {
+ targets: ["projects/p1/instances/i2/databases/db2"],
+ },
+ },
+ },
+ ],
+ } as unknown as Plan;
+
+ expect(buildChangesSummary(plan, t)).toBe(
+ "2 changes · 2 databases and 1 database groups · 2 passed, 1 warning, 2 error"
+ );
+ });
+
+ test("summarizes review approval progress and last approver", () => {
+ const issue = {
+ approvalTemplate: {
+ flow: {
+ roles: ["roles/PROJECT_OWNER", "roles/PROJECT_DBA"],
+ },
+ },
+ approvers: [{ principal: "users/[email protected]" }],
+ } as unknown as Issue;
+
+ expect(buildReviewSummary(issue, t)).toBe(
+ "1 of 2 approved · Last approved by alice"
+ );
+ });
+
+ test("summarizes deploy task progress", () => {
+ const rollout = {
+ stages: [
+ {
+ tasks: [
+ { status: Task_Status.DONE },
+ { status: Task_Status.SKIPPED },
+ { status: Task_Status.NOT_STARTED },
+ ],
+ },
+ ],
+ } as unknown as Rollout;
+
+ expect(buildDeploySummary(rollout, t)).toBe("2/3 tasks");
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.ts b/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.ts
new file mode 100644
index 0000000000..cbfb241593
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/phaseSummary.ts
@@ -0,0 +1,136 @@
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { PlanCheckRun_Status } 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 { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+
+type T = (key: string, options?: Record<string, unknown>) => string;
+
+const isDatabaseGroupName = (name: string): boolean =>
+ name.includes("/databaseGroups/");
+
+export interface PlanCheckSummary {
+ error: number;
+ running: number;
+ success: number;
+ total: number;
+ warning: number;
+}
+
+export const getPlanCheckSummary = (plan: Plan): PlanCheckSummary => {
+ const statusCount = 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;
+ const failed =
+ statusCount[PlanCheckRun_Status[PlanCheckRun_Status.FAILED]] || 0;
+ const totalError = error + failed;
+
+ return {
+ error: totalError,
+ running,
+ success,
+ total: running + success + warning + totalError,
+ warning,
+ };
+};
+
+const targetsForSpec = (spec: Plan["specs"][number]): string[] => {
+ if (spec.config?.case === "changeDatabaseConfig") {
+ return spec.config.value.targets || [];
+ }
+ if (spec.config?.case === "exportDataConfig") {
+ return spec.config.value.targets || [];
+ }
+ return [];
+};
+
+const extractPrincipalEmail = (principal: string): string =>
+ principal.replace(/^users\//, "");
+
+export const buildChangesSummary = (plan: Plan, t: T): string => {
+ const parts: string[] = [];
+
+ parts.push(t("plan.summary.n-changes", { n: plan.specs.length }));
+
+ const targets = Array.from(new Set(plan.specs.flatMap(targetsForSpec)));
+ if (targets.length > 0) {
+ const dbGroupCount = targets.filter(isDatabaseGroupName).length;
+ const dbCount = targets.length - dbGroupCount;
+ const targetParts: string[] = [];
+ if (dbCount > 0) {
+ targetParts.push(t("plan.summary.n-databases", { n: dbCount }));
+ }
+ if (dbGroupCount > 0) {
+ targetParts.push(
+ t("plan.summary.n-database-groups", { n: dbGroupCount })
+ );
+ }
+ parts.push(targetParts.join(` ${t("common.and")} `));
+ }
+
+ const checks = getPlanCheckSummary(plan);
+ if (checks.total > 0) {
+ const checkParts: string[] = [];
+ if (checks.success > 0) {
+ checkParts.push(t("plan.summary.n-passed", { n: checks.success }));
+ }
+ if (checks.warning > 0) {
+ checkParts.push(t("plan.summary.n-warning", { n: checks.warning }));
+ }
+ if (checks.error > 0) {
+ checkParts.push(t("plan.summary.n-error", { n: checks.error }));
+ }
+ if (checkParts.length > 0) {
+ parts.push(checkParts.join(", "));
+ }
+ }
+
+ return parts.join(" · ");
+};
+
+export const buildReviewSummary = (issue: Issue | undefined, t: T): string => {
+ if (!issue) return "";
+
+ const roles = issue.approvalTemplate?.flow?.roles ?? [];
+ const approvers = issue.approvers;
+ const parts: string[] = [];
+
+ if (roles.length > 0) {
+ parts.push(
+ t("plan.summary.n-of-m-approved", {
+ m: roles.length,
+ n: approvers.length,
+ })
+ );
+ }
+
+ if (approvers.length > 0) {
+ const last = approvers[approvers.length - 1];
+ const name = extractPrincipalEmail(last.principal).split("@")[0];
+ parts.push(t("plan.summary.last-approved-by", { name }));
+ }
+
+ return parts.join(" · ");
+};
+
+export const buildDeploySummary = (
+ rollout: Rollout | undefined,
+ t: T
+): string => {
+ if (!rollout) return "";
+
+ const allTasks = rollout.stages.flatMap((stage) => stage.tasks);
+ const completed = allTasks.filter(
+ (task) =>
+ task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
+ ).length;
+
+ return t("plan.summary.n-of-m-tasks", {
+ m: allTasks.length,
+ n: completed,
+ });
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/planCheck.test.ts b/frontend/src/react/pages/project/plan-detail/utils/planCheck.test.ts
new file mode 100644
index 0000000000..0a5e492741
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/planCheck.test.ts
@@ -0,0 +1,76 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+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 { getFilteredResultGroups, getPlanCheckSummary } from "./planCheck";
+
+describe("plan check helpers", () => {
+ test("summarizes run-level and result-level statuses", () => {
+ const summary = getPlanCheckSummary([
+ create(PlanCheckRunSchema, {
+ status: PlanCheckRun_Status.RUNNING,
+ }),
+ create(PlanCheckRunSchema, {
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.ERROR,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.WARNING,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.SUCCESS,
+ }),
+ ],
+ status: PlanCheckRun_Status.FAILED,
+ }),
+ ]);
+
+ expect(summary).toEqual({
+ error: 2,
+ running: 1,
+ success: 1,
+ total: 5,
+ warning: 1,
+ });
+ });
+
+ test("groups filtered results by type and target", () => {
+ const groups = getFilteredResultGroups({
+ planCheckRuns: [
+ create(PlanCheckRunSchema, {
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.ERROR,
+ target: "databases/db1",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.WARNING,
+ target: "databases/db1",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ status: Advice_Level.ERROR,
+ target: "databases/db2",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ ],
+ }),
+ ],
+ selectedStatus: Advice_Level.ERROR,
+ });
+
+ expect(groups).toHaveLength(2);
+ expect(groups.map((group) => group.target)).toEqual([
+ "databases/db1",
+ "databases/db2",
+ ]);
+ expect(groups[0]?.results).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts b/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts
new file mode 100644
index 0000000000..1153f11852
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/planCheck.ts
@@ -0,0 +1,199 @@
+import { create } from "@bufbuild/protobuf";
+import type { Timestamp as TimestampPb } from "@bufbuild/protobuf/wkt";
+import {
+ type Plan_Spec,
+ type PlanCheckRun,
+ type PlanCheckRun_Result,
+ PlanCheckRun_Result_Type,
+ PlanCheckRun_ResultSchema,
+ PlanCheckRun_Status,
+ PlanCheckRunSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import type { CheckReleaseResponse_CheckResult } from "@/types/proto-es/v1/release_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+
+export interface PlanCheckSummary {
+ error: number;
+ running: number;
+ success: number;
+ total: number;
+ warning: number;
+}
+
+export interface ResultGroup {
+ key: string;
+ type: PlanCheckRun_Result_Type;
+ target: string;
+ createTime?: TimestampPb;
+ results: PlanCheckRun_Result[];
+}
+
+export const getPlanCheckSummary = (
+ planCheckRuns: PlanCheckRun[]
+): PlanCheckSummary => {
+ let running = 0;
+ let success = 0;
+ let warning = 0;
+ let error = 0;
+
+ for (const checkRun of planCheckRuns) {
+ 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,
+ };
+};
+
+const targetsForSpec = (spec: Plan_Spec): string[] => {
+ if (spec.config.case === "changeDatabaseConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ if (spec.config.case === "exportDataConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ return [];
+};
+
+export const planCheckRunListForSpec = (
+ planCheckRuns: PlanCheckRun[],
+ spec: Plan_Spec
+): PlanCheckRun[] => {
+ const targetSet = new Set(targetsForSpec(spec));
+ if (targetSet.size === 0) {
+ return [];
+ }
+ return planCheckRuns.flatMap((run) => {
+ const matchingResults = run.results.filter((result) =>
+ targetSet.has(result.target)
+ );
+ if (matchingResults.length > 0) {
+ return [{ ...run, results: matchingResults }];
+ }
+ if (
+ (run.status === PlanCheckRun_Status.RUNNING ||
+ run.status === PlanCheckRun_Status.FAILED) &&
+ run.results.length === 0
+ ) {
+ return [{ ...run, results: [] }];
+ }
+ return [];
+ });
+};
+
+export const getFilteredResultGroups = ({
+ includeRunFailure = false,
+ planCheckRuns,
+ runFailureContent,
+ runFailureTitle,
+ selectedStatus,
+}: {
+ includeRunFailure?: boolean;
+ planCheckRuns: PlanCheckRun[];
+ runFailureContent?: string;
+ runFailureTitle?: string;
+ selectedStatus?: Advice_Level;
+}): ResultGroup[] => {
+ const groups: ResultGroup[] = [];
+ const groupMap = new Map<string, ResultGroup>();
+
+ for (const checkRun of planCheckRuns) {
+ if (
+ includeRunFailure &&
+ 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 || runFailureContent,
+ status: Advice_Level.ERROR,
+ title: runFailureTitle,
+ }),
+ ],
+ 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}`;
+ let group = groupMap.get(key);
+ if (!group) {
+ group = {
+ createTime: checkRun.createTime,
+ key,
+ results: [],
+ target: result.target,
+ type: result.type,
+ };
+ groupMap.set(key, group);
+ groups.push(group);
+ }
+ group.results.push(result);
+ }
+ }
+
+ return groups;
+};
+
+export const transformReleaseCheckResultsToPlanCheckRuns = (
+ results: CheckReleaseResponse_CheckResult[]
+): PlanCheckRun[] => {
+ const allResults: PlanCheckRun_Result[] = [];
+
+ for (const result of results) {
+ for (const advice of result.advices) {
+ allResults.push(
+ create(PlanCheckRun_ResultSchema, {
+ code: advice.code,
+ content: advice.content,
+ report: {
+ case: "sqlReviewReport",
+ value: {
+ startPosition: advice.startPosition,
+ },
+ },
+ status:
+ advice.status === Advice_Level.ERROR
+ ? Advice_Level.ERROR
+ : advice.status === Advice_Level.WARNING
+ ? Advice_Level.WARNING
+ : Advice_Level.SUCCESS,
+ target: result.target,
+ title: advice.title,
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ })
+ );
+ }
+ }
+
+ if (allResults.length === 0) {
+ return [];
+ }
+
+ return [
+ create(PlanCheckRunSchema, {
+ createTime: { nanos: 0, seconds: BigInt(Math.floor(Date.now() / 1000)) },
+ name: "check-run-0",
+ results: allResults,
+ status: PlanCheckRun_Status.DONE,
+ }),
+ ];
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts b/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
new file mode 100644
index 0000000000..96b0fe0da8
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/rolloutPreview.ts
@@ -0,0 +1,248 @@
+import { create } from "@bufbuild/protobuf";
+import {
+ useDatabaseV1Store,
+ useDBGroupStore,
+ useEnvironmentV1Store,
+} from "@/store";
+import { isValidDatabaseGroupName, isValidDatabaseName } from "@/types";
+import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";
+import type {
+ Plan,
+ Plan_ChangeDatabaseConfig,
+ Plan_Spec,
+} from "@/types/proto-es/v1/plan_service_pb";
+import type {
+ Rollout,
+ Stage,
+ Task,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import {
+ RolloutSchema,
+ StageSchema,
+ Task_DatabaseUpdateSchema,
+ Task_Status,
+ Task_Type,
+ TaskSchema,
+} from "@/types/proto-es/v1/rollout_service_pb";
+
+interface TaskCreate {
+ databaseName: string;
+ specId: string;
+ type: Task_Type;
+ sheet: string;
+}
+
+const targetsForSpec = (spec: Plan_Spec): string[] => {
+ if (spec.config.case === "changeDatabaseConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ if (spec.config.case === "exportDataConfig") {
+ return spec.config.value.targets ?? [];
+ }
+ return [];
+};
+
+/**
+ * Generates a rollout preview from a plan without calling the backend.
+ * This replicates the backend's GetPipelineCreate and convertToRollout logic.
+ * Only handles ChangeDatabaseConfig specs.
+ */
+export async function generateRolloutPreview(
+ plan: Plan,
+ projectName: string
+): Promise<Rollout> {
+ // Step 1: Extract all database targets from specs and expand database groups
+ const allDatabaseNames = await extractAndExpandDatabaseTargets(plan.specs);
+ const dbStore = useDatabaseV1Store();
+
+ // Step 2: Fetch databases that are not cached
+ await dbStore.batchGetOrFetchDatabases(allDatabaseNames);
+
+ // Step 3: Generate tasks from specs
+ const tasks = await generateTasksFromSpecs(plan.specs);
+
+ // Step 4: Get environment order from store
+ const environmentOrder = getEnvironmentOrder();
+
+ // Step 5: Group tasks by environment and create stages
+ const stages = groupTasksIntoStages(tasks, environmentOrder, projectName);
+
+ // Step 6: Build and return the rollout
+ return create(RolloutSchema, {
+ name: "", // Preview rollout has no name
+ title: plan.title,
+ stages,
+ });
+}
+
+async function extractAndExpandDatabaseTargets(
+ specs: Plan_Spec[]
+): Promise<string[]> {
+ const databaseNames: string[] = [];
+
+ for (const spec of specs) {
+ if (spec.config.case !== "changeDatabaseConfig") continue;
+
+ const targets = targetsForSpec(spec);
+
+ for (const target of targets) {
+ if (isValidDatabaseName(target)) {
+ databaseNames.push(target);
+ } else if (isValidDatabaseGroupName(target)) {
+ const expandedDbs = await expandDatabaseGroup(target);
+ databaseNames.push(...expandedDbs);
+ }
+ }
+ }
+
+ return [...new Set(databaseNames)];
+}
+
+async function expandDatabaseGroup(
+ databaseGroupName: string
+): Promise<string[]> {
+ const dbGroupStore = useDBGroupStore();
+ try {
+ const dbGroup = await dbGroupStore.getOrFetchDBGroupByName(
+ databaseGroupName,
+ { view: DatabaseGroupView.FULL, silent: true }
+ );
+ return dbGroup.matchedDatabases?.map((db) => db.name) ?? [];
+ } catch {
+ return [];
+ }
+}
+
+async function generateTasksFromSpecs(
+ specs: Plan_Spec[]
+): Promise<TaskCreate[]> {
+ const tasks: TaskCreate[] = [];
+
+ for (const spec of specs) {
+ if (spec.config.case !== "changeDatabaseConfig") continue;
+
+ const specTasks = await generateChangeDatabaseTasks(
+ spec.id,
+ spec.config.value
+ );
+ tasks.push(...specTasks);
+ }
+
+ return tasks;
+}
+
+async function generateChangeDatabaseTasks(
+ specId: string,
+ config: Plan_ChangeDatabaseConfig
+): Promise<TaskCreate[]> {
+ const tasks: TaskCreate[] = [];
+
+ let targets = config.targets ?? [];
+ if (targets.length === 1 && isValidDatabaseGroupName(targets[0])) {
+ targets = await expandDatabaseGroup(targets[0]);
+ }
+
+ for (const target of targets) {
+ if (!isValidDatabaseName(target)) continue;
+
+ tasks.push({
+ databaseName: target,
+ specId,
+ type: Task_Type.DATABASE_MIGRATE,
+ sheet: config.sheet,
+ });
+ }
+
+ return tasks;
+}
+
+function getEnvironmentOrder(): string[] {
+ const environmentStore = useEnvironmentV1Store();
+ return environmentStore.environmentList.map((env) => env.name);
+}
+
+function groupTasksIntoStages(
+ tasks: TaskCreate[],
+ environmentOrder: string[],
+ projectName: string
+): Stage[] {
+ const databaseStore = useDatabaseV1Store();
+
+ // Group tasks by effectiveEnvironment
+ const tasksByEnv = new Map<string, TaskCreate[]>();
+
+ for (const task of tasks) {
+ const db = databaseStore.getDatabaseByName(task.databaseName);
+ const env = db.effectiveEnvironment ?? "";
+ if (env === "") {
+ continue;
+ }
+
+ let envTasks = tasksByEnv.get(env);
+ if (!envTasks) {
+ envTasks = [];
+ tasksByEnv.set(env, envTasks);
+ }
+ envTasks.push(task);
+ }
+
+ // Build stages in environment order
+ const stages: Stage[] = [];
+
+ // First, add stages for environments in the deployment order
+ for (const env of environmentOrder) {
+ const envTasks = tasksByEnv.get(env);
+ if (envTasks && envTasks.length > 0) {
+ stages.push(createStage(env, envTasks, projectName));
+ tasksByEnv.delete(env);
+ }
+ }
+
+ // Then, add any remaining environments at the beginning (as backend does)
+ for (const [env, envTasks] of tasksByEnv) {
+ if (envTasks.length > 0) {
+ stages.unshift(createStage(env, envTasks, projectName));
+ }
+ }
+
+ return stages;
+}
+
+function createStage(
+ environment: string,
+ tasks: TaskCreate[],
+ projectName: string
+): Stage {
+ const envId = environment.replace("environments/", "") || "-";
+
+ return create(StageSchema, {
+ name: `${projectName}/plans/-/rollout/stages/${envId}`,
+ id: envId,
+ environment: environment || "environments/-",
+ tasks: tasks.map((t, index) => createTask(t, envId, projectName, index)),
+ });
+}
+
+function createTask(
+ taskCreate: TaskCreate,
+ stageId: string,
+ projectName: string,
+ index: number
+): Task {
+ return create(TaskSchema, {
+ name: `${projectName}/plans/-/rollout/stages/${stageId}/tasks/${index}`,
+ specId: taskCreate.specId,
+ status: Task_Status.NOT_STARTED,
+ type: taskCreate.type,
+ target: taskCreate.databaseName,
+ payload: {
+ case: "databaseUpdate",
+ value: create(Task_DatabaseUpdateSchema, {
+ source: {
+ case: "sheet",
+ value: taskCreate.sheet,
+ },
+ }),
+ },
+ });
+}
diff --git a/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.test.ts b/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.test.ts
new file mode 100644
index 0000000000..896d523351
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, test } from "vitest";
+import { State } from "@/types/proto-es/v1/common_pb";
+import {
+ Issue_ApprovalStatus,
+ IssueStatus,
+} from "@/types/proto-es/v1/issue_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 { getPlanDetailSidebarStatusInfo } from "./sidebarStatus";
+
+const labels: Record<string, string> = {
+ "common.approved": "Approved",
+ "common.canceled": "Canceled",
+ "common.deploying": "Deploying",
+ "common.done": "Done",
+ "common.draft": "Draft",
+ "common.failed": "Failed",
+ "common.in-review": "In Review",
+ "common.not-started": "Not started",
+ "common.rejected": "Rejected",
+};
+
+const t = (key: string) => labels[key] ?? key;
+
+const status = ({
+ issue,
+ rollout,
+}: {
+ issue?: {
+ approvalStatus: Issue_ApprovalStatus;
+ status: IssueStatus;
+ };
+ rollout?: Rollout;
+}) =>
+ getPlanDetailSidebarStatusInfo({
+ isCreating: false,
+ issue,
+ planState: State.ACTIVE,
+ rollout,
+ t,
+ });
+
+const rolloutWith = (...statuses: Task_Status[]): Rollout =>
+ ({
+ stages: [
+ {
+ tasks: statuses.map((taskStatus) => ({ status: taskStatus })),
+ },
+ ],
+ }) as unknown as Rollout;
+
+describe("plan detail sidebar status", () => {
+ test("maps review statuses like the Vue sidebar", () => {
+ expect(status({}).label).toBe("Draft");
+ expect(
+ status({
+ issue: {
+ approvalStatus: Issue_ApprovalStatus.REJECTED,
+ status: IssueStatus.OPEN,
+ },
+ })
+ ).toEqual({ dotClass: "bg-warning", label: "Rejected" });
+ expect(
+ status({
+ issue: {
+ approvalStatus: Issue_ApprovalStatus.SKIPPED,
+ status: IssueStatus.OPEN,
+ },
+ })
+ ).toEqual({ dotClass: "bg-success", label: "Approved" });
+ });
+
+ test("maps rollout statuses like the Vue sidebar", () => {
+ expect(status({ rollout: rolloutWith(Task_Status.RUNNING) })).toEqual({
+ dotClass: "bg-accent",
+ label: "Deploying",
+ });
+ expect(status({ rollout: rolloutWith(Task_Status.DONE) })).toEqual({
+ dotClass: "bg-success",
+ label: "Done",
+ });
+ expect(status({ rollout: rolloutWith(Task_Status.FAILED) })).toEqual({
+ dotClass: "bg-error",
+ label: "Failed",
+ });
+ expect(status({ rollout: rolloutWith(Task_Status.CANCELED) })).toEqual({
+ dotClass: "bg-control-placeholder",
+ label: "Canceled",
+ });
+ expect(status({ rollout: rolloutWith(Task_Status.NOT_STARTED) })).toEqual({
+ dotClass: "bg-control-placeholder",
+ label: "Not started",
+ });
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.ts b/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.ts
new file mode 100644
index 0000000000..e6dd1f47c2
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/sidebarStatus.ts
@@ -0,0 +1,135 @@
+import { State } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ Issue_ApprovalStatus,
+ IssueStatus,
+} from "@/types/proto-es/v1/issue_service_pb";
+import type { Rollout } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+
+type T = (key: string, options?: Record<string, unknown>) => string;
+
+const TASK_STATUS_FILTERS: Task_Status[] = [
+ Task_Status.RUNNING,
+ Task_Status.FAILED,
+ Task_Status.PENDING,
+ Task_Status.NOT_STARTED,
+ Task_Status.CANCELED,
+ Task_Status.DONE,
+ Task_Status.SKIPPED,
+];
+
+export interface SidebarStatusInfo {
+ dotClass: string;
+ label: string;
+}
+
+export const getPlanDetailSidebarStatusInfo = ({
+ isCreating,
+ issue,
+ planState,
+ rollout,
+ t,
+}: {
+ isCreating: boolean;
+ issue?: Pick<Issue, "approvalStatus" | "status">;
+ planState: State;
+ rollout?: Rollout;
+ t: T;
+}): SidebarStatusInfo => {
+ if (isCreating) {
+ return { dotClass: "bg-control-placeholder", label: t("common.creating") };
+ }
+ if (planState === State.DELETED) {
+ return { dotClass: "bg-control-placeholder", label: t("common.closed") };
+ }
+ if (issue?.status === IssueStatus.CANCELED) {
+ return { dotClass: "bg-control-placeholder", label: t("common.closed") };
+ }
+ if (rollout) {
+ return getRolloutStatusInfo(rollout, t);
+ }
+ return getReviewStatusInfo(issue, t);
+};
+
+const getReviewStatusInfo = (
+ issue: Pick<Issue, "approvalStatus" | "status"> | undefined,
+ t: T
+): SidebarStatusInfo => {
+ if (!issue) {
+ return { dotClass: "bg-control-placeholder", label: t("common.draft") };
+ }
+ if (issue.status === IssueStatus.DONE) {
+ return { dotClass: "bg-success", label: t("common.approved") };
+ }
+
+ switch (issue.approvalStatus) {
+ case Issue_ApprovalStatus.APPROVED:
+ case Issue_ApprovalStatus.SKIPPED:
+ return { dotClass: "bg-success", label: t("common.approved") };
+ case Issue_ApprovalStatus.REJECTED:
+ return { dotClass: "bg-warning", label: t("common.rejected") };
+ default:
+ return { dotClass: "bg-accent", label: t("common.in-review") };
+ }
+};
+
+const getRolloutStatusInfo = (rollout: Rollout, t: T): SidebarStatusInfo => {
+ const hasCompletedTasks = rollout.stages
+ .flatMap((stage) => stage.tasks)
+ .some(
+ (task) =>
+ task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
+ );
+
+ switch (getRolloutStatus(rollout)) {
+ case Task_Status.DONE:
+ case Task_Status.SKIPPED:
+ return { dotClass: "bg-success", label: t("common.done") };
+ case Task_Status.FAILED:
+ return { dotClass: "bg-error", label: t("common.failed") };
+ case Task_Status.RUNNING:
+ case Task_Status.PENDING:
+ return { dotClass: "bg-accent", label: t("common.deploying") };
+ case Task_Status.CANCELED:
+ return {
+ dotClass: "bg-control-placeholder",
+ label: t("common.canceled"),
+ };
+ case Task_Status.NOT_STARTED:
+ if (hasCompletedTasks) {
+ return { dotClass: "bg-accent", label: t("common.deploying") };
+ }
+ return {
+ dotClass: "bg-control-placeholder",
+ label: t("common.not-started"),
+ };
+ default:
+ return {
+ dotClass: "bg-control-placeholder",
+ label: t("common.not-started"),
+ };
+ }
+};
+
+const getStageStatus = (tasks: Array<{ status: Task_Status }>): Task_Status => {
+ if (tasks.length === 0) return Task_Status.NOT_STARTED;
+ for (const status of TASK_STATUS_FILTERS) {
+ if (tasks.some((task) => task.status === status)) {
+ return status;
+ }
+ }
+ return Task_Status.NOT_STARTED;
+};
+
+const getRolloutStatus = (rollout: Rollout): Task_Status => {
+ if (rollout.stages.length === 0) return Task_Status.NOT_STARTED;
+ for (const status of TASK_STATUS_FILTERS) {
+ if (
+ rollout.stages.some((stage) => getStageStatus(stage.tasks) === status)
+ ) {
+ return status;
+ }
+ }
+ return Task_Status.NOT_STARTED;
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/spec.test.ts b/frontend/src/react/pages/project/plan-detail/utils/spec.test.ts
new file mode 100644
index 0000000000..30346e5aa6
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/spec.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, test } from "vitest";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import { getSelectedSpec } from "./spec";
+
+describe("getSelectedSpec", () => {
+ const specs = [{ id: "a" }, { id: "b" }] as Plan_Spec[];
+
+ test("returns matching spec", () => {
+ expect(getSelectedSpec({ selectedSpecId: "b", specs })?.id).toBe("b");
+ });
+
+ test("falls back to first spec", () => {
+ expect(getSelectedSpec({ selectedSpecId: "missing", specs })?.id).toBe("a");
+ });
+
+ test("returns undefined for empty specs", () => {
+ expect(getSelectedSpec({ selectedSpecId: "missing", specs: [] })).toBe(
+ undefined
+ );
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/spec.ts b/frontend/src/react/pages/project/plan-detail/utils/spec.ts
new file mode 100644
index 0000000000..e8d03d53e6
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/spec.ts
@@ -0,0 +1,25 @@
+import type { TFunction } from "i18next";
+import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+
+export const getSelectedSpec = ({
+ selectedSpecId,
+ specs,
+}: {
+ selectedSpecId: string;
+ specs: Plan_Spec[];
+}): Plan_Spec | undefined => {
+ return specs.find((spec) => spec.id === selectedSpecId) ?? specs[0];
+};
+
+export const getSpecTitle = (spec: Plan_Spec, t: TFunction): string => {
+ if (spec.config.case === "createDatabaseConfig") {
+ return t("common.database");
+ }
+ if (spec.config.case === "changeDatabaseConfig") {
+ return t("plan.spec.type.database-change");
+ }
+ if (spec.config.case === "exportDataConfig") {
+ return t("common.export");
+ }
+ return t("common.unknown");
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/specMutation.ts b/frontend/src/react/pages/project/plan-detail/utils/specMutation.ts
new file mode 100644
index 0000000000..9264354ef6
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/specMutation.ts
@@ -0,0 +1,36 @@
+import { clone, create } from "@bufbuild/protobuf";
+import { planServiceClientConnect, sheetServiceClientConnect } from "@/connect";
+import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";
+import {
+ PlanSchema,
+ UpdatePlanRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { extractProjectResourceName, setSheetStatement } from "@/utils";
+import { createEmptyLocalSheet } from "./localSheet";
+
+export const updateSpecSheetWithStatement = async (
+ plan: Plan,
+ spec: Plan_Spec,
+ statement: string
+) => {
+ const planPatch = clone(PlanSchema, plan);
+ const specToPatch = planPatch.specs.find((item) => item.id === spec.id);
+ if (!specToPatch || specToPatch.config.case !== "changeDatabaseConfig") {
+ return;
+ }
+
+ const sheet = createEmptyLocalSheet();
+ setSheetStatement(sheet, statement);
+ const createdSheet = await sheetServiceClientConnect.createSheet({
+ parent: `projects/${extractProjectResourceName(plan.name)}`,
+ sheet,
+ });
+ specToPatch.config.value.sheet = createdSheet.name;
+
+ await planServiceClientConnect.updatePlan(
+ create(UpdatePlanRequestSchema, {
+ plan: planPatch,
+ updateMask: { paths: ["specs"] },
+ })
+ );
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.test.ts b/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.test.ts
new file mode 100644
index 0000000000..643860c344
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.test.ts
@@ -0,0 +1,73 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import {
+ PlanCheckRun_Result_Type,
+ PlanCheckRun_ResultSchema,
+ PlanCheckRunSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+import { getSQLAdviceMarkers } from "./sqlAdvice";
+
+describe("getSQLAdviceMarkers", () => {
+ test("uses latest SQL review warnings and errors with valid positions", () => {
+ const markers = getSQLAdviceMarkers([
+ create(PlanCheckRunSchema, {
+ name: "projects/p/plans/1/planCheckRuns/1",
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ content: "old",
+ report: {
+ case: "sqlReviewReport",
+ value: { startPosition: { column: 2, line: 3 } },
+ },
+ status: Advice_Level.ERROR,
+ title: "Old",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ ],
+ }),
+ create(PlanCheckRunSchema, {
+ name: "projects/p/plans/1/planCheckRuns/2",
+ results: [
+ create(PlanCheckRun_ResultSchema, {
+ code: 123,
+ content: "new warning",
+ report: {
+ case: "sqlReviewReport",
+ value: { startPosition: { column: 4, line: 5 } },
+ },
+ status: Advice_Level.WARNING,
+ title: "Rule",
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ content: "summary ignored",
+ status: Advice_Level.ERROR,
+ type: PlanCheckRun_Result_Type.STATEMENT_SUMMARY_REPORT,
+ }),
+ create(PlanCheckRun_ResultSchema, {
+ content: "line zero ignored",
+ report: {
+ case: "sqlReviewReport",
+ value: { startPosition: { column: 1, line: 0 } },
+ },
+ status: Advice_Level.ERROR,
+ type: PlanCheckRun_Result_Type.STATEMENT_ADVISE,
+ }),
+ ],
+ }),
+ ]);
+
+ expect(markers).toEqual([
+ {
+ endColumn: 4,
+ endLineNumber: 5,
+ message: "new warning",
+ severity: "WARNING",
+ source: "Rule (123) L5:C4",
+ startColumn: 4,
+ startLineNumber: 5,
+ },
+ ]);
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.ts b/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.ts
new file mode 100644
index 0000000000..64c181c5cf
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/sqlAdvice.ts
@@ -0,0 +1,61 @@
+import type { AdviceOption } from "@/react/components/monaco/types";
+import type {
+ PlanCheckRun,
+ PlanCheckRun_Result,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { PlanCheckRun_Result_Type } from "@/types/proto-es/v1/plan_service_pb";
+import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";
+
+const planCheckRunOrdinal = (name: string): number => {
+ const uid = name.match(/(?:^|\/)planCheckRuns\/(\d+)(?:$|\/)/)?.[1];
+ return uid ? Number.parseInt(uid, 10) : 0;
+};
+
+export const getSQLAdviceMarkers = (
+ planCheckRuns: PlanCheckRun[]
+): AdviceOption[] => {
+ const latest = [...planCheckRuns].sort(
+ (left, right) =>
+ planCheckRunOrdinal(right.name) - planCheckRunOrdinal(left.name)
+ )[0];
+ if (!latest) {
+ return [];
+ }
+
+ return latest.results
+ .filter(
+ (result) => result.type === PlanCheckRun_Result_Type.STATEMENT_ADVISE
+ )
+ .map(resultToAdviceOption)
+ .filter((marker): marker is AdviceOption => marker !== undefined);
+};
+
+const resultToAdviceOption = (
+ result: PlanCheckRun_Result
+): AdviceOption | undefined => {
+ if (
+ result.status !== Advice_Level.ERROR &&
+ result.status !== Advice_Level.WARNING
+ ) {
+ return undefined;
+ }
+ if (result.report.case !== "sqlReviewReport") {
+ return undefined;
+ }
+
+ const position = result.report.value.startPosition;
+ if (!position || position.line <= 0) {
+ return undefined;
+ }
+
+ const column = position.column || 1;
+ return {
+ endColumn: column,
+ endLineNumber: position.line,
+ message: result.content,
+ severity: result.status === Advice_Level.ERROR ? "ERROR" : "WARNING",
+ source: `${result.title} (${result.code}) L${position.line}:C${column}`,
+ startColumn: column,
+ startLineNumber: position.line,
+ };
+};
diff --git a/frontend/src/react/pages/project/plan-detail/utils/targets.test.ts b/frontend/src/react/pages/project/plan-detail/utils/targets.test.ts
new file mode 100644
index 0000000000..f3fb220093
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/targets.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, test } from "vitest";
+import {
+ filterPlanTargets,
+ getDatabaseGroupRouteParams,
+ splitInlineDatabases,
+} from "./targets";
+
+describe("splitInlineDatabases", () => {
+ test("splits database group children into inline and overflow lists", () => {
+ expect(splitInlineDatabases(["a", "b", "c"], 2)).toEqual({
+ extraDatabases: ["c"],
+ inlineDatabases: ["a", "b"],
+ });
+ });
+
+ test("filters database targets by display name and groups by resource name", () => {
+ expect(
+ filterPlanTargets({
+ getDatabaseDisplayName: () => "orders",
+ query: "ord",
+ targets: [
+ "projects/p/instances/i/databases/db1",
+ "projects/p/databaseGroups/prod",
+ ],
+ })
+ ).toEqual(["projects/p/instances/i/databases/db1"]);
+
+ expect(
+ filterPlanTargets({
+ getDatabaseDisplayName: () => "orders",
+ query: "prod",
+ targets: [
+ "projects/p/instances/i/databases/db1",
+ "projects/p/databaseGroups/prod",
+ ],
+ })
+ ).toEqual(["projects/p/databaseGroups/prod"]);
+ });
+
+ test("builds database group route params for project routes", () => {
+ expect(
+ getDatabaseGroupRouteParams({
+ databaseGroupName: "prod",
+ projectName: "projects/project-a",
+ })
+ ).toEqual({
+ databaseGroupName: "prod",
+ projectId: "project-a",
+ });
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/utils/targets.ts b/frontend/src/react/pages/project/plan-detail/utils/targets.ts
new file mode 100644
index 0000000000..5c506b3886
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/utils/targets.ts
@@ -0,0 +1,43 @@
+export const MAX_INLINE_DATABASES = 5;
+
+export const splitInlineDatabases = <T>(
+ databases: T[],
+ maxInline = MAX_INLINE_DATABASES
+) => ({
+ extraDatabases: databases.slice(maxInline),
+ inlineDatabases: databases.slice(0, maxInline),
+});
+
+export const filterPlanTargets = ({
+ getDatabaseDisplayName,
+ query,
+ targets,
+}: {
+ getDatabaseDisplayName: (target: string) => string;
+ query: string;
+ targets: string[];
+}) => {
+ const normalized = query.trim().toLowerCase();
+ if (!normalized) {
+ return targets;
+ }
+
+ return targets.filter((target) => {
+ const targetText = target.toLowerCase();
+ if (targetText.includes("/databases/")) {
+ return getDatabaseDisplayName(target).toLowerCase().includes(normalized);
+ }
+ return targetText.includes(normalized);
+ });
+};
+
+export const getDatabaseGroupRouteParams = ({
+ databaseGroupName,
+ projectName,
+}: {
+ databaseGroupName: string;
+ projectName: string;
+}) => ({
+ databaseGroupName,
+ projectId: projectName.replace(/^projects\//, ""),
+});
diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.ts
index 0b3a899647..319291c043 100644
--- a/frontend/src/router/dashboard/projectV1.ts
+++ b/frontend/src/router/dashboard/projectV1.ts
@@ -38,8 +38,7 @@ export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE = `${PROJECT_V1_ROUTE_PLAN_ROLL
export const PROJECT_V1_ROUTE_PLAN_ROLLOUT_TASK = `${PROJECT_V1_ROUTE_PLAN_ROLLOUT_STAGE}.task`;
export const PROJECT_V1_ROUTE_GITOPS = `${PROJECT_V1_ROUTE_DASHBOARD}.gitops`;
-const planDetailComponent = () =>
- import("@/components/Plan/components/PlanDetailPage/PlanDetailLayout.vue");
+const planDetailComponent = () => import("@/react/ReactPageMount.vue");
const planDetailMeta: RouteRecordRaw["meta"] = {
requiredPermissionList: () => [
@@ -58,21 +57,36 @@ const planRoutes: RouteRecordRaw[] = [
name: PROJECT_V1_ROUTE_PLAN_DETAIL,
component: planDetailComponent,
meta: planDetailMeta,
- props: true,
+ props: (route: RouteLocationNormalized) => ({
+ page: "ProjectPlanDetailPage",
+ routeName: route.name?.toString(),
+ routeQuery: route.query,
+ ...route.params,
+ }),
},
{
path: "plans/:planId/specs",
name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPECS,
component: planDetailComponent,
meta: planDetailMeta,
- props: true,
+ props: (route: RouteLocationNormalized) => ({
+ page: "ProjectPlanDetailPage",
+ routeName: route.name?.toString(),
+ routeQuery: route.query,
+ ...route.params,
+ }),
},
{
path: "plans/:planId/specs/:specId",
name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
component: planDetailComponent,
meta: planDetailMeta,
- props: true,
+ props: (route: RouteLocationNormalized) => ({
+ page: "ProjectPlanDetailPage",
+ routeName: route.name?.toString(),
+ routeQuery: route.query,
+ ...route.params,
+ }),
},
];
diff --git a/frontend/src/utils/v1/issue/rollout.ts b/frontend/src/utils/v1/issue/rollout.ts
index defffc545e..32bbe53de1 100644
--- a/frontend/src/utils/v1/issue/rollout.ts
+++ b/frontend/src/utils/v1/issue/rollout.ts
@@ -1,5 +1,5 @@
-import { useI18n } from "vue-i18n";
import { TASK_STATUS_FILTERS } from "@/components/RolloutV1/constants/task";
+import { t as translate } from "@/plugins/i18n";
import { useDatabaseV1Store } from "@/store";
import { isValidDatabaseName, UNKNOWN_ID, unknownDatabase } from "@/types";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
@@ -120,9 +120,9 @@ export const releaseNameOfTaskV1 = (task: Task): string => {
};
export const stringifyTaskStatus = (
- status: Task_Status | TaskRun_Status
+ status: Task_Status | TaskRun_Status,
+ t: (key: string, named?: Record<string, unknown>) => string = translate
): string => {
- const { t } = useI18n();
switch (status) {
case Task_Status.NOT_STARTED:
return t("task.status.not-started");