Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
test(plan): verify Plan Detail lifecycle end to end (#21058)
boojack2cdaadf93b31
diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsxindex 15d11c39a5..d3a789ae85 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.test.tsx@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({creationIssueLabels: [] as string[],createIssue: vi.fn(),createPlan: vi.fn(),+ invalidateProjectPlansPagedDataCache: vi.fn(),lifecycle: { kind: "none" } as { kind: string },page: undefined as unknown as PlanDetailPageState,patchState: vi.fn(),@@ -112,6 +113,11 @@ vi.mock("@/components/ui/dropdown-menu", () => ({),}));+vi.mock("@/lib/projectPagedDataCache", () => ({+ invalidateProjectPlansPagedDataCache:+ mocks.invalidateProjectPlansPagedDataCache,+}));+vi.mock("@/lib/utils", () => ({cn: (...classes: Array<string | false | null | undefined>) =>classes.filter(Boolean).join(" "),@@ -830,6 +836,9 @@ describe("PlanDetailHeader submitted issue behavior", () => {await waitFor(() =>expect(mocks.batchUpdateIssuesStatus).toHaveBeenCalledOnce());+ expect(mocks.invalidateProjectPlansPagedDataCache).toHaveBeenCalledWith(+ "p1"+ );expect(mocks.updateIssue.mock.calls.map(([request]) => request.updateMask)).toEqual(diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsxindex 3d5940145a..79644eb661 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailHeader.tsx@@ -17,6 +17,7 @@ import {DraftReviewIssueCreationError,submitDraftReview,} from "@/lib/plan/workflow";+import { invalidateProjectPlansPagedDataCache } from "@/lib/projectPagedDataCache";import { cn } from "@/lib/utils";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";@@ -288,6 +289,10 @@ export function PlanDetailHeader() {status,}));+ // This mutation changes the Plan List's Issue-derived review badge but+ // not the Plan resource. Invalidate immediately instead of relying on a+ // subsequent detail refresh observing an Issue update-time change.+ invalidateProjectPlansPagedDataCache(page.projectId);if (pageKeyRef.current !== actionPageKey) return;// Closing / reopening records a system comment — refresh page state and the// issue comments so the review timeline reflects it (like issue detail).diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsxindex 11a40048af..f073bb0885 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.test.tsx@@ -199,17 +199,33 @@ const creating = (overrides: Record<string, unknown> = {}) => {} as unknown as PlanDetailPageState;};-test("marks the labels control required while the project forces one and none is set", () => {+test("does not mark labels required during Plan creation", () => {mocks.page = creating();render(<PlanDetailMeta />);+ expect(labelsTrigger()).not.toHaveTextContent("*");+});++test("marks labels required on a persisted draft when none is set", () => {+ const page = makePage();+ mocks.page = {+ ...page,+ issue: { ...page.issue!, labels: [] },+ project: { ...page.project, forceIssueLabels: true },+ };++ render(<PlanDetailMeta />);+expect(labelsTrigger()).toHaveTextContent("*");});-test("drops the required marker once a label satisfies it", () => {- mocks.creationIssueLabels = ["alpha"];- mocks.page = creating();+test("drops the required marker once a draft label satisfies it", () => {+ const page = makePage();+ mocks.page = {+ ...page,+ project: { ...page.project, forceIssueLabels: true },+ };render(<PlanDetailMeta />);@@ -220,9 +236,8 @@ 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;+ issue: { ...page.issue!, labels: [] },+ };render(<PlanDetailMeta />);diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsxindex 5a89f452e2..d208e4f6f9 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailMeta.tsx@@ -61,7 +61,7 @@ export function PlanDetailMeta() {issueLabels={project?.issueLabels ?? []}labels={page.creationIssueLabels}onUpdate={page.setCreationIssueLabels}- required={project?.forceIssueLabels ?? false}+ required={false}/></div>);diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.mdindex 38cfa166da..c049f0ad64 100644--- a/frontend/tests/e2e/README.md+++ b/frontend/tests/e2e/README.md@@ -108,7 +108,7 @@ frontend/tests/e2e/├── sql-editor/ — SQL Editor suite (connection, result, tabs, worksheet,│ schema, admin-mode, history, jit, permissions,│ workspace-gates, batch, misc) + sql-editor.page.ts-├── plan-detail/ — plan detail suite (checks, rollout, sections, tasks)+├── plan-detail/ — plan detail suite (lifecycle, checks, rollout, sections, tasks)│ + plan-detail.page.ts, plan-helpers.ts├── workspace/ — workspace-level suite (external-URL banner)└── masking-exemption/ — masking exemption suitediff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex 02b52b0f7f..96e90500d9 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -242,6 +242,27 @@ export class BytebaseApiClient {});}+ // Custom roles+ async createRole(+ roleId: string,+ title: string,+ permissions: string[],+ ): Promise<{ name: string }> {+ return this.request<{ name: string }>(+ "POST",+ `/v1/roles?roleId=${roleId}`,+ { title, permissions },+ );+ }++ async deleteRole(name: string): Promise<void> {+ try {+ await this.request<unknown>("DELETE", `/v1/${name}`);+ } catch {+ // Best-effort teardown for disposable E2E workspaces.+ }+ }+// Discoveryasync listInstances() {return this.request<{ instances: { name: string; engine: string; title: string }[] }>("GET", "/v1/instances?pageSize=100&showDeleted=false");@@ -536,7 +557,12 @@ export class BytebaseApiClient {});}- async getPlan(planName: string): Promise<{ name: string; hasRollout: boolean; state: string }> {+ async getPlan(planName: string): Promise<{+ name: string;+ hasRollout: boolean;+ issue: string;+ state: string;+ }> {return this.request("GET", `/v1/${planName}`);}@@ -572,6 +598,30 @@ export class BytebaseApiClient {});}+ // Draft review Issues are the UI-authored Plan lifecycle boundary. They stay+ // hidden from active review until the Plan Detail "Ready for Review" action+ // flips only the draft field.+ async createDraftIssue(+ project: string,+ title: string,+ plan: string,+ labels: string[] = [],+ ): Promise<{+ name: string;+ status: string;+ approvalStatus: string;+ draft: boolean;+ labels: string[];+ }> {+ return this.request("POST", `/v1/${project}/issues`, {+ title,+ type: "DATABASE_CHANGE",+ plan,+ draft: true,+ labels,+ });+ }+// Post a comment to an issue. CreateIssueComment binds `body: "issue_comment"`,// so the HTTP body is the IssueComment payload directly. Used by the// markdown-link spec (BYT-9664) to seed a comment with links via the API@@ -582,7 +632,14 @@ export class BytebaseApiClient {});}- async getIssue(issueName: string): Promise<{ name: string; status: string; approvalStatus: string; approvalTemplate: unknown }> {+ async getIssue(issueName: string): Promise<{+ name: string;+ status: string;+ approvalStatus: string;+ approvalTemplate: unknown;+ draft?: boolean;+ labels?: string[];+ }> {return this.request("GET", `/v1/${issueName}`);}@@ -617,6 +674,13 @@ export class BytebaseApiClient {settings: {requireIssueApproval?: boolean;requirePlanCheckNoError?: boolean;+ enforceSqlReview?: boolean;+ forceIssueLabels?: boolean;+ issueLabels?: Array<{+ value: string;+ color?: Record<string, unknown>;+ group?: string;+ }>;allowJustInTimeAccess?: boolean;allowRequestRole?: boolean;// When license is installed, project.allow_self_approval defaults@@ -641,6 +705,18 @@ export class BytebaseApiClient {fields.push("require_plan_check_no_error");body.requirePlanCheckNoError = settings.requirePlanCheckNoError;}+ if (settings.enforceSqlReview !== undefined) {+ fields.push("enforce_sql_review");+ body.enforceSqlReview = settings.enforceSqlReview;+ }+ if (settings.forceIssueLabels !== undefined) {+ fields.push("force_issue_labels");+ body.forceIssueLabels = settings.forceIssueLabels;+ }+ if (settings.issueLabels !== undefined) {+ fields.push("issue_labels");+ body.issueLabels = settings.issueLabels;+ }if (settings.allowJustInTimeAccess !== undefined) {fields.push("allow_just_in_time_access");body.allowJustInTimeAccess = settings.allowJustInTimeAccess;diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.tsindex f8f2b0d900..9aec7d102f 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts@@ -316,26 +316,31 @@ test.describe("Per-spec check counts render plan-wide (BYT-9160)", () => {// fix landed; it now runs as a normal passing guard so a re-regression fails// loudly.test.describe(- "Spec tab switch shows only the selected spec's statement (BYT-9794)",+ "Spec identity and resource routing stay synchronized (BYT-9794/BYT-9805/BYT-9913)",() => {test(- "only the selected spec's statement is shown in CHANGES after switching tabs",+ "target-derived tabs, URLs, history, and the selected statement move together",async () => {const ts = Date.now();const colA = `e2e_stale_a_${ts}`;const colB = `e2e_stale_b_${ts}`;- await createPlanAndWaitForChecks("E2E Stale Spec Editor", [- {- id: `spec-a-${ts}`,- targets: [env.database],- sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colA} TEXT;`,- },- {- id: `spec-b-${ts}`,- targets: [env.database],- sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colB} TEXT;`,- },- ]);+ const specA = `spec-a-${ts}`;+ const specB = `spec-b-${ts}`;+ const planId = await createPlanAndWaitForChecks(+ "E2E Stale Spec Editor",+ [+ {+ id: specA,+ targets: [env.database],+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colA} TEXT;`,+ },+ {+ id: specB,+ targets: [env.database],+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colB} TEXT;`,+ },+ ],+ );await planPage.expandSection("Changes");@@ -368,12 +373,26 @@ test.describe(.join("\n");});- await planPage.specTab(1).click();+ const tab1 = planPage.specTab(1);+ const tab2 = planPage.specTab(2);+ await expect(tab1).toHaveAccessibleName(+ `Change 1: ${env.databaseId}`,+ );+ await expect(tab2).toHaveAccessibleName(+ `Change 2: ${env.databaseId}`,+ );+ await expect(+ page.getByRole("button", { name: /Database Change/ }),+ ).toHaveCount(0);+await expect.poll(readChangesStatements, { timeout: 15_000 }).toContain(colA);- await planPage.specTab(2).click();+ await tab2.click();+ await expect(page).toHaveURL(+ new RegExp(`/plans/${planId}/specs/${specB}$`),+ );await expect.poll(readChangesStatements, { timeout: 15_000 }).toContain(colB);@@ -382,6 +401,25 @@ test.describe(// spec #2's statement remains. (Pre-fix, duplicate keys left spec #1's// editor stacked and this assertion failed.)expect(await readChangesStatements()).not.toContain(colA);++ await tab1.click();+ await expect(page).toHaveURL(+ new RegExp(`/plans/${planId}/specs/${specA}$`),+ );+ await expect+ .poll(readChangesStatements, { timeout: 15_000 })+ .toContain(colA);++ // Same-plan Back restores resource selection without remounting the+ // shell or collapsing Changes (BYT-9913 resource-routing contract).+ await page.goBack();+ await expect(page).toHaveURL(+ new RegExp(`/plans/${planId}/specs/${specB}$`),+ );+ await expect(tab2).toBeVisible();+ await expect+ .poll(readChangesStatements, { timeout: 15_000 })+ .toContain(colB);},);},diff --git a/frontend/tests/e2e/plan-detail/plan-detail-header.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.tssimilarity index 53%rename from frontend/tests/e2e/plan-detail/plan-detail-header.spec.tsrename to frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.tsindex ad4fee5c3a..379561262b 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-header.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts@@ -1,4 +1,4 @@-// Plan detail — HEADER lifecycle slot (the whole sub-area in one file).+// Plan Detail lifecycle — the whole header lifecycle sub-area in one file.//// PR #20720 (BYT-9722) funnels the plan's lifecycle into a single header slot:// one resolver (resolvePlanLifecycleHeaderState) reads the plan/issue/rollout@@ -8,6 +8,13 @@// observer; deployer vs not), so this file is organized as a// state × persona × path matrix, not a happy-path walk://+// DRAFT+// - Create stays actionable and states every blocker on press. (C1)+// - A clean draft becomes ready for review in one press. (S1)+// - Failed checks are either a blocker or one named override. (S2)+// - Forced labels stay in metadata and block only submission. (S3)+// - Unsaved edits and missing permissions are actionable blockers. (S4/S5)+//// REVIEW// - Persona split: candidate sees the "Review" action; a non-candidate// observer sees the read-only "Under review" pill (same plan). (R1/R2)@@ -22,17 +29,18 @@//// TERMINAL / overflow (⋯)// - Close + reopen the review issue. (T1)-// - Close + reopen a draft plan (no issue). (T2)+// - Close + reopen a Plan with a linked draft Issue. (T2)//-// Not covered here (with reason): `create` (draft-create flow, covered by the-// smoke/create paths); `review-generating` / `preparing-rollout` (sub-second-// transient states — not reliably observable in the browser); GitOps `none`+// Not covered here (with reason): `review-generating` / `preparing-rollout`+// (sub-second transient states — not reliably observable in the browser);+// queued/running checks (the sample check finishes too quickly for a stable+// browser assertion); GitOps `none`// (needs a release-backed plan + VCS setup, out of this sub-area).//// Each describe configures the settings IT needs and navigates fresh in its own// beforeAll, so blocks are order-independent (they share one browser for speed,// per AGENTS.md §2). The file-level beforeAll snapshots the originals + opens-// the admin + dba1 browsers; the file-level afterAll restores + closes them.+// the admin + persona browsers; the file-level afterAll restores + closes them.import {test,@@ -41,10 +49,17 @@ import {type BrowserContext,} from "@playwright/test";import { loadTestEnv, type TestEnv } from "../framework/env";-import { BytebaseApiClient } from "../framework/api-client";+import {+ BytebaseApiClient,+ type IamBinding,+} from "../framework/api-client";import { signInBrowserAs } from "../framework/sign-in";import { PlanDetailPage } from "./plan-detail.page";-import { seedReviewPlan, waitForApprovalStatus } from "./plan-helpers";+import {+ seedDraftPlan,+ seedReviewPlan,+ waitForApprovalStatus,+} from "./plan-helpers";test.setTimeout(240_000);test.describe.configure({ mode: "serial" });@@ -62,13 +77,48 @@ let dbaContext: BrowserContext;let dbaPage: Page;let dbaPlanPage: PlanDetailPage;+// A custom read-only persona can load Plan Detail but cannot update its draft+// Issue. This proves lifecycle blockers are real permission explanations, not+// admin-only rendering artifacts.+let viewerContext: BrowserContext;+let viewerPage: Page;+let viewerPlanPage: PlanDetailPage;++interface IssueLabelSetting {+ value: string;+ color?: Record<string, unknown>;+ group?: string;+}+let originalProjectSettings: {requireIssueApproval?: boolean;requirePlanCheckNoError?: boolean;allowSelfApproval?: boolean;+ enforceSqlReview?: boolean;+ forceIssueLabels?: boolean;+ issueLabels?: IssueLabelSetting[];} = {};let originalApproval: unknown = null;const createdReviewConfigs: string[] = [];+let originalProjectIamBindings: IamBinding[] = [];++const VIEWER_EMAIL = "[email protected]";+const VIEWER_PASSWORD = "e2e-plan-lifecycle-pw-1!"; // NOSONAR — e2e fixture only+const VIEWER_ROLE_ID = "e2e-plan-lifecycle-reader";+const VIEWER_ROLE = `roles/${VIEWER_ROLE_ID}`;+const VIEWER_PERMISSIONS = [+ "bb.databases.get",+ "bb.databases.list",+ "bb.issueComments.list",+ "bb.issues.get",+ "bb.planCheckRuns.get",+ "bb.plans.get",+ "bb.projects.get",+ "bb.projects.getIamPolicy",+ "bb.sheets.get",+ "bb.taskRuns.list",+];+const REQUIRED_LABEL = "e2e-lifecycle";const ADMIN_RULE = {source: "CHANGE_DATABASE",@@ -89,6 +139,8 @@ async function setApproval(allowSelfApproval: boolean): Promise<void> {requireIssueApproval: true,requirePlanCheckNoError: false,allowSelfApproval,+ enforceSqlReview: false,+ forceIssueLabels: false,});await env.api.upsertSetting("WORKSPACE_APPROVAL",@@ -102,6 +154,8 @@ async function setPermissive(): Promise<void> {await env.api.updateProjectSettings(env.project, {requireIssueApproval: false,requirePlanCheckNoError: false,+ enforceSqlReview: false,+ forceIssueLabels: false,});// Clear any approval rule a prior describe left in WORKSPACE_APPROVAL —// otherwise a leftover rule still forces a pending review (blocking the@@ -141,6 +195,19 @@ async function goPlan(planId: string): Promise<void> {await planPage.dismissModals();}+async function waitForIssueDraft(+ issueName: string,+ expected: boolean,+ timeoutMs = 30_000,+): Promise<void> {+ await expect+ .poll(async () => (await env.api.getIssue(issueName)).draft ?? false, {+ message: `${issueName} draft should become ${expected}`,+ timeout: timeoutMs,+ })+ .toBe(expected);+}+test.beforeAll(async ({ browser }) => {env = loadTestEnv();projectId = env.project.split("/").pop()!;@@ -151,8 +218,16 @@ test.beforeAll(async ({ browser }) => {requireIssueApproval: !!project.requireIssueApproval,requirePlanCheckNoError: !!project.requirePlanCheckNoError,allowSelfApproval: !!project.allowSelfApproval,+ enforceSqlReview: !!project.enforceSqlReview,+ forceIssueLabels: !!project.forceIssueLabels,+ issueLabels: Array.isArray(project.issueLabels)+ ? (structuredClone(project.issueLabels) as IssueLabelSetting[])+ : [],};originalApproval = (await env.api.getSetting("WORKSPACE_APPROVAL"))?.value ?? null;+ originalProjectIamBindings = structuredClone(+ (await env.api.getProjectIamPolicy(env.project)).bindings,+ );sharedContext = await browser.newContext({ storageState: ".auth/state.json" });page = await sharedContext.newPage();@@ -171,6 +246,40 @@ test.beforeAll(async ({ browser }) => {});dbaPage = await dbaContext.newPage();dbaPlanPage = new PlanDetailPage(dbaPage, env.baseURL);++ try {+ await env.api.createUser(+ VIEWER_EMAIL,+ VIEWER_PASSWORD,+ "E2E Plan Lifecycle Viewer",+ );+ } catch (error) {+ if (!String(error).includes("(409)")) throw error;+ }+ try {+ await env.api.createRole(+ VIEWER_ROLE_ID,+ "E2E Plan Lifecycle Reader",+ VIEWER_PERMISSIONS,+ );+ } catch (error) {+ if (!String(error).includes("(409)")) throw error;+ }+ await env.api.appendProjectBinding(env.project, VIEWER_ROLE, [+ `user:${VIEWER_EMAIL}`,+ ]);+ await signInBrowserAs(+ browser,+ env.baseURL,+ VIEWER_EMAIL,+ VIEWER_PASSWORD,+ ".auth/plan-lifecycle-viewer.json",+ );+ viewerContext = await browser.newContext({+ storageState: ".auth/plan-lifecycle-viewer.json",+ });+ viewerPage = await viewerContext.newPage();+ viewerPlanPage = new PlanDetailPage(viewerPage, env.baseURL);});test.afterAll(async () => {@@ -188,10 +297,316 @@ test.afterAll(async () => {"value.workspace_approval",).catch(() => {});+ const currentProjectIam = await env.api+ .getProjectIamPolicy(env.project)+ .catch(() => undefined);+ if (currentProjectIam) {+ await env.api+ .setProjectIamPolicy(env.project, {+ ...currentProjectIam,+ bindings: originalProjectIamBindings,+ })+ .catch(() => {});+ }+ await env.api.deleteRole(VIEWER_ROLE);+ await viewerContext?.close();await dbaContext?.close();await sharedContext?.close();});+/* ------------------------------ DRAFT ---------------------------------- */++test.describe("Create states every blocker and advances to a real draft (C1)", () => {+ test.beforeAll(async () => {+ await setApproval(false);+ await env.api.updateProjectSettings(env.project, {+ forceIssueLabels: true,+ issueLabels: [+ ...(originalProjectSettings.issueLabels ?? []).filter(+ (label) => label.value !== REQUIRED_LABEL,+ ),+ { value: REQUIRED_LABEL },+ ],+ });+ });++ test("Create defers required labels, states its blockers, and creates a linked draft Issue", async () => {+ await planPage.gotoCreate(projectId, { databaseList: env.database });+ await planPage.dismissModals();++ const labels = page.getByRole("button", { name: /Issue Labels/ }).first();+ await expect(labels).not.toContainText("*");+ await expect(planPage.headerTitle).toHaveValue("");+ await expect(planPage.headerCreateButton).toBeEnabled();+ await planPage.headerCreateButton.click();++ const notice = planPage.lifecycleAlert("Cannot create plan");+ await expect(notice).toBeVisible();+ await expect(notice).toContainText("Title is required");+ await expect(notice).toContainText("Statement is empty");+ await expect(notice).not.toContainText("Issue Labels");+ await expect(planPage.headerTitle).toBeFocused();+ await expect(page).toHaveURL(/\/plans\/create/);++ const title = `E2E Lifecycle Create ${Date.now()}`;+ await planPage.headerTitle.fill(title);+ await expect(notice).not.toContainText("Title is required");+ await expect(notice).toContainText("Statement is empty");++ await planPage.fillPlanStatement("SELECT 1;");+ await expect(notice).toHaveCount(0);++ await planPage.headerCreateButton.click();+ await expect(page).toHaveURL(/\/plans\/(?!create(?:\/|$))[^/?]+$/, {+ timeout: 30_000,+ });+ await expect(planPage.headerReadyForReviewButton).toBeVisible({+ timeout: 15_000,+ });+ await expect(labels).toContainText("*");++ const planId = new URL(page.url()).pathname.split("/").pop()!;+ const plan = await env.api.getPlan(+ `projects/${projectId}/plans/${planId}`,+ );+ expect(plan.issue).toBeTruthy();+ await waitForIssueDraft(plan.issue, true);+ });+});++test.describe("A clean draft submits for review without an intermediate form (S1)", () => {+ let seeded: Awaited<ReturnType<typeof seedDraftPlan>>;++ test.beforeAll(async () => {+ await setApproval(false);+ seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Lifecycle Direct Submit",+ sql: "SELECT 1;",+ runChecks: true,+ });+ });++ test("Ready for Review advances in one press", async () => {+ await goPlan(seeded.planId);+ await expect(planPage.headerReadyForReviewButton).toBeEnabled();++ await planPage.headerReadyForReviewButton.click();++ await expect(+ page.getByRole("button", { name: "Confirm", exact: true }),+ ).toHaveCount(0);+ await waitForIssueDraft(seeded.issueName, false);+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ await expect(planPage.headerStatusPill("Under review")).toBeVisible({+ timeout: 15_000,+ });+ await expect(planPage.headerReadyForReviewButton).toHaveCount(0);+ });+});++test.describe("Failed checks resolve to a blocker or one explicit override (S2)", () => {+ let seeded: Awaited<ReturnType<typeof seedDraftPlan>>;++ test.beforeAll(async () => {+ await setApproval(false);+ await attachErrorConfig();+ seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Lifecycle Failed Checks",+ sql: `ALTER TABLE employee ADD COLUMN e2e_lifecycle_${Date.now()} TEXT;`,+ runChecks: true,+ });+ await env.api.updateProjectSettings(env.project, {+ enforceSqlReview: true,+ });+ });++ test("enforcement blocks submission; relaxing it offers Submit anyway with working cancel", async () => {+ await goPlan(seeded.planId);+ await planPage.headerReadyForReviewButton.click();++ const blocker = planPage.lifecycleAlert("Not ready for review");+ await expect(blocker).toContainText("Some task checks didn't pass.");+ await expect(+ page.getByRole("button", { name: "Submit anyway" }),+ ).toHaveCount(0);+ await waitForIssueDraft(seeded.issueName, true);++ await env.api.updateProjectSettings(env.project, {+ enforceSqlReview: false,+ });+ await page.reload();+ await page.waitForLoadState("networkidle");+ await planPage.headerReadyForReviewButton.click();++ const submitAnyway = page.getByRole("button", {+ name: "Submit anyway",+ exact: true,+ });+ await expect(submitAnyway).toBeVisible();+ const decision = submitAnyway.locator("..").locator("..");+ await expect(+ decision.getByText("Some checks were not successful", { exact: true }),+ ).toBeVisible();+ await expect(+ decision.getByText(+ "Some checks did not pass. Continue anyway only if this is expected.",+ { exact: true },+ ),+ ).toBeVisible();+ await expect(+ decision.getByRole("button", { name: "Confirm", exact: true }),+ ).toHaveCount(0);+ await expect(decision.getByRole("checkbox")).toHaveCount(0);++ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ await expect(submitAnyway).toHaveCount(0);+ await waitForIssueDraft(seeded.issueName, true);++ await planPage.headerReadyForReviewButton.click();+ await page+ .getByRole("button", { name: "Submit anyway", exact: true })+ .click();+ await waitForIssueDraft(seeded.issueName, false);+ await expect(planPage.headerStatusPill("Under review")).toBeVisible({+ timeout: 15_000,+ });+ });+});++test.describe("Forced labels stay in metadata and block only submission (S3)", () => {+ let seeded: Awaited<ReturnType<typeof seedDraftPlan>>;++ test.beforeAll(async () => {+ await setApproval(false);+ await env.api.updateProjectSettings(env.project, {+ forceIssueLabels: true,+ issueLabels: [+ ...(originalProjectSettings.issueLabels ?? []).filter(+ (label) => label.value !== REQUIRED_LABEL,+ ),+ { value: REQUIRED_LABEL },+ ],+ });+ seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Lifecycle Required Label",+ sql: "SELECT 1;",+ });+ });++ test("the blocker points to metadata; selecting a label clears it before direct submission", async () => {+ await goPlan(seeded.planId);+ await planPage.headerReadyForReviewButton.click();++ const blocker = planPage.lifecycleAlert("Not ready for review");+ await expect(blocker).toContainText(+ "Issue Labels are required before review",+ );+ await expect(blocker.getByRole("button")).toHaveCount(0);++ const labels = page.getByRole("button", { name: /Issue Labels/ }).first();+ await expect(labels).toContainText("*");+ await labels.click();+ await page+ .getByRole("button", { name: REQUIRED_LABEL, exact: true })+ .click();++ await expect+ .poll(async () => (await env.api.getIssue(seeded.issueName)).labels ?? [])+ .toContain(REQUIRED_LABEL);+ await expect(blocker).toHaveCount(0);+ await page.keyboard.press("Escape");+ await expect(+ page.getByTestId("plan-detail-page").getByText(REQUIRED_LABEL, {+ exact: true,+ }),+ ).toBeVisible();++ await planPage.headerReadyForReviewButton.click();+ await waitForIssueDraft(seeded.issueName, false);+ await expect(planPage.headerStatusPill("Under review")).toBeVisible({+ timeout: 15_000,+ });+ });+});++test.describe("Unsaved Plan edits block lifecycle advance without disabling it (S4)", () => {+ let seeded: Awaited<ReturnType<typeof seedDraftPlan>>;++ test.beforeAll(async () => {+ await setApproval(false);+ seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Lifecycle Unsaved Edit",+ sql: "SELECT 1;",+ });+ });++ test("Ready for Review explains the edit and advances after it is cancelled", async () => {+ await goPlan(seeded.planId);+ await page.getByRole("button", { name: "Edit", exact: true }).last().click();+ await planPage.fillPlanStatement("SELECT 2;");++ await expect(planPage.headerReadyForReviewButton).toBeEnabled();+ await planPage.headerReadyForReviewButton.click();+ await expect(+ planPage.lifecycleAlert("Not ready for review"),+ ).toContainText("Please save or cancel your changes before continuing");++ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ await expect(planPage.lifecycleAlert("Not ready for review")).toHaveCount(0);+ await planPage.headerReadyForReviewButton.click();+ await waitForIssueDraft(seeded.issueName, false);+ });+});++test.describe("A read-only persona gets an actionable permission explanation (S5)", () => {+ let seeded: Awaited<ReturnType<typeof seedDraftPlan>>;++ test.beforeAll(async () => {+ await setApproval(false);+ seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Lifecycle Viewer",+ sql: "SELECT 1;",+ });+ });++ test("a read-only user sees enabled Ready for Review and the missing permission blocker", async () => {+ await viewerPlanPage.goto(projectId, seeded.planId);+ await viewerPlanPage.dismissModals();+ await expect(viewerPlanPage.headerReadyForReviewButton).toBeEnabled();++ await viewerPlanPage.headerReadyForReviewButton.click();++ await expect(+ viewerPlanPage.lifecycleAlert("Not ready for review"),+ ).toContainText("you need bb.issues.update");+ await waitForIssueDraft(seeded.issueName, true);+ });+});++test.describe("A persisted Plan without its draft Issue is incomplete (S6)", () => {+ let planId = "";++ test.beforeAll(async () => {+ await setApproval(false);+ const ts = Date.now();+ const sheet = await env.api.createSheet(env.project, "SELECT 1;");+ const plan = await env.api.createPlan(+ env.project,+ `E2E Lifecycle Incomplete ${ts}`,+ [{ id: `spec-${ts}`, targets: [env.database], sheet }],+ );+ planId = plan.name.split("/").pop()!;+ });++ test("the header shows Incomplete instead of offering Ready for Review", async () => {+ await goPlan(planId);+ await expect(planPage.headerStamp("Incomplete")).toBeVisible({+ timeout: 15_000,+ });+ await expect(planPage.headerReadyForReviewButton).toHaveCount(0);+ });+});+/* ----------------------------- REVIEW ---------------------------------- */test.describe("Review advance is persona-scoped (R1/R2)", () => {@@ -277,20 +692,13 @@ test.describe("Approved with a failing ERROR check shows the checks-failing pilllet planId = "";test.beforeAll(async () => {- await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await setApproval(true);await attachErrorConfig();// requirePlanCheckNoError:true keeps the rollout blocked after approval, so// the resolver stays on the checks-failing status (not deploy).await env.api.updateProjectSettings(env.project, {- requireIssueApproval: true,requirePlanCheckNoError: true,- allowSelfApproval: true,});- await env.api.upsertSetting(- "WORKSPACE_APPROVAL",- { workspaceApproval: { rules: [ADMIN_RULE] } },- "value.workspace_approval",- );const ts = Date.now();const seeded = await seedReviewPlan(env.api, env.project, env.database, {// A nullable column trips COLUMN_NO_NULL at ERROR level.@@ -435,18 +843,17 @@ test.describe("A multi-stage rollout advances the header stage by stage to Deplo/* -------------------------- TERMINAL / overflow ------------------------- */test.describe("Close and reopen the review from the ⋯ overflow menu (T1)", () => {- let planId = "";+ const titlePrefix = "E2E Hdr T1";const acceptDialogs = (d: import("@playwright/test").Dialog) => d.accept();test.beforeAll(async () => {// Open review, no rollout yet (self-approval off → observer, unapproved).await setApproval(false);const seeded = await seedReviewPlan(env.api, env.project, env.database, {- prefix: "E2E Hdr T1",+ prefix: titlePrefix,sql: "SELECT 1;",runChecks: true,});- planId = seeded.planId;await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);// Close/reopen confirm via window.confirm — auto-accept for this block.page.on("dialog", acceptDialogs);@@ -456,8 +863,20 @@ test.describe("Close and reopen the review from the ⋯ overflow menu (T1)", ()page.off("dialog", acceptDialogs);});- test("Close cancels the review (Closed stamp); Reopen restores it", async () => {- await goPlan(planId);+ test("Close and Reopen update both Plan Detail and the restored Plan List row", async () => {+ const listURL = `${env.baseURL}/projects/${projectId}/plans`;+ const listRow = () =>+ page+ .locator('[data-testid="plan-list-item"]')+ .filter({ hasText: titlePrefix })+ .first();++ await page.goto(listURL);+ await page.waitForLoadState("networkidle");+ await expect(listRow()).toContainText("Under review", {+ timeout: 15_000,+ });+ await listRow().click();await expect(planPage.headerStatusPill("Under review")).toBeVisible({timeout: 15_000,});@@ -467,6 +886,12 @@ test.describe("Close and reopen the review from the ⋯ overflow menu (T1)", ()await planPage.overflowItem("Close").click();await expect(planPage.headerStamp("Closed")).toBeVisible({ timeout: 15_000 });+ // Back must not restore the stale under-review cache (#21017).+ await page.goBack();+ await expect(page).toHaveURL(listURL);+ await expect(listRow()).toContainText("Closed", { timeout: 15_000 });++ await listRow().click();// With a terminal slot (no primary), Reopen is promoted to a direct button.await expect(planPage.headerReopenButton).toBeVisible({ timeout: 10_000 });await planPage.headerReopenButton.click();@@ -474,6 +899,12 @@ test.describe("Close and reopen the review from the ⋯ overflow menu (T1)", ()timeout: 15_000,});await expect(planPage.headerStamp("Closed")).toHaveCount(0);++ await page.goBack();+ await expect(page).toHaveURL(listURL);+ await expect(listRow()).toContainText("Under review", {+ timeout: 15_000,+ });});});@@ -482,14 +913,15 @@ test.describe("Close and reopen a draft plan from the ⋯ overflow menu (T2)", (const acceptDialogs = (d: import("@playwright/test").Dialog) => d.accept();test.beforeAll(async () => {- await setPermissive();- // A plan with NO issue and NO rollout → ready-for-review + close-plan.- const ts = Date.now();- const sheet = await env.api.createSheet(env.project, "SELECT 1;");- const plan = await env.api.createPlan(env.project, `E2E Hdr T2 ${ts}`, [- { id: `spec-${ts}`, targets: [env.database], sheet },- ]);- planId = plan.name.split("/").pop()!;+ await setApproval(false);+ // A UI-authored draft is a Plan plus its linked draft Issue. A persisted+ // Plan without that Issue is an incomplete partial-creation state and must+ // not be mistaken for ready-for-review.+ const seeded = await seedDraftPlan(env.api, env.project, env.database, {+ prefix: "E2E Hdr T2",+ sql: "SELECT 1;",+ });+ planId = seeded.planId;page.on("dialog", acceptDialogs);});@@ -499,10 +931,11 @@ test.describe("Close and reopen a draft plan from the ⋯ overflow menu (T2)", (test("Close deletes the draft plan (Closed stamp); Reopen restores it", async () => {await goPlan(planId);- // Draft with no issue → the primary is "Ready for Review"; Close is in ⋯.- await expect(- planPage.headerRow.getByRole("button", { name: "Ready for Review" }),- ).toBeVisible({ timeout: 15_000 });+ // A linked draft Issue owns the Ready for Review lifecycle state; Close is+ // the secondary action in ⋯.+ await expect(planPage.headerReadyForReviewButton).toBeVisible({+ timeout: 15_000,+ });await planPage.openOverflow();await planPage.overflowItem("Close").click();@@ -510,9 +943,9 @@ test.describe("Close and reopen a draft plan from the ⋯ overflow menu (T2)", (await expect(planPage.headerReopenButton).toBeVisible({ timeout: 10_000 });await planPage.headerReopenButton.click();- await expect(- planPage.headerRow.getByRole("button", { name: "Ready for Review" }),- ).toBeVisible({ timeout: 15_000 });+ await expect(planPage.headerReadyForReviewButton).toBeVisible({+ timeout: 15_000,+ });await expect(planPage.headerStamp("Closed")).toHaveCount(0);});});diff --git a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.tsindex 59b4ac16b1..57093f142f 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts@@ -4,7 +4,7 @@// via permissive project settings):// - Running a successful task transitions to Done.// - Running a failing task (nonexistent target) transitions to Failed-// and surfaces a Retry button.+// and surfaces a Rerun button.import {test,@@ -100,8 +100,8 @@ test.describe("Successful task transitions to Done", () => {});});-test.describe("Failing task transitions to Failed and shows Retry", () => {- test("Run → Failed + Retry button visible", async () => {+test.describe("Failing task transitions to Failed and shows Rerun", () => {+ test("Run → Failed + Rerun button visible", async () => {const missingTable = `nonexistent_table_e2e_${Date.now()}`;await createPlanAndNavigate("E2E Task Failure",@@ -117,7 +117,7 @@ test.describe("Failing task transitions to Failed and shows Retry", () => {timeout: 30_000,});- await expect(planPage.retryButton).toBeVisible({ timeout: 5_000 });+ await expect(planPage.taskRerunButton).toBeVisible({ timeout: 5_000 });});});diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.tsindex d9f1b56e18..4196943e32 100644--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts@@ -7,7 +7,7 @@ export class PlanDetailPage {readonly changesSection: Locator;readonly deploySection: Locator;readonly manualCreateRolloutButton: Locator;- readonly retryButton: Locator;+ readonly taskRerunButton: Locator;// The plan/issue title input rendered in PlanDetailHeader. It is an// <input> bound to the plan or issue title — first textbox on the page.readonly headerTitle: Locator;@@ -37,6 +37,8 @@ export class PlanDetailPage {// "Rerun · <stage>" (distinct from the deploy-section per-task exact "Run").readonly headerRunStage: Locator;readonly headerRerunStage: Locator;+ readonly headerCreateButton: Locator;+ readonly headerReadyForReviewButton: Locator;// The your-turn Review action in the header slot (opens the approve/reject// composer). Scoped so it never resolves to a phase-section control.readonly headerReviewButton: Locator;@@ -51,7 +53,10 @@ export class PlanDetailPage {this.changesSection = page.getByText("Changes").first();this.deploySection = page.getByText("Deploy").first();this.manualCreateRolloutButton = page.getByRole("button", { name: "Manually create rollout" });- this.retryButton = page.getByRole("button", { name: "Retry" });+ this.taskRerunButton = page.getByRole("button", {+ name: "Rerun",+ exact: true,+ });this.headerTitle = page.getByRole("textbox").first();this.reviewButton = page.getByRole("button", { name: "Review", exact: true });@@ -76,6 +81,14 @@ export class PlanDetailPage {// starts with "Re", so /^Run/ and /^Rerun/ never cross-match.this.headerRunStage = this.headerRow.getByRole("button", { name: /^Run/ });this.headerRerunStage = this.headerRow.getByRole("button", { name: /^Rerun/ });+ this.headerCreateButton = this.headerRow.getByRole("button", {+ name: "Create",+ exact: true,+ });+ this.headerReadyForReviewButton = this.headerRow.getByRole("button", {+ name: "Ready for Review",+ exact: true,+ });this.headerReviewButton = this.headerRow.getByRole("button", {name: "Review",exact: true,@@ -123,7 +136,7 @@ export class PlanDetailPage {// because the header lifecycle slot (BYT-9722, #20720) now renders the SAME// status text as a pill — an unscoped getByText would match both and throw a// strict-mode violation (the header pill is asserted separately, scoped to the- // header row, in plan-detail-header.spec.ts).+ // header row, in plan-detail-lifecycle.spec.ts).reviewBadge(text: string): Locator {return this.page.locator("#plan-phase-review")@@ -149,6 +162,31 @@ export class PlanDetailPage {await this.page.waitForLoadState("networkidle");}+ async gotoCreate(+ projectId: string,+ query: Record<string, string> = {},+ ): Promise<void> {+ const search = new URLSearchParams(query).toString();+ await this.page.goto(+ `${this.baseURL}/projects/${projectId}/plans/create${search ? `?${search}` : ""}`,+ );+ await this.page.waitForLoadState("networkidle");+ }++ lifecycleAlert(heading: string): Locator {+ return this.page.getByRole("alert").filter({ hasText: heading });+ }++ async fillPlanStatement(sql: string): Promise<void> {+ const editor = this.page.getByRole("code").first();+ await expect(editor).toBeVisible();+ await editor.click();+ await this.page.keyboard.press("ControlOrMeta+a");+ await this.page.keyboard.press("Delete");+ await this.page.keyboard.insertText(sql);+ await expect(editor.locator(".view-lines")).toContainText(sql);+ }+async dismissModals() {await this.page.evaluate(() => {localStorage.setItem(@@ -210,18 +248,17 @@ export class PlanDetailPage {}}- // Spec tabs render as `<button>N. <Kind></button>` (e.g.- // "1. Database Change") inside the CHANGES section. The "1." and- // "Database Change" pieces live in separate child spans — so plain- // textContent has no separator. Matching the BUTTON's accessible name- // (which inserts the space) via getByRole sidesteps that.+ // Change tabs expose the complete target-derived identity as+ // "Change N: <target>" even when the visual number is omitted because the+ // target is already unique. Match that stable accessible prefix rather than+ // the removed generic "N. Database Change" text.//// Caller must expandSection("Changes") first if a rollout exists,// since the section auto-collapses in that state and the tab won't be// in the visible DOM.specTab(n: number): Locator {return this.page- .getByRole("button", { name: new RegExp(`^${n}\\.\\s+\\w`) })+ .getByRole("button", { name: new RegExp(`^Change ${n}:`) }).first();}diff --git a/frontend/tests/e2e/plan-detail/plan-helpers.ts b/frontend/tests/e2e/plan-detail/plan-helpers.tsindex 87fd2ee366..da5e64f7b7 100644--- a/frontend/tests/e2e/plan-detail/plan-helpers.ts+++ b/frontend/tests/e2e/plan-detail/plan-helpers.ts@@ -52,6 +52,43 @@ export async function seedReviewPlan(};}+// Seed the same database-change shape as seedReviewPlan, but keep its linked+// Issue in the draft lifecycle state. Ready-for-review E2E tests use this as+// setup so the browser owns the actual submission transition.+export async function seedDraftPlan(+ api: BytebaseApiClient,+ project: string,+ database: string,+ opts: {+ prefix: string;+ sql: string;+ labels?: string[];+ runChecks?: boolean;+ },+): Promise<{ planId: string; planName: string; issueName: string }> {+ const ts = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;+ const title = `${opts.prefix} ${ts}`;+ const sheet = await api.createSheet(project, opts.sql);+ const plan = await api.createPlan(project, title, [+ { id: `spec-${ts}`, targets: [database], sheet },+ ]);+ const issue = await api.createDraftIssue(+ project,+ title,+ plan.name,+ opts.labels,+ );+ if (opts.runChecks) {+ await api.runPlanChecks(plan.name);+ await waitForPlanChecksDone(api, plan.name);+ }+ return {+ planId: plan.name.split("/").pop()!,+ planName: plan.name,+ issueName: issue.name,+ };+}+// Poll the latest planCheckRun on `planName` until status === "DONE" or the// timeout elapses. The check run is created asynchronously after// runPlanChecks(), so getPlanCheckRun may briefly 404 — we swallow and