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): cover the 3.23 and 3.24 features, and lock two bugs they found (#21683)
zchpeter3089436e3a3e
diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsxindex 002ac452f8..b2fb963759 100644--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.test.tsx@@ -35,13 +35,7 @@ vi.mock("@/apps/explain-visualizer/QueryPlanViewer", () => ({formatPlanSource: (source: string) => `formatted:${source}`,}));-vi.mock("@/components/ui/copy-button", () => ({- CopyButton: ({ content }: { content: string }) => (- <button type="button" data-content={content}>- copy- </button>- ),-}));+const COPY_PLAN = "sql-editor.query-plan-viewer.copy.plan";describe("QueryPlanResultView", () => {beforeEach(() => vi.clearAllMocks());@@ -122,6 +116,10 @@ describe("QueryPlanResultView", () => {);expect(screen.queryAllByRole("tab")).toHaveLength(1);expect(screen.getByText("formatted:text plan")).toBeInTheDocument();+ // The same labelled copy control as the visualizer's Text tab.+ expect(screen.getByTestId("plan-copy-button")).toHaveAccessibleName(+ COPY_PLAN+ );});test("hides copying for a protected text plan", () => {@@ -129,7 +127,7 @@ describe("QueryPlanResultView", () => {<QueryPlanResultView rawPlan="text plan" disallowCopyingData />);- expect(screen.queryByRole("button", { name: "copy" })).toBeNull();+ expect(screen.queryByTestId("plan-copy-button")).toBeNull();expect(screen.getByText("formatted:text plan").parentElement).toHaveClass("select-none");@@ -150,6 +148,9 @@ describe("QueryPlanResultView", () => {));expect(screen.getByText("formatted:text plan")).toBeInTheDocument();+ expect(screen.getByTestId("plan-copy-button")).toHaveAccessibleName(+ COPY_PLAN+ );});test("loads a text plan on demand when no picture is available", async () => {diff --git a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsxindex fea0788247..1a916cd827 100644--- a/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx+++ b/frontend/src/modules/sql-editor/components/ResultView/QueryPlanResultView.tsx@@ -1,14 +1,17 @@import { LoaderCircle } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import type { QueryPlanTranslate } from "@/apps/explain-visualizer/plan-i18n";+import { PlanCopyButton } from "@/apps/explain-visualizer/PlanCopyButton";+import {+ QueryPlanI18nProvider,+ type QueryPlanTranslate,+} from "@/apps/explain-visualizer/plan-i18n";import type { PlanTableLookup } from "@/apps/explain-visualizer/plan-model";import { QueryPlanView } from "@/apps/explain-visualizer/QueryPlanView";import { formatPlanSource } from "@/apps/explain-visualizer/QueryPlanViewer";import { Alert } from "@/components/ui/alert";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";-import { CopyButton } from "@/components/ui/copy-button";import { Tabs, TabsList, TabsPanel, TabsTrigger } from "@/components/ui/tabs";import { Tooltip } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";@@ -43,9 +46,11 @@ interface LoadRequest {function TextPlan({source,disallowCopyingData,+ translate,}: {source: string;disallowCopyingData: boolean;+ translate: QueryPlanTranslate;}) {const formatted = useMemo(() => formatPlanSource(source), [source]);return (@@ -56,8 +61,15 @@ function TextPlan({)}>{disallowCopyingData ? null : (- <div className="flex shrink-0 justify-end px-4 py-2">- <CopyButton content={formatted} size="sm" appearance="outline" />+ // The visualizer's own copy control, so a text-only plan offers the+ // same "Copy plan" as the visualizer's Text tab.+ <div className="flex shrink-0 items-center justify-end px-4 py-2">+ <QueryPlanI18nProvider translate={translate}>+ <PlanCopyButton+ content={formatted}+ label={translate("copy.plan")}+ />+ </QueryPlanI18nProvider></div>)}<pre className="min-h-0 flex-1 overflow-auto px-4 pb-4 font-mono text-xs leading-4 break-words whitespace-pre-wrap text-main">@@ -182,6 +194,7 @@ export function QueryPlanResultView({<TextPlansource={rawPlan}disallowCopyingData={disallowCopyingData}+ translate={translatePlan}/>) : null}</div>@@ -206,6 +219,7 @@ export function QueryPlanResultView({<TextPlansource={plan?.source ?? rawPlan}disallowCopyingData={disallowCopyingData}+ translate={translatePlan}/></TabsPanel></Tabs>diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex ee9ecd9beb..aa4f6416a8 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -140,13 +140,17 @@ export class BytebaseApiClient {// OAuth2 dynamic client registration (RFC 7591), the call an MCP client makes// before sending its user to the consent page. The backend accepts only// localhost, known hosted-client, and allowlisted app-scheme redirect URIs.+ // grantTypes defaults server-side to ["authorization_code"]; a refresh token+ // is issued only to a client that also registered "refresh_token".async registerOAuth2Client(clientName: string,redirectURIs: string[],+ grantTypes?: string[],): Promise<{ client_id: string }> {return this.request<{ client_id: string }>("POST", "/api/oauth2/register", {client_name: clientName,redirect_uris: redirectURIs,+ ...(grantTypes && { grant_types: grantTypes }),});}@@ -373,7 +377,14 @@ export class BytebaseApiClient {// Instancesasync getInstance(instanceName: string) {- return this.request<{ name: string; dataSources: { id: string; port: string; host: string }[] }>("GET", `/v1/${instanceName}`);+ return this.request<{ name: string; dataSources: { id: string; type?: string; port: string; host: string; username?: string }[] }>("GET", `/v1/${instanceName}`);+ }++ // Soft-delete a workspace instance created by a test. `force` moves its+ // databases to the default project first, which is what a workspace-level+ // instance needs before it can go.+ async deleteInstance(instanceName: string): Promise<void> {+ await this.request<unknown>("DELETE", `/v1/${instanceName}?force=true`);}// Set the instance's database sync allowlist (Instance.sync_databases). A@@ -487,10 +498,20 @@ export class BytebaseApiClient {}// Workload Identities- async createWorkloadIdentity(parent: string, workloadIdentityId: string, title: string, provider: string, issuer: string, subject: string) {+ async createWorkloadIdentity(+ parent: string,+ workloadIdentityId: string,+ title: string,+ config: {+ providerType: "GITHUB" | "GITLAB" | "OIDC";+ issuerUrl: string;+ allowedAudiences: string[];+ subjectPattern: string;+ },+ ) {return this.request<{ name: string; email: string }>("POST",`/v1/${parent}/workloadIdentities?workloadIdentityId=${workloadIdentityId}`,- { title, provider, attestationAuthority: { oidcAuthority: { issuer } }, subjectAttributes: { subject } });+ { title, workloadIdentityConfig: config });}async deleteWorkloadIdentity(email: string) {@@ -1083,4 +1104,68 @@ export class BytebaseApiClient {await client.login(email, password);return client;}++ // Remove one member from a workspace role binding, re-reading the policy so+ // the write carries a current etag. Inverse of addWorkspaceRoleMember.+ async removeWorkspaceRoleMember(workspace: string, email: string, role: string): Promise<void> {+ const policy = await this.getWorkspaceIamPolicy(workspace);+ const member = `user:${email}`;+ const bindings = (policy.bindings ?? []).map((b) =>+ b.role === role ? { ...b, members: (b.members ?? []).filter((m) => m !== member) } : b,+ );+ await this.setWorkspaceIamPolicy(workspace, { ...policy, bindings });+ }++ // Replace Plan.specs (AIP-134 PATCH with update_mask=specs). An accepted+ // specs update transfers last-plan-editor attribution to this client's user,+ // so call it on a client logged in as the user who should become the editor.+ async updatePlanSpecs(+ planName: string,+ specs: { id: string; changeDatabaseConfig?: { targets?: string[]; sheet?: string } }[],+ ): Promise<{ name: string; lastPlanEditor?: string }> {+ return this.request("PATCH", `/v1/${planName}?updateMask=specs`, { name: planName, specs });+ }++ // Authorization-code exchange with PKCE. Form-encoded per RFC 6749, so it+ // bypasses the JSON request helper.+ async exchangeOAuth2Code(params: {+ clientId: string;+ code: string;+ codeVerifier: string;+ redirectUri: string;+ }): Promise<{ access_token?: string; refresh_token?: string; token_type?: string; error?: string; error_description?: string }> {+ const resp = await fetch(`${this.baseURL}/api/oauth2/token`, {+ method: "POST",+ headers: { "Content-Type": "application/x-www-form-urlencoded" },+ body: new URLSearchParams({+ grant_type: "authorization_code",+ code: params.code,+ code_verifier: params.codeVerifier,+ client_id: params.clientId,+ redirect_uri: params.redirectUri,+ }),+ });+ return resp.json();+ }++ // One MCP `initialize` round trip with a bearer token, to prove a consented+ // grant opens an MCP session. Returns the HTTP status and the raw body (the+ // server streams JSON-RPC as SSE).+ async mcpInitialize(accessToken: string): Promise<{ status: number; body: string }> {+ const resp = await fetch(`${this.baseURL}/mcp`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json, text/event-stream",+ Authorization: `Bearer ${accessToken}`,+ },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "e2e", version: "0" } },+ }),+ });+ return { status: resp.status, body: await resp.text() };+ }}diff --git a/frontend/tests/e2e/framework/ui-create-plan.ts b/frontend/tests/e2e/framework/ui-create-plan.tsindex 29c9159a61..ef1e760487 100644--- a/frontend/tests/e2e/framework/ui-create-plan.ts+++ b/frontend/tests/e2e/framework/ui-create-plan.ts@@ -46,12 +46,13 @@ export async function createDatabaseChangePlanViaUI(// first-character loss), while Create only requires NON-EMPTY SQL — a damaged// statement would still be created and fail later, far from its cause.// `insertText` paints the whole string in one input event, and the editor is- // checked to show it before Create is pressed.+ // checked to show it before Create is pressed. The cursor ends on the last+ // line, which Monaco therefore renders however long the statement is.const editor = page.locator(".monaco-editor").first();await editor.click();await page.keyboard.insertText(opts.sql);await expect(editor.locator(".view-lines")).toContainText(- opts.sql.split("\n")[0].trim(),+ opts.sql.trim().split("\n").pop()!.trim(),{ timeout: 10_000 },);const createBtn = page.getByRole("button", { name: "Create", exact: true });diff --git a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.tsindex 9ce08766d4..4d8761aadb 100644--- a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts+++ b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts@@ -1,4 +1,5 @@import { test, expect, type Page, type BrowserContext } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";import { loadTestEnv, type TestEnv } from "../framework/env";import { BytebaseApiClient } from "../framework/api-client";import { getInstancePgPort, execSql } from "../framework/psql";@@ -678,6 +679,116 @@ test.describe("Composite Exemption Expiration (BYT-9788)", () => {});});+// ── Compound conditions and the database filter (3.24: #21609) ──++const EXEMPTION = enUS.project["masking-exemption"];+const DBA_EMAIL = "[email protected]";+const APPROVER_EMAIL = "[email protected]";++// Replaces the project's exemption policy with exactly these exemptions.+async function setExemptions(+ exemptions: { member: string; expression: string; description: string }[],+): Promise<void> {+ await env.api.upsertPolicy(env.project, "masking_exemption", {+ type: "MASKING_EXEMPTION",+ maskingExemptionPolicy: {+ exemptions: exemptions.map(({ member, expression, description }) => ({+ members: [member],+ condition: { expression, description },+ })),+ },+ });+}++// The scope the Grant page writes for one manually selected database.+function databaseScope(databaseName: string): string {+ return `(resource.instance_id == "${env.instanceId}" && resource.database_name == "${databaseName}")`;+}++test.describe("A compound condition reads back as its resources (K1)", () => {+ // An OR of a column-only clause and an instance/database/column clause, the+ // shape #21609's parser learned to read.+ let expression: string;++ test.beforeAll(async () => {+ expression =+ `(resource.column_name in ["salary", "amount"] || ` ++ `resource.instance_id == "${env.instanceId}" && resource.database_name == "${env.databaseId}" && resource.column_name == "emp_no")`;+ await setExemptions([{ member: `user:${env.adminEmail}`, expression, description: "K1 compound" }]);+ });++ test.afterAll(async () => {+ await revokeAllExemptions();+ });++ test("each clause reads back as its own resource row, and the raw CEL toggle shows the stored expression", async () => {+ await test.step("each clause is its own resource row; the member reads All databases", async () => {+ const listPage = new MaskingExemptionPage(page, env.baseURL);+ await listPage.goto(projectId);+ const summary = `${EXEMPTION["n-exemptions_one"].replace("{{n}}", "1")} · ${enUS.database.all}`;+ await expect(listPage.getMemberItem(env.adminEmail)).toContainText(summary);+ await listPage.selectMember(env.adminEmail);++ const columnOnly = page.getByRole("row").filter({ hasText: "salary, amount" });+ await expect(columnOnly).toHaveCount(1);+ await expect(columnOnly).toContainText(enUS.database.all);+ const scoped = page.getByRole("row").filter({ hasText: "emp_no" });+ await expect(scoped).toHaveCount(1);+ await expect(scoped).toContainText(env.instanceId);+ await expect(scoped).toContainText(env.databaseId);+ });++ await test.step("Show raw CEL condition reveals the stored expression and hides it again", async () => {+ const show = page.getByRole("button", { name: EXEMPTION["show-raw-cel-condition"] });+ await expect(show).toHaveAttribute("aria-expanded", "false");+ await show.click();+ const hide = page.getByRole("button", { name: EXEMPTION["hide-raw-cel-condition"] });+ await expect(hide).toHaveAttribute("aria-expanded", "true");+ await expect(page.locator("pre").filter({ hasText: "resource.column_name in" })).toHaveText(expression);+ await hide.click();+ await expect(page.locator("pre").filter({ hasText: "resource.column_name in" })).toHaveCount(0);+ });+ });+});++test.describe("Filtering by database keeps every exemption written for it (K2)", () => {+ test.beforeAll(async () => {+ await setExemptions([+ { member: `user:${DBA_EMAIL}`, expression: databaseScope(env.databaseId), description: "K2 this database" },+ { member: `user:${APPROVER_EMAIL}`, expression: databaseScope("e2e_other_db"), description: "K2 other database" },+ ]);+ });++ test.afterAll(async () => {+ await revokeAllExemptions();+ });++ test("the database's own exemption stays and another database's goes", async () => {+ // The suite's sample instance is project-owned, so the filter's value is+ // projects/<p>/instances/<i>/databases/<d>, while the parser names an+ // instance_id + database_name scope instances/<i>/databases/<d> and the+ // filter compares the two names exactly (BYT-10359).+ test.fail();+ const listPage = new MaskingExemptionPage(page, env.baseURL);+ await listPage.goto(projectId);+ await expect(listPage.getMemberItem(DBA_EMAIL)).toBeVisible();+ await expect(listPage.getMemberItem(APPROVER_EMAIL)).toBeVisible();++ await page.locator('input[autocomplete="off"]').first().click();+ await page+ .locator("[data-search-menu-option-index]")+ .filter({ hasText: enUS.issue["advanced-search"].scope.database.description })+ .click();+ await page.keyboard.type(env.databaseId, { delay: 30 });+ const database = page.locator("[data-search-menu-option-index]").filter({ hasText: env.databaseId });+ await database.first().click();+ await expect(page.locator('[data-search-scope-id="database"]')).toContainText(`/databases/${env.databaseId}`);++ await expect(listPage.getMemberItem(APPROVER_EMAIL)).toHaveCount(0);+ await expect(listPage.getMemberItem(DBA_EMAIL)).toBeVisible({ timeout: 5_000 });+ });+});+// ── Responsive Layout ──test.describe("Responsive Layout", () => {diff --git a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.tsindex 22ebbb8586..f04b5cc1f4 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-review.spec.ts@@ -49,9 +49,14 @@ import {type Page,type BrowserContext,} from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";import { loadTestEnv, type TestEnv } from "../framework/env";import { BytebaseApiClient, type IamPolicy } from "../framework/api-client";import { signInBrowserAs } from "../framework/sign-in";+import {+ createDatabaseChangePlanViaUI,+ submitDraftForReviewViaUI,+} from "../framework/ui-create-plan";import { PlanDetailPage } from "./plan-detail.page";import {authorMayApprove,@@ -1557,3 +1562,503 @@ test.describe("Inline comment threads: walker scrolls the editor once (CUJ N)",expect(await planPage.countStatementEditorScrolls(stepTo(longRoot))).toBe(0);});});++// --- Approval by the person who last changed the plan (3.23, #21298/#21315) ---+//+// Last Plan Editor attribution follows accepted Plan.specs mutations; the+// project setting allow_last_plan_editor_approval (false for an API-created+// project such as project-sample) decides whether that user may approve. It is+// separate from and cumulative with allow_self_approval+// (docs/design/last-plan-change-approval.md). dba1 joins the workspaceAdmin+// step for these blocks so the one-step flow has a second candidate; the+// binding and the setting are restored in afterAll.++const LAST_EDITOR_TOOLTIP = enUS.plan.review["last-plan-editor-cannot-approve"];+const LAST_EDITOR_LINE = enUS.plan.review["candidate-last-changed-plan"];+const LAST_EDITOR_SETTING =+ enUS.project.settings["issue-related"]["allow-last-plan-editor-approval"].self;+const DBA_EMAIL = "[email protected]";+const DBA_PASSWORD = "12345678"; // NOSONAR: e2e fixture++const approveOption = (p: Page) => p.getByRole("radio", { name: /^Approve/ });+const rejectOption = (p: Page) => p.getByRole("radio", { name: /^Reject/ });++async function openReviewPopover(p: Page, planDetail: PlanDetailPage): Promise<void> {+ await planDetail.reviewButton.click();+ await expect(approveOption(p)).toBeVisible({ timeout: 15_000 });+}++// The candidate line under the approval step, e.g. "Demo: Can't approve — …".+function lastEditorLine(p: Page, displayName: string) {+ return p.locator("#plan-phase-review").getByText(`${displayName}: ${LAST_EDITOR_LINE}`);+}++test.describe("The last plan editor cannot approve by default; another reviewer can (L1)", () => {+ test.describe.configure({ mode: "serial" });+ let workspace: string;+ let originalAllowLastEditor: boolean;+ let dbaContext: BrowserContext;+ let dbaPage: Page;+ let dbaPlanPage: PlanDetailPage;+ let planId: string;+ let issueName: string;++ test.beforeAll(async ({ browser }) => {+ await setupApproval(ONE_STEP_RULE);+ originalAllowLastEditor = !!(await env.api.getProject(env.project)).allowLastPlanEditorApproval;+ // The author may self-approve; only the last-editor rule is in force.+ await env.api.updateProjectSettings(env.project, {+ allowSelfApproval: true,+ allowLastPlanEditorApproval: false,+ });+ workspace = (await env.api.getActuatorInfo()).workspace;+ await env.api.addWorkspaceRoleMember(workspace, DBA_EMAIL, "roles/workspaceAdmin");++ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review L1",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_l1_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ issueName = seeded.issueName;++ await signInBrowserAs(browser, env.baseURL, DBA_EMAIL, DBA_PASSWORD, ".auth/dba-last-editor.json");+ dbaContext = await browser.newContext({ storageState: ".auth/dba-last-editor.json" });+ dbaPage = await dbaContext.newPage();+ dbaPlanPage = new PlanDetailPage(dbaPage, env.baseURL);+ });++ test.afterAll(async () => {+ await dbaContext?.close();+ await env.api+ .removeWorkspaceRoleMember(workspace, DBA_EMAIL, "roles/workspaceAdmin")+ .catch((e) => console.warn("cleanup failed: dba1 admin binding", e));+ await env.api+ .updateProjectSettings(env.project, { allowLastPlanEditorApproval: originalAllowLastEditor })+ .catch((e) => console.warn("cleanup failed: allowLastPlanEditorApproval", e));+ });++ test("the creator, who last changed the plan, sees Approve disabled with the reason; Reject stays open", async () => {+ await goReview(planId);+ await expect(lastEditorLine(page, "Demo")).toBeVisible({ timeout: 15_000 });+ await openReviewPopover(page, planPage);+ await expect(approveOption(page)).toBeDisabled();+ await expect(rejectOption(page)).toBeEnabled();+ await approveOption(page).hover();+ await expect(page.getByText(LAST_EDITOR_TOOLTIP)).toBeVisible();+ await page.keyboard.press("Escape");+ });++ test("the other candidate approves", async () => {+ await dbaPlanPage.goto(projectId, planId);+ await dbaPlanPage.dismissModals();+ await dbaPlanPage.expandSection("Review");+ await openReviewPopover(dbaPage, dbaPlanPage);+ await expect(approveOption(dbaPage)).toBeEnabled();+ await dbaPage.keyboard.press("Escape");+ await dbaPlanPage.submitReview("Approve");+ await expect(dbaPlanPage.reviewBadge("Approved")).toBeVisible({ timeout: 15_000 });+ expect((await env.api.getIssue(issueName)).approvalStatus).toBe("APPROVED");+ });+});++test.describe("The project setting and plan edits move who may approve (L2/L3)", () => {+ test.describe.configure({ mode: "serial" });+ let workspace: string;+ let originalAllowLastEditor: boolean;+ let dbaApi: BytebaseApiClient;+ let dbaContext: BrowserContext;+ let dbaPage: Page;+ let dbaPlanPage: PlanDetailPage;+ let planId: string;+ let planName: string;++ test.beforeAll(async ({ browser }) => {+ await setupApproval(ONE_STEP_RULE);+ originalAllowLastEditor = !!(await env.api.getProject(env.project)).allowLastPlanEditorApproval;+ await env.api.updateProjectSettings(env.project, {+ allowSelfApproval: true,+ allowLastPlanEditorApproval: false,+ });+ workspace = (await env.api.getActuatorInfo()).workspace;+ await env.api.addWorkspaceRoleMember(workspace, DBA_EMAIL, "roles/workspaceAdmin");++ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review L2",+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_l2_${Date.now()} TEXT;`,+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ planName = seeded.planName;++ dbaApi = await BytebaseApiClient.asUser(env.baseURL, DBA_EMAIL, DBA_PASSWORD);+ await signInBrowserAs(browser, env.baseURL, DBA_EMAIL, DBA_PASSWORD, ".auth/dba-last-editor.json");+ dbaContext = await browser.newContext({ storageState: ".auth/dba-last-editor.json" });+ dbaPage = await dbaContext.newPage();+ dbaPlanPage = new PlanDetailPage(dbaPage, env.baseURL);+ });++ test.afterAll(async () => {+ await dbaContext?.close();+ await env.api+ .removeWorkspaceRoleMember(workspace, DBA_EMAIL, "roles/workspaceAdmin")+ .catch((e) => console.warn("cleanup failed: dba1 admin binding", e));+ await env.api+ .updateProjectSettings(env.project, { allowLastPlanEditorApproval: originalAllowLastEditor })+ .catch((e) => console.warn("cleanup failed: allowLastPlanEditorApproval", e));+ });++ test("turning the setting on in Project Settings lets the last editor approve (L2)", async () => {+ await page.goto(`${env.baseURL}/projects/${projectId}/settings`);+ // The switch carries no accessible name of its own; it sits beside its+ // label in the same control row.+ const toggle = page+ .getByText(LAST_EDITOR_SETTING, { exact: true })+ .locator("..")+ .getByRole("switch");+ await expect(toggle).toBeVisible({ timeout: 15_000 });+ await expect(toggle).not.toBeChecked();+ await toggle.click();+ await expect(toggle).toBeChecked();+ await page.getByRole("button", { name: enUS.common.update, exact: true }).click();+ await expect+ .poll(async () => !!(await env.api.getProject(env.project)).allowLastPlanEditorApproval, {+ timeout: 10_000,+ })+ .toBe(true);++ await goReview(planId);+ await expect(lastEditorLine(page, "Demo")).toHaveCount(0);+ await openReviewPopover(page, planPage);+ await expect(approveOption(page)).toBeEnabled();+ await page.keyboard.press("Escape");+ });++ test("turning it off again restores the block (L2, inverse)", async () => {+ await env.api.updateProjectSettings(env.project, { allowLastPlanEditorApproval: false });+ await goReview(planId);+ await expect(lastEditorLine(page, "Demo")).toBeVisible({ timeout: 15_000 });+ await openReviewPopover(page, planPage);+ await expect(approveOption(page)).toBeDisabled();+ await page.keyboard.press("Escape");+ });++ test("an accepted specs update by another user moves the block to that user (L3)", async () => {+ await env.api.updateProjectSettings(env.project, { allowLastPlanEditorApproval: false });+ const plan = await env.api.getPlan(planName);+ const sheet = await env.api.createSheet(+ env.project,+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_l3_${Date.now()} TEXT;`,+ );+ const specs = (plan.specs ?? []).map((spec) => ({+ ...spec,+ changeDatabaseConfig: { ...spec.changeDatabaseConfig, sheet },+ }));+ const updated = await dbaApi.updatePlanSpecs(planName, specs);+ expect(updated.lastPlanEditor).toBe(`users/${DBA_EMAIL}`);++ // The creator is no longer the last editor and may approve; dba1 is.+ await goReview(planId);+ await expect(lastEditorLine(page, "DBA1")).toBeVisible({ timeout: 15_000 });+ await expect(lastEditorLine(page, "Demo")).toHaveCount(0);+ await openReviewPopover(page, planPage);+ await expect(approveOption(page)).toBeEnabled();+ await page.keyboard.press("Escape");++ await dbaPlanPage.goto(projectId, planId);+ await dbaPlanPage.dismissModals();+ await dbaPlanPage.expandSection("Review");+ await openReviewPopover(dbaPage, dbaPlanPage);+ await expect(approveOption(dbaPage)).toBeDisabled();+ await dbaPage.keyboard.press("Escape");+ });+});++// --- Inline comments: creation gate, plain vs thread, placement across edits ---+// (3.23: #21514 blocks creation before review submission; #21339 keeps general+// comments plain; #21386's placement engine shifts or outdates an anchor when+// the statement changes — the one flow that PR left unverified in a browser.)++// A timeline card's statement anchor. The recorded statement downloads only+// once the card nears the viewport (StatementAnchorContext's useInViewOnce),+// so the card is scrolled in first; until then the anchor reads PENDING.+async function timelineAnchor(rootText: string) {+ const card = planPage.threadCardIn("review", rootText);+ await card.scrollIntoViewIfNeeded();+ return card.getByTestId("statement-anchor");+}++// The line the editor's single thread marker sits on, by matching its top edge+// to a line-number cell (Monaco renders only the lines in view).+async function markerLine(): Promise<string> {+ return planPage.statementEditor.evaluate((editor) => {+ const marker = editor.querySelector(".bb-thread-glyph");+ if (!marker) return "";+ const top = marker.getBoundingClientRect().top;+ const cell = Array.from(editor.querySelectorAll(".margin-view-overlays .line-numbers")).find(+ (candidate) => Math.abs(candidate.getBoundingClientRect().top - top) < 4,+ );+ return cell?.textContent?.trim() ?? "?";+ });+}++test.describe("Inline comments open with review submission, plain comments stay plain, anchors follow edits (C1–C3)", () => {+ const stamp = Date.now();+ const lines = [1, 2, 3].map(+ (n) => `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_c${n}_${stamp} TEXT;`,+ );+ const insertedLine = `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_c0_${stamp} TEXT;`;+ const plainText = `C2 plain comment ${stamp}`;+ const rootText = `C2 thread on line 3 ${stamp}`;+ let planId: string;+ let planName: string;++ // Replace the statement through the API (a new sheet in Plan.specs), then+ // reload so the placement engine re-anchors against the current sheet.+ async function replaceStatement(sql: string): Promise<void> {+ const plan = await env.api.getPlan(planName);+ const sheet = await env.api.createSheet(env.project, sql);+ await env.api.updatePlanSpecs(+ planName,+ (plan.specs ?? []).map((spec) => ({+ ...spec,+ changeDatabaseConfig: { ...spec.changeDatabaseConfig, sheet },+ })),+ );+ await page.reload();+ await planPage.dismissModals();+ await planPage.expandSection("Changes");+ await expect(planPage.statementEditor).toBeVisible({ timeout: 15_000 });+ }++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const created = await createDatabaseChangePlanViaUI(page, {+ baseURL: env.baseURL,+ projectId,+ database: env.database,+ title: `E2E Review C ${stamp}`,+ sql: lines.join("\n"),+ });+ planId = created.planId;+ planName = `${env.project}/plans/${planId}`;+ await planPage.dismissModals();+ });++ test("a thread opens with review submission, stays apart from plain comments, and follows statement edits", async () => {+ test.setTimeout(300_000);+ await test.step("a draft offers no way to start a thread; Ready for Review opens it (C1)", async () => {+ await planPage.expandSection("Changes");+ await expect(planPage.statementEditor).toBeVisible();+ await expect(planPage.statementEditor).not.toHaveClass(/bb-thread-creatable/);+ await planPage.hoverStatementLine(2);+ await expect(planPage.addThreadGlyph).toHaveCount(0);+ await expect(planPage.composerTrigger).toHaveCount(0);++ await submitDraftForReviewViaUI(page);+ await expect(planPage.statementEditor).toHaveClass(/bb-thread-creatable/, { timeout: 15_000 });+ await expect(planPage.composerTrigger).toBeVisible();+ await planPage.hoverStatementLine(2);+ await expect(planPage.addThreadGlyph).toBeVisible();+ });++ await test.step("a general comment renders as a plain row; a gutter comment is a thread (C2)", async () => {+ await planPage.composerTrigger.click();+ await planPage.composerEditor.fill(plainText);+ await planPage.composerSubmitButton.click();+ const timeline = page.locator("#plan-phase-review");+ const plain = timeline.getByText(plainText, { exact: true });+ await expect(plain).toBeVisible({ timeout: 15_000 });+ // Not a thread: no card, and no Reply / Resolve on its row.+ await expect(timeline.getByTestId("comment-thread").filter({ hasText: plainText })).toHaveCount(0);+ await expect(+ plain.locator("xpath=ancestor::li[1]").getByRole("button", { name: /^(Reply|Resolve)/ }),+ ).toHaveCount(0);++ await planPage.openInlineComposerOn(3);+ await planPage.inlineComposerEditor.fill(rootText);+ await planPage.inlineComposerPublishButton.click();+ await expect(planPage.threadMarkers).toHaveCount(1, { timeout: 15_000 });+ expect(await markerLine()).toBe("3");+ const card = planPage.threadCardIn("review", rootText);+ await expect(card).toBeVisible();+ await expect(card.getByRole("button", { name: "Resolve", exact: true })).toBeVisible();+ await expect(card.getByRole("button", { name: /^Reply/ })).toBeVisible();+ const anchor = await timelineAnchor(rootText);+ await expect(anchor).toHaveAttribute("data-anchor-state", "CURRENT", { timeout: 15_000 });+ await expect(anchor).toContainText("Line 3");+ });++ await test.step("an edit above the anchor shifts the marker and keeps the card current (C3)", async () => {+ await replaceStatement([insertedLine, ...lines].join("\n"));+ await expect(planPage.threadMarkers).toHaveCount(1, { timeout: 15_000 });+ await expect.poll(markerLine).toBe("4");+ const anchor = await timelineAnchor(rootText);+ await expect(anchor).toHaveAttribute("data-anchor-state", "CURRENT", { timeout: 15_000 });+ // The card keeps the lines as originally selected.+ await expect(anchor).toContainText("Line 3");+ });++ await test.step("an edit on the anchored line outdates the thread and removes its marker (C3)", async () => {+ await replaceStatement(+ [+ insertedLine,+ lines[0],+ lines[1],+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_c3_changed_${stamp} TEXT;`,+ ].join("\n"),+ );+ const anchor = await timelineAnchor(rootText);+ await expect(anchor).toHaveAttribute("data-anchor-state", "OUTDATED", { timeout: 15_000 });+ await expect(anchor).toContainText(enUS.plan.review.thread.anchor.outdated);+ await expect(planPage.threadMarkers).toHaveCount(0);+ });+ });+});++// Editing a statement under review keeps the reader's place (3.24: #21547), and+// a Review Activity link lands in the edit editor too (#21543). The read-only+// editor shows thread view zones the edit editor lacks, so a place restored by+// pixels would drift; the tall thread on line 5 makes that drift large.+test.describe("Editing keeps the reading position; Activity links land in the edit editor (C4–C5)", () => {+ test.describe.configure({ mode: "serial" });+ const stamp = Date.now();+ const LINE_COUNT = 60;+ const ACTIVITY_LINE = 50;+ const tallRoot = `C4 tall thread on line 5 ${stamp}`;+ const tallBody = [tallRoot]+ .concat(Array.from({ length: 12 }, (_, i) => `Note ${i + 1} on the column this line adds.`))+ .join("\n\n");+ const farRoot = `C5 thread on line ${ACTIVITY_LINE} ${stamp}`;+ let planId: string;+ let specId: string;++ const changes = () => page.locator("#plan-phase-changes");+ // The statement's own controls show their label; thread cards' are icon buttons.+ const editButton = () =>+ changes().getByRole("button", { name: enUS.common.edit, exact: true }).filter({ hasText: enUS.common.edit });+ const cancelButton = () =>+ changes().getByRole("button", { name: enUS.common.cancel, exact: true }).filter({ hasText: enUS.common.cancel });++ // The first line whose number cell is at or below the editor's top edge.+ async function topVisibleLine(): Promise<number> {+ return planPage.statementEditor.evaluate((editor) => {+ const top = editor.getBoundingClientRect().top;+ const cells = Array.from(editor.querySelectorAll<HTMLElement>(".margin-view-overlays .line-numbers"))+ .map((cell) => ({ line: Number(cell.textContent?.trim()), top: cell.getBoundingClientRect().top }))+ .filter((cell) => cell.top >= top - 1)+ .sort((a, b) => a.top - b.top);+ return cells[0]?.line ?? 0;+ });+ }++ // A line's text, by matching its view line to its number cell.+ async function lineText(lineNumber: number): Promise<string> {+ return planPage.statementEditor.evaluate((editor, wanted) => {+ const cell = Array.from(editor.querySelectorAll(".margin-view-overlays .line-numbers")).find(+ (candidate) => candidate.textContent?.trim() === String(wanted),+ );+ if (!cell) return "";+ const top = cell.getBoundingClientRect().top;+ const line = Array.from(editor.querySelectorAll(".view-lines .view-line")).find(+ (candidate) => Math.abs(candidate.getBoundingClientRect().top - top) < 4,+ );+ return line?.textContent?.replace(/ /g, " ") ?? "";+ }, lineNumber);+ }++ test.beforeAll(async () => {+ await setupApproval(ONE_STEP_RULE);+ const seeded = await seedReviewPlan(env, page, {+ prefix: "E2E Review C4",+ sql: Array.from(+ { length: LINE_COUNT },+ (_, i) => `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_rev_c4_${i + 1}_${stamp} TEXT;`,+ ).join("\n"),+ });+ await waitForApprovalStatus(env.api, seeded.issueName, ["PENDING"]);+ planId = seeded.planId;+ const plan = await env.api.getPlan(seeded.planName);+ const spec = plan.specs?.[0];+ specId = spec?.id ?? "";+ const sheetSha256 = spec?.changeDatabaseConfig?.sheet?.split("/").pop() ?? "";+ expect(specId).not.toBe("");+ const anchor = (line: number) => ({+ statementAnchor: { spec: specId, sheetSha256, startLine: line, endLine: line },+ });+ await env.api.createIssueComment(seeded.issueName, tallBody, anchor(5));+ await env.api.createIssueComment(seeded.issueName, farRoot, anchor(ACTIVITY_LINE));+ });++ test("Edit keeps the top line in view and the cursor where it was (C4)", async () => {+ await goReview(planId);+ await planPage.expandSection("Changes");+ // The first unresolved thread opens by default, so its view zone is in place.+ await expect(planPage.threadCardIn("changes", tallRoot)).toBeVisible({ timeout: 15_000 });+ // Read to the end the way a reviewer can: a click on the anchored line (the+ // thread's zone fills the rest of the view), then Ctrl+End, which scrolls to+ // the last line and puts the cursor there.+ await planPage.statementEditor+ .locator(".view-lines .view-line")+ // Monaco renders spaces as no-break spaces, which \s matches.+ .filter({ hasText: new RegExp(`e2e_rev_c4_5_${stamp}\\s`) })+ .click({ timeout: 10_000 });+ await page.keyboard.press("Control+End");+ await expect.poll(topVisibleLine).toBeGreaterThan(30);+ const top = await topVisibleLine();++ await editButton().click();+ await expect(cancelButton()).toBeVisible();+ await expect.poll(() => planPage.statementLineOffset(top)).toBeGreaterThanOrEqual(0);+ expect(await planPage.statementLineOffset(top)).toBeLessThan(24);+ // Focused with the cursor kept: typing lands at the end of the last line.+ await expect(planPage.statementEditor).toHaveClass(/\bfocused\b/);+ await page.keyboard.type("-- C4");+ await expect.poll(() => lineText(LINE_COUNT)).toMatch(/TEXT;-- C4$/);++ await cancelButton().click();+ await expect(editButton()).toBeVisible();+ });++ // Edit, park the edit editor on line 1, then follow the far thread's link.+ async function followActivityLinkWhileEditing(): Promise<void> {+ await planPage.expandSection("Changes");+ await editButton().click();+ await expect(cancelButton()).toBeVisible();+ await planPage.statementEditor.click({ position: { x: 300, y: 10 } });+ await page.keyboard.press("Control+Home");+ await expect(planPage.statementLineNumber(ACTIVITY_LINE)).toHaveCount(0);++ await planPage.expandSection("Review");+ const card = planPage.threadCardIn("review", farRoot);+ await card.scrollIntoViewIfNeeded();+ await card.getByRole("button", { name: enUS.plan.review.thread.anchor["view-in-statement"] }).click();+ }++ async function expectLineRevealedForTyping(): Promise<void> {+ await expect(page.getByRole("alertdialog")).toHaveCount(0);+ await expect(planPage.statementLineNumber(ACTIVITY_LINE)).toBeInViewport({ timeout: 10_000 });+ await expect(planPage.statementEditor).toHaveClass(/\bfocused\b/);+ await page.keyboard.type("-- C5 ");+ await expect.poll(() => lineText(ACTIVITY_LINE)).toMatch(/^-- C5 ALTER TABLE/);+ await cancelButton().click();+ await expect(editButton()).toBeVisible();+ }++ test("from the spec's URL, an Activity link while editing reveals its line in the edit editor (C5)", async () => {+ await page.goto(`${env.baseURL}/projects/${projectId}/plans/${planId}/specs/${specId}`);+ await planPage.dismissModals();+ await followActivityLinkWhileEditing();+ await expectLineRevealedForTyping();+ });++ test("from the plan's URL, an Activity link while editing does not ask to leave (C5)", async () => {+ // The plan list links here. With no spec in the URL the link pushes the+ // spec's route, and the plan's leave guard treats that in-page move as+ // leaving while any editor is open (BYT-10360).+ test.fail();+ await goReview(planId);+ await followActivityLinkWhileEditing();+ await expectLineRevealedForTyping();+ });+});diff --git a/frontend/tests/e2e/schema-editor/schema-editor.page.ts b/frontend/tests/e2e/schema-editor/schema-editor.page.tsindex 0965fce3a6..01bc97b75e 100644--- a/frontend/tests/e2e/schema-editor/schema-editor.page.ts+++ b/frontend/tests/e2e/schema-editor/schema-editor.page.ts@@ -255,10 +255,9 @@ export class SchemaEditorPage {// Reads the Preview pane's readonly Monaco. Content extraction (not a control// assertion), so reading the editor's text is acceptable. Line numbers are// included but harmless for substring assertions.+ // The preview's complete DDL; see monacoText for why not `.view-lines`.async previewText(): Promise<string> {- const preview = this.sheet.locator(".monaco-editor .view-lines").last();- await expect(preview).toBeVisible({ timeout: 10_000 });- return (await preview.innerText()).replace(/ /g, " ");+ return this.monacoText(this.sheet.locator(".monaco-editor").last());}// ---- Insert / statement ----@@ -267,11 +266,17 @@ export class SchemaEditorPage {await expect(this.sheet).toBeHidden({ timeout: 15_000 });}- // Reads the plan's statement Monaco editor — the COMPLETE text, not the- // rendered viewport. That editor VIRTUALIZES: only the lines in view exist in- // the DOM, so a `.view-lines` read silently truncates a multi-statement DDL- // (this is why a created-table PK, emitted as a trailing separate- // `ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY`, appeared "missing").+ // The plan's statement editor's complete text.+ async planStatementText(): Promise<string> {+ return this.monacoText(this.page.locator(".monaco-editor").first());+ }++ // Reads a Monaco editor's COMPLETE text, not the rendered viewport. Monaco+ // VIRTUALIZES: only the lines in view exist in the DOM, so a `.view-lines`+ // read silently truncates a multi-statement DDL, or a long line wrapped past+ // the bottom edge (a created-table PK, emitted as a trailing separate+ // `ALTER TABLE ... ADD CONSTRAINT ... PRIMARY KEY`, has appeared "missing"+ // both ways).// `window.monaco` is not exposed on the production bundle, so the model is// read the way a user copies it: select all, then copy. Monaco's own copy// handler writes the full selection into the copy event's clipboardData, and@@ -280,8 +285,7 @@ export class SchemaEditorPage {// does not share between a native copy and navigator.clipboard anyway. Each// step waits on its observable effect; the selection is collapsed afterwards// so the editor is left as it was found.- async planStatementText(): Promise<string> {- const editor = this.page.locator(".monaco-editor").first();+ private async monacoText(editor: Locator): Promise<string> {await expect(editor.locator(".view-lines")).toBeVisible({ timeout: 10_000 });await this.page.evaluate(() => {const w = window as unknown as {diff --git a/frontend/tests/e2e/sql-editor/sql-editor-query-plan.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-query-plan.spec.tsnew file mode 100644index 0000000000..5869d4ba8f--- /dev/null+++ b/frontend/tests/e2e/sql-editor/sql-editor-query-plan.spec.ts@@ -0,0 +1,211 @@+// SQL Editor — query plans drawn inline in the result pane (3.23: #21443,+// #21448, #21492, #21493; reshaped by #21646, #21652, #21666).+//+// What the pane draws and what it costs follow+// docs/design/query-plan-visualizer.md §3:+// - Explain (Ctrl/Cmd+E) → asks for the viewer's format: ONE Query call+// - typed EXPLAIN (FORMAT JSON) → drawn from what came back: ONE Query call+// - typed EXPLAIN ANALYZE → executed the statement, so never replayed: text only+// - a plain SELECT → the grid, with Plan in the view switch; choosing+// it explains the executed statement once and the+// plan is cached on the result+// A drawn plan opens on the Diagram tab with its costliest operator selected.+// The request budget is asserted, not just the tabs: a picture must never+// re-execute a statement or plan it twice.++import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient } from "../framework/api-client";+import { SqlEditorPage } from "./sql-editor.page";++// Labels are read from the locale so a copy edit fails here, not silently.+const SQL_EDITOR = enUS["sql-editor"];+const VIEWER = SQL_EDITOR["query-plan-viewer"];+const TAB = VIEWER.tab;+const TEXT_ONLY_TAB = enUS.common.plan;+const COPY_PLAN = VIEWER.copy.plan;+const QUERY_RPC = "/bytebase.v1.SQLService/Query";++test.setTimeout(90_000);++let env: TestEnv & { api: BytebaseApiClient };+let sharedContext: BrowserContext;+let page: Page;+let sqlEditor: SqlEditorPage;+// The body of every SQLService/Query request since the last reset — the cost+// oracle. Bodies are binary protobuf; the statement text survives as ASCII.+const queryRequests: string[] = [];++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+ page.on("request", (request) => {+ if (request.url().endsWith(QUERY_RPC)) queryRequests.push(request.postData() ?? "");+ });+ sqlEditor = new SqlEditorPage(page, env.baseURL);+});++test.afterAll(async () => {+ await sharedContext?.close();+});++// Each describe re-enters the connected DB URL, which opens a fresh saved+// query tab and isolates it from the previous describe's editor + results.+async function openFreshConnectedTab(): Promise<void> {+ const projectId = env.project.split("/").pop()!;+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await expect(sqlEditor.codeEditor.first()).toBeVisible({ timeout: 15_000 });+}++function tab(name: string) {+ return page.getByRole("tab", { name, exact: true });+}++// The active panel of the plan viewer's tab row.+function activePanel() {+ return page.getByRole("tabpanel").last();+}++function viewSwitch() {+ return page.getByRole("radiogroup", { name: SQL_EDITOR["result-view-mode"] });+}++// The Explain shortcut is a Monaco keybinding, so the modifier is Control:+// Monaco reads its CtrlCmd key from the user agent, and the suite's Desktop+// Chrome device reports Windows on every host (AGENTS.md §6).+async function explainCurrentStatement(): Promise<void> {+ await sqlEditor.codeEditor.first().click();+ await page.keyboard.press("Control+e");+}++const STATEMENT = "SELECT * FROM employee WHERE emp_no = 10001";+const NODE = /^Index Scan, employee/;++// The plan opened on the Diagram tab, its one operator selected and ranked+// first in the side panel's costliest list.+async function expectDiagramOpenedOnCostliest(): Promise<void> {+ await expect(tab(TAB.diagram)).toBeVisible({ timeout: 20_000 });+ await expect(tab(TAB.diagram)).toHaveAttribute("aria-selected", "true");+ await expect(page.getByRole("button", { name: NODE })).toHaveAttribute("aria-pressed", "true");+ await expect(page.getByText(VIEWER.summary.costliest, { exact: true })).toBeVisible();+}++test.describe("Explain draws the plan inline in one call (P1)", () => {+ test.beforeAll(async () => {+ await openFreshConnectedTab();+ await sqlEditor.setEditorContent(STATEMENT);+ queryRequests.length = 0;+ await explainCurrentStatement();+ await expect(tab(TAB.diagram)).toBeVisible({ timeout: 20_000 });+ });++ test("Diagram opens first on the costliest operator; Table and Text are offered", async () => {+ await expectDiagramOpenedOnCostliest();+ await expect(page.getByText(/^1 nodes · estimated cost/)).toBeVisible();+ for (const name of [TAB.grid, TAB.text]) {+ await expect(tab(name)).toBeVisible();+ }+ // Retired by #21652: the Query and Summary tabs.+ await expect(page.getByRole("tab", { name: /^(Query|Summary)$/ })).toHaveCount(0);+ });++ test("Table lists the node; Text shows the engine's JSON plan with Copy plan", async () => {+ await tab(TAB.grid).click();+ await expect(page.getByRole("columnheader", { name: "Node" })).toBeVisible();+ await expect(page.getByRole("cell", { name: /Index Scan employee/ })).toBeVisible();++ await tab(TAB.text).click();+ await expect(activePanel()).toContainText('"Node Type": "Index Scan"');+ await expect(activePanel().getByRole("button", { name: COPY_PLAN, exact: true })).toBeVisible();+ });++ test("the picture costs one Query call: the plan is asked for in the viewer's format", async () => {+ // #21666: before, Explain fetched a text plan and replayed it as FORMAT+ // JSON for the picture — two planner runs for one plan.+ expect(queryRequests).toHaveLength(1);+ expect(queryRequests[0]).toContain(STATEMENT);+ });+});++test.describe("A typed EXPLAIN (FORMAT JSON) is drawn from what came back (P2)", () => {+ test("the diagram renders with no replay: one Query call", async () => {+ await openFreshConnectedTab();+ await sqlEditor.setEditorContent(`EXPLAIN (FORMAT JSON) ${STATEMENT}`);+ queryRequests.length = 0;+ await sqlEditor.runButton.click();+ await expectDiagramOpenedOnCostliest();+ await tab(TAB.text).click();+ await expect(activePanel()).toContainText('"Node Type": "Index Scan"');+ // Settled: the result rendered its picture without asking the server again.+ expect(queryRequests).toHaveLength(1);+ });+});++test.describe("A typed EXPLAIN ANALYZE executed the statement and is never replayed (P3)", () => {+ test("the plan stays text-only, with no Diagram tab, no Plan option and one Query call", async () => {+ await openFreshConnectedTab();+ await sqlEditor.setEditorContent(`EXPLAIN ANALYZE ${STATEMENT}`);+ queryRequests.length = 0;+ await sqlEditor.runButton.click();+ await expect(tab(TEXT_ONLY_TAB)).toBeVisible({ timeout: 20_000 });+ await expect(activePanel()).toContainText(/actual time=/);+ // The same labelled copy control as the visualizer's Text tab.+ await expect(activePanel().getByRole("button", { name: COPY_PLAN, exact: true })).toBeVisible();+ await expect(tab(TAB.diagram)).toHaveCount(0);+ // A result that already is a plan offers no Plan view of itself.+ await expect(viewSwitch().getByRole("radio", { name: SQL_EDITOR["plan-view"] })).toHaveCount(0);+ expect(queryRequests).toHaveLength(1);+ });+});++test.describe("A plain SELECT offers its plan in the view switch (P4)", () => {+ test("Plan explains the executed statement once, is cached on the result, and is remembered on re-run", async () => {+ test.setTimeout(150_000);+ await test.step("rows render in the Table view; no plan is fetched until asked", async () => {+ await openFreshConnectedTab();+ await sqlEditor.setEditorContent(STATEMENT);+ queryRequests.length = 0;+ await sqlEditor.runButton.click();+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({ timeout: 20_000 });+ await expect(page.locator('[data-row-index="0"]').first()).toContainText("10001");+ await expect(viewSwitch().getByRole("radio", { name: SQL_EDITOR["table-view"] })).toBeChecked();+ await expect(viewSwitch().getByRole("radio", { name: SQL_EDITOR["plan-view"] })).toBeEnabled();+ await expect(tab(TAB.diagram)).toHaveCount(0);+ expect(queryRequests).toHaveLength(1);+ });++ await test.step("Plan explains the executed statement once, limit included, and marks it Estimated", async () => {+ queryRequests.length = 0;+ // The radio is visually hidden inside its segment; the label takes the click.+ await viewSwitch().getByRole("radio", { name: SQL_EDITOR["plan-view"] }).click({ force: true });+ await expectDiagramOpenedOnCostliest();+ await expect(page.getByText(SQL_EDITOR["plan-estimated"], { exact: true })).toBeVisible();+ expect(queryRequests).toHaveLength(1);+ expect(queryRequests[0]).toContain(`${STATEMENT} LIMIT 1000`);+ });++ await test.step("Table and back to Plan sends nothing: the plan is cached on the result", async () => {+ queryRequests.length = 0;+ await viewSwitch().getByRole("radio", { name: SQL_EDITOR["table-view"] }).click({ force: true });+ await expect(page.locator('[data-row-index="0"]').first()).toContainText("10001");+ await viewSwitch().getByRole("radio", { name: SQL_EDITOR["plan-view"] }).click({ force: true });+ await expect(page.getByRole("button", { name: NODE })).toBeVisible();+ expect(queryRequests).toHaveLength(0);+ });++ await test.step("a re-run in the same tab reopens on the remembered Plan view", async () => {+ // The editor drops a run within a second of the previous one+ // (QUERY_INTERVAL_LIMIT in hooks/useExecuteSQL.ts).+ await page.waitForTimeout(1_100);+ queryRequests.length = 0;+ await sqlEditor.runButton.click();+ // The run, then the fresh result's own plan.+ await expect.poll(() => queryRequests.length, { timeout: 20_000 }).toBe(2);+ await expect(viewSwitch().getByRole("radio", { name: SQL_EDITOR["plan-view"] })).toBeChecked();+ await expectDiagramOpenedOnCostliest();+ });+ });+});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.tsindex ad7ed6323a..d74b11bbb9 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts@@ -7,6 +7,7 @@// a bug-lock (BYT-9478 row-selection highlight) marked inline.import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";import { loadTestEnv, type TestEnv } from "../framework/env";import type { BytebaseApiClient } from "../framework/api-client";import { SqlEditorPage } from "./sql-editor.page";@@ -435,3 +436,139 @@ test.describe("Detail panel scrolls long content to the last line (BYT-9610)", (await page.keyboard.press("Escape");});});++// --- Maximize the result pane (3.23, #21459) ---+//+// A toggle beside the result tabs fills the editor area with the result pane:+// the editor pane and the sidebar collapse in place (Monaco keeps its text),+// Escape restores unless a dialog owns the key, the state is momentary (a tab+// switch hands the editor back), and only a dragged height is remembered.++const RESULT_PANEL_SIZE_KEY = "bb.sql-editor.result-panel-size";++// Monaco sizes its node in pixels and re-lays out on a later frame after its+// container changes, so callers poll this rather than read it once.+async function editorHeight(): Promise<number> {+ const box = await sqlEditor.codeEditor.first().boundingBox();+ return box?.height ?? 0;+}++// The sidebar tree keeps its element while collapsed; its width tells the state.+async function sidebarWidth(): Promise<number> {+ return page.getByRole("tree").first().evaluate((tree) => tree.clientWidth);+}++const maximizeToggle = () =>+ page.getByRole("button", { name: enUS.common.maximize, exact: true });+const restoreToggle = () =>+ page.getByRole("button", { name: enUS.common.restore, exact: true });++test.describe("Maximize fills the editor area with the result pane (M1)", () => {+ test.describe.configure({ mode: "serial" });+ let dockedEditorHeight = 0;+ let dockedSidebarWidth = 0;++ test.beforeAll(async () => {+ await openFreshConnectedTab();+ await sqlEditor.runPreparedQuery("SELECT 1");+ await expect(maximizeToggle()).toBeVisible();+ dockedEditorHeight = await editorHeight();+ dockedSidebarWidth = await sidebarWidth();+ expect(dockedEditorHeight).toBeGreaterThan(100);+ expect(dockedSidebarWidth).toBeGreaterThan(100);+ });++ test("the toggle collapses the editor and sidebar in place; Escape restores the geometry and the statement", async () => {+ await maximizeToggle().click();+ await expect(restoreToggle()).toHaveAttribute("aria-pressed", "true");+ await expect.poll(editorHeight).toBeLessThan(dockedEditorHeight / 4);+ await expect.poll(sidebarWidth).toBe(0);++ await page.keyboard.press("Escape");+ await expect(maximizeToggle()).toHaveAttribute("aria-pressed", "false");+ await expect+ .poll(async () => Math.abs((await editorHeight()) - dockedEditorHeight))+ .toBeLessThanOrEqual(2);+ await expect.poll(sidebarWidth).toBe(dockedSidebarWidth);+ expect(await sqlEditor.readEditorContent()).toBe("SELECT 1");+ });++ test("Escape while a dialog is open closes the dialog only; the next Escape restores", async () => {+ await maximizeToggle().click();+ await expect(restoreToggle()).toHaveAttribute("aria-pressed", "true");+ await page.getByRole("button", { name: enUS.common.export, exact: true }).click();+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();++ await page.keyboard.press("Escape");+ await expect(dialog).toBeHidden();+ await expect(restoreToggle()).toHaveAttribute("aria-pressed", "true");++ await page.keyboard.press("Escape");+ await expect(maximizeToggle()).toHaveAttribute("aria-pressed", "false");+ });+});++test.describe("Maximize is momentary: a tab switch hands the editor back (M2)", () => {+ test("a new query tab opens docked and the maximized tab is docked again on return", async () => {+ await openFreshConnectedTab();+ await sqlEditor.runPreparedQuery("SELECT 1");+ const docked = await editorHeight();+ await maximizeToggle().click();+ await expect(restoreToggle()).toHaveAttribute("aria-pressed", "true");++ await page.getByRole("button", { name: enUS.common.add, exact: true }).click();+ // The new tab has no result pane, hence no toggle, and a full-height editor.+ await expect(restoreToggle()).toHaveCount(0);+ await expect(maximizeToggle()).toHaveCount(0);+ await expect.poll(editorHeight).toBeGreaterThan(docked);++ // Back on the tab that was maximized (the one before the tab just added).+ await page.locator("[data-tab-id]").nth(-2).click();+ await expect(maximizeToggle()).toHaveAttribute("aria-pressed", "false");+ await expect+ .poll(async () => Math.abs((await editorHeight()) - docked))+ .toBeLessThanOrEqual(2);+ });+});++test.describe("A dragged result-pane height is remembered; maximizing is not (M3)", () => {+ test.afterAll(async () => {+ // Leave later specs the default split.+ await page.evaluate((key) => localStorage.removeItem(key), RESULT_PANEL_SIZE_KEY);+ });++ test("dragging the separator persists the height across a reload", async () => {+ await openFreshConnectedTab();+ await sqlEditor.runPreparedQuery("SELECT 1");+ const docked = await editorHeight();+ await page.evaluate((key) => localStorage.removeItem(key), RESULT_PANEL_SIZE_KEY);++ // Drag the editor/result separator up to the middle of the editor.+ const separator = page.locator('[role="separator"][aria-orientation="horizontal"]').first();+ const from = await separator.boundingBox();+ const editor = await sqlEditor.codeEditor.first().boundingBox();+ if (!from || !editor) throw new Error("the separator or the editor has no bounding box");+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);+ await page.mouse.down();+ await page.mouse.move(from.x + from.width / 2, editor.y + editor.height / 2, { steps: 8 });+ await page.mouse.up();++ await expect.poll(editorHeight).toBeLessThan(docked * 0.7);+ await expect+ .poll(() => page.evaluate((key) => Number(localStorage.getItem(key)), RESULT_PANEL_SIZE_KEY))+ .toBeGreaterThan(0.5);++ // Maximizing must not overwrite the remembered height.+ const remembered = await page.evaluate((key) => localStorage.getItem(key), RESULT_PANEL_SIZE_KEY);+ await maximizeToggle().click();+ await page.keyboard.press("Escape");+ await expect(maximizeToggle()).toHaveAttribute("aria-pressed", "false");+ expect(await page.evaluate((key) => localStorage.getItem(key), RESULT_PANEL_SIZE_KEY)).toBe(remembered);++ await page.reload();+ await expect(sqlEditor.codeEditor.first()).toBeVisible({ timeout: 15_000 });+ await sqlEditor.runPreparedQuery("SELECT 1");+ await expect.poll(editorHeight).toBeLessThan(docked * 0.7);+ });+});diff --git a/frontend/tests/e2e/workspace/workspace-audit-log.spec.ts b/frontend/tests/e2e/workspace/workspace-audit-log.spec.tsnew file mode 100644index 0000000000..b5b6ca5844--- /dev/null+++ b/frontend/tests/e2e/workspace/workspace-audit-log.spec.ts@@ -0,0 +1,174 @@+// Audit logs → the Actor filter (3.24: #21541, BYT-10291).+//+// The filter searches users, service accounts and workload identities on one+// keyword, whatever its case, and reads a typed resource name with any casing+// of its prefix. The lists a page can call reach only its own parents, so a+// project-owned service account is found by name from its project's audit log+// and, from the workspace audit log, only when its full email is typed.+//+// The actors are created per run; a service account makes one audited write+// (CreateSheet) so the filter has rows to narrow.++import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";+import { BytebaseApiClient } from "../framework/api-client";+import { loadTestEnv, type TestEnv } from "../framework/env";++const ACTOR_SCOPE = enUS["audit-log"]["advanced-search"].scope.actor;+const ACTOR_COLUMN = enUS["audit-log"].table.actor;++test.setTimeout(120_000);++let env: TestEnv & { api: BytebaseApiClient };+let sharedContext: BrowserContext;+let page: Page;++const suffix = Date.now();+const OWN_ACCOUNT = /^serviceAccount:e2e-(auditor|proj-bot)-\d+@/;+let workspaceAccount: { name: string; email: string };+let projectAccount: { name: string; email: string };+let workloadIdentity: { name: string; email: string };++// Signs in as a service account and makes one audited write in the project.+async function auditedWriteAs(account: { email: string; serviceKey: string }): Promise<void> {+ const client = new BytebaseApiClient({ baseURL: env.baseURL });+ await client.login(account.email, account.serviceKey);+ await client.createSheet(env.project, `SELECT ${suffix};`);+}++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ const { workspace } = await env.api.getActuatorInfo();++ const workspaceSA = await env.api.createServiceAccount(workspace, `e2e-auditor-${suffix}`, "E2E Auditor");+ const projectSA = await env.api.createServiceAccount(env.project, `e2e-proj-bot-${suffix}`, "E2E Project Bot");+ workloadIdentity = await env.api.createWorkloadIdentity(workspace, `e2e-ci-${suffix}`, "E2E CI", {+ providerType: "GITHUB",+ issuerUrl: "https://token.actions.githubusercontent.com",+ allowedAudiences: ["bytebase"],+ subjectPattern: "repo:example/app:ref:refs/heads/main",+ });+ workspaceAccount = workspaceSA;+ projectAccount = projectSA;++ await env.api.appendProjectBinding(env.project, "roles/projectDeveloper", [+ `serviceAccount:${workspaceSA.email}`,+ `serviceAccount:${projectSA.email}`,+ ]);+ await auditedWriteAs(workspaceSA);+ await auditedWriteAs(projectSA);++ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ await sharedContext?.close();+ // Drop this spec's bindings by name rather than restore a snapshot, so a+ // retry also clears what a crashed attempt bound.+ const policy = await env.api.getProjectIamPolicy(env.project);+ policy.bindings = policy.bindings+ .map((binding) => ({+ ...binding,+ members: binding.members.filter((member) => !OWN_ACCOUNT.test(member)),+ }))+ .filter((binding) => binding.members.length > 0);+ await env.api+ .setProjectIamPolicy(env.project, policy)+ .catch((e) => console.warn("cleanup failed: project bindings", e));+ if (workspaceAccount) await env.api.deleteServiceAccount(workspaceAccount.email);+ if (projectAccount) await env.api.deleteServiceAccount(projectAccount.email);+ if (workloadIdentity) await env.api.deleteWorkloadIdentity(workloadIdentity.email);+});++const workspaceAuditLog = () => `${env.baseURL}/audit-log`;+const projectAuditLog = () => `${env.baseURL}/projects/${env.project.split("/").pop()}/audit-logs`;++function menuOption(text: string) {+ return page.locator("[data-search-menu-option-index]").filter({ hasText: text });+}++// Opens the page, picks the Actor scope and types the keyword at a typing pace.+async function searchActor(url: string, keyword: string): Promise<void> {+ await page.goto(url);+ await page.getByPlaceholder(enUS.common.filter).click();+ await menuOption(ACTOR_SCOPE.description).click();+ await page.keyboard.type(keyword, { delay: 30 });+}++// Every Actor cell in the table, once the filtered search has settled.+async function actorCells(): Promise<string[]> {+ const headers = await page.getByRole("columnheader").allInnerTexts();+ const column = headers.findIndex((header) => header.trim() === ACTOR_COLUMN);+ expect(column).toBeGreaterThanOrEqual(0);+ return page+ .locator("tbody tr")+ .evaluateAll(+ (rows, index) => rows.map((row) => row.querySelectorAll("td")[index]?.textContent?.trim() ?? ""),+ column,+ );+}++function expectFilteredTo(actor: string) {+ return expect(page.locator('[data-search-scope-id="actor"]')).toContainText(actor);+}++test.describe("A service account is found by any casing of its name and narrows the log (A1)", () => {+ test("a mixed-case fragment offers the account; choosing it leaves only its rows", async () => {+ await searchActor(workspaceAuditLog(), `E2E-AUDITOR-${suffix}`);+ await menuOption(workspaceAccount.email).click();+ await expectFilteredTo(workspaceAccount.name);+ await expect.poll(async () => new Set(await actorCells()), { timeout: 15_000 }).toEqual(+ new Set([workspaceAccount.name]),+ );+ });+});++test.describe("A workload identity is found the same way (A2)", () => {+ test("a mixed-case fragment offers the identity; choosing it filters on its name", async () => {+ await searchActor(workspaceAuditLog(), `E2E-Ci-${suffix}`);+ await menuOption(workloadIdentity.email).click();+ await expectFilteredTo(workloadIdentity.name);+ // The identity never acted, so nothing is left.+ await expect(page.getByText(enUS.common["no-data"], { exact: true })).toBeVisible({ timeout: 15_000 });+ });+});++test.describe("A typed resource name filters whatever the casing of its prefix (A3)", () => {+ test("ServiceAccounts/<Email> committed with Enter filters on the canonical name", async () => {+ const [local, domain] = workspaceAccount.email.split("@");+ await searchActor(workspaceAuditLog(), `ServiceAccounts/${local.toUpperCase()}@${domain}`);+ await expect(menuOption(workspaceAccount.email)).toBeVisible();+ await page.keyboard.press("Enter");+ await expectFilteredTo(workspaceAccount.name);+ await expect.poll(async () => new Set(await actorCells()), { timeout: 15_000 }).toEqual(+ new Set([workspaceAccount.name]),+ );+ });+});++test.describe("A project-owned service account (A4)", () => {+ test("the workspace log cannot list it, but its full email is offered as typed and filters", async () => {+ await searchActor(workspaceAuditLog(), `E2E-PROJ-BOT-${suffix}`);+ // The account lists reach the workspace only; the search settles empty.+ await expect(page.getByText(enUS.common["search-no-result"], { exact: true })).toBeVisible({ timeout: 15_000 });+ await expect(menuOption(projectAccount.email)).toHaveCount(0);++ await searchActor(workspaceAuditLog(), projectAccount.email.toUpperCase());+ await menuOption(projectAccount.email).click();+ await expectFilteredTo(projectAccount.name);+ await expect.poll(async () => new Set(await actorCells()), { timeout: 15_000 }).toEqual(+ new Set([projectAccount.name]),+ );+ });++ test("the project's own audit log finds it by a fragment", async () => {+ await searchActor(projectAuditLog(), `E2E-PROJ-BOT-${suffix}`);+ await menuOption(projectAccount.email).click();+ await expectFilteredTo(projectAccount.name);+ await expect.poll(async () => new Set(await actorCells()), { timeout: 15_000 }).toEqual(+ new Set([projectAccount.name]),+ );+ });+});diff --git a/frontend/tests/e2e/workspace/workspace-instance-form.spec.ts b/frontend/tests/e2e/workspace/workspace-instance-form.spec.tsnew file mode 100644index 0000000000..21c5739029--- /dev/null+++ b/frontend/tests/e2e/workspace/workspace-instance-form.spec.ts@@ -0,0 +1,204 @@+// Workspace → Instances → Add instance: the connection form (3.23: #21396,+// #21419, #21449, #21454).+//+// The form validates before it submits (the hostname starts empty and is+// required; Test Connection and Create stay disabled until the form is valid),+// offers an explicit Test Connection with inline recovery guidance on failure,+// asks before creating an instance whose connection failed, and edits secrets+// through SecretInput: "Unchanged" until touched, an explicit clear, and the+// form's Cancel to discard.+//+// The connection target is the suite's own sample Postgres, reached over its+// Unix socket directory (the sample instance registers `/tmp` as its host), so+// the success path needs no network and no extra database.++import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient } from "../framework/api-client";++const INSTANCE = enUS.instance;+const RECOVERY = enUS.instance["connection-recovery"];+const COMMON = enUS.common;++test.setTimeout(120_000);++let env: TestEnv & { api: BytebaseApiClient };+let sharedContext: BrowserContext;+let page: Page;+// The sample Postgres' admin data source: host (socket dir), port, user.+let sample: { host: string; port: string; username: string };+const createdInstances: string[] = [];++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ const instance = await env.api.getInstance(env.instance);+ const admin = instance.dataSources.find((ds) => ds.type === "ADMIN") ?? instance.dataSources[0];+ if (!admin?.host || !admin.port || !admin.username) {+ throw new Error(+ `sample instance ${env.instance} has no usable admin data source: ${JSON.stringify(instance.dataSources)}`,+ );+ }+ sample = { host: admin.host, port: admin.port, username: admin.username };+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ for (const name of createdInstances) {+ await env.api.deleteInstance(name).catch((e) => console.warn("cleanup failed:", name, e));+ }+ await sharedContext?.close();+});++const hostname = () => page.getByRole("textbox", { name: "Hostname *" });+const port = () => page.getByRole("textbox", { name: "Port", exact: true });+const username = () => page.getByRole("textbox", { name: "Username", exact: true });+const testConnection = () => page.getByRole("button", { name: INSTANCE["test-connection"], exact: true });+const create = () => page.getByRole("button", { name: "Create", exact: true });++async function gotoNewPostgresInstance(): Promise<void> {+ await page.goto(`${env.baseURL}/instances/new`);+ await page.getByRole("button", { name: "PostgreSQL", exact: true }).click();+ await expect(hostname()).toBeVisible();+ await expect(hostname()).toHaveValue("");+}++// The connection-test result arrives as a toast that stays until dismissed and+// sits over the footer's actions; the user closes it before the next click, so+// the journeys do too. Every toast's × is labelled "Close"+// (components/ui/toast.tsx); the visible card is aria-hidden behind its live+// region, hence includeHidden.+async function closeToasts(): Promise<void> {+ const closes = page.getByRole("button", { name: "Close", exact: true, includeHidden: true });+ for (let attempt = 0; attempt < 5 && (await closes.count()) > 0; attempt++) {+ await closes.first().click({ timeout: 2_000 }).catch(() => {});+ await expect(closes).toHaveCount(0, { timeout: 2_000 }).catch(() => {});+ }+}++test.describe("An empty hostname is refused before anything is sent (I1)", () => {+ test("the required error shows on blur and both actions stay disabled", async () => {+ await gotoNewPostgresInstance();+ await expect(testConnection()).toBeDisabled();+ await expect(create()).toBeDisabled();++ await hostname().click();+ await page.keyboard.press("Tab");+ await expect(hostname()).toHaveAttribute("aria-invalid", "true");+ await expect(page.getByRole("alert").filter({ hasText: INSTANCE.validation.required })).toBeVisible();+ await expect(testConnection()).toBeDisabled();+ await expect(create()).toBeDisabled();+ });+});++test.describe("Test Connection explains an unreachable host; dismissing the error gives the retry back (I2)", () => {+ test("the network recovery card renders with the engine's error, and the retry works once the error is closed", async () => {+ await gotoNewPostgresInstance();+ await hostname().fill("127.0.0.1");+ await port().fill("1");+ await expect(testConnection()).toBeEnabled();+ await testConnection().click();++ await expect(page.getByRole("heading", { name: RECOVERY.network.title })).toBeVisible({ timeout: 20_000 });+ await expect(page.getByText(/connection refused/).first()).toBeVisible();+ // Still on the form: nothing was created.+ await expect(page).toHaveURL(/\/instances\/new$/);++ // The retry runs a second connection check once the error is closed.+ await closeToasts();+ const retried = page.waitForResponse((response) =>+ response.url().endsWith("/bytebase.v1.InstanceService/CreateInstance"),+ );+ await testConnection().click();+ await retried;+ await expect(page.getByRole("heading", { name: RECOVERY.network.title })).toBeVisible();+ await closeToasts();+ });+});++test.describe("Create asks before saving a connection that failed (I4)", () => {+ test("Cancel keeps the form; nothing is created", async () => {+ await gotoNewPostgresInstance();+ await hostname().fill("127.0.0.1");+ await port().fill("1");+ await create().click();++ const dialog = page.getByRole("alertdialog");+ await expect(dialog.getByRole("heading", { name: INSTANCE["failed-to-connect-instance"] })).toBeVisible({ timeout: 20_000 });+ await expect(dialog.getByRole("heading", { name: RECOVERY.network.title })).toBeVisible();+ await expect(dialog.getByRole("button", { name: COMMON["continue-anyway"] })).toBeVisible();+ await dialog.getByRole("button", { name: COMMON.cancel, exact: true }).click();+ await expect(dialog).toBeHidden();+ await expect(page).toHaveURL(/\/instances\/new$/);+ await expect(hostname()).toHaveValue("127.0.0.1");+ await closeToasts();+ });+});++test.describe("Test, create, then edit the secret (I3)", () => {+ const title = `E2E Instance Form ${Date.now()}`;+ let instanceId = "";++ test("a tested connection creates the instance, whose stored password then edits through SecretInput", async () => {+ test.setTimeout(180_000);+ await test.step("a reachable sample Postgres tests successfully and Create lands on the instance", async () => {+ await gotoNewPostgresInstance();+ await page.getByRole("textbox", { name: "Instance Name *" }).fill(title);+ await hostname().fill(sample.host);+ await port().fill(sample.port);+ await username().fill(sample.username);+ await testConnection().click();+ await expect(page.getByText(INSTANCE["successfully-connected-instance"])).toBeVisible({ timeout: 20_000 });++ await closeToasts();+ await create().click();+ await page.waitForURL(/\/instances\/(?!new$)[^/?#]+/, { timeout: 60_000 });+ instanceId = page.url().match(/\/instances\/([^/?#]+)/)?.[1] ?? "";+ expect(instanceId).not.toBe("");+ createdInstances.push(`instances/${instanceId}`);+ // Exact and level 1: the creation toast's heading also contains the title.+ await expect(page.getByRole("heading", { level: 1, name: title, exact: true })).toBeVisible({+ timeout: 20_000,+ });+ });++ await test.step("the stored password reads Unchanged; typing, clearing and Cancel round-trip", async () => {+ // Re-enter the instance without the post-create ?intro= query: that product+ // intro dims the page once the database list loads and swallows clicks.+ expect(instanceId).not.toBe("");+ await page.goto(`${env.baseURL}/instances/${instanceId}`);+ await page.getByRole("tab", { name: COMMON.overview, exact: true }).click();++ const password = page.getByRole("textbox", { name: "Password", exact: true });+ const clear = page.getByRole("button", { name: COMMON.clear, exact: true });+ const reveal = page.getByRole("button", { name: COMMON["toggle-password-visibility"] });+ const update = page.getByRole("button", { name: COMMON.update, exact: true });++ // Untouched: a placeholder, an explicit clear, no pending change.+ await expect(password).toHaveAttribute("placeholder", COMMON["secret-input"].unchanged);+ await expect(password).toHaveValue("");+ await expect(clear).toBeVisible();+ await expect(reveal).toHaveCount(0);+ await expect(update).toHaveCount(0);++ // Typing replaces: the eye reveals only the new input, the form is dirty.+ await password.fill("e2e-new-secret");+ await expect(password).toHaveValue("e2e-new-secret");+ await expect(reveal).toBeVisible();+ await expect(update).toBeEnabled();++ // × clears explicitly — an empty value, no "Unchanged" placeholder, still dirty.+ await clear.click();+ await expect(password).toHaveValue("");+ await expect(password).not.toHaveAttribute("placeholder", COMMON["secret-input"].unchanged);+ await expect(update).toBeEnabled();++ // The form's Cancel discards: back to Unchanged, nothing pending.+ await page.getByRole("button", { name: COMMON.cancel, exact: true }).click();+ await expect(password).toHaveAttribute("placeholder", COMMON["secret-input"].unchanged);+ await expect(update).toHaveCount(0);+ });+ });+});diff --git a/frontend/tests/e2e/workspace/workspace-mcp-consent.spec.ts b/frontend/tests/e2e/workspace/workspace-mcp-consent.spec.tsnew file mode 100644index 0000000000..bb5020372b--- /dev/null+++ b/frontend/tests/e2e/workspace/workspace-mcp-consent.spec.ts@@ -0,0 +1,152 @@+// Workspace → MCP: the OAuth 2.1 consent loop an MCP client goes through+// (3.23: #21254 withholds Allow unless the page holds a served ceiling; #21517+// unifies the consent page with the MCP policy page; #21527 retires the+// masking-exemptions toggle).+//+// The loop is driven end to end: dynamic client registration through the API,+// the authorize redirect into the browser's consent page, Allow or Deny, the+// redirect back to the client with a code or an error, and — for Allow — the+// PKCE token exchange and one MCP `initialize` with the issued token. The+// consent page must disclose the workspace ceiling the grant is worth, and a+// DISABLED ceiling must withhold Allow entirely.+//+// State safety: afterAll puts the capability back to READ_ONLY, the value every+// workspace starts with (backend/store/workspace.go), since a workspace left+// DISABLED would break every later MCP test.++import { createHash, randomBytes } from "node:crypto";+import { test, expect, type Page } from "@playwright/test";+import enUS from "../../../src/locales/en-US.json";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient } from "../framework/api-client";++const CONSENT = enUS.oauth2.consent;+const MODE = enUS.settings.mcp.policy.mode;+const CLIENT_NAME = "E2E MCP client";++test.setTimeout(120_000);++let env: TestEnv & { api: BytebaseApiClient };+let clientId: string;+let redirectUri: string;++async function readCapability(): Promise<string> {+ const setting = (await env.api.getSetting("MCP")) as {+ value?: { mcp?: { capability?: string } };+ } | null;+ return setting?.value?.mcp?.capability ?? "";+}++async function setCapability(capability: string): Promise<void> {+ await env.api.upsertSetting("MCP", { mcp: { capability } }, "value.mcp.capability");+}++const base64url = (bytes: Buffer) => bytes.toString("base64url");++// A fresh PKCE pair per authorization request.+function pkce(): { verifier: string; challenge: string } {+ const verifier = base64url(randomBytes(32));+ const challenge = base64url(createHash("sha256").update(verifier).digest());+ return { verifier, challenge };+}++function authorizeUrl(state: string, challenge: string): string {+ const query = new URLSearchParams({+ response_type: "code",+ client_id: clientId,+ redirect_uri: redirectUri,+ state,+ code_challenge: challenge,+ code_challenge_method: "S256",+ });+ return `${env.baseURL}/api/oauth2/authorize?${query}`;+}++// The callback lands on a path the SPA does not know, so the app routes on+// to its 404 page; the navigation request itself still carries the code or+// the error the server redirected with, so it is captured at request time.+function waitForCallback(page: Page): Promise<URL> {+ return page+ .waitForRequest((request) => request.url().startsWith(`${redirectUri}?`), { timeout: 20_000 })+ .then((request) => new URL(request.url()));+}++test.beforeAll(async () => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ redirectUri = `${env.baseURL}/oauth-e2e-callback`;+ const client = await env.api.registerOAuth2Client(CLIENT_NAME, [redirectUri], [+ "authorization_code",+ "refresh_token",+ ]);+ clientId = client.client_id;+ expect(clientId).not.toBe("");+});++test.afterAll(async () => {+ await setCapability("READ_ONLY");+ expect(await readCapability()).toBe("READ_ONLY");+});++test.describe("Consent discloses the served ceiling and Allow issues a usable grant (X1)", () => {+ test("Allow access → code → token → MCP initialize", async ({ page }) => {+ await setCapability("READ_ONLY");+ const { verifier, challenge } = pkce();+ const state = `allow-${Date.now()}`;+ await page.goto(authorizeUrl(state, challenge));++ await expect(page).toHaveURL(/\/oauth2\/consent\?/);+ await expect(page.getByRole("heading", { name: CONSENT.title })).toBeVisible({ timeout: 20_000 });+ await expect(page.getByText(CLIENT_NAME).first()).toBeVisible();+ // The disclosure is the consent: the mode the workspace serves is named.+ await expect(page.getByText(MODE["read-only"].title, { exact: true }).first()).toBeVisible();+ await expect(page.getByRole("button", { name: enUS.common.deny, exact: true })).toBeVisible();++ const callback = waitForCallback(page);+ await page.getByRole("button", { name: CONSENT["allow-access"], exact: true }).click();+ const url = await callback;+ const code = url.searchParams.get("code") ?? "";+ expect(code).not.toBe("");+ expect(url.searchParams.get("state")).toBe(state);++ const token = await env.api.exchangeOAuth2Code({ clientId, code, codeVerifier: verifier, redirectUri });+ expect(token.error, token.error_description).toBeUndefined();+ expect(token.access_token).toBeTruthy();+ expect(token.refresh_token).toBeTruthy();++ const init = await env.api.mcpInitialize(token.access_token!);+ expect(init.status).toBe(200);+ expect(init.body).toContain('"protocolVersion"');+ });+});++test.describe("Deny sends the client an access_denied error (X3)", () => {+ test("the callback carries error=access_denied and the state", async ({ page }) => {+ await setCapability("READ_ONLY");+ const { challenge } = pkce();+ const state = `deny-${Date.now()}`;+ await page.goto(authorizeUrl(state, challenge));+ await expect(page.getByRole("heading", { name: CONSENT.title })).toBeVisible({ timeout: 20_000 });++ const callback = waitForCallback(page);+ await page.getByRole("button", { name: enUS.common.deny, exact: true }).click();+ const url = await callback;+ expect(url.searchParams.get("error")).toBe("access_denied");+ expect(url.searchParams.get("state")).toBe(state);+ expect(url.searchParams.get("code")).toBeNull();+ });+});++test.describe("A DISABLED ceiling withholds Allow (X2)", () => {+ test("the page says MCP is turned off and offers only Close", async ({ page }) => {+ await setCapability("DISABLED");+ const { challenge } = pkce();+ await page.goto(authorizeUrl(`disabled-${Date.now()}`, challenge));++ await expect(page.getByRole("heading", { name: CONSENT.mcp.disabled.title })).toBeVisible({ timeout: 20_000 });+ await expect(page.getByRole("button", { name: CONSENT["allow-access"] })).toHaveCount(0);+ await expect(page.getByRole("button", { name: enUS.common.deny })).toHaveCount(0);+ await expect(page.getByRole("button", { name: enUS.common.close, exact: true })).toBeVisible();+ await setCapability("READ_ONLY");+ });+});diff --git a/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.tsindex 4ec87b49c7..32aed849a4 100644--- a/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts+++ b/frontend/tests/e2e/workspace/workspace-mcp-policy.spec.ts@@ -276,3 +276,34 @@ test.describe("MCP access policy capability ladder", () => {}});});++// #21527 retired the "Ignore masking exemptions" toggle from the access policy:+// an MCP session applies the caller's own masking provisioning exactly as the+// console does, so the editor holds nothing but the mode cards.+test.describe("The policy editor holds only the mode cards (X4)", () => {+ test("Edit policy offers the three modes and no masking control", async ({+ page,+ }) => {+ await setCapability("READ_ONLY");+ await gotoMCPPage(page);+ await page.getByRole("button", { name: COPY.policy.edit }).click();++ await expect(+ page.getByRole("radiogroup", { name: "Access policy" })+ ).toBeVisible();+ for (const mode of ["disabled", "read-only", "read-write"] as const) {+ await expect(+ page.getByRole("radio", { name: new RegExp(`^${COPY.policy.mode[mode].title}`) })+ ).toBeVisible();+ }+ await expect(page.getByRole("switch")).toHaveCount(0);+ await expect(page.getByRole("checkbox")).toHaveCount(0);+ await expect(page.getByText(/masking exemption/i)).toHaveCount(0);+ // Nothing to save until a different mode is picked.+ await expect(+ page.getByRole("button", { name: COPY.policy.save })+ ).toBeDisabled();+ await page.getByRole("button", { name: "Cancel", exact: true }).click();+ await expect(chip(page, "Read-only")).toBeVisible();+ });+});