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(e2e): AIO plan-detail review section suite + post-merge spec repairs (#20703)
zchpeter89dd9a2a25f3
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex dcccfc279e..d3a2cd375f 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -566,6 +566,27 @@ export class BytebaseApiClient {return this.request("POST", `/v1/${issueName}:approve`, {});}+ // Reject an issue's current approval step. The proto binds body:"*", so the+ // comment travels in the request body (RejectIssueRequest.comment). The new+ // Plan Detail review banner depends on this comment always existing.+ async rejectIssue(+ issueName: string,+ comment: string,+ ): Promise<{ approvalStatus: string }> {+ return this.request("POST", `/v1/${issueName}:reject`, {+ name: issueName,+ comment,+ });+ }++ // Re-request review after a rejection (restarts the approval flow without+ // changing the plan). Mirrors the rejection banner's inline action.+ async requestIssue(issueName: string): Promise<{ approvalStatus: string }> {+ return this.request("POST", `/v1/${issueName}:request`, {+ name: issueName,+ });+ }+// Project settingsasync updateProjectSettings(project: string,diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.tsindex d3d194617c..f8f2b0d900 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts@@ -4,11 +4,15 @@// - WARNING-level rule produces an inline warning count but does NOT// block rollout creation (auto-rollout still happens).// - ERROR-level rule with `requirePlanCheckNoError=true` blocks the-// auto-rollout with NO "Manually create rollout" button; relaxing the-// gate (requirePlanCheckNoError=false) reveals the manual-create button.-// - Multi-spec plans: smoke test that each spec tab is selectable and-// renders an inline check summary (BYT-9160 context; NOT a strict-// regression lock — see the in-test comment).+// auto-rollout; the Review readiness footer reports "Review approved, but+// plan checks failed" and NO "Manually create rollout" button is offered.+// Relaxing the gate (requirePlanCheckNoError=false) lets the user bypass+// via the footer's "Bypass and deploy" action (the old DEPLOY manual+// button is GitOps-only now — AIO review section, 3.19.1).+// - Multi-spec plans: check counts render PLAN-WIDE (BYT-9160 resolution —+// the per-spec sidebar was removed), and switching spec tabs shows only the+// selected spec's statement (BYT-9794 — a duplicate-key regression fixed by+// #20662; guarded here so it can't re-regress).//// Each test owns its review config + project TagPolicy via API, and// cleans up in afterEach so a sibling test doesn't inherit state.@@ -172,8 +176,16 @@ test.describe("ERROR-level review rule with requirePlanCheckNoError=true", () =>// "Manually create rollout" button is offered — the user must// either fix the SQL or relax the gate.// - When the gate is relaxed (requirePlanCheckNoError=false), the- // manual create button DOES appear so the user can bypass the- // failed checks intentionally.+ // manual deploy path appears so the user can bypass the failed+ // checks intentionally.+ //+ // NOTE (AIO plan review section, 3.19.1): the manual "Manually create+ // rollout" button was REMOVED from DEPLOY for issue-backed plans and is+ // now GitOps-only (PlanDetailDeployFuture.tsx). For issue-backed plans the+ // single manual path is the Review section's readiness-footer "Bypass and+ // deploy" action (ReviewReadinessFooter.tsx). The gate-off test below was+ // updated to assert that new path; the gate-on test is unchanged (DEPLOY+ // still explains the block and offers no manual button).// Both halves are covered here so a regression on either side fails// loudly.@@ -196,17 +208,23 @@ test.describe("ERROR-level review rule with requirePlanCheckNoError=true", () =>await expect(planPage.checksSummary()).toContainText("Error", {timeout: 15_000,});- // DEPLOY explains the block.+ // The blocking status moved from DEPLOY to the Review readiness footer (AIO+ // review section): no approval rule → SKIPPED, plus failed checks → the+ // footer reads "Review approved, but plan checks failed". The old DEPLOY+ // "Failed checks are blocking automatic rollout creation" helper text was+ // removed with the DeployFuture dedup.+ await planPage.expandSection("Review");await expect(- page.getByText(/Failed checks are blocking/i).first(),+ page.getByText("Review approved, but plan checks failed"),).toBeVisible({ timeout: 10_000 });- // No manual create path is offered in this state.+ // No manual create path is offered in this state (the gate is mandatory, so+ // the footer's bypass confirm sheet would hard-block deploy anyway).await expect(planPage.manualCreateRolloutButton).not.toBeVisible({timeout: 3_000,});});- test("relaxing the gate (requirePlanCheckNoError=false) reveals the manual-create button", async () => {+ test("relaxing the gate (requirePlanCheckNoError=false) reveals the readiness-footer bypass action", async () => {await attachReviewConfig("ERROR");// Gate OFF — failed checks no longer block; user can bypass.await env.api.updateProjectSettings(env.project, {@@ -225,70 +243,146 @@ test.describe("ERROR-level review rule with requirePlanCheckNoError=true", () =>await expect(planPage.checksSummary()).toContainText("Error", {timeout: 15_000,});- await expect(planPage.manualCreateRolloutButton).toBeVisible({+ // No approval rule (seedTestData clears WORKSPACE_APPROVAL) →+ // approvalStatus SKIPPED; ERROR checks + gate OFF → the Review readiness+ // footer is "Review approved, but plan checks failed" and offers the+ // single manual path: "Bypass and deploy". The old "Manually create+ // rollout" button no longer exists for issue-backed plans.+ await planPage.expandSection("Review");+ await expect(+ planPage.page.getByText("Review approved, but plan checks failed"),+ ).toBeVisible({ timeout: 10_000 });+ await expect(planPage.bypassAndDeployAction).toBeVisible({timeout: 10_000,});+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({+ timeout: 3_000,+ });});});-test.describe("Per-spec scoping (BYT-9160)", () => {- // BYT-9160 was a per-spec rendering bug: the right sidebar always showed- // the LAST spec's check counts regardless of which spec tab was selected.- // The React migration REMOVED that right sidebar. Per-spec data now lives- // in the CHANGES editor (the statement + inline advice markers, scoped to- // the selected spec via planCheckRunListForSpec), while check COUNTS are- // shown PLAN-WIDE (PlanDetailAggregateChecks: one Success/Warning/Error- // summary that opens a results drawer). There is no per-spec count to- // compare anymore, so the surviving contract is: selecting a spec shows- // THAT spec's statement, not a stale sibling's. The two specs carry- // uniquely-stamped columns, so the BYT-9160-class regression (stale- // per-spec content on tab switch) fails loudly.- test("each spec tab shows its own statement; checks render plan-wide", async () => {+test.describe("Per-spec check counts render plan-wide (BYT-9160)", () => {+ // BYT-9160 (original): the per-spec right SIDEBAR always showed the LAST+ // spec's check counts regardless of which spec tab was selected. The React+ // migration REMOVED that sidebar; check counts are now a single PLAN-WIDE+ // aggregate summary (PlanDetailAggregateChecks). That UI element no longer+ // exists, so the original bug cannot recur. This test locks the resolution:+ // the aggregate summary renders and stays present regardless of the selected+ // spec (it is plan-wide, not per-spec).+ //+ // NOTE: the separate contract "selecting a spec shows only THAT spec's+ // STATEMENT" is a *different* concern, guarded separately below (BYT-9794 —+ // a duplicate-key regression that stacked spec editors, fixed by #20662).+ test("the aggregate check summary stays plan-wide across spec switches", async () => {const ts = Date.now();- const colA = `e2e_spec_a_${ts}`;- const colB = `e2e_spec_b_${ts}`;- await createPlanAndWaitForChecks("E2E Per-Spec", [+ await createPlanAndWaitForChecks("E2E Plan-Wide Checks", [{id: `spec-a-${ts}`,targets: [env.database],- sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colA} TEXT;`,+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_pw_a_${ts} TEXT;`,},{id: `spec-b-${ts}`,targets: [env.database],- sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colB} TEXT;`,+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_pw_b_${ts} TEXT;`,},]);- // Expand CHANGES so the spec tabs + statement editor are reachable.await planPage.expandSection("Changes");- // Joined text of every mounted Monaco surface. The CHANGES statement- // editor renders only the SELECTED spec (PlanDetailStatementSection is- // driven by selectedSpec), so this reflects the active spec's statement.- const readStatement = (): Promise<string> =>- page.evaluate(() =>- Array.from(document.querySelectorAll('[role="code"]'))- .flatMap((c) => Array.from(c.querySelectorAll(".view-line")))- .map((l) => l.textContent ?? "")- .join("\n"),- );-- // Spec #1 selected: its statement shows; spec #2's does not.- await planPage.specTab(1).click();- await expect.poll(readStatement, { timeout: 15_000 }).toContain(colA);- expect(await readStatement()).not.toContain(colB);-- // Switching to spec #2 swaps the CHANGES content to spec #2's statement.- // The BYT-9160 regression would leave spec #1's content rendered here.- await planPage.specTab(2).click();- await expect.poll(readStatement, { timeout: 15_000 }).toContain(colB);- expect(await readStatement()).not.toContain(colA);-- // Check counts are now a single plan-wide summary (the per-spec sidebar- // is gone); confirm it renders.+ // The plan-wide aggregate summary renders (the removed per-spec sidebar+ // would have shown per-spec counts here instead).await expect(page.getByText("Success").first()).toBeVisible({timeout: 15_000,});++ // It is plan-wide: still present after switching specs (the BYT-9160+ // sidebar would have re-bound to / gone stale on the selected spec).+ await planPage.specTab(1).click();+ await expect(page.getByText("Success").first()).toBeVisible();+ await planPage.specTab(2).click();+ await expect(page.getByText("Success").first()).toBeVisible();});});++// Regression guard for BYT-9794 (distinct from BYT-9160's deleted sidebar):+// switching spec tabs used to leave the PREVIOUSLY-selected spec's statement+// editor mounted, so both specs' SQL stacked in CHANGES. Root cause: the+// spec-detail sections (TargetsSection / StatementSection / OptionsSection)+// each carried the SAME `key={selectedSpec.id}` — duplicate React keys on+// siblings broke reconciliation, so the old sections weren't removed on+// switch. Fixed by #20662, which consolidated them under a single keyed+// wrapper `<div key={selectedSpec.id}>`. This was a test.fail() lock until the+// 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)",+ () => {+ test(+ "only the selected spec's statement is shown in CHANGES after switching tabs",+ 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;`,+ },+ ]);++ await planPage.expandSection("Changes");++ // Read ONLY the CHANGES section's statement editors — the [role=code]+ // Monaco surfaces between the "Changes" and "Deploy" phase labels. This+ // deliberately excludes the DEPLOY task-statement preview (which shows+ // the first task's SQL and is independent of the spec tab), so the+ // assertion is purely about the CHANGES section leaking a stale editor.+ const readChangesStatements = (): Promise<string> =>+ page.evaluate(() => {+ const spans = Array.from(document.querySelectorAll("span"));+ const changesLabel = spans.find(+ (e) => e.textContent?.trim() === "Changes",+ );+ const deployLabel = spans.find(+ (e) => e.textContent?.trim() === "Deploy",+ );+ if (!changesLabel) return "";+ const FOLLOWING = Node.DOCUMENT_POSITION_FOLLOWING;+ const PRECEDING = Node.DOCUMENT_POSITION_PRECEDING;+ return Array.from(document.querySelectorAll('[role="code"]'))+ .filter(+ (c) =>+ !!(changesLabel.compareDocumentPosition(c) & FOLLOWING) &&+ (!deployLabel ||+ !!(deployLabel.compareDocumentPosition(c) & PRECEDING)),+ )+ .flatMap((c) => Array.from(c.querySelectorAll(".view-line")))+ .map((l) => l.textContent ?? "")+ .join("\n");+ });++ await planPage.specTab(1).click();+ await expect+ .poll(readChangesStatements, { timeout: 15_000 })+ .toContain(colA);++ await planPage.specTab(2).click();+ await expect+ .poll(readChangesStatements, { timeout: 15_000 })+ .toContain(colB);++ // Post-fix (#20662): spec #1's editor is unmounted on switch, so only+ // 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);+ },+ );+ },+);diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.tsnew file mode 100644index 0000000000..d2b76ddbd9--- /dev/null+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts@@ -0,0 +1,708 @@+// Plan detail — AIO Review section (the whole sub-area in one file).+//+// Covers the issue-backed review workflow that now lives inline on Plan Detail+// (spec: docs/superpowers/specs/2026-06-12-aio-plan-review-section-design.md).+// Per the e2e convention (AGENTS.md: one <feature>.spec.ts per sub-area, never+// split by fixture), every facet of the Review section lives here as its own+// describe block — review actions, the rollout-readiness footer, and the+// adaptive approval-flow renderer:+//+// Review actions / recovery / composer / timeline+// - Approval flow + Review action render while PENDING (CUJ A)+// - Approve via the Review popover → node green, action gone, rollout+// auto-creates (CUJ B)+// - Reject requires a comment; rejection banner + in-stream decision (CUJ C)+// - Creator re-requests review without changes (CUJ D)+// - Comment composer: draft survives collapse, post appends + re-collapses (CUJ E)+// - Long-history timeline fold (torn separator + Show all) (CUJ J)+// - Non-candidate sees no Review action but can still comment (permission boundary)+// - BYT-9746 guard: "(edited)" marker shows in place after an inline edit+//+// Rollout-readiness footer + bypass (readinessFooterState.ts)+// - Approved/skipped + failed checks → "Bypass and deploy" → confirm sheet →+// rollout created (CUJ F)+// - Waiting-review bypass link gated by requireIssueApproval (G1 mandatory+// hides it / G2 optional shows the muted link)+// - A mandatory project gate (requirePlanCheckNoError) hard-blocks the+// confirm-sheet Deploy (cannot be acknowledged away)+// - BYT-9745 guard: confirm-sheet REVIEW box shows the skip note for+// skipped-approval issues+//+// Approval-flow renderer (approvalFlowLayout.ts)+// - Long 5-step flow: constrained width folds approved/pending into chips+// while the current step stays named; narrow width renders the full+// vertical stepper with no chips (CUJ I)+//+// Each describe configures the project/workspace settings IT needs in its own+// beforeAll (approval rule, plan-check gate, review config), so the blocks are+// order-independent despite sharing the workspace-level WORKSPACE_APPROVAL+// setting. The file-level beforeAll only snapshots the originals + opens the+// shared browser; the file-level afterAll restores them.++import {+ test,+ expect,+ type Page,+ type BrowserContext,+} from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import { BytebaseApiClient } from "../framework/api-client";+import { signInBrowserAs } from "../framework/sign-in";+import { PlanDetailPage } from "./plan-detail.page";+import { seedReviewPlan, waitForApprovalStatus } from "./plan-helpers";++test.setTimeout(180_000);++let env: TestEnv & { api: BytebaseApiClient };+let projectId: string;++let sharedContext: BrowserContext;+let page: Page;+let planPage: PlanDetailPage;++let originalProjectSettings: {+ requireIssueApproval?: boolean;+ requirePlanCheckNoError?: boolean;+ allowSelfApproval?: boolean;+} = {};+let originalApproval: unknown = null;+const createdReviewConfigs: string[] = [];++const ONE_STEP_RULE = {+ source: "CHANGE_DATABASE",+ condition: { expression: "true" },+ template: {+ flow: { roles: ["roles/workspaceAdmin"] },+ title: "E2E Review One-Step",+ description: "Single-step workspaceAdmin approval",+ },+};++const FIVE_STEP_RULE = {+ source: "CHANGE_DATABASE",+ condition: { expression: "true" },+ template: {+ flow: {+ roles: [+ "roles/workspaceAdmin",+ "roles/workspaceDBA",+ "roles/projectOwner",+ "roles/projectDeveloper",+ "roles/projectReleaser",+ ],+ },+ title: "E2E Five-Step",+ description: "Five-step approval flow",+ },+};++async function goReview(planId: string): Promise<void> {+ await planPage.goto(projectId, planId);+ await planPage.dismissModals();+ await planPage.expandSection("Review");+}++// Configure a mandatory single/multi-step approval flow (the common case for+// the review-action + flow describes). Clears any review-config tag first so a+// prior describe's ERROR rule can't leak in. allowSelfApproval=true lets demo@+// (the issue creator) approve their own issue for single-admin tests.+async function setupApproval(rule: object): Promise<void> {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: true,+ requirePlanCheckNoError: false,+ allowSelfApproval: true,+ });+ await env.api.upsertSetting(+ "WORKSPACE_APPROVAL",+ { workspaceApproval: { rules: [rule] } },+ "value.workspace_approval",+ );+}++// Attach a single ERROR-level COLUMN_NO_NULL rule to the project so a nullable+// column trips it. Tracked in createdReviewConfigs for afterAll cleanup; each+// footer describe that uses it clears the tag in its own beforeAll first.+async function attachErrorConfig(): Promise<void> {+ const id = `e2e-review-err-${Date.now()}`;+ const cfg = await env.api.upsertReviewConfig(id, "E2E Review ERROR", [+ { type: "COLUMN_NO_NULL", level: "ERROR", engine: "POSTGRES" },+ ]);+ createdReviewConfigs.push(cfg.name);+ await env.api.upsertReviewConfigTag(env.project, cfg.name);+}++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);+ originalProjectSettings = {+ requireIssueApproval: !!project.requireIssueApproval,+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,+ allowSelfApproval: !!project.allowSelfApproval,+ };+ originalApproval = (await env.api.getSetting("WORKSPACE_APPROVAL"))?.value ?? null;++ sharedContext = await browser.newContext({+ storageState: ".auth/state.json",+ });+ page = await sharedContext.newPage();+ planPage = new PlanDetailPage(page, env.baseURL);+});++test.afterAll(async () => {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ for (const name of createdReviewConfigs) {+ await env.api.deleteReviewConfig(name).catch(() => {});+ }+ await env.api+ .updateProjectSettings(env.project, originalProjectSettings)+ .catch(() => {});+ await env.api+ .upsertSetting(+ "WORKSPACE_APPROVAL",+ originalApproval ?? { workspaceApproval: { rules: [] } },+ "value.workspace_approval",+ )+ .catch(() => {});+ await sharedContext?.close();+});++test.describe("Review action and approval flow (CUJ A)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review A",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_a_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("renders the approval flow with the current step and Review action", async () => {+ await expect(planPage.reviewBadge("Under review")).toBeVisible({+ timeout: 15_000,+ });+ // The current step: role name + a "Current" badge (never folds).+ await expect(page.getByText("Workspace Admin").first()).toBeVisible();+ await expect(page.getByText("Current", { exact: true })).toBeVisible();+ // The header Review action is offered to the candidate (admin).+ await expect(planPage.reviewButton).toBeVisible();+ });+});++test.describe("Approve via the Review popover (CUJ B)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review B",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_b_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("approving turns the badge to Approved and removes the Review action", async () => {+ await expect(planPage.reviewButton).toBeVisible({ timeout: 15_000 });+ await planPage.submitReview("Approve");+ // patchState updates the issue inline — badge flips, action disappears.+ await expect(planPage.reviewBadge("Approved")).toBeVisible({+ timeout: 15_000,+ });+ await expect(planPage.reviewButton).not.toBeVisible();+ // The reviewer's step turned green ("Approved by …").+ await planPage.expandSection("Review");+ await expect(page.getByText(/^Approved by /).first()).toBeVisible({+ timeout: 15_000,+ });+ });+});++test.describe("Reject requires a comment; banner + in-stream decision (CUJ C)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review C",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_c_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("reject is disabled until a comment is entered, then pins the rejection banner", async () => {+ const reason = "Add a default value before this can ship";+ await planPage.reviewButton.click();+ await page.getByText("Submit feedback and request changes").waitFor();+ await page.locator('label:has-text("Reject")').click();+ // Reject requires a non-empty comment.+ await expect(planPage.reviewSubmitButton).toBeDisabled();+ await planPage.reviewPopoverEditor.fill(reason);+ await expect(planPage.reviewSubmitButton).toBeEnabled();+ await planPage.reviewSubmitButton.click();++ // The rejection banner pins above the timeline with the reason.+ await expect(planPage.rejectionBanner).toBeVisible({ timeout: 15_000 });+ await expect(page.getByText(reason).first()).toBeVisible();+ // The decision also lands in-stream as a permanent timeline row.+ await expect(page.getByText("rejected issue").first()).toBeVisible();+ // Badge flips, action disappears, footer announces the block.+ await expect(planPage.reviewBadge("Rejected")).toBeVisible();+ await expect(planPage.reviewButton).not.toBeVisible();+ await expect(+ page.getByText("Blocked by the rejected review", { exact: false }),+ ).toBeVisible();+ });+});++test.describe("Creator re-requests review without changes (CUJ D)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review D",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_d_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ // Reach the rejected state via API (setup), then verify recovery via UI.+ await env.api.rejectIssue(seeded.issueName, "Please address the feedback");+ planId = seeded.planId;+ await goReview(planId);+ });++ test("inline re-request restarts review and restores the Review action", async () => {+ await expect(planPage.rejectionBanner).toBeVisible({ timeout: 15_000 });+ await planPage.reRequestButton.click();+ // Banner clears, status returns to under-review, the action comes back.+ await expect(planPage.rejectionBanner).toBeHidden({ timeout: 15_000 });+ await expect(planPage.reviewBadge("Under review")).toBeVisible();+ await expect(planPage.reviewButton).toBeVisible();+ });+});++test.describe("Comment composer: draft persistence + post (CUJ E)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review E",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_e_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("draft survives collapse; posting appends the comment and re-collapses", async () => {+ const draft = "Draft that should survive collapse";+ const final = "Looks good — ready to ship";++ await planPage.composerTrigger.click();+ await expect(planPage.composerEditor).toBeVisible();+ await planPage.composerEditor.fill(draft);++ // Collapse via the composer's Cancel, then re-expand → draft restored.+ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ await expect(planPage.composerTrigger).toBeVisible();+ await planPage.composerTrigger.click();+ await expect(planPage.composerEditor).toHaveValue(draft);++ // Replace and post.+ await planPage.composerEditor.fill(final);+ await planPage.composerSubmitButton.click();++ await expect(page.getByText(final).first()).toBeVisible({ timeout: 15_000 });+ // Composer re-collapses to its trigger after posting.+ await expect(planPage.composerTrigger).toBeVisible();+ });+});++test.describe("Long-history timeline fold (CUJ J)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review J",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_j_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ // 12 comments + 2 synthetic head rows = 14 entries → folds (head 3 + tail 3,+ // 8 hidden). NOTE: the shipped fold hides ALL middle rows including user+ // comments (foldTimeline.test.ts) — the design doc's "comments stay visible+ // as islands" was not implemented; this test locks the shipped behavior.+ for (let i = 1; i <= 12; i++) {+ await env.api.createIssueComment(seeded.issueName, `Timeline comment ${i}`);+ }+ planId = seeded.planId;+ await goReview(planId);+ });++ test("middle entries collapse behind a torn separator until Show all", async () => {+ // Head shows comment 1; tail shows comment 12; middle (comment 5) hidden.+ await expect(page.getByText("Timeline comment 1", { exact: true })).toBeVisible({+ timeout: 15_000,+ });+ await expect(+ page.getByText("Timeline comment 12", { exact: true }),+ ).toBeVisible();+ await expect(page.getByText(/\d+ hidden events?/)).toBeVisible();+ await expect(+ page.getByText("Timeline comment 5", { exact: true }),+ ).toBeHidden();++ await page.getByText("Show all").click();+ await expect(+ page.getByText("Timeline comment 5", { exact: true }),+ ).toBeVisible();+ });+});++test.describe("Permission boundary: non-candidate cannot review but can comment", () => {+ test.describe.configure({ mode: "serial" });+ let dbaContext: BrowserContext;+ let dbaPage: Page;+ let dbaPlanPage: PlanDetailPage;+ let planId: string;++ test.beforeAll(async ({ browser }) => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review Perm",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_perm_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;++ // dba1 is workspaceDBA — NOT a candidate of the workspaceAdmin step.+ await signInBrowserAs(+ browser,+ env.baseURL,+ "[email protected]",+ "12345678",+ ".auth/dba-review.json",+ );+ dbaContext = await browser.newContext({+ storageState: ".auth/dba-review.json",+ });+ dbaPage = await dbaContext.newPage();+ dbaPlanPage = new PlanDetailPage(dbaPage, env.baseURL);+ await dbaPlanPage.goto(projectId, planId);+ await dbaPlanPage.dismissModals();+ await dbaPlanPage.expandSection("Review");+ });++ test.afterAll(async () => {+ await dbaContext?.close();+ });++ test("a non-candidate sees no Review action but the composer is available", async () => {+ await expect(dbaPlanPage.reviewBadge("Under review")).toBeVisible({+ timeout: 15_000,+ });+ await expect(dbaPlanPage.reviewButton).not.toBeVisible();+ await expect(dbaPlanPage.composerTrigger).toBeVisible();+ });+});++// Regression guard for BYT-9746 (was finding O7): editing your own comment+// inline must show the "(edited)" marker immediately, not only after a reload.+// The original bug: stores/app/issueComment.ts updateIssueComment() patched+// { ...comment, comment } and discarded the server response, so updateTime was+// never bumped and isEdited (createdTs !== updatedTs) stayed false until a+// refetch. Fixed on main by #20649 (updateIssueComment now stores the RPC+// response). This was a test.fail() lock until the fix landed; it now runs as+// a normal passing guard so a re-regression fails loudly.+test.describe("inline comment edit shows the edited marker in place (BYT-9746)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;+ const original = `O7 edit me ${Date.now()}`;++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review O7",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_o7_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ await env.api.createIssueComment(seeded.issueName, original);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("(edited) marker appears immediately after an inline edit", async () => {+ const edited = `${original} (edited inline)`;+ const row = page.locator("li", { hasText: original });+ await expect(row).toBeVisible({ timeout: 15_000 });+ // The pencil edit affordance (own comment, no text label → target the icon).+ await row.locator("button:has(svg.lucide-pencil)").click();+ const editor = page.locator("textarea[placeholder='Leave a comment...']");+ await editor.fill(edited);+ await page.getByRole("button", { name: "Save", exact: true }).click();++ // Save succeeded once the new text renders — proves the assertion below+ // discriminates the marker, not an unfinished save.+ await expect(page.getByText(edited).first()).toBeVisible({ timeout: 15_000 });+ // Post-fix (#20649): the "(edited)" marker appears immediately, in place.+ await expect(page.getByText("(edited)").first()).toBeVisible({+ timeout: 5_000,+ });+ });+});++test.describe("Bypass when approved but checks failed (CUJ F)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: false,+ requirePlanCheckNoError: false,+ allowSelfApproval: true,+ });+ await env.api.upsertSetting(+ "WORKSPACE_APPROVAL",+ { workspaceApproval: { rules: [] } },+ "value.workspace_approval",+ );+ await attachErrorConfig();+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review F",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_f_${Date.now()} TEXT;`,+ runChecks: true,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["SKIPPED"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("footer is the primary action; confirm sheet → deploy creates the rollout", async () => {+ await expect(+ page.getByText("Review approved, but plan checks failed"),+ ).toBeVisible({ timeout: 15_000 });+ await expect(planPage.bypassAndDeployAction).toBeVisible();++ await planPage.bypassAndDeployAction.click();+ const sheet = page.getByRole("dialog");+ await expect(sheet).toBeVisible();+ // A soft (non-mandatory) failed-check warning must be acknowledged.+ await sheet.getByRole("checkbox").check();+ await sheet.getByRole("button", { name: "Deploy", exact: true }).click();++ // Rollout created → the footer (only shown while !hasRollout) disappears.+ await expect(+ page.getByText("Review approved, but plan checks failed"),+ ).toBeHidden({ timeout: 20_000 });+ await expect(planPage.deploySection).toBeVisible();+ });+});++test.describe("Waiting-review bypass link is gated by requireIssueApproval (CUJ G1/G2)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: true,+ requirePlanCheckNoError: false,+ allowSelfApproval: true,+ });+ await env.api.upsertSetting(+ "WORKSPACE_APPROVAL",+ { workspaceApproval: { rules: [ONE_STEP_RULE] } },+ "value.workspace_approval",+ );+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review G",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_g_${Date.now()} TEXT;`,+ runChecks: true,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("mandatory approval hides the link; optional approval shows it (same plan)", async () => {+ // G1 — requireIssueApproval=true: footer waits, NO bypass link.+ await expect(page.getByText("Waiting on review")).toBeVisible({+ timeout: 15_000,+ });+ await expect(planPage.bypassAndDeployAction).not.toBeVisible();++ // G2 — flip the project to optional approval; the muted link appears.+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: false,+ });+ await goReview(planId);+ await expect(page.getByText("Waiting on review")).toBeVisible({+ timeout: 15_000,+ });+ await expect(planPage.bypassAndDeployAction).toBeVisible();+ });+});++test.describe("A mandatory project gate hard-blocks the bypass confirm", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: false,+ requirePlanCheckNoError: true,+ allowSelfApproval: true,+ });+ await env.api.upsertSetting(+ "WORKSPACE_APPROVAL",+ { workspaceApproval: { rules: [] } },+ "value.workspace_approval",+ );+ await attachErrorConfig();+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review Gate",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_gate_${Date.now()} TEXT;`,+ runChecks: true,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["SKIPPED"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("confirm sheet reports the unmet gate and Deploy stays disabled", async () => {+ await expect(planPage.bypassAndDeployAction).toBeVisible({ timeout: 15_000 });+ await planPage.bypassAndDeployAction.click();+ const sheet = page.getByRole("dialog");+ await expect(sheet).toBeVisible();+ await expect(+ sheet.getByText("Required project gates are not met", { exact: false }),+ ).toBeVisible();+ // The mandatory gate cannot be acknowledged away — Deploy is disabled.+ await expect(+ sheet.getByRole("button", { name: "Deploy", exact: true }),+ ).toBeDisabled();+ });+});++// Regression guard for BYT-9745 (finding O5): the bypass confirm sheet used to+// render an empty bordered box under REVIEW for skipped-approval issues, while+// the main Review section showed "No approval required". Root cause:+// ReviewReadinessFooter rendered <ReviewApprovalFlow> (zero nodes when there+// are no roles) without the skipped-guard PlanReviewSection had. Fixed by+// #20662 — ReviewApprovalFlow now renders the skip note itself. This was a+// test.fail() lock until the fix landed; it now runs as a normal passing guard.+test.describe("confirm sheet shows the skipped state in its review box (BYT-9745)", () => {+ test.describe.configure({ mode: "serial" });+ let planId: string;++ test.beforeAll(async () => {+ await env.api.deletePolicy(env.project, "tag").catch(() => {});+ await env.api.updateProjectSettings(env.project, {+ requireIssueApproval: false,+ requirePlanCheckNoError: false,+ allowSelfApproval: true,+ });+ await env.api.upsertSetting(+ "WORKSPACE_APPROVAL",+ { workspaceApproval: { rules: [] } },+ "value.workspace_approval",+ );+ await attachErrorConfig();+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review O5",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_o5_${Date.now()} TEXT;`,+ runChecks: true,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["SKIPPED"]);+ planId = seeded.planId;+ await goReview(planId);+ });++ test("confirm-sheet review box shows the skip note for a skipped approval", async () => {+ await expect(planPage.bypassAndDeployAction).toBeVisible({ timeout: 15_000 });+ await planPage.bypassAndDeployAction.click();+ const sheet = page.getByRole("dialog");+ await expect(sheet).toBeVisible();+ // The main section shows "No approval required"; post-fix (#20662) the+ // confirm sheet's review box shows it too. Scoped to the sheet so the main+ // section behind the scrim doesn't satisfy it. (Pre-fix the box was empty.)+ await expect(+ sheet.getByText("No approval required", { exact: false }),+ ).toBeVisible({ timeout: 5_000 });+ });+});++test.describe("Long approval flow adaptive rendering (CUJ I)", () => {+ test.describe.configure({ mode: "serial" });++ test.beforeAll(async () => {+ await setupApproval(FIVE_STEP_RULE);+ const seeded = await seedReviewPlan(env.api, env.project, env.database, {+ prefix: "E2E Review Flow",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_flow_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ // Approve step 1 (workspaceAdmin) as demo, step 2 (workspaceDBA) as dba1 →+ // 2 approved, step 3 (projectOwner) current, steps 4-5 pending.+ await env.api.approveIssue(seeded.issueName);+ const dba = await BytebaseApiClient.asUser(+ env.baseURL,+ "[email protected]",+ "12345678",+ );+ await dba.approveIssue(seeded.issueName);+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ await planPage.goto(projectId, seeded.planId);+ await planPage.dismissModals();+ await planPage.expandSection("Review");+ });++ test.afterAll(async () => {+ await page?.setViewportSize({ width: 1280, height: 720 }).catch(() => {});+ });++ test("constrained width folds approved + pending into chips; current stays named", async () => {+ await page.setViewportSize({ width: 900, height: 1100 });+ // Leading approved chip, trailing pending chip, current step named.+ await expect(page.getByText("2 approved")).toBeVisible({ timeout: 15_000 });+ await expect(page.getByText("2 pending")).toBeVisible();+ await expect(page.getByText("Project Owner").first()).toBeVisible();+ await expect(page.getByText("Current", { exact: true })).toBeVisible();+ });++ test("narrow width renders the vertical stepper with every node, no chips", async () => {+ await page.setViewportSize({ width: 480, height: 1500 });+ // Every role is named in the vertical stepper.+ for (const role of [+ "Workspace Admin",+ "Workspace DBA",+ "Project Owner",+ "Project Developer",+ "Project Releaser",+ ]) {+ await expect(page.getByText(role).first()).toBeVisible({ timeout: 15_000 });+ }+ // No fold chips in the vertical layout.+ await expect(page.getByText("2 approved")).toBeHidden();+ await expect(page.getByText("2 pending")).toBeHidden();+ });+});diff --git a/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.tsindex 4c758cb1cc..6a450b6e0c 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts@@ -8,11 +8,11 @@// → rollout blocked until each approval-flow step completes; on the// last approval the rollout auto-creates.// - Approval + plan-check gate with an ERROR-level SQL review rule-// → after approval, the rollout STAYS fully blocked: DEPLOY shows-// "Failed checks are blocking automatic rollout creation" and NO-// "Manually create rollout" button is offered. The user must fix-// the SQL or relax requirePlanCheckNoError (which then reveals the-// manual-create button).+// → after approval, the rollout STAYS fully blocked: the Review+// readiness footer shows "Review approved, but plan checks failed"+// and NO "Manually create rollout" button is offered (the manual+// path is GitOps-only now — AIO review section, 3.19.1). The user+// must fix the SQL or relax requirePlanCheckNoError.//// Approval rules are workspace-level settings (`WORKSPACE_APPROVAL`); the// new bootstrap leaves them empty, so each test that needs an approval@@ -281,18 +281,20 @@ test.describe("Approval + plan-check gate with ERROR-level SQL review", () => {await page.reload();await page.waitForLoadState("networkidle");- // Product contract: with requirePlanCheckNoError=true and an ERROR- // rule, even after the approval flow completes the rollout stays- // fully blocked. DEPLOY shows "Checks must pass. Failed" with the- // helper text "Failed checks are blocking automatic rollout- // creation." NO "Manually create rollout" button is offered — the- // user must either fix the SQL or relax the gate. (Symmetric to- // the `with gate on` test in plan-detail-checks.spec.ts.)+ // Product contract: with requirePlanCheckNoError=true and an ERROR rule,+ // even after the approval flow completes the rollout stays fully blocked.+ // The blocking status now lives in the Review readiness footer (AIO review+ // section): APPROVED + failed checks → "Review approved, but plan checks+ // failed". NO "Manually create rollout" button is offered for issue-backed+ // plans, and the footer's bypass confirm sheet hard-blocks deploy on the+ // mandatory gate. (Symmetric to the `with gate on` test in+ // plan-detail-checks.spec.ts.)await expect(planPage.checksSummary()).toContainText("Error", {timeout: 15_000,});+ await planPage.expandSection("Review");await expect(- page.getByText(/Failed checks are blocking/i).first(),+ page.getByText("Review approved, but plan checks failed"),).toBeVisible({ timeout: 10_000 });await expect(planPage.manualCreateRolloutButton).not.toBeVisible({timeout: 3_000,diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.tsindex 907fe64db1..356be33d48 100644--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts@@ -12,6 +12,23 @@ export class PlanDetailPage {// <input> bound to the plan or issue title — first textbox on the page.readonly headerTitle: Locator;+ // --- Review section (AIO Plan Detail Review) ---+ // The header Review action button (PlanReviewSectionHeader). Distinct from the+ // "Review" phase label, which is a <span>, not a button.+ readonly reviewButton: Locator;+ // The markdown editor inside the Review popover (ReviewActionPopover).+ readonly reviewPopoverEditor: Locator;+ readonly reviewSubmitButton: Locator;+ // The rejection banner pinned above the timeline (ReviewRejectionBanner).+ readonly rejectionBanner: Locator;+ readonly reRequestButton: Locator;+ // The collapsed composer trigger + its expanded editor (ReviewCommentComposer).+ readonly composerTrigger: Locator;+ readonly composerEditor: Locator;+ readonly composerSubmitButton: Locator;+ // The readiness footer's single action, in either weight (link or button).+ readonly bypassAndDeployAction: Locator;+constructor(page: Page, baseURL: string) {this.page = page;this.baseURL = baseURL;@@ -21,6 +38,39 @@ export class PlanDetailPage {this.manualCreateRolloutButton = page.getByRole("button", { name: "Manually create rollout" });this.retryButton = page.getByRole("button", { name: "Retry" });this.headerTitle = page.getByRole("textbox").first();++ this.reviewButton = page.getByRole("button", { name: "Review", exact: true });+ this.reviewPopoverEditor = page.locator(+ "textarea[placeholder='Leave a comment...']",+ );+ this.reviewSubmitButton = page.getByRole("button", { name: "Submit", exact: true });+ this.rejectionBanner = page.getByText(/^Rejected by /).first();+ this.reRequestButton = page.getByRole("button", { name: "re-request review" });+ this.composerTrigger = page.getByRole("button", { name: "Add a comment..." });+ this.composerEditor = page.locator("textarea[placeholder='Add a comment...']");+ this.composerSubmitButton = page.getByRole("button", { name: "Comment", exact: true });+ this.bypassAndDeployAction = page.getByRole("button", { name: "Bypass and deploy" });+ }++ // The Review phase status badge text (e.g. "Under review", "Approved",+ // "Rejected", "Skipped"). Scoped to its known label set so it doesn't match+ // body copy.+ reviewBadge(text: string): Locator {+ return this.page.getByText(text, { exact: true });+ }++ // Open the Review popover, pick an action, optionally type a comment, submit.+ async submitReview(+ action: "Comment" | "Approve" | "Reject",+ comment?: string,+ ): Promise<void> {+ await this.reviewButton.click();+ await this.page.getByText("Submit feedback and request changes").waitFor();+ await this.page.locator(`label:has-text("${action}")`).click();+ if (comment !== undefined) {+ await this.reviewPopoverEditor.fill(comment);+ }+ await this.reviewSubmitButton.click();}async goto(projectId: string, planId: string) {diff --git a/frontend/tests/e2e/plan-detail/plan-helpers.ts b/frontend/tests/e2e/plan-detail/plan-helpers.tsindex b424a7ab6c..87fd2ee366 100644--- a/frontend/tests/e2e/plan-detail/plan-helpers.ts+++ b/frontend/tests/e2e/plan-detail/plan-helpers.ts@@ -1,5 +1,57 @@import type { BytebaseApiClient } from "../framework/api-client";+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++// Poll an issue's approvalStatus until it reaches one of `accept`. Approval-flow+// generation is async after issue creation, so the status briefly sits at+// CHECKING before settling on PENDING / APPROVED / SKIPPED / REJECTED. Fail+// closed on timeout so a regression in flow generation surfaces loudly.+export async function waitForApprovalStatus(+ api: BytebaseApiClient,+ issueName: string,+ accept: string[],+ timeoutMs = 40_000,+): Promise<string> {+ const deadline = Date.now() + timeoutMs;+ let last = "<none>";+ while (Date.now() < deadline) {+ last = (await api.getIssue(issueName)).approvalStatus;+ if (accept.includes(last)) return last;+ await sleep(1000);+ }+ throw new Error(+ `issue ${issueName} approvalStatus did not reach ${accept.join("|")} within ${timeoutMs}ms (last: ${last})`,+ );+}++// Seed a single-spec change plan + its issue against `database`, optionally+// running plan checks and waiting for them to finish. Returns the ids the+// review specs need. Creation only — the caller decides which approval state to+// wait for (PENDING vs SKIPPED) since that depends on the project/workspace+// settings the caller configured.+export async function seedReviewPlan(+ api: BytebaseApiClient,+ project: string,+ database: string,+ opts: { prefix: string; sql: string; runChecks?: boolean },+): Promise<{ planId: string; planName: string; issueName: string }> {+ const ts = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;+ const sheet = await api.createSheet(project, opts.sql);+ const plan = await api.createPlan(project, `${opts.prefix} ${ts}`, [+ { id: `spec-${ts}`, targets: [database], sheet },+ ]);+ const issue = await api.createIssue(project, `${opts.prefix} ${ts}`, plan.name);+ 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 anddiff --git a/frontend/tests/e2e/project-databases/project-databases.spec.ts b/frontend/tests/e2e/project-databases/project-databases.spec.tsindex de22fce663..2c851d329e 100644--- a/frontend/tests/e2e/project-databases/project-databases.spec.ts+++ b/frontend/tests/e2e/project-databases/project-databases.spec.ts@@ -3,12 +3,17 @@// BYT-9609 (FIXED, #20450; cherry-picked to 3.18.1): a user whose only role on a// project is Project Developer opened the project's Database page, checked a// database row, and found EVERY button on the selection action bar (Change-// Database, Export Data, Sync Schema, …) disabled — even though projectDeveloper-// grants those permissions. Visiting the project Members page and returning made-// them clickable, because only the Members route loaded the project IAM policy-// into the React app store; every other project route evaluated permissions-// against an EMPTY policy. The fix loads the project IAM policy on route entry-// for all project routes.+// Database, Sync Schema, …) disabled — even though projectDeveloper grants those+// permissions. Visiting the project Members page and returning made them+// clickable, because only the Members route loaded the project IAM policy into+// the React app store; every other project route evaluated permissions against+// an EMPTY policy. The fix loads the project IAM policy on route entry for all+// project routes.+//+// NOTE: the bar's "Export Data" action was removed when the export center was+// deprecated (#20693) — the contract under test is "IAM-gated actions are+// enabled on a cold route", so we assert against the two permission-gated+// actions that remain (Change Database, Sync Schema). Do not re-add Export Data.//// Per AGENTS.md "F. Test by role": create scoped users via the API, sign each// into its own context, and COLD-load /databases (without visiting Members@@ -106,7 +111,7 @@ test.afterAll(async () => {});test.describe("Project developer action bar is enabled on a cold Database page (BYT-9609)", () => {- test("a projectDeveloper sees Change Database / Export Data / Sync Schema ENABLED without visiting Members first", async ({+ test("a projectDeveloper sees Change Database / Sync Schema ENABLED without visiting Members first", async ({browser,}) => {const page = await openColdDatabasesPage(browser, DEV_USER.authFile);@@ -115,7 +120,7 @@ test.describe("Project developer action bar is enabled on a cold Database page (// The regression: pre-fix these rendered disabled because the project IAM// policy was never fetched on the /databases route. Playwright auto-retries// toBeEnabled, tolerating the async IAM fetch the fix performs on entry.- for (const name of ["Change Database", "Export Data", "Sync Schema"]) {+ for (const name of ["Change Database", "Sync Schema"]) {await expect(page.getByRole("button", { name, exact: true }),`"${name}" must be enabled for a projectDeveloper on a cold Database page`,diff --git a/frontend/tests/e2e/sql-editor/sql-editor-admin-mode.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-admin-mode.spec.tsindex 5bb984d1fb..aa19b25100 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-admin-mode.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-admin-mode.spec.ts@@ -27,14 +27,41 @@ test.afterAll(async () => {await sharedContext?.close();});+// The admin terminal shell no longer carries a `bg-dark-bg` class — #20602+// ("token migration") migrated it to `bg-background`, which resolves to the+// dark token (#1e1e1e) inside the terminal's own theme scope. Returns true when+// a dark-background shell is mounted, located structurally as the first opaque+// dark-background ancestor of the "Exit admin mode" button (page-scoped; the+// admin `page` is shared across this file). Reading the computed color rather+// than a class name keeps the assertion meaningful across future token renames.+async function adminShellIsDark(): Promise<boolean> {+ return await page.evaluate(() => {+ const exit = Array.from(document.querySelectorAll("button")).find((b) =>+ /Exit admin mode/.test(b.textContent || ""),+ );+ let el: Element | null = exit ?? null;+ while (el) {+ const bg = getComputedStyle(el).backgroundColor;+ const m = bg.match(/rgba?\(([^)]+)\)/);+ if (m) {+ const p = m[1].split(",").map((v) => parseFloat(v.trim()));+ if ((p[3] ?? 1) > 0 && (p[0] + p[1] + p[2]) / 3 < 128) return true;+ }+ el = el.parentElement;+ }+ return false;+ });+}+test.describe("Vertical display preserves the admin-mode dark theme", () => {// BYT-9496 (sub-bug R44a): in admin mode, toggling the "Vertical// display" switch on a result panel re-renders the panel as the// transposed key:value layout — but the new layout uses generic// light-theme tokens (`bg-control-bg`) instead of the dark terminal- // tokens (`bg-dark-bg`) used by the surrounding admin shell. The- // result is a white-background, black-text block dropped into the- // middle of an otherwise dark terminal.+ // surface used by the surrounding admin shell. The result is a+ // white-background, black-text block dropped into the middle of an+ // otherwise dark terminal. (The shell's dark surface is `bg-background`+ // in the terminal's theme scope since #20602; it was `bg-dark-bg` before.)//// Bug evidence: .playwright-cli/qa-session-2026-05-12/r44-byt9496-admin-mode/// - 03-notes.txt@@ -101,8 +128,27 @@ test.describe("Vertical display preserves the admin-mode dark theme", () => {.first().waitFor({ timeout: 10_000 });const sample = await page.evaluate(() => {- // Terminal shell wraps everything in admin mode with bg-dark-bg.- const shell = document.querySelector(".bg-dark-bg");+ // Terminal shell. Post-#20602 the admin shell no longer carries a+ // `bg-dark-bg` class — it uses `bg-background` resolved to the dark token+ // inside the terminal's theme scope. Locate it structurally: the first+ // opaque dark-background ancestor of the "Exit admin mode" button.+ const findAdminShell = (): Element | null => {+ const exit = Array.from(document.querySelectorAll("button")).find((b) =>+ /Exit admin mode/.test(b.textContent || ""),+ );+ let el: Element | null = exit ?? null;+ while (el) {+ const bg = getComputedStyle(el).backgroundColor;+ const m = bg.match(/rgba?\(([^)]+)\)/);+ if (m) {+ const p = m[1].split(",").map((v) => parseFloat(v.trim()));+ if ((p[3] ?? 1) > 0 && (p[0] + p[1] + p[2]) / 3 < 128) return el;+ }+ el = el.parentElement;+ }+ return null;+ };+ const shell = findAdminShell();if (!shell) return { reason: "admin terminal shell not found" };const shellBg = getComputedStyle(shell).backgroundColor;@@ -118,19 +164,25 @@ test.describe("Vertical display preserves the admin-mode dark theme", () => {if (!blockCard) return { reason: "vertical block card not found" };const blockBg = getComputedStyle(blockCard).backgroundColor;- // Parse rgb(), rgba(), AND lab() — Chromium 124+ emits lab() for- // some Tailwind tokens so the legacy rgb-only regex returns null- // and the test reports a false failure. For lab(L a b), convert- // to approximate sRGB via the L-only luminance (a/b are tiny for- // near-neutral grays which is what the SQL editor's dark-theme- // tokens are). L is 0–100; mapping linearly to 0–255 is plenty- // for the harmony assertion below.+ // Parse rgb(), rgba(), lab(), AND oklab() — newer Chromium + Tailwind+ // v4 emit lab()/oklab() for some tokens (post-#20602 the SQL editor's+ // dark-theme surfaces resolve to oklab), so the legacy rgb-only regex+ // returns null and the test reports a false failure. For lab/oklab,+ // convert to an approximate gray via the L-only luminance (a/b are tiny+ // for the near-neutral grays the dark theme uses). lab L is 0–100,+ // oklab L is 0–1 — both map linearly to 0–255, plenty for the harmony+ // assertion below.const parse = (s: string) => {const rgb = s.match(/rgba?\(([^)]+)\)/);if (rgb) {const parts = rgb[1].split(",").map((p) => parseFloat(p.trim()));return { r: parts[0], g: parts[1], b: parts[2], a: parts[3] ?? 1 };}+ const oklab = s.match(/^oklab\(\s*([\d.\-]+)/);+ if (oklab) {+ const gray = Math.round(parseFloat(oklab[1]) * 255);+ return { r: gray, g: gray, b: gray, a: 1 };+ }const lab = s.match(/^lab\(\s*([\d.\-]+)\s+([\d.\-]+)\s+([\d.\-]+)/);if (lab) {const L = parseFloat(lab[1]);@@ -179,10 +231,10 @@ test.describe("Vertical display preserves the admin-mode dark theme", () => {// shade for the fix. What we DO require is low contrast against// the shell.//- // Threshold 100 (per channel) is generous: bg-control-bg vs- // bg-dark-bg differs by ~240 on every channel, while a properly- // themed block (e.g., a bg-dark-block one shade lighter than the- // shell, or a translucent overlay) stays well under 100.+ // Threshold 100 (per channel) is generous: a light `bg-control-bg`+ // block vs the dark terminal shell differs by ~240 on every channel,+ // while a properly themed block (one shade lighter than the shell, or+ // a translucent overlay) stays well under 100.expect(sample.maxChannelDelta!,`vertical block must visually harmonize with the admin shell ` +@@ -240,9 +292,11 @@ test.describe("Wrench is not clickable when no database is connected", () => {test.describe("Clicking the wrench enters the admin terminal", () => {// After the click, the editor swaps from WORKSHEET to ADMIN mode.- // TerminalPanel mounts in place of the standard editor — the dark- // shell (.bg-dark-bg) and the "SQL>" prompt are the visible- // signals. The "Exit admin mode" toolbar button also appears.+ // TerminalPanel mounts in place of the standard editor — the "SQL>"+ // prompt and the "Exit admin mode" toolbar button are the visible+ // signals, and the shell mounts with its dark surface (asserted via+ // adminShellIsDark(), since the shell uses `bg-background` in its theme+ // scope post-#20602 rather than a `bg-dark-bg` class).test("admin terminal mounts with dark shell and SQL> prompt", async () => {test.setTimeout(120_000);@@ -255,12 +309,16 @@ test.describe("Clicking the wrench enters the admin terminal", () => {await sqlEditor.adminModeButton.click();await page.waitForTimeout(800);- await expect(page.locator(".bg-dark-bg").first()).toBeVisible({ timeout: 10_000 });// The CompactSQLEditor renders "SQL>" as a sibling line-decoration.- await expect(page.getByText(/SQL>/).first()).toBeVisible({ timeout: 5000 });+ await expect(page.getByText(/SQL>/).first()).toBeVisible({ timeout: 10_000 });await expect(page.getByRole("button", { name: "Exit admin mode", exact: true }),).toBeVisible({ timeout: 5000 });+ // ...and it mounts with its DARK shell (the BYT-9496 theme contract).+ expect(+ await adminShellIsDark(),+ "admin terminal should mount with a dark shell",+ ).toBe(true);});});@@ -308,19 +366,20 @@ test.describe("Exit admin mode returns to the worksheet view", () => {await sqlEditor.adminModeButton.click();await page.waitForTimeout(800);- await expect(page.locator(".bg-dark-bg").first()).toBeVisible({ timeout: 10_000 });-+ // Terminal mounted (admin mode active) with its dark shell.const exitBtn = page.getByRole("button", {name: "Exit admin mode",exact: true,});+ await expect(exitBtn).toBeVisible({ timeout: 10_000 });+ expect(await adminShellIsDark(), "admin shell should be dark").toBe(true);+await exitBtn.click();await page.waitForTimeout(800);- // Dark shell unmounts. (TerminalPanel renders TWO bg-dark-bg- // descendants — the outer wrapper and the inner scroll area.- // Both must vanish, so we check count rather than .first().)- await expect(page.locator(".bg-dark-bg")).toHaveCount(0);+ // Terminal unmounts: the admin-only "Exit admin mode" button is gone (the+ // canonical "admin mode inactive" signal — the dark shell went with it).+ await expect(exitBtn).toHaveCount(0);// Wrench is back (worksheet mode) and enabled (still connected).await expect(sqlEditor.adminModeButton).toBeVisible({ timeout: 5000 });await expect(sqlEditor.adminModeButton).toBeEnabled();@@ -385,9 +444,11 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()await page.waitForTimeout(800);await sqlEditor.adminModeButton.click();await page.waitForTimeout(800);- await expect(page.locator(".bg-dark-bg").first()).toBeVisible({- timeout: 10_000,- });+ // Admin mode active: the "Exit admin mode" toolbar button is present (the+ // dark terminal mounted). Replaces the pre-#20602 `.bg-dark-bg` gate.+ await expect(+ page.getByRole("button", { name: "Exit admin mode", exact: true }),+ ).toBeVisible({ timeout: 10_000 });});test.afterEach(async () => {@@ -442,6 +503,14 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()// a future theme regression matches text to bg.)const contrast = await page.evaluate(() => {const parse = (s: string) => {+ // Handle oklab() too (Tailwind v4 / post-#20602 dark tokens): map the+ // L channel (0–1) to an approximate gray; a/b are ~0 for the neutral+ // grays here. Falls through to rgb()/rgba() otherwise.+ const ok = s.match(/^oklab\(\s*([\d.\-]+)/);+ if (ok) {+ const gray = Math.round(parseFloat(ok[1]) * 255);+ return { r: gray, g: gray, b: gray };+ }const m = s.match(/rgba?\(([^)]+)\)/);if (!m) return null;const [r, g, b] = m[1].split(",").map((v) => parseFloat(v.trim()));@@ -450,7 +519,26 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()const codes = document.querySelectorAll('[role="code"]');const last = codes[codes.length - 1];const line = last?.querySelector(".view-lines .view-line");- const shell = document.querySelector(".bg-dark-bg");+ // Terminal shell: post-#20602 it uses `bg-background` (dark in the+ // terminal's theme scope), no longer `bg-dark-bg`. Find the first opaque+ // dark-background ancestor of the "Exit admin mode" button.+ const findAdminShell = (): Element | null => {+ const exit = Array.from(document.querySelectorAll("button")).find((b) =>+ /Exit admin mode/.test(b.textContent || ""),+ );+ let el: Element | null = exit ?? null;+ while (el) {+ const bg = getComputedStyle(el).backgroundColor;+ const m = bg.match(/rgba?\(([^)]+)\)/);+ if (m) {+ const p = m[1].split(",").map((v) => parseFloat(v.trim()));+ if ((p[3] ?? 1) > 0 && (p[0] + p[1] + p[2]) / 3 < 128) return el;+ }+ el = el.parentElement;+ }+ return null;+ };+ const shell = findAdminShell();if (!line || !shell)return { reason: "missing line or shell" } as { reason: string };const shellRgb = parse(getComputedStyle(shell).backgroundColor);