Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(plan): streamline create and ready-for-review actions (#21047)
boojack83bd74741ba7
diff --git a/docs/plans/2026-07-27-plan-lifecycle-advance-design.md b/docs/plans/2026-07-27-plan-lifecycle-advance-design.mdnew file mode 100644index 0000000000..15e8885e31--- /dev/null+++ b/docs/plans/2026-07-27-plan-lifecycle-advance-design.md@@ -0,0 +1,327 @@+# Plan Lifecycle Advance Design++- **Date:** 2026-07-27+- **Status:** Implemented+- **Issues:** [BYT-9925](https://linear.app/bytebase/issue/BYT-9925/plan-create-button-is-disabled-again-on-validation-errors-hiding),+ [BYT-9936](https://linear.app/bytebase/issue/BYT-9936/ready-for-review-always-opens-an-unnecessary-submission-form)+- **Supersedes behavior from:** #20615 (BYT-9531), #20924++## Summary++The plan-detail header keeps one primary control beside the title. Two of its+states — `create` and `ready-for-review` — disagree with the rest of the header,+and with each other, about how a primary action handles unmet conditions.++`create` disables the button and hides the reasons in a native hover tooltip+that shows only the first one. `ready-for-review` does the opposite: it always+opens a form, even when nothing needs a decision.++Both are the same missing rule, and the rule is already written down in the+deploy phase of the same header.++Replace both with one component:++- The button is **always rendered and always enabled** (except while a request+ is in flight).+- Pressing it with unmet conditions **states all of them** in a popover anchored+ to the button. The list is information — no fields, no confirm, no links away —+ and it closes itself as conditions resolve.+- Pressing it when the only thing left is a deliberate override opens **that one+ decision**, named after what it does.++## Problem++### The row speaks three dialects++| Lifecycle state | Control | Unmet conditions surfaced as |+| --- | --- | --- |+| `create` | Disabled `<Button>` | Native `title`, first reason only |+| `ready-for-review` | `<Button>` + popover | A form: labels, warning, acknowledgement, errors, Confirm/Cancel |+| `ready-for-review` (editing / no permission) | Disabled `<Button>` | Native `title` |+| `run-stage` | `<Button>` + confirm sheet | Not applicable — a real decision |+| `plan-status` | Status pill + gate panel | Click to reveal |+| not actionable | `LifecycleStamp` | Status, never a disabled action |++`DeployStageActions.tsx` states the rule the last three rows follow:++```text+not actionable → status, not a disabled action+```++`PlanStatusAction` supplies the other half: a control you click to learn why.+The two draft states predate the lifecycle refactor and never adopted either.++### Why the current `create` branch is a dead end++`PlanDetailHeader.tsx` renders a disabled button carrying+`title={createDisabledReason}`, where `createDisabledReason` is+`createPermissionReason ?? createPlanBlockingReasons[0]`.++Three separate defects fall out of that one line:++1. **Only the first reason is reachable.** With an empty title and an empty+ statement, fixing the title reveals the second blocker for the first time.+2. **Keyboard and screen-reader users get nothing.** A disabled button is out of+ the tab order, and `title` is unreliable for assistive technology even when+ it is reachable.+3. **`getCreatePlanBlockingReasons` already returns the full list.** The data is+ correct; only the presentation throws it away.++This is a regression. #20615 shipped an always-enabled button with a callout+listing every blocker; #20924 rewrote the branch and dropped it, along with the+`plan.cannot-create` key.++### Why the current `ready-for-review` branch over-asks++The popover always contains an `IssueLabelSelect` and a Confirm/Cancel pair, and+conditionally a checks warning, an acknowledgement checkbox, and an error alert.++- Labels are **already editable** in `PlanDetailMeta`, one row below. The popover+ is a second editor for the same field.+- The warning, the acknowledgement and the error only apply when checks fail.+- Every submission pays the cost of the exception.++## Design++### One rule, three tiers++The tier is derived from data, so the component never hard-codes which surface+appears. The same failing check is tier 1 or tier 2 depending on whether the+project enforces SQL review.++| Tier | Condition | Surface |+| --- | --- | --- |+| 0 | Nothing unresolved | None — the click advances |+| 1 | One or more unmet conditions | A popover listing all of them |+| 2 | A deliberate override | One confirmation, named after what it does |++Tiers 1 and 2 are mutually exclusive, so they share a single popover anchored to+the button.++Two corollaries:++- **Optional metadata is never a gate.** Labels leave the submit path. Where a+ project forces labels they become a tier-1 line; the control stays in the+ metadata row.+- **Nothing removes the action.** A running check, an unsaved edit and a missing+ permission are all tier-1 lines. The button stays where it is, and the popover+ says why. This is one fewer header state to build than a separate+ "no permission" stamp, and it keeps the header's geometry stable.++### Why a popover on the action++The explanation belongs to the control it explains. Anchoring it to the button+keeps that relationship obvious and keeps the sticky header exactly one row tall+in every state — a full-width band across the header reads as a page-level+condition rather than an answer to the press that produced it, and it pushes the+rest of the page down while it is showing.++It also matches the vocabulary the rest of the header already speaks: the+plan-status pill and the review composer both answer a press with a popover+anchored to the control.++Cost, stated plainly: the list closes when the reader clicks away, so with more+than one blocker they may need to press again after resolving the first. The+list is short, every entry names something visible on the page, and pressing+again is one click.++### Blocker sources++```text+create → title, empty statements, create permission+ready-for-review → empty statements, data-export unsupported, checks running,+ checks failed (only when enforceSqlReview), labels+ (only when forceIssueLabels), unsaved edits, update permission+```++A blocker carries a `kind`:++- `fix` — the reader resolves it.+- `wait` — it resolves itself. The row says so, so a running check does not read+ as something forgotten.++### Component shape++One component owns the surface state and renders the button plus both popover+contents:++```ts+<LifecycleAdvanceButton+ blockers={createBlockers}+ busy={updating}+ heading={t("plan.cannot-create")}+ onAdvance={() => void handleCreatePlan()}+ onBlocked={(blockers) => {+ if (blockers.some((blocker) => blocker.id === "title")) {+ titleInputRef.current?.focus();+ }+ }}+ verb={t("common.create")}+/>+```++`LifecycleAdvanceButton` owns one+`"none" | "blockers" | "decision"` surface value, so the two popovers cannot be+open at the same time. The blocker list shows only while the selected surface is+`blockers` and blockers remain, so it self-clears without an effect. A single+`dismiss` closes either surface on outside press, Escape, or Cancel.++The header keys the component on `page.pageKey`, resetting its local surface+when navigation moves to another plan while preserving it across same-plan+resource routes. `onBlocked` receives the current blocker list; the header uses+it for the one nudge that costs nothing: when the missing title is a blocker, put+the cursor in the title field, which is already in the header.++## Implementation++### `frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.ts`++New. Owns the route-local blocker and decision model plus the pure resolvers that+derive it from plan and project state.++```ts+export interface AdvanceBlocker {+ id: string;+ message: string;+ kind: "fix" | "wait";+}++export interface AdvanceDecision {+ headline: string;+ body: string;+ verb: string;+}++export interface AdvanceState {+ blockers: AdvanceBlocker[];+ decision?: AdvanceDecision;+}+```++- Replace `getCreatePlanBlockingReasons` with `getCreatePlanBlockers`, which+ returns `AdvanceBlocker[]` and additionally reports a missing create+ permission.+- Replace `getCreateIssueBlockingErrors` + `getCreateIssueConfirmErrors` with a+ single `getSubmitReviewAdvance`, folding blockers and the optional failed-check+ decision into one result so the two outcomes cannot drift apart.+- Reuse `getPlanCheckSummaryWithFallback` for running and failed checks, while+ handling the backend-only `AVAILABLE` queue status explicitly.+- Export stable empty values for lifecycle states that do not render an advance.++### `frontend/src/lib/plan/workflow.ts`++- `submitDraftReview` drops its `labels` parameter and sends+ `updateMask: { paths: ["draft"] }`. Labels are already persisted by+ `PlanDetailMeta`.+- Remove the header-only blocker and warning helpers now owned beside the route.++### `frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.tsx`++New. Exports `LifecycleAdvanceButton` and its props.++Both surfaces reuse the existing `Popover` primitives, controlled and anchored to+the button rather than trigger-driven, so a press opens them only at tier 1 or 2.+`initialFocus={false}` keeps the caller's `onBlocked` nudge — the cursor in the+empty title — from being stolen by the popup. The blocker list carries+`role="alert"` so it is announced when it appears.++### `frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx`++- Both the `create` and `ready-for-review` branches become callers of the same+ component, differing only in verb, heading and blocker source. The header row+ itself is unchanged — nothing new renders beneath it.+- Delete `showReviewPopover`, `selectedLabels`, `checksWarningAcknowledged` and+ the effect that syncs labels from `page.issue.labels`.+- Delete `ReadyForReviewPopoverContent` and the `IssueLabelSelect` / `Checkbox`+ imports.+- `handleCreatePlan` and `handleSubmitDraftReview` keep their existing+ early-return guards; the component no longer relies on `disabled` to enforce+ them.+- Resolve advance data only for the lifecycle state that currently renders it,+ and key `LifecycleAdvanceButton` on `page.pageKey` to isolate local popover+ state across plans.++### Locales++Four new keys across all five locale files:++| Key | English |+| --- | --- |+| `plan.cannot-create` | Cannot create plan |+| `plan.not-ready-for-review` | Not ready for review |+| `plan.submit-review-anyway` | Submit anyway |+| `plan.blocker.clears-on-its-own` | Clears on its own |++`issue.action-anyway` becomes orphaned when the acknowledgement checkbox goes+and is removed from all five locale files.++Everything else reuses shipping strings: `plan.title-required`,+`plan.navigator.statement-empty`, `plan.labels-required-for-review`,+`plan.editor.save-changes-before-continuing`,+`plan.draft-update-permission-required`, `common.missing-required-permission`,+`plan.lifecycle.gate-checks-failed`, `issue.checks-warning-hint`, and the two+`custom-approval.issue-review.disallow-approve-reason.*` strings.++## Testing++### `frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.test.ts`++New. Covers every resolver branch:++- `getCreatePlanBlockers` — empty title, whitespace title, empty statements,+ both together in order, missing permission, and the valid case.+- `getSubmitReviewAdvance` — empty statements, data export, checks running+ (`kind: "wait"`), checks failed with and without `enforceSqlReview`, labels+ required with and without `forceIssueLabels`, unsaved edits, missing+ `bb.issues.update`, and the clean case.+- The decision is present when checks failed and SQL review is not enforced,+ absent when enforced, absent when checks pass, and absent for a plan that is+ not purely a database change.++### `frontend/src/lib/plan/workflow.test.ts`++- `submitDraftReview` — sends `draft: false` with `updateMask: ["draft"]` and no+ longer writes labels.++### `frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.test.tsx`++New:++- Tier 0 — pressing calls `onAdvance` and opens nothing.+- Tier 1 — pressing does not call `onAdvance`, reveals every blocker, and calls+ `onBlocked`.+- Tier 1 — the list is absent before the first press.+- Tier 1 — the list disappears when the blocker set empties, with no second+ press, and shortens as individual blockers resolve.+- Tier 1 — a `wait` blocker renders its clears-on-its-own affordance.+- Tier 1 — outside press dismisses the list.+- Tier 2 — pressing opens the confirmation and does not advance; confirming+ advances once; cancelling does not.+- Blockers outrank a decision when both are present.+- `busy` disables the primary button while a request is in flight.++### `frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx`++Update the existing draft-advance coverage and add integration cases for the new+tiers:++- Create stays enabled, lists validation and permission blockers, focuses the+ empty title, self-clears when the title is fixed, and never calls `createPlan`+ while blocked.+- A clean draft submits in one press with no intermediate form, and the request+ updates only `draft`; label edits remain owned by the metadata row.+- Unsaved edits and a missing `bb.issues.update` permission list blockers and do+ not submit.+- Failing checks without `enforceSqlReview` reach the named override; enforced+ SQL review renders the same failure as a blocker instead.+- An open blocker list does not survive navigation to another plan.++## Out of scope++- Renaming **Ready for Review** to **Submit for review**. The control names a+ state rather than the action it performs, and the same principle that produces+ *Submit anyway* argues for it — but it is a copy change with its own blast+ radius across locales, tests and docs.+- Any change to `run-stage`, `plan-status`, or the review composer. They already+ follow the rule.+- Backend or protobuf changes. This is frontend-only.diff --git a/frontend/src/lib/plan/workflow.test.ts b/frontend/src/lib/plan/workflow.test.tsindex ce381524ef..4c8df7bc45 100644--- a/frontend/src/lib/plan/workflow.test.ts+++ b/frontend/src/lib/plan/workflow.test.ts@@ -10,29 +10,21 @@ import type {Plan,} from "@/types/proto-es/v1/plan_service_pb";import { PlanSchema } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";import {createPlanWithDraftReview,DraftReviewIssueCreationError,- getCreateIssueBlockingErrors,- getCreateIssueConfirmErrors,- getCreatePlanBlockingReasons,- hasChecksWarning,shouldStayOnPlanDetailPage,submitDraftReview,} from "./workflow";-const t = (key: string) => key;--const makePlan = (cases: string[], statusCount = {}): Plan =>+const makePlan = (cases: string[]): Plan =>({- planCheckRunStatusCount: statusCount,specs: cases.map((caseName) => ({config: { case: caseName, value: {} },})),}) as unknown as Plan;-describe("plan detail header create issue helpers", () => {+describe("shouldStayOnPlanDetailPage", () => {test("keeps database change plans on plan detail after issue creation", () => {expect(shouldStayOnPlanDetailPage(makePlan(["changeDatabaseConfig"]))).toBe(true@@ -41,84 +33,6 @@ describe("plan detail header create issue helpers", () => {false);});-- test("flags non-blocking check warnings without adding a confirm error", () => {- const plan = makePlan(["changeDatabaseConfig"], { ERROR: 1 });- const project = {- enforceSqlReview: false,- forceIssueLabels: false,- } as Project;- const blockingErrors = getCreateIssueBlockingErrors({- emptySpecCount: 0,- plan,- project,- t,- });-- expect(blockingErrors).toEqual([]);- expect(hasChecksWarning(plan)).toBe(true);- expect(- getCreateIssueConfirmErrors({- blockingErrors,- project,- selectedLabelCount: 0,- t,- })- ).toEqual([]);- });-- test("keeps SQL review enforcement as a blocking error", () => {- const plan = makePlan(["changeDatabaseConfig"], { ERROR: 1 });- const project = {- enforceSqlReview: true,- forceIssueLabels: false,- } as Project;-- expect(- getCreateIssueBlockingErrors({- emptySpecCount: 0,- plan,- project,- t,- })- ).toContain(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- );- });-- test("blocks issue creation while plan checks are queued", () => {- const project = {- enforceSqlReview: false,- forceIssueLabels: false,- } as Project;-- expect(- getCreateIssueBlockingErrors({- emptySpecCount: 0,- plan: makePlan(["changeDatabaseConfig"], { AVAILABLE: 1 }),- project,- t,- })- ).toContain(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- );- });-- test("blocks data export issue creation", () => {- const project = {- enforceSqlReview: false,- forceIssueLabels: false,- } as Project;-- expect(- getCreateIssueBlockingErrors({- emptySpecCount: 0,- plan: makePlan(["exportDataConfig"]),- project,- t,- })- ).toContain("issue.data-export.creation-not-supported");- });});describe("createPlanWithDraftReview", () => {@@ -196,30 +110,41 @@ describe("createPlanWithDraftReview", () => {});describe("submitDraftReview", () => {- test("submits the persisted issue by clearing draft and retaining selected labels", async () => {+ test("submits the persisted issue by clearing draft only", async () => {const draft = create(IssueSchema, {name: "projects/p1/issues/456",draft: true,labels: ["old"],});- const submitted = create(IssueSchema, {- ...draft,- draft: false,- labels: ["prod"],- });+ const submitted = create(IssueSchema, { ...draft, draft: false });const updateIssue = vi.fn(async (_request: UpdateIssueRequest) => submitted);await expect(- submitDraftReview({ issue: draft, labels: ["prod"], updateIssue })+ submitDraftReview({ issue: draft, updateIssue })).resolves.toBe(submitted);expect(updateIssue.mock.calls[0][0]).toMatchObject({- issue: { draft: false, labels: ["prod"] },- updateMask: { paths: ["draft", "labels"] },+ issue: { draft: false },+ updateMask: { paths: ["draft"] },});});+ test("leaves labels to the metadata row rather than writing them back", async () => {+ const updateIssue = vi.fn(async (_request: UpdateIssueRequest) =>+ create(IssueSchema, {})+ );++ await submitDraftReview({+ issue: create(IssueSchema, { draft: true, labels: ["stale"] }),+ updateIssue,+ });++ expect(updateIssue.mock.calls[0][0].updateMask?.paths).not.toContain(+ "labels"+ );+ });+test("surfaces the submission failure without retrying", async () => {const failure = new Error("approval setup failed");const updateIssue = vi.fn(async () => {@@ -229,50 +154,9 @@ describe("submitDraftReview", () => {await expect(submitDraftReview({issue: create(IssueSchema, { draft: true }),- labels: [],updateIssue,})).rejects.toBe(failure);expect(updateIssue).toHaveBeenCalledOnce();});});--describe("getCreatePlanBlockingReasons", () => {- test("flags an empty title", () => {- expect(- getCreatePlanBlockingReasons({ title: "", emptySpecCount: 0, t })- ).toEqual(["plan.title-required"]);- });-- test("flags a whitespace-only title", () => {- expect(- getCreatePlanBlockingReasons({ title: " ", emptySpecCount: 0, t })- ).toEqual(["plan.title-required"]);- });-- test("flags empty statements", () => {- expect(- getCreatePlanBlockingReasons({- title: "Add column",- emptySpecCount: 2,- t,- })- ).toEqual(["plan.navigator.statement-empty"]);- });-- test("lists both blockers, title first", () => {- expect(- getCreatePlanBlockingReasons({ title: "", emptySpecCount: 1, t })- ).toEqual(["plan.title-required", "plan.navigator.statement-empty"]);- });-- test("returns no reasons when valid", () => {- expect(- getCreatePlanBlockingReasons({- title: "Add column",- emptySpecCount: 0,- t,- })- ).toEqual([]);- });-});diff --git a/frontend/src/lib/plan/workflow.ts b/frontend/src/lib/plan/workflow.tsindex 6816a98b99..b7fb51d3a6 100644--- a/frontend/src/lib/plan/workflow.ts+++ b/frontend/src/lib/plan/workflow.ts@@ -16,9 +16,6 @@ import type {Plan,} from "@/types/proto-es/v1/plan_service_pb";import { CreatePlanRequestSchema } from "@/types/proto-es/v1/plan_service_pb";-import type { Project } from "@/types/proto-es/v1/project_service_pb";--type T = (key: string, options?: Record<string, unknown>) => string;export class DraftReviewIssueCreationError extends Error {readonly plan: Plan;@@ -73,13 +70,14 @@ export async function createPlanWithDraftReview({}}+// Submitting only flips the draft flag. Labels are owned by the plan metadata+// row, which persists them on change — the submit path must not write them back+// and silently undo an edit made while the header was open.export async function submitDraftReview({issue,- labels,updateIssue,}: {issue: Issue;- labels: string[];updateIssue: (request: UpdateIssueRequest) => Promise<Issue>;}): Promise<Issue> {return updateIssue(@@ -87,9 +85,8 @@ export async function submitDraftReview({issue: create(IssueSchema, {...issue,draft: false,- labels,}),- updateMask: { paths: ["draft", "labels"] },+ updateMask: { paths: ["draft"] },}));}@@ -105,94 +102,3 @@ export const shouldStayOnPlanDetailPage = (plan: Plan): boolean => {spec.config?.case === "exportDataConfig");};--export const hasChecksWarning = (plan: Plan): boolean => {- const statusCount = plan.planCheckRunStatusCount || {};- const hasError =- (statusCount.ERROR ?? 0) > 0 || (statusCount.FAILED ?? 0) > 0;- return (- hasError &&- plan.specs.length > 0 &&- plan.specs.every((spec) => spec.config?.case === "changeDatabaseConfig")- );-};--export const getCreatePlanBlockingReasons = ({- title,- emptySpecCount,- t,-}: {- title: string;- emptySpecCount: number;- t: T;-}): string[] => {- const reasons: string[] = [];- if (!title.trim()) {- reasons.push(t("plan.title-required"));- }- if (emptySpecCount > 0) {- reasons.push(t("plan.navigator.statement-empty"));- }- return reasons;-};--export const getCreateIssueBlockingErrors = ({- emptySpecCount,- plan,- project,- t,-}: {- emptySpecCount: number;- plan: Plan;- project: Pick<Project, "enforceSqlReview">;- t: T;-}): string[] => {- const errors: string[] = [];- const statusCount = plan.planCheckRunStatusCount || {};-- if (emptySpecCount > 0) {- errors.push(t("plan.navigator.statement-empty"));- }- if (plan.specs.some((spec) => spec.config?.case === "exportDataConfig")) {- errors.push(t("issue.data-export.creation-not-supported"));- }- if ((statusCount.AVAILABLE ?? 0) > 0 || (statusCount.RUNNING ?? 0) > 0) {- errors.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"- )- );- }- if (- ((statusCount.ERROR ?? 0) > 0 || (statusCount.FAILED ?? 0) > 0) &&- project.enforceSqlReview- ) {- errors.push(- t(- "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"- )- );- }-- return errors;-};--export const getCreateIssueConfirmErrors = ({- blockingErrors,- project,- selectedLabelCount,- t,-}: {- blockingErrors: string[];- project: Pick<Project, "forceIssueLabels">;- selectedLabelCount: number;- t: T;-}): string[] => {- const errors = [...blockingErrors];-- if (project.forceIssueLabels && selectedLabelCount === 0) {- errors.push(t("plan.labels-required-for-review"));- }-- return errors;-};diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 610877bb46..20ab3d327c 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1294,7 +1294,6 @@"this-grant-allows": "This grant allows","unmask-data-in-results": "Unmask sensitive data in results"},- "action-anyway": "{{action}} anyway","advanced-search": {"filter": "Filter","scope": {@@ -1532,6 +1531,10 @@"plan": {"add-spec": "Add Change","add-spec-pending-draft": "Save or discard the pending change before adding another",+ "blocker": {+ "clears-on-its-own": "Clears on its own"+ },+ "cannot-create": "Cannot create plan","checks": {"completed": "Plan checks completed","failed-to-run": "Failed to run plan checks",@@ -1544,7 +1547,7 @@"description": {"placeholder": "Add description"},- "draft-update-permission-required": "You can view this draft, but you need bb.issues.update to edit labels or submit it for review.",+ "draft-update-permission-required": "You can view this draft, but you need bb.issues.update to edit issue labels or submit it for review.","editor": {"save-changes-before-continuing": "Please save or cancel your changes before continuing"},@@ -1562,7 +1565,7 @@"self": "Isolation Level","serializable": "Serializable"},- "labels-required-for-review": "Labels are required before review",+ "labels-required-for-review": "Issue Labels are required before review","lifecycle": {"checking": "Checking…","checks-failing": "Checks failing",@@ -1594,6 +1597,7 @@"statement-empty": "Statement is empty"},"new-plan": "New Plan",+ "not-ready-for-review": "Not ready for review","options": {"no-options-available": "No options available","self": "Options"@@ -1702,6 +1706,7 @@"reopen-confirm": "Reopen this plan?","reopen-review-confirm": "Reopen this review?"},+ "submit-review-anyway": "Submit anyway","subtitle": "Draft database changes and run pre-checks before creating an issue for approval.","summary": {"last-approved-by": "Last approved by {{name}}",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 707d669c0d..6636eb1b42 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1294,7 +1294,6 @@"this-grant-allows": "Esta concesión permite","unmask-data-in-results": "Desenmascarar datos sensibles en los resultados"},- "action-anyway": "{{action}} de todos modos","advanced-search": {"filter": "Filtrar","scope": {@@ -1532,6 +1531,10 @@"plan": {"add-spec": "Agregar cambio","add-spec-pending-draft": "Guarda o descarta el cambio pendiente antes de agregar otro",+ "blocker": {+ "clears-on-its-own": "Se resuelve solo"+ },+ "cannot-create": "No se puede crear el plan","checks": {"completed": "Se completaron las verificaciones del plan","failed-to-run": "No se pudieron ejecutar las verificaciones del plan",@@ -1544,7 +1547,7 @@"description": {"placeholder": "Agregar descripción"},- "draft-update-permission-required": "Puedes ver este borrador, pero necesitas bb.issues.update para editar etiquetas o enviarlo a revisión.",+ "draft-update-permission-required": "Puedes ver este borrador, pero necesitas bb.issues.update para editar etiquetas de problema o enviarlo a revisión.","editor": {"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."},@@ -1562,7 +1565,7 @@"self": "Nivel de Aislamiento","serializable": "Serializable"},- "labels-required-for-review": "Se requieren etiquetas antes de la revisión",+ "labels-required-for-review": "Se requieren etiquetas de problema antes de la revisión","lifecycle": {"checking": "Comprobando…","checks-failing": "Comprobaciones fallidas",@@ -1594,6 +1597,7 @@"statement-empty": "La sentencia está vacía"},"new-plan": "Nuevo plan",+ "not-ready-for-review": "No está listo para revisión","options": {"no-options-available": "No hay opciones disponibles","self": "Opciones"@@ -1702,6 +1706,7 @@"reopen-confirm": "¿Reabrir este plan?","reopen-review-confirm": "¿Reabrir esta revisión?"},+ "submit-review-anyway": "Enviar de todos modos","subtitle": "Redactar cambios en la base de datos y ejecutar comprobaciones previas antes de crear un problema para su aprobación.","summary": {"last-approved-by": "Última aprobación por {{name}}",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex dbc54a8c2f..3b7a19d210 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1294,7 +1294,6 @@"this-grant-allows": "このアクセス権限で許可される操作","unmask-data-in-results": "結果内の機密データのマスクを解除"},- "action-anyway": "まだ {{action}} が必要です","advanced-search": {"filter": "フィルター","scope": {@@ -1532,6 +1531,10 @@"plan": {"add-spec": "変更を追加","add-spec-pending-draft": "新しい変更を追加する前に、保留中の変更を保存または破棄してください",+ "blocker": {+ "clears-on-its-own": "自動的に解消されます"+ },+ "cannot-create": "プランを作成できません","checks": {"completed": "プランチェックが完了しました","failed-to-run": "プランチェックの実行に失敗しました",@@ -1544,7 +1547,7 @@"description": {"placeholder": "説明を追加"},- "draft-update-permission-required": "この下書きは表示できますが、ラベルの編集やレビューへの提出には bb.issues.update が必要です。",+ "draft-update-permission-required": "この下書きは表示できますが、イシューラベルの編集やレビューへの提出には bb.issues.update が必要です。","editor": {"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"},@@ -1562,7 +1565,7 @@"self": "分離レベル","serializable": "直列化可能"},- "labels-required-for-review": "レビュー前にラベルが必要です",+ "labels-required-for-review": "レビュー前にイシューラベルが必要です","lifecycle": {"checking": "チェック中…","checks-failing": "チェック失敗",@@ -1594,6 +1597,7 @@"statement-empty": "ステートメントが空です"},"new-plan": "プランの作成",+ "not-ready-for-review": "レビューの準備ができていません","options": {"no-options-available": "利用可能なオプションはありません","self": "オプション"@@ -1702,6 +1706,7 @@"reopen-confirm": "このプランを再開きますか?","reopen-review-confirm": "このレビューを再開しますか?"},+ "submit-review-anyway": "それでも提出する","subtitle": "承認のためにイシューを作成する前に、データベースの変更を下書きし、事前チェックを実行します。","summary": {"last-approved-by": "{{name}} が最後に承認",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex c4790d61c8..7ddb76a831 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1294,7 +1294,6 @@"this-grant-allows": "Cấp quyền này cho phép","unmask-data-in-results": "Hiển thị dữ liệu nhạy cảm trong kết quả"},- "action-anyway": "{{action}} bằng mọi cách","advanced-search": {"filter": "Bộ lọc","scope": {@@ -1532,6 +1531,10 @@"plan": {"add-spec": "Thêm thay đổi","add-spec-pending-draft": "Lưu hoặc hủy thay đổi đang chờ trước khi thêm thay đổi khác",+ "blocker": {+ "clears-on-its-own": "Tự động hoàn tất"+ },+ "cannot-create": "Không thể tạo kế hoạch","checks": {"completed": "Đã hoàn thành kiểm tra kế hoạch","failed-to-run": "Không thể chạy kiểm tra kế hoạch",@@ -1544,7 +1547,7 @@"description": {"placeholder": "Thêm mô tả"},- "draft-update-permission-required": "Bạn có thể xem bản nháp này, nhưng cần bb.issues.update để chỉnh sửa nhãn hoặc gửi đi xem xét.",+ "draft-update-permission-required": "Bạn có thể xem bản nháp này, nhưng cần bb.issues.update để chỉnh sửa nhãn vấn đề hoặc gửi đi xem xét.","editor": {"save-changes-before-continuing": "Vui lòng lưu hoặc hủy thay đổi của bạn trước khi tiếp tục"},@@ -1562,7 +1565,7 @@"self": "Mức Độ Cô Lập","serializable": "Tuần tự hóa"},- "labels-required-for-review": "Cần có nhãn trước khi review",+ "labels-required-for-review": "Cần có nhãn vấn đề trước khi review","lifecycle": {"checking": "Đang kiểm tra…","checks-failing": "Kiểm tra thất bại",@@ -1594,6 +1597,7 @@"statement-empty": "Câu lệnh đang trống"},"new-plan": "Kế hoạch mới",+ "not-ready-for-review": "Chưa sẵn sàng để xem xét","options": {"no-options-available": "Không có tùy chọn nào khả dụng","self": "Tùy chọn"@@ -1702,6 +1706,7 @@"reopen-confirm": "Mở lại kế hoạch này?","reopen-review-confirm": "Mở lại đợt xem xét này?"},+ "submit-review-anyway": "Vẫn gửi","subtitle": "Soạn thảo các thay đổi cơ sở dữ liệu và chạy các bước kiểm tra sơ bộ trước khi tạo vấn đề để phê duyệt.","summary": {"last-approved-by": "Phê duyệt gần nhất bởi {{name}}",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 9a3608f0d2..be10f3a716 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1294,7 +1294,6 @@"this-grant-allows": "此授权允许","unmask-data-in-results": "在结果中查看未脱敏的敏感数据"},- "action-anyway": "仍要{{action}}","advanced-search": {"filter": "过滤","scope": {@@ -1532,6 +1531,10 @@"plan": {"add-spec": "添加变更","add-spec-pending-draft": "请先保存或放弃当前的待处理变更,然后再添加新变更",+ "blocker": {+ "clears-on-its-own": "将自动完成"+ },+ "cannot-create": "无法创建变更计划","checks": {"completed": "已完成计划检查","failed-to-run": "运行计划检查失败",@@ -1544,7 +1547,7 @@"description": {"placeholder": "添加描述"},- "draft-update-permission-required": "你可以查看此草稿,但需要 bb.issues.update 才能编辑标签或提交审批。",+ "draft-update-permission-required": "你可以查看此草稿,但需要 bb.issues.update 才能编辑工单标签或提交审批。","editor": {"save-changes-before-continuing": "请保存或取消更改,然后再继续"},@@ -1562,7 +1565,7 @@"self": "隔离级别","serializable": "串行化"},- "labels-required-for-review": "提交审批前必须设置标签",+ "labels-required-for-review": "提交审批前必须设置工单标签","lifecycle": {"checking": "检查中…","checks-failing": "检查失败",@@ -1594,6 +1597,7 @@"statement-empty": "语句为空"},"new-plan": "创建变更计划",+ "not-ready-for-review": "尚未准备好提交审核","options": {"no-options-available": "暂无可配置项","self": "配置项"@@ -1702,6 +1706,7 @@"reopen-confirm": "确认重新打开这个计划?","reopen-review-confirm": "确认重新打开这个审批?"},+ "submit-review-anyway": "仍然提交","subtitle": "草拟数据库变更并运行预检查,然后创建工单以请求审批。","summary": {"last-approved-by": "最后由 {{name}} 审批",diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsxindex d547d9f5da..15d11c39a5 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx@@ -54,23 +54,6 @@ vi.mock("@/api", () => ({},}));-vi.mock("@/components/IssueLabelSelect", () => ({- IssueLabelSelect: ({- onChange,- selected,- }: {- onChange: (labels: string[]) => void;- selected: string[];- }) => (- <div>- <output data-testid="selected-labels">{selected.join(",")}</output>- <button onClick={() => onChange(["replacement"])} type="button">- select replacement label- </button>- </div>- ),-}));-vi.mock("@/components/MarkdownEditor", () => ({MarkdownEditor: ({ content }: { content: string }) => <span>{content}</span>,}));@@ -89,76 +72,17 @@ vi.mock("@/components/ui/button", () => ({}) => <button {...props}>{children}</button>,}));-vi.mock("@/components/ui/checkbox", () => ({- Checkbox: ({- checked,- onCheckedChange,- }: {- checked: boolean;- onCheckedChange?: (checked: boolean) => void;- }) => (- <input- checked={checked}- onChange={(event) => onCheckedChange?.(event.target.checked)}- type="checkbox"- />- ),-}));-vi.mock("@/components/ui/textarea", () => ({Textarea: (props: TextareaHTMLAttributes<HTMLTextAreaElement>) => (<textarea {...props} />),}));-vi.mock("@/components/ui/popover", async () => {- const React = await vi.importActual<typeof import("react")>("react");- const PopoverContext = React.createContext<{- onOpenChange?: (open: boolean) => void;- open: boolean;- }>({ open: false });-- return {- Popover: ({- children,- onOpenChange,- open = false,- }: {- children: ReactNode;- onOpenChange?: (open: boolean) => void;- open?: boolean;- }) => (- <PopoverContext.Provider value={{ onOpenChange, open }}>- <div>{children}</div>- </PopoverContext.Provider>- ),- PopoverContent: ({ children }: { children: ReactNode }) => {- const { open } = React.useContext(PopoverContext);- return open ? <div>{children}</div> : null;- },- PopoverTrigger: ({- children,- render,- }: {- children: ReactNode;- render?: ReactElement<ButtonHTMLAttributes<HTMLButtonElement>>;- }) => {- const { onOpenChange, open } = React.useContext(PopoverContext);- if (!isValidElement(render)) return <>{children}</>;- const originalOnClick = render.props.onClick;- return cloneElement(- render,- {- onClick: (event) => {- originalOnClick?.(event);- onOpenChange?.(!open);- },- },- children- );- },- };-});+vi.mock("@/components/ui/popover", () => ({+ Popover: ({ children, open }: { children: ReactNode; open?: boolean }) =>+ open ? <div>{children}</div> : null,+ PopoverContent: ({ children }: { children: ReactNode }) => <>{children}</>,+}));vi.mock("@/components/ui/dropdown-menu", () => ({DropdownMenu: ({ children }: { children: ReactNode }) => (@@ -481,51 +405,29 @@ describe("PlanDetailHeader draft ownership", () => {).toBeVisible();});- test("resets review labels and warning acknowledgment after navigation", () => {+ test("does not carry a revealed notice to the next plan", () => {mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);mocks.lifecycle = { kind: "ready-for-review" };mocks.page = {...makePage(),- issue: { ...makePage().issue!, labels: ["old"] },- plan: {- ...makePage().plan,- planCheckRunStatusCount: { ERROR: 1 },- specs: [{ config: { case: "changeDatabaseConfig", value: {} } }],- },+ isEditing: true,} as unknown as PlanDetailPageState;const { rerender } = render(<PlanDetailHeader />);fireEvent.click(screen.getByRole("button", { name: "plan.ready-for-review" }));- fireEvent.click(- screen.getByRole("button", { name: "select replacement label" })+ expect(screen.getByRole("alert")).toHaveTextContent(+ "plan.editor.save-changes-before-continuing");- fireEvent.click(screen.getByRole("checkbox"));- expect(screen.getByTestId("selected-labels")).toHaveTextContent(- "replacement"- );- expect(screen.getByRole("checkbox")).toBeChecked();- mocks.page = {- ...mocks.page,- pageKey: "plan-456",- issue: { ...mocks.page.issue!, labels: ["new"] },- plan: {- ...mocks.page.plan,- name: "projects/p1/plans/456",- },- };+ mocks.page = { ...mocks.page, pageKey: "plan-456" };rerender(<PlanDetailHeader />);- fireEvent.click(- screen.getByRole("button", { name: "plan.ready-for-review" })- );- expect(screen.getByTestId("selected-labels")).toHaveTextContent("new");- expect(screen.getByRole("checkbox")).not.toBeChecked();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();});- test("submits labels from the Ready for Review popover and surfaces a single failure", async () => {+ test("submits the draft in one press and surfaces a single failure", async () => {const failure = new Error("approval setup failed");mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);mocks.lifecycle = { kind: "ready-for-review" };@@ -539,20 +441,17 @@ describe("PlanDetailHeader draft ownership", () => {fireEvent.click(screen.getByRole("button", { name: "plan.ready-for-review" }));- expect(screen.getByTestId("selected-labels")).toHaveTextContent("old");- fireEvent.click(- screen.getByRole("button", { name: "select replacement label" })- );- fireEvent.click(screen.getByRole("button", { name: "common.confirm" }));++ // No form stands between the press and the submission.+ expect(+ screen.queryByRole("button", { name: "common.confirm" })+ ).not.toBeInTheDocument();await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledOnce());expect(mocks.updateIssue).toHaveBeenCalledWith(expect.objectContaining({- issue: expect.objectContaining({- draft: false,- labels: ["replacement"],- }),- updateMask: { paths: ["draft", "labels"] },+ issue: expect.objectContaining({ draft: false }),+ updateMask: { paths: ["draft"] },}));await waitFor(() =>@@ -567,6 +466,98 @@ describe("PlanDetailHeader draft ownership", () => {expect(mocks.patchState).not.toHaveBeenCalled();});+ test("leaves label edits to the metadata row", async () => {+ mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ mocks.page = {+ ...makePage(),+ issue: { ...makePage().issue!, labels: ["keep-me"] },+ };+ render(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );++ await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledOnce());+ expect(+ mocks.updateIssue.mock.calls[0][0].updateMask.paths+ ).not.toContain("labels");+ });++ test("lists a missing update permission instead of disabling the action", () => {+ mocks.permissions = new Set(["bb.plans.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ mocks.page = makePage();+ render(<PlanDetailHeader />);++ const submit = screen.getByRole("button", {+ name: "plan.ready-for-review",+ });+ expect(submit).toBeEnabled();+ fireEvent.click(submit);++ expect(screen.getByRole("alert")).toHaveTextContent(+ "plan.draft-update-permission-required"+ );+ expect(mocks.updateIssue).not.toHaveBeenCalled();+ });++ test("confirms a named override before submitting past failed checks", async () => {+ mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ const page = makePage();+ mocks.page = {+ ...page,+ plan: {+ ...page.plan,+ planCheckRunStatusCount: { ERROR: 1 },+ specs: [{ config: { case: "changeDatabaseConfig", value: {} } }],+ },+ } as unknown as PlanDetailPageState;+ render(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );++ expect(mocks.updateIssue).not.toHaveBeenCalled();+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("button", { name: "plan.submit-review-anyway" })+ );++ await waitFor(() => expect(mocks.updateIssue).toHaveBeenCalledOnce());+ });++ test("blocks rather than confirms failed checks where SQL review is enforced", () => {+ mocks.permissions = new Set(["bb.plans.update", "bb.issues.update"]);+ mocks.lifecycle = { kind: "ready-for-review" };+ const page = makePage();+ mocks.page = {+ ...page,+ plan: {+ ...page.plan,+ planCheckRunStatusCount: { ERROR: 1 },+ specs: [{ config: { case: "changeDatabaseConfig", value: {} } }],+ },+ project: { ...page.project, enforceSqlReview: true },+ } as unknown as PlanDetailPageState;+ render(<PlanDetailHeader />);++ fireEvent.click(+ screen.getByRole("button", { name: "plan.ready-for-review" })+ );++ expect(+ screen.queryByRole("button", { name: "plan.submit-review-anyway" })+ ).not.toBeInTheDocument();+ expect(screen.getByRole("alert")).toHaveTextContent(+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"+ );+ expect(mocks.updateIssue).not.toHaveBeenCalled();+ });+test("ignores a title update response from the previous plan", async () => {const pending = deferred<Record<string, unknown>>();mocks.updatePlan.mockReturnValueOnce(pending.promise);@@ -701,7 +692,7 @@ describe("PlanDetailHeader draft ownership", () => {expect(screen.getByRole("button", { name: "common.create" })).toBeEnabled();});- test("keeps invalid draft creation blocked without a confirmation panel", () => {+ test("lists every blocker instead of disabling Create", () => {mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);mocks.lifecycle = { kind: "create" };const page = makePage({ creating: true });@@ -712,10 +703,67 @@ describe("PlanDetailHeader draft ownership", () => {render(<PlanDetailHeader />);- expect(screen.getByRole("button", { name: "common.create" })).toBeDisabled();- expect(screen.getByRole("button", { name: "common.create" })).toHaveAttribute(- "title",- "plan.title-required"+ const create = screen.getByRole("button", { name: "common.create" });+ expect(create).toBeEnabled();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();++ fireEvent.click(create);++ expect(mocks.createPlan).not.toHaveBeenCalled();+ const notice = screen.getByRole("alert");+ expect(notice).toHaveTextContent("plan.cannot-create");+ expect(notice).toHaveTextContent("plan.title-required");+ });++ test("puts the cursor in the empty title when that is the blocker", () => {+ mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);+ mocks.lifecycle = { kind: "create" };+ const page = makePage({ creating: true });+ mocks.page = { ...page, plan: { ...page.plan, title: "" } };++ render(<PlanDetailHeader />);+ // Create mode focuses the title on mount; move focus away so the assertion+ // is about the blocked press and not about that.+ const createButton = screen.getByRole("button", { name: "common.create" });+ createButton.focus();+ expect(document.activeElement).toBe(createButton);++ fireEvent.click(createButton);++ expect(document.activeElement).toBe(+ screen.getByPlaceholderText("common.untitled")+ );+ });++ test("clears the create notice as the blocker resolves", () => {+ mocks.permissions = new Set(["bb.plans.create", "bb.issues.create"]);+ mocks.lifecycle = { kind: "create" };+ const page = makePage({ creating: true });+ mocks.page = { ...page, plan: { ...page.plan, title: "" } };+ const { rerender } = render(<PlanDetailHeader />);+ fireEvent.click(screen.getByRole("button", { name: "common.create" }));+ expect(screen.getByRole("alert")).toBeInTheDocument();++ mocks.page = { ...mocks.page, plan: { ...mocks.page.plan, title: "Named" } };+ rerender(<PlanDetailHeader />);++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("lists a missing create permission instead of disabling Create", () => {+ mocks.permissions = new Set(["bb.plans.create"]);+ mocks.lifecycle = { kind: "create" };+ mocks.page = makePage({ creating: true });++ render(<PlanDetailHeader />);++ const create = screen.getByRole("button", { name: "common.create" });+ expect(create).toBeEnabled();+ fireEvent.click(create);++ expect(mocks.createPlan).not.toHaveBeenCalled();+ expect(screen.getByRole("alert")).toHaveTextContent(+ "common.missing-required-permission");});diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsxindex 409bc10515..3d5940145a 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx@@ -1,35 +1,20 @@import { clone, create } from "@bufbuild/protobuf";-import { EllipsisVertical, Loader2 } from "lucide-react";+import { EllipsisVertical } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { issueServiceClientConnect, planServiceClientConnect } from "@/api";import { router } from "@/app/router";import { PROJECT_V1_ROUTE_PLAN_DETAIL } from "@/app/router/handles";-import {- type IssueLabel,- IssueLabelSelect,-} from "@/components/IssueLabelSelect";-import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";-import { Checkbox } from "@/components/ui/checkbox";import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/components/ui/popover";import {createPlanWithDraftReview,DraftReviewIssueCreationError,- getCreateIssueBlockingErrors,- getCreateIssueConfirmErrors,- getCreatePlanBlockingReasons,- hasChecksWarning,submitDraftReview,} from "@/lib/plan/workflow";import { cn } from "@/lib/utils";@@ -56,6 +41,16 @@ import { usePlanDetailSpecValidation } from "../hooks/usePlanDetailSpecValidatioimport { focusPlanPhase } from "../shell/focusPhase";import { usePlanDetailContext } from "../shell/PlanDetailContext";import { getLocalSheetByName, removeLocalSheet } from "../utils/localSheet";+import {+ getCreatePlanBlockers,+ getSubmitReviewAdvance,+ NO_ADVANCE,+ NO_BLOCKERS,+} from "./lifecycle/advanceState";+import {+ LifecycleAdvanceButton,+ type LifecycleAdvanceProps,+} from "./lifecycle/LifecycleAdvance";import { PlanLifecycleSlot } from "./lifecycle/PlanLifecycleSlot";import { PlanLifecycleStamp } from "./lifecycle/PlanLifecycleStamp";import { slotHasPrimaryControl } from "./lifecycle/planLifecycleHeaderState";@@ -75,41 +70,20 @@ export function PlanDetailHeader() {const [title, setTitle] = useState(persistedTitle);const [editingTitle, setEditingTitle] = useState(false);const [updating, setUpdating] = useState(false);- const [showReviewPopover, setShowReviewPopover] = useState(false);- const [selectedLabels, setSelectedLabels] = useState<string[]>([]);- const [checksWarningAcknowledged, setChecksWarningAcknowledged] =- useState(false);const [submittingReview, setSubmittingReview] = useState(false);const { emptySpecIdSet } = usePlanDetailSpecValidation(page.plan.specs ?? []);const titleInputRef = useRef<HTMLInputElement>(null);const titleAutoFocusedRef = useRef(false);const pageKeyRef = useRef(page.pageKey);pageKeyRef.current = page.pageKey;- const createPlanBlockingReasons = useMemo(- () =>- getCreatePlanBlockingReasons({- title: page.plan.title,- emptySpecCount: emptySpecIdSet.size,- t,- }),- [emptySpecIdSet.size, page.plan.title, t]- );- const canCreatePlan = hasProjectPermissionV2(project, "bb.plans.create");- const canCreateIssue = hasProjectPermissionV2(project, "bb.issues.create");- const canCreateDraftReview = canCreatePlan && canCreateIssue;- const createPermissionReason = canCreateDraftReview- ? undefined- : t("common.missing-required-permission", {- permissions: ["bb.plans.create", "bb.issues.create"]- .filter(- (permission) =>- !hasProjectPermissionV2(- project,- permission as "bb.plans.create" | "bb.issues.create"- )- )- .join(", "),- });+ const missingCreatePermissions = (+ ["bb.plans.create", "bb.issues.create"] as const+ ).filter((permission) => !hasProjectPermissionV2(project, permission));+ const createPermissionReason = missingCreatePermissions.length+ ? t("common.missing-required-permission", {+ permissions: missingCreatePermissions.join(", "),+ })+ : undefined;const canUpdatePlan =page.plan.creator === currentUser.name ||@@ -119,9 +93,6 @@ export function PlanDetailHeader() {setTitle(persistedTitle);setEditingTitle(false);setUpdating(false);- setShowReviewPopover(false);- setSelectedLabels(draftIssue ? (page.issue?.labels ?? []) : []);- setChecksWarningAcknowledged(false);setSubmittingReview(false);titleAutoFocusedRef.current = false;setEditing("title", false);@@ -133,12 +104,6 @@ export function PlanDetailHeader() {}}, [editingTitle, persistedTitle]);- useEffect(() => {- if (draftIssue && !showReviewPopover) {- setSelectedLabels(page.issue?.labels ?? []);- }- }, [draftIssue, page.issue?.labels, showReviewPopover]);-const allowTitleEdit = useMemo(() => {if (page.readonly) return false;if (page.isCreating) return true;@@ -202,13 +167,6 @@ export function PlanDetailHeader() {page.issue.status === IssueStatus.CANCELED &&canUpdateIssue;- const submitDisabled = page.isEditing || !canUpdateIssue;- const submitDisabledReason = page.isEditing- ? t("plan.editor.save-changes-before-continuing")- : !canUpdateIssue- ? t("plan.draft-update-permission-required")- : undefined;-const saveTitle = async () => {if (page.isCreating) {patchState({@@ -427,6 +385,64 @@ export function PlanDetailHeader() {? secondaryActions.slice(1): secondaryActions;+ // Everything standing between the reader and the next lifecycle state, as+ // data. A missing permission is one more entry rather than a separate header+ // state, so the action never disappears or goes dead.+ // Only the state that renders the advance resolves it: in create mode every+ // title keystroke hands out a fresh `page.plan`, and the submit resolver walks+ // the specs for a result create mode never reads.+ const isCreating = lifecycle.kind === "create";+ const isSubmitting = lifecycle.kind === "ready-for-review";+ // Labels come from the metadata row, which persists them on change — the+ // submit path only counts them, so key the memo on the count, not the array.+ const selectedLabelCount = page.issue?.labels?.length ?? 0;++ const createBlockers = useMemo(+ () =>+ isCreating+ ? getCreatePlanBlockers({+ emptySpecCount: emptySpecIdSet.size,+ permissionReason: createPermissionReason,+ title: page.plan.title,+ t,+ })+ : NO_BLOCKERS,+ [+ createPermissionReason,+ emptySpecIdSet.size,+ isCreating,+ page.plan.title,+ t,+ ]+ );++ const submitAdvance = useMemo(+ () =>+ isSubmitting+ ? getSubmitReviewAdvance({+ emptySpecCount: emptySpecIdSet.size,+ isEditing: page.isEditing,+ permissionReason: canUpdateIssue+ ? undefined+ : t("plan.draft-update-permission-required"),+ plan: page.plan,+ project,+ selectedLabelCount,+ t,+ })+ : NO_ADVANCE,+ [+ canUpdateIssue,+ emptySpecIdSet.size,+ isSubmitting,+ page.isEditing,+ page.plan,+ project,+ selectedLabelCount,+ t,+ ]+ );+const createSheets = async (actionPageKey: string) => {for (const spec of page.plan.specs) {let config = null;@@ -450,7 +466,7 @@ export function PlanDetailHeader() {};const handleCreatePlan = async () => {- if (createPlanBlockingReasons.length > 0 || !canCreateDraftReview) {+ if (createBlockers.length > 0) {return;}const actionPageKey = page.pageKey;@@ -502,51 +518,8 @@ export function PlanDetailHeader() {}};- const createIssueBlockingErrors = useMemo(- () =>- getCreateIssueBlockingErrors({- emptySpecCount: emptySpecIdSet.size,- plan: page.plan,- project,- t,- }),- [emptySpecIdSet.size, page.plan, project, t]- );- const createDisabledReason =- createPermissionReason ?? createPlanBlockingReasons[0];- const showChecksWarning = useMemo(- () => hasChecksWarning(page.plan),- [page.plan]- );- const createIssueConfirmErrors = useMemo(- () =>- getCreateIssueConfirmErrors({- blockingErrors: createIssueBlockingErrors,- project,- selectedLabelCount: selectedLabels.length,- t,- }),- [createIssueBlockingErrors, project, selectedLabels.length, t]- );-- const resetReviewPopoverDraft = () => {- setSelectedLabels(page.issue?.labels ?? []);- setChecksWarningAcknowledged(false);- };-- const handleReviewPopoverOpenChange = (open: boolean) => {- setShowReviewPopover(open);- if (!open) {- resetReviewPopoverDraft();- }- };-const handleSubmitDraftReview = async () => {- if (- !page.issue?.draft ||- !canUpdateIssue ||- createIssueConfirmErrors.length > 0- ) {+ if (!page.issue?.draft || submitAdvance.blockers.length > 0) {return;}const actionPageKey = page.pageKey;@@ -554,12 +527,10 @@ export function PlanDetailHeader() {setSubmittingReview(true);const submittedIssue = await submitDraftReview({issue: page.issue,- labels: selectedLabels,updateIssue: (request) =>issueServiceClientConnect.updateIssue(request),});if (pageKeyRef.current !== actionPageKey) return;- handleReviewPopoverOpenChange(false);patchState({ issue: submittedIssue });await page.refreshState();if (pageKeyRef.current !== actionPageKey) return;@@ -579,6 +550,32 @@ export function PlanDetailHeader() {}};+ let advance: LifecycleAdvanceProps | undefined;+ if (isCreating) {+ advance = {+ blockers: createBlockers,+ busy: updating,+ heading: t("plan.cannot-create"),+ onAdvance: () => void handleCreatePlan(),+ // The empty title is the one blocker whose field is already in this row.+ onBlocked: (blockers) => {+ if (blockers.some((blocker) => blocker.id === "title")) {+ titleInputRef.current?.focus();+ }+ },+ verb: t("common.create"),+ };+ } else if (isSubmitting) {+ advance = {+ blockers: submitAdvance.blockers,+ busy: submittingReview,+ decision: submitAdvance.decision,+ heading: t("plan.not-ready-for-review"),+ onAdvance: () => void handleSubmitDraftReview(),+ verb: t("plan.ready-for-review"),+ };+ }+return (<div className="px-2 py-2 sm:px-4"><div className="flex flex-row items-center justify-between gap-2">@@ -625,55 +622,10 @@ export function PlanDetailHeader() {{/* Lifecycle slot: one primary advance/status per state. Create andready-for-review stay here (coupled to the title/create flow); allother states render through PlanLifecycleSlot. */}- {lifecycle.kind === "create" ? (- <Button- disabled={- updating ||- !canCreateDraftReview ||- createPlanBlockingReasons.length > 0- }- onClick={() => void handleCreatePlan()}- title={createDisabledReason}- >- {updating && <Loader2 className="mr-2 size-4 animate-spin" />}- {t("common.create")}- </Button>- ) : lifecycle.kind === "ready-for-review" ? (- <Popover- open={showReviewPopover}- onOpenChange={handleReviewPopoverOpenChange}- >- <PopoverTrigger- render={- <Button- disabled={submitDisabled}- title={submitDisabledReason}- />- }- >- {t("plan.ready-for-review")}- </PopoverTrigger>- <PopoverContent- align="end"- className="w-[min(28rem,calc(100vw-2rem))] px-4 py-4"- >- <ReadyForReviewPopoverContent- checksWarningAcknowledged={checksWarningAcknowledged}- confirmErrors={createIssueConfirmErrors}- forceIssueLabels={project.forceIssueLabels}- issueLabels={project.issueLabels ?? []}- onCancel={() => handleReviewPopoverOpenChange(false)}- onChecksWarningAcknowledgedChange={- setChecksWarningAcknowledged- }- onConfirm={() => void handleSubmitDraftReview()}- onSelectedLabelsChange={setSelectedLabels}- selectedLabels={selectedLabels}- showChecksWarning={showChecksWarning}- submitting={submittingReview}- />- </PopoverContent>- </Popover>+ {advance ? (+ // Keyed on the plan so a surface opened for one plan cannot greet+ // the reader on the next.+ <LifecycleAdvanceButton key={page.pageKey} {...advance} />) : (<PlanLifecycleSlot state={lifecycle} />)}@@ -713,87 +665,3 @@ export function PlanDetailHeader() {</div>);}--function ReadyForReviewPopoverContent({- checksWarningAcknowledged,- confirmErrors,- forceIssueLabels,- issueLabels,- onCancel,- onChecksWarningAcknowledgedChange,- onConfirm,- onSelectedLabelsChange,- selectedLabels,- showChecksWarning,- submitting,-}: {- checksWarningAcknowledged: boolean;- confirmErrors: string[];- forceIssueLabels: boolean;- issueLabels: IssueLabel[];- onCancel: () => void;- onChecksWarningAcknowledgedChange?: (checked: boolean) => void;- onConfirm: () => void;- onSelectedLabelsChange: (labels: string[]) => void;- selectedLabels: string[];- showChecksWarning: boolean;- submitting: boolean;-}) {- const { t } = useTranslation();-- return (- <div className="flex flex-col gap-y-4">- {showChecksWarning && (- <Alert variant="warning" description={t("issue.checks-warning-hint")} />- )}- <IssueLabelSelect- labels={issueLabels}- onChange={onSelectedLabelsChange}- required={forceIssueLabels}- selected={selectedLabels}- />- {showChecksWarning && (- <label className="flex items-center gap-x-2 text-sm text-control">- <Checkbox- checked={checksWarningAcknowledged}- onCheckedChange={(checked) =>- onChecksWarningAcknowledgedChange?.(checked)- }- />- <span>- {t("issue.action-anyway", {- action: t("common.confirm"),- })}- </span>- </label>- )}- {confirmErrors.length > 0 && (- <Alert- variant="error"- description={- <span className="whitespace-pre-line">- {confirmErrors.join("\n")}- </span>- }- />- )}- <div className="flex justify-start gap-x-2 pt-1">- <Button- disabled={- confirmErrors.length > 0 ||- (showChecksWarning && !checksWarningAcknowledged) ||- submitting- }- onClick={onConfirm}- size="sm"- >- {submitting && <Loader2 className="size-4 animate-spin" />}- {t("common.confirm")}- </Button>- <Button onClick={onCancel} size="sm" appearance="secondary">- {t("common.cancel")}- </Button>- </div>- </div>- );-}diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsxindex 5ead66e31a..11a40048af 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx@@ -185,6 +185,63 @@ test("does not warn about missing Issue labels during creation", () => {expect(screen.queryByRole("alert")).not.toBeInTheDocument();});+const labelsTrigger = () =>+ screen.getByRole("button", { name: /issue\.labels/ });++const creating = (overrides: Record<string, unknown> = {}) => {+ const page = makePage();+ return {+ ...page,+ isCreating: true,+ issue: undefined,+ project: { ...page.project, forceIssueLabels: true },+ ...overrides,+ } as unknown as PlanDetailPageState;+};++test("marks the labels control required while the project forces one and none is set", () => {+ mocks.page = creating();++ render(<PlanDetailMeta />);++ expect(labelsTrigger()).toHaveTextContent("*");+});++test("drops the required marker once a label satisfies it", () => {+ mocks.creationIssueLabels = ["alpha"];+ mocks.page = creating();++ render(<PlanDetailMeta />);++ expect(labelsTrigger()).not.toHaveTextContent("*");+});++test("does not mark the control required when the project does not force labels", () => {+ const page = makePage();+ mocks.page = {+ ...page,+ isCreating: true,+ issue: undefined,+ } as unknown as PlanDetailPageState;++ render(<PlanDetailMeta />);++ expect(labelsTrigger()).not.toHaveTextContent("*");+});++test("does not mark labels required after the draft is submitted", () => {+ const page = makePage();+ mocks.page = {+ ...page,+ issue: { ...page.issue!, draft: false, labels: [] },+ project: { ...page.project, forceIssueLabels: true },+ };++ render(<PlanDetailMeta />);++ expect(labelsTrigger()).not.toHaveTextContent("*");+});+test("keeps draft labels read-only without issues.update and editable with it", async () => {const { rerender } = render(<PlanDetailMeta />);diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsxindex f14a7068a7..5a89f452e2 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx@@ -61,6 +61,7 @@ export function PlanDetailMeta() {issueLabels={project?.issueLabels ?? []}labels={page.creationIssueLabels}onUpdate={page.setCreationIssueLabels}+ required={project?.forceIssueLabels ?? false}/></div>);@@ -111,6 +112,7 @@ export function PlanDetailMeta() {issueLabels={project?.issueLabels ?? []}labels={page.issue.labels || []}onUpdate={handleLabelsUpdate}+ required={page.issue.draft && (project?.forceIssueLabels ?? false)}/></>)}@@ -123,11 +125,14 @@ function InlineLabels({issueLabels,labels,onUpdate,+ required,}: {allowChange: boolean;issueLabels: Array<{ color?: Color; value: string }>;labels: string[];onUpdate: (labels: string[]) => Promise<void> | void;+ /** The project forces issue labels, so submitting for review needs one. */+ required: boolean;}) {const { t } = useTranslation();const [open, setOpen] = useState(false);@@ -204,6 +209,11 @@ function InlineLabels({><Plus className="size-3" /><span>{t("issue.labels")}</span>+ {/* Only while unsatisfied: once a label is picked the trigger is an+ "add another" affordance, and the requirement is already met. */}+ {required && labels.length === 0 && (+ <span className="text-error">*</span>+ )}</PopoverTrigger><PopoverContentside="bottom"diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.test.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.test.tsxnew file mode 100644index 0000000000..ceff628010--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.test.tsx@@ -0,0 +1,327 @@+import { fireEvent, render, screen } from "@testing-library/react";+import type { ButtonHTMLAttributes, ReactNode } from "react";+import { describe, expect, test, vi } from "vitest";+import type { AdvanceBlocker } from "./advanceState";+import {+ LifecycleAdvanceButton,+ type LifecycleAdvanceProps,+} from "./LifecycleAdvance";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/components/ui/button", () => ({+ Button: ({+ appearance: _appearance,+ children,+ size: _size,+ ...props+ }: ButtonHTMLAttributes<HTMLButtonElement> & {+ appearance?: string;+ size?: string;+ }) => <button {...props}>{children}</button>,+}));++vi.mock("@/components/ui/popover", () => ({+ Popover: ({+ children,+ onOpenChange,+ open,+ }: {+ children: ReactNode;+ onOpenChange?: (open: boolean) => void;+ open?: boolean;+ }) =>+ open ? (+ <div data-testid="popover">+ <button onClick={() => onOpenChange?.(false)} type="button">+ outside-press+ </button>+ {children}+ </div>+ ) : null,+ PopoverContent: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++const fix = (id: string, message = id): AdvanceBlocker => ({+ id,+ kind: "fix",+ message,+});++const DECISION = {+ body: "issue.checks-warning-hint",+ headline: "plan.lifecycle.gate-checks-failed",+ verb: "plan.submit-review-anyway",+};++function Harness(props: Partial<LifecycleAdvanceProps> = {}) {+ return (+ <LifecycleAdvanceButton+ blockers={[]}+ heading="plan.cannot-create"+ onAdvance={vi.fn()}+ verb="Create"+ {...props}+ />+ );+}++const pressPrimary = () =>+ fireEvent.click(screen.getByRole("button", { name: "Create" }));++describe("LifecycleAdvance tier 0", () => {+ test("advances on press and opens nothing", () => {+ const onAdvance = vi.fn();+ render(<Harness onAdvance={onAdvance} />);++ pressPrimary();++ expect(onAdvance).toHaveBeenCalledOnce();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();+ });++});++describe("LifecycleAdvance tier 1", () => {+ test("shows nothing before the first press", () => {+ render(<Harness blockers={[fix("title")]} />);++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("keeps the action enabled and states every blocker on press", () => {+ const onAdvance = vi.fn();+ render(+ <Harness+ blockers={[fix("title", "plan.title-required"), fix("statement")]}+ onAdvance={onAdvance}+ />+ );++ expect(screen.getByRole("button", { name: "Create" })).toBeEnabled();+ pressPrimary();++ expect(onAdvance).not.toHaveBeenCalled();+ const notice = screen.getByRole("alert");+ expect(notice).toHaveTextContent("plan.cannot-create");+ expect(notice).toHaveTextContent("plan.title-required");+ expect(notice).toHaveTextContent("statement");+ });++ test("runs the blocked-press nudge", () => {+ const onBlocked = vi.fn();+ render(<Harness blockers={[fix("title")]} onBlocked={onBlocked} />);++ pressPrimary();++ expect(onBlocked).toHaveBeenCalledOnce();+ });++ test("stays closed after the last blocker resolves", () => {+ const { rerender } = render(<Harness blockers={[fix("title")]} />);+ pressPrimary();+ expect(screen.getByRole("alert")).toBeInTheDocument();++ rerender(<Harness blockers={[]} />);++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();++ rerender(<Harness blockers={[fix("title")]} />);++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("shortens as blockers resolve one at a time", () => {+ const { rerender } = render(+ <Harness blockers={[fix("title"), fix("statement")]} />+ );+ pressPrimary();++ rerender(<Harness blockers={[fix("statement")]} />);++ const notice = screen.getByRole("alert");+ expect(notice).toHaveTextContent("statement");+ expect(notice).not.toHaveTextContent("title");+ });++ test("marks a self-resolving blocker so it does not read as a chore", () => {+ render(+ <Harness+ blockers={[+ { id: "checks-running", kind: "wait", message: "checks are running" },+ ]}+ />+ );+ pressPrimary();++ expect(screen.getByRole("alert")).toHaveTextContent(+ "plan.blocker.clears-on-its-own"+ );+ });++ test("does not mark a blocker the reader has to resolve", () => {+ render(<Harness blockers={[fix("title")]} />);+ pressPrimary();++ expect(screen.getByRole("alert")).not.toHaveTextContent(+ "plan.blocker.clears-on-its-own"+ );+ });++ test("outranks a decision", () => {+ const onAdvance = vi.fn();+ render(+ <Harness+ blockers={[fix("statement")]}+ decision={DECISION}+ onAdvance={onAdvance}+ />+ );++ pressPrimary();++ expect(screen.getByRole("alert")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "plan.submit-review-anyway" })+ ).not.toBeInTheDocument();+ expect(onAdvance).not.toHaveBeenCalled();+ });++ test("closes on outside press", () => {+ render(<Harness blockers={[fix("title")]} />);+ pressPrimary();+ expect(screen.getByRole("alert")).toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "outside-press" }));++ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++});++describe("LifecycleAdvance tier 2", () => {+ test("asks before advancing", () => {+ const onAdvance = vi.fn();+ render(<Harness decision={DECISION} onAdvance={onAdvance} />);++ pressPrimary();++ expect(onAdvance).not.toHaveBeenCalled();+ expect(screen.getByTestId("popover")).toHaveTextContent(+ "plan.lifecycle.gate-checks-failed"+ );+ expect(screen.getByTestId("popover")).toHaveTextContent(+ "issue.checks-warning-hint"+ );+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });++ test("names the override after what it does", () => {+ render(<Harness decision={DECISION} />);+ pressPrimary();++ expect(+ screen.getByRole("button", { name: "plan.submit-review-anyway" })+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "common.confirm" })+ ).not.toBeInTheDocument();+ });++ test("advances once when confirmed and closes the confirmation", () => {+ const onAdvance = vi.fn();+ render(<Harness decision={DECISION} onAdvance={onAdvance} />);+ pressPrimary();++ fireEvent.click(+ screen.getByRole("button", { name: "plan.submit-review-anyway" })+ );++ expect(onAdvance).toHaveBeenCalledOnce();+ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();+ });++ test("does not advance when cancelled", () => {+ const onAdvance = vi.fn();+ render(<Harness decision={DECISION} onAdvance={onAdvance} />);+ pressPrimary();++ fireEvent.click(screen.getByRole("button", { name: "common.cancel" }));++ expect(onAdvance).not.toHaveBeenCalled();+ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();+ });++ test("asks no acknowledgement checkbox and offers no metadata fields", () => {+ render(<Harness decision={DECISION} />);+ pressPrimary();++ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ });++ test("switches an open decision to blockers when checks restart", () => {+ const { rerender } = render(<Harness decision={DECISION} />);+ pressPrimary();++ rerender(+ <Harness+ blockers={[+ { id: "checks-running", kind: "wait", message: "checks are running" },+ ]}+ />+ );++ expect(screen.getByRole("alert")).toHaveTextContent("checks are running");+ expect(+ screen.queryByRole("button", { name: "plan.submit-review-anyway" })+ ).not.toBeInTheDocument();+ });++ test("lets new blockers outrank a still-valid open decision", () => {+ const { rerender } = render(<Harness decision={DECISION} />);+ pressPrimary();++ rerender(+ <Harness blockers={[fix("statement")]} decision={DECISION} />+ );++ expect(screen.getByRole("alert")).toHaveTextContent("statement");+ expect(+ screen.queryByRole("button", { name: "plan.submit-review-anyway" })+ ).not.toBeInTheDocument();++ rerender(<Harness decision={DECISION} />);++ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();+ });++ test("closes an open decision when it is no longer required", () => {+ const { rerender } = render(<Harness decision={DECISION} />);+ pressPrimary();++ rerender(<Harness />);++ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();++ rerender(<Harness decision={DECISION} />);++ expect(screen.queryByTestId("popover")).not.toBeInTheDocument();+ });+});++describe("LifecycleAdvance in flight", () => {+ test("disables the action while a request is running", () => {+ const onAdvance = vi.fn();+ render(<Harness busy onAdvance={onAdvance} />);++ const button = screen.getByRole("button", { name: "Create" });+ expect(button).toBeDisabled();+ fireEvent.click(button);+ expect(onAdvance).not.toHaveBeenCalled();+ });++});diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.tsx b/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.tsxnew file mode 100644index 0000000000..853b1e5986--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/LifecycleAdvance.tsx@@ -0,0 +1,182 @@+// The header's primary lifecycle advance, shared by the two draft states+// (create, ready-for-review).+//+// One rule, three tiers, derived from data rather than hard-coded per state:+//+// 0 nothing unresolved -> the press advances, and opens nothing+// 1 unmet conditions -> the press states all of them in a list+// 2 a deliberate override -> the press opens that one decision+//+// The button is always rendered and always enabled (except in flight), so an+// unmet condition is never a dead control with the explanation locked behind a+// hover. Both surfaces are popovers anchored to the button, so the explanation+// stays attached to the control it belongs to instead of spanning the header.+// The blocker list is information: no fields, no confirm, no links away — and it+// closes itself as the last condition clears.+//+// Callers reset it by navigation: key the element on the plan so a surface+// opened for one plan cannot greet the reader on the next.+import { CircleX, Clock3, Loader2 } from "lucide-react";+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent } from "@/components/ui/popover";+import type { AdvanceBlocker, AdvanceDecision } from "./advanceState";++export interface LifecycleAdvanceProps {+ blockers: AdvanceBlocker[];+ busy?: boolean;+ decision?: AdvanceDecision;+ /** Names the blocked state, e.g. "Cannot create plan". */+ heading: string;+ onAdvance: () => void;+ /** Optional nudge toward an unmet condition, e.g. focus the empty title. */+ onBlocked?: (blockers: AdvanceBlocker[]) => void;+ verb: string;+}++export function LifecycleAdvanceButton({+ blockers,+ busy = false,+ decision,+ heading,+ onAdvance,+ onBlocked,+ verb,+}: LifecycleAdvanceProps) {+ const { t } = useTranslation();+ // The two surfaces are mutually exclusive by construction, so one value+ // rather than two booleans that must never both be true.+ const [surface, setSurface] = useState<"none" | "blockers" | "decision">(+ "none"+ );+ const buttonRef = useRef<HTMLButtonElement>(null);++ // Derived visibility prevents prop changes from briefly rendering a stale+ // tier before the stored surface is reconciled below.+ const showBlockers = surface !== "none" && blockers.length > 0;+ const showDecision =+ surface === "decision" && blockers.length === 0 && decision !== undefined;+ const dismiss = () => setSurface("none");++ // Clear or switch an invalid tier so it cannot reopen without another press.+ useEffect(() => {+ setSurface((current) => {+ if (current === "blockers" && blockers.length === 0) {+ return "none";+ }+ if (current !== "decision") {+ return current;+ }+ if (blockers.length > 0) {+ return "blockers";+ }+ if (!decision) {+ return "none";+ }+ return current;+ });+ }, [blockers.length, decision]);++ const press = () => {+ if (blockers.length > 0) {+ setSurface("blockers");+ onBlocked?.(blockers);+ return;+ }+ if (decision) {+ setSurface("decision");+ return;+ }+ onAdvance();+ };++ return (+ <>+ <Button disabled={busy} onClick={press} ref={buttonRef} type="button">+ {busy && <Loader2 className="mr-2 size-4 animate-spin" />}+ {verb}+ </Button>+ {/* Controlled and anchored rather than trigger-driven: a press opens this+ only at tier 1 or 2, so it must not toggle on every press. */}+ <Popover+ onOpenChange={(open) => {+ if (!open) dismiss();+ }}+ open={showBlockers || showDecision}+ >+ <PopoverContent+ align="end"+ anchor={buttonRef}+ // Sized by its content, not fixed: a one-line blocker on a phone+ // otherwise renders a near-full-bleed panel that reads as detached+ // from the button. The floor keeps it from resizing visibly as+ // blockers resolve; the cap keeps it inside the viewport.+ className="min-w-64 max-w-[min(22rem,calc(100vw-2rem))] p-0"+ initialFocus={false}+ >+ {showBlockers ? (+ <div className="divide-y" role="alert">+ <p className="px-4 py-2.5 text-sm font-medium text-error">+ {heading}+ </p>+ {blockers.map((blocker) => (+ <div+ className="flex items-start gap-x-2 px-4 py-2.5 text-sm text-control"+ key={blocker.id}+ >+ {blocker.kind === "wait" ? (+ <Clock3 className="mt-0.5 size-4 shrink-0 text-warning" />+ ) : (+ <CircleX className="mt-0.5 size-4 shrink-0 text-error" />+ )}+ <span className="min-w-0 flex-1">{blocker.message}</span>+ {blocker.kind === "wait" && (+ <span className="shrink-0 text-xs text-control-light">+ {t("plan.blocker.clears-on-its-own")}+ </span>+ )}+ </div>+ ))}+ </div>+ ) : (+ decision && (+ <div className="divide-y">+ {/* Warning-toned: the action can still proceed, so this must not+ read as the error state the blocker list uses. */}+ <p className="px-4 py-2.5 text-sm font-medium text-warning">+ {decision.headline}+ </p>+ <p className="px-4 py-2.5 text-sm text-control">+ {decision.body}+ </p>+ <div className="flex gap-x-2 rounded-b-sm bg-control-bg/50 px-4 py-2.5">+ <Button+ disabled={busy}+ onClick={() => {+ dismiss();+ onAdvance();+ }}+ size="sm"+ type="button"+ >+ {busy && <Loader2 className="size-4 animate-spin" />}+ {decision.verb}+ </Button>+ <Button+ appearance="outline"+ onClick={dismiss}+ size="sm"+ type="button"+ >+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ )+ )}+ </PopoverContent>+ </Popover>+ </>+ );+}diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.test.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.test.tsnew file mode 100644index 0000000000..1945c9b9ca--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.test.ts@@ -0,0 +1,308 @@+import { describe, expect, test } from "vitest";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";+import { getCreatePlanBlockers, getSubmitReviewAdvance } from "./advanceState";++const t = (key: string) => key;++const makePlan = (cases: string[], statusCount = {}): Plan =>+ ({+ planCheckRunStatusCount: statusCount,+ specs: cases.map((caseName) => ({+ config: { case: caseName, value: {} },+ })),+ }) as unknown as Plan;++const project = (+ overrides: Partial<+ Pick<Project, "enforceSqlReview" | "forceIssueLabels">+ > = {}+) =>+ ({+ enforceSqlReview: false,+ forceIssueLabels: false,+ ...overrides,+ }) as Project;++const submitArgs = (+ overrides: Partial<Parameters<typeof getSubmitReviewAdvance>[0]> = {}+) => ({+ emptySpecCount: 0,+ isEditing: false,+ plan: makePlan(["changeDatabaseConfig"]),+ project: project(),+ selectedLabelCount: 1,+ t,+ ...overrides,+});++const ids = (blockers: { id: string }[]) => blockers.map((b) => b.id);++describe("getCreatePlanBlockers", () => {+ test("flags an empty title", () => {+ expect(getCreatePlanBlockers({ emptySpecCount: 0, title: "", t })).toEqual([+ { id: "title", kind: "fix", message: "plan.title-required" },+ ]);+ });++ test("flags a whitespace-only title", () => {+ expect(+ ids(getCreatePlanBlockers({ emptySpecCount: 0, title: " ", t }))+ ).toEqual(["title"]);+ });++ test("flags empty statements", () => {+ expect(+ getCreatePlanBlockers({ emptySpecCount: 2, title: "Add column", t })+ ).toEqual([+ {+ id: "statement",+ kind: "fix",+ message: "plan.navigator.statement-empty",+ },+ ]);+ });++ test("lists every blocker, title first", () => {+ expect(+ ids(+ getCreatePlanBlockers({+ emptySpecCount: 1,+ permissionReason: "common.missing-required-permission",+ title: "",+ t,+ })+ )+ ).toEqual(["title", "statement", "permission"]);+ });++ test("reports a missing permission as a blocker rather than hiding the action", () => {+ expect(+ getCreatePlanBlockers({+ emptySpecCount: 0,+ permissionReason: "common.missing-required-permission",+ title: "Add column",+ t,+ })+ ).toEqual([+ {+ id: "permission",+ kind: "fix",+ message: "common.missing-required-permission",+ },+ ]);+ });++ test("returns no blockers when valid", () => {+ expect(+ getCreatePlanBlockers({ emptySpecCount: 0, title: "Add column", t })+ ).toEqual([]);+ });+});++describe("getSubmitReviewAdvance", () => {+ test("returns no blockers for a clean draft", () => {+ expect(getSubmitReviewAdvance(submitArgs()).blockers).toEqual([]);+ });++ test("flags empty statements", () => {+ expect(+ ids(getSubmitReviewAdvance(submitArgs({ emptySpecCount: 1 })).blockers)+ ).toEqual(["statement"]);+ });++ test("blocks data export submission", () => {+ expect(+ getSubmitReviewAdvance(+ submitArgs({ plan: makePlan(["exportDataConfig"]) })+ ).blockers+ ).toContainEqual(+ expect.objectContaining({+ id: "data-export",+ message: "issue.data-export.creation-not-supported",+ })+ );+ });++ test("marks queued and running checks as a wait, not a chore", () => {+ for (const statusCount of [{ AVAILABLE: 1 }, { RUNNING: 1 }]) {+ expect(+ getSubmitReviewAdvance(+ submitArgs({ plan: makePlan(["changeDatabaseConfig"], statusCount) })+ ).blockers+ ).toEqual([+ {+ id: "checks-running",+ kind: "wait",+ message:+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running",+ },+ ]);+ }+ });++ test("blocks failed checks only where SQL review is enforced", () => {+ const plan = makePlan(["changeDatabaseConfig"], { ERROR: 1 });++ expect(ids(getSubmitReviewAdvance(submitArgs({ plan })).blockers)).toEqual(+ []+ );+ expect(+ getSubmitReviewAdvance(+ submitArgs({ plan, project: project({ enforceSqlReview: true }) })+ ).blockers+ ).toContainEqual(+ expect.objectContaining({+ id: "checks-failed",+ message:+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass",+ })+ );+ });++ test("treats a failed run the same as an errored one", () => {+ expect(+ ids(+ getSubmitReviewAdvance(+ submitArgs({+ plan: makePlan(["changeDatabaseConfig"], { FAILED: 1 }),+ project: project({ enforceSqlReview: true }),+ })+ ).blockers+ )+ ).toEqual(["checks-failed"]);+ });++ test("requires labels only where the project forces them", () => {+ expect(+ ids(+ getSubmitReviewAdvance(submitArgs({ selectedLabelCount: 0 })).blockers+ )+ ).toEqual([]);+ expect(+ getSubmitReviewAdvance(+ submitArgs({+ project: project({ forceIssueLabels: true }),+ selectedLabelCount: 0,+ })+ ).blockers+ ).toEqual([+ {+ id: "labels",+ kind: "fix",+ message: "plan.labels-required-for-review",+ },+ ]);+ });++ test("accepts an existing label when the project forces them", () => {+ expect(+ getSubmitReviewAdvance(+ submitArgs({+ project: project({ forceIssueLabels: true }),+ selectedLabelCount: 1,+ })+ ).blockers+ ).toEqual([]);+ });++ test("flags unsaved statement edits", () => {+ expect(+ getSubmitReviewAdvance(submitArgs({ isEditing: true })).blockers+ ).toEqual([+ {+ id: "editing",+ kind: "fix",+ message: "plan.editor.save-changes-before-continuing",+ },+ ]);+ });++ test("reports a missing update permission as a blocker", () => {+ expect(+ getSubmitReviewAdvance(+ submitArgs({+ permissionReason: "plan.draft-update-permission-required",+ })+ ).blockers+ ).toEqual([+ {+ id: "permission",+ kind: "fix",+ message: "plan.draft-update-permission-required",+ },+ ]);+ });++ test("lists every blocker at once", () => {+ expect(+ ids(+ getSubmitReviewAdvance(+ submitArgs({+ emptySpecCount: 1,+ isEditing: true,+ permissionReason: "plan.draft-update-permission-required",+ plan: makePlan(["exportDataConfig"], { RUNNING: 1, ERROR: 1 }),+ project: project({+ enforceSqlReview: true,+ forceIssueLabels: true,+ }),+ selectedLabelCount: 0,+ })+ ).blockers+ )+ ).toEqual([+ "statement",+ "data-export",+ "checks-running",+ "checks-failed",+ "labels",+ "editing",+ "permission",+ ]);+ });+});++describe("getSubmitReviewAdvance override", () => {+ const decisionFor = (+ overrides: Partial<Parameters<typeof getSubmitReviewAdvance>[0]>+ ) => getSubmitReviewAdvance(submitArgs(overrides)).decision;++ test("offers the override when checks failed and SQL review is not enforced", () => {+ expect(+ decisionFor({ plan: makePlan(["changeDatabaseConfig"], { ERROR: 1 }) })+ ).toEqual({+ body: "issue.checks-warning-hint",+ headline: "plan.lifecycle.gate-checks-failed",+ verb: "plan.submit-review-anyway",+ });+ });++ test("withholds the override where SQL review is enforced, and blocks instead", () => {+ const advance = getSubmitReviewAdvance(+ submitArgs({+ plan: makePlan(["changeDatabaseConfig"], { ERROR: 1 }),+ project: project({ enforceSqlReview: true }),+ })+ );++ expect(advance.decision).toBeUndefined();+ expect(ids(advance.blockers)).toEqual(["checks-failed"]);+ });++ test("offers nothing when checks pass", () => {+ expect(+ decisionFor({ plan: makePlan(["changeDatabaseConfig"], { SUCCESS: 2 }) })+ ).toBeUndefined();+ });++ test("offers nothing for a plan that is not purely a database change", () => {+ expect(+ decisionFor({+ plan: makePlan(["changeDatabaseConfig", "exportDataConfig"], {+ ERROR: 1,+ }),+ })+ ).toBeUndefined();+ });+});diff --git a/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.ts b/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.tsnew file mode 100644index 0000000000..a005539a30--- /dev/null+++ b/frontend/src/routes/project/plan-detail/components/lifecycle/advanceState.ts@@ -0,0 +1,156 @@+// Resolver for the header's primary advance (BYT-9925, BYT-9936).+//+// Pure functions that turn plan/project state into the data the advance control+// renders: everything unresolved, and — separately — the one thing the reader+// may deliberately override. Sibling to planLifecycleHeaderState.ts, which+// answers "which control does the header show"; this answers "what does that+// control say when pressed".+import { getPlanCheckSummaryWithFallback } from "@/lib/plan/check";+import type { Plan } from "@/types/proto-es/v1/plan_service_pb";+import type { Project } from "@/types/proto-es/v1/project_service_pb";++type T = (key: string, options?: Record<string, unknown>) => string;++// One unresolved condition standing between the reader and the next lifecycle+// state. `wait` clears on its own (a running check); `fix` is theirs to resolve.+// The distinction is what stops a running check from reading as a chore.+export interface AdvanceBlocker {+ id: string;+ message: string;+ kind: "fix" | "wait";+}++// A deliberate override: the action can proceed, but only once the reader says+// so. `verb` names what confirming does, so the control reads correctly out of+// context.+export interface AdvanceDecision {+ headline: string;+ body: string;+ verb: string;+}++export interface AdvanceState {+ blockers: AdvanceBlocker[];+ decision?: AdvanceDecision;+}++// Stable empty values, so a lifecycle state that renders no advance does not+// hand out a fresh array identity on every render.+export const NO_BLOCKERS: AdvanceBlocker[] = [];+export const NO_ADVANCE: AdvanceState = { blockers: NO_BLOCKERS };++const fix = (id: string, message: string): AdvanceBlocker => ({+ id,+ kind: "fix",+ message,+});++export const getCreatePlanBlockers = ({+ emptySpecCount,+ permissionReason,+ title,+ t,+}: {+ emptySpecCount: number;+ permissionReason?: string;+ title: string;+ t: T;+}): AdvanceBlocker[] => {+ const blockers: AdvanceBlocker[] = [];+ if (!title.trim()) {+ blockers.push(fix("title", t("plan.title-required")));+ }+ if (emptySpecCount > 0) {+ blockers.push(fix("statement", t("plan.navigator.statement-empty")));+ }+ if (permissionReason) {+ blockers.push(fix("permission", permissionReason));+ }+ return blockers;+};++export const getSubmitReviewAdvance = ({+ emptySpecCount,+ isEditing,+ permissionReason,+ plan,+ project,+ selectedLabelCount,+ t,+}: {+ emptySpecCount: number;+ isEditing: boolean;+ permissionReason?: string;+ plan: Plan;+ project: Pick<Project, "enforceSqlReview" | "forceIssueLabels">;+ selectedLabelCount: number;+ t: T;+}): AdvanceState => {+ const blockers: AdvanceBlocker[] = [];+ const checks = getPlanCheckSummaryWithFallback(+ [],+ plan.planCheckRunStatusCount+ );+ // AVAILABLE (queued, not yet started) is a backend plan-check status that the+ // shared summary does not count, and a queued check still has to finish.+ const queued = plan.planCheckRunStatusCount?.AVAILABLE ?? 0;++ if (emptySpecCount > 0) {+ blockers.push(fix("statement", t("plan.navigator.statement-empty")));+ }+ if (plan.specs.some((spec) => spec.config?.case === "exportDataConfig")) {+ blockers.push(+ fix("data-export", t("issue.data-export.creation-not-supported"))+ );+ }+ if (checks.running > 0 || queued > 0) {+ blockers.push({+ id: "checks-running",+ kind: "wait",+ message: t(+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-are-still-running"+ ),+ });+ }++ // Failed checks are evaluated once and land on exactly one side: a blocker+ // where the project forbids the override, otherwise the reader's to+ // authorize. Keeping both outcomes in one branch stops them drifting apart.+ // The override is offered only for plans that are purely database changes.+ const isPureDatabaseChange =+ plan.specs.length > 0 &&+ plan.specs.every((spec) => spec.config?.case === "changeDatabaseConfig");+ let decision: AdvanceDecision | undefined;+ if (checks.error > 0) {+ if (project.enforceSqlReview) {+ blockers.push(+ fix(+ "checks-failed",+ t(+ "custom-approval.issue-review.disallow-approve-reason.some-task-checks-didnt-pass"+ )+ )+ );+ } else if (isPureDatabaseChange) {+ decision = {+ body: t("issue.checks-warning-hint"),+ headline: t("plan.lifecycle.gate-checks-failed"),+ verb: t("plan.submit-review-anyway"),+ };+ }+ }++ if (project.forceIssueLabels && selectedLabelCount === 0) {+ blockers.push(fix("labels", t("plan.labels-required-for-review")));+ }+ if (isEditing) {+ blockers.push(+ fix("editing", t("plan.editor.save-changes-before-continuing"))+ );+ }+ if (permissionReason) {+ blockers.push(fix("permission", permissionReason));+ }++ return { blockers, decision };+};