Skip to content

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

feat(frontend): plan lifecycle header actions (BYT-9722) (#20720)

boojack338849590a79
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 76f8804910..4cf7fd5858 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1474,6 +1474,27 @@
"serializable": "Serializable"
},
"labels-required-for-review": "Labels are required before review",
+ "lifecycle": {
+ "checking": "Checking…",
+ "checks-failing_one": "{{count}} check failing",
+ "checks-failing_other": "{{count}} checks failing",
+ "deployed": "Deployed",
+ "gate-checks-failed": "Some checks were not successful",
+ "gate-checks-failed-sub": "{{failing}} failing, {{passed}} passed",
+ "gate-checks-passed": "All checks passed",
+ "gate-checks-passed-sub": "{{count}} passed",
+ "gate-checks-running": "Checks are running",
+ "gate-checks-running-sub": "{{running}} running, {{passed}} passed",
+ "gate-review-approved": "Changes approved",
+ "gate-review-pending": "Review in progress",
+ "gate-review-rejected": "Changes requested",
+ "preparing-rollout": "Preparing rollout…",
+ "rejected": "Rejected",
+ "rerun-stage": "Rerun · {{stage}}",
+ "review-waiting": "Waiting for {{role}}",
+ "run-stage": "Run · {{stage}}",
+ "stage-status": "{{status}} · {{stage}}"
+ },
"meta": {
"created-by": "Created by {{user}}"
},
@@ -1552,7 +1573,9 @@
"n-checks-failed_other": "{{count}} checks failed",
"n-checks-passed_one": "{{count}} check passed",
"n-checks-passed_other": "{{count}} checks passed",
+ "rollout-auto-creates": "Rollout auto-creates after approval",
"rollout-blocked-by-failed-checks": "rollout won't be created automatically until checks pass",
+ "rollout-not-created": "Rollout was not created automatically",
"waiting-on-review": "Waiting on review"
},
"rejection": {
@@ -1573,7 +1596,9 @@
},
"state": {
"close-confirm": "Close this plan?",
- "reopen-confirm": "Reopen this plan?"
+ "close-review-confirm": "Close this review?",
+ "reopen-confirm": "Reopen this plan?",
+ "reopen-review-confirm": "Reopen this review?"
},
"subtitle": "Draft database changes and run pre-checks before creating an issue for approval.",
"summary": {
@@ -1995,7 +2020,6 @@
},
"stage": {
"confirm-create": "Confirm to create tasks for this stage?",
- "run-stage": "Run Tasks",
"self_one": "Stage",
"self_other": "Stages"
},
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 7dd529268e..17e39b5a34 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1474,6 +1474,27 @@
"serializable": "Serializable"
},
"labels-required-for-review": "Se requieren etiquetas antes de la revisión",
+ "lifecycle": {
+ "checking": "Comprobando…",
+ "checks-failing_one": "{{count}} comprobación fallida",
+ "checks-failing_other": "{{count}} comprobaciones fallidas",
+ "deployed": "Desplegado",
+ "gate-checks-failed": "Algunas comprobaciones fallaron",
+ "gate-checks-failed-sub": "{{failing}} con errores, {{passed}} correctas",
+ "gate-checks-passed": "Todas las comprobaciones correctas",
+ "gate-checks-passed-sub": "{{count}} correctas",
+ "gate-checks-running": "Comprobaciones en curso",
+ "gate-checks-running-sub": "{{running}} en curso, {{passed}} correctas",
+ "gate-review-approved": "Cambios aprobados",
+ "gate-review-pending": "Revisión en curso",
+ "gate-review-rejected": "Cambios solicitados",
+ "preparing-rollout": "Preparando despliegue…",
+ "rejected": "Rechazado",
+ "rerun-stage": "Reejecutar · {{stage}}",
+ "review-waiting": "Esperando a {{role}}",
+ "run-stage": "Ejecutar · {{stage}}",
+ "stage-status": "{{status}} · {{stage}}"
+ },
"meta": {
"created-by": "Creado por {{user}}"
},
@@ -1552,7 +1573,9 @@
"n-checks-failed_other": "{{count}} comprobaciones fallidas",
"n-checks-passed_one": "{{count}} comprobación superada",
"n-checks-passed_other": "{{count}} comprobaciones superadas",
+ "rollout-auto-creates": "El despliegue se crea automáticamente tras la aprobación",
"rollout-blocked-by-failed-checks": "el despliegue no se creará automáticamente hasta que las comprobaciones pasen",
+ "rollout-not-created": "El despliegue no se creó automáticamente",
"waiting-on-review": "Esperando revisión"
},
"rejection": {
@@ -1573,7 +1596,9 @@
},
"state": {
"close-confirm": "¿Cerrar este plan?",
- "reopen-confirm": "¿Reabrir este plan?"
+ "close-review-confirm": "¿Cerrar esta revisión?",
+ "reopen-confirm": "¿Reabrir este plan?",
+ "reopen-review-confirm": "¿Reabrir esta revisión?"
},
"subtitle": "Redactar cambios en la base de datos y ejecutar comprobaciones previas antes de crear un problema para su aprobación.",
"summary": {
@@ -1995,7 +2020,6 @@
},
"stage": {
"confirm-create": "¿Confirmas la creación de tareas para esta etapa?",
- "run-stage": "Ejecutar tareas",
"self_one": "Etapa",
"self_other": "Etapas"
},
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index f961e3f672..b5417c831b 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1474,6 +1474,27 @@
"serializable": "直列化可能"
},
"labels-required-for-review": "レビュー前にラベルが必要です",
+ "lifecycle": {
+ "checking": "チェック中…",
+ "checks-failing_one": "{{count}} 件のチェック失敗",
+ "checks-failing_other": "{{count}} 件のチェック失敗",
+ "deployed": "デプロイ済み",
+ "gate-checks-failed": "一部のチェックが失敗しました",
+ "gate-checks-failed-sub": "{{failing}} 件失敗、{{passed}} 件成功",
+ "gate-checks-passed": "すべてのチェックに合格",
+ "gate-checks-passed-sub": "{{count}} 件成功",
+ "gate-checks-running": "チェックを実行中",
+ "gate-checks-running-sub": "{{running}} 件実行中、{{passed}} 件成功",
+ "gate-review-approved": "変更が承認されました",
+ "gate-review-pending": "レビュー中",
+ "gate-review-rejected": "変更がリクエストされました",
+ "preparing-rollout": "ロールアウトを準備中…",
+ "rejected": "却下されました",
+ "rerun-stage": "再実行 · {{stage}}",
+ "review-waiting": "{{role}} の承認待ち",
+ "run-stage": "実行 · {{stage}}",
+ "stage-status": "{{status}} · {{stage}}"
+ },
"meta": {
"created-by": "{{user}} が作成"
},
@@ -1552,7 +1573,9 @@
"n-checks-failed_other": "{{count}} 件のチェックに失敗",
"n-checks-passed_one": "{{count}} 件のチェックに合格",
"n-checks-passed_other": "{{count}} 件のチェックに合格",
+ "rollout-auto-creates": "承認後にロールアウトが自動作成されます",
"rollout-blocked-by-failed-checks": "チェックが通過するまでロールアウトは自動作成されません",
+ "rollout-not-created": "ロールアウトは自動作成されませんでした",
"waiting-on-review": "レビュー待ち"
},
"rejection": {
@@ -1573,7 +1596,9 @@
},
"state": {
"close-confirm": "このプランを閉じますか?",
- "reopen-confirm": "このプランを再開きますか?"
+ "close-review-confirm": "このレビューを閉じますか?",
+ "reopen-confirm": "このプランを再開きますか?",
+ "reopen-review-confirm": "このレビューを再開しますか?"
},
"subtitle": "承認のためにイシューを作成する前に、データベースの変更を下書きし、事前チェックを実行します。",
"summary": {
@@ -1995,7 +2020,6 @@
},
"stage": {
"confirm-create": "このステージのタスクを作成しますか?",
- "run-stage": "タスクを実行",
"self_one": "ステージ",
"self_other": "ステージ"
},
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 3a17733734..ae8549286e 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1474,6 +1474,27 @@
"serializable": "Tuần tự hóa"
},
"labels-required-for-review": "Cần có nhãn trước khi review",
+ "lifecycle": {
+ "checking": "Đang kiểm tra…",
+ "checks-failing_one": "{{count}} kiểm tra thất bại",
+ "checks-failing_other": "{{count}} kiểm tra thất bại",
+ "deployed": "Đã triển khai",
+ "gate-checks-failed": "Một số kiểm tra không thành công",
+ "gate-checks-failed-sub": "{{failing}} thất bại, {{passed}} thành công",
+ "gate-checks-passed": "Tất cả kiểm tra đã qua",
+ "gate-checks-passed-sub": "{{count}} thành công",
+ "gate-checks-running": "Đang chạy kiểm tra",
+ "gate-checks-running-sub": "{{running}} đang chạy, {{passed}} thành công",
+ "gate-review-approved": "Đã duyệt thay đổi",
+ "gate-review-pending": "Đang xem xét",
+ "gate-review-rejected": "Yêu cầu thay đổi",
+ "preparing-rollout": "Đang chuẩn bị triển khai…",
+ "rejected": "Đã từ chối",
+ "rerun-stage": "Chạy lại · {{stage}}",
+ "review-waiting": "Đang chờ {{role}}",
+ "run-stage": "Chạy · {{stage}}",
+ "stage-status": "{{status}} · {{stage}}"
+ },
"meta": {
"created-by": "Tạo bởi {{user}}"
},
@@ -1552,7 +1573,9 @@
"n-checks-failed_other": "{{count}} kiểm tra thất bại",
"n-checks-passed_one": "{{count}} kiểm tra đạt",
"n-checks-passed_other": "{{count}} kiểm tra đạt",
+ "rollout-auto-creates": "Bản triển khai tự động tạo sau khi phê duyệt",
"rollout-blocked-by-failed-checks": "bản triển khai sẽ không được tạo tự động cho đến khi các kiểm tra đạt",
+ "rollout-not-created": "Bản triển khai chưa được tạo tự động",
"waiting-on-review": "Đang chờ xét duyệt"
},
"rejection": {
@@ -1573,7 +1596,9 @@
},
"state": {
"close-confirm": "Đóng kế hoạch này?",
- "reopen-confirm": "Mở lại kế hoạch này?"
+ "close-review-confirm": "Đóng đợt xem xét này?",
+ "reopen-confirm": "Mở lại kế hoạch này?",
+ "reopen-review-confirm": "Mở lại đợt xem xét này?"
},
"subtitle": "Soạn thảo các thay đổi cơ sở dữ liệu và chạy các bước kiểm tra sơ bộ trước khi tạo vấn đề để phê duyệt.",
"summary": {
@@ -1995,7 +2020,6 @@
},
"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"
},
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 73b4e38b63..6429aeddac 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1474,6 +1474,27 @@
"serializable": "串行化"
},
"labels-required-for-review": "提交审批前必须设置标签",
+ "lifecycle": {
+ "checking": "检查中…",
+ "checks-failing_one": "{{count}} 项检查失败",
+ "checks-failing_other": "{{count}} 项检查失败",
+ "deployed": "已部署",
+ "gate-checks-failed": "部分检查未通过",
+ "gate-checks-failed-sub": "{{failing}} 项失败,{{passed}} 项通过",
+ "gate-checks-passed": "所有检查已通过",
+ "gate-checks-passed-sub": "{{count}} 项通过",
+ "gate-checks-running": "检查运行中",
+ "gate-checks-running-sub": "{{running}} 项运行中,{{passed}} 项通过",
+ "gate-review-approved": "变更已批准",
+ "gate-review-pending": "审核中",
+ "gate-review-rejected": "请求变更",
+ "preparing-rollout": "正在准备发布…",
+ "rejected": "已拒绝",
+ "rerun-stage": "重新执行 · {{stage}}",
+ "review-waiting": "等待 {{role}}",
+ "run-stage": "执行 · {{stage}}",
+ "stage-status": "{{status}} · {{stage}}"
+ },
"meta": {
"created-by": "由 {{user}} 创建"
},
@@ -1540,8 +1561,8 @@
"confirm-checks-failed_one": "{{count}} 项失败的检查",
"confirm-checks-failed_other": "{{count}} 项失败的检查",
"confirm-checks-running": "检查仍在运行",
- "confirm-review-not-approved": "审核尚未通过",
- "confirm-review-rejected": "审核已被拒绝",
+ "confirm-review-not-approved": "审批尚未通过",
+ "confirm-review-rejected": "审批已被拒绝",
"creating-rollout-automatically": "正在自动创建发布...",
"errors-passed-not-created_one": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",
"errors-passed-not-created_other": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",
@@ -1552,7 +1573,9 @@
"n-checks-failed_other": "{{count}} 项检查失败",
"n-checks-passed_one": "{{count}} 项检查通过",
"n-checks-passed_other": "{{count}} 项检查通过",
+ "rollout-auto-creates": "审批通过后自动创建发布",
"rollout-blocked-by-failed-checks": "在检查通过前不会自动创建发布",
+ "rollout-not-created": "发布未自动创建",
"waiting-on-review": "等待审批"
},
"rejection": {
@@ -1573,7 +1596,9 @@
},
"state": {
"close-confirm": "确认关闭这个计划?",
- "reopen-confirm": "确认重新打开这个计划?"
+ "close-review-confirm": "确认关闭这个审批?",
+ "reopen-confirm": "确认重新打开这个计划?",
+ "reopen-review-confirm": "确认重新打开这个审批?"
},
"subtitle": "草拟数据库变更并运行预检查,然后创建工单以请求审批。",
"summary": {
@@ -1995,7 +2020,6 @@
},
"stage": {
"confirm-create": "确认创建此阶段的任务?",
- "run-stage": "运行任务",
"self_one": "阶段",
"self_other": "阶段"
},
diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
index 2f64938468..7b461a015e 100644
--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx
@@ -105,6 +105,10 @@ vi.mock("./components/PlanDetailHeader", () => ({
PlanDetailHeader: () => null,
}));
+vi.mock("./components/PlanDetailHeaderDetails", () => ({
+ PlanDetailHeaderDetails: () => null,
+}));
+
vi.mock("./shell/constants", () => ({
INLINE_TASK_PANEL_BREAKPOINT_PX: 1024,
}));
diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
index c5bc6d298f..a04d67da20 100644
--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx
@@ -26,9 +26,11 @@ import { DeployTaskDetailPanel } from "./components/deploy/DeployTaskDetailPanel
import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";
import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";
import { PlanDetailHeader } from "./components/PlanDetailHeader";
+import { PlanDetailHeaderDetails } from "./components/PlanDetailHeaderDetails";
import { PlanReviewSection } from "./components/review/PlanReviewSection";
import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";
import { INLINE_TASK_PANEL_BREAKPOINT_PX } from "./shell/constants";
+import { planPhaseAnchorId } from "./shell/focusPhase";
import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";
import { PlanDetailProvider } from "./shell/PlanDetailContext";
import {
@@ -75,6 +77,17 @@ function ProjectPlanDetailPageInner({
}) {
const { t } = useTranslation();
const [pageHost, setPageHost] = useState<HTMLDivElement | null>(null);
+ // The sticky title row only shows its bottom border once content scrolls
+ // under it (GitHub issue-header pattern) — flat at the top, separated when
+ // stuck. pageHost is the scroll container.
+ const [headerStuck, setHeaderStuck] = useState(false);
+ useEffect(() => {
+ if (!pageHost) return;
+ const onScroll = () => setHeaderStuck(pageHost.scrollTop > 0);
+ onScroll();
+ pageHost.addEventListener("scroll", onScroll, { passive: true });
+ return () => pageHost.removeEventListener("scroll", onScroll);
+ }, [pageHost]);
const [selectedSpecId, setSelectedSpecId] = useState(specId ?? "");
const page = usePlanDetailPage({
projectId,
@@ -254,9 +267,20 @@ function ProjectPlanDetailPageInner({
page.ready ? "" : "invisible pointer-events-none"
)}
>
- <header className="shrink-0 border-b bg-white">
+ {/* Only the title/action row is sticky (GitHub issue-header pattern);
+ the description + metadata below scroll away beneath it. pageHost
+ (overflow-x-hidden → overflow-y auto) is the scroll container, so
+ top-0 pins to it; z-20 keeps it above the phase rail nodes (z-10).
+ The border appears only when stuck, so the row is flat at the top. */}
+ <header
+ className={cn(
+ "sticky top-0 z-20 shrink-0 bg-white",
+ headerStuck && "border-b"
+ )}
+ >
<PlanDetailHeader />
</header>
+ <PlanDetailHeaderDetails />
<div
className="min-h-0 flex flex-1 flex-col lg:grid"
@@ -267,6 +291,7 @@ function ProjectPlanDetailPageInner({
which the connector line fills so it stays continuous. */}
<div className="flex min-w-0 flex-col pb-6 pl-2 pr-4 pt-4 xl:pr-8 2xl:pr-12">
<PhaseSection
+ anchorId={planPhaseAnchorId("changes")}
badge={phaseConfigs.changes.badge}
expanded={page.activePhases.has("changes")}
icon={<Code2 className="size-3 md:size-4" />}
@@ -285,6 +310,7 @@ function ProjectPlanDetailPageInner({
{reviewVisible && (
<PhaseSection
+ anchorId={planPhaseAnchorId("review")}
badge={phaseConfigs.review.badge}
expanded={page.activePhases.has("review")}
icon={<MessageSquareMore className="size-3 md:size-4" />}
@@ -305,6 +331,7 @@ function ProjectPlanDetailPageInner({
)}
<PhaseSection
+ anchorId={planPhaseAnchorId("deploy")}
badge={phaseConfigs.deploy.badge}
expanded={page.activePhases.has("deploy")}
icon={<Rocket className="size-3 md:size-4" />}
@@ -424,6 +451,7 @@ function PhaseSection({
children,
onToggle,
onSelect,
+ anchorId,
}: {
badge?: {
label: string;
@@ -440,6 +468,7 @@ function PhaseSection({
children: ReactNode;
onToggle: () => void;
onSelect: () => void;
+ anchorId?: string;
}) {
const { t } = useTranslation();
const dotClass =
@@ -452,7 +481,7 @@ function PhaseSection({
: "border-2 border-dashed border-control-border text-control-placeholder";
return (
- <div className={cn("flex", isLast && "mb-48")}>
+ <div className={cn("flex scroll-mt-16", isLast && "mb-48")} id={anchorId}>
<div className="flex w-10 shrink-0 flex-col items-center md:w-16">
<div
className="relative z-10 mt-0.5 flex h-5 w-5 shrink-0 cursor-pointer items-center justify-center md:h-7 md:w-7"
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
index 795d711776..05feb2f6f0 100644
--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeader.tsx
@@ -1,5 +1,5 @@
import { clone, create } from "@bufbuild/protobuf";
-import { Ban, ChevronUp, Loader2, Plus } from "lucide-react";
+import { EllipsisVertical, Loader2 } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { issueServiceClientConnect, planServiceClientConnect } from "@/connect";
@@ -7,10 +7,15 @@ import {
type IssueLabel,
IssueLabelSelect,
} from "@/react/components/IssueLabelSelect";
-import { MarkdownEditor } from "@/react/components/MarkdownEditor";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { Checkbox } from "@/react/components/ui/checkbox";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
import {
Popover,
PopoverContent,
@@ -26,10 +31,12 @@ import { useAppStore } from "@/react/stores/app";
import { pushNotification } from "@/store";
import { State } from "@/types/proto-es/v1/common_pb";
import {
+ BatchUpdateIssuesStatusRequestSchema,
CreateIssueRequestSchema,
Issue_Type,
IssueSchema,
IssueStatus,
+ ListIssueCommentsRequestSchema,
UpdateIssueRequestSchema,
} from "@/types/proto-es/v1/issue_service_pb";
import {
@@ -45,6 +52,7 @@ import {
hasProjectPermissionV2,
} from "@/utils";
import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidation";
+import { focusPlanPhase } from "../shell/focusPhase";
import { usePlanDetailContext } from "../shell/PlanDetailContext";
import {
getCreateIssueBlockingErrors,
@@ -54,9 +62,13 @@ import {
shouldStayOnPlanDetailPage,
} from "../utils/header";
import { getLocalSheetByName, removeLocalSheet } from "../utils/localSheet";
-import { isReleaseBackedPlan } from "../utils/spec";
-import { PlanDetailMeta } from "./PlanDetailMeta";
+import { PlanLifecycleSlot } from "./lifecycle/PlanLifecycleSlot";
+import { PlanLifecycleStamp } from "./lifecycle/PlanLifecycleStamp";
+import { slotHasPrimaryControl } from "./lifecycle/planLifecycleHeaderState";
+import { usePlanLifecycleHeader } from "./lifecycle/usePlanLifecycleHeader";
+// The sticky title/action row. Description + metadata live in
+// PlanDetailHeaderDetails so they scroll away while this row stays pinned.
export function PlanDetailHeader() {
const { t } = useTranslation();
const page = usePlanDetailContext();
@@ -64,10 +76,7 @@ export function PlanDetailHeader() {
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[]>([]);
@@ -95,12 +104,6 @@ export function PlanDetailHeader() {
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;
@@ -122,24 +125,6 @@ export function PlanDetailHeader() {
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,
- ]);
-
useEffect(() => {
// Route changes within the plan-detail page (create → existing → create)
// re-render the same React root, so the guard must reset when leaving
@@ -153,16 +138,9 @@ export function PlanDetailHeader() {
titleInputRef.current?.focus();
}, [page.isCreating, page.ready]);
- const isGitOpsPlan = useMemo(
- () => isReleaseBackedPlan(page.plan.specs),
- [page.plan.specs]
- );
- const showSubmitForReview =
- !!page.plan.name &&
- !page.isCreating &&
- !page.plan.issue &&
- !isGitOpsPlan &&
- page.plan.state === State.ACTIVE;
+ // The resolver owns "what does the header show": the create / ready-for-review
+ // advances surface as lifecycle states, replacing the old ad-hoc booleans.
+ const lifecycle = usePlanLifecycleHeader(page);
const showClosePlan =
!page.isCreating &&
!page.plan.issue &&
@@ -174,6 +152,20 @@ export function PlanDetailHeader() {
!page.plan.hasRollout &&
page.plan.state === State.DELETED;
+ // Close (cancel) / reopen the review issue from the header, mirroring the issue
+ // detail page. Close is offered during the review phase (open issue, no rollout
+ // yet); reopen once the review was canceled.
+ const canUpdateIssue = hasProjectPermissionV2(project, "bb.issues.update");
+ const showCloseIssue =
+ !!page.issue &&
+ page.issue.status === IssueStatus.OPEN &&
+ !page.plan.hasRollout &&
+ canUpdateIssue;
+ const showReopenIssue =
+ !!page.issue &&
+ page.issue.status === IssueStatus.CANCELED &&
+ canUpdateIssue;
+
const submitDisabled = page.isEditing;
const submitDisabledReason = submitDisabled
? t("plan.editor.save-changes-before-continuing")
@@ -245,61 +237,57 @@ export function PlanDetailHeader() {
}
};
- const saveDescription = async () => {
- if (page.isCreating) {
- patchState({
- plan: {
- ...page.plan,
- description,
- },
- });
- setEditingDescription(false);
- setEditing("description", false);
- return;
- }
-
- let saved = false;
+ const updatePlanState = async (state: State) => {
try {
- setUpdating(true);
- const planPatch = create(PlanSchema, {
- ...page.plan,
- description,
- });
- const response = await planServiceClientConnect.updatePlan(
+ const planPatch = clone(PlanSchema, page.plan);
+ planPatch.state = state;
+ const updated = await planServiceClientConnect.updatePlan(
create(UpdatePlanRequestSchema, {
plan: planPatch,
- updateMask: { paths: ["description"] },
+ updateMask: { paths: ["state"] },
})
);
- patchState({ plan: response });
- saved = true;
+ patchState({ plan: updated });
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
} catch (error) {
pushNotification({
module: "bytebase",
style: "CRITICAL",
- title: t("common.error"),
+ title: t("common.failed"),
description: String(error),
});
- } finally {
- setUpdating(false);
- if (saved) {
- setEditingDescription(false);
- setEditing("description", false);
- }
}
};
- const updatePlanState = async (state: State) => {
+ const updateIssueStatus = async (status: IssueStatus) => {
+ const issue = page.issue;
+ if (!issue) return;
try {
- const planPatch = clone(PlanSchema, page.plan);
- planPatch.state = state;
- const updated = await planServiceClientConnect.updatePlan(
- create(UpdatePlanRequestSchema, {
- plan: planPatch,
- updateMask: { paths: ["state"] },
+ await issueServiceClientConnect.batchUpdateIssuesStatus(
+ create(BatchUpdateIssuesStatusRequestSchema, {
+ parent: project.name,
+ issues: [issue.name],
+ status,
})
);
- patchState({ plan: updated });
+ // Closing / reopening records a system comment — refresh page state and the
+ // issue comments so the review timeline reflects it (like issue detail).
+ await Promise.all([
+ page.refreshState(),
+ useAppStore.getState().listIssueComments(
+ create(ListIssueCommentsRequestSchema, {
+ parent: issue.name,
+ pageSize: 1000,
+ })
+ ),
+ ]);
+ // Land on the review section so the close/reopen system comment and the
+ // updated status are visible (consistent with the other header advances).
+ focusPlanPhase("review", page.expandPhase);
pushNotification({
module: "bytebase",
style: "SUCCESS",
@@ -315,6 +303,71 @@ export function PlanDetailHeader() {
}
};
+ // Secondary lifecycle actions collapse into a "..." overflow menu beside the
+ // primary slot, matching the issue detail page — the slot keeps one action or
+ // status, everything else lives in the menu.
+ const secondaryActions: {
+ key: string;
+ label: string;
+ onSelect: () => void;
+ }[] = [];
+ if (showClosePlan) {
+ secondaryActions.push({
+ key: "close-plan",
+ label: t("common.close"),
+ onSelect: () => {
+ if (window.confirm(t("plan.state.close-confirm"))) {
+ void updatePlanState(State.DELETED);
+ }
+ },
+ });
+ }
+ if (showReopenPlan) {
+ secondaryActions.push({
+ key: "reopen-plan",
+ label: t("common.reopen"),
+ onSelect: () => {
+ if (window.confirm(t("plan.state.reopen-confirm"))) {
+ void updatePlanState(State.ACTIVE);
+ }
+ },
+ });
+ }
+ if (showCloseIssue) {
+ secondaryActions.push({
+ key: "close-issue",
+ label: t("issue.batch-transition.close"),
+ onSelect: () => {
+ if (window.confirm(t("plan.state.close-review-confirm"))) {
+ void updateIssueStatus(IssueStatus.CANCELED);
+ }
+ },
+ });
+ }
+ if (showReopenIssue) {
+ secondaryActions.push({
+ key: "reopen-issue",
+ label: t("issue.batch-transition.reopen"),
+ onSelect: () => {
+ if (window.confirm(t("plan.state.reopen-review-confirm"))) {
+ void updateIssueStatus(IssueStatus.OPEN);
+ }
+ },
+ });
+ }
+
+ // With no primary in the slot (terminal / none), surface the first secondary
+ // action directly (e.g. Reopen) rather than hiding it; the rest stay in the
+ // overflow menu.
+ const slotHasPrimary = slotHasPrimaryControl(lifecycle);
+ const promotedAction =
+ !slotHasPrimary && secondaryActions.length > 0
+ ? secondaryActions[0]
+ : undefined;
+ const overflowActions = promotedAction
+ ? secondaryActions.slice(1)
+ : secondaryActions;
+
const createSheets = async () => {
for (const spec of page.plan.specs) {
let config = null;
@@ -406,10 +459,6 @@ export function PlanDetailHeader() {
}
};
- const isDescriptionLong =
- (description?.length ?? 0) > 150 ||
- (description?.split("\n").length ?? 0) > 3;
-
const handleCreateIssue = async () => {
if (createIssueConfirmErrors.length > 0) return;
try {
@@ -436,6 +485,8 @@ export function PlanDetailHeader() {
});
if (shouldStayOnPlanDetailPage(page.plan)) {
await page.refreshState();
+ // Land the user on the review they just opened.
+ focusPlanPhase("review", page.expandPhase);
return;
}
void router.push({
@@ -460,17 +511,14 @@ export function PlanDetailHeader() {
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">
+ <div className="flex min-w-0 flex-1 items-center gap-x-2">
+ {/* Terminal status (Closed / Deployed) sits at the far left, before
+ the title — a state badge, not an action. */}
+ <PlanLifecycleStamp state={lifecycle} />
<input
ref={titleInputRef}
className={cn(
- "h-9 w-full bg-transparent text-xl! font-bold text-main outline-hidden",
+ "h-9 min-w-0 flex-1 bg-transparent text-xl! font-bold text-main outline-hidden",
editingTitle
? "border border-control-border px-3"
: "border border-transparent px-0",
@@ -503,7 +551,10 @@ export function PlanDetailHeader() {
</div>
<div className="flex shrink-0 items-center gap-x-2">
- {page.isCreating ? (
+ {/* Lifecycle slot: one primary advance/status per state. Create and
+ ready-for-review stay here (coupled to the title/create flow); all
+ other states render through PlanLifecycleSlot. */}
+ {lifecycle.kind === "create" ? (
<Popover
modal={false}
onOpenChange={setShowCreateErrors}
@@ -536,195 +587,78 @@ export function PlanDetailHeader() {
/>
</PopoverContent>
</Popover>
+ ) : lifecycle.kind === "ready-for-review" ? (
+ <Popover
+ open={showReviewPopover}
+ onOpenChange={handleReviewPopoverOpenChange}
+ >
+ <PopoverTrigger
+ render={
+ <Button
+ disabled={submitDisabled}
+ title={submitDisabledReason}
+ />
+ }
+ >
+ {t("plan.ready-for-review")}
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ className="w-[min(28rem,calc(100vw-2rem))] px-4 py-4"
+ >
+ <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}
+ />
+ </PopoverContent>
+ </Popover>
) : (
- <>
- {showSubmitForReview && (
- <Popover
- open={showReviewPopover}
- onOpenChange={handleReviewPopoverOpenChange}
- >
- <PopoverTrigger
- render={
- <Button
- disabled={submitDisabled}
- title={submitDisabledReason}
- />
- }
- >
- {t("plan.ready-for-review")}
- </PopoverTrigger>
- <PopoverContent
- align="end"
- className="w-[min(28rem,calc(100vw-2rem))] px-4 py-4"
- >
- <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}
- />
- </PopoverContent>
- </Popover>
- )}
- {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>
- )}
- </>
+ <PlanLifecycleSlot state={lifecycle} />
)}
- </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 && (
+ {/* Secondary actions trail the lifecycle slot in a "..." overflow menu
+ and never compete with it for the primary position — except when the
+ slot has no primary, where the first one (e.g. Reopen) surfaces
+ directly. */}
+ {promotedAction && (
+ <Button onClick={promotedAction.onSelect} variant="outline">
+ {promotedAction.label}
+ </Button>
+ )}
+ {overflowActions.length > 0 && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
<Button
- onClick={() => {
- setDescription(page.plan.description);
- setEditingDescription(false);
- setEditing("description", false);
- }}
- size="xs"
+ aria-label={t("common.more")}
+ className="px-2"
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}
+ <EllipsisVertical className="size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {overflowActions.map((action) => (
+ <DropdownMenuItem key={action.key} onClick={action.onSelect}>
+ {action.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
</div>
-
- <PlanDetailMeta />
</div>
);
}
diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx
new file mode 100644
index 0000000000..cd6d155ad1
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailHeaderDetails.tsx
@@ -0,0 +1,224 @@
+// The scrolling part of the plan header — description + metadata. Split out from
+// the title/action row (PlanDetailHeader) so only that first row stays sticky on
+// scroll, following GitHub's issue-header pattern (BYT-9722). Owns its own
+// description-edit state; the title row owns the title + lifecycle slot.
+import { create } from "@bufbuild/protobuf";
+import { ChevronUp, Plus } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { planServiceClientConnect } from "@/connect";
+import { MarkdownEditor } from "@/react/components/MarkdownEditor";
+import { Button } from "@/react/components/ui/button";
+import { Textarea } from "@/react/components/ui/textarea";
+import { cn } from "@/react/lib/utils";
+import { pushNotification } from "@/store";
+import {
+ PlanSchema,
+ UpdatePlanRequestSchema,
+} from "@/types/proto-es/v1/plan_service_pb";
+import { hasProjectPermissionV2 } from "@/utils";
+import { usePlanDetailContext } from "../shell/PlanDetailContext";
+import { PlanDetailMeta } from "./PlanDetailMeta";
+
+export function PlanDetailHeaderDetails() {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const { patchState, setEditing } = page;
+ const currentUser = page.currentUser;
+ const project = page.project;
+ const [description, setDescription] = useState(page.plan.description);
+ const [editingDescription, setEditingDescription] = useState(false);
+ const [showFullDescription, setShowFullDescription] = useState(false);
+ const [updating, setUpdating] = useState(false);
+
+ useEffect(() => {
+ setDescription((prev) =>
+ prev === page.plan.description ? prev : page.plan.description
+ );
+ }, [page.plan.description]);
+
+ 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 isDescriptionLong =
+ (description?.length ?? 0) > 150 ||
+ (description?.split("\n").length ?? 0) > 3;
+
+ 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);
+ }
+ }
+ };
+
+ return (
+ <div className="shrink-0 border-b bg-white px-2 pb-2 sm:px-4">
+ <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
+ disabled={updating}
+ 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"
+ 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
+ className="italic opacity-60"
+ onClick={() => {
+ setEditingDescription(true);
+ setEditing("description", true);
+ }}
+ size="xs"
+ variant="ghost"
+ >
+ <Plus className="mr-1 h-4 w-4" />
+ {t("plan.description.placeholder")}
+ </Button>
+ ) : null}
+ </div>
+
+ <PlanDetailMeta />
+ </div>
+ );
+}
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
index ef60e401fb..c122355bbd 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployBranch.tsx
@@ -6,10 +6,10 @@ import { useAppStore } from "@/react/stores/app";
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 "../../shell/PlanDetailContext";
import { generateRolloutPreview } from "../../utils/rolloutPreview";
+import { getFrontierStage } from "../lifecycle/frontierStage";
import { DeployPendingTasksSection } from "./DeployPendingTasksSection";
import { DeployStageList } from "./DeployStageCard";
import { DeployStageContentView } from "./DeployStageContentView";
@@ -80,15 +80,10 @@ export function DeployBranch({
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]);
+ // Default to the frontier (first non-complete) stage, falling back to the
+ // first stage once every stage is complete.
+ return getFrontierStage(page.rollout) ?? page.rollout.stages[0];
+ }, [page.rollout, page.routeStageId, selectedTask]);
useEffect(() => {
let canceled = false;
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
deleted file mode 100644
index 76ca7159e4..0000000000
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageActionSection.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-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 "../../shell/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
index 5dfabddb7b..48b20a7ba8 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageCard.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageCard.tsx
@@ -1,20 +1,15 @@
import { ArrowRight, Eye } from "lucide-react";
-import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";
import { Button } from "@/react/components/ui/button";
-import { useAppStore } from "@/react/stores/app";
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 { useStageTitle } from "../lifecycle/useStageTitle";
import { PlanDetailTabItem, PlanDetailTabStrip } from "../PlanDetailTabStrip";
function StageProgressCard({ stage }: { stage: Stage }) {
- const environmentList = useAppStore((s) => s.environmentList);
- const env = useMemo(
- () => useAppStore.getState().getEnvironmentByName(stage.environment),
- [environmentList, stage.environment]
- );
+ const title = useStageTitle(stage);
const completed = stage.tasks.filter(
(task) =>
task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
@@ -24,7 +19,7 @@ function StageProgressCard({ stage }: { stage: Stage }) {
return (
<div className="flex items-center gap-2">
<TaskStatusIcon size="tiny" status={stageStatus} />
- <span className="text-sm font-medium text-main">{env.title}</span>
+ <span className="text-sm font-medium text-main">{title}</span>
<span className="text-xs text-control-light">
({completed}/{stage.tasks.length})
</span>
diff --git a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx
index 4bed04aafa..93f4669d70 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.test.tsx
@@ -47,14 +47,6 @@ vi.mock("./DeployTaskFilter", () => ({
vi.mock("./DeployStageRollbackSection", () => ({
DeployStageRollbackSection: () => null,
}));
-vi.mock("../PlanDetailTaskRolloutActionPanel", () => ({
- PlanDetailTaskRolloutActionPanel: () => null,
-}));
-vi.mock("../../../issue-detail/utils/rollout", () => ({
- canRolloutTasks: () => false,
- preloadRolloutPermissionContext: () => Promise.resolve(),
- RUNNABLE_TASK_STATUSES: [],
-}));
vi.mock("@/connect", () => ({ rolloutServiceClientConnect: {} }));
vi.mock("@/store", () => ({ pushNotification: () => undefined }));
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
index ef09fc1c48..3b17174ec1 100644
--- a/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/deploy/DeployStageContentView.tsx
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
-import { Play, Plus } from "lucide-react";
-import { useEffect, useState } from "react";
+import { Plus } from "lucide-react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import { rolloutServiceClientConnect } from "@/connect";
import { Button } from "@/react/components/ui/button";
@@ -10,13 +10,7 @@ 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 "../../shell/PlanDetailContext";
-import { PlanDetailTaskRolloutActionPanel } from "../PlanDetailTaskRolloutActionPanel";
import { DeployStageRollbackSection } from "./DeployStageRollbackSection";
import { DeployTaskFilter } from "./DeployTaskFilter";
import { DeployTaskList } from "./DeployTaskList";
@@ -30,8 +24,6 @@ export function DeployStageContentView({
}) {
const { t } = useTranslation();
const page = usePlanDetailContext();
- const currentUser = page.currentUser;
- const project = page.project;
const [filterStatuses, setFilterStatuses] = useState<Task_Status[]>([]);
// Scope the task filter to the stage: when switching to a different stage,
// drop the previous stage's filter so it can't silently hide the new stage's
@@ -43,45 +35,9 @@ export function DeployStageContentView({
setFilteredStageName(stage.name);
setFilterStatuses([]);
}
- 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))
@@ -101,17 +57,13 @@ export function DeployStageContentView({
)}
</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>
- ) : (
+ {/* The bulk "run this stage" advance now lives in the page header's
+ lifecycle slot (Run · {stage}, frontier-only — BYT-9722), so this
+ row no longer duplicates it. "Create" is a separate action for a
+ stage that doesn't exist in the rollout yet; per-task actions and
+ the multi-select toolbar below still cover ad hoc runs. */}
+ {!isStageCreated && (
+ <div className="flex shrink-0 items-center gap-x-2">
<Button
onClick={async () => {
const confirmed = window.confirm(
@@ -145,8 +97,8 @@ export function DeployStageContentView({
<Plus className="h-4 w-4" />
{t("common.create")}
</Button>
- )}
- </div>
+ </div>
+ )}
</div>
</div>
@@ -162,16 +114,6 @@ export function DeployStageContentView({
{isStageCreated && <DeployStageRollbackSection 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/lifecycle/DeployStageActions.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/DeployStageActions.tsx
new file mode 100644
index 0000000000..cd145ad874
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/DeployStageActions.tsx
@@ -0,0 +1,154 @@
+// Deploy-phase lifecycle slot content, pointed at the frontier stage. "Run"
+// opens the same run confirmation sheet the Deploy section uses; a user who
+// can't run the stage — and every user while it is running — sees the frontier's
+// computed status instead (consistent with the review phase: not actionable →
+// status, not a disabled action; and with the Deploy section, which renders the
+// same getStageStatus + TaskStatusIcon). Skip / cancel / rollback and per-task
+// controls stay in the Deploy section beside their task context.
+import { Play } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { TaskStatusIcon } from "@/react/components/TaskStatusIcon";
+import { Button } from "@/react/components/ui/button";
+import { router } from "@/react/router";
+import {
+ type Stage,
+ Task_Status,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { getStageStatus, stringifyTaskStatus } from "@/utils";
+import {
+ canRolloutTasks,
+ preloadRolloutPermissionContext,
+ RUNNABLE_TASK_STATUSES,
+} from "../../../issue-detail/utils/rollout";
+import { focusPlanPhase } from "../../shell/focusPhase";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { PlanDetailTaskRolloutActionPanel } from "../PlanDetailTaskRolloutActionPanel";
+import { stageHasFailedOrCanceledTasks } from "./frontierStage";
+import { LifecycleStamp } from "./LifecycleStamp";
+import { useStageTitle } from "./useStageTitle";
+
+export function RunStageAction({ stage }: { stage: Stage }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const project = page.project;
+ const currentUser = page.currentUser;
+ const [open, setOpen] = useState(false);
+ const [permissionReady, setPermissionReady] = useState(false);
+ const title = useStageTitle(stage);
+ // If any task in the frontier stage already ran (failed / canceled), running
+ // the stage re-runs it — surface that as "Rerun" rather than "Run".
+ const isRerun = stageHasFailedOrCanceledTasks(stage);
+
+ const runnableTasks = useMemo(
+ () =>
+ stage.tasks.filter((task) =>
+ RUNNABLE_TASK_STATUSES.includes(task.status)
+ ),
+ [stage.tasks]
+ );
+ // Polling swaps the stage/rollout objects every tick, giving `runnableTasks` a
+ // fresh identity even when the set is unchanged. Key the IAM preload on a
+ // stable name string so it doesn't refetch (and flicker permissionReady) each
+ // poll — only when the runnable set actually changes.
+ const runnableTaskKey = runnableTasks.map((task) => task.name).join("|");
+
+ // Gate the header action on the same permission the Deploy section enforces.
+ useEffect(() => {
+ let canceled = false;
+ const load = async () => {
+ setPermissionReady(false);
+ await preloadRolloutPermissionContext({
+ environment: stage.environment,
+ projectName: project.name,
+ tasks: runnableTasks,
+ });
+ if (!canceled) setPermissionReady(true);
+ };
+ void load();
+ return () => {
+ canceled = true;
+ };
+ }, [project.name, runnableTaskKey, stage.environment]);
+
+ // Wait for the permission check so we never flash an action a user can't take.
+ if (!permissionReady) {
+ return null;
+ }
+
+ const canRun = canRolloutTasks({
+ currentUser,
+ environment: stage.environment,
+ issue: page.issue,
+ project,
+ tasks: runnableTasks,
+ });
+
+ // Not actionable → show the frontier status, not an action (consistent with
+ // the review phase, and with the Deploy section's stage status display).
+ if (!canRun) {
+ return <FrontierStatusStamp stage={stage} />;
+ }
+
+ const runLabel = isRerun
+ ? t("plan.lifecycle.rerun-stage", { stage: title })
+ : t("plan.lifecycle.run-stage", { stage: title });
+
+ return (
+ <>
+ <Button
+ className="max-w-48 shrink-0 gap-x-1.5"
+ onClick={() => setOpen(true)}
+ >
+ <Play className="size-4 shrink-0" />
+ <span className="truncate" title={runLabel}>
+ {runLabel}
+ </span>
+ </Button>
+ <PlanDetailTaskRolloutActionPanel
+ action="RUN"
+ onConfirm={async () => {
+ await page.refreshState();
+ // Land on the stage that was run: switch the deploy selection to it if
+ // another stage is currently selected, then bring the phase into view.
+ const stageId = stage.name.split("/").pop();
+ if (stageId && page.routeStageId && page.routeStageId !== stageId) {
+ void router.push({ query: { phase: "deploy", stageId } });
+ }
+ focusPlanPhase("deploy", page.expandPhase);
+ }}
+ onOpenChange={setOpen}
+ open={open}
+ target={{ stage, type: "tasks" }}
+ />
+ </>
+ );
+}
+
+// The frontier stage's status, rendered exactly as the Deploy section renders a
+// stage: the canonical TaskStatusIcon for the computed getStageStatus, with the
+// same status word (stringifyTaskStatus). Tinted red only on failure. Shown
+// while the stage is running (nobody can act) or when the current user can't run
+// it — a status, never a disabled action.
+export function FrontierStatusStamp({ stage }: { stage: Stage }) {
+ const { t } = useTranslation();
+ const title = useStageTitle(stage);
+ const status = getStageStatus(stage);
+ const label = t("plan.lifecycle.stage-status", {
+ stage: title,
+ status: stringifyTaskStatus(status, t),
+ });
+
+ return (
+ <LifecycleStamp
+ className="max-w-48"
+ size="md"
+ tone={status === Task_Status.FAILED ? "error" : "neutral"}
+ >
+ <TaskStatusIcon size="tiny" status={status} />
+ <span className="truncate" title={label}>
+ {label}
+ </span>
+ </LifecycleStamp>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/LifecycleStamp.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/LifecycleStamp.tsx
new file mode 100644
index 0000000000..b80f4e0411
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/LifecycleStamp.tsx
@@ -0,0 +1,36 @@
+import type { ReactNode } from "react";
+import { cn } from "@/react/lib/utils";
+
+// A bordered pill, not a button — it makes the lifecycle state visible without
+// implying another primary action. Two sizes: `sm` (default) is a compact badge
+// for the terminal state next to the title (Closed / Deployed); `md` matches the
+// action button height (h-9) for right-slot statuses that stand in for the
+// advance action, so the slot stays consistent when it swaps action ↔ status.
+// The outline-not-fill, rounded-full shape keeps it reading as status either way.
+export function LifecycleStamp({
+ tone = "neutral",
+ size = "sm",
+ className,
+ children,
+}: {
+ tone?: "neutral" | "success" | "error";
+ size?: "sm" | "md";
+ className?: string;
+ children: ReactNode;
+}) {
+ return (
+ <span
+ className={cn(
+ "inline-flex shrink-0 items-center rounded-full border text-sm",
+ size === "sm" && "gap-x-1 px-2 py-0.5",
+ size === "md" && "h-9 gap-x-1.5 px-3",
+ tone === "success" && "border-success/40 text-success",
+ tone === "error" && "border-error/40 text-error",
+ tone === "neutral" && "text-control",
+ className
+ )}
+ >
+ {children}
+ </span>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.test.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.test.tsx
new file mode 100644
index 0000000000..aef6101480
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.test.tsx
@@ -0,0 +1,134 @@
+import { create } from "@bufbuild/protobuf";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { StageSchema } from "@/types/proto-es/v1/rollout_service_pb";
+import type { PlanLifecycleHeaderState } from "./planLifecycleHeaderState";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("../../shell/PlanDetailContext", () => ({
+ usePlanDetailContext: () => ({ issue: { name: "projects/p/issues/1" } }),
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({ children }: { children: React.ReactNode }) => (
+ <button type="button">{children}</button>
+ ),
+}));
+
+vi.mock("./LifecycleStamp", () => ({
+ LifecycleStamp: ({ children }: { children: React.ReactNode }) => (
+ <span>{children}</span>
+ ),
+}));
+
+vi.mock("./ReviewYourTurnAction", () => ({
+ ReviewYourTurnAction: () => <div>marker-review-your-turn</div>,
+}));
+
+vi.mock("./PlanStatusAction", () => ({
+ PlanStatusAction: () => <div>marker-plan-status</div>,
+}));
+
+vi.mock("./DeployStageActions", () => ({
+ RunStageAction: () => <div>marker-run-stage</div>,
+ FrontierStatusStamp: () => <div>marker-running-stage</div>,
+}));
+
+import React from "react";
+import { PlanLifecycleSlot } from "./PlanLifecycleSlot";
+import { PlanLifecycleStamp } from "./PlanLifecycleStamp";
+
+let container: HTMLDivElement;
+let root: ReturnType<typeof createRoot>;
+
+beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ document.body.removeChild(container);
+});
+
+const renderEl = (element: React.ReactElement) =>
+ act(() => {
+ root.render(element);
+ });
+
+const slot = (state: PlanLifecycleHeaderState) =>
+ renderEl(<PlanLifecycleSlot state={state} />);
+
+const checks = { error: 1, running: 0, success: 0, total: 1, warning: 0 };
+const stage = create(StageSchema, { name: "stages/1" });
+
+describe("PlanLifecycleSlot (right action area)", () => {
+ test("renders the matching control for each active state", () => {
+ slot({ kind: "review-generating" });
+ expect(container.textContent).toContain("plan.review.action");
+
+ slot({ kind: "review-your-turn" });
+ expect(container.textContent).toContain("marker-review-your-turn");
+
+ slot({ kind: "plan-status", reason: "rejected", checks });
+ expect(container.textContent).toContain("marker-plan-status");
+
+ slot({ kind: "preparing-rollout" });
+ expect(container.textContent).toContain("plan.lifecycle.preparing-rollout");
+
+ slot({ kind: "run-stage", stage });
+ expect(container.textContent).toContain("marker-run-stage");
+
+ slot({ kind: "running-stage", stage });
+ expect(container.textContent).toContain("marker-running-stage");
+ });
+
+ test("renders nothing for header-owned, terminal, and none states", () => {
+ // create / ready-for-review render in the header; closed / deployed render
+ // as the left stamp; none renders nothing.
+ for (const kind of [
+ "create",
+ "ready-for-review",
+ "closed",
+ "deployed",
+ "none",
+ ] as const) {
+ slot({ kind });
+ expect(container.textContent).toBe("");
+ }
+ });
+});
+
+describe("PlanLifecycleStamp (left of title)", () => {
+ test("renders the terminal stamp for closed / deployed", () => {
+ renderEl(<PlanLifecycleStamp state={{ kind: "closed" }} />);
+ expect(container.textContent).toContain("common.closed");
+
+ renderEl(<PlanLifecycleStamp state={{ kind: "deployed" }} />);
+ expect(container.textContent).toContain("plan.lifecycle.deployed");
+ });
+
+ test("renders nothing for non-terminal states", () => {
+ for (const kind of [
+ "create",
+ "review-your-turn",
+ "running-stage",
+ ] as const) {
+ renderEl(
+ <PlanLifecycleStamp
+ state={kind === "running-stage" ? { kind, stage } : { kind }}
+ />
+ );
+ expect(container.textContent).toBe("");
+ }
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx
new file mode 100644
index 0000000000..4b74d02957
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleSlot.tsx
@@ -0,0 +1,62 @@
+// The single lifecycle slot rendered next to the plan title. It switches on the
+// resolved header state and shows one of: an advance action, a read-only status
+// control, a progress indicator, or a terminal stamp. Draft states (create,
+// ready-for-review) are rendered by PlanDetailHeader because they are coupled to
+// the title/create flow; everything else lives here.
+import { Loader2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import { FrontierStatusStamp, RunStageAction } from "./DeployStageActions";
+import { LifecycleStamp } from "./LifecycleStamp";
+import { PlanStatusAction } from "./PlanStatusAction";
+import type { PlanLifecycleHeaderState } from "./planLifecycleHeaderState";
+import { ReviewYourTurnAction } from "./ReviewYourTurnAction";
+
+export function PlanLifecycleSlot({
+ state,
+}: {
+ state: PlanLifecycleHeaderState;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+
+ switch (state.kind) {
+ case "review-generating":
+ // The approval flow is still being generated — show the Review affordance
+ // disabled with a loading spinner; no click action until it resolves.
+ return (
+ <Button className="gap-x-1.5" disabled>
+ <Loader2 className="size-4 animate-spin" />
+ {t("plan.review.action")}
+ </Button>
+ );
+ case "review-your-turn":
+ // review-your-turn only resolves while an open issue exists.
+ return page.issue ? <ReviewYourTurnAction issue={page.issue} /> : null;
+ case "plan-status":
+ return page.issue ? (
+ <PlanStatusAction
+ checks={state.checks}
+ issue={page.issue}
+ reason={state.reason}
+ />
+ ) : null;
+ case "preparing-rollout":
+ return (
+ <LifecycleStamp size="md">
+ <Loader2 className="size-3.5 animate-spin" />
+ {t("plan.lifecycle.preparing-rollout")}
+ </LifecycleStamp>
+ );
+ case "run-stage":
+ return <RunStageAction stage={state.stage} />;
+ case "running-stage":
+ return <FrontierStatusStamp stage={state.stage} />;
+ default:
+ // create / ready-for-review render in the header; closed / deployed are
+ // terminal stamps rendered left of the title (PlanLifecycleStamp); none
+ // renders nothing.
+ return null;
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleStamp.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleStamp.tsx
new file mode 100644
index 0000000000..ff95632f7c
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanLifecycleStamp.tsx
@@ -0,0 +1,34 @@
+// Terminal lifecycle stamp shown at the far left, before the title — a status
+// badge for the plan's final state (like GitHub's Open/Closed pill), not an
+// action. Active states and advances render on the right via PlanLifecycleSlot.
+import { Ban, CircleCheckBig } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { LifecycleStamp } from "./LifecycleStamp";
+import type { PlanLifecycleHeaderState } from "./planLifecycleHeaderState";
+
+export function PlanLifecycleStamp({
+ state,
+}: {
+ state: PlanLifecycleHeaderState;
+}) {
+ const { t } = useTranslation();
+
+ switch (state.kind) {
+ case "closed":
+ return (
+ <LifecycleStamp>
+ <Ban className="size-4" />
+ {t("common.closed")}
+ </LifecycleStamp>
+ );
+ case "deployed":
+ return (
+ <LifecycleStamp tone="success">
+ <CircleCheckBig className="size-4" />
+ {t("plan.lifecycle.deployed")}
+ </LifecycleStamp>
+ );
+ default:
+ return null;
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanStatusAction.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
new file mode 100644
index 0000000000..58b28012d3
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/PlanStatusAction.tsx
@@ -0,0 +1,441 @@
+// The header's read-only "Plan status" control, shown when the current user does
+// not own the next action (observer, not-your-turn) or the plan is in a pre-deploy
+// blocker state. The trigger names the blocker; clicking opens a details panel
+// styled after GitHub's merge box — two collapsible gate rows (Review, Plan
+// checks), each a status icon + headline + subtext. The detail is ours: Review
+// expands to the (compact) approval flow; Plan checks expands to a severity
+// breakdown with a "View Details" link into the existing plan-check drawer. The
+// footer shows at most one state-dependent action: re-request review when
+// rejected (mirroring the section's rejection banner), otherwise the demoted
+// bypass-and-deploy override (BYT-9722).
+import { create } from "@bufbuild/protobuf";
+import {
+ ChevronDown,
+ ChevronRight,
+ CircleCheck,
+ CircleX,
+ Clock3,
+ Loader2,
+} from "lucide-react";
+import { type ReactNode, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { issueServiceClientConnect } from "@/connect";
+import { PlanCheckResultsDrawer } from "@/react/components/plan-check/PlanCheckSection";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/react/components/ui/popover";
+import { useCurrentUser } from "@/react/hooks/useAppState";
+import { displayRoleTitleFromList } from "@/react/lib/role";
+import { cn } from "@/react/lib/utils";
+import { useAppStore } from "@/react/stores/app";
+import { pushNotification } from "@/store";
+import { userNamePrefix } from "@/store/modules/v1/common";
+import { unknownUser } from "@/types";
+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import { RequestIssueRequestSchema } from "@/types/proto-es/v1/issue_service_pb";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import type { PlanCheckSummary } from "../../utils/phaseSummary";
+import { BypassAndDeploySheet, useBypassDeploy } from "../review/bypassDeploy";
+import { deriveSteps, ReviewApprovalFlow } from "../review/ReviewApprovalFlow";
+import type { PlanStatusReason } from "./planLifecycleHeaderState";
+import { getPlanStatusTone, type PlanStatusTone } from "./planStatusLabel";
+
+const TONE_TRIGGER: Record<PlanStatusTone, string> = {
+ neutral: "border-control-border text-control",
+ error: "border-error/40 text-error",
+};
+
+export function PlanStatusAction({
+ issue,
+ reason,
+ checks,
+}: {
+ issue: Issue;
+ reason: PlanStatusReason;
+ checks: PlanCheckSummary;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [open, setOpen] = useState(false);
+ const [checksDrawerOpen, setChecksDrawerOpen] = useState(false);
+ const bypass = useBypassDeploy(issue, page.plan);
+ const tone = getPlanStatusTone(reason);
+ // Only the Review gate expands (to the approval flow); Checks is a static row
+ // with a View Details link. Open Review by default when it is the active gate.
+ const [reviewOpen, setReviewOpen] = useState(
+ reason === "in-review" || reason === "rejected"
+ );
+
+ // Literal t() calls (not t(dynamicKey)) so the i18n usage scanner sees them.
+ const labelText = (() => {
+ switch (reason) {
+ case "checking":
+ return t("plan.lifecycle.checking");
+ case "in-review":
+ // Reuse the shared review-status label so the header matches the plan
+ // list / issue surfaces ("Under review"), not a header-only "In review".
+ return t("common.under-review");
+ case "rejected":
+ return t("plan.lifecycle.rejected");
+ case "checks-failing":
+ return t("plan.lifecycle.checks-failing", { count: checks.error });
+ }
+ })();
+
+ return (
+ <>
+ <Popover onOpenChange={setOpen} open={open}>
+ <PopoverTrigger
+ render={
+ <button
+ className={cn(
+ "inline-flex h-9 shrink-0 items-center gap-x-1 rounded-full border px-3 text-sm hover:bg-control-bg/40",
+ TONE_TRIGGER[tone]
+ )}
+ type="button"
+ />
+ }
+ >
+ {labelText}
+ <ChevronDown className="size-4" />
+ </PopoverTrigger>
+ <PopoverContent
+ align="end"
+ className="w-[min(30rem,calc(100vw-2rem))] p-0"
+ >
+ <div className="flex max-h-[70vh] flex-col divide-y overflow-y-auto">
+ <ReviewGateRow
+ issue={issue}
+ onToggle={() => setReviewOpen((v) => !v)}
+ open={reviewOpen}
+ />
+ <ChecksGateRow
+ onViewDetails={() => {
+ setOpen(false);
+ setChecksDrawerOpen(true);
+ }}
+ summary={bypass.planCheckSummary}
+ />
+ </div>
+ <PlanStatusFooter
+ bypass={bypass}
+ issue={issue}
+ onBypass={() => {
+ setOpen(false);
+ bypass.triggerDeploy();
+ }}
+ reason={reason}
+ />
+ </PopoverContent>
+ </Popover>
+ <BypassAndDeploySheet bypass={bypass} issue={issue} />
+ {/* Rendered outside the popover so it survives the popover closing. */}
+ <PlanCheckResultsDrawer
+ includeRunFailure
+ onOpenChange={setChecksDrawerOpen}
+ open={checksDrawerOpen}
+ planCheckRuns={page.planCheckRuns}
+ />
+ </>
+ );
+}
+
+/* --------------------------- gate row shell ----------------------------- */
+
+// Shared icon-adjacent label for the gate rows: a title with an optional
+// subtitle beneath it.
+function GateLabel({ title, subtitle }: { title: string; subtitle: string }) {
+ return (
+ <span className="min-w-0 flex-1">
+ <span className="block text-sm font-medium leading-tight text-main">
+ {title}
+ </span>
+ {subtitle && (
+ <span className="mt-0.5 block truncate text-xs leading-tight text-control-light">
+ {subtitle}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function GateRow({
+ icon,
+ title,
+ subtitle,
+ open,
+ onToggle,
+ children,
+}: {
+ icon: ReactNode;
+ title: string;
+ subtitle: string;
+ open: boolean;
+ onToggle: () => void;
+ children: ReactNode;
+}) {
+ return (
+ <div>
+ <button
+ className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-control-bg/40"
+ onClick={onToggle}
+ type="button"
+ >
+ {icon}
+ <GateLabel subtitle={subtitle} title={title} />
+ <ChevronDown
+ className={cn(
+ "size-4 shrink-0 text-control-light transition-transform",
+ open && "rotate-180"
+ )}
+ />
+ </button>
+ {open && <div className="border-t bg-control-bg/20">{children}</div>}
+ </div>
+ );
+}
+
+/* ------------------------- review gate (ours) --------------------------- */
+
+function ReviewGateRow({
+ issue,
+ open,
+ onToggle,
+}: {
+ issue: Issue;
+ open: boolean;
+ onToggle: () => void;
+}) {
+ const { t } = useTranslation();
+ const roleList = useAppStore((state) => state.roleList);
+ const steps = useMemo(() => deriveSteps(issue), [issue]);
+ const rejectedStep = steps.find((step) => step.status === "rejected");
+ const currentStep = steps.find((step) => step.status === "current");
+ const rejecter = useAppStore((state) =>
+ rejectedStep?.approver
+ ? state.getUserByIdentifier(rejectedStep.approver)
+ : undefined
+ );
+ const approvedCount = steps.filter(
+ (step) => step.status === "approved"
+ ).length;
+
+ let icon: ReactNode;
+ let title: string;
+ let subtitle: string;
+ if (issue.approvalStatus === ApprovalStatus.REJECTED) {
+ icon = <CircleX className="size-5 shrink-0 text-error" />;
+ title = t("plan.lifecycle.gate-review-rejected");
+ subtitle = t("plan.review.approval-flow.rejected-by", {
+ user: (rejecter ?? unknownUser(rejectedStep?.approver ?? "")).title,
+ });
+ } else if (issue.approvalStatus === ApprovalStatus.APPROVED) {
+ icon = <CircleCheck className="size-5 shrink-0 text-success" />;
+ title = t("plan.lifecycle.gate-review-approved");
+ subtitle = t("plan.summary.n-of-m-approved", {
+ n: approvedCount,
+ m: steps.length,
+ });
+ } else if (issue.approvalStatus === ApprovalStatus.SKIPPED) {
+ icon = <CircleCheck className="size-5 shrink-0 text-success" />;
+ title = t("custom-approval.approval-flow.skip");
+ subtitle = "";
+ } else {
+ icon = <Clock3 className="size-5 shrink-0 text-control-light" />;
+ title = t("plan.lifecycle.gate-review-pending");
+ subtitle = currentStep
+ ? t("plan.lifecycle.review-waiting", {
+ role: displayRoleTitleFromList(currentStep.role, roleList),
+ })
+ : t("plan.summary.n-of-m-approved", {
+ n: approvedCount,
+ m: steps.length,
+ });
+ }
+
+ return (
+ <GateRow
+ icon={icon}
+ onToggle={onToggle}
+ open={open}
+ subtitle={subtitle}
+ title={title}
+ >
+ <ReviewApprovalFlow compact issue={issue} />
+ </GateRow>
+ );
+}
+
+/* -------------------------- checks gate (ours) -------------------------- */
+
+// Static (non-expandable) row: the header already summarizes the checks, so the
+// only affordance is a View Details link into the full drawer.
+function ChecksGateRow({
+ summary,
+ onViewDetails,
+}: {
+ summary: PlanCheckSummary;
+ onViewDetails: () => void;
+}) {
+ const { t } = useTranslation();
+
+ let icon: ReactNode;
+ let title: string;
+ let subtitle: string;
+ if (summary.error > 0) {
+ icon = <CircleX className="size-5 shrink-0 text-error" />;
+ title = t("plan.lifecycle.gate-checks-failed");
+ subtitle = t("plan.lifecycle.gate-checks-failed-sub", {
+ failing: summary.error,
+ passed: summary.success,
+ });
+ } else if (summary.running > 0) {
+ icon = (
+ <Loader2 className="size-5 shrink-0 animate-spin text-control-light" />
+ );
+ title = t("plan.lifecycle.gate-checks-running");
+ subtitle = t("plan.lifecycle.gate-checks-running-sub", {
+ running: summary.running,
+ passed: summary.success,
+ });
+ } else {
+ icon = <CircleCheck className="size-5 shrink-0 text-success" />;
+ title = t("plan.lifecycle.gate-checks-passed");
+ subtitle = t("plan.lifecycle.gate-checks-passed-sub", {
+ count: summary.success,
+ });
+ }
+
+ return (
+ <div className="flex items-center gap-3 px-4 py-3">
+ {icon}
+ <GateLabel subtitle={subtitle} title={title} />
+ {summary.total > 0 && (
+ <button
+ className="inline-flex shrink-0 items-center gap-0.5 text-xs text-accent hover:underline"
+ onClick={onViewDetails}
+ type="button"
+ >
+ {t("common.view-details")}
+ <ChevronRight className="size-3.5" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+/* --------------------------- footer (one action) ------------------------ */
+
+function PlanStatusFooter({
+ reason,
+ issue,
+ bypass,
+ onBypass,
+}: {
+ reason: PlanStatusReason;
+ issue: Issue;
+ bypass: ReturnType<typeof useBypassDeploy>;
+ onBypass: () => void;
+}) {
+ const { t } = useTranslation();
+ if (reason === "rejected") {
+ return (
+ <div className="border-t px-4 py-2.5">
+ <ReRequestGuidance issue={issue} />
+ </div>
+ );
+ }
+ if (bypass.weight === "none") {
+ return null;
+ }
+ // Two-state note: the rollout either auto-creates once review approves (nothing
+ // else blocking) or it wasn't created automatically (checks block it).
+ const note =
+ bypass.state.kind === "waiting-review" && bypass.checks.error === 0
+ ? t("plan.review.footer.rollout-auto-creates")
+ : t("plan.review.footer.rollout-not-created");
+ return (
+ <div className="flex items-center gap-x-3 border-t px-4 py-2.5">
+ <span className="flex-1 text-xs text-control-placeholder">{note}</span>
+ <BypassAction bypass={bypass} onClick={onBypass} />
+ </div>
+ );
+}
+
+// Mirrors ReviewRejectionBanner: guidance-prefix + accent inline link + suffix,
+// gated on the issue creator (non-readonly); plain text otherwise.
+function ReRequestGuidance({ issue }: { issue: Issue }) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const currentUser = useCurrentUser();
+ const [reRequesting, setReRequesting] = useState(false);
+ const canReRequest =
+ issue.creator === `${userNamePrefix}${currentUser?.email ?? ""}` &&
+ !page.readonly;
+
+ const handleReRequest = async () => {
+ if (reRequesting) return;
+ try {
+ setReRequesting(true);
+ const response = await issueServiceClientConnect.requestIssue(
+ create(RequestIssueRequestSchema, { name: issue.name })
+ );
+ page.patchState({ issue: response });
+ await page.refreshState();
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setReRequesting(false);
+ }
+ };
+
+ return (
+ <span className="text-xs leading-relaxed text-control-light">
+ {t("plan.review.rejection.guidance-prefix")}{" "}
+ {canReRequest ? (
+ <button
+ className="font-medium text-accent hover:underline disabled:opacity-60"
+ disabled={reRequesting}
+ onClick={() => void handleReRequest()}
+ type="button"
+ >
+ {t("plan.review.rejection.re-request-review")}
+ </button>
+ ) : (
+ <span>{t("plan.review.rejection.re-request-review")}</span>
+ )}{" "}
+ {t("plan.review.rejection.guidance-suffix")}
+ </span>
+ );
+}
+
+// The bypass override — always a quiet, muted link (a deliberate, demoted escape
+// hatch). The confirm sheet still enforces mandatory project gates.
+function BypassAction({
+ bypass,
+ onClick,
+}: {
+ bypass: ReturnType<typeof useBypassDeploy>;
+ onClick: () => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <button
+ className="inline-flex shrink-0 items-center gap-x-1 text-xs text-control-placeholder underline hover:text-control disabled:opacity-60"
+ disabled={bypass.creating}
+ onClick={onClick}
+ type="button"
+ >
+ {bypass.creating && <Loader2 className="size-3 animate-spin" />}
+ {t("plan.review.footer.bypass-and-deploy")}
+ </button>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/ReviewYourTurnAction.tsx b/frontend/src/react/pages/project/plan-detail/components/lifecycle/ReviewYourTurnAction.tsx
new file mode 100644
index 0000000000..6dfb1bbb89
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/ReviewYourTurnAction.tsx
@@ -0,0 +1,32 @@
+// The header advance when it is the current user's turn to review: a "Review"
+// button that opens the same Comment / Approve / Reject composer used by the
+// review section. The Review section stays the source of detail — this just
+// brings the action to the top-of-page lifecycle slot (BYT-9722).
+import { ChevronDown } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/react/components/ui/popover";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import { ReviewActionPopover } from "../review/ReviewActionPopover";
+
+export function ReviewYourTurnAction({ issue }: { issue: Issue }) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Popover onOpenChange={setOpen} open={open}>
+ <PopoverTrigger render={<Button className="shrink-0 gap-x-1.5" />}>
+ {t("plan.review.action")}
+ <ChevronDown className="size-4" />
+ </PopoverTrigger>
+ <PopoverContent align="end" className="px-4 py-4">
+ <ReviewActionPopover issue={issue} onClose={() => setOpen(false)} />
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.test.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.test.ts
new file mode 100644
index 0000000000..b2d1bb1931
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.test.ts
@@ -0,0 +1,37 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import {
+ StageSchema,
+ Task_Status,
+ TaskSchema,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import { stageHasFailedOrCanceledTasks } from "./frontierStage";
+
+const stage = (...statuses: Task_Status[]) =>
+ create(StageSchema, {
+ tasks: statuses.map((status) => create(TaskSchema, { status })),
+ });
+
+describe("stageHasFailedOrCanceledTasks", () => {
+ test("false when all runnable tasks are fresh (not started)", () => {
+ expect(stageHasFailedOrCanceledTasks(stage(Task_Status.NOT_STARTED))).toBe(
+ false
+ );
+ expect(
+ stageHasFailedOrCanceledTasks(
+ stage(Task_Status.NOT_STARTED, Task_Status.DONE)
+ )
+ ).toBe(false);
+ });
+
+ test("true when any task previously ran (failed or canceled)", () => {
+ expect(
+ stageHasFailedOrCanceledTasks(
+ stage(Task_Status.NOT_STARTED, Task_Status.FAILED)
+ )
+ ).toBe(true);
+ expect(stageHasFailedOrCanceledTasks(stage(Task_Status.CANCELED))).toBe(
+ true
+ );
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts
new file mode 100644
index 0000000000..012c63999b
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/frontierStage.ts
@@ -0,0 +1,45 @@
+// Frontier-stage helpers shared by the deploy section and the lifecycle header.
+// The "frontier" is the first stage that is not yet complete — the single stage
+// the header's lifecycle advance points at. A stage is complete when every task
+// is done or skipped.
+import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";
+import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";
+import { RUNNABLE_TASK_STATUSES } from "../../../issue-detail/utils/rollout";
+
+export function isStageComplete(stage: Stage): boolean {
+ return stage.tasks.every(
+ (task) =>
+ task.status === Task_Status.DONE || task.status === Task_Status.SKIPPED
+ );
+}
+
+// The first non-complete stage, or undefined when every stage is complete.
+export function getFrontierStage(
+ rollout: Rollout | undefined
+): Stage | undefined {
+ return rollout?.stages.find((stage) => !isStageComplete(stage));
+}
+
+export function stageHasRunnableTasks(stage: Stage): boolean {
+ return stage.tasks.some((task) =>
+ RUNNABLE_TASK_STATUSES.includes(task.status)
+ );
+}
+
+// A task that already executed once (failed or canceled) — running the stage
+// again is a re-run rather than a first run. Mirrors the per-task "Retry" label,
+// which keys off a prior execution. Named in full so it isn't mistaken for
+// stageHasRunningTasks.
+export function stageHasFailedOrCanceledTasks(stage: Stage): boolean {
+ return stage.tasks.some(
+ (task) =>
+ task.status === Task_Status.FAILED || task.status === Task_Status.CANCELED
+ );
+}
+
+export function stageHasRunningTasks(stage: Stage): boolean {
+ return stage.tasks.some(
+ (task) =>
+ task.status === Task_Status.RUNNING || task.status === Task_Status.PENDING
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts
new file mode 100644
index 0000000000..9bdb2b88fa
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.test.ts
@@ -0,0 +1,205 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";
+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
+import {
+ RolloutSchema,
+ StageSchema,
+ Task_Status,
+ TaskSchema,
+} from "@/types/proto-es/v1/rollout_service_pb";
+import type { PlanCheckSummary } from "../../utils/phaseSummary";
+import {
+ type PlanLifecycleResolverInput,
+ resolvePlanLifecycleHeaderState,
+} from "./planLifecycleHeaderState";
+
+const checks = (error = 0, running = 0, success = 8): PlanCheckSummary => ({
+ error,
+ running,
+ success,
+ total: error + running + success,
+ warning: 0,
+});
+
+const base: PlanLifecycleResolverInput = {
+ isCreating: false,
+ isGitOpsPlan: false,
+ readonly: false,
+ planState: State.ACTIVE,
+ hasIssue: true,
+ issueStatus: IssueStatus.OPEN,
+ approvalStatus: ApprovalStatus.PENDING,
+ hasCurrentStep: false,
+ isCurrentUserCandidate: false,
+ checks: checks(),
+ hasRollout: false,
+ rollout: undefined,
+};
+
+const resolve = (over: Partial<PlanLifecycleResolverInput> = {}) =>
+ resolvePlanLifecycleHeaderState({ ...base, ...over });
+
+const stage = (name: string, statuses: Task_Status[]) =>
+ create(StageSchema, {
+ name,
+ tasks: statuses.map((status) => create(TaskSchema, { status })),
+ });
+
+const rollout = (...stages: ReturnType<typeof stage>[]) =>
+ create(RolloutSchema, { stages });
+
+describe("resolvePlanLifecycleHeaderState — draft & terminal", () => {
+ test("creating", () => {
+ expect(resolve({ isCreating: true }).kind).toBe("create");
+ });
+
+ test("closed plan is a terminal stamp", () => {
+ expect(resolve({ planState: State.DELETED }).kind).toBe("closed");
+ });
+
+ test("no issue yet -> ready for review", () => {
+ expect(resolve({ hasIssue: false }).kind).toBe("ready-for-review");
+ });
+
+ test("canceled review with no rollout -> closed", () => {
+ expect(resolve({ issueStatus: IssueStatus.CANCELED }).kind).toBe("closed");
+ });
+
+ test("canceled review is terminal even with a rollout (not deploy)", () => {
+ expect(
+ resolve({
+ issueStatus: IssueStatus.CANCELED,
+ hasRollout: true,
+ rollout: rollout(stage("s1", [Task_Status.NOT_STARTED])),
+ }).kind
+ ).toBe("closed");
+ });
+
+ test("gitops plan with no rollout -> none", () => {
+ expect(resolve({ isGitOpsPlan: true, hasIssue: false }).kind).toBe("none");
+ });
+});
+
+describe("resolvePlanLifecycleHeaderState — review", () => {
+ test("approval still generating -> review-generating", () => {
+ expect(resolve({ approvalStatus: ApprovalStatus.CHECKING }).kind).toBe(
+ "review-generating"
+ );
+ });
+
+ test("pending + current user's turn -> review-your-turn", () => {
+ expect(
+ resolve({ hasCurrentStep: true, isCurrentUserCandidate: true }).kind
+ ).toBe("review-your-turn");
+ });
+
+ test("readonly suppresses the your-turn advance -> plan-status", () => {
+ const state = resolve({
+ hasCurrentStep: true,
+ isCurrentUserCandidate: true,
+ readonly: true,
+ });
+ expect(state.kind).toBe("plan-status");
+ });
+
+ test("pending + not your turn + clean checks -> in-review", () => {
+ const state = resolve({});
+ expect(state).toMatchObject({ kind: "plan-status", reason: "in-review" });
+ });
+
+ test("pending + checks failing -> still in-review (review is the active gate)", () => {
+ const state = resolve({ checks: checks(2) });
+ expect(state).toMatchObject({ kind: "plan-status", reason: "in-review" });
+ });
+
+ test("rejected -> plan-status rejected", () => {
+ const state = resolve({ approvalStatus: ApprovalStatus.REJECTED });
+ expect(state).toMatchObject({ kind: "plan-status", reason: "rejected" });
+ });
+});
+
+describe("resolvePlanLifecycleHeaderState — pre-deploy gates", () => {
+ test("approved + checks failing -> checks-failing", () => {
+ const state = resolve({
+ approvalStatus: ApprovalStatus.APPROVED,
+ checks: checks(1),
+ });
+ expect(state).toMatchObject({
+ kind: "plan-status",
+ reason: "checks-failing",
+ });
+ });
+
+ test("approved + checks still running -> checking", () => {
+ const state = resolve({
+ approvalStatus: ApprovalStatus.APPROVED,
+ checks: checks(0, 2),
+ });
+ expect(state).toMatchObject({ kind: "plan-status", reason: "checking" });
+ });
+
+ test("approved + all gates passed, no rollout yet -> preparing-rollout", () => {
+ expect(resolve({ approvalStatus: ApprovalStatus.APPROVED }).kind).toBe(
+ "preparing-rollout"
+ );
+ // Skipped approval behaves the same as approved.
+ expect(resolve({ approvalStatus: ApprovalStatus.SKIPPED }).kind).toBe(
+ "preparing-rollout"
+ );
+ });
+});
+
+describe("resolvePlanLifecycleHeaderState — deploy", () => {
+ const deployBase: Partial<PlanLifecycleResolverInput> = {
+ hasRollout: true,
+ approvalStatus: ApprovalStatus.APPROVED,
+ issueStatus: IssueStatus.DONE,
+ };
+
+ test("frontier with runnable tasks -> run-stage at the frontier", () => {
+ const state = resolve({
+ ...deployBase,
+ rollout: rollout(
+ stage("stages/1", [Task_Status.DONE]),
+ stage("stages/2", [Task_Status.NOT_STARTED])
+ ),
+ });
+ expect(state.kind).toBe("run-stage");
+ expect(state.kind === "run-stage" && state.stage.name).toBe("stages/2");
+ });
+
+ test("frontier with only in-progress tasks -> running-stage", () => {
+ const state = resolve({
+ ...deployBase,
+ rollout: rollout(stage("stages/1", [Task_Status.RUNNING])),
+ });
+ expect(state).toMatchObject({ kind: "running-stage" });
+ });
+
+ test("every stage complete -> deployed", () => {
+ expect(
+ resolve({
+ ...deployBase,
+ rollout: rollout(
+ stage("stages/1", [Task_Status.DONE]),
+ stage("stages/2", [Task_Status.SKIPPED])
+ ),
+ }).kind
+ ).toBe("deployed");
+ });
+
+ test("rollout exists but is empty -> none", () => {
+ expect(resolve({ ...deployBase, rollout: rollout() }).kind).toBe("none");
+ });
+
+ test("deploy takes priority over a pending approvalStatus once a rollout exists", () => {
+ // hasRollout short-circuits to deploy resolution before the review block.
+ const state = resolve({
+ hasRollout: true,
+ approvalStatus: ApprovalStatus.PENDING,
+ rollout: rollout(stage("stages/1", [Task_Status.NOT_STARTED])),
+ });
+ expect(state.kind).toBe("run-stage");
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts
new file mode 100644
index 0000000000..32b55b2552
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planLifecycleHeaderState.ts
@@ -0,0 +1,188 @@
+// Resolver for the plan-detail header's single "lifecycle slot" (BYT-9722).
+//
+// One pure function reads the plan's current state and decides the single safe
+// next action / status the header shows. It is evaluated top to bottom: the
+// first matching state owns the slot. Async, IAM-derived inputs (whether it is
+// the user's turn to review, whether they may run the frontier stage) are
+// computed by usePlanLifecycleHeader and passed in as plain values so this stays
+// pure and unit-testable.
+import { ApprovalStatus, State } from "@/types/proto-es/v1/common_pb";
+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
+import type { Rollout, Stage } from "@/types/proto-es/v1/rollout_service_pb";
+import type { PlanCheckSummary } from "../../utils/phaseSummary";
+import {
+ getFrontierStage,
+ stageHasRunnableTasks,
+ stageHasRunningTasks,
+} from "./frontierStage";
+
+// The blocker/readiness label shown when the slot is a read-only status rather
+// than an advance action. The component maps each reason to copy + tone.
+// One gate at a time: review is the active gate first ("In review" regardless of
+// checks); checks only become the headline once review has passed.
+export type PlanStatusReason =
+ | "checking" // approved, plan checks still running
+ | "in-review" // review pending (the active gate)
+ | "rejected" // review rejected
+ | "checks-failing"; // review approved, but plan checks failed
+
+export type PlanLifecycleHeaderState =
+ // Nothing safe to surface (GitOps with no rollout, inconsistent backend
+ // state). The slot renders empty and detail stays in the sections.
+ | { kind: "none" }
+ // Draft & review setup.
+ | { kind: "create" }
+ | { kind: "ready-for-review" }
+ | { kind: "closed" } // terminal stamp
+ // Review.
+ | { kind: "review-generating" } // disabled + loading
+ | { kind: "review-your-turn" }
+ | { kind: "plan-status"; reason: PlanStatusReason; checks: PlanCheckSummary }
+ // Pre-deploy → rollout creation.
+ | { kind: "preparing-rollout" }
+ // Deploy (frontier stage). Run permission is enforced by the run confirmation
+ // sheet (canRolloutTasks), so the resolver only decides which stage is the
+ // frontier advance — it does not gate on IAM.
+ | { kind: "run-stage"; stage: Stage }
+ | { kind: "running-stage"; stage: Stage }
+ | { kind: "deployed" }; // terminal stamp
+
+export interface PlanLifecycleResolverInput {
+ isCreating: boolean;
+ isGitOpsPlan: boolean;
+ readonly: boolean;
+ planState: State;
+ hasIssue: boolean;
+
+ issueStatus: IssueStatus | undefined;
+ approvalStatus: ApprovalStatus;
+ hasCurrentStep: boolean;
+ isCurrentUserCandidate: boolean;
+
+ checks: PlanCheckSummary;
+
+ hasRollout: boolean;
+ rollout: Rollout | undefined;
+}
+
+function resolveDeploy(
+ input: PlanLifecycleResolverInput
+): PlanLifecycleHeaderState {
+ const { rollout } = input;
+ // A rollout without deployable stages is an inconsistent backend state, not a
+ // user workflow — defer to the Deploy section rather than guess an action.
+ if (!rollout || rollout.stages.length === 0) {
+ return { kind: "none" };
+ }
+ const frontier = getFrontierStage(rollout);
+ if (!frontier) {
+ return { kind: "deployed" };
+ }
+ if (stageHasRunnableTasks(frontier)) {
+ return { kind: "run-stage", stage: frontier };
+ }
+ if (stageHasRunningTasks(frontier)) {
+ return { kind: "running-stage", stage: frontier };
+ }
+ // Non-complete frontier with nothing runnable or running: defer to Deploy.
+ return { kind: "none" };
+}
+
+export function resolvePlanLifecycleHeaderState(
+ input: PlanLifecycleResolverInput
+): PlanLifecycleHeaderState {
+ // Brand-new plan being created.
+ if (input.isCreating) {
+ return { kind: "create" };
+ }
+
+ // Terminal: closed plan. (Close-after-issue/rollout is future work, BYT-9204.)
+ if (input.planState === State.DELETED) {
+ return { kind: "closed" };
+ }
+
+ // A canceled review is terminal even after a rollout was created — surface the
+ // closed stamp, not deploy actions (matches the issue detail page). This must
+ // precede the rollout branch, which otherwise wins on a stale/orphaned rollout.
+ if (input.issueStatus === IssueStatus.CANCELED) {
+ return { kind: "closed" };
+ }
+
+ // Once a rollout exists, the review gates are settled and the lifecycle is in
+ // deploy — the header summarizes the frontier stage.
+ if (input.hasRollout) {
+ return resolveDeploy(input);
+ }
+
+ // GitOps/release-backed plans bypass review; with no rollout yet there is no
+ // safe header advance to offer.
+ if (input.isGitOpsPlan) {
+ return { kind: "none" };
+ }
+
+ // No review issue yet: the draft can be submitted for review.
+ if (!input.hasIssue) {
+ return { kind: "ready-for-review" };
+ }
+
+ // Issue exists but is no longer open (review canceled) and never produced a
+ // rollout: the lifecycle ended.
+ if (
+ input.issueStatus !== undefined &&
+ input.issueStatus !== IssueStatus.OPEN
+ ) {
+ return { kind: "closed" };
+ }
+
+ // Approval flow still being generated — no safe action until it resolves.
+ if (input.approvalStatus === ApprovalStatus.CHECKING) {
+ return { kind: "review-generating" };
+ }
+
+ // Rejected review.
+ if (input.approvalStatus === ApprovalStatus.REJECTED) {
+ return { kind: "plan-status", reason: "rejected", checks: input.checks };
+ }
+
+ // Approved / skipped: pre-deploy gate evaluation, then rollout creation.
+ if (
+ input.approvalStatus === ApprovalStatus.APPROVED ||
+ input.approvalStatus === ApprovalStatus.SKIPPED
+ ) {
+ if (input.checks.error > 0) {
+ return {
+ kind: "plan-status",
+ reason: "checks-failing",
+ checks: input.checks,
+ };
+ }
+ if (input.checks.running > 0) {
+ return { kind: "plan-status", reason: "checking", checks: input.checks };
+ }
+ // All required gates passed; the backend auto-creates the rollout. Show a
+ // transient progress state until it arrives, then resolveDeploy takes over.
+ return { kind: "preparing-rollout" };
+ }
+
+ // Pending review: the advance is the current reviewer's to take.
+ if (input.hasCurrentStep && input.isCurrentUserCandidate && !input.readonly) {
+ return { kind: "review-your-turn" };
+ }
+ // Review is the active gate — surface it plainly regardless of check state.
+ return { kind: "plan-status", reason: "in-review", checks: input.checks };
+}
+
+// Whether the right-hand lifecycle slot renders a primary action/status control.
+// The terminal states (closed / deployed) render as a stamp left of the title,
+// and "none" is empty — in those cases the header surfaces a secondary action
+// directly instead of tucking it into the overflow menu. Kept next to the
+// resolver so this stays in sync with the states it produces.
+export function slotHasPrimaryControl(
+ state: PlanLifecycleHeaderState
+): boolean {
+ return (
+ state.kind !== "none" &&
+ state.kind !== "closed" &&
+ state.kind !== "deployed"
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.test.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.test.ts
new file mode 100644
index 0000000000..8430461daf
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, test } from "vitest";
+import { getPlanStatusTone } from "./planStatusLabel";
+
+describe("getPlanStatusTone", () => {
+ test("checking / in-review are neutral", () => {
+ expect(getPlanStatusTone("checking")).toBe("neutral");
+ expect(getPlanStatusTone("in-review")).toBe("neutral");
+ });
+
+ test("rejected / checks-failing are errors (hard blockers)", () => {
+ expect(getPlanStatusTone("rejected")).toBe("error");
+ expect(getPlanStatusTone("checks-failing")).toBe("error");
+ });
+});
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.ts
new file mode 100644
index 0000000000..d597589174
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/planStatusLabel.ts
@@ -0,0 +1,17 @@
+// Maps a Plan status reason to its tone. Kept pure and separate from the
+// component so the mapping is unit-testable; the label text itself is rendered
+// with literal t() calls in PlanStatusAction so the i18n usage scanner sees it.
+import type { PlanStatusReason } from "./planLifecycleHeaderState";
+
+export type PlanStatusTone = "neutral" | "error";
+
+export function getPlanStatusTone(reason: PlanStatusReason): PlanStatusTone {
+ switch (reason) {
+ case "checking":
+ case "in-review":
+ return "neutral";
+ case "rejected":
+ case "checks-failing":
+ return "error";
+ }
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
new file mode 100644
index 0000000000..03602e6053
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/usePlanLifecycleHeader.ts
@@ -0,0 +1,87 @@
+// Gathers the async / IAM-derived inputs the pure resolver needs (whose turn it
+// is to review, whether the user may run the frontier stage) and feeds them into
+// resolvePlanLifecycleHeaderState. Mirrors how ReviewReadinessFooter computes its
+// inputs before calling computeReadinessFooterState.
+import { create } from "@bufbuild/protobuf";
+import { useMemo } from "react";
+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import { IssueSchema } from "@/types/proto-es/v1/issue_service_pb";
+import type { PlanDetailPageState } from "../../shell/hooks/types";
+import { getPlanCheckSummary } from "../../utils/phaseSummary";
+import { isReleaseBackedPlan } from "../../utils/spec";
+import { deriveSteps } from "../review/ReviewApprovalFlow";
+import { useApprovalCandidates } from "../review/useApprovalCandidates";
+import {
+ type PlanLifecycleHeaderState,
+ resolvePlanLifecycleHeaderState,
+} from "./planLifecycleHeaderState";
+
+// Stable placeholder so the candidate hook can run unconditionally (rules of
+// hooks) when no issue exists yet; an empty role resolves to no candidates.
+const EMPTY_ISSUE: Issue = create(IssueSchema, {});
+
+export function usePlanLifecycleHeader(
+ page: PlanDetailPageState
+): PlanLifecycleHeaderState {
+ const issue = page.issue;
+ const currentRole = useMemo(
+ () =>
+ issue
+ ? (deriveSteps(issue).find((step) => step.status === "current")?.role ??
+ "")
+ : "",
+ [issue]
+ );
+ const { isCurrentUserCandidate } = useApprovalCandidates(
+ issue ?? EMPTY_ISSUE,
+ page.projectId,
+ currentRole
+ );
+
+ const isGitOpsPlan = useMemo(
+ () => isReleaseBackedPlan(page.plan.specs),
+ [page.plan.specs]
+ );
+ const checks = useMemo(() => getPlanCheckSummary(page.plan), [page.plan]);
+
+ // Depend on the primitives the resolver actually reads, not the whole
+ // `issue` object — polling replaces `page.issue` with a fresh reference every
+ // tick, which would re-run the resolver and re-render the header even when the
+ // status/approval it consumes is unchanged.
+ const hasIssue = !!page.plan.issue || !!page.issue;
+ const issueStatus = page.issue?.status;
+ const approvalStatus =
+ page.issue?.approvalStatus ?? ApprovalStatus.APPROVAL_STATUS_UNSPECIFIED;
+
+ return useMemo(
+ () =>
+ resolvePlanLifecycleHeaderState({
+ isCreating: page.isCreating,
+ isGitOpsPlan,
+ readonly: page.readonly,
+ planState: page.plan.state,
+ hasIssue,
+ issueStatus,
+ approvalStatus,
+ hasCurrentStep: currentRole !== "",
+ isCurrentUserCandidate,
+ checks,
+ hasRollout: !!page.rollout,
+ rollout: page.rollout,
+ }),
+ [
+ approvalStatus,
+ checks,
+ currentRole,
+ hasIssue,
+ isCurrentUserCandidate,
+ isGitOpsPlan,
+ issueStatus,
+ page.isCreating,
+ page.plan.state,
+ page.readonly,
+ page.rollout,
+ ]
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/lifecycle/useStageTitle.ts b/frontend/src/react/pages/project/plan-detail/components/lifecycle/useStageTitle.ts
new file mode 100644
index 0000000000..ee07844aba
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/lifecycle/useStageTitle.ts
@@ -0,0 +1,13 @@
+import { useMemo } from "react";
+import { useAppStore } from "@/react/stores/app";
+import type { Stage } from "@/types/proto-es/v1/rollout_service_pb";
+
+// Resolve a stage's display title (its environment title), subscribing to
+// environmentList so it updates once environments load. Mirrors DeployStageCard.
+export function useStageTitle(stage: Stage): string {
+ const environmentList = useAppStore((state) => state.environmentList);
+ return useMemo(
+ () => useAppStore.getState().getEnvironmentByName(stage.environment).title,
+ [environmentList, stage.environment]
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx
index e76783c793..fb788b9bda 100644
--- a/frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx
@@ -51,7 +51,16 @@ export function deriveSteps(issue: Issue): FlowStep[] {
});
}
-export function ReviewApprovalFlow({ issue }: { issue: Issue }) {
+export function ReviewApprovalFlow({
+ issue,
+ compact = false,
+}: {
+ issue: Issue;
+ // Fold to at most four nodes (approved chip + two waiting + pending chip),
+ // rendered vertically. Used by the header Plan status popover, which is too
+ // narrow for the full flow.
+ compact?: boolean;
+}) {
const { t } = useTranslation();
const hostRef = useRef<HTMLDivElement>(null);
const [width, setWidth] = useState(0);
@@ -91,6 +100,14 @@ export function ReviewApprovalFlow({ issue }: { issue: Issue }) {
);
}
+ if (compact) {
+ return (
+ <div className="min-w-0 px-4 py-3">
+ <CompactVerticalFlow issue={issue} steps={steps} />
+ </div>
+ );
+ }
+
return (
<div ref={hostRef} className="min-w-0 px-4 py-3">
{layout.kind === "vertical" ? (
@@ -566,3 +583,99 @@ function PendingPopoverRow({ issue, step }: { issue: Issue; step: FlowStep }) {
</div>
);
}
+
+// Compact fold used by the header Plan status popover: collapse all approved
+// steps into one chip, name up to two upcoming (waiting) steps, and fold the
+// rest into a "N pending" chip — at most four rows, stacked vertically.
+function CompactVerticalFlow({
+ issue,
+ steps,
+}: {
+ issue: Issue;
+ steps: FlowStep[];
+}) {
+ const approved = steps.filter((step) => step.status === "approved");
+ const rest = steps.filter((step) => step.status !== "approved");
+ const named = rest.slice(0, 2);
+ const folded = rest.slice(2);
+ const hasFolded = folded.length > 0;
+
+ // Rows render in order: an approved fold, up to two named steps, then a pending
+ // fold. `isLast` (which drops the trailing connector) is a self-contained
+ // expression per row, so it doesn't depend on push order.
+ const rows: ReactNode[] = [];
+ if (approved.length > 0) {
+ rows.push(
+ <ApprovedFoldRow
+ isLast={named.length === 0 && !hasFolded}
+ key="approved-fold"
+ steps={approved}
+ />
+ );
+ }
+ named.forEach((step, i) => {
+ rows.push(
+ <FlowNode
+ isLast={i === named.length - 1 && !hasFolded}
+ issue={issue}
+ key={`step-${step.index}`}
+ step={step}
+ vertical
+ />
+ );
+ });
+ if (hasFolded) {
+ rows.push(<PendingFoldRow isLast key="pending-fold" steps={folded} />);
+ }
+
+ return <div className="flex flex-col">{rows}</div>;
+}
+
+function ApprovedFoldRow({
+ steps,
+ isLast,
+}: {
+ steps: FlowStep[];
+ isLast: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex min-w-0 items-start gap-x-2">
+ <div className="flex flex-col items-center self-stretch">
+ <StatusDot index={0} status="approved" />
+ {!isLast && <div className="w-px flex-1 bg-control-border" />}
+ </div>
+ <div className={cn("min-w-0", !isLast && "pb-3")}>
+ <span className="text-sm font-medium text-control">
+ {t("plan.review.approval-flow.n-approved", { n: steps.length })}
+ </span>
+ <div className="mt-1 flex h-4 items-center">
+ <ChipAvatars principals={steps.map((step) => step.approver ?? "")} />
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function PendingFoldRow({
+ steps,
+ isLast,
+}: {
+ steps: FlowStep[];
+ isLast: boolean;
+}) {
+ const { t } = useTranslation();
+ return (
+ <div className="flex min-w-0 items-start gap-x-2">
+ <div className="flex flex-col items-center self-stretch">
+ <div className="size-6 shrink-0 rounded-full border-2 border-dashed border-control-border" />
+ {!isLast && <div className="w-px flex-1 bg-control-border" />}
+ </div>
+ <div className={cn("min-w-0", !isLast && "pb-3")}>
+ <span className="text-sm font-medium text-control">
+ {t("plan.review.approval-flow.n-pending", { n: steps.length })}
+ </span>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx
index 316d3826dd..2a31e172e3 100644
--- a/frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx
@@ -1,32 +1,10 @@
-import { create } from "@bufbuild/protobuf";
import { Ban, CircleCheck, CircleX, Clock3, Loader2 } from "lucide-react";
-import { Fragment, type ReactNode, useMemo, useState } from "react";
+import { Fragment, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
-import { rolloutServiceClientConnect } from "@/connect";
-import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
-import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
-import { Checkbox } from "@/react/components/ui/checkbox";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from "@/react/components/ui/sheet";
-import { pushNotification } from "@/store";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
-import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
-import { usePlanDetailContext } from "../../shell/PlanDetailContext";
-import { getPlanCheckSummary } from "../../utils/phaseSummary";
-import { getPlanCheckSummaryWithFallback } from "../../utils/planCheck";
-import { ReviewApprovalFlow } from "./ReviewApprovalFlow";
-import {
- computeBypassActionWeight,
- computeReadinessFooterState,
-} from "./readinessFooterState";
+import { BypassAndDeploySheet, useBypassDeploy } from "./bypassDeploy";
export function ReviewReadinessFooter({
issue,
@@ -36,120 +14,11 @@ export function ReviewReadinessFooter({
plan: Plan;
}) {
const { t } = useTranslation();
- const page = usePlanDetailContext();
- const [creating, setCreating] = useState(false);
- const [confirmOpen, setConfirmOpen] = useState(false);
- const [acknowledge, setAcknowledge] = useState(false);
-
- const checks = useMemo(() => getPlanCheckSummary(plan), [plan]);
- const state = useMemo(
- () =>
- computeReadinessFooterState({
- hasRollout: plan.hasRollout,
- issueStatus: issue.status,
- approvalStatus: issue.approvalStatus,
- checks,
- }),
- [checks, issue.approvalStatus, issue.status, plan.hasRollout]
- );
- const weight = computeBypassActionWeight({
- state: state.kind,
- canCreateRollout: page.projectCanCreateRollout && !page.readonly,
- requireIssueApproval: page.projectRequireIssueApproval,
- });
- // Must run before the "hidden" early return below — otherwise the hook count
- // drops when a deploy flips the footer to hidden, and React throws "rendered
- // fewer hooks than expected" on the success path.
- const planCheckSummary = useMemo(
- () =>
- getPlanCheckSummaryWithFallback(
- page.planCheckRuns,
- plan.planCheckRunStatusCount
- ),
- [page.planCheckRuns, plan.planCheckRunStatusCount]
- );
+ const bypass = useBypassDeploy(issue, plan);
+ const { state, checks, weight, creating, triggerDeploy } = bypass;
if (state.kind === "hidden") return null;
- const openConfirm = () => {
- setAcknowledge(false);
- setConfirmOpen(true);
- };
-
- // When the review has passed and every plan check is green there is nothing
- // to bypass or confirm — deploy straight away. Any other case (failed/running
- // checks, or bypassing review) opens the confirm sheet.
- const triggerDeploy = () => {
- if (state.kind === "all-gates-passed" && checks.running === 0) {
- void bypass();
- } else {
- openConfirm();
- }
- };
-
- const bypass = async () => {
- if (creating) return;
- try {
- setCreating(true);
- await rolloutServiceClientConnect.createRollout(
- create(CreateRolloutRequestSchema, { parent: plan.name })
- );
- setConfirmOpen(false);
- await page.refreshState();
- } catch (error) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.failed"),
- description: String(error),
- });
- } finally {
- setCreating(false);
- }
- };
-
- // The project's enforced gates and whether each is satisfied. Enforced gates
- // are HARD: if any is unmet, bypass-and-deploy is blocked entirely — you can
- // only bypass the project's *optional* requirements, never its mandatory ones.
- const reviewApproved =
- state.kind === "all-gates-passed" ||
- state.kind === "approved-checks-failed";
- const gates: { label: string; met: boolean }[] = [];
- if (page.projectRequireIssueApproval) {
- gates.push({
- label: t("plan.review.footer.gate-approval"),
- met: reviewApproved,
- });
- }
- if (page.projectRequirePlanCheckNoError) {
- gates.push({
- label: t("plan.review.footer.gate-no-failed-checks"),
- met: checks.error === 0,
- });
- }
- const gatesBlocked = gates.some((gate) => !gate.met);
-
- // Soft items this bypass would skip (NOT enforced by project policy) — shown
- // as warnings the user must acknowledge. Moot when a hard gate blocks deploy.
- const warnings: string[] = [];
- if (!page.projectRequireIssueApproval) {
- if (state.kind === "rejected") {
- warnings.push(t("plan.review.footer.confirm-review-rejected"));
- } else if (state.kind === "waiting-review") {
- warnings.push(t("plan.review.footer.confirm-review-not-approved"));
- }
- }
- if (!page.projectRequirePlanCheckNoError && checks.error > 0) {
- warnings.push(
- t("plan.review.footer.confirm-checks-failed", { count: checks.error })
- );
- }
- if (checks.running > 0) {
- warnings.push(t("plan.review.footer.confirm-checks-running"));
- }
- const needAck = warnings.length > 0;
- const confirmDisabled = creating || gatesBlocked || (needAck && !acknowledge);
-
// Each non-zero count is its own "·"-separated segment with a leading dot, so
// empty buckets (e.g. "0 checks passed") are dropped rather than shown.
const checkSegments: { key: string; node: ReactNode }[] = [];
@@ -264,94 +133,7 @@ export function ReviewReadinessFooter({
</Button>
)}
- <Sheet
- onOpenChange={(open) => {
- setConfirmOpen(open);
- if (!open) setAcknowledge(false);
- }}
- open={confirmOpen}
- >
- <SheetContent
- className="w-[28rem] max-w-[calc(100vw-2rem)]"
- width="standard"
- >
- <SheetHeader>
- <SheetTitle>{t("plan.review.footer.bypass-and-deploy")}</SheetTitle>
- </SheetHeader>
- <SheetBody className="gap-y-4">
- {gatesBlocked ? (
- <Alert
- description={
- <ul className="list-inside list-disc text-sm">
- {gates
- .filter((gate) => !gate.met)
- .map((gate) => (
- <li key={gate.label}>{gate.label}</li>
- ))}
- </ul>
- }
- title={t("plan.review.footer.gates-blocked")}
- variant="error"
- />
- ) : (
- needAck && (
- <Alert
- variant="warning"
- description={
- <ul className="list-inside list-disc text-sm">
- {warnings.map((warning) => (
- <li key={warning}>{warning}</li>
- ))}
- </ul>
- }
- title={t("plan.review.footer.confirm-bypass-title")}
- />
- )
- )}
-
- <div className="flex flex-col gap-y-1">
- <h3 className="textlabel uppercase">
- {t("plan.navigator.review")}
- </h3>
- <div className="rounded-md border">
- <ReviewApprovalFlow issue={issue} />
- </div>
- </div>
-
- <PlanCheckSection
- canRun={false}
- includeRunFailure
- isRunning={false}
- onRun={() => {}}
- planCheckRuns={page.planCheckRuns}
- summaryOverride={planCheckSummary}
- />
- </SheetBody>
- <SheetFooter className="justify-between">
- {!gatesBlocked && needAck ? (
- <label className="flex items-center gap-x-2 text-sm text-control">
- <Checkbox
- checked={acknowledge}
- disabled={creating}
- onCheckedChange={setAcknowledge}
- />
- <span>{t("plan.review.footer.confirm-acknowledge")}</span>
- </label>
- ) : (
- <div />
- )}
- <div className="flex items-center gap-x-2">
- <Button onClick={() => setConfirmOpen(false)} variant="ghost">
- {t("common.cancel")}
- </Button>
- <Button disabled={confirmDisabled} onClick={() => void bypass()}>
- {creating && <Loader2 className="size-4 animate-spin" />}
- {t("plan.navigator.deploy")}
- </Button>
- </div>
- </SheetFooter>
- </SheetContent>
- </Sheet>
+ <BypassAndDeploySheet issue={issue} bypass={bypass} />
</div>
);
}
diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx
index 0ff3339936..a2e3cd5447 100644
--- a/frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx
+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx
@@ -1,87 +1,45 @@
-import { ChevronDown, Info, ShieldAlert, ShieldCheck } from "lucide-react";
-import { useMemo, useState } from "react";
+import { Info, ShieldAlert, ShieldCheck } from "lucide-react";
import { useTranslation } from "react-i18next";
import { RouterLink } from "@/react/components/RouterLink";
-import { Button } from "@/react/components/ui/button";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@/react/components/ui/popover";
import { Tooltip } from "@/react/components/ui/tooltip";
import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";
-import { ApprovalStatus, RiskLevel } from "@/types/proto-es/v1/common_pb";
+import { RiskLevel } from "@/types/proto-es/v1/common_pb";
import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";
import { extractIssueUID } from "@/utils/v1/issue/issue";
import { usePlanDetailContext } from "../../shell/PlanDetailContext";
-import { ReviewActionPopover } from "./ReviewActionPopover";
-import { deriveSteps } from "./ReviewApprovalFlow";
-import { useApprovalCandidates } from "./useApprovalCandidates";
+// The Review advance (Comment / Approve / Reject) lives in the page header's
+// lifecycle slot now (BYT-9722), so this section header is title + metadata only
+// — no duplicate Review action.
export function PlanReviewSectionHeader({ issue }: { issue: Issue }) {
const { t } = useTranslation();
const page = usePlanDetailContext();
- const [open, setOpen] = useState(false);
const issueUID = extractIssueUID(issue.name);
- const currentRole = useMemo(() => {
- const steps = deriveSteps(issue);
- return steps.find((s) => s.status === "current")?.role ?? "";
- }, [issue]);
- const { isCurrentUserCandidate } = useApprovalCandidates(
- issue,
- page.projectId,
- currentRole
- );
-
- const showReview =
- !page.readonly &&
- issue.status === IssueStatus.OPEN &&
- issue.approvalStatus === ApprovalStatus.PENDING &&
- currentRole !== "" &&
- isCurrentUserCandidate;
-
return (
- // The Review button stays pinned top-right on the first row; the title and
- // its badges share the remaining space and wrap (badges drop to a second
- // row) when the width is too narrow to fit them beside the button.
- <div className="flex items-start gap-x-2 px-4 pt-3 sm:items-center">
- <div className="flex min-w-0 flex-1 flex-col gap-y-1.5 sm:flex-row sm:items-center sm:gap-x-2 sm:gap-y-0">
- <div className="flex shrink-0 items-center gap-x-1">
- <h3 className="text-base font-medium text-main">
- {t("issue.approval-flow.self")}
- </h3>
- {issue.approvalTemplate?.title?.trim() && (
- <Tooltip content={issue.approvalTemplate.title.trim()}>
- <Info className="size-3.5 text-control-light" />
- </Tooltip>
- )}
- </div>
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">
- <RiskChip riskLevel={issue.riskLevel} />
- <RouterLink
- className="inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs text-control hover:border-control-border"
- to={{
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: { issueId: issueUID, projectId: page.projectId },
- }}
- >
- {t("common.issue")} #{issueUID}
- </RouterLink>
- </div>
+ <div className="flex flex-col gap-y-1.5 px-4 pt-3 sm:flex-row sm:items-center sm:gap-x-2 sm:gap-y-0">
+ <div className="flex shrink-0 items-center gap-x-1">
+ <h3 className="text-base font-medium text-main">
+ {t("issue.approval-flow.self")}
+ </h3>
+ {issue.approvalTemplate?.title?.trim() && (
+ <Tooltip content={issue.approvalTemplate.title.trim()}>
+ <Info className="size-3.5 text-control-light" />
+ </Tooltip>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5">
+ <RiskChip riskLevel={issue.riskLevel} />
+ <RouterLink
+ className="inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs text-control hover:border-control-border"
+ to={{
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: { issueId: issueUID, projectId: page.projectId },
+ }}
+ >
+ {t("common.issue")} #{issueUID}
+ </RouterLink>
</div>
- {showReview && (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger render={<Button className="shrink-0 gap-x-1.5" />}>
- {t("plan.review.action")}
- <ChevronDown className="size-4" />
- </PopoverTrigger>
- <PopoverContent align="end" className="px-4 py-4">
- <ReviewActionPopover issue={issue} onClose={() => setOpen(false)} />
- </PopoverContent>
- </Popover>
- )}
</div>
);
}
diff --git a/frontend/src/react/pages/project/plan-detail/components/review/bypassDeploy.tsx b/frontend/src/react/pages/project/plan-detail/components/review/bypassDeploy.tsx
new file mode 100644
index 0000000000..8525ef33f1
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/components/review/bypassDeploy.tsx
@@ -0,0 +1,309 @@
+// Shared "bypass and deploy" state machine + confirm sheet. Both the review
+// readiness footer and the header's Plan status panel surface this manual-deploy
+// override, so the gate/warning logic and the confirmation UI live here once
+// (BYT-9722). The backend only enforces bb.rollouts.create on CreateRollout; the
+// project "require issue approval" / "require no failed checks" settings are
+// client-side gates that this module evaluates before allowing a bypass.
+import { create } from "@bufbuild/protobuf";
+import { Loader2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { rolloutServiceClientConnect } from "@/connect";
+import { PlanCheckSection } from "@/react/components/plan-check/PlanCheckSection";
+import { Alert } from "@/react/components/ui/alert";
+import { Button } from "@/react/components/ui/button";
+import { Checkbox } from "@/react/components/ui/checkbox";
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from "@/react/components/ui/sheet";
+import { pushNotification } from "@/store";
+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";
+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";
+import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";
+import { focusPlanPhase } from "../../shell/focusPhase";
+import { usePlanDetailContext } from "../../shell/PlanDetailContext";
+import type { PlanCheckSummary } from "../../utils/phaseSummary";
+import { getPlanCheckSummary } from "../../utils/phaseSummary";
+import { getPlanCheckSummaryWithFallback } from "../../utils/planCheck";
+import { ReviewApprovalFlow } from "./ReviewApprovalFlow";
+import {
+ type BypassActionWeight,
+ computeBypassActionWeight,
+ computeReadinessFooterState,
+ type ReadinessFooterState,
+} from "./readinessFooterState";
+
+export interface BypassDeploy {
+ state: ReadinessFooterState;
+ checks: PlanCheckSummary;
+ weight: BypassActionWeight;
+ creating: boolean;
+ triggerDeploy: () => void;
+ createRollout: () => Promise<void>;
+ confirmOpen: boolean;
+ setConfirmOpen: (open: boolean) => void;
+ acknowledge: boolean;
+ setAcknowledge: (value: boolean) => void;
+ gates: { label: string; met: boolean }[];
+ gatesBlocked: boolean;
+ warnings: string[];
+ needAck: boolean;
+ confirmDisabled: boolean;
+ planCheckSummary: PlanCheckSummary;
+}
+
+export function useBypassDeploy(issue: Issue, plan: Plan): BypassDeploy {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const [creating, setCreating] = useState(false);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [acknowledge, setAcknowledge] = useState(false);
+
+ const checks = useMemo(() => getPlanCheckSummary(plan), [plan]);
+ const state = useMemo(
+ () =>
+ computeReadinessFooterState({
+ hasRollout: plan.hasRollout,
+ issueStatus: issue.status,
+ approvalStatus: issue.approvalStatus,
+ checks,
+ }),
+ [checks, issue.approvalStatus, issue.status, plan.hasRollout]
+ );
+ const weight = computeBypassActionWeight({
+ state: state.kind,
+ canCreateRollout: page.projectCanCreateRollout && !page.readonly,
+ requireIssueApproval: page.projectRequireIssueApproval,
+ });
+ const planCheckSummary = useMemo(
+ () =>
+ getPlanCheckSummaryWithFallback(
+ page.planCheckRuns,
+ plan.planCheckRunStatusCount
+ ),
+ [page.planCheckRuns, plan.planCheckRunStatusCount]
+ );
+
+ const openConfirm = () => {
+ setAcknowledge(false);
+ setConfirmOpen(true);
+ };
+
+ // When the review has passed and every plan check is green there is nothing to
+ // bypass or confirm — deploy straight away. Any other case (failed/running
+ // checks, or bypassing review) opens the confirm sheet.
+ const triggerDeploy = () => {
+ if (state.kind === "all-gates-passed" && checks.running === 0) {
+ void createRollout();
+ } else {
+ openConfirm();
+ }
+ };
+
+ const createRollout = async () => {
+ if (creating) return;
+ try {
+ setCreating(true);
+ await rolloutServiceClientConnect.createRollout(
+ create(CreateRolloutRequestSchema, { parent: plan.name })
+ );
+ setConfirmOpen(false);
+ await page.refreshState();
+ // Land the user on the freshly created rollout.
+ focusPlanPhase("deploy", page.expandPhase);
+ } catch (error) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.failed"),
+ description: String(error),
+ });
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ // The project's enforced gates and whether each is satisfied. Enforced gates
+ // are HARD: if any is unmet, bypass-and-deploy is blocked entirely — you can
+ // only bypass the project's *optional* requirements, never its mandatory ones.
+ const reviewApproved =
+ state.kind === "all-gates-passed" ||
+ state.kind === "approved-checks-failed";
+ const gates: { label: string; met: boolean }[] = [];
+ if (page.projectRequireIssueApproval) {
+ gates.push({
+ label: t("plan.review.footer.gate-approval"),
+ met: reviewApproved,
+ });
+ }
+ if (page.projectRequirePlanCheckNoError) {
+ gates.push({
+ label: t("plan.review.footer.gate-no-failed-checks"),
+ met: checks.error === 0,
+ });
+ }
+ const gatesBlocked = gates.some((gate) => !gate.met);
+
+ // Soft items this bypass would skip (NOT enforced by project policy) — shown
+ // as warnings the user must acknowledge. Moot when a hard gate blocks deploy.
+ const warnings: string[] = [];
+ if (!page.projectRequireIssueApproval) {
+ if (state.kind === "rejected") {
+ warnings.push(t("plan.review.footer.confirm-review-rejected"));
+ } else if (state.kind === "waiting-review") {
+ warnings.push(t("plan.review.footer.confirm-review-not-approved"));
+ }
+ }
+ if (!page.projectRequirePlanCheckNoError && checks.error > 0) {
+ warnings.push(
+ t("plan.review.footer.confirm-checks-failed", { count: checks.error })
+ );
+ }
+ if (checks.running > 0) {
+ warnings.push(t("plan.review.footer.confirm-checks-running"));
+ }
+ const needAck = warnings.length > 0;
+ const confirmDisabled = creating || gatesBlocked || (needAck && !acknowledge);
+
+ return {
+ state,
+ checks,
+ weight,
+ creating,
+ triggerDeploy,
+ createRollout,
+ confirmOpen,
+ setConfirmOpen,
+ acknowledge,
+ setAcknowledge,
+ gates,
+ gatesBlocked,
+ warnings,
+ needAck,
+ confirmDisabled,
+ planCheckSummary,
+ };
+}
+
+export function BypassAndDeploySheet({
+ issue,
+ bypass,
+}: {
+ issue: Issue;
+ bypass: BypassDeploy;
+}) {
+ const { t } = useTranslation();
+ const page = usePlanDetailContext();
+ const {
+ gates,
+ gatesBlocked,
+ warnings,
+ needAck,
+ acknowledge,
+ setAcknowledge,
+ confirmOpen,
+ setConfirmOpen,
+ confirmDisabled,
+ creating,
+ planCheckSummary,
+ } = bypass;
+
+ return (
+ <Sheet
+ onOpenChange={(open) => {
+ setConfirmOpen(open);
+ if (!open) setAcknowledge(false);
+ }}
+ open={confirmOpen}
+ >
+ <SheetContent
+ className="w-[28rem] max-w-[calc(100vw-2rem)]"
+ width="standard"
+ >
+ <SheetHeader>
+ <SheetTitle>{t("plan.review.footer.bypass-and-deploy")}</SheetTitle>
+ </SheetHeader>
+ <SheetBody className="gap-y-4">
+ {gatesBlocked ? (
+ <Alert
+ description={
+ <ul className="list-inside list-disc text-sm">
+ {gates
+ .filter((gate) => !gate.met)
+ .map((gate) => (
+ <li key={gate.label}>{gate.label}</li>
+ ))}
+ </ul>
+ }
+ title={t("plan.review.footer.gates-blocked")}
+ variant="error"
+ />
+ ) : (
+ needAck && (
+ <Alert
+ variant="warning"
+ description={
+ <ul className="list-inside list-disc text-sm">
+ {warnings.map((warning) => (
+ <li key={warning}>{warning}</li>
+ ))}
+ </ul>
+ }
+ title={t("plan.review.footer.confirm-bypass-title")}
+ />
+ )
+ )}
+
+ <div className="flex flex-col gap-y-1">
+ <h3 className="textlabel uppercase">
+ {t("plan.navigator.review")}
+ </h3>
+ <div className="rounded-md border">
+ <ReviewApprovalFlow issue={issue} />
+ </div>
+ </div>
+
+ <PlanCheckSection
+ canRun={false}
+ includeRunFailure
+ isRunning={false}
+ onRun={() => {}}
+ planCheckRuns={page.planCheckRuns}
+ summaryOverride={planCheckSummary}
+ />
+ </SheetBody>
+ <SheetFooter className="justify-between">
+ {!gatesBlocked && needAck ? (
+ <label className="flex items-center gap-x-2 text-sm text-control">
+ <Checkbox
+ checked={acknowledge}
+ disabled={creating}
+ onCheckedChange={setAcknowledge}
+ />
+ <span>{t("plan.review.footer.confirm-acknowledge")}</span>
+ </label>
+ ) : (
+ <div />
+ )}
+ <div className="flex items-center gap-x-2">
+ <Button onClick={() => setConfirmOpen(false)} variant="ghost">
+ {t("common.cancel")}
+ </Button>
+ <Button
+ disabled={confirmDisabled}
+ onClick={() => void bypass.createRollout()}
+ >
+ {creating && <Loader2 className="size-4 animate-spin" />}
+ {t("plan.navigator.deploy")}
+ </Button>
+ </div>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ );
+}
diff --git a/frontend/src/react/pages/project/plan-detail/shell/focusPhase.ts b/frontend/src/react/pages/project/plan-detail/shell/focusPhase.ts
new file mode 100644
index 0000000000..8a6fd011a8
--- /dev/null
+++ b/frontend/src/react/pages/project/plan-detail/shell/focusPhase.ts
@@ -0,0 +1,21 @@
+import type { PlanDetailPhase } from "../shared/stores/types";
+
+export const planPhaseAnchorId = (phase: PlanDetailPhase): string =>
+ `plan-phase-${phase}`;
+
+// Expand a plan-detail phase and bring it into view. Header actions call this so
+// the user lands on the section their action affects (e.g. deploy after a bypass
+// or run). The phase section's anchor element is always mounted — even collapsed
+// or "future" — so the scroll can run right after the expand; `scroll-mt` on the
+// anchor keeps it clear of the sticky header.
+export function focusPlanPhase(
+ phase: PlanDetailPhase,
+ expandPhase: (phase: PlanDetailPhase) => void
+): void {
+ expandPhase(phase);
+ requestAnimationFrame(() => {
+ document
+ .getElementById(planPhaseAnchorId(phase))
+ ?.scrollIntoView({ behavior: "smooth", block: "start" });
+ });
+}