Skip to content

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

feat(e2e): plan-detail test suite for CUJ lifecycle + BYT-9158 regressions (#19981)

zchpeterf50117e238d4
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.ts
index 0e11cb82ef..743bb6c221 100644
--- a/frontend/tests/e2e/framework/api-client.ts
+++ b/frontend/tests/e2e/framework/api-client.ts
@@ -146,4 +146,86 @@ export class BytebaseApiClient {
async deleteWorkloadIdentity(email: string) {
try { await this.request<unknown>("DELETE", `/v1/workloadIdentities/${email}`); } catch { /* ignore */ }
}
+
+ // Sheets
+ async createSheet(project: string, content: string): Promise<string> {
+ const b64 = Buffer.from(content).toString("base64");
+ const resp = await this.request<{ name: string }>(
+ "POST", `/v1/${project}/sheets`, { content: b64 }
+ );
+ return resp.name;
+ }
+
+ // Plans
+ async createPlan(project: string, title: string, specs: { id: string; targets: string[]; sheet: string }[]): Promise<{ name: string }> {
+ return this.request<{ name: string }>("POST", `/v1/${project}/plans`, {
+ title,
+ specs: specs.map(s => ({
+ id: s.id,
+ changeDatabaseConfig: { targets: s.targets, sheet: s.sheet },
+ })),
+ });
+ }
+
+ async getPlan(planName: string): Promise<{ name: string; hasRollout: boolean; state: string }> {
+ return this.request("GET", `/v1/${planName}`);
+ }
+
+ async runPlanChecks(planName: string): Promise<void> {
+ await this.request("POST", `/v1/${planName}:runPlanChecks`, {});
+ }
+
+ async getPlanCheckRun(planName: string): Promise<{ status: string; results: { status: string; type: string; title: string }[] }> {
+ return this.request("GET", `/v1/${planName}/planCheckRun`);
+ }
+
+ // Issues
+ async createIssue(project: string, title: string, plan: string): Promise<{ name: string; status: string; approvalStatus: string }> {
+ return this.request("POST", `/v1/${project}/issues`, {
+ title, type: "DATABASE_CHANGE", plan,
+ });
+ }
+
+ async getIssue(issueName: string): Promise<{ name: string; status: string; approvalStatus: string; approvalTemplate: unknown }> {
+ return this.request("GET", `/v1/${issueName}`);
+ }
+
+ async approveIssue(issueName: string): Promise<{ approvalStatus: string }> {
+ return this.request("POST", `/v1/${issueName}:approve`, {});
+ }
+
+ // Project settings
+ async updateProjectSettings(project: string, settings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean }): Promise<void> {
+ const fields: string[] = [];
+ if (settings.requireIssueApproval !== undefined) fields.push("require_issue_approval");
+ if (settings.requirePlanCheckNoError !== undefined) fields.push("require_plan_check_no_error");
+ await this.request("PATCH", `/v1/${project}?update_mask=${fields.join(",")}`, settings);
+ }
+
+ async getProject(project: string): Promise<Record<string, unknown>> {
+ return this.request("GET", `/v1/${project}`);
+ }
+
+ // Review config
+ async getReviewConfig(name: string): Promise<{ name: string; rules: { type: string; level: string; engine: string; payload: string }[] }> {
+ return this.request("GET", `/v1/${name}`);
+ }
+
+ async updateReviewConfigRuleLevel(configName: string, ruleType: string, engine: string, newLevel: string): Promise<void> {
+ const config = await this.getReviewConfig(configName);
+ for (const rule of config.rules) {
+ if (rule.type === ruleType && rule.engine === engine) {
+ rule.level = newLevel;
+ break;
+ }
+ }
+ await this.request("PATCH", `/v1/${configName}?update_mask=rules`, { rules: config.rules });
+ }
+
+ // Multi-user helper
+ static async asUser(baseURL: string, email: string, password: string): Promise<BytebaseApiClient> {
+ const client = new BytebaseApiClient({ baseURL, credentials: { email, password } });
+ await client.login(email, password);
+ return client;
+ }
}
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts
new file mode 100644
index 0000000000..ff81077ba9
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts
@@ -0,0 +1,165 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+let issueName: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let shouldSkip = false;
+let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Capture both settings before mutating.
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+
+ // Require approval so the approval flow is generated; disable plan-check gate
+ // so the SQL check result doesn't block us independently.
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: true,
+ requirePlanCheckNoError: false,
+ });
+
+ // Unique column name avoids collisions across runs.
+ const columnName = `e2e_approval_${Date.now()}`;
+ const sheetName = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
+ );
+
+ const specId = `spec-${Date.now()}`;
+ const plan = await env.api.createPlan(
+ env.project,
+ `E2E Approval Blocker Test ${Date.now()}`,
+ [{ id: specId, targets: [env.database], sheet: sheetName }]
+ );
+ planId = plan.name.split("/").pop()!;
+
+ const issue = await env.api.createIssue(
+ env.project,
+ "E2E Approval Blocker",
+ plan.name
+ );
+ issueName = issue.name;
+
+ // Run plan checks — this triggers SQL classification which drives the
+ // approval flow generation. Without this call the approvalStatus may
+ // stay "SKIPPED" (no matching rule) rather than becoming "PENDING".
+ await env.api.runPlanChecks(plan.name);
+
+ // Wait for the approval flow to reach PENDING. If it instead reaches
+ // SKIPPED (no approval rule matched), the suite is skipped gracefully
+ // so it doesn't produce false failures in environments without the
+ // required policy.
+ const deadline = Date.now() + 30_000;
+ let lastStatus = "";
+ while (Date.now() < deadline) {
+ const freshIssue = await env.api.getIssue(issueName);
+ lastStatus = freshIssue.approvalStatus;
+ if (lastStatus === "PENDING" || lastStatus === "SKIPPED" || lastStatus === "APPROVED") break;
+ await new Promise((resolve) => setTimeout(resolve, 1000));
+ }
+
+ if (lastStatus === "SKIPPED" || lastStatus === "APPROVED") {
+ // No approval rule matched, or auto-approved — skip this blocker suite.
+ shouldSkip = true;
+ return;
+ }
+
+ if (lastStatus !== "PENDING") {
+ throw new Error(
+ `Timed out waiting for approvalStatus "PENDING" on issue "${issueName}"; last status: "${lastStatus}"`
+ );
+ }
+
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+ // Restore both settings to the values captured before the test mutated them.
+ await env.api
+ .updateProjectSettings(env.project, originalSettings)
+ .catch((err: unknown) => {
+ console.warn(
+ `afterAll updateProjectSettings: ${err instanceof Error ? err.message : err}`
+ );
+ });
+});
+
+test.describe("Plan Detail: Approval Blocker", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("deploy section shows approval pending when required", async () => {
+ test.skip(shouldSkip, "No approval rule matched — environment lacks required policy");
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ // The deploy section should surface the approval gate message.
+ const deployArea = page.getByText("Deploy").locator("..");
+ await expect(
+ deployArea.getByText(/Approval flow must be done/i)
+ ).toBeVisible({ timeout: 15_000 });
+
+ // A "Pending" indicator should also be visible somewhere in the deploy area.
+ await expect(deployArea.getByText(/Pending/i).first()).toBeVisible();
+ });
+
+ test("no manual create rollout button when approval is pending and required", async () => {
+ test.skip(shouldSkip, "No approval rule matched");
+ // The button must NOT exist (or must be hidden) when approval is blocking.
+ // Use a short timeout — if it's present the test fails fast.
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 3_000,
+ });
+ });
+
+ test("sidebar shows Under review", async () => {
+ test.skip(shouldSkip, "No approval rule matched");
+ await expect(
+ page.getByRole("complementary").getByText(/Under review/i)
+ ).toBeVisible();
+ });
+
+ test("after approving both steps, deploy section updates", async () => {
+ test.skip(shouldSkip, "No approval rule matched");
+ // First approval: admin (Project Owner / first approver in the flow).
+ await env.api.approveIssue(issueName);
+
+ // Second approval: DBA role.
+ const dbaApi = await BytebaseApiClient.asUser(
+ env.baseURL,
+ "12345678"
+ );
+ await dbaApi.approveIssue(issueName);
+
+ // Reload so the browser picks up the updated approval state.
+ await page.reload();
+ await page.waitForLoadState("networkidle");
+
+ // After both approvals, the sidebar should reflect "Approved" or the page
+ // may show a rollout (auto-created if checks also passed). Either way,
+ // the approval is no longer "Pending".
+ await expect(
+ page.getByText(/Approved|Approval is complete/i).first()
+ ).toBeVisible({ timeout: 15_000 });
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts
new file mode 100644
index 0000000000..2112a7823b
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts
@@ -0,0 +1,205 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let shouldSkip = false;
+let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+
+// Counts captured by test 1, consumed by test 2
+let spec1SuccessCount = 0;
+let spec2SuccessCount = 0;
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Capture and set permissive settings
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ const ts = Date.now();
+
+ // Create two sheets with distinct SQL
+ const sheetA = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9160a_${ts} TEXT;`
+ );
+ const sheetB = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9160b_${ts} INTEGER NOT NULL DEFAULT 0;`
+ );
+
+ // Discover a second database on a different instance
+ const { instances } = await env.api.listInstances();
+ // env.instance is like "instances/test-sample-instance" — extract its name
+ const primaryInstanceName = env.instance; // e.g. "instances/prod-sample-instance"
+
+ let secondDatabase: string | null = null;
+
+ for (const inst of instances) {
+ if (inst.name === primaryInstanceName) continue;
+ if (inst.name.includes("bytebase-meta")) continue;
+ if (inst.engine !== "POSTGRES") continue;
+ try {
+ const { databases } = await env.api.listDatabases(inst.name);
+ // Only pick databases that belong to our project
+ const candidate = databases.find((db) => db.project === env.project);
+ if (candidate) {
+ secondDatabase = candidate.name;
+ break;
+ }
+ } catch {
+ // Instance unreachable — skip
+ }
+ }
+
+ if (!secondDatabase) {
+ // No second instance/database available — flag to skip all tests
+ shouldSkip = true;
+ return;
+ }
+
+ // Create plan with 2 specs:
+ // Spec A — single target (env.database), sheet A
+ // Spec B — two targets (env.database + secondDatabase, overlapping), sheet B
+ const plan = await env.api.createPlan(
+ env.project,
+ `E2E BYT-9160 Check Consistency ${ts}`,
+ [
+ { id: `spec-a-${ts}`, targets: [env.database], sheet: sheetA },
+ {
+ id: `spec-b-${ts}`,
+ targets: [env.database, secondDatabase],
+ sheet: sheetB,
+ },
+ ]
+ );
+ planId = plan.name.split("/").pop()!;
+
+ // Create issue so the plan gets a full lifecycle context
+ await env.api.createIssue(env.project, "E2E BYT-9160 Check Consistency", plan.name);
+
+ // Run plan checks
+ await env.api.runPlanChecks(plan.name);
+
+ // Poll until plan checks are DONE (max 60 s).
+ // getPlanCheckRun returns 404 before the first run completes — catch and retry.
+ let checksDone = false;
+ const deadline = Date.now() + 60_000;
+ while (Date.now() < deadline) {
+ try {
+ const checkRun = await env.api.getPlanCheckRun(plan.name);
+ if (checkRun.status === "DONE") { checksDone = true; break; }
+ } catch {
+ // Check run not created yet — retry
+ }
+ await new Promise((r) => setTimeout(r, 2000));
+ }
+ if (!checksDone) {
+ throw new Error(`Plan checks did not reach DONE within 60s for ${plan.name}`);
+ }
+
+ // Open the shared browser context
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
+ await sharedContext?.close();
+});
+
+test.describe("Plan Detail: Check Count Consistency (BYT-9160)", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("spec #2 has more check results than spec #1", async () => {
+ test.skip(shouldSkip, "No second database available for multi-spec plan");
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ // Helper: read the success count digit next to "Success" text in the inline Checks h3 area.
+ // Uses evaluate to find the count reliably regardless of nesting.
+ const readInlineSuccessCount = async (): Promise<number> => {
+ return page.evaluate(() => {
+ // Find all elements with text "Success" that are near an h3 "Checks"
+ const all = Array.from(document.querySelectorAll("*"));
+ for (const el of all) {
+ if (el.children.length > 0) continue; // leaf nodes only
+ if (el.textContent?.trim() !== "Success") continue;
+ // Walk siblings and parent siblings to find a digit
+ const parent = el.parentElement;
+ if (!parent) continue;
+ const siblings = Array.from(parent.querySelectorAll("*"));
+ for (const s of siblings) {
+ if (s === el) continue;
+ const t = s.textContent?.trim();
+ if (t && /^\d+$/.test(t)) {
+ // Check that this is near an h3 "Checks" (within 5 parents)
+ let node: Element | null = parent;
+ for (let i = 0; i < 5 && node; i++) {
+ if (node.querySelector("h3")?.textContent?.includes("Checks")) {
+ return parseInt(t, 10);
+ }
+ node = node.parentElement;
+ }
+ }
+ }
+ }
+ return 0;
+ });
+ };
+
+ // Spec #1 is already selected
+ await expect(page.getByText("Success").first()).toBeVisible({ timeout: 15_000 });
+ spec1SuccessCount = await readInlineSuccessCount();
+ expect(spec1SuccessCount).toBeGreaterThan(0);
+
+ // Click spec #2 tab. Use exact match to avoid matching "Issue #..." text
+ // (issue numbers in demo are 100+, so "#2" is unambiguous).
+ await page.getByText("#2", { exact: true }).first().click();
+ await page.waitForLoadState("networkidle");
+ await expect(page.getByText("Success").first()).toBeVisible({ timeout: 10_000 });
+ spec2SuccessCount = await readInlineSuccessCount();
+
+ // Spec #2 targets two databases, so it must produce more check results
+ expect(spec2SuccessCount).toBeGreaterThan(0);
+ expect(spec2SuccessCount).toBeGreaterThan(spec1SuccessCount);
+ });
+
+ // BYT-9160: sidebar always shows the last spec's counts regardless of which
+ // spec tab is selected. Mark fixme until the bug is resolved.
+ test.fixme("sidebar check counts match selected spec #1 (BYT-9160)", async () => {
+ // Select spec #1
+ await planPage.specTab(1).click();
+ await expect(planPage.inlineCheckCount("Success")).toBeVisible({ timeout: 10_000 });
+
+ const sidebarRaw = await planPage.sidebarCheckCount("Success").textContent();
+ const inlineRaw = await planPage.inlineCheckCount("Success").textContent();
+
+ const sidebarCount = parseInt(sidebarRaw ?? "0", 10);
+ const inlineCount = parseInt(inlineRaw ?? "0", 10);
+
+ // Sidebar should reflect spec #1 — not spec #2's larger count.
+ // This assertion FAILS because sidebar shows spec #2's count (the bug).
+ expect(sidebarCount).toBe(inlineCount);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts
new file mode 100644
index 0000000000..bce0328efc
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts
@@ -0,0 +1,164 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ const ts = Date.now();
+
+ const sheet = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9161_${ts} TEXT;`
+ );
+
+ const plan = await env.api.createPlan(
+ env.project,
+ `E2E BYT-9161 Section Preservation ${ts}`,
+ [{ id: `spec-${ts}`, targets: [env.database], sheet }]
+ );
+ planId = plan.name.split("/").pop()!;
+
+ await env.api.createIssue(env.project, `E2E BYT-9161 Section Preservation ${ts}`, plan.name);
+
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ await planPage.createRolloutWithBypass();
+ await page.waitForLoadState("networkidle");
+});
+
+test.afterAll(async () => {
+ await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
+ await sharedContext?.close();
+});
+
+test.describe("Plan Detail: Section Expansion Preservation (BYT-9161)", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("sections expanded after rollout creation", async () => {
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
+ });
+
+ test("clicking View details preserves section state", async () => {
+ // Open the task detail panel via the "View details" link in the Deploy section
+ const viewDetailsLink = page
+ .getByRole("link", { name: "View details" })
+ .first();
+ if (await viewDetailsLink.isVisible({ timeout: 5_000 }).catch(() => false)) {
+ await viewDetailsLink.click();
+ await page.waitForLoadState("networkidle");
+ } else {
+ // Fallback: look for any clickable detail trigger in the deploy area
+ const detailButton = page
+ .getByText("View details")
+ .first();
+ if (await detailButton.isVisible({ timeout: 3_000 }).catch(() => false)) {
+ await detailButton.click();
+ await page.waitForLoadState("networkidle");
+ }
+ }
+
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+
+ test("closing detail panel preserves section state", async () => {
+ // Close the detail panel using Escape first; fall back to a close button
+ const closeButton = page
+ .getByRole("button", { name: "Close" })
+ .or(page.locator("[aria-label='Close']"))
+ .first();
+
+ if (await closeButton.isVisible({ timeout: 2_000 }).catch(() => false)) {
+ await closeButton.click();
+ } else {
+ await page.keyboard.press("Escape");
+ }
+ // Wait for the drawer to fully close. If the drawer class doesn't match,
+ // reload the page to guarantee a clean state rather than silently proceeding.
+ const drawerHidden = await expect(page.locator(".n-drawer-container"))
+ .toBeHidden({ timeout: 5_000 })
+ .then(() => true)
+ .catch(() => false);
+ if (!drawerHidden) {
+ // Drawer didn't close — reload to ensure section state assertions are meaningful
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ }
+
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+
+ test("collapsing one section doesn't affect others", async () => {
+ // Reload page to guarantee clean state (no lingering drawers from previous test)
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ // Collapse the Changes section
+ const changesToggle = planPage.getSectionToggle("Changes");
+ if (await changesToggle.isVisible({ timeout: 3_000 }).catch(() => false)) {
+ const text = await changesToggle.textContent();
+ if (text?.includes("Hide")) {
+ await changesToggle.click();
+ await expect(changesToggle).toHaveText(/Show details/, { timeout: 5_000 });
+ }
+ }
+
+ expect(await planPage.isSectionExpanded("Changes")).toBe(false);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
+
+ // Re-expand Changes so subsequent tests start from a consistent state
+ const changesToggleAfter = planPage.getSectionToggle("Changes");
+ if (await changesToggleAfter.isVisible({ timeout: 3_000 }).catch(() => false)) {
+ const text = await changesToggleAfter.textContent();
+ if (text?.includes("Show")) {
+ await changesToggleAfter.click();
+ await expect(changesToggleAfter).toHaveText(/Hide details/, { timeout: 5_000 });
+ }
+ }
+ });
+
+ test("navigation away and back preserves section state", async () => {
+ // Navigate to the issues list
+ await page.goto(`${env.baseURL}/projects/${projectId}/issues`);
+ await page.waitForLoadState("networkidle");
+
+ // Navigate back to the plan
+ await planPage.goto(projectId, planId);
+ await page.waitForLoadState("networkidle");
+
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts
new file mode 100644
index 0000000000..9139fc86c4
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts
@@ -0,0 +1,168 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+let issueName: string;
+let planURL: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let shouldSkip = false;
+let originalRuleLevel = "WARNING";
+let originalProjectSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+let planPage: PlanDetailPage;
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Capture original project settings before mutating.
+ const project = await env.api.getProject(env.project);
+ originalProjectSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+
+ // Enable approval + plan-check gate
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: true,
+ requirePlanCheckNoError: true,
+ });
+
+ // Capture original rule level before mutating, so afterAll restores the exact value.
+ const config = await env.api.getReviewConfig("reviewConfigs/sql-review-sample-policy");
+ const rule = config.rules.find((r) => r.type === "COLUMN_NO_NULL" && r.engine === "POSTGRES");
+ originalRuleLevel = rule?.level ?? "WARNING";
+
+ // Upgrade COLUMN_NO_NULL to ERROR so checks will fail
+ await env.api.updateReviewConfigRuleLevel(
+ "reviewConfigs/sql-review-sample-policy",
+ "COLUMN_NO_NULL",
+ "POSTGRES",
+ "ERROR"
+ );
+
+ // Create sheet — nullable TEXT column triggers COLUMN_NO_NULL ERROR
+ const columnName = `e2e_checks_${Date.now()}`;
+ const sheetName = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
+ );
+
+ // Create the plan
+ const specId = `spec-${Date.now()}`;
+ const plan = await env.api.createPlan(env.project, `E2E Checks Blocker Test ${Date.now()}`, [
+ { id: specId, targets: [env.database], sheet: sheetName },
+ ]);
+ planId = plan.name.split("/").pop()!;
+ planURL = `${env.baseURL}/projects/${projectId}/plans/${planId}`;
+
+ // Create an issue backed by the plan
+ const issue = await env.api.createIssue(env.project, "E2E Checks Blocker", plan.name);
+ issueName = issue.name;
+
+ // Run plan checks to trigger the SQL review errors
+ await env.api.runPlanChecks(plan.name);
+
+ // Poll until approval is no longer CHECKING
+ const deadline = Date.now() + 60_000;
+ let approvalStatus = "CHECKING";
+ while (Date.now() < deadline) {
+ const issueData = await env.api.getIssue(issueName);
+ approvalStatus = issueData.approvalStatus;
+ if (approvalStatus !== "CHECKING") break;
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+
+ // If PENDING, approve both steps (Project Owner + DBA)
+ if (approvalStatus === "PENDING") {
+ await env.api.approveIssue(issueName);
+ const dbaApi = await BytebaseApiClient.asUser(env.baseURL, "[email protected]", "12345678");
+ await dbaApi.approveIssue(issueName);
+ }
+
+ // Verify approval is APPROVED. If the environment has no matching approval
+ // rule, status may be SKIPPED — skip the suite rather than false-fail.
+ const finalIssue = await env.api.getIssue(issueName);
+ if (finalIssue.approvalStatus === "SKIPPED") {
+ shouldSkip = true;
+ return;
+ }
+ if (finalIssue.approvalStatus !== "APPROVED") {
+ throw new Error(
+ `Expected approvalStatus "APPROVED" but got "${finalIssue.approvalStatus}" on issue "${issueName}"`
+ );
+ }
+
+ // Open the shared browser context
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ // Restore project settings to the values captured before the test mutated them.
+ await env.api.updateProjectSettings(env.project, originalProjectSettings);
+
+ // Restore COLUMN_NO_NULL rule to the level captured before the test mutated it.
+ await env.api.updateReviewConfigRuleLevel(
+ "reviewConfigs/sql-review-sample-policy",
+ "COLUMN_NO_NULL",
+ "POSTGRES",
+ originalRuleLevel
+ );
+
+ await sharedContext?.close();
+});
+
+test.describe("Plan Detail: Checks Blocker (BYT-9159)", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("checks show ERROR result", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED — environment lacks matching rule");
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ await expect(page.getByText(/Error|Failed/i).first()).toBeVisible({ timeout: 15_000 });
+ });
+
+ test("approval shows Done", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED");
+ await expect(
+ page.getByText(/Approved|Done/i).first()
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("deploy section says checks are blocking", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED");
+ await expect(page.getByText("Failed checks are blocking")).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("no manual create rollout button when checks required and failed (BYT-9159)", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED");
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({ timeout: 3_000 });
+ });
+
+ test("button appears after disabling check requirement", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED");
+ await env.api.updateProjectSettings(env.project, { requirePlanCheckNoError: false });
+
+ await page.goto(planURL);
+ await page.waitForLoadState("networkidle");
+ await planPage.dismissModals();
+
+ await expect(planPage.manualCreateRolloutButton).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("deploy text confirms checks are optional", async () => {
+ test.skip(shouldSkip, "Approval resolved to SKIPPED");
+ await expect(page.getByText(/Failed checks won't block/i)).toBeVisible({ timeout: 10_000 });
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts
new file mode 100644
index 0000000000..26c8cf233a
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts
@@ -0,0 +1,113 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Capture and set permissive project settings
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ // Create a dedicated sheet for this test
+ const columnName = `e2e_lifecycle_${Date.now()}`;
+ const sheetName = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
+ );
+
+ // Create the plan
+ const specId = `spec-${Date.now()}`;
+ const plan = await env.api.createPlan(env.project, `E2E Lifecycle Test ${Date.now()}`, [
+ { id: specId, targets: [env.database], sheet: sheetName },
+ ]);
+ planId = plan.name.split("/").pop()!;
+
+ // Create an issue backed by the plan (required to drive the lifecycle UI)
+ await env.api.createIssue(env.project, "E2E Lifecycle", plan.name);
+
+ // Open the shared browser context
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
+ await sharedContext?.close();
+});
+
+test.describe("Plan Detail: Lifecycle + Section Preservation", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("navigate to plan and see all three phases", async () => {
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ await expect(planPage.changesSection).toBeVisible();
+ await expect(planPage.reviewSection).toBeVisible();
+ await expect(planPage.deploySection).toBeVisible();
+ });
+
+ test("sections are expanded by default", async () => {
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+
+ test("create rollout with bypass", async () => {
+ await planPage.createRolloutWithBypass();
+ await expect(page.getByText(/Not started|Deploying/i).first()).toBeVisible({ timeout: 15_000 });
+ });
+
+ test("sections remain expanded after rollout creation (BYT-9161)", async () => {
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+
+ test("run task and wait for completion", async () => {
+ await planPage.runTask();
+ await expect(page.getByText("Done").first()).toBeVisible({ timeout: 30_000 });
+ });
+
+ test("sidebar shows Done status after completion", async () => {
+ await expect(page.getByRole("complementary").getByText(/Done/i).first()).toBeVisible();
+ });
+
+ test("state preserved after navigation away and back", async () => {
+ await page.goto(`${env.baseURL}/projects/${projectId}/issues`);
+ await page.waitForLoadState("networkidle");
+
+ await planPage.goto(projectId, planId);
+ await expect(planPage.deploySection).toBeVisible();
+ });
+
+ test("sections still expanded after navigation (BYT-9161)", async () => {
+ // After task completion phases may auto-collapse — either expanded or
+ // the toggle is absent (section is always open). Both are acceptable.
+ const changesExpanded = await planPage.isSectionExpanded("Changes");
+ // isSectionExpanded returns true when toggle is absent (no collapse control)
+ // so any truthy result — or explicit true — satisfies the regression check.
+ expect(changesExpanded).toBe(true);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts
new file mode 100644
index 0000000000..fe32d2d87a
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts
@@ -0,0 +1,92 @@
+import { test, expect, type Page, type BrowserContext } from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Capture and set permissive project settings
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ // Create a sheet targeting a nonexistent table — will fail at execution time
+ const tableName = `nonexistent_table_e2e_${Date.now()}`;
+ const sheetName = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE ${tableName} ADD COLUMN c1 TEXT;`
+ );
+
+ // Create the plan
+ const specId = `spec-${Date.now()}`;
+ const plan = await env.api.createPlan(env.project, `E2E Task Failure Test ${Date.now()}`, [
+ { id: specId, targets: [env.database], sheet: sheetName },
+ ]);
+ planId = plan.name.split("/").pop()!;
+
+ // Create an issue backed by the plan (required to drive the lifecycle UI)
+ await env.api.createIssue(env.project, "E2E Task Failure", plan.name);
+
+ // Open the shared browser context
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
+ await sharedContext?.close();
+});
+
+test.describe("Plan Detail: Task Failure (CUJ 4)", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("navigate and create rollout", async () => {
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ await planPage.createRolloutWithBypass();
+ await expect(page.getByText(/Not started|Deploying/i).first()).toBeVisible({ timeout: 15_000 });
+ });
+
+ test("run task that will fail", async () => {
+ await planPage.runTask();
+ await expect(page.getByText("Failed").first()).toBeVisible({ timeout: 30_000 });
+ });
+
+ test("task shows Failed status", async () => {
+ await expect(page.getByText("Failed").first()).toBeVisible();
+ });
+
+ test("Retry button is visible", async () => {
+ await expect(planPage.retryButton).toBeVisible();
+ });
+
+ test("sidebar shows Failed", async () => {
+ await expect(page.getByRole("complementary").getByText("Failed").first()).toBeVisible();
+ });
+
+ test("sections remain expanded after failure (BYT-9161)", async () => {
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ expect(await planPage.isSectionExpanded("Review")).toBe(true);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
new file mode 100644
index 0000000000..c46e0884d5
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
@@ -0,0 +1,117 @@
+import { expect, type Page, type Locator } from "@playwright/test";
+
+export class PlanDetailPage {
+ readonly page: Page;
+ readonly baseURL: string;
+
+ readonly changesSection: Locator;
+ readonly reviewSection: Locator;
+ readonly deploySection: Locator;
+ readonly manualCreateRolloutButton: Locator;
+ readonly bypassWarningsCheckbox: Locator;
+ readonly confirmRolloutButton: Locator;
+ readonly retryButton: Locator;
+
+ constructor(page: Page, baseURL: string) {
+ this.page = page;
+ this.baseURL = baseURL;
+
+ this.changesSection = page.getByText("Changes").first();
+ this.reviewSection = page.getByText("Review").first();
+ this.deploySection = page.getByText("Deploy").first();
+ this.manualCreateRolloutButton = page.getByRole("button", { name: "Manually create rollout" });
+ this.bypassWarningsCheckbox = page.getByRole("checkbox", { name: "Bypass warnings" });
+ this.confirmRolloutButton = page.getByRole("dialog").getByRole("button", { name: "Confirm" });
+ this.retryButton = page.getByRole("button", { name: "Retry" });
+ }
+
+ async goto(projectId: string, planId: string) {
+ await this.page.goto(`${this.baseURL}/projects/${projectId}/plans/${planId}`);
+ await this.page.waitForLoadState("networkidle");
+ }
+
+ async dismissModals() {
+ await this.page.evaluate(() => {
+ localStorage.setItem(
+ "bb.release",
+ JSON.stringify({
+ ignoreRemindModalTillNextRelease: true,
+ nextCheckTs: Date.now() + 86400000,
+ })
+ );
+ });
+ const dismiss = this.page.getByRole("button", { name: "Dismiss" });
+ if (await dismiss.isVisible({ timeout: 2000 }).catch(() => false)) {
+ await dismiss.click();
+ }
+ }
+
+ async createRolloutWithBypass() {
+ await this.manualCreateRolloutButton.click();
+ await this.bypassWarningsCheckbox.check();
+ // Arm the response waiter BEFORE clicking so a fast response isn't missed.
+ const responsePromise = this.page.waitForResponse(
+ (r) => r.url().includes("Rollout") && r.status() < 400
+ );
+ await this.confirmRolloutButton.click();
+ await responsePromise;
+ }
+
+ async runTask() {
+ // Match only buttons with exact text "Run" (not "Run check", "Run Tasks").
+ // Use getByRole with exact name to avoid substring matches.
+ const enabledRun = this.page
+ .getByRole("button", { name: "Run", exact: true })
+ .and(this.page.locator("button:not([disabled])"))
+ .last();
+ await expect(enabledRun).toBeVisible({ timeout: 15_000 });
+ await enabledRun.click();
+ const confirmDialog = this.page.getByRole("dialog").filter({ hasText: "Run task" });
+ await confirmDialog.getByRole("button", { name: "Run" }).click();
+ }
+
+ getSectionToggle(sectionName: string): Locator {
+ return this.page
+ .getByText(sectionName, { exact: true })
+ .first()
+ .locator("..")
+ .getByText(/Hide details|Show details/)
+ .first();
+ }
+
+ async isSectionExpanded(sectionName: string): Promise<boolean> {
+ const toggle = this.getSectionToggle(sectionName);
+ if (await toggle.isVisible({ timeout: 1000 }).catch(() => false)) {
+ const text = await toggle.textContent();
+ return text?.includes("Hide") ?? false;
+ }
+ return true;
+ }
+
+ specTab(n: number): Locator {
+ return this.page.getByText("Changes").locator("..").getByText(`#${n}`).first();
+ }
+
+ // Returns the count number for the given status (Warning/Success/Error)
+ // in the inline Checks area (h3 level, not sidebar h4).
+ inlineCheckCount(status: string): Locator {
+ return this.page
+ .getByRole("heading", { name: "Checks", level: 3 })
+ .locator("../..")
+ .getByText(status)
+ .locator("..")
+ .getByText(/^\d+$/);
+ }
+
+ // Returns the count number for the given status (Warning/Success/Error)
+ // in the sidebar Checks area (h4 level).
+ sidebarCheckCount(status: string): Locator {
+ return this.page
+ .getByRole("complementary")
+ .getByRole("heading", { name: "Checks", level: 4 })
+ .locator("..")
+ .getByText(status)
+ .locator("..")
+ .getByText(/^\d+$/);
+ }
+}