Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(plan-detail): add review section (#20599)
boojack56e15ec6d8cb
diff --git a/docs/superpowers/plans/2026-06-12-aio-plan-review-section.md b/docs/superpowers/plans/2026-06-12-aio-plan-review-section.mdnew file mode 100644index 0000000000..c774893c00--- /dev/null+++ b/docs/superpowers/plans/2026-06-12-aio-plan-review-section.md@@ -0,0 +1,3278 @@+# AIO Plan Detail Review Section Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Bring the full issue-backed review workflow (approval flow, review actions, rejection recovery, activity timeline + composer, rollout-readiness footer) into the Plan Detail Review section, per `docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.md`.++**Architecture:** Self-contained React components under `frontend/src/react/pages/project/plan-detail/components/review/`, driven by three unit-tested pure modules (approval-flow layout, timeline fold, footer state). Reuses the existing `issueComment` app-store slice, `approveIssue`/`rejectIssue`/`requestIssue` connect calls, and `PlanDetailContext` plumbing. No backend, proto, or store changes.++**Tech Stack:** React + TypeScript, Tailwind v4 + shadcn-style shared UI (`@/react/components/ui/`), Zustand app store, connect-es clients, vitest.++**Read the spec first** — it embeds the authoritative mockups: `docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.md`.++**Conventions that apply to every task** (from `AGENTS.md` / `frontend/AGENTS.md`):+- All user-facing strings via `useTranslation()` and nested keys in `frontend/src/locales/en-US.json` + `zh-CN.json` (Task 2 adds them all up front). Never hardcode display text.+- Use shared UI components (`Button`, `Popover`, `Tooltip`, `Badge`) — no ad-hoc styled controls; `gap-x-2` for button groups; semantic color tokens (`text-control`, `bg-success`, `text-error`…), never raw colors.+- Tests run with: `pnpm --dir frontend test -- run <path>` (vitest). Type check: `pnpm --dir frontend type-check`. Autofix: `pnpm --dir frontend fix`.+- Commit after each task. Do not switch branches, reset, or cherry-pick.++**File structure (final state):**++```+frontend/src/react/lib/plan/diffPlanSpecs.ts (moved from issue-detail/utils/)+frontend/src/react/pages/project/plan-detail/components/review/+├── PlanReviewSection.tsx assembly + CHECKING/SKIPPED states + comment fetching+├── ReviewSectionHeader.tsx risk chip, issue chip, Review button + popover host+├── ReviewActionPopover.tsx comment/approve/reject radio + markdown editor+├── ReviewApprovalFlow.tsx horizontal adaptive row / vertical compact stepper+├── approvalFlowLayout.ts pure layout math + .test.ts+├── useApprovalCandidates.ts per-role candidate computation (extracted logic)+├── ReviewRejectionBanner.tsx rejected-state alert + re-request inline action+├── ReviewActivityTimeline.tsx two-tier rows + torn-separator fold + comment editing+├── timelineEvents.ts event mapping (pure) + .test.ts+├── foldTimeline.ts fold math (pure) + .test.ts+├── ReviewCommentComposer.tsx collapsed composer + localStorage draft+├── ReviewReadinessFooter.tsx status line + Bypass and deploy+└── readinessFooterState.ts state + gating math (pure) + .test.ts+Modified: ProjectPlanDetailPage.tsx (ReviewBranch), PlanDetailDeployFuture.tsx (dedup),+ locales en-US.json / zh-CN.json+Deleted: components/PlanDetailApprovalFlow.tsx + .test.tsx+```++---++### Task 1: Move `diffPlanSpecs` to the shared plan lib++The timeline needs spec-diff rendering; the module is pure and currently lives under issue-detail.++**Files:**+- Move: `frontend/src/react/pages/project/issue-detail/utils/diffPlanSpecs.ts` → `frontend/src/react/lib/plan/diffPlanSpecs.ts`+- Modify: every importer of the old path++- [ ] **Step 1: Move the file**++```bash+cd frontend && git mv src/react/pages/project/issue-detail/utils/diffPlanSpecs.ts src/react/lib/plan/diffPlanSpecs.ts+```++- [ ] **Step 2: Update importers**++Find them: `grep -rn "utils/diffPlanSpecs\|\./diffPlanSpecs" frontend/src/react --include="*.ts*"`. Expected importers: `issue-detail/components/IssueDetailCommentList.tsx` (relative `../utils/diffPlanSpecs`) and any test file. Change each import to:++```ts+import {+ diffEntryKey,+ diffPlanSpecsForEvent,+ type SpecDiffEntry,+} from "@/react/lib/plan/diffPlanSpecs";+```++If `diffPlanSpecs.test.ts` exists next to the old location, `git mv` it to `frontend/src/react/lib/plan/diffPlanSpecs.test.ts` and fix its relative import to `./diffPlanSpecs`.++- [ ] **Step 3: Verify**++Run: `pnpm --dir frontend type-check && pnpm --dir frontend test -- run src/react/lib/plan`+Expected: type check passes; any moved tests pass.++- [ ] **Step 4: Commit**++```bash+git add -A frontend/src/react && git commit -m "refactor: move diffPlanSpecs to shared plan lib"+```++---++### Task 2: Add all `plan.review.*` locale keys++**Files:**+- Modify: `frontend/src/locales/en-US.json` (inside the existing `"plan"` object — there is no `"review"` key yet)+- Modify: `frontend/src/locales/zh-CN.json` (same position)++- [ ] **Step 1: Add the nested `review` object to `plan` in en-US.json**++```json+"review": {+ "action": "Review",+ "comment-required-to-reject": "A comment is required to reject",+ "approval-flow": {+ "n-approved": "{{n}} approved",+ "n-pending": "{{n}} pending",+ "current": "Current",+ "approved-by": "Approved by {{user}}",+ "rejected-by": "Rejected by {{user}}",+ "n-reviewers": "{{n}} reviewers"+ },+ "rejection": {+ "title": "Rejected by {{user}}",+ "guidance-prefix": "Update your changes to address the feedback, or",+ "re-request-review": "re-request review",+ "guidance-suffix": "without changes"+ },+ "activity": {+ "self": "Activity",+ "created-this-plan": "created this plan",+ "marked-ready-for-review": "marked this plan ready for review",+ "approved-review": "approved {{role}} review",+ "rejected-review": "rejected {{role}} review",+ "re-requested-review": "re-requested review",+ "n-hidden-events": "{{count}} hidden events",+ "show-all": "Show all",+ "add-a-comment": "Add a comment..."+ },+ "footer": {+ "waiting-on-review": "Waiting on review",+ "auto-rollout-after-approval": "rollout is created automatically after approval",+ "n-checks-passed": "{{n}} checks passed",+ "n-checks-failed": "{{n}} checks failed,",+ "all-gates-passed": "All gates passed",+ "creating-rollout-automatically": "creating rollout automatically...",+ "approved-but-checks-failed": "Review approved, but plan checks failed",+ "errors-passed-not-created": "{{errors}} errors, {{passed}} passed. Rollout was not created automatically.",+ "blocked-by-rejection": "Blocked by the rejected review — address the feedback above to continue",+ "bypass-and-deploy": "Bypass and deploy"+ }+}+```++- [ ] **Step 2: Add the zh-CN translations in the same position**++```json+"review": {+ "action": "审批",+ "comment-required-to-reject": "拒绝时必须填写评论",+ "approval-flow": {+ "n-approved": "{{n}} 人已批准",+ "n-pending": "{{n}} 个待审批",+ "current": "当前",+ "approved-by": "由 {{user}} 批准",+ "rejected-by": "由 {{user}} 拒绝",+ "n-reviewers": "{{n}} 位审批人"+ },+ "rejection": {+ "title": "被 {{user}} 拒绝",+ "guidance-prefix": "请根据反馈修改变更,或",+ "re-request-review": "重新发起审批",+ "guidance-suffix": "(不做修改)"+ },+ "activity": {+ "self": "动态",+ "created-this-plan": "创建了此变更单",+ "marked-ready-for-review": "将此变更单提交审批",+ "approved-review": "批准了{{role}}审批",+ "rejected-review": "拒绝了{{role}}审批",+ "re-requested-review": "重新发起了审批",+ "n-hidden-events": "{{count}} 条隐藏动态",+ "show-all": "显示全部",+ "add-a-comment": "添加评论..."+ },+ "footer": {+ "waiting-on-review": "等待审批",+ "auto-rollout-after-approval": "审批通过后将自动创建发布",+ "n-checks-passed": "{{n}} 项检查通过",+ "n-checks-failed": "{{n}} 项检查失败,",+ "all-gates-passed": "所有条件已满足",+ "creating-rollout-automatically": "正在自动创建发布...",+ "approved-but-checks-failed": "审批已通过,但变更检查失败",+ "errors-passed-not-created": "{{errors}} 项错误,{{passed}} 项通过。未自动创建发布。",+ "blocked-by-rejection": "已被拒绝的审批阻塞 — 请先处理上方反馈",+ "bypass-and-deploy": "跳过并发布"+ }+}+```++- [ ] **Step 3: Verify JSON validity**++Run: `python3 -c "import json; json.load(open('frontend/src/locales/en-US.json')); json.load(open('frontend/src/locales/zh-CN.json')); print('ok')"`+Expected: `ok`++- [ ] **Step 4: Commit**++```bash+git add frontend/src/locales && git commit -m "feat(plan): add plan.review locale keys"+```++---++### Task 3: Pure module — `approvalFlowLayout`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.ts`+- Test: `frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.ts`++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, test } from "vitest";+import {+ computeApprovalFlowLayout,+ VERTICAL_BREAKPOINT_PX,+} from "./approvalFlowLayout";+import type { ApprovalStepStatus } from "./approvalFlowLayout";++const statuses = (s: string): ApprovalStepStatus[] =>+ s.split("") .map((c) =>+ c === "a" ? "approved" : c === "c" ? "current" : c === "r" ? "rejected" : "pending"+ );++describe("computeApprovalFlowLayout", () => {+ test("narrow container switches to vertical", () => {+ const layout = computeApprovalFlowLayout(statuses("aacpp"), 400);+ expect(layout.kind).toBe("vertical");+ });++ test("everything fits: nothing folds", () => {+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 2000);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 0,+ namedPending: 3,+ });+ });++ test("approved folds first; nearest pending stays named", () => {+ // 3 approved + current + 3 pending at ~900px: approved chip + current ++ // 1 named pending + pending chip (per the mockup's middle row).+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 900);+ expect(layout.kind).toBe("horizontal");+ if (layout.kind !== "horizontal") return;+ expect(layout.foldedApproved).toBe(3);+ expect(layout.namedPending).toBeGreaterThanOrEqual(1);+ expect(layout.namedPending).toBeLessThan(3);+ });++ test("minimum form: chip + current + chip", () => {+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 640);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 3,+ namedPending: 0,+ });+ });++ test("rejected step is the anchor like current", () => {+ const layout = computeApprovalFlowLayout(statuses("aarpp"), 640);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 2,+ namedPending: 0,+ });+ });++ test("no approved steps: no approved chip cost, pending folds only as needed", () => {+ const layout = computeApprovalFlowLayout(statuses("cpppp"), 2000);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 0,+ namedPending: 4,+ });+ });++ test("exports the vertical breakpoint", () => {+ expect(VERTICAL_BREAKPOINT_PX).toBeGreaterThan(0);+ });+});+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.ts`+Expected: FAIL — module not found.++- [ ] **Step 3: Implement**++```ts+// Pure layout math for the horizontal approval flow (spec: "Approval flow+// renderer"). The current (or rejected) step is the anchor and never folds;+// approved steps fold first into one leading chip; trailing pending steps+// fold into one dashed chip, farthest-from-current first.+export type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";++export type ApprovalFlowLayout =+ | { kind: "vertical" }+ | {+ kind: "horizontal";+ // Leading approved steps folded into the "N approved" chip (0 = all named).+ foldedApproved: number;+ // Pending steps after the anchor rendered as full named nodes,+ // counted from the one nearest the anchor.+ namedPending: number;+ };++export const VERTICAL_BREAKPOINT_PX = 560;++// Width budget per element, connector included. Estimates — the row also has+// min-w-0 truncation, so being a little conservative is fine.+const NAMED_NODE_PX = 190;+const ANCHOR_NODE_PX = 240;+const CHIP_PX = 150;++export function computeApprovalFlowLayout(+ statuses: ApprovalStepStatus[],+ containerWidth: number+): ApprovalFlowLayout {+ if (containerWidth < VERTICAL_BREAKPOINT_PX) {+ return { kind: "vertical" };+ }++ const anchorIndex = statuses.findIndex(+ (s) => s === "current" || s === "rejected"+ );+ // Fully-approved (or skipped) flows have no anchor; render all named if they+ // fit, otherwise fold approved into the chip.+ const approvedCount = anchorIndex === -1 ? statuses.length : anchorIndex;+ const pendingCount =+ anchorIndex === -1 ? 0 : statuses.length - anchorIndex - 1;+ const anchorCost = anchorIndex === -1 ? 0 : ANCHOR_NODE_PX;++ const fits = (foldedApproved: number, namedPending: number): boolean => {+ const namedApproved = approvedCount - foldedApproved;+ const foldedPending = pendingCount - namedPending;+ const width =+ (foldedApproved > 0 ? CHIP_PX : 0) ++ namedApproved * NAMED_NODE_PX ++ anchorCost ++ namedPending * NAMED_NODE_PX ++ (foldedPending > 0 ? CHIP_PX : 0);+ return width <= containerWidth;+ };++ // 1. Everything named.+ if (fits(0, pendingCount)) {+ return { kind: "horizontal", foldedApproved: 0, namedPending: pendingCount };+ }+ // 2. Approved fold first (all-or-nothing chip), keep pending named, then+ // fold pending from the far end until it fits.+ for (let named = pendingCount; named >= 0; named--) {+ if (fits(approvedCount, named)) {+ return {+ kind: "horizontal",+ foldedApproved: approvedCount,+ namedPending: named,+ };+ }+ }+ // 3. Minimum form regardless: chip + anchor + chip.+ return { kind: "horizontal", foldedApproved: approvedCount, namedPending: 0 };+}+```++- [ ] **Step 4: Run the test to verify it passes**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.ts`+Expected: PASS (7 tests).++- [ ] **Step 5: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): approval flow layout math"+```++---++### Task 4: Pure modules — `timelineEvents` + `foldTimeline`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts`+- Create: `frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.ts`+- Test: `.../review/timelineEvents.test.ts`, `.../review/foldTimeline.test.ts`++- [ ] **Step 1: Write the failing tests**++`timelineEvents.test.ts`:++```ts+import { create } from "@bufbuild/protobuf";+import { describe, expect, test } from "vitest";+import {+ IssueComment_Approval_Status,+ IssueCommentSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { buildTimelineEntries } from "./timelineEvents";++const userComment = (name: string, comment: string) =>+ create(IssueCommentSchema, { name, comment, creator: "users/[email protected]" });++const approvalComment = (+ name: string,+ status: IssueComment_Approval_Status,+ comment = ""+) =>+ create(IssueCommentSchema, {+ name,+ comment,+ creator: "users/[email protected]",+ event: { case: "approval", value: { status } },+ });++describe("buildTimelineEntries", () => {+ test("synthetic head rows come first, oldest-first", () => {+ const entries = buildTimelineEntries({+ planCreator: "users/[email protected]",+ planCreateTime: { seconds: 1n, nanos: 0 },+ issueCreator: "users/[email protected]",+ issueCreateTime: { seconds: 2n, nanos: 0 },+ comments: [userComment("c1", "hello")],+ });+ expect(entries.map((e) => e.source.type)).toEqual([+ "plan-created",+ "ready-for-review",+ "comment",+ ]);+ });++ test("user comments are island cards", () => {+ const [entry] = buildTimelineEntries({+ comments: [userComment("c1", "hi")],+ });+ expect(entry.tier).toBe("card");+ expect(entry.island).toBe(true);+ });++ test("rejection with comment is an island card; bare approval is a system island", () => {+ const entries = buildTimelineEntries({+ comments: [+ approvalComment("c1", IssueComment_Approval_Status.REJECTED, "no"),+ approvalComment("c2", IssueComment_Approval_Status.APPROVED),+ ],+ });+ expect(entries[0]).toMatchObject({ tier: "card", island: true });+ expect(entries[1]).toMatchObject({ tier: "system", island: true });+ });++ test("issue/plan update events are foldable system rows", () => {+ const update = create(IssueCommentSchema, {+ name: "c1",+ creator: "users/[email protected]",+ event: {+ case: "issueUpdate",+ value: { fromTitle: "a", toTitle: "b", fromLabels: [], toLabels: [] },+ },+ });+ const [entry] = buildTimelineEntries({ comments: [update] });+ expect(entry).toMatchObject({ tier: "system", island: false });+ });+});+```++`foldTimeline.test.ts`:++```ts+import { describe, expect, test } from "vitest";+import { FOLD_MIN_HIDDEN, foldTimeline } from "./foldTimeline";++interface E {+ id: string;+ island: boolean;+}+const sys = (id: string): E => ({ id, island: false });+const island = (id: string): E => ({ id, island: true });++describe("foldTimeline", () => {+ test("short timelines never fold", () => {+ const entries = Array.from({ length: 14 }, (_, i) => sys(`e${i}`));+ const items = foldTimeline(entries, false);+ expect(items).toHaveLength(14);+ expect(items.every((i) => i.type === "entry")).toBe(true);+ });++ test("folds when the middle has >= FOLD_MIN_HIDDEN hidable events", () => {+ const entries = Array.from({ length: 15 }, (_, i) => sys(`e${i}`));+ const items = foldTimeline(entries, false);+ const fold = items.find((i) => i.type === "fold");+ expect(fold).toMatchObject({ type: "fold", count: FOLD_MIN_HIDDEN });+ // first 5 + fold + last 5+ expect(items).toHaveLength(11);+ });++ test("islands in the folded range stay visible and don't count", () => {+ const entries = [+ ...Array.from({ length: 5 }, (_, i) => sys(`head${i}`)),+ sys("h0"),+ island("c0"),+ ...Array.from({ length: 5 }, (_, i) => sys(`h${i + 1}`)),+ ...Array.from({ length: 5 }, (_, i) => sys(`tail${i}`)),+ ];+ const items = foldTimeline(entries, false);+ const ids = items.map((i) => (i.type === "entry" ? i.entry.id : "FOLD"));+ expect(ids).toContain("c0");+ expect(ids).not.toContain("h0");+ const fold = items.find((i) => i.type === "fold");+ expect(fold).toMatchObject({ count: 6 });+ // fold marker sits at the position of the first hidden event (before c0)+ expect(ids.indexOf("FOLD")).toBeLessThan(ids.indexOf("c0"));+ });++ test("middle with too few hidable events does not fold", () => {+ const entries = [+ ...Array.from({ length: 5 }, (_, i) => sys(`head${i}`)),+ sys("h0"),+ ...Array.from({ length: 4 }, (_, i) => island(`c${i}`)),+ ...Array.from({ length: 5 }, (_, i) => sys(`tail${i}`)),+ ];+ expect(foldTimeline(entries, false)).toHaveLength(15);+ });++ test("expanded shows everything", () => {+ const entries = Array.from({ length: 30 }, (_, i) => sys(`e${i}`));+ expect(foldTimeline(entries, true)).toHaveLength(30);+ });+});+```++- [ ] **Step 2: Run tests to verify they fail**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review`+Expected: FAIL — modules not found.++- [ ] **Step 3: Implement `timelineEvents.ts`**++```ts+// Maps the review timeline's event sources into a flat, oldest-first entry+// list with the two-tier weight model (spec: "Activity timeline").+// Plan check results are never timeline entries.+import type { Timestamp } from "@bufbuild/protobuf/wkt";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import { IssueComment_Approval_Status } from "@/types/proto-es/v1/issue_service_pb";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";++export type TimelineTier = "card" | "system";++export type TimelineSource =+ | { type: "plan-created"; creator: string; time?: Timestamp }+ | { type: "ready-for-review"; creator: string; time?: Timestamp }+ | { type: "comment"; comment: IssueComment };++export interface TimelineEntry {+ id: string;+ tier: TimelineTier;+ // Islands never fold: comments and review decisions stay visible inside+ // the folded range.+ island: boolean;+ source: TimelineSource;+}++export function buildTimelineEntries(input: {+ planCreator?: string;+ planCreateTime?: Timestamp;+ issueCreator?: string;+ issueCreateTime?: Timestamp;+ comments: IssueComment[];+}): TimelineEntry[] {+ const entries: TimelineEntry[] = [];+ if (input.planCreator) {+ entries.push({+ id: "plan-created",+ tier: "system",+ island: false,+ source: {+ type: "plan-created",+ creator: input.planCreator,+ time: input.planCreateTime,+ },+ });+ }+ if (input.issueCreator) {+ entries.push({+ id: "ready-for-review",+ tier: "system",+ island: false,+ source: {+ type: "ready-for-review",+ creator: input.issueCreator,+ time: input.issueCreateTime,+ },+ });+ }+ for (const comment of input.comments) {+ const type = getIssueCommentType(comment);+ const isApproval = type === IssueCommentType.APPROVAL;+ const isCard =+ type === IssueCommentType.USER_COMMENT ||+ (isApproval &&+ comment.event.case === "approval" &&+ comment.event.value.status === IssueComment_Approval_Status.REJECTED &&+ comment.comment !== "");+ entries.push({+ id: comment.name,+ tier: isCard ? "card" : "system",+ island: isCard || isApproval,+ source: { type: "comment", comment },+ });+ }+ return entries;+}+```++- [ ] **Step 4: Implement `foldTimeline.ts`**++```ts+// Torn-separator fold (spec: "Long-history fold"). First FOLD_HEAD and last+// FOLD_TAIL entries always render; in between, only non-island entries hide,+// replaced by a single fold marker carrying the exact hidden count at the+// position of the first hidden entry. One click ("Show all") expands all.+export interface FoldableEntry {+ id: string;+ island: boolean;+}++export type FoldedItem<T extends FoldableEntry> =+ | { type: "entry"; entry: T }+ | { type: "fold"; count: number };++export const FOLD_HEAD = 5;+export const FOLD_TAIL = 5;+export const FOLD_MIN_HIDDEN = 5;++export function foldTimeline<T extends FoldableEntry>(+ entries: T[],+ expanded: boolean+): FoldedItem<T>[] {+ const all = entries.map((entry) => ({ type: "entry" as const, entry }));+ if (expanded || entries.length < FOLD_HEAD + FOLD_TAIL + FOLD_MIN_HIDDEN) {+ return all;+ }+ const middle = entries.slice(FOLD_HEAD, entries.length - FOLD_TAIL);+ const hiddenCount = middle.filter((e) => !e.island).length;+ if (hiddenCount < FOLD_MIN_HIDDEN) {+ return all;+ }+ const items: FoldedItem<T>[] = entries+ .slice(0, FOLD_HEAD)+ .map((entry) => ({ type: "entry" as const, entry }));+ let foldEmitted = false;+ for (const entry of middle) {+ if (entry.island) {+ items.push({ type: "entry", entry });+ } else if (!foldEmitted) {+ items.push({ type: "fold", count: hiddenCount });+ foldEmitted = true;+ }+ }+ for (const entry of entries.slice(entries.length - FOLD_TAIL)) {+ items.push({ type: "entry", entry });+ }+ return items;+}+```++- [ ] **Step 5: Run tests to verify they pass**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review`+Expected: PASS (all tests in both files plus Task 3's).++- [ ] **Step 6: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): timeline event mapping and fold math"+```++---++### Task 5: Pure module — `readinessFooterState`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.ts`+- Test: `.../review/readinessFooterState.test.ts`++- [ ] **Step 1: Write the failing test**++```ts+import { describe, expect, test } from "vitest";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import {+ computeBypassActionWeight,+ computeReadinessFooterState,+} from "./readinessFooterState";++const checks = (error = 0, success = 8) => ({+ error,+ running: 0,+ success,+ total: error + success,+ warning: 0,+});++const base = {+ hasRollout: false,+ issueStatus: IssueStatus.OPEN,+ checks: checks(),+};++describe("computeReadinessFooterState", () => {+ test("hidden once the rollout exists", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ hasRollout: true,+ approvalStatus: ApprovalStatus.APPROVED,+ }).kind+ ).toBe("hidden");+ });++ test("hidden when the issue is not open", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ issueStatus: IssueStatus.CANCELED,+ approvalStatus: ApprovalStatus.PENDING,+ }).kind+ ).toBe("hidden");+ });++ test("pending review -> waiting-review (checks failed or not)", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.PENDING,+ }).kind+ ).toBe("waiting-review");+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.PENDING,+ checks: checks(2),+ }).kind+ ).toBe("waiting-review");+ });++ test("approved or skipped with passing checks -> all-gates-passed", () => {+ for (const approvalStatus of [+ ApprovalStatus.APPROVED,+ ApprovalStatus.SKIPPED,+ ]) {+ expect(+ computeReadinessFooterState({ ...base, approvalStatus }).kind+ ).toBe("all-gates-passed");+ }+ });++ test("approved with failed checks -> approved-checks-failed", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.APPROVED,+ checks: checks(2),+ }).kind+ ).toBe("approved-checks-failed");+ });++ test("rejected -> rejected", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.REJECTED,+ }).kind+ ).toBe("rejected");+ });+});++describe("computeBypassActionWeight", () => {+ const allowed = {+ canCreateRollout: true,+ requireIssueApproval: false,+ requirePlanCheckNoError: false,+ };++ test("primary button only when approved and checks failed", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "approved-checks-failed",+ checksFailed: true,+ })+ ).toBe("button");+ });++ test("muted link while review in progress or while waiting on automation", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "waiting-review",+ checksFailed: false,+ })+ ).toBe("link");+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "waiting-review",+ checksFailed: true,+ })+ ).toBe("link");+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "all-gates-passed",+ checksFailed: false,+ })+ ).toBe("link");+ });++ test("never shown when rejected or hidden", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "rejected",+ checksFailed: false,+ })+ ).toBe("none");+ expect(+ computeBypassActionWeight({+ ...allowed,+ state: "hidden",+ checksFailed: false,+ })+ ).toBe("none");+ });++ test("hidden without bb.rollouts.create", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ canCreateRollout: false,+ state: "approved-checks-failed",+ checksFailed: true,+ })+ ).toBe("none");+ });++ test("project enforcement hides the action it would violate", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ requireIssueApproval: true,+ state: "waiting-review",+ checksFailed: false,+ })+ ).toBe("none");+ expect(+ computeBypassActionWeight({+ ...allowed,+ requirePlanCheckNoError: true,+ state: "approved-checks-failed",+ checksFailed: true,+ })+ ).toBe("none");+ });+});+```++- [ ] **Step 2: Run the test to verify it fails**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review/readinessFooterState.test.ts`+Expected: FAIL — module not found.++- [ ] **Step 3: Implement**++```ts+// Footer state machine + bypass gating (spec: "Rollout readiness footer").+// The backend only enforces bb.rollouts.create on CreateRollout; the project+// "require issue approval" / "require no failed checks" settings are+// client-side gates, so the action hides whenever clicking it would violate+// one of them in the current state. The status line renders for everyone.+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import type { PlanCheckSummary } from "../../utils/phaseSummary";++export type ReadinessFooterStateKind =+ | "hidden"+ | "waiting-review"+ | "all-gates-passed"+ | "approved-checks-failed"+ | "rejected";++export interface ReadinessFooterState {+ kind: ReadinessFooterStateKind;+ checks: PlanCheckSummary;+}++export function computeReadinessFooterState(input: {+ hasRollout: boolean;+ issueStatus: IssueStatus | undefined;+ approvalStatus: ApprovalStatus;+ checks: PlanCheckSummary;+}): ReadinessFooterState {+ const { checks } = input;+ if (input.hasRollout || input.issueStatus !== IssueStatus.OPEN) {+ return { kind: "hidden", checks };+ }+ if (input.approvalStatus === ApprovalStatus.REJECTED) {+ return { kind: "rejected", checks };+ }+ if (+ input.approvalStatus === ApprovalStatus.APPROVED ||+ input.approvalStatus === ApprovalStatus.SKIPPED+ ) {+ return {+ kind: checks.error > 0 ? "approved-checks-failed" : "all-gates-passed",+ checks,+ };+ }+ return { kind: "waiting-review", checks };+}++export type BypassActionWeight = "none" | "link" | "button";++export function computeBypassActionWeight(input: {+ state: ReadinessFooterStateKind;+ canCreateRollout: boolean;+ requireIssueApproval: boolean;+ requirePlanCheckNoError: boolean;+ checksFailed: boolean;+}): BypassActionWeight {+ if (input.state === "hidden" || input.state === "rejected") {+ return "none";+ }+ if (!input.canCreateRollout) {+ return "none";+ }+ if (input.requireIssueApproval && input.state === "waiting-review") {+ return "none";+ }+ if (input.requirePlanCheckNoError && input.checksFailed) {+ return "none";+ }+ return input.state === "approved-checks-failed" ? "button" : "link";+}+```++- [ ] **Step 4: Run the test to verify it passes**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review/readinessFooterState.test.ts`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): readiness footer state and bypass gating math"+```++---++### Task 6: `useApprovalCandidates` hook++Extract the per-role candidate computation out of `PlanDetailApprovalFlow.tsx`'s `useApprovalStep` (lines ~653–838) so both the approval-flow renderer (avatar groups) and the header Review button (visibility) can use it. This is a move-and-trim, not new logic.++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/useApprovalCandidates.ts`+- Reference (do not modify yet): `frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx:653-838`++- [ ] **Step 1: Implement the hook**++Copy the candidate-resolution pipeline from `useApprovalStep` verbatim where possible (IAM bindings → group expansion → user fetch → active-USER filter → self-approval filter). The hook is per-role, not per-step-index:++```ts+import { useCallback, useEffect, useMemo, useState } from "react";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useProjectByName } from "@/react/hooks/useProjectByName";+import { useAppStore } from "@/react/stores/app";+import { ensureGroupIdentifier } from "@/react/stores/app/group";+import { projectNamePrefix, userNamePrefix } from "@/store/modules/v1/common";+import { State } from "@/types/proto-es/v1/common_pb";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import {+ AccountType,+ getAccountTypeByEmail,+ groupBindingPrefix,+} from "@/types/v1/user";+import {+ ensureUserFullName,+ isBindingPolicyExpired,+ memberMapToRolesInProjectIAM,+} from "@/utils";++export interface ApprovalCandidates {+ // Active human users who can act on this role's approval step, with the+ // self-approval restriction already applied.+ candidates: User[];+ // True when the current user may approve/reject this step.+ isCurrentUserCandidate: boolean;+ // True when the current user holds the role but is blocked by the+ // project's self-approval rule.+ selfApprovalBlocked: boolean;+}++export function useApprovalCandidates(+ issue: Issue,+ projectId: string,+ role: string+): ApprovalCandidates {+ const currentUser = useCurrentUser();+ const currentUserEmail = currentUser?.email ?? "";+ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useProjectByName(projectName);+ const projectIamPolicy = useAppStore(+ (state) => state.projectPoliciesByName[projectName]+ );+ const batchGetOrFetchUsers = useAppStore(+ (state) => state.batchGetOrFetchUsers+ );+ const batchGetOrFetchGroups = useAppStore(+ (state) => state.batchGetOrFetchGroups+ );+ const groupsByName = useAppStore((state) => state.groupsByName);+ const getGroupByIdentifier = useCallback(+ (identifier: string) => groupsByName[ensureGroupIdentifier(identifier)],+ [groupsByName]+ );+ const [candidates, setCandidates] = useState<User[]>([]);++ // Prefetch any groups bound to this role so candidate expansion can see+ // their members (same dance as the old useApprovalStep).+ const groupNamesKey = useMemo(() => {+ if (!projectIamPolicy) return "";+ const names: string[] = [];+ for (const binding of projectIamPolicy.bindings) {+ if (binding.role !== role || isBindingPolicyExpired(binding)) continue;+ for (const member of binding.members) {+ if (member.startsWith(groupBindingPrefix)) {+ names.push(member);+ }+ }+ }+ return [...new Set(names)].sort().join(" ");+ }, [projectIamPolicy, role]);++ useEffect(() => {+ const names = groupNamesKey ? groupNamesKey.split(" ") : [];+ void batchGetOrFetchGroups(names).catch(() => undefined);+ }, [groupNamesKey, batchGetOrFetchGroups]);++ const candidateEmailsKey = useMemo(() => {+ if (!projectIamPolicy) return "";+ const memberMap = memberMapToRolesInProjectIAM(+ projectIamPolicy,+ role,+ getGroupByIdentifier+ );+ const names: string[] = [];+ for (const fullname of memberMap.keys()) {+ if (fullname.startsWith(userNamePrefix)) {+ names.push(fullname);+ }+ }+ return [...new Set(names)].sort().join(" ");+ }, [projectIamPolicy, role, getGroupByIdentifier]);++ const isCreator = issue.creator === `${userNamePrefix}${currentUserEmail}`;+ const allowSelfApproval = project.allowSelfApproval;++ const filteredEmailsKey = useMemo(() => {+ const emails = candidateEmailsKey ? candidateEmailsKey.split(" ") : [];+ if (!allowSelfApproval && isCreator) {+ return emails+ .filter((e) => e !== `${userNamePrefix}${currentUserEmail}`)+ .join(" ");+ }+ return emails.join(" ");+ }, [allowSelfApproval, candidateEmailsKey, currentUserEmail, isCreator]);++ useEffect(() => {+ let canceled = false;+ const load = async () => {+ const emails = filteredEmailsKey ? filteredEmailsKey.split(" ") : [];+ if (emails.length === 0) {+ setCandidates([]);+ return;+ }+ const users = await batchGetOrFetchUsers(emails.map(ensureUserFullName));+ if (canceled) return;+ setCandidates(+ users+ .filter(+ (user) =>+ user &&+ user.state === State.ACTIVE &&+ getAccountTypeByEmail(user.email) === AccountType.USER+ )+ .sort((left, right) => {+ if (left.email === currentUserEmail) return -1;+ if (right.email === currentUserEmail) return 1;+ return left.title.localeCompare(right.title);+ })+ );+ };+ void load();+ return () => {+ canceled = true;+ };+ }, [batchGetOrFetchUsers, currentUserEmail, filteredEmailsKey]);++ const isCurrentUserCandidate = useMemo(+ () => candidates.some((user) => user.email === currentUserEmail),+ [candidates, currentUserEmail]+ );+ const selfApprovalBlocked = useMemo(() => {+ if (allowSelfApproval || !isCreator) return false;+ const raw = candidateEmailsKey ? candidateEmailsKey.split(" ") : [];+ return raw.includes(`${userNamePrefix}${currentUserEmail}`);+ }, [allowSelfApproval, candidateEmailsKey, currentUserEmail, isCreator]);++ return { candidates, isCurrentUserCandidate, selfApprovalBlocked };+}+```++- [ ] **Step 2: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS.++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): extract approval candidate computation hook"+```++---++### Task 7: `ReviewApprovalFlow` component++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx`++Renders the adaptive flow per the spec's "Approval flow renderer" section and `assets/2026-06-12-aio-plan-review/approval-flow-compaction.png`. Anatomy:++- **Horizontal** (container ≥ `VERTICAL_BREAKPOINT_PX`): `[N approved chip | named approved nodes] → … → anchor node → named pending nodes → [N pending chip]`, joined by short arrow connectors.+- **Vertical** (< breakpoint): every step as a compact stacked row; only the anchor row carries the candidate avatar group.+- Chips reveal their folded nodes in a hover `Tooltip` (read-only: role · ✓ · approver · time for approved; role · candidate count for pending).+- Step status derives from `issue.approvers[index]` exactly like the old component (`approved` / `rejected` / `current` / `pending`).++- [ ] **Step 1: Implement**++```tsx+import { Check, X } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";+import { Badge } from "@/react/components/ui/badge";+import { Tooltip } from "@/react/components/ui/tooltip";+import { displayRoleTitleFromList } from "@/react/lib/role";+import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";+import { unknownUser } from "@/types";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import { Issue_Approver_Status } from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import {+ type ApprovalStepStatus,+ computeApprovalFlowLayout,+} from "./approvalFlowLayout";+import { useApprovalCandidates } from "./useApprovalCandidates";++interface FlowStep {+ index: number;+ role: string;+ status: ApprovalStepStatus;+ approver?: string; // principal of the recorded decision+}++function deriveSteps(issue: Issue): FlowStep[] {+ const roles = issue.approvalTemplate?.flow?.roles ?? [];+ return roles.map((role, index) => {+ const approver = issue.approvers[index];+ let status: ApprovalStepStatus = "pending";+ if (approver?.status === Issue_Approver_Status.APPROVED) {+ status = "approved";+ } else if (approver?.status === Issue_Approver_Status.REJECTED) {+ status = "rejected";+ } else {+ const blocked = roles.slice(0, index).some((_, i) => {+ const prev = issue.approvers[i];+ return prev?.status !== Issue_Approver_Status.APPROVED;+ });+ status = blocked ? "pending" : "current";+ }+ return { index, role, status, approver: approver?.principal };+ });+}++export function ReviewApprovalFlow({ issue }: { issue: Issue }) {+ const hostRef = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);++ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;+ const observer = new ResizeObserver((entries) => {+ setWidth(entries[0]?.contentRect.width ?? 0);+ });+ observer.observe(host);+ return () => observer.disconnect();+ }, []);++ const steps = useMemo(() => deriveSteps(issue), [issue]);+ const layout = useMemo(+ () => computeApprovalFlowLayout(steps.map((s) => s.status), width || 9999),+ [steps, width]+ );++ return (+ <div ref={hostRef} className="min-w-0 px-4 py-3">+ {layout.kind === "vertical" ? (+ <VerticalFlow issue={issue} steps={steps} />+ ) : (+ <HorizontalFlow+ foldedApproved={layout.foldedApproved}+ issue={issue}+ namedPending={layout.namedPending}+ steps={steps}+ />+ )}+ </div>+ );+}++function HorizontalFlow({+ foldedApproved,+ issue,+ namedPending,+ steps,+}: {+ foldedApproved: number;+ issue: Issue;+ namedPending: number;+ steps: FlowStep[];+}) {+ const anchorIndex = steps.findIndex(+ (s) => s.status === "current" || s.status === "rejected"+ );+ const approved = steps.filter((s) => s.status === "approved");+ const foldedApprovedSteps = approved.slice(0, foldedApproved);+ const namedSteps = steps.filter(+ (s) =>+ !foldedApprovedSteps.includes(s) &&+ (anchorIndex === -1 || s.index <= anchorIndex + namedPending)+ );+ const foldedPendingSteps =+ anchorIndex === -1 ? [] : steps.slice(anchorIndex + 1 + namedPending);++ const items: React.ReactNode[] = [];+ if (foldedApprovedSteps.length > 0) {+ items.push(+ <ApprovedChip key="approved-chip" issue={issue} steps={foldedApprovedSteps} />+ );+ }+ for (const step of namedSteps) {+ items.push(<FlowNode key={step.index} issue={issue} step={step} />);+ }+ if (foldedPendingSteps.length > 0) {+ items.push(<PendingChip key="pending-chip" steps={foldedPendingSteps} />);+ }++ return (+ <div className="flex min-w-0 items-center gap-x-2 overflow-hidden">+ {items.map((item, i) => (+ <div key={i} className="flex min-w-0 items-center gap-x-2">+ {i > 0 && (+ <div className="h-px w-8 shrink-0 bg-control-border" aria-hidden />+ )}+ {item}+ </div>+ ))}+ </div>+ );+}++function VerticalFlow({ issue, steps }: { issue: Issue; steps: FlowStep[] }) {+ return (+ <div className="flex flex-col gap-y-3">+ {steps.map((step) => (+ <FlowNode key={step.index} issue={issue} step={step} vertical />+ ))}+ </div>+ );+}++function StatusDot({ status }: { status: ApprovalStepStatus }) {+ return (+ <div+ className={cn(+ "flex size-6 shrink-0 items-center justify-center rounded-full",+ status === "approved" && "bg-success text-white",+ status === "rejected" && "bg-error text-white",+ status === "current" && "bg-accent text-white",+ status === "pending" && "border-2 border-dashed border-control-border"+ )}+ >+ {status === "approved" && <Check className="size-3.5" />}+ {status === "rejected" && <X className="size-3.5" />}+ {status === "current" && <div className="size-2 rounded-full bg-white" />}+ </div>+ );+}++function FlowNode({+ issue,+ step,+ vertical = false,+}: {+ issue: Issue;+ step: FlowStep;+ vertical?: boolean;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const roleList = useAppStore((state) => state.roleList);+ const approverUser = useAppStore((state) =>+ step.approver ? state.getUserByIdentifier(step.approver) : undefined+ );+ const roleName = displayRoleTitleFromList(step.role, roleList);+ const isAnchor = step.status === "current" || step.status === "rejected";++ const subtitle =+ step.status === "approved"+ ? t("plan.review.approval-flow.approved-by", {+ user: (approverUser ?? unknownUser(step.approver ?? "")).title,+ })+ : step.status === "rejected"+ ? t("plan.review.approval-flow.rejected-by", {+ user: (approverUser ?? unknownUser(step.approver ?? "")).title,+ })+ : undefined;++ return (+ <div className={cn("flex min-w-0 items-start gap-x-2", !vertical && "shrink-0")}>+ <StatusDot status={step.status} />+ <div className="min-w-0">+ <div className="flex items-center gap-x-1.5">+ <span className="truncate text-sm font-medium text-main">+ {roleName}+ </span>+ {step.status === "current" && (+ <Badge variant="secondary">+ {t("plan.review.approval-flow.current")}+ </Badge>+ )}+ </div>+ {subtitle ? (+ <div className="truncate text-xs text-control-light">{subtitle}</div>+ ) : isAnchor && step.status === "current" ? (+ <CandidateAvatars issue={issue} projectId={page.projectId} role={step.role} />+ ) : step.status === "pending" ? (+ <CandidateCount issue={issue} projectId={page.projectId} role={step.role} />+ ) : null}+ </div>+ </div>+ );+}++function CandidateAvatars({+ issue,+ projectId,+ role,+}: {+ issue: Issue;+ projectId: string;+ role: string;+}) {+ const { candidates } = useApprovalCandidates(issue, projectId, role);+ const visible = candidates.slice(0, 4);+ const overflow = candidates.length - visible.length;+ if (candidates.length === 0) return null;+ return (+ <div className="mt-1 flex items-center -space-x-1">+ {visible.map((user) => {+ const name = user.title || user.email.split("@")[0];+ return (+ <Tooltip content={user.email} key={user.name}>+ <span+ className="flex size-5 items-center justify-center rounded-full text-[10px] font-medium text-white ring-2 ring-white"+ style={{ backgroundColor: getAvatarColor(name) }}+ >+ {getInitials(name)}+ </span>+ </Tooltip>+ );+ })}+ {overflow > 0 && (+ <span className="flex size-5 items-center justify-center rounded-full bg-control-bg text-[10px] text-control ring-2 ring-white">+ +{overflow}+ </span>+ )}+ </div>+ );+}++function CandidateCount({+ issue,+ projectId,+ role,+}: {+ issue: Issue;+ projectId: string;+ role: string;+}) {+ const { t } = useTranslation();+ const { candidates } = useApprovalCandidates(issue, projectId, role);+ if (candidates.length === 0) return null;+ return (+ <div className="text-xs text-control-light">+ {t("plan.review.approval-flow.n-reviewers", { n: candidates.length })}+ </div>+ );+}++function ApprovedChip({ issue, steps }: { issue: Issue; steps: FlowStep[] }) {+ const { t } = useTranslation();+ const roleList = useAppStore((state) => state.roleList);+ const usersByIdentifier = useAppStore((state) => state.getUserByIdentifier);+ return (+ <Tooltip+ content={+ <div className="flex flex-col gap-y-1">+ {steps.map((step) => (+ <div key={step.index} className="flex items-center gap-x-1 text-xs">+ <span>{displayRoleTitleFromList(step.role, roleList)}</span>+ <Check className="size-3 text-success" />+ <span>+ {(usersByIdentifier(step.approver ?? "") ??+ unknownUser(step.approver ?? "")).title}+ </span>+ </div>+ ))}+ </div>+ }+ >+ <div className="flex shrink-0 cursor-default items-center gap-x-1.5 rounded-full border px-2.5 py-1">+ <div className="flex size-4 items-center justify-center rounded-full bg-success text-white">+ <Check className="size-3" />+ </div>+ <ChipAvatars principals={steps.map((s) => s.approver ?? "")} />+ <span className="text-xs font-medium text-control">+ {t("plan.review.approval-flow.n-approved", { n: steps.length })}+ </span>+ </div>+ </Tooltip>+ );+}++function ChipAvatars({ principals }: { principals: string[] }) {+ const getUserByIdentifier = useAppStore((state) => state.getUserByIdentifier);+ return (+ <span className="flex items-center -space-x-1">+ {principals.slice(0, 3).map((principal, i) => {+ const user = getUserByIdentifier(principal) ?? unknownUser(principal);+ const name = user.title || user.email.split("@")[0];+ return (+ <span+ className="flex size-4 items-center justify-center rounded-full text-[9px] font-medium text-white ring-1 ring-white"+ key={`${principal}-${i}`}+ style={{ backgroundColor: getAvatarColor(name) }}+ >+ {getInitials(name)}+ </span>+ );+ })}+ </span>+ );+}++function PendingChip({ steps }: { steps: FlowStep[] }) {+ const { t } = useTranslation();+ const roleList = useAppStore((state) => state.roleList);+ return (+ <Tooltip+ content={+ <div className="flex flex-col gap-y-1">+ {steps.map((step) => (+ <div key={step.index} className="text-xs">+ {displayRoleTitleFromList(step.role, roleList)}+ </div>+ ))}+ </div>+ }+ >+ <div className="flex shrink-0 cursor-default items-center gap-x-1.5 rounded-full border border-dashed px-2.5 py-1">+ <span className="text-xs text-control-light">+ {t("plan.review.approval-flow.n-pending", { n: steps.length })}+ </span>+ </div>+ </Tooltip>+ );+}+```++Export `deriveSteps` as well (the rejection banner and header need step status): add `export` to its declaration and export the `FlowStep` interface.++- [ ] **Step 2: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS.++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): adaptive approval flow renderer"+```++---++### Task 8: `ReviewRejectionBanner` component++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewRejectionBanner.tsx`++Per spec "Rejection banner" + `assets/2026-06-12-aio-plan-review/rejected-review.png`: red-tinted panel, "Rejected by {user} · {time}", full comment as markdown, one guidance line with the inline re-request action (creator only).++- [ ] **Step 1: Implement**++```tsx+import { create } from "@bufbuild/protobuf";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { issueServiceClientConnect } from "@/connect";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useAppStore } from "@/react/stores/app";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";+import { pushNotification } from "@/store";+import { userNamePrefix } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueComment_Approval_Status,+ RequestIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";++export function findLastRejection(+ comments: IssueComment[]+): IssueComment | undefined {+ for (let i = comments.length - 1; i >= 0; i--) {+ const comment = comments[i];+ if (+ getIssueCommentType(comment) === IssueCommentType.APPROVAL &&+ comment.event.case === "approval" &&+ comment.event.value.status === IssueComment_Approval_Status.REJECTED+ ) {+ return comment;+ }+ }+ return undefined;+}++export function ReviewRejectionBanner({+ comments,+ issue,+}: {+ comments: IssueComment[];+ issue: Issue;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const currentUser = useCurrentUser();+ const [reRequesting, setReRequesting] = useState(false);+ const rejection = useMemo(() => findLastRejection(comments), [comments]);+ const rejectorUser = useAppStore((state) =>+ rejection ? state.getUserByIdentifier(rejection.creator) : undefined+ );++ if (issue.approvalStatus !== ApprovalStatus.REJECTED || !rejection) {+ return null;+ }++ const rejector = rejectorUser ?? unknownUser(rejection.creator);+ const isCreator =+ issue.creator === `${userNamePrefix}${currentUser?.email ?? ""}`;++ 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 (+ <div className="mx-4 mt-3 rounded-md border border-error/30 bg-error/5 px-3 py-2.5">+ <div className="flex items-center gap-x-2 text-sm font-medium text-error">+ <span>+ {t("plan.review.rejection.title", { user: rejector.title })}+ </span>+ {rejection.createTime && (+ <HumanizeTs+ className="text-xs font-normal text-error/70"+ ts={getTimeForPbTimestampProtoEs(rejection.createTime, 0) / 1000}+ />+ )}+ </div>+ {rejection.comment && (+ <div className="mt-1 text-sm text-control">+ <MarkdownEditor content={rejection.comment} mode="preview" />+ </div>+ )}+ <div className="mt-1.5 text-xs text-control-light">+ {t("plan.review.rejection.guidance-prefix")}{" "}+ {isCreator && !page.readonly ? (+ <button+ className="underline hover:text-control 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")}+ </div>+ </div>+ );+}+```++- [ ] **Step 2: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS.++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): rejection banner with inline re-request"+```++---++### Task 9: `ReviewCommentComposer` + `ReviewActivityTimeline`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewCommentComposer.tsx`+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx`++- [ ] **Step 1: Implement the composer**++Collapsed one-liner that expands into the markdown editor; draft persisted to localStorage keyed by issue name (spec: "Comment composer").++```tsx+import { Loader2 } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { UserAvatar } from "@/react/components/UserAvatar";+import { Button } from "@/react/components/ui/button";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useAppStore } from "@/react/stores/app";+import { pushNotification } from "@/store";++const draftKey = (issueName: string) => `bb.plan-review.draft.${issueName}`;++export function ReviewCommentComposer({ issueName }: { issueName: string }) {+ const { t } = useTranslation();+ const currentUser = useCurrentUser();+ const [expanded, setExpanded] = useState(false);+ const [content, setContent] = useState("");+ const [posting, setPosting] = useState(false);++ // Restore the unsent draft on mount / issue change.+ useEffect(() => {+ const draft = localStorage.getItem(draftKey(issueName)) ?? "";+ setContent(draft);+ setExpanded(false);+ }, [issueName]);++ const persistDraft = useCallback(+ (value: string) => {+ setContent(value);+ if (value) {+ localStorage.setItem(draftKey(issueName), value);+ } else {+ localStorage.removeItem(draftKey(issueName));+ }+ },+ [issueName]+ );++ const post = async () => {+ if (!content.trim() || posting) return;+ try {+ setPosting(true);+ await useAppStore.getState().createIssueComment({+ issueName,+ comment: content,+ });+ persistDraft("");+ setExpanded(false);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setPosting(false);+ }+ };++ if (!expanded) {+ return (+ <button+ className="flex w-full items-center gap-x-3 rounded-md border px-3 py-2 text-left text-sm text-control-placeholder hover:border-control-border"+ onClick={() => setExpanded(true)}+ type="button"+ >+ <UserAvatar size="sm" title={currentUser?.title || currentUser?.email} />+ <span>{t("plan.review.activity.add-a-comment")}</span>+ </button>+ );+ }++ return (+ <div className="flex items-start gap-x-3">+ <div className="shrink-0 pt-1">+ <UserAvatar size="sm" title={currentUser?.title || currentUser?.email} />+ </div>+ <div className="min-w-0 flex-1">+ <MarkdownEditor+ content={content}+ onChange={persistDraft}+ onSubmit={() => void post()}+ placeholder={t("plan.review.activity.add-a-comment")}+ />+ <div className="mt-2 flex items-center justify-end gap-x-2">+ <Button+ onClick={() => setExpanded(false)}+ size="sm"+ variant="ghost"+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={posting || content.trim().length === 0}+ onClick={() => void post()}+ size="sm"+ >+ {posting && <Loader2 className="size-4 animate-spin" />}+ {t("common.comment")}+ </Button>+ </div>+ </div>+ </div>+ );+}+```++- [ ] **Step 2: Implement the timeline**++Two-tier rows per `timelineEvents.ts`, fold per `foldTimeline.ts` (torn separator per `assets/2026-06-12-aio-plan-review/activity-timeline-fold.png`), inline editing of own comments, composer as last entry.++```tsx+import { Loader2, Pencil } from "lucide-react";+import { type ReactNode, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { UserAvatar } from "@/react/components/UserAvatar";+import { Button } from "@/react/components/ui/button";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useProjectByName } from "@/react/hooks/useProjectByName";+import { diffEntryKey, diffPlanSpecsForEvent } from "@/react/lib/plan/diffPlanSpecs";+import { displayRoleTitleFromList } from "@/react/lib/role";+import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";+import { extractUserEmail, pushNotification } from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueComment_Approval_Status,+ IssueStatus,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { foldTimeline } from "./foldTimeline";+import { ReviewCommentComposer } from "./ReviewCommentComposer";+import {+ buildTimelineEntries,+ type TimelineEntry,+ type TimelineSource,+} from "./timelineEvents";++export function ReviewActivityTimeline({+ comments,+ issue,+ plan,+}: {+ comments: IssueComment[];+ issue: Issue;+ plan: Plan;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ const [expanded, setExpanded] = useState(false);++ const entries = useMemo(+ () =>+ buildTimelineEntries({+ planCreator: plan.creator,+ planCreateTime: plan.createTime,+ issueCreator: issue.creator,+ issueCreateTime: issue.createTime,+ comments,+ }),+ [comments, issue.createTime, issue.creator, plan.createTime, plan.creator]+ );+ const items = useMemo(() => foldTimeline(entries, expanded), [entries, expanded]);+ const allowComment = Boolean(+ project &&+ issue.status === IssueStatus.OPEN &&+ hasProjectPermissionV2(project, "bb.issueComments.create")+ );++ return (+ <div className="flex flex-col gap-y-2 px-4 pb-3">+ <h4 className="text-sm font-medium text-main">+ {t("plan.review.activity.self")}+ </h4>+ <div className="flex flex-col gap-y-2">+ {items.map((item, i) =>+ item.type === "fold" ? (+ <TornSeparator+ count={item.count}+ key={`fold-${i}`}+ onShowAll={() => setExpanded(true)}+ />+ ) : (+ <TimelineRow entry={item.entry} key={item.entry.id} />+ )+ )}+ {allowComment && <ReviewCommentComposer issueName={issue.name} />}+ </div>+ </div>+ );+}++function TornSeparator({+ count,+ onShowAll,+}: {+ count: number;+ onShowAll: () => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="flex items-center gap-x-3 py-1">+ <div className="h-px flex-1 border-t border-dashed border-control-border" />+ <div className="flex flex-col items-center rounded-sm border bg-control-bg/50 px-3 py-1">+ <span className="text-xs text-control">+ {t("plan.review.activity.n-hidden-events", { count })}+ </span>+ <button+ className="text-xs text-accent hover:underline"+ onClick={onShowAll}+ type="button"+ >+ {t("plan.review.activity.show-all")}+ </button>+ </div>+ <div className="h-px flex-1 border-t border-dashed border-control-border" />+ </div>+ );+}++function TimelineRow({ entry }: { entry: TimelineEntry }) {+ if (entry.tier === "card") {+ // Cards are always comments (user comments or rejections with a body).+ if (entry.source.type !== "comment") return null;+ return <CommentCard comment={entry.source.comment} />;+ }+ return <SystemRow source={entry.source} />;+}++function ActorName({ principal }: { principal: string }) {+ const user = useAppStore((state) => state.getUserByIdentifier(principal));+ const resolved = user ?? unknownUser(principal);+ return (+ <span className="font-medium text-main">+ {resolved.title || resolved.email}+ </span>+ );+}++function SystemRow({ source }: { source: TimelineSource }) {+ const { t } = useTranslation();++ if (source.type === "plan-created" || source.type === "ready-for-review") {+ return (+ <div className="flex min-w-0 items-center gap-x-2 text-sm text-control-light">+ <ActorName principal={source.creator} />+ <span className="min-w-0 truncate">+ {source.type === "plan-created"+ ? t("plan.review.activity.created-this-plan")+ : t("plan.review.activity.marked-ready-for-review")}+ </span>+ {source.time && (+ <HumanizeTs+ className="shrink-0 text-xs text-control-placeholder"+ ts={getTimeForPbTimestampProtoEs(source.time, 0) / 1000}+ />+ )}+ </div>+ );+ }++ const comment = source.comment;+ return (+ <div className="flex min-w-0 items-center gap-x-2 text-sm text-control-light">+ <ActorName principal={comment.creator} />+ <span className="min-w-0 truncate">+ <SystemSentence comment={comment} />+ </span>+ {comment.createTime && (+ <HumanizeTs+ className="shrink-0 text-xs text-control-placeholder"+ ts={getTimeForPbTimestampProtoEs(comment.createTime, 0) / 1000}+ />+ )}+ </div>+ );+}++function SystemSentence({ comment }: { comment: IssueComment }) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const roleList = useAppStore((state) => state.roleList);+ const type = getIssueCommentType(comment);++ if (type === IssueCommentType.APPROVAL && comment.event.case === "approval") {+ const { status } = comment.event.value;+ // The role of the decided step isn't on the event; use the generic+ // sentence from the issue-detail vocabulary when it can't be derived.+ const stepIndex = page.issue?.approvers.findIndex(+ (a) => a.principal === comment.creator+ );+ const role =+ stepIndex !== undefined && stepIndex >= 0+ ? page.issue?.approvalTemplate?.flow?.roles[stepIndex]+ : undefined;+ const roleTitle = role ? displayRoleTitleFromList(role, roleList) : "";+ if (status === IssueComment_Approval_Status.APPROVED) {+ return roleTitle+ ? t("plan.review.activity.approved-review", { role: roleTitle })+ : t("custom-approval.issue-review.approved-issue");+ }+ if (status === IssueComment_Approval_Status.REJECTED) {+ return roleTitle+ ? t("plan.review.activity.rejected-review", { role: roleTitle })+ : t("custom-approval.issue-review.rejected-issue");+ }+ return t("plan.review.activity.re-requested-review");+ }++ if (type === IssueCommentType.ISSUE_UPDATE && comment.event.case === "issueUpdate") {+ const e = comment.event.value;+ if (e.fromTitle !== undefined && e.toTitle !== undefined) {+ return t("activity.sentence.changed-from-to", {+ name: t("issue.issue-name").toLowerCase(),+ newValue: e.toTitle,+ oldValue: e.fromTitle,+ });+ }+ if (e.fromDescription !== undefined && e.toDescription !== undefined) {+ return t("activity.sentence.changed-description");+ }+ if (e.fromStatus !== undefined && e.toStatus !== undefined) {+ if (e.toStatus === IssueStatus.DONE)+ return t("activity.sentence.resolved-issue");+ if (e.toStatus === IssueStatus.CANCELED)+ return t("activity.sentence.canceled-issue");+ return t("activity.sentence.reopened-issue");+ }+ if (e.fromLabels.length !== 0 || e.toLabels.length !== 0) {+ return t("activity.sentence.changed-labels");+ }+ return t("common.updated");+ }++ if (type === IssueCommentType.PLAN_UPDATE && comment.event.case === "planUpdate") {+ const entries = diffPlanSpecsForEvent(comment.event.value);+ if (entries.length === 0) return t("common.updated");+ const labels = entries.map((entry) =>+ entry.kind === "added"+ ? t("activity.sentence.added-spec")+ : entry.kind === "removed"+ ? t("activity.sentence.removed-spec")+ : entry.sheetChanged+ ? t("activity.sentence.modified-sql-of")+ : entry.targetsChanged+ ? t("activity.sentence.changed-targets-of")+ : t("common.updated")+ );+ return (+ <>+ {entries.map((entry, i) => (+ <span key={diffEntryKey(entry)}>+ {i > 0 && ", "}+ {labels[i]} {t("plan.spec.change")}+ </span>+ ))}+ </>+ );+ }++ return t("common.updated");+}++function CommentCard({ comment }: { comment: IssueComment }) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const currentUser = useCurrentUser();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ const creatorUser = useAppStore((state) =>+ state.getUserByIdentifier(comment.creator)+ );+ const creator = creatorUser ?? unknownUser(comment.creator);+ const [isEditing, setIsEditing] = useState(false);+ const [editContent, setEditContent] = useState(comment.comment);+ const [saving, setSaving] = useState(false);++ const allowEdit = Boolean(+ project &&+ (currentUser?.email === extractUserEmail(comment.creator) ||+ hasProjectPermissionV2(project, "bb.issueComments.update"))+ );+ const createdTs = getTimeForPbTimestampProtoEs(comment.createTime, 0);+ const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime, 0);+ const isEdited =+ createdTs !== updatedTs &&+ getIssueCommentType(comment) === IssueCommentType.USER_COMMENT;+ const isRejection =+ getIssueCommentType(comment) === IssueCommentType.APPROVAL;++ const save = async () => {+ if (!editContent || editContent === comment.comment) {+ setIsEditing(false);+ return;+ }+ try {+ setSaving(true);+ await useAppStore.getState().updateIssueComment({+ issueCommentName: comment.name,+ comment: editContent,+ });+ setIsEditing(false);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="flex items-start gap-x-3">+ <div className="shrink-0 pt-1.5">+ <UserAvatar size="sm" title={creator.title || creator.email} />+ </div>+ <div+ className={cn(+ "min-w-0 flex-1 overflow-hidden rounded-md border",+ isRejection && "border-error/30"+ )}+ >+ <div+ className={cn(+ "flex items-center justify-between px-3 py-1.5",+ isRejection ? "bg-error/5" : "bg-control-bg/50"+ )}+ >+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">+ <span className="font-medium text-main">+ {creator.title || creator.email}+ </span>+ {isRejection && (+ <span className="text-control-light">+ <SystemSentence comment={comment} />+ </span>+ )}+ {comment.createTime && (+ <HumanizeTs+ className="text-xs text-control-placeholder"+ ts={createdTs / 1000}+ />+ )}+ {isEdited && (+ <span className="text-xs text-control-placeholder">+ ({t("common.edited")})+ </span>+ )}+ </div>+ {allowEdit && !isEditing && !isRejection && (+ <Button+ onClick={() => {+ setEditContent(comment.comment);+ setIsEditing(true);+ }}+ size="xs"+ variant="ghost"+ >+ <Pencil className="size-3.5" />+ </Button>+ )}+ </div>+ <div className="border-t px-3 py-2 text-sm text-control">+ {isEditing ? (+ <div>+ <MarkdownEditor+ content={editContent}+ onChange={setEditContent}+ onSubmit={() => void save()}+ />+ <div className="mt-2 flex items-center justify-end gap-x-2">+ <Button+ onClick={() => setIsEditing(false)}+ size="xs"+ variant="ghost"+ >+ {t("common.cancel")}+ </Button>+ <Button+ disabled={saving || editContent === comment.comment}+ onClick={() => void save()}+ size="xs"+ >+ {saving && <Loader2 className="size-3.5 animate-spin" />}+ {t("common.save")}+ </Button>+ </div>+ </div>+ ) : (+ <MarkdownEditor content={comment.comment} mode="preview" />+ )}+ </div>+ </div>+ </div>+ );+}+```++- [ ] **Step 3: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS. (If `plan.createTime` doesn't exist on the Plan proto, use `plan.createTime` per `plan_service_pb` — verify with `grep -n "createTime" frontend/src/types/proto-es/v1/plan_service_pb.d.ts`; it exists on Plan.)++- [ ] **Step 4: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): activity timeline with fold and draft-preserving composer"+```++---++### Task 10: `ReviewActionPopover` + `ReviewSectionHeader`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewActionPopover.tsx`+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx`++- [ ] **Step 1: Implement the popover**++Comment / Approve / Reject radio + markdown, like Issue Detail's review popover but: reject requires a non-empty comment, and submission never navigates away (spec: "Review action").++```tsx+import { create } from "@bufbuild/protobuf";+import { Check, Loader2, MessageCircle, X } from "lucide-react";+import { type ReactNode, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { issueServiceClientConnect } from "@/connect";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { Button } from "@/react/components/ui/button";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useAppStore } from "@/react/stores/app";+import { pushNotification } from "@/store";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import {+ ApproveIssueRequestSchema,+ RejectIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";++type ReviewAction = "COMMENT" | "APPROVE" | "REJECT";++export function ReviewActionPopover({+ issue,+ onClose,+}: {+ issue: Issue;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const [action, setAction] = useState<ReviewAction>("COMMENT");+ const [comment, setComment] = useState("");+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ setAction("COMMENT");+ setComment("");+ }, [issue.name]);++ const commentMissing = comment.trim().length === 0;+ const submitDisabled =+ loading ||+ (action === "COMMENT" && commentMissing) ||+ (action === "REJECT" && commentMissing);++ const submit = async () => {+ if (submitDisabled) return;+ try {+ setLoading(true);+ if (action === "APPROVE") {+ const response = await issueServiceClientConnect.approveIssue(+ create(ApproveIssueRequestSchema, { comment, name: issue.name })+ );+ page.patchState({ issue: response });+ } else if (action === "REJECT") {+ const response = await issueServiceClientConnect.rejectIssue(+ create(RejectIssueRequestSchema, { comment, name: issue.name })+ );+ page.patchState({ issue: response });+ } else {+ await useAppStore.getState().createIssueComment({+ issueName: issue.name,+ comment,+ });+ }+ await page.refreshState();+ onClose();+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="flex w-[min(34rem,calc(100vw-2rem))] flex-col gap-y-3">+ <MarkdownEditor+ content={comment}+ onChange={setComment}+ onSubmit={() => void submit()}+ />+ <div className="flex flex-col gap-y-2.5">+ <ReviewOption+ description={t("issue.review.comment-description")}+ icon={<MessageCircle className="size-4 text-control" />}+ label={t("common.comment")}+ onSelect={() => setAction("COMMENT")}+ selected={action === "COMMENT"}+ />+ <ReviewOption+ description={t("issue.review.approve-description")}+ icon={<Check className="size-4 text-success" />}+ label={t("common.approve")}+ onSelect={() => setAction("APPROVE")}+ selected={action === "APPROVE"}+ />+ <ReviewOption+ description={t("issue.review.reject-description")}+ icon={<X className="size-4 text-error" />}+ label={t("common.reject")}+ onSelect={() => setAction("REJECT")}+ selected={action === "REJECT"}+ />+ </div>+ <div className="flex items-center justify-start gap-x-2 pt-1">+ <Tooltip+ content={+ action === "REJECT" && commentMissing+ ? t("plan.review.comment-required-to-reject")+ : undefined+ }+ >+ <span className="inline-flex">+ <Button+ disabled={submitDisabled}+ onClick={() => void submit()}+ size="sm"+ >+ {loading && <Loader2 className="size-4 animate-spin" />}+ {t("common.submit")}+ </Button>+ </span>+ </Tooltip>+ <Button onClick={onClose} size="sm" variant="ghost">+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ );+}++function ReviewOption({+ description,+ icon,+ label,+ onSelect,+ selected,+}: {+ description?: string;+ icon?: ReactNode;+ label: string;+ onSelect: () => void;+ selected: boolean;+}) {+ return (+ <label+ className={cnSelected(selected)}+ >+ <input+ checked={selected}+ className="mt-1 size-4 accent-accent"+ onChange={onSelect}+ type="radio"+ />+ {icon && <span className="mt-1 shrink-0">{icon}</span>}+ <span className="flex flex-col">+ <span className="text-sm font-medium leading-6">{label}</span>+ {description && (+ <span className="text-xs text-control-light">{description}</span>+ )}+ </span>+ </label>+ );+}++function cnSelected(selected: boolean) {+ return [+ "flex cursor-pointer items-start gap-3 text-left transition-colors",+ selected ? "text-main" : "text-control",+ ].join(" ");+}+```++- [ ] **Step 2: Implement the section header**++Risk chip + issue chip + the only header action (spec: "Review action"; mockup `review-in-progress.png`).++```tsx+import { ChevronDown, ShieldAlert, ShieldCheck } from "lucide-react";+import { useMemo, useState } from "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 { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";+import { ApprovalStatus, 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 { deriveSteps } from "./ReviewApprovalFlow";+import { ReviewActionPopover } from "./ReviewActionPopover";+import { useApprovalCandidates } from "./useApprovalCandidates";++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 (+ <div className="flex items-center gap-x-2 px-4 pt-3">+ <h3 className="text-base font-medium text-main">+ {t("issue.approval-flow.self")}+ </h3>+ <div className="flex min-w-0 flex-1 items-center gap-x-1.5 pl-1">+ <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="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>+ );+}++function RiskChip({ riskLevel }: { riskLevel: RiskLevel }) {+ const { t } = useTranslation();+ if (riskLevel === RiskLevel.RISK_LEVEL_UNSPECIFIED) return null;+ const label =+ riskLevel === RiskLevel.LOW+ ? t("issue.risk-level.low")+ : riskLevel === RiskLevel.MODERATE+ ? t("issue.risk-level.moderate")+ : t("issue.risk-level.high");+ const Icon = riskLevel === RiskLevel.LOW ? ShieldCheck : ShieldAlert;+ return (+ <span className="inline-flex shrink-0 items-center gap-x-1 rounded-full border px-2 py-0.5 text-xs text-control">+ <Icon+ className={+ riskLevel === RiskLevel.LOW+ ? "size-3.5 text-success"+ : riskLevel === RiskLevel.MODERATE+ ? "size-3.5 text-warning"+ : "size-3.5 text-error"+ }+ />+ {label}+ </span>+ );+}+```++Note: the header keeps the risk-level *tooltip* semantics of the old component as a visible chip per the mockup ("High risk" pill).++- [ ] **Step 3: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS.++- [ ] **Step 4: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): review header action and review popover"+```++---++### Task 11: `ReviewReadinessFooter`++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx`++Per spec table and `assets/2026-06-12-aio-plan-review/readiness-footer-states.png`.++- [ ] **Step 1: Implement**++```tsx+import { create } from "@bufbuild/protobuf";+import { Ban, CircleCheck, CircleX, Clock3, Loader2 } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { rolloutServiceClientConnect } from "@/connect";+import { Button } from "@/react/components/ui/button";+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 { pushNotification } from "@/store";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { getPlanCheckSummary } from "../../utils/phaseSummary";+import {+ computeBypassActionWeight,+ computeReadinessFooterState,+} from "./readinessFooterState";++export function ReviewReadinessFooter({+ issue,+ plan,+}: {+ issue: Issue;+ plan: Plan;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const [creating, setCreating] = 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,+ requirePlanCheckNoError: page.projectRequirePlanCheckNoError,+ checksFailed: checks.error > 0,+ });++ if (state.kind === "hidden") return null;++ const bypass = async () => {+ if (creating) return;+ try {+ setCreating(true);+ await rolloutServiceClientConnect.createRollout(+ create(CreateRolloutRequestSchema, { parent: plan.name })+ );+ await page.refreshState();+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setCreating(false);+ }+ };++ const checkCounts = (+ <>+ {checks.error > 0 && (+ <span className="text-error">+ {t("plan.review.footer.n-checks-failed", { n: checks.error })}+ </span>+ )}+ <span>+ {t("plan.review.footer.n-checks-passed", { n: checks.success })}+ </span>+ </>+ );++ return (+ <div+ className={+ state.kind === "approved-checks-failed"+ ? "flex items-center gap-x-2 border-t px-4 py-2.5"+ : "flex items-center gap-x-2 border-t px-4 py-2.5 text-sm text-control-placeholder"+ }+ >+ {state.kind === "waiting-review" && (+ <>+ <Clock3 className="size-4 shrink-0" />+ <span className="font-medium text-control">+ {t("plan.review.footer.waiting-on-review")}+ </span>+ <span>·</span>+ <span className="min-w-0 truncate">+ {t("plan.review.footer.auto-rollout-after-approval")}+ </span>+ <span>·</span>+ {checkCounts}+ </>+ )}+ {state.kind === "all-gates-passed" && (+ <>+ <CircleCheck className="size-4 shrink-0 text-success" />+ <span className="font-medium text-control">+ {t("plan.review.footer.all-gates-passed")}+ </span>+ <span>·</span>+ <span className="min-w-0 truncate">+ {t("plan.review.footer.creating-rollout-automatically")}+ </span>+ <span>·</span>+ {checkCounts}+ </>+ )}+ {state.kind === "approved-checks-failed" && (+ <>+ <CircleX className="size-4 shrink-0 text-error" />+ <div className="min-w-0 flex-1">+ <div className="text-sm font-semibold text-main">+ {t("plan.review.footer.approved-but-checks-failed")}+ </div>+ <div className="text-xs text-control-placeholder">+ {t("plan.review.footer.errors-passed-not-created", {+ errors: checks.error,+ passed: checks.success,+ })}+ </div>+ </div>+ </>+ )}+ {state.kind === "rejected" && (+ <>+ <Ban className="size-4 shrink-0" />+ <span className="min-w-0 truncate">+ {t("plan.review.footer.blocked-by-rejection")}+ </span>+ </>+ )}++ {state.kind !== "approved-checks-failed" && <div className="flex-1" />}++ {weight === "link" && (+ <button+ className="shrink-0 text-xs text-control-placeholder underline hover:text-control disabled:opacity-60"+ disabled={creating}+ onClick={() => void bypass()}+ type="button"+ >+ {t("plan.review.footer.bypass-and-deploy")}+ </button>+ )}+ {weight === "button" && (+ <Button+ className="shrink-0"+ disabled={creating}+ onClick={() => void bypass()}+ >+ {creating && <Loader2 className="size-4 animate-spin" />}+ {t("plan.review.footer.bypass-and-deploy")}+ </Button>+ )}+ </div>+ );+}+```++- [ ] **Step 2: Verify it compiles**++Run: `pnpm --dir frontend type-check`+Expected: PASS.++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "feat(plan): rollout readiness footer with bypass action"+```++---++### Task 12: `PlanReviewSection` assembly + page integration++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx`+- Modify: `frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx` (the `ReviewBranch` function, ~line 523, and the import at line 26)++- [ ] **Step 1: Implement the section assembly**++```tsx+import { create } from "@bufbuild/protobuf";+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import { useAppStore } from "@/react/stores/app";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import { ListIssueCommentsRequestSchema } from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { PlanReviewSectionHeader } from "./ReviewSectionHeader";+import { ReviewActivityTimeline } from "./ReviewActivityTimeline";+import { ReviewApprovalFlow } from "./ReviewApprovalFlow";+import { ReviewReadinessFooter } from "./ReviewReadinessFooter";+import { ReviewRejectionBanner } from "./ReviewRejectionBanner";++const EMPTY_COMMENTS: IssueComment[] = [];++export function PlanReviewSection() {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const issue = page.issue;+ const issueName = issue?.name ?? "";+ const issueUpdateKey = `${issue?.updateTime?.seconds ?? ""}:${issue?.updateTime?.nanos ?? ""}`;+ const loadProjectIamPolicy = useAppStore(+ (state) => state.loadProjectIamPolicy+ );++ // Candidate computation needs project + IAM in the cache.+ useEffect(() => {+ const projectName = `${projectNamePrefix}${page.projectId}`;+ void useAppStore+ .getState()+ .getOrFetchProjectByName(projectName)+ .catch(() => undefined);+ void loadProjectIamPolicy(projectName).catch(() => undefined);+ }, [loadProjectIamPolicy, page.projectId]);++ // Refetch comments whenever the issue changes server-side (polling bumps+ // updateTime) or after local actions refresh the issue.+ useEffect(() => {+ if (!issueName) return;+ void useAppStore+ .getState()+ .listIssueComments(+ create(ListIssueCommentsRequestSchema, {+ parent: issueName,+ pageSize: 1000,+ })+ )+ .catch(() => undefined);+ }, [issueName, issueUpdateKey]);++ const comments = useAppStore((state) =>+ issueName ? state.getIssueComments(issueName) : EMPTY_COMMENTS+ );++ if (!issue) return null;++ if (issue.approvalStatus === ApprovalStatus.CHECKING) {+ return (+ <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">+ <div className="size-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />+ <span>+ {t("custom-approval.issue-review.generating-approval-flow")}+ </span>+ </div>+ );+ }++ const skipped =+ issue.approvalStatus === ApprovalStatus.SKIPPED ||+ (issue.approvalTemplate?.flow?.roles ?? []).length === 0;++ return (+ <div className="flex flex-col">+ <PlanReviewSectionHeader issue={issue} />+ {skipped ? (+ <div className="px-4 py-3 text-sm text-control-placeholder">+ {t("custom-approval.approval-flow.skip")}+ </div>+ ) : (+ <ReviewApprovalFlow issue={issue} />+ )}+ <ReviewRejectionBanner comments={comments} issue={issue} />+ <ReviewActivityTimeline+ comments={comments}+ issue={issue}+ plan={page.plan}+ />+ <ReviewReadinessFooter issue={issue} plan={page.plan} />+ </div>+ );+}+```++Naming note: the header component is `PlanReviewSectionHeader` (defined in Task 10's `ReviewSectionHeader.tsx`).++- [ ] **Step 2: Wire into the page**++In `ProjectPlanDetailPage.tsx`, replace the import (line 26) and `ReviewBranch`:++```tsx+import { PlanReviewSection } from "./components/review/PlanReviewSection";+```++```tsx+function ReviewBranch() {+ const { t } = useTranslation();+ const page = usePlanDetailContext();++ if (!page.issue) {+ return (+ <div className="p-4 text-sm text-control-light">+ {t("common.no-data")}+ </div>+ );+ }++ return <PlanReviewSection />;+}+```++- [ ] **Step 3: Verify**++Run: `pnpm --dir frontend type-check && pnpm --dir frontend test -- run src/react/pages/project/plan-detail`+Expected: type check passes. The old `PlanDetailApprovalFlow.test.tsx` still passes (component still exists until Task 14).++- [ ] **Step 4: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail && git commit -m "feat(plan): assemble review section into plan detail"+```++---++### Task 13: Deploy-future dedup++**Files:**+- Modify: `frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx`++Per spec "Cleanups folded in": for issue-backed plans the footer is now the single gate-status source and the single manual path. GitOps plans (no Review section) keep everything.++- [ ] **Step 1: Trim the issue-backed branch**++In `PlanDetailDeployFuture.tsx`:+- Delete the `requirementItems` array and the `<ul>` that renders it (the `page.issue && (...)` block).+- Change `planReadyForManualRollout` / button rendering so the manual-create hint, button, and confirm `Sheet` render **only when `isGitOpsPlan`**. The non-GitOps branch keeps only the description paragraph (`plan.phase.deploy-description`).+- Delete now-unused locals (`errorMessages`, `warningMessages`, `bypassWarnings`, `rolloutConfirmOpen`, `manualCreateRolloutDescription`, the Sheet and its imports) **for the non-GitOps path** — since GitOps skips the confirm sheet already (it calls `createRollout()` directly), the whole `Sheet`, `requirementItems`, warning/error message machinery, and `PlanCheckStatusSummary` become dead code; delete them. Final shape:++```tsx+export function PlanDetailDeployFuture() {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const [creatingRollout, setCreatingRollout] = useState(false);++ const isGitOpsPlan = useMemo(+ () => isReleaseBackedPlan(page.plan.specs),+ [page.plan.specs]+ );+ const canCreateRollout = Boolean(+ isGitOpsPlan &&+ !page.plan.hasRollout &&+ page.plan.state === State.ACTIVE &&+ page.projectCanCreateRollout+ );++ const createRollout = async () => {+ if (creatingRollout) return;+ try {+ setCreatingRollout(true);+ const createdRollout = await rolloutServiceClientConnect.createRollout(+ create(CreateRolloutRequestSchema, { parent: page.plan.name })+ );+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("common.created"),+ });+ await page.refreshState();+ void router.push(+ buildPlanDeployRouteFromRolloutName(createdRollout.name)+ );+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setCreatingRollout(false);+ }+ };++ return (+ <div className="mt-1.5">+ <p className="text-sm text-control-placeholder">+ {isGitOpsPlan+ ? t("plan.phase.deploy-description-gitops")+ : t("plan.phase.deploy-description")}+ </p>+ {canCreateRollout && (+ <div className="mt-3">+ <Button+ disabled={creatingRollout}+ onClick={() => void createRollout()}+ size="sm"+ variant="outline"+ >+ {t("plan.phase.create-rollout-action")}+ </Button>+ </div>+ )}+ </div>+ );+}+```++Clean the import list down to what remains.++- [ ] **Step 2: Verify**++Run: `pnpm --dir frontend type-check && pnpm --dir frontend check`+Expected: PASS (the `check` run also flags unused imports).++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail && git commit -m "feat(plan): dedup deploy-future manual rollout into review footer"+```++---++### Task 14: Delete the superseded approval-flow component++**Files:**+- Delete: `frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx`+- Delete: `frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx`+- Possibly modify: `frontend/src/locales/*.json` (remove `plan.view-discussion` if dead)++- [ ] **Step 1: Confirm no remaining callers**++Run: `grep -rn "PlanDetailApprovalFlow\|PlanDetailSidebarApprovalFlow\|PlanDetailReviewApprovalFlow" frontend/src --include="*.ts*" | grep -v "components/PlanDetailApprovalFlow"`+Expected: no output (Task 12 removed the page import).++- [ ] **Step 2: Delete**++```bash+git rm frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx+```++- [ ] **Step 3: Remove dead locale keys**++Run: `grep -rn "plan.view-discussion" frontend/src --include="*.ts*" --include="*.vue"`+If no hits remain, delete the `"view-discussion"` key from `plan` in every locale file that has it (`grep -l "view-discussion" frontend/src/locales/*.json`).++- [ ] **Step 4: Verify**++Run: `pnpm --dir frontend type-check && pnpm --dir frontend test -- run src/react/pages/project/plan-detail`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add -A frontend/src && git commit -m "refactor(plan): delete superseded PlanDetailApprovalFlow"+```++---++### Task 15: Component tests — five review-section states++**Files:**+- Create: `frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx`++Follow the mock pattern of the deleted `PlanDetailApprovalFlow.test.tsx` (it's in git history at `HEAD~1`, and Task 14's step 2 shows the path): `IS_REACT_ACT_ENVIRONMENT`, `vi.hoisted` mocks for `react-i18next` (t returns the key with interpolations appended), `@/connect`, `@/react/stores/app` (`useAppStore` selector backed by a mock state object), `@/react/components/MarkdownEditor` (render content in a div), `@/react/components/FeatureBadge`, and `@/react/router`. Render with `createRoot` inside `act`, wrapped in `PlanDetailProvider` with a `PlanDetailPageState` stub.++- [ ] **Step 1: Write the test**++```tsx+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import {+ Issue_Approver_Status,+ IssueStatus,+} from "@/types/proto-es/v1/issue_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { PlanReviewSection } from "./PlanReviewSection";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++const mocks = vi.hoisted(() => ({+ comments: [] as unknown[],+ state: {+ roleList: [],+ projectsByName: {},+ projectPoliciesByName: {},+ groupsByName: {},+ getIssueComments: () => mocks.comments,+ getUserByIdentifier: () => undefined,+ listIssueComments: vi.fn(async () => ({ issueComments: [] })),+ getOrFetchProjectByName: vi.fn(async () => ({})),+ loadProjectIamPolicy: vi.fn(async () => ({})),+ batchGetOrFetchUsers: vi.fn(async () => []),+ batchGetOrFetchGroups: vi.fn(async () => []),+ createIssueComment: vi.fn(async () => undefined),+ updateIssueComment: vi.fn(async () => undefined),+ } as Record<string, unknown>,+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, opts?: Record<string, unknown>) =>+ opts ? `${key}:${JSON.stringify(opts)}` : key,+ }),+}));++vi.mock("@/react/stores/app", () => {+ const useAppStore = Object.assign(+ (selector: (s: unknown) => unknown) => selector(mocks.state),+ { getState: () => mocks.state }+ );+ return { useAppStore };+});++vi.mock("@/react/components/MarkdownEditor", () => ({+ MarkdownEditor: ({ content }: { content: string }) => (+ <div data-testid="markdown">{content}</div>+ ),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: {+ approveIssue: vi.fn(async () => ({})),+ rejectIssue: vi.fn(async () => ({})),+ requestIssue: vi.fn(async () => ({})),+ },+ rolloutServiceClientConnect: {+ createRollout: vi.fn(async () => ({ name: "r", stages: [] })),+ },+}));++vi.mock("@/react/router", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/react/router")>()),+ router: { push: vi.fn(), resolve: () => ({ fullPath: "/", href: "/" }) },+}));++vi.mock("@/react/hooks/useProjectByName", () => ({+ useProjectByName: () => ({+ name: "projects/p1",+ allowSelfApproval: true,+ }),+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useCurrentUser: () => ({+ name: "users/me",+ email: "[email protected]",+ title: "Me",+ }),+}));++function makeIssue(overrides: Partial<Issue>): Issue {+ return {+ name: "projects/p1/issues/1",+ creator: "users/[email protected]",+ status: IssueStatus.OPEN,+ approvalStatus: ApprovalStatus.PENDING,+ approvalTemplate: {+ flow: { roles: ["roles/projectOwner", "roles/workspaceDBA"] },+ },+ approvers: [],+ riskLevel: 0,+ labels: [],+ ...overrides,+ } as unknown as Issue;+}++function makePage(issue: Issue, planOverrides = {}): PlanDetailPageState {+ return {+ projectId: "p1",+ planId: "1",+ pageKey: "k",+ projectTitle: "P1",+ projectRequireIssueApproval: false,+ projectRequirePlanCheckNoError: false,+ projectCanCreateRollout: true,+ currentUser: { name: "users/me", email: "[email protected]", title: "Me" },+ project: { name: "projects/p1" },+ isCreating: false,+ isInitializing: false,+ ready: true,+ readonly: false,+ plan: {+ name: "projects/p1/plans/1",+ creator: "users/[email protected]",+ specs: [],+ hasRollout: false,+ planCheckRunStatusCount: { SUCCESS: 8 },+ ...planOverrides,+ },+ issue,+ rollout: undefined,+ planCheckRuns: [],+ taskRuns: [],+ isEditing: false,+ isRefreshing: false,+ isRunningChecks: false,+ setIsRunningChecks: () => {},+ activePhases: new Set(["review"]),+ pendingLeaveConfirm: false,+ layoutMode: "DESKTOP",+ containerWidth: 1400,+ patchState: vi.fn(),+ refreshState: vi.fn(async () => {}),+ bypassLeaveGuardOnce: () => {},+ setEditing: () => {},+ togglePhase: () => {},+ expandPhase: () => {},+ closeTaskPanel: () => {},+ resolveLeaveConfirm: () => {},+ } as unknown as PlanDetailPageState;+}++async function render(element: ReactElement): Promise<HTMLDivElement> {+ const host = document.createElement("div");+ document.body.appendChild(host);+ const root = createRoot(host);+ await act(async () => {+ root.render(element);+ });+ return host;+}++const renderSection = (page: PlanDetailPageState) =>+ render(+ <PlanDetailProvider value={page}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++beforeEach(() => {+ document.body.innerHTML = "";+ mocks.comments = [];+});++describe("PlanReviewSection states", () => {+ test("in progress: waiting footer with muted bypass link", async () => {+ const host = await renderSection(makePage(makeIssue({})));+ expect(host.textContent).toContain("plan.review.footer.waiting-on-review");+ expect(host.textContent).toContain("plan.review.footer.bypass-and-deploy");+ expect(host.querySelector("button.underline")).not.toBeNull();+ });++ test("rejected: banner + blocked footer, no bypass action", async () => {+ mocks.comments = [+ {+ name: "projects/p1/issues/1/issueComments/c1",+ comment: "fix it",+ creator: "users/[email protected]",+ event: { case: "approval", value: { status: 3 } }, // REJECTED+ },+ ];+ const issue = makeIssue({+ approvalStatus: ApprovalStatus.REJECTED,+ approvers: [+ { principal: "users/[email protected]", status: Issue_Approver_Status.REJECTED },+ ],+ } as Partial<Issue>);+ const host = await renderSection(makePage(issue));+ expect(host.textContent).toContain("plan.review.rejection.title");+ expect(host.textContent).toContain(+ "plan.review.footer.blocked-by-rejection"+ );+ expect(host.textContent).not.toContain(+ "plan.review.footer.bypass-and-deploy"+ );+ });++ test("approved + checks failed: primary bypass button", async () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.APPROVED });+ const host = await renderSection(+ makePage(issue, { planCheckRunStatusCount: { SUCCESS: 8, ERROR: 2 } })+ );+ expect(host.textContent).toContain(+ "plan.review.footer.approved-but-checks-failed"+ );+ // primary action is a real Button, not the muted underline link+ expect(host.querySelector("button.underline")).toBeNull();+ expect(host.textContent).toContain("plan.review.footer.bypass-and-deploy");+ });++ test("approved + checks passed: all gates passed, muted link", async () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.APPROVED });+ const host = await renderSection(makePage(issue));+ expect(host.textContent).toContain("plan.review.footer.all-gates-passed");+ expect(host.querySelector("button.underline")).not.toBeNull();+ });++ test("skipped approval: skip line, footer still present", async () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.SKIPPED });+ const host = await renderSection(makePage(issue));+ expect(host.textContent).toContain("custom-approval.approval-flow.skip");+ expect(host.textContent).toContain("plan.review.footer.all-gates-passed");+ });++ test("footer disappears once the rollout exists", async () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.APPROVED });+ const host = await renderSection(makePage(issue, { hasRollout: true }));+ expect(host.textContent).not.toContain(+ "plan.review.footer.bypass-and-deploy"+ );+ });+});+```++Adjust mock shapes to whatever the components actually read — the test must compile against the real component imports; if a mocked store method is missing, add it to `mocks.state`.++- [ ] **Step 2: Run the test**++Run: `pnpm --dir frontend test -- run src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx`+Expected: PASS (6 tests). Iterate on mock completeness until green — do not weaken assertions.++- [ ] **Step 3: Commit**++```bash+git add frontend/src/react/pages/project/plan-detail/components/review && git commit -m "test(plan): review section state coverage"+```++---++### Task 16: Full gates + verification++**Files:** none new.++- [ ] **Step 1: Autofix and validate everything**++```bash+pnpm --dir frontend fix+pnpm --dir frontend check+pnpm --dir frontend type-check+pnpm --dir frontend test -- run+```+Expected: all pass. `fix` may reorder imports — re-run `check` after.++- [ ] **Step 2: Verify the backend re-review assumption (spec requirement)**++The spec relies on existing backend behavior: editing the plan while rejected restarts review. Verify in code (not by changing anything): `grep -rn "ApprovalFindingDone\|approval_finding" backend/api/v1/plan_service.go | head` — `UpdatePlan` should reset the issue's approval finding. If it does NOT, stop and report: the rejection-banner guidance line overpromises and the spec needs an update — do not silently ship.++- [ ] **Step 3: Manual smoke (optional but recommended)**++Start the stack (`PG_URL=postgresql://bbdev@localhost/bbdev go run ./backend/bin/server/main.go --port 8080 --data . --debug` + `pnpm --dir frontend dev`), create a plan with an approval flow, and walk CUJ 1 (approve → footer → auto rollout), CUJ 2/3 (reject with comment → banner → re-request), CUJ 4 (comment draft survives collapse), CUJ 5 (approve with a failing check → primary Bypass and deploy). The `verify` or `bytebase-team-skills:bytebase-e2e-testing` skill can drive this.++- [ ] **Step 4: Commit any fix-ups**++```bash+git add -A && git commit -m "chore(plan): review section lint/test fix-ups"+```++---++## Self-review notes (already applied)++- Spec coverage: header action (T10), approval flow + layout (T3/T7), rejection banner + re-request (T8), timeline two-tier + fold + islands (T4/T9), composer + draft (T9), footer five states + gating + direct CreateRollout (T5/T11), CHECKING/SKIPPED carry-over (T12), deploy dedup GitOps-preserving (T13), dead-code deletion (T14), i18n en+zh (T2), unit + component tests (T3/T4/T5/T15), gates (T16). The 3.20.0 redirects are intentionally absent (out of scope).+- Type consistency: `deriveSteps`/`FlowStep` exported from `ReviewApprovalFlow` and consumed by the header; `PlanReviewSectionHeader` is the single name across T10/T12; `foldTimeline` takes `(entries, expanded)` everywhere; footer math types match `getPlanCheckSummary`'s `PlanCheckSummary`.+- Known judgment calls an executor may adjust without breaking the spec: exact px constants in `approvalFlowLayout`, Tailwind classes, and Tooltip vs Popover for chip reveal (spec says popover-on-hover; shared `Tooltip` renders content on hover and is the closest existing primitive — do not build a new floating surface).diff --git a/docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.md b/docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.mdnew file mode 100644index 0000000000..83ebee15f3--- /dev/null+++ b/docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.md@@ -0,0 +1,321 @@+# AIO Plan Detail Review Section — Design++Date: 2026-06-12+Source: "AIO Plan Page UI/UX Design" doc (2026-05-28, updated 2026-06-09; reviewers Peter Zhu, Xzavier Zane, Danny Xu). This spec translates the approved UX design into a frontend implementation design.++## Summary++Make Plan Detail the primary review surface for CI/CD plans. The Review phase+section gains the full issue-backed review workflow — approval flow, review+actions (comment / approve / reject), rejection recovery, a unified activity+timeline with composer, and a rollout-readiness footer — so users complete the+review decision beside SQL, targets, checks, risk, and settings without+leaving the page.++## Scope++- **In scope (3.19.1 release-plan stage):** the Review section redesign on+ Plan Detail described below. Issue Detail keeps its existing review+ capability unchanged.+- **Out of scope:** the 3.20.0 redirect behavior for issue-based review entry+ points (separate spec); backend workflow changes; approval policy or+ permission model changes; release-based (GitOps) database changes; full+ visual redesign of Plan Detail; deploy/rollout redesign; plan/issue+ title-description-label unification.++## Approach decision++Self-contained implementation (approved): new components live in+`frontend/src/react/pages/project/plan-detail/components/review/`. They reuse+the app-store `issueComment` slice, the `approveIssue` / `rejectIssue` /+`requestIssue` / `createIssueComment` connect calls, and leaf components+(`MarkdownEditor`, `UserAvatar`, `HumanizeTs`, `Tooltip`, `Popover`), plus+pure utils extracted from Issue Detail where the import is clean+(`diffPlanSpecs`, approval-candidate computation). No Issue Detail page+components are imported or modified — zero regression risk on the page that+remains the fallback in 3.19.1.++## Component structure++`ReviewBranch` in `ProjectPlanDetailPage.tsx` renders a new+`PlanReviewSection`, stacked top to bottom:++```+PlanReviewSection+├── ReviewSectionHeader — "Approval Flow" + risk chip + issue #chip · Review button (far right)+├── ReviewApprovalFlow — horizontal adaptive row / vertical stepper (narrow)+├── ReviewRejectionBanner — only when rejected, pinned above the timeline+├── ReviewActivityTimeline — unified oldest-first events + comments+│ └── ReviewCommentComposer — collapsed "Add a comment…", last timeline entry+└── ReviewReadinessFooter — quiet status line + "Bypass and deploy"+```++Canonical anatomy (① Review action ② approval flow ③ activity timeline+④ composer ⑤ readiness footer; the footer link label in this older mockup+reads "Bypass review and deploy" — superseded by "Bypass and deploy",+decided 2026-06-10):++++- Replaces the `review`-mode rendering of `PlanDetailApprovalFlow.tsx`. The+ `sidebar` mode of that component has no callers; the whole component is+ deleted.+- The `PhaseSection` shell (status dot, badge, expand/collapse) is unchanged.+- The CHECKING ("generating approval flow…") and SKIPPED one-line renderings+ carry over into the new section unchanged.+- The footer sits below the composer deliberately: the composer reads as the+ final timeline entry; the footer is the terminal summary of the section.++## Design guidelines (from the UX doc, binding)++- Keep review inline with plan context; no navigation away for any review act.+- Each review state has exactly one primary action with one home: Review+ (header) while actionable; re-request (rejection banner) when rejected;+ Bypass and deploy (footer) only when it is the only path forward.+- Rejection is the only alert-styled state; approved/pending/skipped stay+ neutral. Color is reserved for approval outcomes and the live blocker.+- Exception actions use secondary styling while a normal path remains.+- Plan check results are never timeline rows.++## Review action (header button)++- **Visibility:** issue OPEN, `approvalStatus` PENDING, and the current user+ is a candidate of the current approval step (reuse the candidate logic in+ `useApprovalStep`, excluding users blocked by the self-approval rule).+ Non-candidates see no button; they comment via the composer.+- **Popover:** Comment / Approve / Reject radio options + markdown editor,+ same pattern as Issue Detail's review popover, rebuilt in the review folder.+ Approve/Reject options render only for candidates (the popover is only+ reachable by candidates, so in practice all three options show).+- **Reject requires a non-empty comment** — submit disabled otherwise. The+ rejection banner depends on the reason always existing. (Issue Detail's+ popover is not changed.)+- **After submit:** patch issue state, `refreshState()`, refetch comments.+ Stay on Plan Detail — no redirect (unlike Issue Detail's post-approve+ navigation). The footer / Deploy section communicate what happens next.++## Approval flow renderer++++- **Wide containers — horizontal row, adaptive compaction.** Three anchors:+ - Approved steps fold into one leading chip: stacked avatars + "N approved".+ - The current (under-review) step never folds: two rows — role ++ `Current` badge, then candidate avatar group with "+N" overflow. No+ "Waiting for…" text.+ - Trailing pending steps that don't fit fold into one dashed "N pending"+ chip.+ - Fill rule: reserve the three anchors, spend leftover width expanding+ folded nodes nearest the current step, next-first; on shrink they refold,+ current last to go.+- **Narrow / mobile — vertical stepper, always compact.** Same anatomy+ stacked; chips never unfold by width; only the current node is expanded.+- **Hover to reveal:** each chip opens a read-only popover listing its folded+ nodes (approved: role · ✓ · approver · time; pending: role · reviewers).+- Step status (approved / rejected / current / pending) derives from+ `issue.approvers` exactly as today; a rejected step renders a red X node+ inline.+- Layout math is a pure function `computeApprovalFlowLayout(steps, width)`+ driven by a `ResizeObserver` on the section card (the page-level+ `containerWidth` tracks the page, not this card). Unit-tested without+ rendering.++## Rejection banner++++- Renders only while `approvalStatus` is REJECTED, pinned between the+ approval flow and the timeline; red-tinted panel — the single alert-styled+ element on the page (replaces today's warning-styled banner).+- Content: "Rejected by {user} · {relative time}", the full rejection comment+ (markdown), and one guidance line naming both recovery paths: "Update your+ changes to address the feedback, or re-request review without changes" —+ with re-request review as an inline text action, visible only to the issue+ creator (existing `canReRequest` + `requestIssue`).+- Derivation: the latest APPROVAL-type issue comment whose approval status is+ REJECTED (tightens today's `lastRejection`, which takes any APPROVAL+ comment). The banner derives from live approval state and disappears the+ moment review restarts by either path.+- The rejection decision also lands in-stream as a permanent timeline entry+ (card weight, since it carries the comment).+- Editing the plan restarts review on the backend (existing behavior, doc+ CUJ 3); the page's polling/refresh picks up the regenerated flow.+ **Implementation must verify this end-to-end before relying on it; it is an+ assumption about existing backend behavior, not a change.**++## Activity timeline++One unified oldest-first stream. No tabs, no filters.++**Two visual tiers:**++- Full cards (avatar + header + markdown body): user comments; rejection+ decisions with their comment.+- Compact gray one-liners (actor + action + relative time): approvals,+ re-requests, issue status changes (resolved / canceled / reopened), title /+ description / label changes, plan spec updates (statement / targets / prior+ backup — reusing `diffPlanSpecs`, extracted from `issue-detail/utils/` to a+ shared pure module).++**Event sources:**++- Synthetic head rows from metadata: "{creator} created this plan"+ (plan.creator/createTime) and "{creator} marked this plan ready for review"+ (issue.creator/createTime).+- All issue comments from the existing `issueComment` app-store slice.+- Plan check results are never rendered as timeline rows.+- The user's own comments are editable inline (pencil → markdown editor),+ same permission rules as Issue Detail (`bb.issueComments.update` or own+ comment).++**Long-history fold (torn separator):**++++- The first 5 and last 5 entries always render. The middle folds behind a+ full-width torn separator with the exact count and a single action:+ "N hidden events · Show all". One click expands everything in place,+ scroll-anchored; no incremental "load more".+- Fold activates only when the middle has ≥5 hidable events+ (first 5 + last 5 + at least 5 hidden; threshold 15+).+- Comments and decision events inside the folded range stay visible as+ islands — only routine system events fold; the count counts hidden rows+ only.+- `foldTimeline(entries)` is a pure function with unit tests.++## Comment composer++- Last entry of the timeline: collapsed single line (current-user avatar ++ "Add a comment…") for anyone with `bb.issueComments.create`.+- Expands on click/focus into the markdown editor with a Comment submit+ button; posting appends the comment above and re-collapses.+- Unsent draft is preserved in `localStorage`, keyed by issue name, and+ restored on the next expand — no text is ever lost to collapse or+ navigation.++## Rollout readiness footer++A quiet single line under a hairline divider at the bottom of the section.+Exists only while `!plan.hasRollout` and the issue is OPEN; once the rollout+exists the footer disappears and Deploy answers "what happens next".++One action label in every state: **"Bypass and deploy"**. The status line+names what is blocking or running; only the action's weight changes.++++| State | Status line | Action |+|---|---|---|+| Review in progress · checks passed | clock icon · "Waiting on review · rollout is created automatically after approval · 8 checks passed" | muted underlined link, far right |+| Review in progress · checks failed | same, but "2 checks failed," rendered red; failed count is the only signal | muted link (review is still the normal path) |+| Approved or skipped · checks passed · rollout pending | green check · "All gates passed · creating rollout automatically… · 10 checks passed" | muted link (bypasses the wait on automatic creation) |+| Approved or skipped · checks failed | red check-failure icon · bold "Review approved, but plan checks failed" · "2 errors, 8 passed. Rollout was not created automatically." | primary button — the page's one primary action |+| Rejected | blocked icon · "Blocked by the rejected review — address the feedback above to continue" · checks count | none |++- Check counts come from `getPlanCheckSummary(plan)`.+- **Gating:** the backend enforces only `bb.rollouts.create` on+ `CreateRollout`; the project settings are client-side gates. The action is+ hidden when the user lacks `bb.rollouts.create`, or when a project+ enforcement setting forbids the bypass in the current state+ (`projectRequireIssueApproval` while review is not approved/skipped;+ `projectRequirePlanCheckNoError` while checks fail) — the same rules the+ Deploy section applies today. The status line renders for everyone.+- **Click:** direct `CreateRollout` call — no confirm sheet. The control+ disables while in flight; creation is idempotent, so a click racing the+ automatic creation is safe (first creator wins). On success: refresh state;+ the footer disappears; Deploy becomes the active section. No navigation.++## Critical user journeys (acceptance)++1. **Reviewer approves.** Open Plan Detail → inspect Changes → click Review+ (header) → approve. Their node turns green, the header action disappears,+ the footer shows "All gates passed · creating rollout automatically…".+ Once the rollout is created the footer disappears and Deploy is active.+2. **Reviewer rejects with feedback.** Review → reject with a comment. The+ rejection banner pins above the timeline; the decision also lands+ in-stream as a permanent row; the header action disappears.+3. **Creator recovers from rejection.** The banner pins the reviewer's+ comment with one guidance line naming both paths. Editing the plan inline+ and saving restarts review automatically (banner gone, checks re-run,+ approval flow regenerated). The inline re-request action restarts review+ without changes, keeping earlier approvals.+4. **Participant discusses.** Open the collapsed composer → write markdown →+ post. The comment appears above the composer; the composer re-collapses;+ an unsent draft survives collapse and is restored.+5. **Releaser bypasses the last gate.** Review approved/skipped but checks+ failed → the footer is the page's one primary action → Bypass and deploy →+ rollout created, footer gone, Deploy takes over. In every other+ non-rejected state the same action is a muted link.++## Full-page mockups++Desktop and mobile, full Plan Detail lifecycle with the Review section in+context (mobile uses the vertical, always-compact approval stepper):++++Approved state — review completed, Deploy active:++++## Data flow++Existing plumbing only: `usePlanDetailPage` polling for plan / issue /+rollout; the `issueComment` slice for the timeline (fetched on mount,+re-fetched when `issue.updateTime` changes and after any action);+`patchState` / `refreshState` after approve / reject / comment / re-request /+bypass. No new stores, no proto or API changes, no backend changes.++## Cleanups folded in++- Delete `PlanDetailApprovalFlow.tsx` (both modes; `sidebar` is dead code).+- **Deploy-future dedup (approved decision):** for issue-backed plans, remove+ the requirements checklist, the manual "Create rollout" button, and its+ confirm sheet from `PlanDetailDeployFuture` — keep only the one-line+ description. The readiness footer is the single source of gate status and+ the single manual path. GitOps (release-backed) plans render no Review+ section and keep their existing Deploy-future creation flow unchanged.++## Error handling++- All connect calls follow the page's existing pattern: `pushNotification`+ CRITICAL on failure, controls disabled while submitting, state refreshed on+ success.+- A bypass click that loses the race to automatic creation surfaces no error+ path the user must handle: refresh shows the created rollout either way.+- Comment list fetch failures degrade to an empty timeline with the existing+ loading/blank states; the approval flow and footer derive from the issue+ object and stay functional.++## i18n++All new strings under nested `plan.review.*` keys in+`frontend/src/locales/`, translated in all five locale files (en-US, zh-CN,+es-ES, ja-JP, vi-VN) — `check-react-i18n.mjs` enforces key parity with en-US,+so fallback-only is not an option. No hardcoded display strings.++## Testing++- Unit tests (vitest, colocated): `computeApprovalFlowLayout` (anchor+ reservation, expand/refold order), `foldTimeline` (threshold, islands,+ counts), footer state mapping (five states × gating), timeline event+ mapping (comment types → tier/sentence).+- Component tests: `PlanReviewSection` in the five states (in progress,+ rejected, approved-checks-failed, all-gates-passed, skipped); review+ popover reject-requires-comment; composer draft persistence.+- Gates: `pnpm --dir frontend fix`, `check`, `type-check`, `test`.++## References++- UX source: "AIO Plan Page UI/UX Design" PDF (repo root, untracked), Google+ Doc 1goYvRASKwAbHt96x3mS8eQOIwaXmonldm37CTzBUrMU. Mockups extracted from the+ PDF into `assets/2026-06-12-aio-plan-review/` and embedded above.+- Prior-art research: 6 comparators, 54 audited claims (Reference section of+ the UX doc) — adopted patterns: single unified timeline, two-tier weight,+ collapsed composer, color discipline; avoided anti-patterns: silent/middle+ truncation, newest-first pagination, decision auto-comments, server-side+ filters, always-expanded composer.+- Current code: `frontend/src/react/pages/project/plan-detail/` (page, shell+ hooks, deploy components), `frontend/src/react/pages/project/issue-detail/`+ (review popover pattern, comment list, diffPlanSpecs),+ `frontend/src/react/stores/app/issueComment.ts`.diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3023cd8381..fc2b7e3824 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -288,7 +288,6 @@"discard-changes": "Discard changes","discord": "Discord","dismiss": "Dismiss",- "done": "Done","download": "Download","draft": "Draft","duplicate": "Duplicate",@@ -1303,7 +1302,6 @@},"write": "Write"},- "create-rollout": "Create Rollout","data-export": {"download-tooltip": "Available for 24 hours","file-expired": "File Expired",@@ -1491,19 +1489,8 @@},"phase": {"create-rollout-action": "Manually create rollout",- "deploy-approval-must-complete": "Approval flow must be done.",- "deploy-approval-optional": "Approval can be bypassed based on the current project settings.",- "deploy-approval-pending": "Finish the approval flow before rollout can proceed automatically.",- "deploy-approval-ready": "Approval is complete for this plan.",- "deploy-checks-blocked": "Failed checks are blocking automatic rollout creation.",- "deploy-checks-must-pass": "Checks must pass.",- "deploy-checks-optional": "Failed checks won't block manual rollout in this project.",- "deploy-checks-ready": "Checks are ready for automatic rollout creation.",- "deploy-checks-running": "Wait for running checks to finish before automatic rollout can proceed.","deploy-description": "Bytebase will automatically create the rollout when all checks pass and the issue is approved.","deploy-description-gitops": "This plan is ready to roll out. Create a rollout to deploy the linked release.",- "deploy-manual-create-description": "Based on the current project settings, you can also create the rollout manually.",- "deploy-manual-create-description-readonly": "User with Create Rollout permission can create the rollout manually.","hide-details": "Hide details","review-description": "Submit for review to proceed","show-details": "Show details"@@ -1513,6 +1500,63 @@"requirements-not-met": "Pre-backup requirements not met: {{databases}}"},"ready-for-review": "Ready for Review",+ "review": {+ "action": "Review",+ "activity": {+ "add-a-comment": "Add a comment...",+ "created-this-plan": "created this plan",+ "marked-ready-for-review": "marked this plan ready for review",+ "n-hidden-events_one": "{{count}} hidden event",+ "n-hidden-events_other": "{{count}} hidden events",+ "self": "Activity",+ "show-all": "Show all"+ },+ "approval-flow": {+ "and-n-more_one": "and {{count}} more",+ "and-n-more_other": "and {{count}} more",+ "approved-by": "Approved by {{user}}",+ "current": "Current",+ "n-approved": "{{n}} approved",+ "n-pending": "{{n}} pending",+ "n-reviewers_one": "{{count}} reviewer",+ "n-reviewers_other": "{{count}} reviewers",+ "no-reviewers": "No reviewers",+ "rejected-by": "Rejected by {{user}}"+ },+ "comment-required-to-reject": "A comment is required to reject",+ "footer": {+ "all-gates-passed": "All gates passed",+ "approved-but-checks-failed": "Review approved, but plan checks failed",+ "auto-rollout-after-approval": "rollout is created automatically after approval",+ "blocked-by-rejection": "Blocked by the rejected review — address the feedback above to continue",+ "bypass-and-deploy": "Bypass and deploy",+ "confirm-acknowledge": "Bypass",+ "confirm-bypass-title": "This will bypass:",+ "confirm-checks-failed_one": "{{count}} failed plan check",+ "confirm-checks-failed_other": "{{count}} failed plan checks",+ "confirm-checks-running": "Plan checks still running",+ "confirm-review-not-approved": "Review not yet approved",+ "confirm-review-rejected": "Review rejected",+ "creating-rollout-automatically": "creating rollout automatically...",+ "errors-passed-not-created_one": "{{count}} error, {{passed}} passed. Rollout was not created automatically.",+ "errors-passed-not-created_other": "{{count}} errors, {{passed}} passed. Rollout was not created automatically.",+ "gate-approval": "Issue approval",+ "gate-no-failed-checks": "No failed plan checks",+ "gates-blocked": "Required project gates are not met — deployment is blocked.",+ "n-checks-failed_one": "{{count}} check failed",+ "n-checks-failed_other": "{{count}} checks failed",+ "n-checks-passed_one": "{{count}} check passed",+ "n-checks-passed_other": "{{count}} checks passed",+ "rollout-blocked-by-failed-checks": "rollout won't be created automatically until checks pass",+ "waiting-on-review": "Waiting on review"+ },+ "rejection": {+ "guidance-prefix": "Update your changes to address the feedback, or",+ "guidance-suffix": "without changes",+ "re-request-review": "re-request review",+ "title": "Rejected by {{user}}"+ }+ },"run": "Run checks","select-isolation-level": "Select isolation level","select-targets": "Select Targets",@@ -1547,8 +1591,7 @@"title": "Targets","view-all": "View all ({{count}})"},- "title-required": "Title is required",- "view-discussion": "View discussion"+ "title-required": "Title is required"},"plugin": {"ai": {@@ -1936,7 +1979,6 @@}},"rollout": {- "bypass-stage-requirements": "Bypass warnings","no-stages": "No stages available","no-tasks-created": "No tasks created yet","pending-tasks-preview": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex ab1228dbf0..aa81c4852f 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -288,7 +288,6 @@"discard-changes": "Descartar cambios","discord": "Discord","dismiss": "Descartar",- "done": "Hecho","download": "Descargar","draft": "Borrador","duplicate": "Duplicar",@@ -1303,7 +1302,6 @@},"write": "Escribir"},- "create-rollout": "Crear rollout","data-export": {"download-tooltip": "Disponible por 24 horas","file-expired": "Archivo expirado",@@ -1491,19 +1489,8 @@},"phase": {"create-rollout-action": "Crear rollout manualmente",- "deploy-approval-must-complete": "El flujo de aprobación debe completarse.",- "deploy-approval-optional": "La aprobación puede omitirse según la configuración actual del proyecto.",- "deploy-approval-pending": "Completa el flujo de aprobación antes de que el rollout pueda continuar automáticamente.",- "deploy-approval-ready": "La aprobación ya está completa para este plan.",- "deploy-checks-blocked": "Las verificaciones fallidas están bloqueando la creación automática del rollout.",- "deploy-checks-must-pass": "Las comprobaciones deben aprobarse.",- "deploy-checks-optional": "Las verificaciones fallidas no bloquearán el rollout manual en este proyecto.",- "deploy-checks-ready": "Las verificaciones ya permiten la creación automática del rollout.",- "deploy-checks-running": "Espera a que terminen las verificaciones en ejecución antes de que el rollout automático pueda continuar.","deploy-description": "Bytebase creará automáticamente el rollout cuando todas las comprobaciones pasen y el issue esté aprobado.","deploy-description-gitops": "Este plan está listo para implementarse. Crea un rollout para desplegar la versión vinculada.",- "deploy-manual-create-description": "Según la configuración actual del proyecto, también puede crear el rollout manualmente.",- "deploy-manual-create-description-readonly": "Un usuario con el permiso Create Rollout puede crear el rollout manualmente.","hide-details": "Ocultar detalles","review-description": "Envíe para revisión para continuar","show-details": "Mostrar detalles"@@ -1513,6 +1500,63 @@"requirements-not-met": "Los requisitos de copia previa no se cumplen para: {{databases}}"},"ready-for-review": "Listo para revisión",+ "review": {+ "action": "Revisar",+ "activity": {+ "add-a-comment": "Añadir un comentario...",+ "created-this-plan": "creó este plan",+ "marked-ready-for-review": "marcó este plan como listo para revisión",+ "n-hidden-events_one": "{{count}} evento oculto",+ "n-hidden-events_other": "{{count}} eventos ocultos",+ "self": "Actividad",+ "show-all": "Mostrar todo"+ },+ "approval-flow": {+ "and-n-more_one": "y {{count}} más",+ "and-n-more_other": "y {{count}} más",+ "approved-by": "Aprobado por {{user}}",+ "current": "Actual",+ "n-approved": "{{n}} aprobados",+ "n-pending": "{{n}} pendientes",+ "n-reviewers_one": "{{count}} revisor",+ "n-reviewers_other": "{{count}} revisores",+ "no-reviewers": "Sin revisores",+ "rejected-by": "Rechazado por {{user}}"+ },+ "comment-required-to-reject": "Se requiere un comentario para rechazar",+ "footer": {+ "all-gates-passed": "Todos los requisitos cumplidos",+ "approved-but-checks-failed": "Revisión aprobada, pero las comprobaciones del plan fallaron",+ "auto-rollout-after-approval": "el despliegue se crea automáticamente tras la aprobación",+ "blocked-by-rejection": "Bloqueado por la revisión rechazada — atiende los comentarios de arriba para continuar",+ "bypass-and-deploy": "Omitir y desplegar",+ "confirm-acknowledge": "Omitir",+ "confirm-bypass-title": "Esto omitirá:",+ "confirm-checks-failed_one": "{{count}} comprobación del plan fallida",+ "confirm-checks-failed_other": "{{count}} comprobaciones del plan fallidas",+ "confirm-checks-running": "Comprobaciones del plan en ejecución",+ "confirm-review-not-approved": "Revisión aún no aprobada",+ "confirm-review-rejected": "Revisión rechazada",+ "creating-rollout-automatically": "creando el despliegue automáticamente...",+ "errors-passed-not-created_one": "{{count}} error, {{passed}} superadas. El despliegue no se creó automáticamente.",+ "errors-passed-not-created_other": "{{count}} errores, {{passed}} superadas. El despliegue no se creó automáticamente.",+ "gate-approval": "Aprobación del problema",+ "gate-no-failed-checks": "Sin comprobaciones fallidas",+ "gates-blocked": "No se cumplen los controles obligatorios del proyecto: el despliegue está bloqueado.",+ "n-checks-failed_one": "{{count}} comprobación fallida",+ "n-checks-failed_other": "{{count}} comprobaciones fallidas",+ "n-checks-passed_one": "{{count}} comprobación superada",+ "n-checks-passed_other": "{{count}} comprobaciones superadas",+ "rollout-blocked-by-failed-checks": "el despliegue no se creará automáticamente hasta que las comprobaciones pasen",+ "waiting-on-review": "Esperando revisión"+ },+ "rejection": {+ "guidance-prefix": "Actualiza tus cambios para atender los comentarios, o",+ "guidance-suffix": "sin cambios",+ "re-request-review": "vuelve a solicitar la revisión",+ "title": "Rechazado por {{user}}"+ }+ },"run": "Volver a verificar","select-isolation-level": "Seleccionar nivel de aislamiento","select-targets": "Seleccionar destinos",@@ -1547,8 +1591,7 @@"title": "Objetivos","view-all": "Ver todo ({{count}})"},- "title-required": "El título es obligatorio",- "view-discussion": "Ver discusión"+ "title-required": "El título es obligatorio"},"plugin": {"ai": {@@ -1936,7 +1979,6 @@}},"rollout": {- "bypass-stage-requirements": "Omitir advertencias","no-stages": "No hay etapas disponibles","no-tasks-created": "Aún no se han creado tareas","pending-tasks-preview": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex ef00459a57..67582c34c3 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -288,7 +288,6 @@"discard-changes": "変更をキャンセルする","discord": "Discord","dismiss": "閉じる",- "done": "完了","download": "ダウンロード","draft": "下書き","duplicate": "コピー",@@ -1303,7 +1302,6 @@},"write": "作成"},- "create-rollout": "ロールアウトを作成","data-export": {"download-tooltip": "24 時間利用可能","file-expired": "ファイルの有効期限が切れました",@@ -1491,19 +1489,8 @@},"phase": {"create-rollout-action": "手動でロールアウトを作成",- "deploy-approval-must-complete": "承認フローが完了している必要があります。",- "deploy-approval-optional": "現在のプロジェクト設定では、承認フローをスキップできます。",- "deploy-approval-pending": "ロールアウトを自動的に進める前に承認フローを完了してください。",- "deploy-approval-ready": "このプランの承認は完了しています。",- "deploy-checks-blocked": "失敗したチェックによりロールアウトの自動作成が止まっています。",- "deploy-checks-must-pass": "チェックに合格する必要があります。",- "deploy-checks-optional": "このプロジェクトでは、チェック失敗は手動ロールアウトを妨げません。",- "deploy-checks-ready": "チェックはロールアウトの自動作成が可能な状態です。",- "deploy-checks-running": "実行中のチェックが終わるまで、ロールアウトの自動作成は続行されません。","deploy-description": "すべてのチェックが通過し、Issue が承認されると、Bytebase は自動的にロールアウトを作成します。","deploy-description-gitops": "このプランはロールアウトの準備ができています。リンクされたリリースをデプロイするにはロールアウトを作成してください。",- "deploy-manual-create-description": "現在のプロジェクト設定に応じて、ロールアウトを手動で作成することもできます。",- "deploy-manual-create-description-readonly": "Create Rollout 権限を持つユーザーがロールアウトを手動で作成できます。","hide-details": "詳細を隠す","review-description": "続行するにはレビューに提出してください","show-details": "詳細を表示"@@ -1513,6 +1500,63 @@"requirements-not-met": "次のデータベースは事前バックアップ要件を満たしていません: {{databases}}"},"ready-for-review": "レビュー準備完了",+ "review": {+ "action": "レビュー",+ "activity": {+ "add-a-comment": "コメントを追加...",+ "created-this-plan": "がこのプランを作成しました",+ "marked-ready-for-review": "がこのプランをレビュー準備完了にしました",+ "n-hidden-events_one": "{{count}} 件の非表示イベント",+ "n-hidden-events_other": "{{count}} 件の非表示イベント",+ "self": "アクティビティ",+ "show-all": "すべて表示"+ },+ "approval-flow": {+ "and-n-more_one": "他 {{count}} 名",+ "and-n-more_other": "他 {{count}} 名",+ "approved-by": "{{user}} が承認",+ "current": "現在",+ "n-approved": "{{n}} 件承認済み",+ "n-pending": "{{n}} 件保留中",+ "n-reviewers_one": "{{count}} 名のレビュアー",+ "n-reviewers_other": "{{count}} 名のレビュアー",+ "no-reviewers": "レビュアーなし",+ "rejected-by": "{{user}} が却下"+ },+ "comment-required-to-reject": "却下するにはコメントが必要です",+ "footer": {+ "all-gates-passed": "すべての条件を満たしました",+ "approved-but-checks-failed": "レビューは承認されましたが、プランチェックに失敗しました",+ "auto-rollout-after-approval": "承認後にロールアウトが自動作成されます",+ "blocked-by-rejection": "却下されたレビューによりブロックされています — 続行するには上記のフィードバックに対応してください",+ "bypass-and-deploy": "バイパスしてデプロイ",+ "confirm-acknowledge": "バイパス",+ "confirm-bypass-title": "次をバイパスします:",+ "confirm-checks-failed_one": "{{count}} 件の失敗したプランチェック",+ "confirm-checks-failed_other": "{{count}} 件の失敗したプランチェック",+ "confirm-checks-running": "プランチェック実行中",+ "confirm-review-not-approved": "レビュー未承認",+ "confirm-review-rejected": "レビュー却下",+ "creating-rollout-automatically": "ロールアウトを自動作成中...",+ "errors-passed-not-created_one": "{{count}} 件のエラー、{{passed}} 件合格。ロールアウトは自動作成されませんでした。",+ "errors-passed-not-created_other": "{{count}} 件のエラー、{{passed}} 件合格。ロールアウトは自動作成されませんでした。",+ "gate-approval": "課題の承認",+ "gate-no-failed-checks": "失敗したプランチェックなし",+ "gates-blocked": "必須のプロジェクトゲートが満たされていないため、デプロイはブロックされています。",+ "n-checks-failed_one": "{{count}} 件のチェックに失敗",+ "n-checks-failed_other": "{{count}} 件のチェックに失敗",+ "n-checks-passed_one": "{{count}} 件のチェックに合格",+ "n-checks-passed_other": "{{count}} 件のチェックに合格",+ "rollout-blocked-by-failed-checks": "チェックが通過するまでロールアウトは自動作成されません",+ "waiting-on-review": "レビュー待ち"+ },+ "rejection": {+ "guidance-prefix": "フィードバックに対応して変更を更新するか、変更なしで",+ "guidance-suffix": "こともできます",+ "re-request-review": "レビューを再依頼する",+ "title": "{{user}} に却下されました"+ }+ },"run": "再チェック","select-isolation-level": "分離レベルを選択","select-targets": "対象を選択",@@ -1547,8 +1591,7 @@"title": "ターゲット","view-all": "すべて表示 ({{count}})"},- "title-required": "タイトルは必須です",- "view-discussion": "ディスカッションを見る"+ "title-required": "タイトルは必須です"},"plugin": {"ai": {@@ -1936,7 +1979,6 @@}},"rollout": {- "bypass-stage-requirements": "警告をバイパス","no-stages": "利用可能なステージはありません","no-tasks-created": "まだタスクが作成されていません","pending-tasks-preview": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 06dc132205..6b18b446eb 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -288,7 +288,6 @@"discard-changes": "Hủy thay đổi","discord": "Discord","dismiss": "Loại bỏ",- "done": "Hoàn tất","download": "Tải xuống","draft": "Bản nháp","duplicate": "Nhân bản",@@ -1303,7 +1302,6 @@},"write": "Viết"},- "create-rollout": "Tạo rollout","data-export": {"download-tooltip": "Có sẵn trong 24 giờ","file-expired": "Tệp đã hết hạn",@@ -1491,19 +1489,8 @@},"phase": {"create-rollout-action": "Tạo rollout thủ công",- "deploy-approval-must-complete": "Luồng phê duyệt phải hoàn tất.",- "deploy-approval-optional": "Có thể bỏ qua luồng phê duyệt theo cấu hình dự án hiện tại.",- "deploy-approval-pending": "Hoàn tất luồng phê duyệt trước khi rollout có thể tiếp tục tự động.",- "deploy-approval-ready": "Phê duyệt cho kế hoạch này đã hoàn tất.",- "deploy-checks-blocked": "Các kiểm tra lỗi đang chặn việc tạo rollout tự động.",- "deploy-checks-must-pass": "Các kiểm tra phải đạt.",- "deploy-checks-optional": "Các kiểm tra lỗi sẽ không chặn rollout thủ công trong dự án này.",- "deploy-checks-ready": "Các kiểm tra đã sẵn sàng để tạo rollout tự động.",- "deploy-checks-running": "Hãy chờ các kiểm tra đang chạy hoàn tất trước khi rollout tự động có thể tiếp tục.","deploy-description": "Bytebase sẽ tự động tạo rollout khi tất cả kiểm tra đều đạt và issue đã được phê duyệt.","deploy-description-gitops": "Kế hoạch này đã sẵn sàng để triển khai. Tạo một rollout để triển khai bản phát hành được liên kết.",- "deploy-manual-create-description": "Dựa trên cài đặt dự án hiện tại, bạn cũng có thể tạo rollout thủ công.",- "deploy-manual-create-description-readonly": "Người dùng có quyền Create Rollout có thể tạo rollout thủ công.","hide-details": "Ẩn chi tiết","review-description": "Gửi để xem xét để tiếp tục","show-details": "Hiển thị chi tiết"@@ -1513,6 +1500,63 @@"requirements-not-met": "Các cơ sở dữ liệu sau không đáp ứng yêu cầu sao lưu trước: {{databases}}"},"ready-for-review": "Sẵn sàng để xem xét",+ "review": {+ "action": "Xem xét",+ "activity": {+ "add-a-comment": "Thêm bình luận...",+ "created-this-plan": "đã tạo kế hoạch này",+ "marked-ready-for-review": "đã đánh dấu kế hoạch này sẵn sàng xét duyệt",+ "n-hidden-events_one": "{{count}} sự kiện ẩn",+ "n-hidden-events_other": "{{count}} sự kiện ẩn",+ "self": "Hoạt động",+ "show-all": "Hiển thị tất cả"+ },+ "approval-flow": {+ "and-n-more_one": "và {{count}} người khác",+ "and-n-more_other": "và {{count}} người khác",+ "approved-by": "Được phê duyệt bởi {{user}}",+ "current": "Hiện tại",+ "n-approved": "{{n}} đã phê duyệt",+ "n-pending": "{{n}} đang chờ",+ "n-reviewers_one": "{{count}} người xét duyệt",+ "n-reviewers_other": "{{count}} người xét duyệt",+ "no-reviewers": "Không có người xét duyệt",+ "rejected-by": "Bị từ chối bởi {{user}}"+ },+ "comment-required-to-reject": "Cần có bình luận để từ chối",+ "footer": {+ "all-gates-passed": "Đã đạt mọi điều kiện",+ "approved-but-checks-failed": "Xét duyệt đã được phê duyệt, nhưng kiểm tra kế hoạch thất bại",+ "auto-rollout-after-approval": "bản triển khai được tạo tự động sau khi phê duyệt",+ "blocked-by-rejection": "Bị chặn bởi xét duyệt đã từ chối — hãy xử lý phản hồi ở trên để tiếp tục",+ "bypass-and-deploy": "Bỏ qua và triển khai",+ "confirm-acknowledge": "Bỏ qua",+ "confirm-bypass-title": "Thao tác này sẽ bỏ qua:",+ "confirm-checks-failed_one": "{{count}} kiểm tra kế hoạch thất bại",+ "confirm-checks-failed_other": "{{count}} kiểm tra kế hoạch thất bại",+ "confirm-checks-running": "Kiểm tra kế hoạch đang chạy",+ "confirm-review-not-approved": "Đánh giá chưa được phê duyệt",+ "confirm-review-rejected": "Đánh giá bị từ chối",+ "creating-rollout-automatically": "đang tự động tạo bản triển khai...",+ "errors-passed-not-created_one": "{{count}} lỗi, {{passed}} đạt. Bản triển khai không được tạo tự động.",+ "errors-passed-not-created_other": "{{count}} lỗi, {{passed}} đạt. Bản triển khai không được tạo tự động.",+ "gate-approval": "Phê duyệt vấn đề",+ "gate-no-failed-checks": "Không có kiểm tra kế hoạch thất bại",+ "gates-blocked": "Các cổng bắt buộc của dự án chưa được đáp ứng — việc triển khai bị chặn.",+ "n-checks-failed_one": "{{count}} kiểm tra thất bại",+ "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-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",+ "waiting-on-review": "Đang chờ xét duyệt"+ },+ "rejection": {+ "guidance-prefix": "Cập nhật thay đổi để xử lý phản hồi, hoặc",+ "guidance-suffix": "mà không thay đổi",+ "re-request-review": "yêu cầu xét duyệt lại",+ "title": "Bị {{user}} từ chối"+ }+ },"run": "Kiểm tra lại","select-isolation-level": "Chọn mức độ cô lập","select-targets": "Chọn mục tiêu",@@ -1547,8 +1591,7 @@"title": "Mục tiêu","view-all": "Xem tất cả ({{count}})"},- "title-required": "Tiêu đề là bắt buộc",- "view-discussion": "Xem thảo luận"+ "title-required": "Tiêu đề là bắt buộc"},"plugin": {"ai": {@@ -1936,7 +1979,6 @@}},"rollout": {- "bypass-stage-requirements": "Bỏ qua cảnh báo","no-stages": "Không có giai đoạn nào","no-tasks-created": "Chưa có tác vụ nào được tạo","pending-tasks-preview": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex bcbf24388f..3e45f8314e 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -288,7 +288,6 @@"discard-changes": "取消修改","discord": "Discord","dismiss": "关闭",- "done": "完成","download": "下载","draft": "草稿","duplicate": "拷贝",@@ -1303,7 +1302,6 @@},"write": "编辑"},- "create-rollout": "创建发布","data-export": {"download-tooltip": "24 小时可用","file-expired": "文件已过期",@@ -1491,19 +1489,8 @@},"phase": {"create-rollout-action": "手动创建发布",- "deploy-approval-must-complete": "审批流必须完成。",- "deploy-approval-optional": "根据当前项目设置,审批流可以被绕过。",- "deploy-approval-pending": "在系统自动创建发布前,需要先完成审批流。",- "deploy-approval-ready": "该计划的审批已完成。",- "deploy-checks-blocked": "未通过的检查正在阻止系统自动创建发布。",- "deploy-checks-must-pass": "检查必须通过。",- "deploy-checks-optional": "在当前项目中,未通过的检查不会阻止手动创建发布。",- "deploy-checks-ready": "检查结果已满足系统自动创建发布的条件。",- "deploy-checks-running": "请等待运行中的检查完成,系统才能继续自动创建发布。","deploy-description": "当所有检查都通过且工单审批完成后,Bytebase 会自动创建发布。","deploy-description-gitops": "此计划已就绪,可以发布。创建一个发布以部署关联的 Release。",- "deploy-manual-create-description": "根据当前项目设置,你也可以手动创建发布。",- "deploy-manual-create-description-readonly": "拥有“创建发布”权限的用户可以手动创建发布。","hide-details": "隐藏详情","review-description": "提交审批以继续","show-details": "显示详情"@@ -1513,6 +1500,63 @@"requirements-not-met": "以下数据库不满足预备份要求:{{databases}}"},"ready-for-review": "准备提交评审",+ "review": {+ "action": "审批",+ "activity": {+ "add-a-comment": "添加评论...",+ "created-this-plan": "创建了此计划",+ "marked-ready-for-review": "将此计划提交审批",+ "n-hidden-events_one": "{{count}} 条隐藏动态",+ "n-hidden-events_other": "{{count}} 条隐藏动态",+ "self": "动态",+ "show-all": "显示全部"+ },+ "approval-flow": {+ "and-n-more_one": "还有 {{count}} 位",+ "and-n-more_other": "还有 {{count}} 位",+ "approved-by": "由 {{user}} 批准",+ "current": "当前",+ "n-approved": "{{n}} 人已批准",+ "n-pending": "{{n}} 个待审批",+ "n-reviewers_one": "{{count}} 位审批人",+ "n-reviewers_other": "{{count}} 位审批人",+ "no-reviewers": "无审批人",+ "rejected-by": "由 {{user}} 拒绝"+ },+ "comment-required-to-reject": "拒绝时必须填写评论",+ "footer": {+ "all-gates-passed": "所有条件已满足",+ "approved-but-checks-failed": "审批已通过,但变更检查失败",+ "auto-rollout-after-approval": "审批通过后将自动创建发布",+ "blocked-by-rejection": "已被拒绝的审批阻塞 — 请先处理上方反馈",+ "bypass-and-deploy": "跳过并发布",+ "confirm-acknowledge": "绕过",+ "confirm-bypass-title": "将绕过:",+ "confirm-checks-failed_one": "{{count}} 项失败的检查",+ "confirm-checks-failed_other": "{{count}} 项失败的检查",+ "confirm-checks-running": "检查仍在运行",+ "confirm-review-not-approved": "审核尚未通过",+ "confirm-review-rejected": "审核已被拒绝",+ "creating-rollout-automatically": "正在自动创建发布...",+ "errors-passed-not-created_one": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",+ "errors-passed-not-created_other": "{{count}} 项错误,{{passed}} 项通过。未自动创建发布。",+ "gate-approval": "工单审批",+ "gate-no-failed-checks": "无失败的检查",+ "gates-blocked": "项目所设置的条件未满足,无法部署。",+ "n-checks-failed_one": "{{count}} 项检查失败",+ "n-checks-failed_other": "{{count}} 项检查失败",+ "n-checks-passed_one": "{{count}} 项检查通过",+ "n-checks-passed_other": "{{count}} 项检查通过",+ "rollout-blocked-by-failed-checks": "在检查通过前不会自动创建发布",+ "waiting-on-review": "等待审批"+ },+ "rejection": {+ "guidance-prefix": "请根据反馈修改变更,或",+ "guidance-suffix": "(不做修改)",+ "re-request-review": "重新发起审批",+ "title": "被 {{user}} 拒绝"+ }+ },"run": "重新检查","select-isolation-level": "选择隔离级别","select-targets": "选择目标",@@ -1547,8 +1591,7 @@"title": "目标库","view-all": "查看全部 ({{count}})"},- "title-required": "标题不能为空",- "view-discussion": "查看讨论"+ "title-required": "标题不能为空"},"plugin": {"ai": {@@ -1936,7 +1979,6 @@}},"rollout": {- "bypass-stage-requirements": "绕过警告","no-stages": "暂无阶段","no-tasks-created": "尚未创建任务","pending-tasks-preview": {diff --git a/frontend/src/react/components/issue-activity/IssueCommentActivity.tsx b/frontend/src/react/components/issue-activity/IssueCommentActivity.tsxnew file mode 100644index 0000000000..3614f39f20--- /dev/null+++ b/frontend/src/react/components/issue-activity/IssueCommentActivity.tsx@@ -0,0 +1,860 @@+// Shared rendering for issue-comment activity items — the colored action icon+// badge and the human-readable action sentence (including rich plan-spec diff+// rows). Used by both the issue-detail comment list and the plan-detail review+// timeline so their icons, wordings, and detailed styles stay consistent.+import { Loader2 } from "lucide-react";+import { Fragment, type ReactNode, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import {+ type ActivityIconSpec,+ ICON_BADGE_TONE,+ ISSUE_EVENT_ICON,+ PLAN_CHANGE_ICON,+ REVIEW_DECISION_ICON,+} from "@/react/components/issue-activity/activityIcons";+import { ReadonlyDiffMonaco } from "@/react/components/monaco";+import { RouterLink } from "@/react/components/RouterLink";+import { UserAvatar } from "@/react/components/UserAvatar";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import {+ diffEntryKey,+ diffPlanSpecsForEvent,+ type SpecDiffEntry,+} from "@/react/lib/plan/diffPlanSpecs";+import { cn } from "@/react/lib/utils";+import { router } from "@/react/router";+import { buildPlanDeployRouteFromPlanName } from "@/react/router/routeHelpers";+import { useAppStore } from "@/react/stores/app";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";+import { extractUserEmail } from "@/store";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import {+ Issue_Type,+ IssueComment_Approval_Status,+ IssueStatus,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan, Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";+import type { User } from "@/types/proto-es/v1/user_service_pb";+import { extractPlanUID, getSpecDisplayInfo } from "@/utils";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import {+ enablePriorBackupOfSpec,+ sheetNameOfSpec,+ targetsOfSpec,+} from "@/utils/v1/issue/plan";+import { getSheetStatement } from "@/utils/v1/sheet";++interface ActivityProps {+ issue?: Issue;+ plan?: Plan;+ comment: IssueComment;+ // When true (the plan-detail review timeline, which already sits on the+ // plan), spec/plan references render as plain text instead of links — the+ // links would only redirect to the page you're already on (BYT-9710). The+ // issue-detail page leaves this off so its navigation links stay.+ linkless?: boolean;+}++// A DONE issue-update that created the rollout for a database-change plan — the+// timeline renders this as a "review done, rollout created" line rather than a+// plain "resolved issue".+function isDoneRolloutComment(+ issue: Issue | undefined,+ plan: Plan | undefined,+ comment: IssueComment+): boolean {+ if (comment.event.case !== "issueUpdate") {+ return false;+ }+ const { fromStatus, toStatus } = comment.event.value;+ return (+ issue?.type === Issue_Type.DATABASE_CHANGE &&+ plan?.hasRollout === true &&+ getIssueCommentType(comment) === IssueCommentType.ISSUE_UPDATE &&+ fromStatus !== undefined &&+ fromStatus !== IssueStatus.DONE &&+ toStatus === IssueStatus.DONE+ );+}++// Whether the current user may edit a comment: only user comments and approval+// decisions that carry a note are editable, and only by their author or someone+// with the update permission. Shared so both activity surfaces gate edits alike.+export function canEditIssueComment(+ comment: IssueComment,+ currentUserEmail: string,+ project: Parameters<typeof hasProjectPermissionV2>[0] | undefined+): boolean {+ if (!project) {+ return false;+ }+ const type = getIssueCommentType(comment);+ const editable =+ type === IssueCommentType.USER_COMMENT ||+ (type === IssueCommentType.APPROVAL && comment.comment !== "");+ if (!editable) {+ return false;+ }+ if (currentUserEmail === extractUserEmail(comment.creator)) {+ return true;+ }+ return hasProjectPermissionV2(project, "bb.issueComments.update");+}++// The timeline row shell shared by every activity item: the connector line, the+// left icon gutter, and a body that is a bordered card when present or a+// borderless inline header when absent. This is the single source of the+// activity-item layout for both the issue-detail list and the review timeline.+export function ActivityRowShell({+ body,+ header,+ icon,+ id,+ isLast,+ subjectSuffix,+}: {+ body?: ReactNode;+ header: ReactNode;+ icon: ReactNode;+ id?: string;+ isLast: boolean;+ subjectSuffix?: ReactNode;+}) {+ return (+ <li>+ <div className="relative pb-3" id={id}>+ {!isLast && (+ <span+ aria-hidden="true"+ className="absolute left-4 -ml-px h-full w-0.5 bg-gray-200"+ />+ )}+ <div className="relative flex items-start">+ <div className="pt-1.5">{icon}</div>+ <div className="min-w-0 flex-1">+ <div+ className={cn(+ "overflow-hidden rounded-lg border",+ body+ ? "ml-3 border-gray-200 bg-white"+ : "ml-1 border-transparent"+ )}+ >+ <div className={cn("px-3 py-2", body && "bg-gray-50")}>+ <div className="flex items-center justify-between">+ <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">+ {header}+ </div>+ {subjectSuffix}+ </div>+ </div>+ {body && (+ <div className="wrap-break-word border-t border-gray-200 px-3 py-2 text-sm text-gray-700 [&_.markdown-body>div>:first-child]:mt-0 [&_.markdown-body>div>:last-child]:mb-0">+ {body}+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </li>+ );+}++export function CommentCreator({ creator }: { creator: User }) {+ return (+ <span className="font-medium text-main">+ {creator.title || creator.email}+ </span>+ );+}++// Header line for a comment-backed activity item: creator (suppressed for the+// done-rollout system comment, whose sentence already names the actor), action+// sentence, timestamp, and an "(edited)" marker for edited user comments.+function IssueCommentHeader({ comment, issue, linkless, plan }: ActivityProps) {+ const { t } = useTranslation();+ const creatorUser = useAppStore((state) =>+ state.getUserByIdentifier(comment.creator)+ );+ const creator = creatorUser ?? unknownUser(comment.creator);+ const createdTs = getTimeForPbTimestampProtoEs(comment.createTime, 0);+ const updatedTs = getTimeForPbTimestampProtoEs(comment.updateTime, 0);+ const isEdited =+ createdTs !== updatedTs &&+ getIssueCommentType(comment) === IssueCommentType.USER_COMMENT;++ return (+ <>+ {!isDoneRolloutComment(issue, plan, comment) && (+ <CommentCreator creator={creator} />+ )}+ <IssueCommentActionSentence+ comment={comment}+ issue={issue}+ linkless={linkless}+ plan={plan}+ />+ {comment.createTime && (+ <HumanizeTs className="text-gray-500" ts={createdTs / 1000} />+ )}+ {isEdited && (+ <span className="text-xs text-gray-500">({t("common.edited")})</span>+ )}+ </>+ );+}++// A complete comment-backed activity row: icon + header assembled from the+// shared pieces, with an optional body and edit affordance supplied by the page.+export function IssueCommentRow({+ body,+ comment,+ isLast,+ issue,+ linkless,+ plan,+ subjectSuffix,+}: ActivityProps & {+ body?: ReactNode;+ isLast: boolean;+ subjectSuffix?: ReactNode;+}) {+ return (+ <ActivityRowShell+ body={body}+ header={+ <IssueCommentHeader+ comment={comment}+ issue={issue}+ linkless={linkless}+ plan={plan}+ />+ }+ icon={+ <IssueCommentActionIcon comment={comment} issue={issue} plan={plan} />+ }+ id={comment.name}+ isLast={isLast}+ subjectSuffix={subjectSuffix}+ />+ );+}++function IssueCommentActionIcon({ issue, plan, comment }: ActivityProps) {+ const creatorUser = useAppStore((state) =>+ state.getUserByIdentifier(comment.creator)+ );+ const user = creatorUser ?? unknownUser(comment.creator);+ const commentType = getIssueCommentType(comment);++ if (+ commentType === IssueCommentType.APPROVAL &&+ comment.event.case === "approval"+ ) {+ const { status } = comment.event.value;+ if (status === IssueComment_Approval_Status.APPROVED) {+ return <ActivityBadge spec={REVIEW_DECISION_ICON.approved} />;+ }+ if (status === IssueComment_Approval_Status.REJECTED) {+ return <ActivityBadge spec={REVIEW_DECISION_ICON.rejected} />;+ }+ if (status === IssueComment_Approval_Status.PENDING) {+ return <ActivityBadge spec={REVIEW_DECISION_ICON.reRequested} />;+ }+ }++ if (+ commentType === IssueCommentType.ISSUE_UPDATE &&+ comment.event.case === "issueUpdate"+ ) {+ if (isDoneRolloutComment(issue, plan, comment)) {+ return <ActivityBadge spec={ISSUE_EVENT_ICON.resolved} />;+ }++ const { fromLabels, toDescription, toLabels, toTitle } =+ comment.event.value;+ if (+ toTitle !== undefined ||+ toDescription !== undefined ||+ toLabels.length !== 0 ||+ fromLabels.length !== 0+ ) {+ return <ActivityBadge spec={ISSUE_EVENT_ICON.fieldEdit} />;+ }+ }++ if (+ commentType === IssueCommentType.PLAN_UPDATE &&+ comment.event.case === "planUpdate"+ ) {+ const entries = diffPlanSpecsForEvent(comment.event.value);+ const allAdded =+ entries.length > 0 && entries.every((e) => e.kind === "added");+ const allRemoved =+ entries.length > 0 && entries.every((e) => e.kind === "removed");+ if (allAdded) return <ActivityBadge spec={PLAN_CHANGE_ICON.added} />;+ if (allRemoved) return <ActivityBadge spec={PLAN_CHANGE_ICON.deleted} />;+ return <ActivityBadge spec={PLAN_CHANGE_ICON.edited} />;+ }++ return (+ <div className="relative pl-0.5">+ <div className="flex h-7 w-7 items-center justify-center rounded-full bg-white ring-4 ring-white">+ <UserAvatar+ className="h-7 w-7 text-[0.8rem] font-medium"+ size="sm"+ title={user.title || user.email}+ />+ </div>+ </div>+ );+}++export function CommentIconBadge({+ className,+ icon,+}: {+ className: string;+ icon: ReactNode;+}) {+ return (+ <div className="relative pl-0.5">+ <div+ className={cn(+ "flex h-7 w-7 items-center justify-center rounded-full ring-4 ring-white",+ className+ )}+ >+ {icon}+ </div>+ </div>+ );+}++// Renders an activity badge from a design-module icon spec — the white glyph on+// a tone-colored circle. The single place activity badges are built.+function ActivityBadge({ spec }: { spec: ActivityIconSpec }) {+ const { Icon, tone } = spec;+ return (+ <CommentIconBadge+ className={ICON_BADGE_TONE[tone]}+ icon={<Icon className="size-4" />}+ />+ );+}++function IssueCommentActionSentence({+ issue,+ plan,+ comment,+ linkless,+}: ActivityProps) {+ const { t } = useTranslation();+ const commentType = getIssueCommentType(comment);++ if (+ commentType === IssueCommentType.APPROVAL &&+ comment.event.case === "approval"+ ) {+ const { status } = comment.event.value;+ if (status === IssueComment_Approval_Status.APPROVED) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("custom-approval.issue-review.approved-issue")}+ </span>+ );+ }+ if (status === IssueComment_Approval_Status.REJECTED) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("custom-approval.issue-review.rejected-issue")}+ </span>+ );+ }+ if (status === IssueComment_Approval_Status.PENDING) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("custom-approval.issue-review.re-requested-review")}+ </span>+ );+ }+ }++ if (+ commentType === IssueCommentType.ISSUE_UPDATE &&+ comment.event.case === "issueUpdate"+ ) {+ const {+ fromDescription,+ fromLabels,+ fromStatus,+ fromTitle,+ toDescription,+ toLabels,+ toStatus,+ toTitle,+ } = comment.event.value;+ if (fromTitle !== undefined && toTitle !== undefined) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.changed-from-to", {+ name: t("issue.issue-name").toLowerCase(),+ newValue: toTitle,+ oldValue: fromTitle,+ })}+ </span>+ );+ }+ if (fromDescription !== undefined && toDescription !== undefined) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.changed-description")}+ </span>+ );+ }+ if (fromStatus !== undefined && toStatus !== undefined) {+ if (toStatus === IssueStatus.DONE) {+ if (isDoneRolloutComment(issue, plan, comment)) {+ // On the plan-detail timeline (linkless) the rollout is for the plan+ // you're already viewing, so drop the "for plan #id" link entirely.+ const planUID = linkless || !plan ? "" : extractPlanUID(plan.name);+ const planRoute =+ linkless || !plan+ ? undefined+ : buildPlanDeployRouteFromPlanName(plan.name);+ const sentence =+ issue?.approvalStatus === ApprovalStatus.APPROVED+ ? planUID+ ? t("activity.sentence.review-done-rollout-created-for-plan")+ : t("activity.sentence.review-done-rollout-created")+ : planUID+ ? t("activity.sentence.review-skipped-rollout-created-for-plan")+ : t("activity.sentence.review-skipped-rollout-created");++ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {sentence}+ {planUID && planRoute && (+ <>+ {" "}+ <RouterLink+ className="font-medium text-accent hover:underline"+ to={planRoute}+ >+ #{planUID}+ </RouterLink>+ </>+ )}+ </span>+ );+ }+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.resolved-issue")}+ </span>+ );+ }+ if (toStatus === IssueStatus.CANCELED) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.canceled-issue")}+ </span>+ );+ }+ if (toStatus === IssueStatus.OPEN) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.reopened-issue")}+ </span>+ );+ }+ }+ if (fromLabels.length !== 0 || toLabels.length !== 0) {+ return (+ <span className="wrap-break-word min-w-0 text-gray-600">+ {t("activity.sentence.changed-labels")}+ </span>+ );+ }+ }++ if (+ commentType === IssueCommentType.PLAN_UPDATE &&+ comment.event.case === "planUpdate"+ ) {+ const entries = diffPlanSpecsForEvent(comment.event.value);+ if (entries.length === 0) return null;+ if (entries.length === 1) {+ return (+ <SpecDiffRow+ entry={entries[0]}+ linkless={linkless}+ multi={false}+ plan={plan}+ />+ );+ }+ return (+ <div className="flex flex-col gap-1">+ {entries.map((entry) => (+ <SpecDiffRow+ entry={entry}+ key={diffEntryKey(entry)}+ linkless={linkless}+ multi+ plan={plan}+ />+ ))}+ </div>+ );+ }++ return <span className="wrap-break-word min-w-0 text-gray-600" />;+}++function SpecDiffRow({+ entry,+ linkless,+ multi,+ plan,+}: {+ entry: SpecDiffEntry;+ linkless?: boolean;+ multi?: boolean;+ plan?: Plan;+}) {+ const { t } = useTranslation();+ const planName = plan?.name ?? "";++ if (entry.kind === "added") {+ return (+ <SpecChangeRow+ linkless={linkless}+ plan={plan}+ showIndex={multi}+ specRef={specResourceName(planName, entry.spec)}+ >+ {t("activity.sentence.added-spec")}+ </SpecChangeRow>+ );+ }++ if (entry.kind === "removed") {+ return (+ <SpecChangeRow+ linkless={linkless}+ plan={plan}+ showIndex={multi}+ specRef={specResourceName(planName, entry.spec)}+ >+ {t("activity.sentence.removed-spec")}+ </SpecChangeRow>+ );+ }++ // updated. The verb fragments ("modified SQL of", "changed targets of")+ // precede the spec chip; the detail for each (SQL diff button, target +/-+ // list) trails *after* the chip so the sentence reads+ // "<verb> Change <detail>" rather than splicing the detail before the noun.+ const fragments: ReactNode[] = [];+ const trailingItems: ReactNode[] = [];+ if (entry.sheetChanged) {+ const fromSheet = sheetNameOfSpec(entry.from);+ const toSheet = sheetNameOfSpec(entry.to);+ fragments.push(+ <span key="sheet">{t("activity.sentence.modified-sql-of")}</span>+ );+ trailingItems.push(+ <IssueStatementUpdateButton+ key="sql"+ newSheet={toSheet}+ oldSheet={fromSheet}+ />+ );+ }+ if (entry.targetsChanged) {+ const fromTargets = targetsOfSpec(entry.from);+ const toTargets = targetsOfSpec(entry.to);+ const fromSet = new Set(fromTargets);+ const toSet = new Set(toTargets);+ const added = toTargets.filter((x) => !fromSet.has(x));+ const removed = fromTargets.filter((x) => !toSet.has(x));+ const diffText = [+ added.length > 0 ? `+${added.join(", ")}` : null,+ removed.length > 0 ? `-${removed.join(", ")}` : null,+ ]+ .filter(Boolean)+ .join(" ");+ fragments.push(+ <span key="targets">{t("activity.sentence.changed-targets-of")}</span>+ );+ // The raw target resource paths are noise on the plan-detail timeline+ // (linkless) — you're already viewing the plan — so only the issue page+ // shows the +/- target diff.+ if (diffText && !linkless) {+ trailingItems.push(+ <span className="text-xs text-control-light" key="targets-diff">+ {diffText}+ </span>+ );+ }+ }+ if (entry.priorBackupChanged) {+ const flipped = enablePriorBackupOfSpec(entry.to);+ fragments.push(+ <span key="backup">+ {flipped+ ? t("activity.sentence.enabled-prior-backup-on")+ : t("activity.sentence.disabled-prior-backup-on")}+ </span>+ );+ }+ if (fragments.length === 0 && entry.otherChanged) {+ // Unknown attribute change — generic fallback with a JSON-diff toggle.+ return (+ <SpecChangeRow+ linkless={linkless}+ plan={plan}+ showIndex={multi}+ specRef={specResourceName(planName, entry.to)}+ >+ <span>{t("common.updated")}</span>+ <details className="ml-2 text-xs">+ <summary className="cursor-pointer text-control-light">+ {t("common.detail")}+ </summary>+ <pre className="mt-1 max-h-48 overflow-auto rounded bg-control-bg p-2">+ {JSON.stringify({ from: entry.from, to: entry.to }, null, 2)}+ </pre>+ </details>+ </SpecChangeRow>+ );+ }++ return (+ <SpecChangeRow+ linkless={linkless}+ plan={plan}+ showIndex={multi}+ specRef={specResourceName(planName, entry.to)}+ trailing={trailingItems.length > 0 ? <>{trailingItems}</> : null}+ >+ {joinFragments(fragments, t("common.and"))}+ </SpecChangeRow>+ );+}++function specResourceName(planName: string, spec: Plan_Spec): string {+ return planName ? `${planName}/specs/${spec.id}` : `specs/${spec.id}`;+}++function SpecChangeRow({+ children,+ linkless,+ plan,+ showIndex,+ specRef,+ trailing,+}: {+ children: ReactNode;+ linkless?: boolean;+ plan?: Plan;+ showIndex?: boolean;+ specRef: string;+ trailing?: ReactNode;+}) {+ const { t } = useTranslation();+ const specs = plan?.specs ?? [];+ const specInfo = getSpecDisplayInfo(specs, specRef);+ const specIdFromRef = specRef.match(/\/specs\/([^/]+)$/)?.[1] ?? "";+ const specId = specInfo?.specId ?? specIdFromRef;+ const specIdShort = specId.slice(0, 8);+ // Only link to specs that still exist in the live plan — otherwise the spec+ // view would silently bounce back to specs[0]. On the plan-detail timeline+ // (linkless) we're already on the plan, so the link would just re-navigate to+ // the current page and the id slice is meaningless noise — render plain text.+ const specRoute =+ !linkless && specInfo?.specId+ ? {+ query: {+ ...router.currentRoute.value.query,+ spec: specInfo.specId,+ },+ }+ : null;++ // On the plan-detail timeline (linkless) we identify the change by its 1-based+ // index in the plan — shown for multi-change and edit events — or mark it+ // "(Deleted)" when the spec no longer exists. The issue page keeps the linked+ // id slice.+ let chipSuffix: ReactNode = null;+ if (linkless) {+ if (specInfo == null) {+ chipSuffix = (+ <span className="text-xs text-control-placeholder">+ ({t("common.deleted")})+ </span>+ );+ } else if (showIndex) {+ chipSuffix = (+ <span className="rounded-full bg-control-bg px-1.5 py-0.5 text-xs text-main">+ {specInfo.displayIndex}+ </span>+ );+ }+ } else if (specIdShort !== "") {+ chipSuffix = (+ <span className="rounded-full bg-control-bg px-1.5 py-0.5 text-xs text-main">+ {specIdShort}+ </span>+ );+ }++ const chip = (+ <span className="inline-flex items-center gap-1">+ {t("plan.spec.change")}+ {chipSuffix}+ </span>+ );++ return (+ <span className="inline-flex items-center gap-1 whitespace-nowrap text-gray-600">+ {children}{" "}+ {specRoute != null ? (+ <RouterLink+ className="inline-flex items-center gap-1 hover:underline"+ to={specRoute}+ >+ {chip}+ </RouterLink>+ ) : (+ chip+ )}+ {trailing != null ? <> {trailing}</> : null}+ </span>+ );+}++function joinFragments(fragments: ReactNode[], separator: string): ReactNode {+ if (fragments.length === 0) return null;+ if (fragments.length === 1) return fragments[0];+ return fragments.map((f, i) => (+ <Fragment key={i}>+ {i > 0 ? <span> {separator} </span> : null}+ {f}+ </Fragment>+ ));+}++function IssueStatementUpdateButton({+ newSheet,+ oldSheet,+}: {+ newSheet: string;+ oldSheet: string;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const [oldStatement, setOldStatement] = useState("");+ const [newStatement, setNewStatement] = useState("");+ const [isLoading, setIsLoading] = useState(false);++ useEffect(() => {+ if (!open) {+ return;+ }+ let canceled = false;+ const load = async () => {+ setIsLoading(true);+ try {+ // One side may be empty when the sheet was attached (no oldSheet)+ // or cleared (no newSheet). Treat that side as empty content+ // rather than fetching by an empty resource name.+ const fetchStatement = async (sheetName: string) => {+ if (!sheetName) return "";+ const sheet = await useAppStore+ .getState()+ .getOrFetchSheetByName(sheetName);+ return sheet ? getSheetStatement(sheet) : "";+ };+ const [oldValue, newValue] = await Promise.all([+ fetchStatement(oldSheet),+ fetchStatement(newSheet),+ ]);+ if (!canceled) {+ setOldStatement(oldValue);+ setNewStatement(newValue);+ }+ } finally {+ if (!canceled) {+ setIsLoading(false);+ }+ }+ };+ void load();+ return () => {+ canceled = true;+ };+ }, [newSheet, oldSheet, open]);++ return (+ <>+ <button+ className="inline-flex items-center text-accent hover:underline"+ onClick={() => setOpen(true)}+ type="button"+ >+ {t("common.view-details")}+ </button>+ <Dialog onOpenChange={setOpen} open={open}>+ <DialogContent className="max-w-none border-0 p-0 sm:w-[calc(100vw-9rem)] 2xl:max-w-none">+ <div className="px-6 pt-5">+ <DialogTitle>{t("common.detail")}</DialogTitle>+ </div>+ <div className="px-6 pb-6 pt-2">+ {(() => {+ // Fill the dialog instead of letting the editor shrink to+ // content height — short SQL diffs were leaving most of the+ // dialog blank. Cap at a sensible max so very tall viewports+ // don't get an awkwardly-stretched editor.+ const height = Math.min(+ 900,+ Math.max(400, window.innerHeight - 240)+ );+ if (isLoading) {+ return (+ <div+ className="flex w-full items-center justify-center rounded-md border"+ style={{ height }}+ >+ <Loader2 className="h-6 w-6 animate-spin text-control-light" />+ </div>+ );+ }+ return (+ <ReadonlyDiffMonaco+ className="w-full"+ max={height}+ min={height}+ modified={newStatement}+ original={oldStatement}+ />+ );+ })()}+ </div>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/frontend/src/react/components/issue-activity/activityIcons.ts b/frontend/src/react/components/issue-activity/activityIcons.tsnew file mode 100644index 0000000000..a4cb6d2e07--- /dev/null+++ b/frontend/src/react/components/issue-activity/activityIcons.ts@@ -0,0 +1,74 @@+// Single source of truth for review/activity icons (BYT-9713).+//+// The same action must look the same everywhere it appears — the button you+// click to approve/reject and the badge that act produces in the activity+// timeline. This module declares the canonical icon + color for each action and+// activity event; every surface consumes these specs instead of hard-coding its+// own glyph, so a change here updates all surfaces at once.+//+// Tone rule (applied consistently across every family):+// success → positive / added / done (green)+// error → negative / deleted / rejected (red)+// neutral → edits & process (gray)+//+// Icon families:+// Review decision (action + activity): approve 👍 / reject 👎 / re-request ↺+// Plan change (activity): added / deleted / edited — one symmetric "file"+// trio, so "edit a change" (FilePen) never collides with an issue-field+// edit (Pencil) or a reject.+// Issue event (activity): field edit (Pencil) / resolved (CheckCircle2)+//+// `Pencil` is reserved for exactly one meaning — an issue *field* edit.+import {+ CheckCircle2,+ FileMinus2,+ FilePen,+ FilePlus2,+ type LucideIcon,+ Pencil,+ RotateCcw,+ ThumbsDown,+ ThumbsUp,+} from "lucide-react";++export type IconTone = "success" | "error" | "neutral";++export interface ActivityIconSpec {+ Icon: LucideIcon;+ tone: IconTone;+}++// Review decisions — the only family rendered on two surfaces (the action+// buttons and the activity badges), so they share one descriptor.+export const REVIEW_DECISION_ICON = {+ approved: { Icon: ThumbsUp, tone: "success" },+ rejected: { Icon: ThumbsDown, tone: "error" },+ reRequested: { Icon: RotateCcw, tone: "neutral" },+} satisfies Record<string, ActivityIconSpec>;++// Plan change events — activity only.+export const PLAN_CHANGE_ICON = {+ added: { Icon: FilePlus2, tone: "success" },+ deleted: { Icon: FileMinus2, tone: "error" },+ edited: { Icon: FilePen, tone: "neutral" },+} satisfies Record<string, ActivityIconSpec>;++// Issue events — activity only.+export const ISSUE_EVENT_ICON = {+ fieldEdit: { Icon: Pencil, tone: "neutral" },+ resolved: { Icon: CheckCircle2, tone: "success" },+} satisfies Record<string, ActivityIconSpec>;++// Tone → classes. Activity badges fill the circle (white glyph on bg-tone);+// action buttons tint just the glyph (text-tone).+export const ICON_BADGE_TONE: Record<IconTone, string> = {+ success: "bg-success text-white",+ error: "bg-error text-white",+ neutral: "bg-control-bg text-control",+};++export const ICON_TEXT_TONE: Record<IconTone, string> = {+ success: "text-success",+ error: "text-error",+ neutral: "text-control",+};diff --git a/frontend/src/react/pages/project/issue-detail/utils/__tests__/diffPlanSpecs.test.ts b/frontend/src/react/lib/plan/diffPlanSpecs.test.tssimilarity index 98%rename from frontend/src/react/pages/project/issue-detail/utils/__tests__/diffPlanSpecs.test.tsrename to frontend/src/react/lib/plan/diffPlanSpecs.test.tsindex 855bb7fe56..88135e4880 100644--- a/frontend/src/react/pages/project/issue-detail/utils/__tests__/diffPlanSpecs.test.ts+++ b/frontend/src/react/lib/plan/diffPlanSpecs.test.ts@@ -5,7 +5,7 @@ import {type Plan_Spec,Plan_SpecSchema,} from "@/types/proto-es/v1/plan_service_pb";-import { diffPlanSpecs, type SpecDiffEntry } from "../diffPlanSpecs";+import { diffPlanSpecs, type SpecDiffEntry } from "./diffPlanSpecs";function cdcSpec(opts: {id: string;diff --git a/frontend/src/react/pages/project/issue-detail/utils/diffPlanSpecs.ts b/frontend/src/react/lib/plan/diffPlanSpecs.tssimilarity index 100%rename from frontend/src/react/pages/project/issue-detail/utils/diffPlanSpecs.tsrename to frontend/src/react/lib/plan/diffPlanSpecs.tsdiff --git a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsxindex 6686b9b806..956f1c9041 100644--- a/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx+++ b/frontend/src/react/pages/project/issue-detail/components/IssueDetailCommentList.tsx@@ -1,77 +1,33 @@import { create } from "@bufbuild/protobuf";-import {- CheckCircle2,- Loader2,- Pencil,- Play,- Plus,- ThumbsUp,- Trash2,-} from "lucide-react";-import {- Fragment,- type ReactNode,- useCallback,- useEffect,- useMemo,- useState,-} from "react";+import { Loader2, Pencil, Plus } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { issueServiceClientConnect } from "@/connect";import { HumanizeTs } from "@/react/components/HumanizeTs";+import {+ CommentCreator,+ canEditIssueComment,+ IssueCommentRow,+} from "@/react/components/issue-activity/IssueCommentActivity";import { MarkdownEditor } from "@/react/components/MarkdownEditor";-import { ReadonlyDiffMonaco } from "@/react/components/monaco";-import { RouterLink } from "@/react/components/RouterLink";import { UserAvatar } from "@/react/components/UserAvatar";import { Button } from "@/react/components/ui/button";-import {- Dialog,- DialogContent,- DialogTitle,-} from "@/react/components/ui/dialog";import { useCurrentUser } from "@/react/hooks/useAppState";import { useProjectByName } from "@/react/hooks/useProjectByName";-import { cn } from "@/react/lib/utils";-import { router, useCurrentRoute } from "@/react/router";-import { buildPlanDeployRouteFromPlanName } from "@/react/router/routeHelpers";+import { useCurrentRoute } from "@/react/router";import { useAppStore } from "@/react/stores/app";-import {- getIssueCommentType,- IssueCommentType,-} from "@/react/stores/app/issueComment";-import { extractUserEmail, pushNotification } from "@/store";+import { pushNotification } from "@/store";import { projectNamePrefix } from "@/store/modules/v1/common";import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";-import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";import {type IssueComment,- IssueComment_Approval_Status,IssueSchema,- IssueStatus,ListIssueCommentsRequestSchema,UpdateIssueRequestSchema,} from "@/types/proto-es/v1/issue_service_pb";-import type { Plan_Spec } from "@/types/proto-es/v1/plan_service_pb";-import type { User } from "@/types/proto-es/v1/user_service_pb";-import {- extractPlanUID,- extractProjectResourceName,- getSpecDisplayInfo,-} from "@/utils";+import { extractProjectResourceName } from "@/utils";import { hasProjectPermissionV2 } from "@/utils/iam/permission";-import {- enablePriorBackupOfSpec,- sheetNameOfSpec,- targetsOfSpec,-} from "@/utils/v1/issue/plan";-import { getSheetStatement } from "@/utils/v1/sheet";import { useIssueDetailContext } from "../context/IssueDetailContext";-import { isDatabaseChangeDoneRolloutComment } from "../utils/activity";-import {- diffEntryKey,- diffPlanSpecsForEvent,- type SpecDiffEntry,-} from "../utils/diffPlanSpecs";// Stable empty reference for the no-issue branch of the comments selector.const EMPTY_ISSUE_COMMENTS: IssueComment[] = [];@@ -207,22 +163,8 @@ export function IssueDetailCommentList() {);};- const allowEditComment = (comment: IssueComment): boolean => {- if (!project) {- return false;- }- const commentType = getIssueCommentType(comment);- const isEditable =- commentType === IssueCommentType.USER_COMMENT ||- (commentType === IssueCommentType.APPROVAL && comment.comment !== "");- if (!isEditable) {- return false;- }- if (currentUser.email === extractUserEmail(comment.creator)) {- return true;- }- return hasProjectPermissionV2(project, "bb.issueComments.update");- };+ const allowEditComment = (comment: IssueComment): boolean =>+ canEditIssueComment(comment, currentUser.email, project);const startEditComment = (comment: IssueComment) => {setActiveCommentName(comment.name);@@ -270,9 +212,7 @@ export function IssueDetailCommentList() {return (<IssueCommentRowkey={item.name}- isLast={index === issueComments.length - 1}- issueComment={item}- comment={+ body={item.comment ? (<EditableMarkdownContentallowSave={allowUpdateComment}@@ -289,6 +229,10 @@ export function IssueDetailCommentList() {/>) : null}+ comment={item}+ isLast={index === issueComments.length - 1}+ issue={page.issue}+ plan={page.plan}subjectSuffix={allowEditComment(item) && !activeCommentName ? (<Button@@ -427,7 +371,7 @@ function IssueDescriptionCommentRow({return (<li>- <div className="relative pb-4">+ <div className="relative pb-3">{issueComments.length > 0 && (<spanaria-hidden="true"@@ -506,561 +450,6 @@ function IssueDescriptionCommentRow({);}-function IssueCommentRow({- comment,- isLast,- issueComment,- subjectSuffix,-}: {- comment?: ReactNode;- isLast: boolean;- issueComment: IssueComment;- subjectSuffix?: ReactNode;-}) {- return (- <li>- <div className="relative pb-4" id={issueComment.name}>- {!isLast && (- <span- aria-hidden="true"- className="absolute left-4 -ml-px h-full w-0.5 bg-gray-200"- />- )}- <div className="relative flex items-start">- <div className="pt-1.5">- <CommentActionIcon issueComment={issueComment} />- </div>- <div className="min-w-0 flex-1">- <div- className={cn(- "overflow-hidden rounded-lg border",- comment- ? "ml-3 border-gray-200 bg-white"- : "ml-1 border-transparent"- )}- >- <div className={cn("px-3 py-2", comment && "bg-gray-50")}>- <div className="flex items-center justify-between">- <div className="flex min-w-0 flex-wrap items-center gap-x-2 text-sm">- <CommentActionHeader issueComment={issueComment} />- </div>- {subjectSuffix}- </div>- </div>- {comment && (- <div className="wrap-break-word border-t border-gray-200 px-4 py-3 text-sm whitespace-pre-wrap text-gray-700">- {comment}- </div>- )}- </div>- </div>- </div>- </div>- </li>- );-}--function CommentActionHeader({ issueComment }: { issueComment: IssueComment }) {- const { t } = useTranslation();- const page = useIssueDetailContext();- const creatorUser = useAppStore((state) =>- state.getUserByIdentifier(issueComment.creator)- );- const creator = creatorUser ?? unknownUser(issueComment.creator);- const createdTs = getTimeForPbTimestampProtoEs(issueComment.createTime, 0);- const updatedTs = getTimeForPbTimestampProtoEs(issueComment.updateTime, 0);- const isEdited =- createdTs !== updatedTs &&- getIssueCommentType(issueComment) === IssueCommentType.USER_COMMENT;-- return (- <>- {!isDatabaseChangeDoneRolloutComment(- page.issue,- page.plan,- issueComment- ) && <CommentCreator creator={creator} />}- <CommentActionSentence issueComment={issueComment} />- {issueComment.createTime && (- <HumanizeTs className="text-gray-500" ts={createdTs / 1000} />- )}- {isEdited && (- <span className="text-xs text-gray-500">({t("common.edited")})</span>- )}- </>- );-}--function CommentCreator({ creator }: { creator: User }) {- return (- <span className="font-medium text-main">- {creator.title || creator.email}- </span>- );-}--function CommentActionSentence({- issueComment,-}: {- issueComment: IssueComment;-}) {- const { t } = useTranslation();- const page = useIssueDetailContext();- const commentType = getIssueCommentType(issueComment);-- if (- commentType === IssueCommentType.APPROVAL &&- issueComment.event.case === "approval"- ) {- const { status } = issueComment.event.value;- if (status === IssueComment_Approval_Status.APPROVED) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("custom-approval.issue-review.approved-issue")}- </span>- );- }- if (status === IssueComment_Approval_Status.REJECTED) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("custom-approval.issue-review.rejected-issue")}- </span>- );- }- if (status === IssueComment_Approval_Status.PENDING) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("custom-approval.issue-review.re-requested-review")}- </span>- );- }- }-- if (- commentType === IssueCommentType.ISSUE_UPDATE &&- issueComment.event.case === "issueUpdate"- ) {- const {- fromDescription,- fromLabels,- fromStatus,- fromTitle,- toDescription,- toLabels,- toStatus,- toTitle,- } = issueComment.event.value;- if (fromTitle !== undefined && toTitle !== undefined) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.changed-from-to", {- name: t("issue.issue-name").toLowerCase(),- newValue: toTitle,- oldValue: fromTitle,- })}- </span>- );- }- if (fromDescription !== undefined && toDescription !== undefined) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.changed-description")}- </span>- );- }- if (fromStatus !== undefined && toStatus !== undefined) {- if (toStatus === IssueStatus.DONE) {- if (- isDatabaseChangeDoneRolloutComment(- page.issue,- page.plan,- issueComment- )- ) {- const planUID = page.plan ? extractPlanUID(page.plan.name) : "";- const planRoute = page.plan- ? buildPlanDeployRouteFromPlanName(page.plan.name)- : undefined;- const sentence =- page.issue?.approvalStatus === ApprovalStatus.APPROVED- ? planUID- ? t("activity.sentence.review-done-rollout-created-for-plan")- : t("activity.sentence.review-done-rollout-created")- : planUID- ? t("activity.sentence.review-skipped-rollout-created-for-plan")- : t("activity.sentence.review-skipped-rollout-created");-- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {sentence}- {planUID && planRoute && (- <>- {" "}- <RouterLink- to={planRoute}- className="font-medium text-accent hover:underline"- >- #{planUID}- </RouterLink>- </>- )}- </span>- );- }- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.resolved-issue")}- </span>- );- }- if (toStatus === IssueStatus.CANCELED) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.canceled-issue")}- </span>- );- }- if (toStatus === IssueStatus.OPEN) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.reopened-issue")}- </span>- );- }- }- if (fromLabels.length !== 0 || toLabels.length !== 0) {- return (- <span className="wrap-break-word min-w-0 text-gray-600">- {t("activity.sentence.changed-labels")}- </span>- );- }- }-- if (- commentType === IssueCommentType.PLAN_UPDATE &&- issueComment.event.case === "planUpdate"- ) {- const entries = diffPlanSpecsForEvent(issueComment.event.value);- if (entries.length === 0) return null;- if (entries.length === 1) {- return <SpecDiffRow entry={entries[0]} />;- }- return (- <div className="flex flex-col gap-1">- {entries.map((entry) => (- <SpecDiffRow key={diffEntryKey(entry)} entry={entry} />- ))}- </div>- );- }-- return <span className="wrap-break-word min-w-0 text-gray-600" />;-}--function SpecDiffRow({ entry }: { entry: SpecDiffEntry }) {- const { t } = useTranslation();- const page = useIssueDetailContext();- const planName = page.plan?.name ?? "";-- if (entry.kind === "added") {- return (- <SpecChangeRow specRef={specResourceName(planName, entry.spec)}>- {t("activity.sentence.added-spec")}- </SpecChangeRow>- );- }-- if (entry.kind === "removed") {- return (- <SpecChangeRow specRef={specResourceName(planName, entry.spec)}>- {t("activity.sentence.removed-spec")}- </SpecChangeRow>- );- }-- // updated- const fragments: ReactNode[] = [];- let trailing: ReactNode = null;- if (entry.sheetChanged) {- const fromSheet = sheetNameOfSpec(entry.from);- const toSheet = sheetNameOfSpec(entry.to);- fragments.push(- <span key="sheet">{t("activity.sentence.modified-sql-of")}</span>- );- trailing = (- <IssueDetailStatementUpdateButton- newSheet={toSheet}- oldSheet={fromSheet}- />- );- }- if (entry.targetsChanged) {- const fromTargets = targetsOfSpec(entry.from);- const toTargets = targetsOfSpec(entry.to);- const fromSet = new Set(fromTargets);- const toSet = new Set(toTargets);- const added = toTargets.filter((x) => !fromSet.has(x));- const removed = fromTargets.filter((x) => !toSet.has(x));- const diffText = [- added.length > 0 ? `+${added.join(", ")}` : null,- removed.length > 0 ? `-${removed.join(", ")}` : null,- ]- .filter(Boolean)- .join(" ");- fragments.push(- <span key="targets" className="inline-flex items-center gap-1">- {t("activity.sentence.changed-targets-of")}{" "}- <span className="text-xs">{diffText}</span>- </span>- );- }- if (entry.priorBackupChanged) {- const flipped = enablePriorBackupOfSpec(entry.to);- fragments.push(- <span key="backup">- {flipped- ? t("activity.sentence.enabled-prior-backup-on")- : t("activity.sentence.disabled-prior-backup-on")}- </span>- );- }- if (fragments.length === 0 && entry.otherChanged) {- // Unknown attribute change — generic fallback with a JSON-diff toggle.- return (- <SpecChangeRow specRef={specResourceName(planName, entry.to)}>- <span>{t("common.updated")}</span>- <details className="ml-2 text-xs">- <summary className="cursor-pointer text-control-light">- {t("common.detail")}- </summary>- <pre className="mt-1 max-h-48 overflow-auto rounded bg-control-bg p-2">- {JSON.stringify({ from: entry.from, to: entry.to }, null, 2)}- </pre>- </details>- </SpecChangeRow>- );- }-- return (- <SpecChangeRow- specRef={specResourceName(planName, entry.to)}- trailing={trailing}- >- {joinFragments(fragments, t("common.and"))}- </SpecChangeRow>- );-}--function specResourceName(planName: string, spec: Plan_Spec): string {- return planName ? `${planName}/specs/${spec.id}` : `specs/${spec.id}`;-}--function SpecChangeRow({- specRef,- children,- trailing,-}: {- specRef: string;- children: ReactNode;- trailing?: ReactNode;-}) {- const { t } = useTranslation();- const page = useIssueDetailContext();- const specs = page.plan?.specs ?? [];- const specInfo = getSpecDisplayInfo(specs, specRef);- const specIdFromRef = specRef.match(/\/specs\/([^/]+)$/)?.[1] ?? "";- const specId = specInfo?.specId ?? specIdFromRef;- const specIdShort = specId.slice(0, 8);- // Only link to specs that still exist in the live plan — otherwise the spec- // view would silently bounce back to specs[0].- const specRoute = specInfo?.specId- ? {- query: {- ...router.currentRoute.value.query,- spec: specInfo.specId,- },- }- : null;-- const chip = (- <span className="inline-flex items-center gap-1">- {t("plan.spec.change")}- {specIdShort !== "" ? (- <span className="rounded-full bg-control-bg px-1.5 py-0.5 text-xs text-main">- {specIdShort}- </span>- ) : null}- </span>- );-- return (- <span className="inline-flex items-center gap-1 whitespace-nowrap text-gray-600">- {children}{" "}- {specRoute != null ? (- <RouterLink- className="inline-flex items-center gap-1 hover:underline"- to={specRoute}- >- {chip}- </RouterLink>- ) : (- chip- )}- {trailing != null ? <> {trailing}</> : null}- </span>- );-}--function joinFragments(fragments: ReactNode[], separator: string): ReactNode {- if (fragments.length === 0) return null;- if (fragments.length === 1) return fragments[0];- return fragments.map((f, i) => (- <Fragment key={i}>- {i > 0 ? <span> {separator} </span> : null}- {f}- </Fragment>- ));-}--function CommentActionIcon({ issueComment }: { issueComment: IssueComment }) {- const page = useIssueDetailContext();- const creatorUser = useAppStore((state) =>- state.getUserByIdentifier(issueComment.creator)- );- const user = creatorUser ?? unknownUser(issueComment.creator);- const commentType = getIssueCommentType(issueComment);-- if (- commentType === IssueCommentType.APPROVAL &&- issueComment.event.case === "approval"- ) {- const { status } = issueComment.event.value;- if (status === IssueComment_Approval_Status.APPROVED) {- return (- <CommentIconBadge- className="bg-success text-white"- icon={<ThumbsUp className="h-4 w-4" />}- />- );- }- if (status === IssueComment_Approval_Status.REJECTED) {- return (- <CommentIconBadge- className="bg-warning text-white"- icon={<Pencil className="h-4 w-4" />}- />- );- }- if (status === IssueComment_Approval_Status.PENDING) {- return (- <CommentIconBadge- className="bg-control-bg text-control"- icon={<Play className="ml-px h-4 w-4" strokeWidth={3} />}- />- );- }- }-- if (- commentType === IssueCommentType.ISSUE_UPDATE &&- issueComment.event.case === "issueUpdate"- ) {- if (- isDatabaseChangeDoneRolloutComment(page.issue, page.plan, issueComment)- ) {- return (- <CommentIconBadge- className="bg-success text-white"- icon={<CheckCircle2 className="size-4" />}- />- );- }-- const { fromLabels, toDescription, toLabels, toTitle } =- issueComment.event.value;- if (- toTitle !== undefined ||- toDescription !== undefined ||- toLabels.length !== 0 ||- fromLabels.length !== 0- ) {- return (- <CommentIconBadge- className="bg-control-bg text-control"- icon={<Pencil className="h-4 w-4" />}- />- );- }- }-- if (- commentType === IssueCommentType.PLAN_UPDATE &&- issueComment.event.case === "planUpdate"- ) {- const entries = diffPlanSpecsForEvent(issueComment.event.value);- const allAdded =- entries.length > 0 && entries.every((e) => e.kind === "added");- const allRemoved =- entries.length > 0 && entries.every((e) => e.kind === "removed");- if (allAdded) {- return (- <CommentIconBadge- className="bg-success text-white"- icon={<Plus className="h-4 w-4" />}- />- );- }- if (allRemoved) {- return (- <CommentIconBadge- className="bg-error text-white"- icon={<Trash2 className="h-4 w-4" />}- />- );- }- return (- <CommentIconBadge- className="bg-control-bg text-control"- icon={<Pencil className="h-4 w-4" />}- />- );- }-- return (- <div className="relative pl-0.5">- <div className="flex h-7 w-7 items-center justify-center rounded-full bg-white ring-4 ring-white">- <UserAvatar- className="h-7 w-7 text-[0.8rem] font-medium"- size="sm"- title={user.title || user.email}- />- </div>- </div>- );-}--function CommentIconBadge({- className,- icon,-}: {- className: string;- icon: ReactNode;-}) {- return (- <div className="relative pl-0.5">- <div- className={cn(- "flex h-7 w-7 items-center justify-center rounded-full ring-4 ring-white",- className- )}- >- {icon}- </div>- </div>- );-}-function EditableMarkdownContent({allowSave,content,@@ -1119,105 +508,3 @@ function EditableMarkdownContent({</div>);}--function IssueDetailStatementUpdateButton({- newSheet,- oldSheet,-}: {- newSheet: string;- oldSheet: string;-}) {- const { t } = useTranslation();- const [open, setOpen] = useState(false);- const [oldStatement, setOldStatement] = useState("");- const [newStatement, setNewStatement] = useState("");- const [isLoading, setIsLoading] = useState(false);-- useEffect(() => {- if (!open) {- return;- }- let canceled = false;- const load = async () => {- setIsLoading(true);- try {- // One side may be empty when the sheet was attached (no oldSheet)- // or cleared (no newSheet). Treat that side as empty content- // rather than fetching by an empty resource name.- const fetchStatement = async (sheetName: string) => {- if (!sheetName) return "";- const sheet = await useAppStore- .getState()- .getOrFetchSheetByName(sheetName);- return sheet ? getSheetStatement(sheet) : "";- };- const [oldValue, newValue] = await Promise.all([- fetchStatement(oldSheet),- fetchStatement(newSheet),- ]);- if (!canceled) {- setOldStatement(oldValue);- setNewStatement(newValue);- }- } finally {- if (!canceled) {- setIsLoading(false);- }- }- };- void load();- return () => {- canceled = true;- };- }, [newSheet, oldSheet, open]);-- return (- <>- <button- className="inline-flex items-center text-accent hover:underline"- onClick={() => setOpen(true)}- type="button"- >- {t("common.view-details")}- </button>- <Dialog onOpenChange={setOpen} open={open}>- <DialogContent className="max-w-none border-0 p-0 sm:w-[calc(100vw-9rem)] 2xl:max-w-none">- <div className="px-6 pt-5">- <DialogTitle>{t("common.detail")}</DialogTitle>- </div>- <div className="px-6 pb-6 pt-2">- {(() => {- // Fill the dialog instead of letting the editor shrink to- // content height — short SQL diffs were leaving most of the- // dialog blank. Cap at a sensible max so very tall viewports- // don't get an awkwardly-stretched editor.- const height = Math.min(- 900,- Math.max(400, window.innerHeight - 240)- );- if (isLoading) {- return (- <div- className="flex w-full items-center justify-center rounded-md border"- style={{ height }}- >- <Loader2 className="h-6 w-6 animate-spin text-control-light" />- </div>- );- }- return (- <ReadonlyDiffMonaco- className="w-full"- max={height}- min={height}- modified={newStatement}- original={oldStatement}- />- );- })()}- </div>- </DialogContent>- </Dialog>- </>- );-}diff --git a/frontend/src/react/pages/project/issue-detail/utils/activity.ts b/frontend/src/react/pages/project/issue-detail/utils/activity.tsdeleted file mode 100644index 4cc784d41c..0000000000--- a/frontend/src/react/pages/project/issue-detail/utils/activity.ts+++ /dev/null@@ -1,27 +0,0 @@-import {- getIssueCommentType,- IssueCommentType,-} from "@/react/stores/app/issueComment";-import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import { Issue_Type, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";-import type { Plan } from "@/types/proto-es/v1/plan_service_pb";--export const isDatabaseChangeDoneRolloutComment = (- issue: Issue | undefined,- plan: Plan | undefined,- issueComment: IssueComment-) => {- if (issueComment.event.case !== "issueUpdate") {- return false;- }-- const { fromStatus, toStatus } = issueComment.event.value;- return (- issue?.type === Issue_Type.DATABASE_CHANGE &&- plan?.hasRollout === true &&- getIssueCommentType(issueComment) === IssueCommentType.ISSUE_UPDATE &&- fromStatus !== undefined &&- fromStatus !== IssueStatus.DONE &&- toStatus === IssueStatus.DONE- );-};diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsxindex e8c14ebd1d..1defe66a49 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.test.tsx@@ -76,8 +76,8 @@ vi.mock("./components/deploy/DeployTaskDetailPanel", () => ({DeployTaskDetailPanel: () => null,}));-vi.mock("./components/PlanDetailApprovalFlow", () => ({- PlanDetailReviewApprovalFlow: () => null,+vi.mock("./components/review/PlanReviewSection", () => ({+ PlanReviewSection: () => null,}));vi.mock("./components/PlanDetailChangesBranch", () => ({diff --git a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsxindex edaa3de286..74d0c1450a 100644--- a/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx+++ b/frontend/src/react/pages/project/plan-detail/ProjectPlanDetailPage.tsx@@ -23,10 +23,10 @@ import { Task_Status } from "@/types/proto-es/v1/rollout_service_pb";import { getReviewBadge } from "../utils/reviewBadge";import { DeployBranch } from "./components/deploy/DeployBranch";import { DeployTaskDetailPanel } from "./components/deploy/DeployTaskDetailPanel";-import { PlanDetailReviewApprovalFlow } from "./components/PlanDetailApprovalFlow";import { PlanDetailChangesBranch } from "./components/PlanDetailChangesBranch";import { PlanDetailDeployFuture } from "./components/PlanDetailDeployFuture";import { PlanDetailHeader } from "./components/PlanDetailHeader";+import { PlanReviewSection } from "./components/review/PlanReviewSection";import { PlanDetailStoreProvider } from "./shared/stores/PlanDetailStoreProvider";import { INLINE_TASK_PANEL_BREAKPOINT_PX } from "./shell/constants";import { usePlanDetailPage } from "./shell/hooks/usePlanDetailPage";@@ -532,11 +532,7 @@ function ReviewBranch() {);}- return (- <div className="flex flex-col">- <PlanDetailReviewApprovalFlow />- </div>- );+ return <PlanReviewSection />;}function DesktopColumn({diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsxdeleted file mode 100644index 1c96056066..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.test.tsx+++ /dev/null@@ -1,372 +0,0 @@-import type { ReactElement } from "react";-import { act } from "react";-import { createRoot } from "react-dom/client";-import { beforeEach, describe, expect, test, vi } from "vitest";-import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";-import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import { Issue_Approver_Status } from "@/types/proto-es/v1/issue_service_pb";-import type { PlanDetailPageState } from "../shell/hooks/types";-import { PlanDetailProvider } from "../shell/PlanDetailContext";-import { PlanDetailReviewApprovalFlow } from "./PlanDetailApprovalFlow";--(- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }-).IS_REACT_ACT_ENVIRONMENT = true;--const mocks = vi.hoisted(() => ({- comments: [] as Array<{- comment?: string;- creator: string;- event?: { case?: string };- }>,- getIssueComments: vi.fn(() => mocks.comments),- listIssueComments: vi.fn(async () => ({ issueComments: mocks.comments })),- requestIssue: vi.fn(async () => ({})),- routerPush: vi.fn(),- routerResolve: vi.fn(() => ({- fullPath: "/projects/p1/issues/123",- href: "/projects/p1/issues/123",- })),- useTranslation: vi.fn(() => ({- t: (key: string) => key,- })),- getOrFetchProjectByName: vi.fn(async () => ({})),- getOrFetchProjectIamPolicy: vi.fn(async () => ({})),- getProjectByName: vi.fn(() => ({ allowSelfApproval: false })),- getProjectIamPolicy: vi.fn(() => ({ bindings: [] })),- batchGetOrFetchGroups: vi.fn(async () => []),- batchGetOrFetchUsers: vi.fn(async () => []),- getOrFetchUserByIdentifier: vi.fn(async () => undefined),- pushNotification: vi.fn(),- currentUser: { email: "[email protected]", name: "users/me" },- projectIamPolicyStore: {- getOrFetchProjectIamPolicy: vi.fn(async () => ({})),- getProjectIamPolicy: vi.fn(() => ({ bindings: [] })),- },- projectStore: {- getOrFetchProjectByName: vi.fn(async () => ({})),- getProjectByName: vi.fn(() => ({ allowSelfApproval: false })),- },- roleList: [- {- name: "roles/PROJECT_OWNER",- title: "Project Owner",- },- ],- issueCommentStore: {- getIssueComments: vi.fn(() => mocks.comments),- listIssueComments: vi.fn(async () => ({ issueComments: mocks.comments })),- },-}));--vi.mock("react-i18next", () => ({- initReactI18next: { type: "3rdParty", init: () => {} },- useTranslation: mocks.useTranslation,-}));--vi.mock("@/react/router", async (importOriginal) => ({- ...(await importOriginal<typeof import("@/react/router")>()),- router: {- push: mocks.routerPush,- resolve: mocks.routerResolve,- },-}));--vi.mock("@/react/components/FeatureBadge", () => ({- FeatureBadge: () => <span data-testid="feature-badge">feature</span>,-}));--vi.mock("@/connect", () => ({- issueServiceClientConnect: {- requestIssue: mocks.requestIssue,- },-}));--vi.mock("@/store", () => ({- pushNotification: mocks.pushNotification,-}));--vi.mock("@/react/hooks/useAppState", () => ({- useCurrentUser: () => mocks.currentUser,-}));--vi.mock("@/react/stores/app", () => ({- useAppStore: Object.assign(- (selector: (state: unknown) => unknown) =>- selector({- batchGetOrFetchGroups: mocks.batchGetOrFetchGroups,- batchGetOrFetchUsers: mocks.batchGetOrFetchUsers,- getOrFetchUserByIdentifier: mocks.getOrFetchUserByIdentifier,- roleList: mocks.roleList,- loadProjectIamPolicy:- mocks.projectIamPolicyStore.getOrFetchProjectIamPolicy,- // The approval flow now subscribes to projectPoliciesByName directly- // so the candidate list re-renders when the policy resolves.- projectPoliciesByName: { "projects/p1": { bindings: [] } },- // The approval flow subscribes to projectsByName so the project- // selector re-renders when the cache changes.- projectsByName: { "projects/p1": { allowSelfApproval: false } },- getIssueComments: mocks.issueCommentStore.getIssueComments,- }),- {- getState: () => ({- listIssueComments: mocks.issueCommentStore.listIssueComments,- getOrFetchProjectByName: mocks.projectStore.getOrFetchProjectByName,- getProjectByName: mocks.projectStore.getProjectByName,- }),- }- ),-}));--vi.mock("@/store/modules/v1/common", () => ({- projectNamePrefix: "projects/",- roleNamePrefix: "roles/",- userNamePrefix: "users/",-}));--vi.mock("@/react/stores/app/issueComment", () => ({- IssueCommentType: {- APPROVAL: "APPROVAL",- },- getIssueCommentType: (comment: { event?: { case?: string } }) =>- comment.event?.case === "approval" ? "APPROVAL" : "USER_COMMENT",-}));--vi.mock("@/utils", () => ({- displayRoleTitle: (role: { title?: string; name?: string }) =>- role.title ?? role.name ?? "",- ensureUserFullName: (user: { title?: string; name?: string }) =>- user.title ?? user.name ?? "",- isBindingPolicyExpired: () => false,- memberMapToRolesInProjectIAM: () => new Map(),-}));--const renderIntoContainer = (element: ReactElement) => {- const container = document.createElement("div");- const root = createRoot(container);-- return {- container,- render: () => {- act(() => {- root.render(element);- });- },- unmount: () =>- act(() => {- root.unmount();- }),- };-};--const makePageState = ({- issue,- readonly = false,-}: {- issue?: Issue;- readonly?: boolean;-}): PlanDetailPageState =>- ({- activePhases: new Set(["review"]),- closeTaskPanel: vi.fn(),- containerWidth: 0,- expandPhase: vi.fn(),- isCreating: false,- isEditing: false,- isInitializing: false,- isRefreshing: false,- issue,- pageKey: "projects/p1/plans/1",- patchState: vi.fn(),- plan: { creator: "users/me", name: "projects/p1/plans/1" },- planCheckRuns: [],- planId: "1",- projectId: "p1",- projectTitle: "Project 1",- readonly,- ready: true,- refreshState: vi.fn(async () => undefined),- rollout: undefined,- routeName: undefined,- routePhase: undefined,- routeStageId: undefined,- routeTaskId: undefined,- selectedTaskName: undefined,- setEditing: vi.fn(),- layoutMode: "NONE",- specId: undefined,- taskRuns: [],- togglePhase: vi.fn(),- }) as unknown as PlanDetailPageState;--const makeIssue = ({- approvalStatus,- approvers = [],- roles = ["roles/PROJECT_OWNER"],- creator = "users/me",-}: {- approvalStatus: ApprovalStatus;- approvers?: Array<Record<string, unknown>>;- roles?: string[];- creator?: string;-}): Issue =>- ({- approvalStatus,- approvalTemplate: {- description: "Sensitive databases",- flow: {- roles,- },- title: "Prod policy",- },- approvers,- creator,- name: "projects/p1/issues/123",- riskLevel: 2,- }) as unknown as Issue;--beforeEach(() => {- mocks.comments = [];- mocks.issueCommentStore.getIssueComments.mockClear();- mocks.issueCommentStore.listIssueComments.mockClear();- mocks.requestIssue.mockClear();- mocks.routerPush.mockClear();- mocks.routerResolve.mockClear();- mocks.pushNotification.mockClear();- mocks.batchGetOrFetchGroups.mockClear();- mocks.projectIamPolicyStore.getOrFetchProjectIamPolicy.mockClear();- mocks.projectIamPolicyStore.getProjectIamPolicy.mockClear();- mocks.projectStore.getOrFetchProjectByName.mockClear();- mocks.projectStore.getProjectByName.mockClear();- mocks.batchGetOrFetchUsers.mockClear();- mocks.getOrFetchUserByIdentifier.mockClear();-});--describe("PlanDetailApprovalFlow", () => {- test("renders generating row for checking approval flow", () => {- const issue = makeIssue({- approvalStatus: ApprovalStatus.CHECKING,- });- const { container, render, unmount } = renderIntoContainer(- <PlanDetailProvider value={makePageState({ issue })}>- <PlanDetailReviewApprovalFlow />- </PlanDetailProvider>- );-- render();-- expect(container.textContent).toContain(- "custom-approval.issue-review.generating-approval-flow"- );- expect(container.textContent).not.toContain("issue.approval-flow.self");- expect(container.textContent).not.toContain("plan.view-discussion");-- unmount();- });-- test("renders skip placeholder when approval flow is skipped", () => {- const issue = makeIssue({- approvalStatus: ApprovalStatus.SKIPPED,- roles: [],- });- const { container, render, unmount } = renderIntoContainer(- <PlanDetailProvider value={makePageState({ issue })}>- <PlanDetailReviewApprovalFlow />- </PlanDetailProvider>- );-- render();-- expect(container.textContent).toContain(- "custom-approval.approval-flow.skip"- );- expect(container.textContent).not.toContain("issue.approval-flow.self");-- unmount();- });-- test("renders timeline header and footer link for pending approval", () => {- const issue = makeIssue({- approvalStatus: ApprovalStatus.PENDING,- approvers: [- {- principal: "users/approver",- status: Issue_Approver_Status.PENDING,- },- ],- });- const { container, render, unmount } = renderIntoContainer(- <PlanDetailProvider value={makePageState({ issue })}>- <PlanDetailReviewApprovalFlow />- </PlanDetailProvider>- );-- render();-- expect(container.textContent).toContain("issue.approval-flow.self");- expect(container.textContent).toContain("common.under-review");- expect(container.textContent).toContain(- "common.issue #123 · plan.view-discussion"- );-- const footerLink = [...container.querySelectorAll("a")].find((link) =>- link.textContent?.includes("common.issue #123 · plan.view-discussion")- );- expect(footerLink).toBeTruthy();- expect(footerLink?.getAttribute("href")).toBe("/projects/p1/issues/123");-- act(() => {- footerLink?.dispatchEvent(- new MouseEvent("click", { bubbles: true, cancelable: true })- );- });-- expect(mocks.routerPush).toHaveBeenCalledWith(- expect.objectContaining({- params: {- issueId: "123",- projectId: "p1",- },- })- );-- unmount();- });-- test("renders rejection banner and re-request action when allowed", () => {- mocks.comments = [- {- comment: "Needs more work",- creator: "[email protected]",- event: { case: "approval" },- },- ];- const issue = makeIssue({- approvalStatus: ApprovalStatus.REJECTED,- approvers: [- {- principal: "users/approver",- status: Issue_Approver_Status.REJECTED,- },- ],- creator: "users/[email protected]",- });- const { container, render, unmount } = renderIntoContainer(- <PlanDetailProvider value={makePageState({ issue })}>- <PlanDetailReviewApprovalFlow />- </PlanDetailProvider>- );-- render();-- expect(container.textContent).toContain(- "custom-approval.issue-review.rejected-by [email protected]"- );- expect(container.textContent).toContain("Needs more work");- expect(container.textContent).toContain(- "custom-approval.issue-review.re-request-review"- );-- unmount();- });-});diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsxdeleted file mode 100644index 9a99b83698..0000000000--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailApprovalFlow.tsx+++ /dev/null@@ -1,876 +0,0 @@-import { create } from "@bufbuild/protobuf";-import {- RotateCcw,- ShieldAlert,- ShieldCheck,- ThumbsUp,- User,- X,-} from "lucide-react";-import { useCallback, useEffect, useMemo, useState } from "react";-import { useTranslation } from "react-i18next";-import { issueServiceClientConnect } from "@/connect";-import { FeatureBadge } from "@/react/components/FeatureBadge";-import { RouterLink } from "@/react/components/RouterLink";-import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";-import { Button } from "@/react/components/ui/button";-import { Tooltip } from "@/react/components/ui/tooltip";-import { useCurrentUser } from "@/react/hooks/useAppState";-import { useProjectByName } from "@/react/hooks/useProjectByName";-import { displayRoleTitleFromList } from "@/react/lib/role";-import { cn } from "@/react/lib/utils";-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";-import { useAppStore } from "@/react/stores/app";-import { ensureGroupIdentifier } from "@/react/stores/app/group";-import {- getIssueCommentType,- IssueCommentType,-} from "@/react/stores/app/issueComment";-import { pushNotification } from "@/store";-import { projectNamePrefix, userNamePrefix } from "@/store/modules/v1/common";-import {- ApprovalStatus,- RiskLevel,- State,-} from "@/types/proto-es/v1/common_pb";-import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";-import {- Issue_Approver_Status,- ListIssueCommentsRequestSchema,- RequestIssueRequestSchema,-} from "@/types/proto-es/v1/issue_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import type { User as UserMessage } from "@/types/proto-es/v1/user_service_pb";-import {- AccountType,- getAccountTypeByEmail,- groupBindingPrefix,-} from "@/types/v1/user";-import {- ensureUserFullName,- isBindingPolicyExpired,- memberMapToRolesInProjectIAM,-} from "@/utils";-import { extractIssueUID } from "@/utils/v1/issue/issue";-import { usePlanDetailContext } from "../shell/PlanDetailContext";--type ApprovalStepStatus = "approved" | "rejected" | "current" | "pending";--// Stable empty array for the comments selector — the selector must return a-// cached reference when we want React to skip re-renders, otherwise the store-// subscription will treat every render as a snapshot change.-const EMPTY_COMMENTS: IssueComment[] = [];--export function PlanDetailSidebarApprovalFlow() {- return <PlanDetailApprovalFlowContent mode="sidebar" />;-}--export function PlanDetailReviewApprovalFlow() {- return <PlanDetailApprovalFlowContent mode="review" />;-}--export function PlanDetailApprovalFlow() {- return <PlanDetailSidebarApprovalFlow />;-}--function PlanDetailApprovalFlowContent({- mode,-}: {- mode: "review" | "sidebar";-}) {- const { t } = useTranslation();- const page = usePlanDetailContext();- const loadProjectIamPolicy = useAppStore(- (state) => state.loadProjectIamPolicy- );- const projectName = `${projectNamePrefix}${page.projectId}`;- const issue = page.issue;-- useEffect(() => {- void useAppStore- .getState()- .getOrFetchProjectByName(projectName)- .catch(() => undefined);- void loadProjectIamPolicy(projectName).catch(() => undefined);- }, [loadProjectIamPolicy, projectName]);-- useEffect(() => {- if (mode !== "review") {- return;- }- if (!issue?.name) {- return;- }- void useAppStore- .getState()- .listIssueComments(- create(ListIssueCommentsRequestSchema, {- parent: issue.name,- pageSize: 100,- })- )- .catch(() => undefined);- }, [issue?.name, mode]);-- // `getIssueComments` returns a stable empty array on miss, so reading it- // inside the selector won't loop.- const comments = useAppStore((state) =>- issue ? state.getIssueComments(issue.name) : EMPTY_COMMENTS- );- const lastRejection = useMemo(() => {- if (!issue || issue.approvalStatus !== ApprovalStatus.REJECTED) {- return undefined;- }- for (let i = comments.length - 1; i >= 0; i--) {- const comment = comments[i];- if (getIssueCommentType(comment) === IssueCommentType.APPROVAL) {- return {- comment: comment.comment || "",- creator: comment.creator,- };- }- }- return undefined;- }, [comments, issue]);-- if (!issue) {- return null;- }-- const approvalSteps = issue.approvalTemplate?.flow?.roles ?? [];- const statusTag = getStatusTag(issue, approvalSteps.length, t);- const issueUID = extractIssueUID(issue.name);- const riskLevelText =- issue.riskLevel === RiskLevel.LOW- ? t("issue.risk-level.low")- : issue.riskLevel === RiskLevel.MODERATE- ? t("issue.risk-level.moderate")- : issue.riskLevel === RiskLevel.HIGH- ? t("issue.risk-level.high")- : "";- const ruleText = [- issue.approvalTemplate?.title?.trim(),- issue.approvalTemplate?.description?.trim(),- ]- .filter(Boolean)- .join(" · ");-- if (issue.approvalStatus === ApprovalStatus.CHECKING) {- if (mode === "review") {- return (- <div className="flex flex-col">- <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">- <div className="h-4 w-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />- <span>- {t("custom-approval.issue-review.generating-approval-flow")}- </span>- </div>- </div>- );- }- return (- <div>- <div className="flex w-full flex-row flex-wrap items-center gap-2">- <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>- <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />- <ApprovalRiskLevelIcon- riskLevel={issue.riskLevel}- title={issue.approvalTemplate?.title?.trim()}- />- </div>- <div className="mt-2 flex items-center gap-x-2 text-sm text-control-placeholder">- <div className="h-4 w-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />- <span>- {t("custom-approval.issue-review.generating-approval-flow")}- </span>- </div>- </div>- );- }-- if (- issue.approvalStatus === ApprovalStatus.SKIPPED ||- approvalSteps.length === 0- ) {- if (mode === "review") {- return (- <div className="flex flex-col">- <div className="p-4 text-sm text-control-placeholder">- {t("custom-approval.approval-flow.skip")}- </div>- </div>- );- }- return (- <div>- <div className="flex w-full flex-row flex-wrap items-center gap-2">- <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>- <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />- <ApprovalRiskLevelIcon- riskLevel={issue.riskLevel}- title={issue.approvalTemplate?.title?.trim()}- />- </div>- <div className="mt-2 flex items-center gap-x-1 text-sm text-control-placeholder">- {t("custom-approval.approval-flow.skip")}- </div>- </div>- );- }-- if (mode === "sidebar") {- return (- <div>- <div className="flex w-full flex-row flex-wrap items-center gap-2">- <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>- <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />- <ApprovalRiskLevelIcon- riskLevel={issue.riskLevel}- title={issue.approvalTemplate?.title?.trim()}- />- <div className="grow" />- {statusTag && (- <span- className={cn(- "inline-flex items-center rounded-full px-2 py-0.5 text-xs",- statusTag.className- )}- >- {statusTag.label}- </span>- )}- </div>-- <div className="mt-2">- <div className="mt-1 flex flex-col gap-y-4 pl-1">- {approvalSteps.map((step, index) => (- <ApprovalStepItem- key={`${step}-${index}`}- issue={issue}- readonly={page.readonly}- step={step}- stepIndex={index}- stepNumber={index + 1}- totalSteps={approvalSteps.length}- />- ))}- </div>- </div>- </div>- );- }-- return (- <div className="flex flex-col">- {issue.approvalStatus === ApprovalStatus.REJECTED && lastRejection && (- <div className="mx-4 mt-3 rounded-sm border border-warning bg-warning/10 px-3 py-2 text-sm text-warning">- <div className="font-medium">- {t("custom-approval.issue-review.rejected-by")}{" "}- {lastRejection.creator}- </div>- {lastRejection.comment && (- <div className="mt-1">{lastRejection.comment}</div>- )}- </div>- )}-- <div className="px-4 py-3">- <div className="flex w-full flex-row flex-wrap items-center gap-2">- <h3 className="textinfolabel">{t("issue.approval-flow.self")}</h3>- <FeatureBadge feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />- <ApprovalRiskLevelIcon- riskLevel={issue.riskLevel}- title={issue.approvalTemplate?.title?.trim()}- />- <div className="grow" />- {statusTag && (- <span- className={cn(- "inline-flex items-center rounded-full px-2 py-0.5 text-xs",- statusTag.className- )}- >- {statusTag.label}- </span>- )}- </div>-- <div className="mt-2">- <div className="mt-1 flex flex-col gap-y-4 pl-1">- {approvalSteps.map((step, index) => (- <ApprovalStepItem- key={`${step}-${index}`}- issue={issue}- readonly={page.readonly}- step={step}- stepIndex={index}- stepNumber={index + 1}- totalSteps={approvalSteps.length}- />- ))}- </div>- </div>- </div>-- <div className="flex items-center gap-x-2 border-t px-4 py-2.5 text-sm text-control-placeholder">- <ApprovalRiskLevelIcon- riskLevel={issue.riskLevel}- title={issue.approvalTemplate?.title?.trim()}- />- {riskLevelText && <span>{riskLevelText}</span>}- {riskLevelText && ruleText && <span>·</span>}- {ruleText && <span className="min-w-0 truncate">{ruleText}</span>}- <div className="flex-1" />- <RouterLink- className="text-accent"- to={{- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,- params: {- issueId: issueUID,- projectId: page.projectId,- },- }}- >- {t("common.issue")} #{issueUID} · {t("plan.view-discussion")} →- </RouterLink>- </div>- </div>- );-}--function ApprovalStepItem({- issue,- readonly,- step,- stepIndex,- stepNumber,- totalSteps,-}: {- issue: Issue;- readonly: boolean;- step: string;- stepIndex: number;- stepNumber: number;- totalSteps: number;-}) {- const { t } = useTranslation();- const {- canReRequest,- handleReRequestReview,- potentialApprovers,- reRequesting,- roleName,- showSelfApprovalTip,- status,- stepApprover,- } = useApprovalStep(issue, step, stepIndex);-- return (- <div className="relative pl-9">- {stepIndex < totalSteps - 1 && (- <div className="absolute left-[13px] top-7 bottom-[-16px] w-px bg-control-border" />- )}-- <div- className={cn(- "absolute left-0 top-0 z-10 flex h-7 w-7 items-center justify-center rounded-full",- status === "approved"- ? "bg-success"- : status === "rejected"- ? "bg-warning"- : status === "current"- ? "bg-accent"- : "bg-control-bg"- )}- >- {status === "approved" ? (- <ThumbsUp className="h-3.5 w-3.5 text-white" />- ) : status === "rejected" ? (- <X className="h-3.5 w-3.5 text-white" />- ) : status === "current" ? (- <User className="h-3.5 w-3.5 text-white" />- ) : (- <span className="text-xs font-medium text-gray-600">- {stepNumber}- </span>- )}- </div>-- <div>- <div className="text-sm font-medium text-gray-900">{roleName}</div>- <div className="mt-1 text-sm text-gray-600">- {status === "approved" && (- <div className="flex flex-row items-center gap-1">- <span className="text-xs">- {t("custom-approval.issue-review.approved-by")}- </span>- {stepApprover?.principal && (- <ApprovalUserText candidate={stepApprover.principal} />- )}- </div>- )}-- {status === "rejected" && (- <div className="flex flex-col gap-1">- <div className="flex flex-row items-center gap-1">- <span className="text-xs">- {t("custom-approval.issue-review.rejected-by")}- </span>- {stepApprover?.principal && (- <ApprovalUserText candidate={stepApprover.principal} />- )}- </div>- {canReRequest && !readonly && (- <div className="mt-1">- <Button- className="gap-x-1.5 border border-accent/30 bg-accent/10 text-accent hover:bg-accent/15"- disabled={reRequesting}- onClick={() => {- void handleReRequestReview();- }}- size="xs"- variant="ghost"- >- <RotateCcw className="h-3 w-3" />- {t("custom-approval.issue-review.re-request-review")}- </Button>- </div>- )}- </div>- )}-- {status === "current" && !readonly && (- <div className="flex flex-col gap-1">- <PotentialApprovers users={potentialApprovers} />- {showSelfApprovalTip && (- <div className="rounded-sm border border-yellow-600 bg-yellow-50 px-1 py-0.5 text-xs text-yellow-600">- {t("custom-approval.issue-review.self-approval-not-allowed")}- </div>- )}- </div>- )}- </div>- </div>- </div>- );-}--function ApprovalUserText({ candidate }: { candidate: string }) {- const getOrFetchUserByIdentifier = useAppStore(- (state) => state.getOrFetchUserByIdentifier- );- const [user, setUser] = useState<UserMessage>();-- useEffect(() => {- let canceled = false;-- const load = async () => {- const next = await getOrFetchUserByIdentifier({- identifier: candidate,- });- if (canceled || !next) return;- if (- getAccountTypeByEmail(next.email) !== AccountType.USER ||- next.state !== State.ACTIVE- ) {- setUser(undefined);- return;- }- setUser(next);- };-- void load();- return () => {- canceled = true;- };- }, [candidate, getOrFetchUserByIdentifier]);-- if (!user) return null;-- const displayName = user.title || user.email.split("@")[0];- return (- <span className="inline-flex items-center gap-1">- <span- className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-medium text-white"- style={{ backgroundColor: getAvatarColor(displayName) }}- >- {getInitials(displayName)}- </span>- <span className="text-xs text-control">{displayName}</span>- </span>- );-}--function PotentialApprovers({ users }: { users: UserMessage[] }) {- const { t } = useTranslation();-- if (users.length === 0) return null;-- if (users.length <= 3) {- return (- <div className="flex flex-col items-start gap-1">- {users.map((user) => (- <ApprovalCandidateRow key={user.name} user={user} />- ))}- </div>- );- }-- const visibleUsers = users.slice(0, 3);- const names = visibleUsers- .map((user) => user.title || user.email.split("@")[0])- .join(", ");- const remainingCount = users.length - visibleUsers.length;-- return (- <Tooltip- content={- <div className="flex max-w-xs flex-col gap-y-1">- {users.map((user) => (- <ApprovalCandidateRow key={user.name} showEmail user={user} />- ))}- </div>- }- side="bottom"- >- <span className="cursor-pointer text-xs text-control-light hover:text-accent">- {t("custom-approval.issue-review.and-n-other-users", {- count: remainingCount,- names,- })}- </span>- </Tooltip>- );-}--function ApprovalCandidateRow({- showEmail = false,- user,-}: {- showEmail?: boolean;- user: UserMessage;-}) {- const { t } = useTranslation();- const currentUser = useCurrentUser();- const displayName = user.title || user.email.split("@")[0];- const isCurrentUser = currentUser?.name === user.name;-- return (- <div className="inline-flex items-center gap-1.5">- <span- className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-medium text-white"- style={{ backgroundColor: getAvatarColor(displayName) }}- >- {getInitials(displayName)}- </span>- <span className="text-xs text-control">{displayName}</span>- {isCurrentUser && (- <span className="rounded-full bg-success/10 px-1.5 py-0.5 text-[10px] text-success">- {t("common.you")}- </span>- )}- {showEmail && (- <span className="text-xs text-control-light">{user.email}</span>- )}- </div>- );-}--function ApprovalRiskLevelIcon({- riskLevel,- title,-}: {- riskLevel: RiskLevel;- title?: string;-}) {- const { t } = useTranslation();-- if (riskLevel === RiskLevel.RISK_LEVEL_UNSPECIFIED) {- return null;- }-- const riskLevelText =- riskLevel === RiskLevel.LOW- ? t("issue.risk-level.low")- : riskLevel === RiskLevel.MODERATE- ? t("issue.risk-level.moderate")- : t("issue.risk-level.high");-- return (- <Tooltip- content={- <div className="flex flex-col gap-1">- <div>- <span>{riskLevelText}</span>- <span className="ml-1 opacity-60">- ({t("issue.risk-level.self")})- </span>- </div>- {title && <div className="text-sm opacity-80">{title}</div>}- </div>- }- >- {riskLevel === RiskLevel.LOW ? (- <ShieldCheck className="h-4 w-4 text-success" />- ) : riskLevel === RiskLevel.MODERATE ? (- <ShieldAlert className="h-4 w-4 text-warning" />- ) : (- <ShieldAlert className="h-4 w-4 text-error" />- )}- </Tooltip>- );-}--function getStatusTag(- issue: Issue,- approvalStepCount: number,- t: ReturnType<typeof useTranslation>["t"]-) {- if (approvalStepCount === 0) {- return undefined;- }- if (issue.approvalStatus === ApprovalStatus.APPROVED) {- return {- className: "bg-success/10 text-success",- label: t("issue.table.approved"),- };- }- if (issue.approvalStatus === ApprovalStatus.REJECTED) {- return {- className: "bg-warning/10 text-warning",- label: t("common.rejected"),- };- }- if (issue.approvalStatus === ApprovalStatus.PENDING) {- return {- className: "bg-accent/10 text-accent",- label: t("common.under-review"),- };- }- return undefined;-}--function useApprovalStep(issue: Issue, step: string, stepIndex: number) {- const { t } = useTranslation();- const roleList = useAppStore((state) => state.roleList);- const page = usePlanDetailContext();- const { patchState } = page;- const currentUser = useCurrentUser();- // subscribe to re-render on project cache change- const projectsByName = useAppStore((s) => s.projectsByName);- void projectsByName;- const batchGetOrFetchUsers = useAppStore(- (state) => state.batchGetOrFetchUsers- );- const batchGetOrFetchGroups = useAppStore(- (state) => state.batchGetOrFetchGroups- );- const groupsByName = useAppStore((state) => state.groupsByName);- // Resolve groups from the app store cache the prefetch above populates.- // Depending on `groupsByName` makes candidate computation recompute once- // the prefetched groups arrive.- const getGroupByIdentifier = useCallback(- (identifier: string) => groupsByName[ensureGroupIdentifier(identifier)],- [groupsByName]- );- const [potentialApprovers, setPotentialApprovers] = useState<UserMessage[]>(- []- );- const [reRequesting, setReRequesting] = useState(false);- const projectName = `${projectNamePrefix}${page.projectId}`;- const currentUserEmail = currentUser?.email ?? "";- const project = useProjectByName(projectName);- // Subscribe directly to the Zustand project IAM cache so this step- // re-renders the moment loadProjectIamPolicy() resolves.- const projectIamPolicy = useAppStore(- (state) => state.projectPoliciesByName[projectName]- );- const stepApprover = issue.approvers[stepIndex];-- const status = useMemo<ApprovalStepStatus>(() => {- if (stepApprover?.status === Issue_Approver_Status.APPROVED) {- return "approved";- }- if (stepApprover?.status === Issue_Approver_Status.REJECTED) {- return "rejected";- }- for (let i = 0; i < stepIndex; i++) {- const previousApprover = issue.approvers[i];- if (- !previousApprover ||- (previousApprover.status !== Issue_Approver_Status.APPROVED &&- previousApprover.status !== Issue_Approver_Status.REJECTED)- ) {- return "pending";- }- if (previousApprover.status === Issue_Approver_Status.REJECTED) {- return "pending";- }- }- return "current";- }, [issue.approvers, stepApprover, stepIndex]);-- const roleName = useMemo(() => {- return step- ? displayRoleTitleFromList(step, roleList)- : t("custom-approval.approval-flow.node.approver");- }, [roleList, step, t]);-- const canReRequest = useMemo(() => {- return (- issue.creator === `${userNamePrefix}${currentUserEmail}` &&- stepApprover?.status === Issue_Approver_Status.REJECTED- );- }, [currentUserEmail, issue.creator, stepApprover?.status]);-- const groupNamesKey = useMemo(() => {- if (!projectIamPolicy) return "";- const names: string[] = [];- for (const binding of projectIamPolicy.bindings) {- if (binding.role !== step || isBindingPolicyExpired(binding)) continue;- for (const member of binding.members) {- if (member.startsWith(groupBindingPrefix)) {- names.push(member);- }- }- }- return [...new Set(names)].sort().join("\u0000");- }, [projectIamPolicy, step]);- const groupNames = useMemo(- () => (groupNamesKey ? groupNamesKey.split("\u0000") : []),- [groupNamesKey]- );-- useEffect(() => {- void batchGetOrFetchGroups(groupNames).catch(() => undefined);- }, [groupNames, batchGetOrFetchGroups]);-- const candidateEmailsKey = useMemo(() => {- if (!projectIamPolicy) return "";- const memberMap = memberMapToRolesInProjectIAM(- projectIamPolicy,- step,- getGroupByIdentifier- );- const candidates: string[] = [];- for (const fullname of memberMap.keys()) {- if (fullname.startsWith(userNamePrefix)) {- candidates.push(fullname);- }- }- return [...new Set(candidates)].sort().join("\u0000");- }, [projectIamPolicy, step, getGroupByIdentifier]);- const candidateEmails = useMemo(- () => (candidateEmailsKey ? candidateEmailsKey.split("\u0000") : []),- [candidateEmailsKey]- );-- const isCurrentUserInCandidates = useMemo(- () => candidateEmails.includes(`${userNamePrefix}${currentUserEmail}`),- [candidateEmails, currentUserEmail]- );-- const filteredCandidateEmails = useMemo(() => {- if (- !project.allowSelfApproval &&- issue.creator === `${userNamePrefix}${currentUserEmail}`- ) {- return candidateEmails.filter(- (candidate) => candidate !== `${userNamePrefix}${currentUserEmail}`- );- }- return candidateEmails;- }, [- candidateEmails,- currentUserEmail,- issue.creator,- project.allowSelfApproval,- ]);-- const showSelfApprovalTip = useMemo(() => {- return (- status === "current" &&- !project.allowSelfApproval &&- issue.creator === `${userNamePrefix}${currentUserEmail}` &&- isCurrentUserInCandidates- );- }, [- currentUserEmail,- isCurrentUserInCandidates,- issue.creator,- project.allowSelfApproval,- status,- ]);-- useEffect(() => {- let canceled = false;-- const load = async () => {- if (status !== "current" || filteredCandidateEmails.length === 0) {- setPotentialApprovers([]);- return;- }-- const users = await batchGetOrFetchUsers(- filteredCandidateEmails.map(ensureUserFullName)- );- if (canceled) return;-- const next = users- .filter(- (user) =>- user &&- user.state === State.ACTIVE &&- getAccountTypeByEmail(user.email) === AccountType.USER- )- .sort((left, right) => {- if (left.email === currentUserEmail) return -1;- if (right.email === currentUserEmail) return 1;- return left.title.localeCompare(right.title);- });- setPotentialApprovers(next);- };-- void load();- return () => {- canceled = true;- };- }, [batchGetOrFetchUsers, currentUserEmail, filteredCandidateEmails, status]);-- const handleReRequestReview = async () => {- if (reRequesting) return;-- try {- setReRequesting(true);- const response = await issueServiceClientConnect.requestIssue(- create(RequestIssueRequestSchema, { name: issue.name })- );- patchState({ issue: response });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("custom-approval.issue-review.re-request-review-success"),- });- } catch (error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("common.failed"),- description: String(error),- });- } finally {- setReRequesting(false);- }- };-- return {- canReRequest,- handleReRequestReview,- potentialApprovers,- reRequesting,- roleName,- showSelfApprovalTip,- status,- stepApprover,- };-}diff --git a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsxindex 57bfae0d07..a432ea63d7 100644--- a/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx+++ b/frontend/src/react/pages/project/plan-detail/components/PlanDetailDeployFuture.tsx@@ -1,33 +1,13 @@import { create } from "@bufbuild/protobuf";-import {- CheckCircle2,- CircleAlert,- Clock3,- Loader2,- MinusCircle,-} from "lucide-react";import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import { rolloutServiceClientConnect } from "@/connect";-import { Alert } 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 { router } from "@/react/router";import { buildPlanDeployRouteFromRolloutName } from "@/react/router/routeHelpers";import { pushNotification } from "@/store";import { State } from "@/types/proto-es/v1/common_pb";-import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";import { CreateRolloutRequestSchema } from "@/types/proto-es/v1/rollout_service_pb";-import { Advice_Level } from "@/types/proto-es/v1/sql_service_pb";-import { isApprovalCompleted } from "../../issue-detail/utils/approval";import { usePlanDetailContext } from "../shell/PlanDetailContext";import { isReleaseBackedPlan } from "../utils/spec";@@ -35,119 +15,24 @@ export function PlanDetailDeployFuture() {const { t } = useTranslation();const page = usePlanDetailContext();const [creatingRollout, setCreatingRollout] = useState(false);- const [rolloutConfirmOpen, setRolloutConfirmOpen] = useState(false);- const [bypassWarnings, setBypassWarnings] = useState(false);- const planChecksFailed = useMemo(() => {- const counts = page.plan.planCheckRunStatusCount ?? {};- return (- (counts[Advice_Level[Advice_Level.ERROR]] ?? 0) > 0 ||- (counts.FAILED ?? 0) > 0- );- }, [page.plan.planCheckRunStatusCount]);- const planChecksRunning = useMemo(() => {- const counts = page.plan.planCheckRunStatusCount ?? {};- return (counts.RUNNING ?? 0) > 0;- }, [page.plan.planCheckRunStatusCount]);- const issueApproved = isApprovalCompleted(page.issue);const isGitOpsPlan = useMemo(() => isReleaseBackedPlan(page.plan.specs),[page.plan.specs]);- // GitOps (release-backed) plans never get an issue, so allow rollout- // creation as soon as the plan is active.- const planReadyForManualRollout =- !page.plan.hasRollout &&- page.plan.state === State.ACTIVE &&- (isGitOpsPlan || (!!page.issue && page.issue.status === IssueStatus.OPEN));const canCreateRollout = Boolean(- planReadyForManualRollout && page.projectCanCreateRollout+ isGitOpsPlan &&+ !page.plan.hasRollout &&+ page.plan.state === State.ACTIVE &&+ page.projectCanCreateRollout);- const showManualCreateRolloutHint = Boolean(- planReadyForManualRollout &&- (isGitOpsPlan ||- (!(page.projectRequireIssueApproval && !issueApproved) &&- !(page.projectRequirePlanCheckNoError && planChecksFailed) &&- (!page.projectRequireIssueApproval ||- !page.projectRequirePlanCheckNoError)))- );- const manualCreateRolloutDescription = canCreateRollout- ? t("plan.phase.deploy-manual-create-description")- : t("plan.phase.deploy-manual-create-description-readonly");- const errorMessages = useMemo(() => {- const messages: string[] = [];- if (!page.projectCanCreateRollout) {- messages.push(- t("common.missing-required-permission", {- permissions: "bb.rollouts.create",- })- );- }- if (!isGitOpsPlan && page.projectRequireIssueApproval && !issueApproved) {- messages.push(- t("project.settings.issue-related.require-issue-approval.description")- );- }- if (page.projectRequirePlanCheckNoError && planChecksFailed) {- messages.push(- t(- "project.settings.issue-related.require-plan-check-no-error.description"- )- );- }- return messages;- }, [- isGitOpsPlan,- issueApproved,- page.projectCanCreateRollout,- page.projectRequireIssueApproval,- page.projectRequirePlanCheckNoError,- planChecksFailed,- t,- ]);- const warningMessages = useMemo(() => {- const messages: string[] = [];- if (!isGitOpsPlan && !page.projectRequireIssueApproval && !issueApproved) {- messages.push(- t("project.settings.issue-related.require-issue-approval.description")- );- }- if (planChecksRunning) {- messages.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- )- );- } else if (!page.projectRequirePlanCheckNoError && planChecksFailed) {- messages.push(- t(- "project.settings.issue-related.require-plan-check-no-error.description"- )- );- }- return messages;- }, [- isGitOpsPlan,- issueApproved,- page.projectRequireIssueApproval,- page.projectRequirePlanCheckNoError,- planChecksFailed,- planChecksRunning,- t,- ]);- const createRolloutDisabled =- creatingRollout ||- errorMessages.length > 0 ||- (warningMessages.length > 0 && !bypassWarnings);const createRollout = async () => {if (creatingRollout) return;try {setCreatingRollout(true);const createdRollout = await rolloutServiceClientConnect.createRollout(- create(CreateRolloutRequestSchema, {- parent: page.plan.name,- })+ create(CreateRolloutRequestSchema, { parent: page.plan.name }));pushNotification({module: "bytebase",@@ -155,7 +40,6 @@ export function PlanDetailDeployFuture() {title: t("common.created"),});await page.refreshState();- setRolloutConfirmOpen(false);void router.push(buildPlanDeployRouteFromRolloutName(createdRollout.name));@@ -171,84 +55,6 @@ export function PlanDetailDeployFuture() {}};- const requirementItems = [- page.projectRequirePlanCheckNoError- ? planChecksRunning- ? {- key: "checks",- label: t("plan.phase.deploy-checks-must-pass"),- description: t("plan.phase.deploy-checks-running"),- tagLabel: t("common.in-progress"),- statusClass: "text-warning",- icon: Clock3,- iconClass: "text-warning/80",- required: true,- }- : planChecksFailed- ? {- key: "checks",- label: t("plan.phase.deploy-checks-must-pass"),- description: t("plan.phase.deploy-checks-blocked"),- tagLabel: t("common.failed"),- statusClass: "text-error",- icon: CircleAlert,- iconClass: "text-error/80",- required: true,- }- : {- key: "checks",- label: t("plan.phase.deploy-checks-must-pass"),- description: t("plan.phase.deploy-checks-ready"),- tagLabel: t("common.done"),- statusClass: "text-success",- icon: CheckCircle2,- iconClass: "text-success/80",- required: true,- }- : {- key: "checks",- label: t("plan.phase.deploy-checks-must-pass"),- description: t("plan.phase.deploy-checks-optional"),- tagLabel: t("common.optional"),- statusClass: "text-control-placeholder",- icon: MinusCircle,- iconClass: "text-control-placeholder",- required: false,- },- page.projectRequireIssueApproval- ? issueApproved- ? {- key: "approval",- label: t("plan.phase.deploy-approval-must-complete"),- description: t("plan.phase.deploy-approval-ready"),- tagLabel: t("common.done"),- statusClass: "text-success",- icon: CheckCircle2,- iconClass: "text-success/80",- required: true,- }- : {- key: "approval",- label: t("plan.phase.deploy-approval-must-complete"),- description: t("plan.phase.deploy-approval-pending"),- tagLabel: t("common.pending"),- statusClass: "text-warning",- icon: Clock3,- iconClass: "text-warning/80",- required: true,- }- : {- key: "approval",- label: t("plan.phase.deploy-approval-must-complete"),- description: t("plan.phase.deploy-approval-optional"),- tagLabel: t("common.optional"),- statusClass: "text-control-placeholder",- icon: MinusCircle,- iconClass: "text-control-placeholder",- required: false,- },- ];-return (<div className="mt-1.5"><p className="text-sm text-control-placeholder">@@ -256,203 +62,17 @@ export function PlanDetailDeployFuture() {? t("plan.phase.deploy-description-gitops"): t("plan.phase.deploy-description")}</p>-- {page.issue && (- <ul className="mt-2.5 max-w-[28rem] space-y-1">- {requirementItems.map((item) => {- const Icon = item.icon;- return (- <li key={item.key} className="flex items-start gap-2 py-1">- <div className="flex min-w-0 items-start gap-2">- <Icon- className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${item.iconClass}`}- />- <div className="min-w-0">- <div className="flex flex-wrap items-center gap-1.5">- <span className="text-xs font-medium text-control">- {item.label}- </span>- {item.required && (- <span className="text-[10px] font-medium text-error/80">- *- </span>- )}- <span- className={`text-[11px] font-medium ${item.statusClass}`}- >- {item.tagLabel}- </span>- </div>- <p className="mt-0.5 text-[11px] text-control-placeholder">- {item.description}- </p>- </div>- </div>- </li>- );- })}- </ul>- )}-- {showManualCreateRolloutHint &&- (isGitOpsPlan ? canCreateRollout : true) && (- <div className="mt-3 flex max-w-[28rem] flex-col items-start gap-y-2">- {!isGitOpsPlan && (- <p className="text-xs text-control-placeholder">- {manualCreateRolloutDescription}- </p>- )}- {canCreateRollout && (- <Button- disabled={creatingRollout}- onClick={() => {- // GitOps plans skip the confirm sheet — there's no issue or- // approval context to display, and the user already has- // bb.rollouts.create at this point. Note this also bypasses- // soft warnings (running checks, optional approval) by design.- if (isGitOpsPlan) {- void createRollout();- return;- }- setRolloutConfirmOpen(true);- }}- size="sm"- variant="outline"- >- {t("plan.phase.create-rollout-action")}- </Button>- )}- </div>- )}-- <Sheet- onOpenChange={(open) => {- setRolloutConfirmOpen(open);- if (!open) {- setBypassWarnings(false);- }- }}- open={rolloutConfirmOpen}- >- <SheetContent- className="w-[28rem] max-w-[calc(100vw-2rem)]"- width="standard"- >- <SheetHeader>- <SheetTitle>{t("issue.create-rollout")}</SheetTitle>- </SheetHeader>- <SheetBody className="gap-y-4">- {errorMessages.length > 0 ? (- <Alert- variant="error"- title={t("common.error")}- description={- <ul className="list-inside list-disc text-sm">- {errorMessages.map((message) => (- <li key={message}>{message}</li>- ))}- </ul>- }- />- ) : warningMessages.length > 0 ? (- <Alert- variant="warning"- title={t("common.warning")}- description={- <ul className="list-inside list-disc text-sm">- {warningMessages.map((message) => (- <li key={message}>{message}</li>- ))}- </ul>- }- />- ) : null}-- {page.issue && (- <div className="flex flex-col gap-y-2">- <span className="font-medium text-control">- {t("plan.navigator.review")}- </span>- <span className="text-sm text-control-light">- {issueApproved- ? t("plan.phase.deploy-approval-ready")- : t("plan.phase.deploy-approval-pending")}- </span>- </div>- )}-- <PlanCheckStatusSummary- planChecksFailed={planChecksFailed}- planChecksRunning={planChecksRunning}- />- </SheetBody>- <SheetFooter className="justify-between">- {warningMessages.length > 0 && errorMessages.length === 0 ? (- <label className="flex items-center gap-x-2 text-sm text-control">- <Checkbox- checked={bypassWarnings}- disabled={creatingRollout}- onCheckedChange={(checked) => setBypassWarnings(checked)}- />- <span>{t("rollout.bypass-stage-requirements")}</span>- </label>- ) : (- <div />- )}- <div className="flex items-center gap-x-2">- <Button- onClick={() => setRolloutConfirmOpen(false)}- variant="ghost"- >- {t("common.cancel")}- </Button>- <Button- disabled={createRolloutDisabled}- onClick={() => void createRollout()}- >- {creatingRollout && (- <Loader2 className="h-4 w-4 animate-spin" />- )}- {t("common.confirm")}- </Button>- </div>- </SheetFooter>- </SheetContent>- </Sheet>- </div>- );-}--function PlanCheckStatusSummary({- planChecksFailed,- planChecksRunning,-}: {- planChecksFailed: boolean;- planChecksRunning: boolean;-}) {- const { t } = useTranslation();- const page = usePlanDetailContext();- const statusCount = page.plan.planCheckRunStatusCount ?? {};- const hasAnyChecks = Object.values(statusCount).some((count) => count > 0);-- return (- <div className="flex flex-col gap-y-2">- <span className="font-medium text-control">- {t("plan.navigator.checks")}- </span>- {hasAnyChecks ? (- <div className="flex flex-wrap items-center gap-2 text-sm text-control-light">- {planChecksRunning && <span>{t("common.running")}</span>}- {planChecksFailed ? (- <span className="text-error">{t("common.failed")}</span>- ) : (- <span className="text-success">{t("common.done")}</span>- )}+ {canCreateRollout && (+ <div className="mt-3">+ <Button+ disabled={creatingRollout}+ onClick={() => void createRollout()}+ size="sm"+ variant="outline"+ >+ {t("plan.phase.create-rollout-action")}+ </Button></div>- ) : (- <span className="text-sm text-control-placeholder">- {t("plan.overview.no-checks")}- </span>)}</div>);diff --git a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsxnew file mode 100644index 0000000000..b6b5c630a5--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.test.tsx@@ -0,0 +1,647 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueComment_Approval_Status,+ IssueStatus,+} from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { PlanDetailPageState } from "../../shell/hooks/types";+import { PlanDetailProvider } from "../../shell/PlanDetailContext";+import { PlanReviewSection } from "./PlanReviewSection";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++// ---------------------------------------------------------------------------+// Hoisted mocks (vi.hoisted runs before imports so vi.mock factories can+// close over these values).+// ---------------------------------------------------------------------------+const mocks = vi.hoisted(() => ({+ comments: [] as IssueComment[],+ getIssueComments: vi.fn((_issueName: string) => [] as IssueComment[]),+ listIssueComments: vi.fn(async () => ({ issueComments: [] })),+ getOrFetchProjectByName: vi.fn(async () => ({})),+ loadProjectIamPolicy: vi.fn(async () => ({})),+ getUserByIdentifier: vi.fn(() => undefined),+ roleList: [] as unknown[],+ projectsByName: {} as Record<string, unknown>,+ projectPoliciesByName: {} as Record<string, unknown>,+ groupsByName: {} as Record<string, unknown>,+ batchGetOrFetchUsers: vi.fn(async () => []),+ batchGetOrFetchGroups: vi.fn(async () => []),+ createIssueComment: vi.fn(async () => ({})),+ updateIssueComment: vi.fn(async () => ({})),+ getProjectByName: vi.fn(() => ({+ name: "projects/p1",+ allowSelfApproval: true,+ })),+ requestIssue: vi.fn(async () => ({})),+ approveIssue: vi.fn(async () => ({})),+ rejectIssue: vi.fn(async () => ({})),+ createRollout: vi.fn(async () => ({ name: "rollouts/r1", stages: [] })),+ routerPush: vi.fn(),+ routerResolve: vi.fn(() => ({+ fullPath: "/projects/p1/issues/123",+ href: "/projects/p1/issues/123",+ })),+ currentUser: {+ email: "[email protected]",+ name: "users/[email protected]",+ title: "Me",+ },+}));++// ---------------------------------------------------------------------------+// Module mocks+// ---------------------------------------------------------------------------++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({+ t: (key: string, params?: Record<string, unknown>) => {+ if (params && Object.keys(params).length > 0) {+ return `${key}:${JSON.stringify(params)}`;+ }+ return key;+ },+ }),+}));++vi.mock("@/react/stores/app", () => ({+ useAppStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector({+ getIssueComments: (issueName: string) =>+ mocks.getIssueComments(issueName),+ getUserByIdentifier: mocks.getUserByIdentifier,+ roleList: mocks.roleList,+ projectsByName: mocks.projectsByName,+ projectPoliciesByName: mocks.projectPoliciesByName,+ groupsByName: mocks.groupsByName,+ batchGetOrFetchUsers: mocks.batchGetOrFetchUsers,+ batchGetOrFetchGroups: mocks.batchGetOrFetchGroups,+ loadProjectIamPolicy: mocks.loadProjectIamPolicy,+ }),+ {+ getState: () => ({+ listIssueComments: mocks.listIssueComments,+ getOrFetchProjectByName: mocks.getOrFetchProjectByName,+ loadProjectIamPolicy: mocks.loadProjectIamPolicy,+ getProjectByName: mocks.getProjectByName,+ createIssueComment: mocks.createIssueComment,+ updateIssueComment: mocks.updateIssueComment,+ }),+ }+ ),+}));++vi.mock("@/connect", () => ({+ issueServiceClientConnect: {+ requestIssue: mocks.requestIssue,+ approveIssue: mocks.approveIssue,+ rejectIssue: mocks.rejectIssue,+ },+ rolloutServiceClientConnect: {+ createRollout: mocks.createRollout,+ },+}));++vi.mock("@/react/router", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/react/router")>()),+ router: {+ push: mocks.routerPush,+ resolve: mocks.routerResolve,+ },+}));++vi.mock("@/store", () => ({+ pushNotification: vi.fn(),+ extractUserEmail: (identifier: string) => identifier.replace(/^users\//, ""),+}));++vi.mock("@/store/modules/v1/common", () => ({+ projectNamePrefix: "projects/",+ roleNamePrefix: "roles/",+ userNamePrefix: "users/",+ issueNamePrefix: "issues/",+ getProjectIdIssueIdIssueCommentId: (name: string) => {+ const parts = name.split("/");+ return { projectId: parts[1], issueId: parts[3], issueCommentId: parts[5] };+ },+}));++vi.mock("@/react/hooks/useAppState", () => ({+ useCurrentUser: () => mocks.currentUser,+}));++vi.mock("@/react/hooks/useProjectByName", () => ({+ useProjectByName: () => ({+ name: "projects/p1",+ allowSelfApproval: true,+ }),+}));++vi.mock("@/react/components/MarkdownEditor", () => ({+ MarkdownEditor: ({ content }: { content?: string }) => (+ <div data-testid="markdown">{content}</div>+ ),+}));++vi.mock("@/react/components/HumanizeTs", () => ({+ HumanizeTs: ({ ts }: { ts: number }) => (+ <span data-testid="humanize-ts">{ts}</span>+ ),+}));++vi.mock("@/react/components/UserAvatar", () => ({+ UserAvatar: ({ title }: { title?: string }) => (+ <span data-testid="user-avatar">{title}</span>+ ),+ getAvatarColor: () => "#000",+ getInitials: (name: string) => name.slice(0, 2),+}));++vi.mock("@/react/components/RouterLink", () => ({+ RouterLink: ({+ children,+ to,+ }: {+ children: React.ReactNode;+ to: unknown;+ }) => <a href={JSON.stringify(to)}>{children}</a>,+}));++vi.mock("@/react/components/ui/tooltip", () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++vi.mock("@/react/components/ui/badge", () => ({+ Badge: ({ children }: { children: React.ReactNode }) => (+ <span>{children}</span>+ ),+}));++vi.mock("@/react/components/ui/popover", () => ({+ Popover: ({ children }: { children: React.ReactNode }) => <>{children}</>,+ PopoverTrigger: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ PopoverContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));++vi.mock("@/react/components/ui/alert", () => ({+ Alert: ({+ children,+ title,+ }: {+ children: React.ReactNode;+ title?: React.ReactNode;+ }) => (+ <div data-testid="alert">+ {title && <div data-testid="alert-title">{title}</div>}+ <div data-testid="alert-body">{children}</div>+ </div>+ ),+ alertVariants: {},+}));++vi.mock("@/react/lib/utils", () => ({+ cn: (...classes: Array<string | false | null | undefined>) =>+ classes.filter(Boolean).join(" "),+}));++vi.mock("@/react/lib/role", () => ({+ displayRoleTitleFromList: (role: string) => role,+}));++vi.mock("@/react/lib/plan/diffPlanSpecs", () => ({+ diffPlanSpecsForEvent: () => [],+ diffEntryKey: (entry: { kind: string }) => entry.kind,+}));++vi.mock("@/utils", () => ({+ displayRoleTitle: (role: { title?: string; name?: string }) =>+ role.title ?? role.name ?? "",+ ensureUserFullName: (name: string) => name,+ isBindingPolicyExpired: () => false,+ memberMapToRolesInProjectIAM: () => new Map(),+}));++vi.mock("@/utils/iam/permission", () => ({+ hasProjectPermissionV2: () => false,+}));++vi.mock("@/utils/v1/issue/issue", () => ({+ extractIssueUID: (name: string) => name.split("/").pop() ?? "",+}));++vi.mock("@/utils/v1/issue/plan", () => ({+ enablePriorBackupOfSpec: () => false,+}));++vi.mock("@/types", () => ({+ unknownUser: (principal: string) => ({+ name: principal,+ email: principal.replace(/^users\//, ""),+ title: principal.replace(/^users\//, ""),+ }),+ getTimeForPbTimestampProtoEs: () => 0,+}));++vi.mock("@/react/stores/app/issueComment", () => ({+ IssueCommentType: {+ APPROVAL: "APPROVAL",+ USER_COMMENT: "USER_COMMENT",+ ISSUE_UPDATE: "ISSUE_UPDATE",+ PLAN_UPDATE: "PLAN_UPDATE",+ },+ getIssueCommentType: (comment: { event?: { case?: string } }) => {+ if (comment.event?.case === "approval") return "APPROVAL";+ if (comment.event?.case === "issueUpdate") return "ISSUE_UPDATE";+ if (comment.event?.case === "planUpdate") return "PLAN_UPDATE";+ return "USER_COMMENT";+ },+}));++vi.mock("@/react/stores/app/group", () => ({+ ensureGroupIdentifier: (id: string) => id,+}));++vi.mock("@/types/v1/user", () => ({+ AccountType: { USER: "USER", SERVICE_ACCOUNT: "SERVICE_ACCOUNT" },+ getAccountTypeByEmail: () => "USER",+ groupBindingPrefix: "groups/",+}));++// Mock the heavy sub-components that have intractable fan-out:+// - ReviewApprovalFlow: uses ResizeObserver, many store subscriptions, Tooltip+// - ReviewActivityTimeline: uses many comment utilities, comment composer+// Both are mocked to null. ReviewRejectionBanner and ReviewReadinessFooter+// are kept real because the assertions target them directly.+vi.mock("./ReviewApprovalFlow", () => ({+ ReviewApprovalFlow: () => null,+ deriveSteps: (issue: Issue) => {+ const roles = issue.approvalTemplate?.flow?.roles ?? [];+ return roles.map((role: string, index: number) => ({+ index,+ role,+ status: "pending" as const,+ approver: undefined,+ }));+ },+}));++vi.mock("./ReviewActivityTimeline", () => ({+ ReviewActivityTimeline: () => null,+}));++// Import React for JSX — must come after vi.mock calls.+import React from "react";++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++const makeIssueComment = (status: IssueComment_Approval_Status): IssueComment =>+ ({+ name: "projects/p1/issues/123/issueComments/1",+ comment: "Needs rework",+ creator: "users/[email protected]",+ createTime: undefined,+ updateTime: undefined,+ event: {+ case: "approval" as const,+ value: { status },+ },+ }) as unknown as IssueComment;++const makeIssue = ({+ approvalStatus,+ status = IssueStatus.OPEN,+ roles = ["roles/PROJECT_OWNER"],+}: {+ approvalStatus: ApprovalStatus;+ status?: IssueStatus;+ roles?: string[];+}): Issue =>+ ({+ name: "projects/p1/issues/123",+ creator: "users/[email protected]",+ approvalStatus,+ status,+ approvers: [],+ approvalTemplate: {+ flow: { roles },+ title: "Test policy",+ },+ riskLevel: 0,+ updateTime: undefined,+ }) as unknown as Issue;++const makePlan = ({+ hasRollout = false,+ planCheckRunStatusCount = {} as Record<string, number>,+}: {+ hasRollout?: boolean;+ planCheckRunStatusCount?: Record<string, number>;+} = {}): Plan =>+ ({+ name: "projects/p1/plans/1",+ creator: "users/[email protected]",+ specs: [],+ hasRollout,+ planCheckRunStatusCount,+ createTime: undefined,+ }) as unknown as Plan;++const makePageState = (+ issue: Issue,+ plan: Plan,+ overrides: Partial<PlanDetailPageState> = {}+): PlanDetailPageState =>+ ({+ projectId: "p1",+ planId: "1",+ pageKey: "projects/p1/plans/1",+ projectTitle: "Project 1",+ plan,+ issue,+ readonly: false,+ projectCanCreateRollout: true,+ projectRequireIssueApproval: false,+ projectRequirePlanCheckNoError: false,+ isCreating: false,+ isInitializing: false,+ isEditing: false,+ isRefreshing: false,+ isRunningChecks: false,+ setIsRunningChecks: vi.fn(),+ ready: true,+ patchState: vi.fn(),+ refreshState: vi.fn(async () => undefined),+ activePhases: new Set(["review"]),+ routeName: undefined,+ routePhase: undefined,+ routeStageId: undefined,+ routeTaskId: undefined,+ selectedTaskName: undefined,+ layoutMode: "NONE",+ containerWidth: 0,+ pendingLeaveConfirm: false,+ planCheckRuns: [],+ taskRuns: [],+ rollout: undefined,+ currentUser: mocks.currentUser,+ project: { name: "projects/p1" },+ bypassLeaveGuardOnce: vi.fn(),+ setEditing: vi.fn(),+ togglePhase: vi.fn(),+ expandPhase: vi.fn(),+ closeTaskPanel: vi.fn(),+ resolveLeaveConfirm: vi.fn(),+ ...overrides,+ }) as unknown as PlanDetailPageState;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ };+};++// ---------------------------------------------------------------------------+// Setup+// ---------------------------------------------------------------------------++beforeEach(() => {+ mocks.comments = [];+ mocks.getIssueComments.mockImplementation(() => mocks.comments);+ vi.clearAllMocks();+ mocks.getIssueComments.mockImplementation(() => mocks.comments);+});++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++describe("PlanReviewSection — five review states", () => {+ test("in-progress (PENDING, checks pass): footer shows waiting-on-review + muted underline bypass link", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.PENDING });+ const plan = makePlan();+ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ expect(container.textContent).toContain(+ "plan.review.footer.waiting-on-review"+ );+ // Muted underline link — not a primary Button+ const underlineBtn = container.querySelector("button.underline");+ expect(underlineBtn).not.toBeNull();+ expect(underlineBtn?.textContent).toContain(+ "plan.review.footer.bypass-and-deploy"+ );+ // Should NOT be a primary Button element (no class "underline" on shared Button)+ expect(container.textContent).not.toContain(+ "plan.review.footer.blocked-by-rejection"+ );+ expect(container.textContent).not.toContain(+ "plan.review.footer.all-gates-passed"+ );++ unmount();+ });++ // BYT-9709: with failed checks the rollout will NOT be created automatically+ // after approval, so the waiting-review line must not promise auto-creation.+ test("in-progress (PENDING) + checks failed: footer drops the auto-rollout promise", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.PENDING });+ const plan = makePlan({+ planCheckRunStatusCount: { ERROR: 1, SUCCESS: 2 },+ });+ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ expect(container.textContent).toContain(+ "plan.review.footer.waiting-on-review"+ );+ expect(container.textContent).not.toContain(+ "plan.review.footer.auto-rollout-after-approval"+ );+ expect(container.textContent).toContain(+ "plan.review.footer.rollout-blocked-by-failed-checks"+ );++ unmount();+ });++ test("rejected (REJECTED + rejection comment): rejection banner renders + footer shows blocked-by-rejection + bypass action (explicit override)", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.REJECTED });+ const plan = makePlan();+ const rejectionComment = makeIssueComment(+ IssueComment_Approval_Status.REJECTED+ );+ mocks.comments = [rejectionComment];+ mocks.getIssueComments.mockImplementation(() => mocks.comments);++ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ // Rejection banner should be visible+ const alertTitle = container.querySelector("[data-testid='alert-title']");+ expect(alertTitle).not.toBeNull();+ expect(alertTitle?.textContent).toContain("plan.review.rejection.title");++ // Footer shows blocked-by-rejection+ expect(container.textContent).toContain(+ "plan.review.footer.blocked-by-rejection"+ );++ // A rejected review still offers an explicit bypass-and-deploy override+ // (the page state grants bb.rollouts.create and is not readonly).+ expect(container.textContent).toContain(+ "plan.review.footer.bypass-and-deploy"+ );++ unmount();+ });++ test("approved + checks failed (APPROVED, ERROR>0): footer shows approved-but-checks-failed + primary Button bypass", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.APPROVED });+ // Simulate error checks via planCheckRunStatusCount using Advice_Level.ERROR key+ const plan = makePlan({+ planCheckRunStatusCount: { ERROR: 3, SUCCESS: 2 },+ });++ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ expect(container.textContent).toContain(+ "plan.review.footer.approved-but-checks-failed"+ );++ // Primary Button — the shared Button component renders without the underline+ // class; verify bypass-and-deploy text is present.+ expect(container.textContent).toContain(+ "plan.review.footer.bypass-and-deploy"+ );+ // Must NOT be the muted underline link+ const underlineBtn = container.querySelector("button.underline");+ expect(underlineBtn).toBeNull();++ unmount();+ });++ test("approved + checks passed (APPROVED, checks pass): footer shows all-gates-passed + muted underline link", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.APPROVED });+ const plan = makePlan({ planCheckRunStatusCount: { SUCCESS: 5 } });++ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ expect(container.textContent).toContain(+ "plan.review.footer.all-gates-passed"+ );+ // Muted underline link present+ const underlineBtn = container.querySelector("button.underline");+ expect(underlineBtn).not.toBeNull();+ expect(underlineBtn?.textContent).toContain(+ "plan.review.footer.bypass-and-deploy"+ );++ unmount();+ });++ test("skipped (SKIPPED): skip line renders + footer shows all-gates-passed", () => {+ const issue = makeIssue({+ approvalStatus: ApprovalStatus.SKIPPED,+ roles: [],+ });+ const plan = makePlan({ planCheckRunStatusCount: { SUCCESS: 2 } });++ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ // Skip placeholder rendered in PlanReviewSection itself+ expect(container.textContent).toContain(+ "custom-approval.approval-flow.skip"+ );+ expect(container.textContent).toContain(+ "plan.review.footer.all-gates-passed"+ );++ unmount();+ });++ test("footer disappears once a rollout exists (hasRollout true → no bypass action)", () => {+ const issue = makeIssue({ approvalStatus: ApprovalStatus.PENDING });+ const plan = makePlan({ hasRollout: true });++ const { container, render, unmount } = renderIntoContainer(+ <PlanDetailProvider value={makePageState(issue, plan)}>+ <PlanReviewSection />+ </PlanDetailProvider>+ );++ render();++ // Footer is entirely hidden — no footer keys, no bypass button+ expect(container.textContent).not.toContain(+ "plan.review.footer.waiting-on-review"+ );+ expect(container.textContent).not.toContain(+ "plan.review.footer.bypass-and-deploy"+ );+ expect(container.textContent).not.toContain(+ "plan.review.footer.all-gates-passed"+ );++ unmount();+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsxnew file mode 100644index 0000000000..aa926ffd87--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/PlanReviewSection.tsx@@ -0,0 +1,93 @@+import { create } from "@bufbuild/protobuf";+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import { useAppStore } from "@/react/stores/app";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import { ListIssueCommentsRequestSchema } from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { ReviewActivityTimeline } from "./ReviewActivityTimeline";+import { ReviewApprovalFlow } from "./ReviewApprovalFlow";+import { ReviewReadinessFooter } from "./ReviewReadinessFooter";+import { ReviewRejectionBanner } from "./ReviewRejectionBanner";+import { PlanReviewSectionHeader } from "./ReviewSectionHeader";++const EMPTY_COMMENTS: IssueComment[] = [];++export function PlanReviewSection() {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const issue = page.issue;+ const issueName = issue?.name ?? "";+ const issueUpdateKey = `${issue?.updateTime?.seconds ?? ""}:${issue?.updateTime?.nanos ?? ""}`;+ const loadProjectIamPolicy = useAppStore(+ (state) => state.loadProjectIamPolicy+ );++ // Candidate computation needs project + IAM in the cache.+ useEffect(() => {+ const projectName = `${projectNamePrefix}${page.projectId}`;+ void useAppStore+ .getState()+ .getOrFetchProjectByName(projectName)+ .catch(() => undefined);+ void loadProjectIamPolicy(projectName).catch(() => undefined);+ }, [loadProjectIamPolicy, page.projectId]);++ // Refetch comments whenever the issue changes server-side (polling bumps+ // updateTime) or after local actions refresh the issue.+ useEffect(() => {+ if (!issueName) return;+ void useAppStore+ .getState()+ .listIssueComments(+ create(ListIssueCommentsRequestSchema, {+ parent: issueName,+ pageSize: 1000,+ })+ )+ .catch(() => undefined);+ }, [issueName, issueUpdateKey]);++ const comments = useAppStore((state) =>+ issueName ? state.getIssueComments(issueName) : EMPTY_COMMENTS+ );++ if (!issue) return null;++ if (issue.approvalStatus === ApprovalStatus.CHECKING) {+ return (+ <div className="flex items-center gap-x-2 p-4 text-sm text-control-placeholder">+ <div className="size-4 animate-spin rounded-full border-2 border-control-border border-t-accent" />+ <span>+ {t("custom-approval.issue-review.generating-approval-flow")}+ </span>+ </div>+ );+ }++ const skipped =+ issue.approvalStatus === ApprovalStatus.SKIPPED ||+ (issue.approvalTemplate?.flow?.roles ?? []).length === 0;++ return (+ <div className="flex flex-col">+ <PlanReviewSectionHeader issue={issue} />+ {skipped ? (+ <div className="px-4 py-3 text-sm text-control-placeholder">+ {t("custom-approval.approval-flow.skip")}+ </div>+ ) : (+ <ReviewApprovalFlow issue={issue} />+ )}+ <ReviewRejectionBanner comments={comments} issue={issue} />+ <ReviewActivityTimeline+ comments={comments}+ issue={issue}+ plan={page.plan}+ />+ <ReviewReadinessFooter issue={issue} plan={page.plan} />+ </div>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewActionPopover.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActionPopover.tsxnew file mode 100644index 0000000000..380c084a27--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActionPopover.tsx@@ -0,0 +1,183 @@+import { create } from "@bufbuild/protobuf";+import { Loader2, MessageCircle } from "lucide-react";+import { type ReactNode, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { issueServiceClientConnect } from "@/connect";+import {+ type ActivityIconSpec,+ ICON_TEXT_TONE,+ REVIEW_DECISION_ICON,+} from "@/react/components/issue-activity/activityIcons";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { Button } from "@/react/components/ui/button";+import { Tooltip } from "@/react/components/ui/tooltip";+import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";+import { pushNotification } from "@/store";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import {+ ApproveIssueRequestSchema,+ RejectIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";++type ReviewAction = "COMMENT" | "APPROVE" | "REJECT";++export function ReviewActionPopover({+ issue,+ onClose,+}: {+ issue: Issue;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const [action, setAction] = useState<ReviewAction>("COMMENT");+ const [comment, setComment] = useState("");+ const [loading, setLoading] = useState(false);++ useEffect(() => {+ setAction("COMMENT");+ setComment("");+ }, [issue.name]);++ const commentMissing = comment.trim().length === 0;+ const submitDisabled =+ loading ||+ (action === "COMMENT" && commentMissing) ||+ (action === "REJECT" && commentMissing);++ const submit = async () => {+ if (submitDisabled) return;+ try {+ setLoading(true);+ if (action === "APPROVE") {+ const response = await issueServiceClientConnect.approveIssue(+ create(ApproveIssueRequestSchema, { comment, name: issue.name })+ );+ page.patchState({ issue: response });+ } else if (action === "REJECT") {+ const response = await issueServiceClientConnect.rejectIssue(+ create(RejectIssueRequestSchema, { comment, name: issue.name })+ );+ page.patchState({ issue: response });+ } else {+ await useAppStore.getState().createIssueComment({+ issueName: issue.name,+ comment,+ });+ }+ await page.refreshState();+ onClose();+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setLoading(false);+ }+ };++ return (+ <div className="flex w-[min(34rem,calc(100vw-2rem))] flex-col gap-y-3">+ <MarkdownEditor+ content={comment}+ onChange={setComment}+ onSubmit={() => void submit()}+ />+ <div className="flex flex-col gap-y-2.5">+ <ReviewOption+ description={t("issue.review.comment-description")}+ icon={<MessageCircle className="size-4 text-control" />}+ label={t("common.comment")}+ onSelect={() => setAction("COMMENT")}+ selected={action === "COMMENT"}+ />+ <ReviewOption+ description={t("issue.review.approve-description")}+ icon={<DecisionIcon spec={REVIEW_DECISION_ICON.approved} />}+ label={t("common.approve")}+ onSelect={() => setAction("APPROVE")}+ selected={action === "APPROVE"}+ />+ <ReviewOption+ description={t("issue.review.reject-description")}+ icon={<DecisionIcon spec={REVIEW_DECISION_ICON.rejected} />}+ label={t("common.reject")}+ onSelect={() => setAction("REJECT")}+ selected={action === "REJECT"}+ />+ </div>+ <div className="flex items-center justify-start gap-x-2 pt-1">+ <Tooltip+ content={+ action === "REJECT" && commentMissing+ ? t("plan.review.comment-required-to-reject")+ : undefined+ }+ >+ <span className="inline-flex">+ <Button+ disabled={submitDisabled}+ onClick={() => void submit()}+ size="sm"+ >+ {loading && <Loader2 className="size-4 animate-spin" />}+ {t("common.submit")}+ </Button>+ </span>+ </Tooltip>+ <Button onClick={onClose} size="sm" variant="ghost">+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ );+}++// Tints the shared review-decision glyph for the action menu (text tone, vs the+// filled badge the same spec produces in the activity timeline).+function DecisionIcon({ spec }: { spec: ActivityIconSpec }) {+ const { Icon, tone } = spec;+ return <Icon className={cn("size-4", ICON_TEXT_TONE[tone])} />;+}++function ReviewOption({+ description,+ icon,+ label,+ onSelect,+ selected,+}: {+ description?: string;+ icon?: ReactNode;+ label: string;+ onSelect: () => void;+ selected: boolean;+}) {+ return (+ <label+ className={cn(+ "flex cursor-pointer items-start gap-3 text-left transition-colors",+ selected ? "text-main" : "text-control"+ )}+ >+ <input+ checked={selected}+ className="mt-1 size-4 accent-accent"+ onChange={onSelect}+ type="radio"+ />+ {icon && <span className="mt-1 shrink-0">{icon}</span>}+ <span className="flex flex-col">+ <span className="text-sm font-medium leading-6">{label}</span>+ {description && (+ <span className="text-xs text-control-light">{description}</span>+ )}+ </span>+ </label>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsxnew file mode 100644index 0000000000..8cd4c66bf4--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewActivityTimeline.tsx@@ -0,0 +1,347 @@+import { FileText, Loader2, Pencil, Send } from "lucide-react";+import { type ReactNode, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import {+ ActivityRowShell,+ CommentCreator,+ CommentIconBadge,+ canEditIssueComment,+ IssueCommentRow,+} from "@/react/components/issue-activity/IssueCommentActivity";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { Button } from "@/react/components/ui/button";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useProjectByName } from "@/react/hooks/useProjectByName";+import { diffPlanSpecsForEvent } from "@/react/lib/plan/diffPlanSpecs";+import { useAppStore } from "@/react/stores/app";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";+import { pushNotification } from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import { hasProjectPermissionV2 } from "@/utils/iam/permission";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { foldTimeline } from "./foldTimeline";+import { ReviewCommentComposer } from "./ReviewCommentComposer";+import {+ buildTimelineEntries,+ type TimelineEntry,+ type TimelineSource,+} from "./timelineEvents";++export function ReviewActivityTimeline({+ comments,+ issue,+ plan,+}: {+ comments: IssueComment[];+ issue: Issue;+ plan: Plan;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ const [expanded, setExpanded] = useState(false);++ const entries = useMemo(+ () =>+ buildTimelineEntries({+ planCreator: plan.creator,+ planCreateTime: plan.createTime,+ issueCreator: issue.creator,+ issueCreateTime: issue.createTime,+ comments,+ }),+ [comments, issue.createTime, issue.creator, plan.createTime, plan.creator]+ );+ const items = useMemo(() => {+ const renderable = entries.filter(isRenderableEntry);+ return foldTimeline(renderable, expanded);+ }, [entries, expanded]);+ // Permission-gated only — comments are allowed regardless of issue status+ // (the backend and the issue-detail list allow commenting on done issues).+ const allowComment = Boolean(+ project && hasProjectPermissionV2(project, "bb.issueComments.create")+ );++ return (+ <div className="flex flex-col gap-y-2 px-4 pb-3 pt-4">+ <h4 className="text-sm font-medium text-main">+ {t("plan.review.activity.self")}+ </h4>+ <ul className="flex flex-col">+ {items.map((item, i) => {+ if (item.type === "fold") {+ return (+ <TornSeparator+ count={item.count}+ key={`fold-${i}`}+ onShowAll={() => setExpanded(true)}+ />+ );+ }+ const isLast = !items+ .slice(i + 1)+ .some((next) => next.type !== "fold");+ return (+ <ActivityRow+ entry={item.entry}+ issue={issue}+ isLast={isLast}+ key={item.entry.id}+ plan={plan}+ />+ );+ })}+ </ul>+ {allowComment && <ReviewCommentComposer issueName={issue.name} />}+ </div>+ );+}++// A plan update whose specs are proto-equal produces no sentence; drop it+// entirely so the timeline doesn't show a verbless row (and so the connector+// line's "last row" math stays correct).+function isRenderableEntry(entry: TimelineEntry): boolean {+ if (entry.source.type !== "comment") return true;+ const comment = entry.source.comment;+ if (+ getIssueCommentType(comment) === IssueCommentType.PLAN_UPDATE &&+ comment.event.case === "planUpdate"+ ) {+ return diffPlanSpecsForEvent(comment.event.value).length > 0;+ }+ return true;+}++// Torn-paper zigzag edge (a triangle-wave stroke) tiled horizontally on each+// side of the fold marker. Encoded as an inline SVG data URI because no Tailwind+// utility produces a sawtooth line.+const TORN_EDGE_STYLE = {+ backgroundImage:+ "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='8'%3E%3Cpath d='M0 6 L12 2 L24 6' fill='none' stroke='%23cfd8e6' stroke-width='1'/%3E%3C/svg%3E\")",+ backgroundRepeat: "repeat-x",+ backgroundPosition: "center",+} as const;++function TornSeparator({+ count,+ onShowAll,+}: {+ count: number;+ onShowAll: () => void;+}) {+ const { t } = useTranslation();+ return (+ <div className="flex items-center gap-x-2 py-2">+ <div aria-hidden="true" className="h-2 flex-1" style={TORN_EDGE_STYLE} />+ <button+ className="group shrink-0 bg-white px-2 text-xs text-control-light hover:text-control"+ onClick={onShowAll}+ type="button"+ >+ {t("plan.review.activity.n-hidden-events", { count })}+ <span className="mx-1 text-control-placeholder">·</span>+ <span className="text-accent group-hover:underline">+ {t("plan.review.activity.show-all")}+ </span>+ </button>+ <div aria-hidden="true" className="h-2 flex-1" style={TORN_EDGE_STYLE} />+ </div>+ );+}++function ActivityRow({+ entry,+ issue,+ isLast,+ plan,+}: {+ entry: TimelineEntry;+ issue: Issue;+ isLast: boolean;+ plan: Plan;+}) {+ const source = entry.source;+ if (source.type === "comment") {+ return (+ <ReviewCommentRow+ comment={source.comment}+ isLast={isLast}+ issue={issue}+ plan={plan}+ />+ );+ }+ // Synthetic, review-only events (plan created / marked ready) have no backing+ // issue comment, so render the shared row shell with a local icon + header.+ return (+ <ActivityRowShell+ header={<SyntheticHeader source={source} />}+ icon={<SyntheticIcon type={source.type} />}+ isLast={isLast}+ />+ );+}++function SyntheticIcon({+ type,+}: {+ type: "plan-created" | "ready-for-review";+}) {+ return (+ <CommentIconBadge+ className="bg-control-bg text-control"+ icon={+ type === "plan-created" ? (+ <FileText className="h-4 w-4" />+ ) : (+ <Send className="h-4 w-4" />+ )+ }+ />+ );+}++function SyntheticHeader({+ source,+}: {+ source: Extract<+ TimelineSource,+ { type: "plan-created" | "ready-for-review" }+ >;+}) {+ const { t } = useTranslation();+ return (+ <>+ <ActorName principal={source.creator} />+ <span className="wrap-break-word min-w-0 text-gray-600">+ {source.type === "plan-created"+ ? t("plan.review.activity.created-this-plan")+ : t("plan.review.activity.marked-ready-for-review")}+ </span>+ {source.time && (+ <HumanizeTs+ className="text-gray-500"+ ts={getTimeForPbTimestampProtoEs(source.time, 0) / 1000}+ />+ )}+ </>+ );+}++function ActorName({ principal }: { principal: string }) {+ const user = useAppStore((state) => state.getUserByIdentifier(principal));+ return <CommentCreator creator={user ?? unknownUser(principal)} />;+}++// A comment-backed timeline row: delegates layout/icon/header to the shared+// IssueCommentRow and owns the inline edit affordance (matching the issue page).+function ReviewCommentRow({+ comment,+ isLast,+ issue,+ plan,+}: {+ comment: IssueComment;+ isLast: boolean;+ issue: Issue;+ plan: Plan;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const currentUser = useCurrentUser();+ const project = useProjectByName(`${projectNamePrefix}${page.projectId}`);+ const [isEditing, setIsEditing] = useState(false);+ const [editContent, setEditContent] = useState(comment.comment);+ const [saving, setSaving] = useState(false);++ const allowEdit = canEditIssueComment(comment, currentUser.email, project);++ const save = async () => {+ if (!editContent || editContent === comment.comment) {+ setIsEditing(false);+ return;+ }+ try {+ setSaving(true);+ await useAppStore.getState().updateIssueComment({+ issueCommentName: comment.name,+ comment: editContent,+ });+ setIsEditing(false);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setSaving(false);+ }+ };++ let body: ReactNode;+ if (comment.comment) {+ body = isEditing ? (+ <div>+ <MarkdownEditor+ content={editContent}+ onChange={setEditContent}+ onSubmit={() => void save()}+ />+ <div className="mt-2 flex items-center justify-end gap-x-2">+ <Button onClick={() => setIsEditing(false)} size="xs" variant="ghost">+ {t("common.cancel")}+ </Button>+ <Button+ disabled={+ saving ||+ editContent.trim().length === 0 ||+ editContent === comment.comment+ }+ onClick={() => void save()}+ size="xs"+ >+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t("common.save")}+ </Button>+ </div>+ </div>+ ) : (+ <MarkdownEditor content={comment.comment} mode="preview" />+ );+ }++ const subjectSuffix =+ allowEdit && !isEditing ? (+ <Button+ onClick={() => {+ setEditContent(comment.comment);+ setIsEditing(true);+ }}+ size="xs"+ variant="ghost"+ >+ <Pencil className="h-3.5 w-3.5" />+ </Button>+ ) : undefined;++ return (+ <IssueCommentRow+ body={body}+ comment={comment}+ isLast={isLast}+ issue={issue}+ linkless+ plan={plan}+ subjectSuffix={subjectSuffix}+ />+ );+}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.tsxnew file mode 100644index 0000000000..317bb28631--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewApprovalFlow.tsx@@ -0,0 +1,534 @@+import { Check, User, X } from "lucide-react";+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { getAvatarColor, getInitials } from "@/react/components/UserAvatar";+import { Badge } from "@/react/components/ui/badge";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/react/components/ui/popover";+import { displayRoleTitleFromList } from "@/react/lib/role";+import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { unknownUser } from "@/types";+import type { Issue } from "@/types/proto-es/v1/issue_service_pb";+import { Issue_Approver_Status } from "@/types/proto-es/v1/issue_service_pb";+import type { User as UserProto } from "@/types/proto-es/v1/user_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";+import {+ type ApprovalStepStatus,+ computeApprovalFlowLayout,+} from "./approvalFlowLayout";+import { useApprovalCandidates } from "./useApprovalCandidates";++export interface FlowStep {+ index: number;+ role: string;+ status: ApprovalStepStatus;+ approver?: string; // principal of the recorded decision+}++export function deriveSteps(issue: Issue): FlowStep[] {+ const roles = issue.approvalTemplate?.flow?.roles ?? [];+ return roles.map((role, index) => {+ const approver = issue.approvers[index];+ let status: ApprovalStepStatus = "pending";+ if (approver?.status === Issue_Approver_Status.APPROVED) {+ status = "approved";+ } else if (approver?.status === Issue_Approver_Status.REJECTED) {+ status = "rejected";+ } else {+ const blocked = roles.slice(0, index).some((_, i) => {+ const prev = issue.approvers[i];+ return prev?.status !== Issue_Approver_Status.APPROVED;+ });+ status = blocked ? "pending" : "current";+ }+ return { index, role, status, approver: approver?.principal };+ });+}++export function ReviewApprovalFlow({ issue }: { issue: Issue }) {+ const hostRef = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);++ useEffect(() => {+ const host = hostRef.current;+ if (!host) return;+ const observer = new ResizeObserver((entries) => {+ setWidth(entries[0]?.contentRect.width ?? 0);+ });+ observer.observe(host);+ return () => observer.disconnect();+ }, []);++ const steps = useMemo(() => deriveSteps(issue), [issue]);+ const layout = useMemo(+ () =>+ // width is 0 on first paint before the ResizeObserver fires; fall back+ // to a wide value so the initial layout is horizontal and corrects once+ // the real width arrives.+ computeApprovalFlowLayout(+ steps.map((s) => s.status),+ width || 9999+ ),+ [steps, width]+ );++ return (+ <div ref={hostRef} className="min-w-0 px-4 py-3">+ {layout.kind === "vertical" ? (+ <VerticalFlow issue={issue} steps={steps} />+ ) : (+ <HorizontalFlow+ foldedApproved={layout.foldedApproved}+ issue={issue}+ namedPending={layout.namedPending}+ steps={steps}+ />+ )}+ </div>+ );+}++function HorizontalFlow({+ foldedApproved,+ issue,+ namedPending,+ steps,+}: {+ foldedApproved: number;+ issue: Issue;+ namedPending: number;+ steps: FlowStep[];+}) {+ const anchorIndex = steps.findIndex(+ (s) => s.status === "current" || s.status === "rejected"+ );+ const approved = steps.filter((s) => s.status === "approved");+ const foldedApprovedSteps = approved.slice(0, foldedApproved);+ const namedSteps = steps.filter(+ (s) =>+ !foldedApprovedSteps.includes(s) &&+ (anchorIndex === -1 || s.index <= anchorIndex + namedPending)+ );+ const foldedPendingSteps =+ anchorIndex === -1 ? [] : steps.slice(anchorIndex + 1 + namedPending);++ // Each item carries a stable key tied to its identity (chip name or step+ // index) so React reconciles correctly when the fold counts change with the+ // viewport — an array index key would graft a node onto the wrong slot.+ const items: { key: string; node: ReactNode }[] = [];+ if (foldedApprovedSteps.length > 0) {+ items.push({+ key: "approved-chip",+ node: <ApprovedChip steps={foldedApprovedSteps} />,+ });+ }+ for (const step of namedSteps) {+ items.push({+ key: `step-${step.index}`,+ node: <FlowNode issue={issue} step={step} />,+ });+ }+ if (foldedPendingSteps.length > 0) {+ items.push({+ key: "pending-chip",+ node: <PendingChip issue={issue} steps={foldedPendingSteps} />,+ });+ }++ return (+ <div className="flex min-w-0 items-start gap-x-2 overflow-hidden">+ {items.map((item, i) => (+ <div key={item.key} className="flex min-w-0 items-start gap-x-2">+ {i > 0 && (+ <div+ aria-hidden+ className="mt-3 h-px w-8 shrink-0 bg-control-border"+ />+ )}+ {item.node}+ </div>+ ))}+ </div>+ );+}++function VerticalFlow({ issue, steps }: { issue: Issue; steps: FlowStep[] }) {+ return (+ <div className="flex flex-col gap-y-3">+ {steps.map((step) => (+ <FlowNode key={step.index} issue={issue} step={step} vertical />+ ))}+ </div>+ );+}++function StatusDot({+ status,+ index,+}: {+ status: ApprovalStepStatus;+ index: number;+}) {+ return (+ <div+ className={cn(+ "flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-medium",+ status === "approved" && "bg-success text-white",+ status === "rejected" && "bg-error text-white",+ status === "current" && "bg-accent text-white",+ status === "pending" && "bg-control-bg text-control"+ )}+ >+ {status === "approved" && <Check className="size-3.5" />}+ {status === "rejected" && <X className="size-3.5" />}+ {status === "current" && <User className="size-3.5" />}+ {status === "pending" && index}+ </div>+ );+}++function FlowNode({+ issue,+ step,+ vertical = false,+}: {+ issue: Issue;+ step: FlowStep;+ vertical?: boolean;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const roleList = useAppStore((state) => state.roleList);+ const approverUser = useAppStore((state) =>+ step.approver ? state.getUserByIdentifier(step.approver) : undefined+ );+ const roleName = displayRoleTitleFromList(step.role, roleList);++ const subtitle =+ step.status === "approved"+ ? t("plan.review.approval-flow.approved-by", {+ user: (approverUser ?? unknownUser(step.approver ?? "")).title,+ })+ : step.status === "rejected"+ ? t("plan.review.approval-flow.rejected-by", {+ user: (approverUser ?? unknownUser(step.approver ?? "")).title,+ })+ : undefined;++ return (+ <div+ className={cn(+ "flex min-w-0 items-start gap-x-2",+ !vertical && "shrink-0"+ )}+ >+ <StatusDot index={step.index + 1} status={step.status} />+ <div className="min-w-0">+ <div className="flex items-center gap-x-1.5">+ <span className="truncate text-sm font-medium text-main">+ {roleName}+ </span>+ {step.status === "current" && (+ <Badge className="px-1.5 py-0 text-[10px]" variant="secondary">+ {t("plan.review.approval-flow.current")}+ </Badge>+ )}+ </div>+ {subtitle ? (+ <div className="mt-1 h-4 truncate text-xs leading-4 text-control-light">+ {subtitle}+ </div>+ ) : step.status === "current" || step.status === "pending" ? (+ <NodeReviewers+ issue={issue}+ projectId={page.projectId}+ role={step.role}+ />+ ) : null}+ </div>+ </div>+ );+}++// The reviewer line under a current/pending node: an avatar stack + "N+// reviewers" count, where the whole row is a hover target that reveals the full+// reviewer list (BYT-9711). Rendered for future stages too, not just current.+function NodeReviewers({+ issue,+ projectId,+ role,+}: {+ issue: Issue;+ projectId: string;+ role: string;+}) {+ const { t } = useTranslation();+ // Whether the project IAM policy is in cache yet — used to tell "still+ // loading" (show nothing) apart from "genuinely no eligible reviewers".+ const policyLoaded = useAppStore(+ (state) =>+ state.projectPoliciesByName[`${projectNamePrefix}${projectId}`] !==+ undefined+ );+ const { candidates } = useApprovalCandidates(issue, projectId, role);+ if (candidates.length === 0) {+ // No eligible reviewers means this stage can never be approved — surface it+ // explicitly rather than rendering nothing (BYT-9711). Stay silent until the+ // policy resolves so it doesn't flash during load.+ if (!policyLoaded) return null;+ return (+ <div className="mt-1 flex h-4 items-center text-xs leading-4 text-control-placeholder">+ {t("plan.review.approval-flow.no-reviewers")}+ </div>+ );+ }+ const visible = candidates.slice(0, 3);+ const overflow = candidates.length - visible.length;+ // A role can resolve to thousands of candidates; render a bounded, scrollable+ // slice in the popover and summarize the rest rather than mounting every row.+ const MAX_LISTED = 50;+ const listed = candidates.slice(0, MAX_LISTED);+ const remaining = candidates.length - listed.length;++ return (+ <Popover>+ <PopoverTrigger+ delay={100}+ nativeButton={false}+ openOnHover+ render={+ <div className="mt-1 flex h-4 w-fit cursor-default items-center gap-x-1.5">+ <div className="flex items-center -space-x-1">+ {visible.map((user) => (+ <InitialsAvatar+ className="size-4 text-[9px] ring-2 ring-white"+ key={user.name}+ user={user}+ />+ ))}+ {overflow > 0 && (+ <span className="flex size-4 items-center justify-center rounded-full bg-control-bg text-[9px] font-medium text-control ring-2 ring-white">+ +{overflow}+ </span>+ )}+ </div>+ <span className="text-xs text-control-light">+ {t("plan.review.approval-flow.n-reviewers", {+ count: candidates.length,+ })}+ </span>+ </div>+ }+ />+ <PopoverContent align="start" className="w-60" side="bottom">+ <div className="flex max-h-64 flex-col gap-y-2 overflow-y-auto">+ {listed.map((user) => (+ <div className="flex items-center gap-x-2" key={user.name}>+ <InitialsAvatar className="size-6 text-[10px]" user={user} />+ <div className="min-w-0">+ <div className="truncate text-sm text-main">+ {user.title || user.email.split("@")[0]}+ </div>+ <div className="truncate text-xs text-control-light">+ {user.email}+ </div>+ </div>+ </div>+ ))}+ </div>+ {remaining > 0 && (+ <div className="mt-2 border-t pt-1.5 text-xs text-control-placeholder">+ {t("plan.review.approval-flow.and-n-more", { count: remaining })}+ </div>+ )}+ </PopoverContent>+ </Popover>+ );+}++function ApprovedChip({ steps }: { steps: FlowStep[] }) {+ const { t } = useTranslation();+ return (+ <Popover>+ <PopoverTrigger+ delay={100}+ nativeButton={false}+ openOnHover+ render={+ <div className="flex shrink-0 cursor-default items-start gap-x-2">+ <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-success text-white">+ <Check className="size-3.5" />+ </div>+ <div className="min-w-0">+ <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((s) => s.approver ?? "")} />+ </div>+ </div>+ </div>+ }+ />+ <PopoverContent align="start" className="w-64" side="bottom">+ <div className="flex flex-col gap-y-2.5">+ {steps.map((step) => (+ <ApprovedPopoverRow key={step.index} step={step} />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ );+}++function ApprovedPopoverRow({ step }: { step: FlowStep }) {+ const { t } = useTranslation();+ const roleList = useAppStore((state) => state.roleList);+ const approverUser = useAppStore((state) =>+ step.approver ? state.getUserByIdentifier(step.approver) : undefined+ );+ const approver = approverUser ?? unknownUser(step.approver ?? "");+ const roleName = displayRoleTitleFromList(step.role, roleList);+ return (+ <div className="flex items-start gap-x-2">+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-success text-white">+ <Check className="size-3" />+ </span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium text-main">{roleName}</div>+ <div className="mt-0.5 flex items-center gap-x-1 text-xs text-control-light">+ <InitialsAvatar+ className="size-4 shrink-0 text-[8px]"+ user={approver}+ />+ <span className="truncate">+ {t("plan.review.approval-flow.approved-by", {+ user: approver.title,+ })}+ </span>+ </div>+ </div>+ </div>+ );+}++// Small circular initials avatar. `className` carries the per-call size/ring+// variant; the common geometry + color derivation lives here.+function InitialsAvatar({+ className,+ user,+}: {+ className: string;+ user: UserProto;+}) {+ const name = user.title || user.email.split("@")[0];+ return (+ <span+ className={cn(+ "flex items-center justify-center rounded-full font-medium text-white",+ className+ )}+ style={{ backgroundColor: getAvatarColor(name) }}+ >+ {getInitials(name)}+ </span>+ );+}++function ChipAvatars({ principals }: { principals: string[] }) {+ const getUserByIdentifier = useAppStore((state) => state.getUserByIdentifier);+ return (+ <span className="flex items-center -space-x-1">+ {principals.slice(0, 3).map((principal, i) => (+ <InitialsAvatar+ className="size-4 text-[9px] ring-1 ring-white"+ key={`${principal}-${i}`}+ user={getUserByIdentifier(principal) ?? unknownUser(principal)}+ />+ ))}+ </span>+ );+}++function PendingChip({ issue, steps }: { issue: Issue; steps: FlowStep[] }) {+ const { t } = useTranslation();+ return (+ <Popover>+ <PopoverTrigger+ delay={100}+ nativeButton={false}+ openOnHover+ render={+ <div className="flex shrink-0 cursor-default items-start gap-x-2">+ <div className="size-6 shrink-0 rounded-full border-2 border-dashed border-control-border" />+ <span className="text-sm font-medium text-control">+ {t("plan.review.approval-flow.n-pending", { n: steps.length })}+ </span>+ </div>+ }+ />+ <PopoverContent align="start" className="w-64" side="bottom">+ <div className="flex flex-col gap-y-2.5">+ {steps.map((step) => (+ <PendingPopoverRow issue={issue} key={step.index} step={step} />+ ))}+ </div>+ </PopoverContent>+ </Popover>+ );+}++// One row inside the folded-pending popover: step number, role, candidate+// avatars, and reviewer count — mirrors a live flow node on the light surface.+function PendingPopoverRow({ issue, step }: { issue: Issue; step: FlowStep }) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const roleList = useAppStore((state) => state.roleList);+ const { candidates } = useApprovalCandidates(+ issue,+ page.projectId,+ step.role+ );+ const roleName = displayRoleTitleFromList(step.role, roleList);+ const visible = candidates.slice(0, 4);+ const overflow = candidates.length - visible.length;++ return (+ <div className="flex items-start gap-x-2">+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-control-bg text-[10px] font-medium text-control">+ {step.index + 1}+ </span>+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-medium text-main">{roleName}</div>+ {candidates.length > 0 && (+ <div className="mt-1 flex items-center gap-x-1.5">+ <div className="flex items-center -space-x-1">+ {visible.map((user) => (+ <InitialsAvatar+ className="size-4 text-[8px] ring-2 ring-background"+ key={user.name}+ user={user}+ />+ ))}+ {overflow > 0 && (+ <span className="flex size-4 items-center justify-center rounded-full bg-control-bg text-[8px] text-control ring-2 ring-background">+ +{overflow}+ </span>+ )}+ </div>+ <span className="text-xs text-control-light">+ {t("plan.review.approval-flow.n-reviewers", {+ count: candidates.length,+ })}+ </span>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewCommentComposer.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewCommentComposer.tsxnew file mode 100644index 0000000000..a986bc00f5--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewCommentComposer.tsx@@ -0,0 +1,109 @@+import { Loader2 } from "lucide-react";+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { MarkdownEditor } from "@/react/components/MarkdownEditor";+import { UserAvatar } from "@/react/components/UserAvatar";+import { Button } from "@/react/components/ui/button";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useAppStore } from "@/react/stores/app";+import { pushNotification } from "@/store";++const draftKey = (issueName: string) => `bb.plan-review.draft.${issueName}`;++export function ReviewCommentComposer({ issueName }: { issueName: string }) {+ const { t } = useTranslation();+ const currentUser = useCurrentUser();+ const [expanded, setExpanded] = useState(false);+ const [content, setContent] = useState("");+ const [posting, setPosting] = useState(false);++ // Restore the unsent draft on mount / issue change.+ useEffect(() => {+ const draft = localStorage.getItem(draftKey(issueName)) ?? "";+ setContent(draft);+ setExpanded(false);+ }, [issueName]);++ const persistDraft = useCallback(+ (value: string) => {+ setContent(value);+ if (value) {+ localStorage.setItem(draftKey(issueName), value);+ } else {+ localStorage.removeItem(draftKey(issueName));+ }+ },+ [issueName]+ );++ const post = async () => {+ if (!content.trim() || posting) return;+ try {+ setPosting(true);+ await useAppStore.getState().createIssueComment({+ issueName,+ comment: content,+ });+ persistDraft("");+ setExpanded(false);+ } catch (error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("common.failed"),+ description: String(error),+ });+ } finally {+ setPosting(false);+ }+ };++ if (!expanded) {+ return (+ <div className="flex items-center gap-x-3">+ <div className="shrink-0 pl-0.5">+ <UserAvatar+ size="sm"+ title={currentUser.title || currentUser.email}+ />+ </div>+ <button+ className="min-w-0 flex-1 rounded-md border px-3 py-1.5 text-left text-sm text-control-placeholder hover:border-control-border"+ onClick={() => setExpanded(true)}+ type="button"+ >+ {t("plan.review.activity.add-a-comment")}+ </button>+ </div>+ );+ }++ return (+ <div className="flex items-start gap-x-3">+ <div className="shrink-0 pl-0.5 pt-1">+ <UserAvatar size="sm" title={currentUser.title || currentUser.email} />+ </div>+ <div className="min-w-0 flex-1">+ <MarkdownEditor+ content={content}+ onChange={persistDraft}+ onSubmit={() => void post()}+ placeholder={t("plan.review.activity.add-a-comment")}+ />+ <div className="mt-2 flex items-center justify-end gap-x-2">+ <Button onClick={() => setExpanded(false)} size="sm" variant="ghost">+ {t("common.cancel")}+ </Button>+ <Button+ disabled={posting || content.trim().length === 0}+ onClick={() => void post()}+ size="sm"+ >+ {posting && <Loader2 className="size-4 animate-spin" />}+ {t("common.comment")}+ </Button>+ </div>+ </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.tsxnew file mode 100644index 0000000000..316d3826dd--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewReadinessFooter.tsx@@ -0,0 +1,357 @@+import { create } from "@bufbuild/protobuf";+import { Ban, CircleCheck, CircleX, Clock3, Loader2 } from "lucide-react";+import { Fragment, type ReactNode, 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 { usePlanDetailContext } from "../../shell/PlanDetailContext";+import { getPlanCheckSummary } from "../../utils/phaseSummary";+import { getPlanCheckSummaryWithFallback } from "../../utils/planCheck";+import { ReviewApprovalFlow } from "./ReviewApprovalFlow";+import {+ computeBypassActionWeight,+ computeReadinessFooterState,+} from "./readinessFooterState";++export function ReviewReadinessFooter({+ issue,+ plan,+}: {+ issue: Issue;+ 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]+ );++ 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 }[] = [];+ if (checks.error > 0) {+ checkSegments.push({+ key: "failed",+ node: (+ <span className="whitespace-nowrap text-error">+ {t("plan.review.footer.n-checks-failed", { count: checks.error })}+ </span>+ ),+ });+ }+ if (checks.success > 0) {+ checkSegments.push({+ key: "passed",+ node: (+ <span className="whitespace-nowrap">+ {t("plan.review.footer.n-checks-passed", { count: checks.success })}+ </span>+ ),+ });+ }+ const checkCounts = checkSegments.map((segment) => (+ <Fragment key={segment.key}>+ <span>·</span>+ {segment.node}+ </Fragment>+ ));++ return (+ <div+ className={+ state.kind === "approved-checks-failed"+ ? "flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-4 py-2.5"+ : "flex flex-wrap items-center gap-x-2 gap-y-1 border-t px-4 py-2.5 text-sm text-control-placeholder"+ }+ >+ {state.kind === "waiting-review" && (+ <>+ <Clock3 className="size-4 shrink-0" />+ <span className="whitespace-nowrap font-medium text-control">+ {t("plan.review.footer.waiting-on-review")}+ </span>+ <span className="hidden sm:inline">·</span>+ <span className="hidden whitespace-nowrap sm:inline">+ {checks.error > 0+ ? t("plan.review.footer.rollout-blocked-by-failed-checks")+ : t("plan.review.footer.auto-rollout-after-approval")}+ </span>+ {checkCounts}+ </>+ )}+ {state.kind === "all-gates-passed" && (+ <>+ <CircleCheck className="size-4 shrink-0 text-success" />+ <span className="whitespace-nowrap font-medium text-control">+ {t("plan.review.footer.all-gates-passed")}+ </span>+ <span className="hidden sm:inline">·</span>+ <span className="hidden whitespace-nowrap sm:inline">+ {t("plan.review.footer.creating-rollout-automatically")}+ </span>+ {checkCounts}+ </>+ )}+ {state.kind === "approved-checks-failed" && (+ <>+ <CircleX className="size-6 shrink-0 text-error" />+ <div className="min-w-0 flex-1">+ <div className="text-sm font-semibold text-main">+ {t("plan.review.footer.approved-but-checks-failed")}+ </div>+ <div className="text-xs text-control-placeholder">+ {t("plan.review.footer.errors-passed-not-created", {+ count: checks.error,+ passed: checks.success,+ })}+ </div>+ </div>+ </>+ )}+ {state.kind === "rejected" && (+ <>+ <Ban className="size-4 shrink-0" />+ <span className="min-w-0 truncate">+ {t("plan.review.footer.blocked-by-rejection")}+ </span>+ </>+ )}++ {weight === "link" && (+ <button+ className="ml-auto inline-flex shrink-0 items-center gap-x-1 text-xs text-control-placeholder underline hover:text-control disabled:opacity-60"+ disabled={creating}+ onClick={triggerDeploy}+ type="button"+ >+ {creating && <Loader2 className="size-3 animate-spin" />}+ {t("plan.review.footer.bypass-and-deploy")}+ </button>+ )}+ {weight === "button" && (+ <Button+ className="ml-auto shrink-0"+ disabled={creating}+ onClick={triggerDeploy}+ variant="outline"+ >+ {creating && <Loader2 className="size-4 animate-spin" />}+ {t("plan.review.footer.bypass-and-deploy")}+ </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>+ </div>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/ReviewRejectionBanner.tsx b/frontend/src/react/pages/project/plan-detail/components/review/ReviewRejectionBanner.tsxnew file mode 100644index 0000000000..2fba795a84--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewRejectionBanner.tsx@@ -0,0 +1,132 @@+import { create } from "@bufbuild/protobuf";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { issueServiceClientConnect } from "@/connect";+import { HumanizeTs } from "@/react/components/HumanizeTs";+import { Alert } from "@/react/components/ui/alert";+import { useCurrentUser } from "@/react/hooks/useAppState";+import { useAppStore } from "@/react/stores/app";+import {+ getIssueCommentType,+ IssueCommentType,+} from "@/react/stores/app/issueComment";+import { pushNotification } from "@/store";+import { userNamePrefix } from "@/store/modules/v1/common";+import { getTimeForPbTimestampProtoEs, unknownUser } from "@/types";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import type { Issue, IssueComment } from "@/types/proto-es/v1/issue_service_pb";+import {+ IssueComment_Approval_Status,+ RequestIssueRequestSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { usePlanDetailContext } from "../../shell/PlanDetailContext";++function findLastRejection(comments: IssueComment[]): IssueComment | undefined {+ for (let i = comments.length - 1; i >= 0; i--) {+ const comment = comments[i];+ if (+ getIssueCommentType(comment) === IssueCommentType.APPROVAL &&+ comment.event.case === "approval" &&+ comment.event.value.status === IssueComment_Approval_Status.REJECTED+ ) {+ return comment;+ }+ }+ return undefined;+}++export function ReviewRejectionBanner({+ comments,+ issue,+}: {+ comments: IssueComment[];+ issue: Issue;+}) {+ const { t } = useTranslation();+ const page = usePlanDetailContext();+ const currentUser = useCurrentUser();+ const [reRequesting, setReRequesting] = useState(false);+ const rejection = useMemo(() => findLastRejection(comments), [comments]);+ const rejectorUser = useAppStore((state) =>+ rejection ? state.getUserByIdentifier(rejection.creator) : undefined+ );++ if (issue.approvalStatus !== ApprovalStatus.REJECTED || !rejection) {+ return null;+ }++ const rejector = rejectorUser ?? unknownUser(rejection.creator);+ const isCreator =+ issue.creator === `${userNamePrefix}${currentUser?.email ?? ""}`;++ 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 (+ <Alert+ className="mx-4 mt-3 w-auto px-3 py-2"+ showIcon={false}+ variant="error"+ title={+ <span className="flex items-center gap-x-2 text-error">+ <span>+ {t("plan.review.rejection.title", { user: rejector.title })}+ </span>+ {rejection.createTime && (+ <>+ <span className="text-error/50">·</span>+ <HumanizeTs+ className="text-xs font-normal text-error/70"+ ts={+ getTimeForPbTimestampProtoEs(rejection.createTime, 0) / 1000+ }+ />+ </>+ )}+ </span>+ }+ >+ <div className="mt-1 flex flex-col gap-y-1 text-xs text-control-light">+ {rejection.comment && (+ <span className="wrap-anywhere whitespace-pre-wrap text-sm text-control">+ {rejection.comment}+ </span>+ )}+ <span>+ {t("plan.review.rejection.guidance-prefix")}{" "}+ {isCreator && !page.readonly ? (+ <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>+ </div>+ </Alert>+ );+}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.tsxnew file mode 100644index 0000000000..31df67f2e3--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/ReviewSectionHeader.tsx@@ -0,0 +1,105 @@+import { ChevronDown, ShieldAlert, ShieldCheck } from "lucide-react";+import { useMemo, useState } from "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 { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/react/router/handles";+import { ApprovalStatus, 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";++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">+ <h3 className="shrink-0 text-base font-medium text-main">+ {t("issue.approval-flow.self")}+ </h3>+ <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>+ {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>+ );+}++function RiskChip({ riskLevel }: { riskLevel: RiskLevel }) {+ const { t } = useTranslation();+ if (riskLevel === RiskLevel.RISK_LEVEL_UNSPECIFIED) return null;+ const label =+ riskLevel === RiskLevel.LOW+ ? t("issue.risk-level.low")+ : riskLevel === RiskLevel.MODERATE+ ? t("issue.risk-level.moderate")+ : t("issue.risk-level.high");+ const Icon = riskLevel === RiskLevel.LOW ? ShieldCheck : ShieldAlert;+ return (+ <span className="inline-flex shrink-0 items-center gap-x-1 rounded-full border px-2 py-0.5 text-xs text-control">+ <Icon+ className={+ riskLevel === RiskLevel.LOW+ ? "size-3.5 text-success"+ : riskLevel === RiskLevel.MODERATE+ ? "size-3.5 text-warning"+ : "size-3.5 text-error"+ }+ />+ {label}+ </span>+ );+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.ts b/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.tsnew file mode 100644index 0000000000..a02d69aa08--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.test.ts@@ -0,0 +1,93 @@+import { describe, expect, test } from "vitest";+import type { ApprovalStepStatus } from "./approvalFlowLayout";+import {+ computeApprovalFlowLayout,+ VERTICAL_BREAKPOINT_PX,+} from "./approvalFlowLayout";++const statuses = (s: string): ApprovalStepStatus[] =>+ s+ .split("")+ .map((c) =>+ c === "a"+ ? "approved"+ : c === "c"+ ? "current"+ : c === "r"+ ? "rejected"+ : "pending"+ );++describe("computeApprovalFlowLayout", () => {+ test("narrow container switches to vertical", () => {+ const layout = computeApprovalFlowLayout(statuses("aacpp"), 400);+ expect(layout.kind).toBe("vertical");+ });++ test("everything fits: nothing folds", () => {+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 2000);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 0,+ namedPending: 3,+ });+ });++ test("approved folds first; nearest pending stays named", () => {+ // 3 approved + current + 3 pending at ~900px: approved chip + current ++ // 1 named pending + pending chip (per the mockup's middle row).+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 900);+ expect(layout.kind).toBe("horizontal");+ if (layout.kind !== "horizontal") return;+ expect(layout.foldedApproved).toBe(3);+ expect(layout.namedPending).toBeGreaterThanOrEqual(1);+ expect(layout.namedPending).toBeLessThan(3);+ });++ test("minimum form: chip + current + chip", () => {+ const layout = computeApprovalFlowLayout(statuses("aaacppp"), 640);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 3,+ namedPending: 0,+ });+ });++ test("rejected step is the anchor like current", () => {+ const layout = computeApprovalFlowLayout(statuses("aarpp"), 640);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 2,+ namedPending: 0,+ });+ });++ test("fully approved: names as many nodes as fit, folding only the rest", () => {+ // 7 approved, no anchor. Wide enough for all 7 named.+ expect(computeApprovalFlowLayout(statuses("aaaaaaa"), 2000)).toEqual({+ kind: "horizontal",+ foldedApproved: 0,+ namedPending: 0,+ });+ // Medium width: partial fold (some named approved + a smaller chip), not+ // an all-or-nothing "7 approved" chip.+ const mid = computeApprovalFlowLayout(statuses("aaaaaaa"), 1200);+ expect(mid.kind).toBe("horizontal");+ if (mid.kind !== "horizontal") return;+ expect(mid.foldedApproved).toBeGreaterThan(0);+ expect(mid.foldedApproved).toBeLessThan(7);+ });++ test("no approved steps: no approved chip cost, pending folds only as needed", () => {+ const layout = computeApprovalFlowLayout(statuses("cpppp"), 2000);+ expect(layout).toEqual({+ kind: "horizontal",+ foldedApproved: 0,+ namedPending: 4,+ });+ });++ test("exports the vertical breakpoint", () => {+ expect(VERTICAL_BREAKPOINT_PX).toBeGreaterThan(0);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.ts b/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.tsnew file mode 100644index 0000000000..4e8c86f80a--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/approvalFlowLayout.ts@@ -0,0 +1,78 @@+// Pure layout math for the horizontal approval flow (spec: "Approval flow+// renderer"). The current (or rejected) step is the anchor and never folds;+// approved steps fold first into one leading chip; trailing pending steps+// fold into one dashed chip, farthest-from-current first.+export type ApprovalStepStatus =+ | "approved"+ | "rejected"+ | "current"+ | "pending";++export type ApprovalFlowLayout =+ | { kind: "vertical" }+ | {+ kind: "horizontal";+ // Leading approved steps folded into the "N approved" chip (0 = all named).+ foldedApproved: number;+ // Pending steps after the anchor rendered as full named nodes,+ // counted from the one nearest the anchor.+ namedPending: number;+ };++export const VERTICAL_BREAKPOINT_PX = 560;++// Width budget per element, connector included. Estimates — the row also has+// min-w-0 truncation, so being a little conservative is fine.+const NAMED_NODE_PX = 190;+const ANCHOR_NODE_PX = 240;+const CHIP_PX = 150;++export function computeApprovalFlowLayout(+ statuses: ApprovalStepStatus[],+ containerWidth: number+): ApprovalFlowLayout {+ if (containerWidth < VERTICAL_BREAKPOINT_PX) {+ return { kind: "vertical" };+ }++ const anchorIndex = statuses.findIndex(+ (s) => s === "current" || s === "rejected"+ );+ // Fully-approved (or skipped) flows have no anchor; render all named if they+ // fit, otherwise fold approved into the chip.+ const approvedCount = anchorIndex === -1 ? statuses.length : anchorIndex;+ const pendingCount =+ anchorIndex === -1 ? 0 : statuses.length - anchorIndex - 1;+ const anchorCost = anchorIndex === -1 ? 0 : ANCHOR_NODE_PX;++ const fits = (foldedApproved: number, namedPending: number): boolean => {+ const namedApproved = approvedCount - foldedApproved;+ const foldedPending = pendingCount - namedPending;+ const width =+ (foldedApproved > 0 ? CHIP_PX : 0) ++ namedApproved * NAMED_NODE_PX ++ anchorCost ++ namedPending * NAMED_NODE_PX ++ (foldedPending > 0 ? CHIP_PX : 0);+ return width <= containerWidth;+ };++ // Name as many nodes as the width allows. Prefer naming upcoming (pending)+ // steps, then the most recent approved ones; both counted nearest the anchor.+ // For each pending count (most first), fold the fewest approved that still+ // fits — so a roomy row shows partial "N approved" + several named nodes+ // instead of collapsing everything into one chip.+ for (let namedPending = pendingCount; namedPending >= 0; namedPending--) {+ for (+ let foldedApproved = 0;+ foldedApproved <= approvedCount;+ foldedApproved+++ ) {+ if (fits(foldedApproved, namedPending)) {+ return { kind: "horizontal", foldedApproved, namedPending };+ }+ }+ }+ // Minimum form regardless: chip + anchor + chip.+ return { kind: "horizontal", foldedApproved: approvedCount, namedPending: 0 };+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.test.ts b/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.test.tsnew file mode 100644index 0000000000..b394009e0a--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.test.ts@@ -0,0 +1,42 @@+import { describe, expect, test } from "vitest";+import { FOLD_HEAD, FOLD_TAIL, foldTimeline } from "./foldTimeline";++interface E {+ id: string;+}+const e = (id: string): E => ({ id });++describe("foldTimeline", () => {+ test("timelines of 10 or fewer never fold", () => {+ const entries = Array.from({ length: 10 }, (_, i) => e(`e${i}`));+ const items = foldTimeline(entries, false);+ expect(items).toHaveLength(10);+ expect(items.every((i) => i.type === "entry")).toBe(true);+ });++ test("folds the middle once over 10 entries", () => {+ const entries = Array.from({ length: 11 }, (_, i) => e(`e${i}`));+ const items = foldTimeline(entries, false);+ // first 3 + fold + last 3+ expect(items).toHaveLength(FOLD_HEAD + 1 + FOLD_TAIL);+ const ids = items.map((i) => (i.type === "entry" ? i.entry.id : "FOLD"));+ expect(ids).toEqual(["e0", "e1", "e2", "FOLD", "e8", "e9", "e10"]);+ const fold = items.find((i) => i.type === "fold");+ expect(fold).toMatchObject({+ type: "fold",+ count: 11 - FOLD_HEAD - FOLD_TAIL,+ });+ });++ test("hidden count grows with the timeline length", () => {+ const entries = Array.from({ length: 30 }, (_, i) => e(`e${i}`));+ const items = foldTimeline(entries, false);+ expect(items).toHaveLength(FOLD_HEAD + 1 + FOLD_TAIL);+ expect(items.find((i) => i.type === "fold")).toMatchObject({ count: 24 });+ });++ test("expanded shows everything", () => {+ const entries = Array.from({ length: 30 }, (_, i) => e(`e${i}`));+ expect(foldTimeline(entries, true)).toHaveLength(30);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.ts b/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.tsnew file mode 100644index 0000000000..90a31d9438--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/foldTimeline.ts@@ -0,0 +1,36 @@+// Long-history fold: once the timeline has more than FOLD_THRESHOLD entries,+// only the first FOLD_HEAD and last FOLD_TAIL render; everything in between+// collapses into a single fold marker carrying the exact hidden count. One+// click ("Show all") expands the whole list.+export interface FoldableEntry {+ id: string;+}++export type FoldedItem<T extends FoldableEntry> =+ | { type: "entry"; entry: T }+ | { type: "fold"; count: number };++export const FOLD_HEAD = 3;+export const FOLD_TAIL = 3;+// Fold only when collapsing would actually hide something, i.e. there are more+// than head + tail entries. ">10" in the design (3 + 3 visible + >=5 hidden).+export const FOLD_THRESHOLD = 10;++export function foldTimeline<T extends FoldableEntry>(+ entries: T[],+ expanded: boolean+): FoldedItem<T>[] {+ const all = entries.map((entry) => ({ type: "entry" as const, entry }));+ if (expanded || entries.length <= FOLD_THRESHOLD) {+ return all;+ }+ const hiddenCount = entries.length - FOLD_HEAD - FOLD_TAIL;+ const items: FoldedItem<T>[] = entries+ .slice(0, FOLD_HEAD)+ .map((entry) => ({ type: "entry" as const, entry }));+ items.push({ type: "fold", count: hiddenCount });+ for (const entry of entries.slice(entries.length - FOLD_TAIL)) {+ items.push({ type: "entry", entry });+ }+ return items;+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.test.ts b/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.test.tsnew file mode 100644index 0000000000..7b1bbb544e--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.test.ts@@ -0,0 +1,166 @@+import { describe, expect, test } from "vitest";+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import {+ computeBypassActionWeight,+ computeReadinessFooterState,+} from "./readinessFooterState";++const checks = (error = 0, success = 8) => ({+ error,+ running: 0,+ success,+ total: error + success,+ warning: 0,+});++const base = {+ hasRollout: false,+ issueStatus: IssueStatus.OPEN,+ checks: checks(),+};++describe("computeReadinessFooterState", () => {+ test("hidden once the rollout exists", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ hasRollout: true,+ approvalStatus: ApprovalStatus.APPROVED,+ }).kind+ ).toBe("hidden");+ });++ test("hidden when the issue is not open", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ issueStatus: IssueStatus.CANCELED,+ approvalStatus: ApprovalStatus.PENDING,+ }).kind+ ).toBe("hidden");+ });++ test("pending review -> waiting-review (checks failed or not)", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.PENDING,+ }).kind+ ).toBe("waiting-review");+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.PENDING,+ checks: checks(2),+ }).kind+ ).toBe("waiting-review");+ });++ test("approved or skipped with passing checks -> all-gates-passed", () => {+ for (const approvalStatus of [+ ApprovalStatus.APPROVED,+ ApprovalStatus.SKIPPED,+ ]) {+ expect(+ computeReadinessFooterState({ ...base, approvalStatus }).kind+ ).toBe("all-gates-passed");+ }+ });++ test("approved with failed checks -> approved-checks-failed", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.APPROVED,+ checks: checks(2),+ }).kind+ ).toBe("approved-checks-failed");+ });++ test("rejected -> rejected", () => {+ expect(+ computeReadinessFooterState({+ ...base,+ approvalStatus: ApprovalStatus.REJECTED,+ }).kind+ ).toBe("rejected");+ });+});++describe("computeBypassActionWeight", () => {+ const allowed = {+ canCreateRollout: true,+ requireIssueApproval: false,+ };++ test("primary button when review passed but checks failed", () => {+ expect(+ computeBypassActionWeight({ ...allowed, state: "approved-checks-failed" })+ ).toBe("button");+ });++ test("muted link while review in progress or all gates passed", () => {+ expect(+ computeBypassActionWeight({ ...allowed, state: "waiting-review" })+ ).toBe("link");+ expect(+ computeBypassActionWeight({ ...allowed, state: "all-gates-passed" })+ ).toBe("link");+ });++ test("review passed: always shown regardless of project check policy", () => {+ // requirePlanCheckNoError no longer hides the action — the confirm sheet+ // blocks deploy instead. The action is always offered after review passes.+ for (const state of [+ "all-gates-passed",+ "approved-checks-failed",+ ] as const) {+ expect(computeBypassActionWeight({ ...allowed, state })).not.toBe("none");+ }+ });++ test("never shown when hidden", () => {+ expect(computeBypassActionWeight({ ...allowed, state: "hidden" })).toBe(+ "none"+ );+ });++ test("rejected is an explicit override: shown whenever permitted", () => {+ expect(+ computeBypassActionWeight({+ canCreateRollout: true,+ requireIssueApproval: true,+ state: "rejected",+ })+ ).toBe("link");+ // ...but still gated by the create-rollout permission.+ expect(+ computeBypassActionWeight({+ ...allowed,+ canCreateRollout: false,+ state: "rejected",+ })+ ).toBe("none");+ });++ test("hidden without bb.rollouts.create", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ canCreateRollout: false,+ state: "approved-checks-failed",+ })+ ).toBe("none");+ });++ test("mandatory approval hides the bypass while review is in progress", () => {+ expect(+ computeBypassActionWeight({+ ...allowed,+ requireIssueApproval: true,+ state: "waiting-review",+ })+ ).toBe("none");+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.ts b/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.tsnew file mode 100644index 0000000000..7a45730368--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/readinessFooterState.ts@@ -0,0 +1,77 @@+// Footer state machine + bypass gating (spec: "Rollout readiness footer").+// The backend only enforces bb.rollouts.create on CreateRollout; the project+// "require issue approval" / "require no failed checks" settings are+// client-side gates, so the action hides whenever clicking it would violate+// one of them in the current state. The status line renders for everyone.+import { ApprovalStatus } from "@/types/proto-es/v1/common_pb";+import { IssueStatus } from "@/types/proto-es/v1/issue_service_pb";+import type { PlanCheckSummary } from "../../utils/phaseSummary";++export type ReadinessFooterStateKind =+ | "hidden"+ | "waiting-review"+ | "all-gates-passed"+ | "approved-checks-failed"+ | "rejected";++export interface ReadinessFooterState {+ kind: ReadinessFooterStateKind;+ checks: PlanCheckSummary;+}++export function computeReadinessFooterState(input: {+ hasRollout: boolean;+ issueStatus: IssueStatus | undefined;+ approvalStatus: ApprovalStatus;+ checks: PlanCheckSummary;+}): ReadinessFooterState {+ const { checks } = input;+ if (input.hasRollout || input.issueStatus !== IssueStatus.OPEN) {+ return { kind: "hidden", checks };+ }+ if (input.approvalStatus === ApprovalStatus.REJECTED) {+ return { kind: "rejected", checks };+ }+ if (+ input.approvalStatus === ApprovalStatus.APPROVED ||+ input.approvalStatus === ApprovalStatus.SKIPPED+ ) {+ return {+ kind: checks.error > 0 ? "approved-checks-failed" : "all-gates-passed",+ checks,+ };+ }+ return { kind: "waiting-review", checks };+}++export type BypassActionWeight = "none" | "link" | "button";++export function computeBypassActionWeight(input: {+ state: ReadinessFooterStateKind;+ canCreateRollout: boolean;+ requireIssueApproval: boolean;+}): BypassActionWeight {+ if (input.state === "hidden") {+ return "none";+ }+ if (!input.canCreateRollout) {+ return "none";+ }+ // A rejected review is an explicit, deliberate override: show the action+ // whenever the user can create a rollout. Kept as a muted link so it stays+ // quiet next to the "blocked" message. The confirm sheet still blocks deploy+ // when a mandatory project gate is unmet.+ if (input.state === "rejected") {+ return "link";+ }+ // Review still in progress: only offer the bypass when approval is optional —+ // a mandatory-approval project must not be bypassed before a decision.+ if (input.state === "waiting-review") {+ return input.requireIssueApproval ? "none" : "link";+ }+ // Review passed (approved/skipped): always offer a manual deploy when the user+ // can create a rollout, regardless of plan-check state. Prominent button when+ // checks failed (the call to action), muted link otherwise. The confirm sheet+ // still blocks deploy if the project mandates no failed checks.+ return input.state === "approved-checks-failed" ? "button" : "link";+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.ts b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.tsnew file mode 100644index 0000000000..bb91a92445--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.test.ts@@ -0,0 +1,51 @@+import { create } from "@bufbuild/protobuf";+import { TimestampSchema } from "@bufbuild/protobuf/wkt";+import { describe, expect, test } from "vitest";+import {+ IssueComment_Approval_Status,+ IssueCommentSchema,+} from "@/types/proto-es/v1/issue_service_pb";+import { buildTimelineEntries } from "./timelineEvents";++const userComment = (name: string, comment: string) =>+ create(IssueCommentSchema, { name, comment, creator: "users/[email protected]" });++const approvalComment = (+ name: string,+ status: IssueComment_Approval_Status,+ comment = ""+) =>+ create(IssueCommentSchema, {+ name,+ comment,+ creator: "users/[email protected]",+ event: { case: "approval", value: { status } },+ });++describe("buildTimelineEntries", () => {+ test("synthetic head rows come first, oldest-first", () => {+ const entries = buildTimelineEntries({+ planCreator: "users/[email protected]",+ planCreateTime: create(TimestampSchema, { seconds: 1n, nanos: 0 }),+ issueCreator: "users/[email protected]",+ issueCreateTime: create(TimestampSchema, { seconds: 2n, nanos: 0 }),+ comments: [userComment("c1", "hello")],+ });+ expect(entries.map((e) => e.source.type)).toEqual([+ "plan-created",+ "ready-for-review",+ "comment",+ ]);+ });++ test("each comment maps to a comment-source entry keyed by its name", () => {+ const entries = buildTimelineEntries({+ comments: [+ approvalComment("c1", IssueComment_Approval_Status.REJECTED, "no"),+ userComment("c2", "hi"),+ ],+ });+ expect(entries.map((e) => e.id)).toEqual(["c1", "c2"]);+ expect(entries.every((e) => e.source.type === "comment")).toBe(true);+ });+});diff --git a/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.tsnew file mode 100644index 0000000000..84ef39a0d3--- /dev/null+++ b/frontend/src/react/pages/project/plan-detail/components/review/timelineEvents.ts@@ -0,0 +1,50 @@+// Maps the review timeline's event sources into a flat, oldest-first entry+// list (spec: "Activity timeline"). Whether an entry renders as a bordered+// card or a one-line system row is decided at render time by body presence,+// so no weight/tier is stored here. Plan check results are never entries.+import type { Timestamp } from "@bufbuild/protobuf/wkt";+import type { IssueComment } from "@/types/proto-es/v1/issue_service_pb";++export type TimelineSource =+ | { type: "plan-created"; creator: string; time?: Timestamp }+ | { type: "ready-for-review"; creator: string; time?: Timestamp }+ | { type: "comment"; comment: IssueComment };++export interface TimelineEntry {+ id: string;+ source: TimelineSource;+}++export function buildTimelineEntries(input: {+ planCreator?: string;+ planCreateTime?: Timestamp;+ issueCreator?: string;+ issueCreateTime?: Timestamp;+ comments: IssueComment[];+}): TimelineEntry[] {+ const entries: TimelineEntry[] = [];+ if (input.planCreator) {+ entries.push({+ id: "plan-created",+ source: {+ type: "plan-created",+ creator: input.planCreator,+ time: input.planCreateTime,+ },+ });+ }+ if (input.issueCreator) {+ entries.push({+ id: "ready-for-review",+ source: {+ type: "ready-for-review",+ creator: input.issueCreator,+ time: input.issueCreateTime,+ },+ });+ }+ for (const comment of input.comments) {+ entries.push({ id: comment.name, source: { type: "comment", comment } });+ }+ return entries;+}diff --git a/frontend/src/react/pages/project/plan-detail/components/review/useApprovalCandidates.ts b/frontend/src/react/pages/project/plan-detail/components/review/useApprovalCandidates.tsnew file mode 100644index 0000000000..d95426b10cBinary files /dev/null and b/frontend/src/react/pages/project/plan-detail/components/review/useApprovalCandidates.ts differ