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): add regression locks for 15 fixed issues; fix 2 stale tests (#20603)
zchpetercd672015a084
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.tsindex c77f95b18b..dcccfc279e 100644--- a/frontend/tests/e2e/framework/api-client.ts+++ b/frontend/tests/e2e/framework/api-client.ts@@ -163,9 +163,19 @@ export class BytebaseApiClient {await this.request<unknown>("PATCH", "/v1/subscription/license", { license });}- // Returns server info — notably the current workspace resource name.- async getActuatorInfo(): Promise<{ workspace: string }> {- return this.request<{ workspace: string }>("GET", "/v1/actuator/info");+ // Returns server info — notably the current workspace resource name and the+ // count of distinct users occupying a seat in workspace IAM (seat-limit spec).+ async getActuatorInfo(): Promise<{ workspace: string; userCountInIam?: number }> {+ return this.request<{ workspace: string; userCountInIam?: number }>(+ "GET",+ "/v1/actuator/info",+ );+ }++ // Current subscription plan (e.g. "FREE", "ENTERPRISE"). Used by the seat-limit+ // spec (BYT-9633) to confirm the license drop took effect and was restored.+ async getSubscription(): Promise<{ plan?: string }> {+ return this.request<{ plan?: string }>("GET", "/v1/subscription");}// Creates an end-user with the given email/password/title in the caller's@@ -174,6 +184,24 @@ export class BytebaseApiClient {await this.request<unknown>("POST", "/v1/users", { email, password, title });}+ // Soft-delete (deactivate) a user. The principal is marked deleted but its IAM+ // bindings remain — a deactivated user no longer occupies a seat. Best-effort+ // so teardown of seat-limit fixtures can't fail the suite (BYT-9633).+ async deleteUser(email: string): Promise<void> {+ try { await this.request<unknown>("DELETE", `/v1/users/${email}`); } catch { /* ignore */ }+ }++ // Reactivate a soft-deleted user. NOT best-effort: the seat-limit spec asserts+ // this REJECTS (ResourceExhausted) when reactivating would exceed the limit, so+ // the error must propagate (BYT-9633 / #20497 preUndeleteUserGuard).+ async undeleteUser(email: string): Promise<{ name: string }> {+ return this.request<{ name: string }>(+ "POST",+ `/v1/users/${email}:undelete`,+ { name: `users/${email}` },+ );+ }+// Grants `email` the given role at the workspace level by merging a new// binding into the existing IAM policy. Idempotent: if the binding already// includes the member, returns without re-issuing setIamPolicy.@@ -199,6 +227,21 @@ export class BytebaseApiClient {});}+ // Read/write the full workspace IAM policy. The seat-limit spec (BYT-9633)+ // snapshots the policy, appends many user: members in one write to push the+ // workspace over the FREE-plan seat limit, then restores the snapshot.+ async getWorkspaceIamPolicy(workspace: string): Promise<IamPolicy> {+ return this.request<IamPolicy>("GET", `/v1/${workspace}:getIamPolicy`);+ }++ async setWorkspaceIamPolicy(workspace: string, policy: IamPolicy): Promise<IamPolicy> {+ return this.request<IamPolicy>("POST", `/v1/${workspace}:setIamPolicy`, {+ resource: workspace,+ policy,+ etag: policy.etag ?? "",+ });+ }+// Discoveryasync listInstances() {return this.request<{ instances: { name: string; engine: string; title: string }[] }>("GET", "/v1/instances?pageSize=100&showDeleted=false");@@ -212,6 +255,27 @@ export class BytebaseApiClient {return this.request<unknown>("POST", `/v1/${databaseFullName}:sync`, {});}+ // Sync an instance so Bytebase discovers databases created out-of-band+ // (e.g. via psql CREATE DATABASE). Used by the targets "View all" spec+ // (BYT-9558) which needs >20 target databases on the sample instance.+ async syncInstance(instanceName: string) {+ return this.request<unknown>("POST", `/v1/${instanceName}:sync`, {+ name: instanceName,+ });+ }++ // Move a database into a project (UpdateDatabase, update_mask=project). The+ // backend's validateSpecs rejects plan/issue targets that don't belong to the+ // plan's project, so a database created via psql must be transferred before it+ // can be used as a change target (BYT-9558).+ async transferDatabaseToProject(databaseFullName: string, project: string) {+ return this.request<unknown>(+ "PATCH",+ `/v1/${databaseFullName}?updateMask=project`,+ { name: databaseFullName, project },+ );+ }+// Policiesasync getPolicy(policyName: string) {try {@@ -268,6 +332,41 @@ export class BytebaseApiClient {{ id: dataSourceId, port });}+ // Add a data source (typically READ_ONLY) to an instance. AddDataSource binds+ // `body: "*"`, so the HTTP body carries both the instance `name` and the+ // `dataSource`. Used by the automatic-routing spec (BYT-9557) to give an+ // instance both an admin and a read-only data source.+ async addDataSource(+ instanceName: string,+ dataSource: {+ id: string;+ type: "READ_ONLY" | "ADMIN";+ username: string;+ password?: string;+ host: string;+ port: string;+ },+ ) {+ return this.request<unknown>("POST", `/v1/${instanceName}:addDataSource`, {+ name: instanceName,+ dataSource,+ });+ }++ // Remove a data source by id. Best-effort (teardown): the admin data source+ // stays at index 0, so a failed read-only removal can't corrupt+ // getInstancePgPort (which reads dataSources[0]).+ async removeDataSource(instanceName: string, dataSourceId: string) {+ try {+ await this.request<unknown>("POST", `/v1/${instanceName}:removeDataSource`, {+ name: instanceName,+ dataSource: { id: dataSourceId },+ });+ } catch {+ /* best-effort teardown */+ }+ }+// Query — endpoint is /v1/instances/{instance}/databases/{database}:queryasync query(databaseFullName: string, statement: string) {return this.request<{ results: unknown[] }>("POST", `/v1/${databaseFullName}:query`, {@@ -435,9 +534,27 @@ export class BytebaseApiClient {}// Issues- async createIssue(project: string, title: string, plan: string): Promise<{ name: string; status: string; approvalStatus: string }> {+ async createIssue(+ project: string,+ title: string,+ plan: string,+ description?: string,+ ): Promise<{ name: string; status: string; approvalStatus: string }> {return this.request("POST", `/v1/${project}/issues`, {- title, type: "DATABASE_CHANGE", plan,+ title,+ type: "DATABASE_CHANGE",+ plan,+ ...(description !== undefined && { description }),+ });+ }++ // Post a comment to an issue. CreateIssueComment binds `body: "issue_comment"`,+ // so the HTTP body is the IssueComment payload directly. Used by the+ // markdown-link spec (BYT-9664) to seed a comment with links via the API+ // rather than driving the review popover.+ async createIssueComment(issueName: string, comment: string): Promise<{ name: string }> {+ return this.request<{ name: string }>("POST", `/v1/${issueName}:comment`, {+ comment,});}diff --git a/frontend/tests/e2e/framework/psql.ts b/frontend/tests/e2e/framework/psql.tsindex fa8e160429..3d31b8bd72 100644--- a/frontend/tests/e2e/framework/psql.ts+++ b/frontend/tests/e2e/framework/psql.ts@@ -34,3 +34,23 @@ export function execSql(dbName: string, port: string, sql: string): void {{ stdio: "pipe" },);}++// Run a read query and return the raw scalar/tuple output (tuples-only,+// unaligned). Reads as the owner (bbsample), so it reflects the committed+// table state — use it as a positive oracle that a write actually landed,+// instead of inferring success from the absence of a UI error. Same+// interpolation-safety contract as execSql.+export function querySql(dbName: string, port: string, sql: string): string {+ return execFileSync(+ "psql",+ [+ "-h", "/tmp",+ "-p", port,+ "-U", "bbsample",+ "-d", dbName,+ "-v", "ON_ERROR_STOP=1",+ "-tAc", sql,+ ],+ { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] },+ ).trim();+}diff --git a/frontend/tests/e2e/issue-detail/issue-detail-comments.spec.ts b/frontend/tests/e2e/issue-detail/issue-detail-comments.spec.tsnew file mode 100644index 0000000000..1aee0cb5a2--- /dev/null+++ b/frontend/tests/e2e/issue-detail/issue-detail-comments.spec.ts@@ -0,0 +1,149 @@+// Issue detail — markdown comments & description (link rendering).+//+// BYT-9664 (FIXED, #20537): since 3.17.1, links rendered in issue comments (and+// the issue description) navigated the CURRENT tab — a full-page redirect away+// from the issue detail page — instead of opening in a new tab as they did+// through 3.17.0. Root cause: the Vue→React migration replaced the old Vue+// markdown preview (a DOMPurify hook forced target="_blank" + a sandboxed+// iframe) with a React MarkdownEditor that emitted plain <a href> via+// dangerouslySetInnerHTML, so links defaulted to same-tab navigation. The old+// code also never set `rel`, leaving a reverse-tabnabbing gap.+//+// The fix's sanitizePreviewHtml (MarkdownEditor.tsx) sets target="_blank" AND+// rel="noopener noreferrer" on every rendered <a>. The same component renders+// BOTH comments and the issue description, so this file locks both surfaces+// (comment = the reported surface; description = the sibling site from the+// CUJ analysis).+//+// Seeds the comment + description via the API (CreateIssueComment / issue+// description) rather than driving the review popover — the bug lives in the+// read-only render path, which both surfaces share.++import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient } from "../framework/api-client";++test.describe.configure({ mode: "serial" });++let env: TestEnv & { api: BytebaseApiClient };+let sharedContext: BrowserContext;+let page: Page;++const STAMP = Date.now();+// Distinct external URLs so the rendered <a> elements are unambiguous to locate.+const MD_LINK_URL = `https://example.com/byt9664-comment-${STAMP}`;+const BARE_URL = `https://example.com/byt9664-bare-${STAMP}`;+const DESC_LINK_URL = `https://example.com/byt9664-desc-${STAMP}`;++let issueName = "";+let issueUrl = "";++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);++ // Create a real plan + issue. The description carries a markdown link (sibling+ // surface); the comment is posted right after (the reported surface).+ const sheet = await env.api.createSheet(+ env.project,+ "SELECT 1; -- byt9664",+ );+ const plan = await env.api.createPlan(env.project, `BYT-9664 ${STAMP}`, [+ { id: `spec-${STAMP}`, targets: [env.database], sheet },+ ]);+ const issue = await env.api.createIssue(+ env.project,+ `BYT-9664 ${STAMP}`,+ plan.name,+ `Reference: [design doc](${DESC_LINK_URL})`,+ );+ issueName = issue.name;+ await env.api.createIssueComment(+ issueName,+ `[docs](${MD_LINK_URL}) and a bare link ${BARE_URL}`,+ );++ const projectId = env.project.split("/").pop()!;+ const issueId = issueName.split("/").pop()!;+ issueUrl = `${env.baseURL}/projects/${projectId}/issues/${issueId}`;++ sharedContext = await browser.newContext({+ storageState: ".auth/state.json",+ });+ // Keep the run hermetic: never actually load the external sites. The popup /+ // navigation still fires (which is what we assert) — the request just aborts.+ await sharedContext.route(/example\.com/, (route) => route.abort());+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ await sharedContext?.close();+});++test.describe("Issue comment links open in a new tab with rel=noopener noreferrer (BYT-9664)", () => {+ test("rendered comment links carry target=_blank + rel, and clicking does not redirect the issue page", async () => {+ test.setTimeout(120_000);++ await page.goto(issueUrl);+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForLoadState("networkidle").catch(() => {});++ // The markdown link and the linkified bare URL both render as <a> in the+ // comment body. Locate by href (unique per run).+ const mdLink = page.locator(`a[href="${MD_LINK_URL}"]`).first();+ const bareLink = page.locator(`a[href="${BARE_URL}"]`).first();+ await expect(mdLink).toBeVisible({ timeout: 15_000 });+ await expect(bareLink).toBeVisible({ timeout: 10_000 });++ // Attribute oracle — exactly what the fix restored (and the unit test in+ // MarkdownEditor.test.tsx asserts). Pre-fix: no target, no rel.+ for (const link of [mdLink, bareLink]) {+ await expect(link).toHaveAttribute("target", "_blank");+ await expect(link).toHaveAttribute(+ "rel",+ /(?=.*noopener)(?=.*noreferrer)/,+ );+ }++ // Behavioral oracle — clicking opens a NEW tab while the issue page stays+ // put (the user-visible symptom was a full-page redirect away from the+ // issue). The external request is aborted by the context route, so the+ // popup opens but loads nothing — the page event is all we need.+ const issuePath = new URL(issueUrl).pathname;+ const [popup] = await Promise.all([+ sharedContext.waitForEvent("page"),+ mdLink.click(),+ ]);+ // The issue page stays put. (The app legitimately appends its own `?spec=`+ // query param on load, so compare the PATHNAME — a same-tab redirect to the+ // external link would change the pathname/host entirely.)+ expect(+ new URL(page.url()).pathname,+ "clicking a comment link must NOT redirect the issue page",+ ).toBe(issuePath);+ expect(page.url(), "the issue page must not navigate to the link target").not.toContain(+ "example.com",+ );+ await popup.close();+ });+});++test.describe("Issue description links open in a new tab (BYT-9664 sibling surface)", () => {+ test("the rendered description link carries target=_blank + rel", async () => {+ test.setTimeout(120_000);++ await page.goto(issueUrl);+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForLoadState("networkidle").catch(() => {});++ // The issue description renders through the same MarkdownEditor read-only+ // path as comments — so the same sanitize contract must apply.+ const descLink = page.locator(`a[href="${DESC_LINK_URL}"]`).first();+ await expect(descLink).toBeVisible({ timeout: 15_000 });+ await expect(descLink).toHaveAttribute("target", "_blank");+ await expect(descLink).toHaveAttribute(+ "rel",+ /(?=.*noopener)(?=.*noreferrer)/,+ );+ });+});diff --git a/frontend/tests/e2e/issue-detail/issue-detail-targets.spec.ts b/frontend/tests/e2e/issue-detail/issue-detail-targets.spec.tsnew file mode 100644index 0000000000..adcbed6800--- /dev/null+++ b/frontend/tests/e2e/issue-detail/issue-detail-targets.spec.ts@@ -0,0 +1,177 @@+// Issue detail — Targets "View all" sheet (scrollability).+//+// BYT-9558 (FIXED, #20427): on a Data Change Issue with many targets, clicking+// "View all (N)" opened a popup that was frozen — the user could not scroll down+// to see all the targets. Root cause: the targets list rendered in a Dialog whose+// nested flex/overflow chain never produced a scrollable container, so content+// below the fold was unreachable. The fix replaced the Dialog with a Sheet whose+// SheetBody is `overflow-hidden` and whose inner list is+// `min-h-0 flex-1 overflow-y-auto` (IssueDetailDatabaseChangeView.tsx) — a real+// scroll container.+//+// The same broken pattern + fix also lived on the Plan detail Changes/Targets+// sheet (PlanDetailChangesBranch.tsx); that sibling surface is a candidate for a+// follow-up lock (CUJ analysis) but is not covered here.+//+// Owns its fixtures: creates >20 databases via psql, syncs + transfers them into+// the project, targets them in a single-spec plan/issue, and drops them in+// afterAll.++import { test, expect, type BrowserContext, type Page } from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient } from "../framework/api-client";+import { execSql, getInstancePgPort } from "../framework/psql";++test.describe.configure({ mode: "serial" });++// 21 > DEFAULT_VISIBLE_TARGETS (20), so the "View all (21)" button renders.+const TARGET_COUNT = 21;+const STAMP = Date.now();+// Unique per run so a CI retry against the same disposable server doesn't collide.+const DB_PREFIX = `e2e_tgt_${STAMP}_`;+const dbShortNames = Array.from(+ { length: TARGET_COUNT },+ (_, i) => `${DB_PREFIX}${String(i + 1).padStart(2, "0")}`,+);+// The last target — must require scrolling to reach inside the sheet.+const LAST_DB = dbShortNames[dbShortNames.length - 1];++let env: TestEnv & { api: BytebaseApiClient };+let pgPort = "";+let sharedContext: BrowserContext;+let page: Page;+let issueUrl = "";++test.beforeAll(async ({ browser }) => {+ test.setTimeout(240_000);+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ pgPort = await getInstancePgPort(env);++ // 1. Create the databases via psql (CREATE DATABASE can't run in the same db+ // being changed, but a single psql -c against the env database is fine).+ for (const name of dbShortNames) {+ execSql(env.databaseId, pgPort, `CREATE DATABASE ${name}`);+ }++ // 2. Sync the instance so Bytebase discovers them, then poll until present.+ await env.api.syncInstance(env.instance);+ await expect+ .poll(+ async () => {+ const { databases } = await env.api.listDatabases(env.instance);+ const names = new Set((databases ?? []).map((d) => d.name));+ return dbShortNames.every((short) =>+ names.has(`${env.instance}/databases/${short}`),+ );+ },+ { timeout: 60_000, message: "synced databases should appear" },+ )+ .toBe(true);++ // 3. Transfer each into the project (backend validateSpecs rejects targets not+ // in the plan's project).+ const targetFullNames: string[] = [];+ for (const short of dbShortNames) {+ const full = `${env.instance}/databases/${short}`;+ await env.api.transferDatabaseToProject(full, env.project);+ targetFullNames.push(full);+ }++ // 4. One spec targeting all 21 new databases → "View all (21)".+ const sheet = await env.api.createSheet(env.project, "SELECT 1; -- byt9558");+ const plan = await env.api.createPlan(env.project, `BYT-9558 ${STAMP}`, [+ { id: `spec-${STAMP}`, targets: targetFullNames, sheet },+ ]);+ const issue = await env.api.createIssue(env.project, `BYT-9558 ${STAMP}`, plan.name);++ const projectId = env.project.split("/").pop()!;+ const issueId = issue.name.split("/").pop()!;+ issueUrl = `${env.baseURL}/projects/${projectId}/issues/${issueId}`;++ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });+ page = await sharedContext.newPage();+});++test.afterAll(async () => {+ await sharedContext?.close();+ // Best-effort: drop the databases and re-sync so Bytebase forgets them.+ for (const name of dbShortNames) {+ try {+ execSql(env.databaseId, pgPort, `DROP DATABASE IF EXISTS ${name}`);+ } catch {+ /* best-effort — a lingering connection can block DROP on a disposable server */+ }+ }+ await env.api.syncInstance(env.instance).catch(() => {});+});++test.describe("Targets 'View all' sheet scrolls to the last target (BYT-9558)", () => {+ test("the all-targets sheet is scrollable — the last target can be brought into view", async () => {+ test.setTimeout(120_000);++ await page.goto(issueUrl);+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForLoadState("networkidle").catch(() => {});++ // The Targets section shows "View all (21)".+ const viewAll = page.getByRole("button", {+ name: `View all (${TARGET_COUNT})`,+ });+ await expect(viewAll).toBeVisible({ timeout: 15_000 });+ await viewAll.click();++ // The Sheet opens with title "Targets (21)".+ const sheet = page+ .getByRole("dialog")+ .filter({ hasText: `Targets (${TARGET_COUNT})` });+ await expect(sheet).toBeVisible({ timeout: 5000 });++ // The scroll container (min-h-0 flex-1 overflow-y-auto) must actually+ // overflow — sanity that we have enough rows to exercise the bug.+ const scrollRegion = sheet.locator("div.overflow-y-auto").first();+ await expect(scrollRegion).toBeVisible({ timeout: 5000 });+ const overflow = await scrollRegion.evaluate(+ (el) => el.scrollHeight - el.clientHeight,+ );+ expect(+ overflow,+ "the targets list must overflow its container (otherwise scroll can't be tested)",+ ).toBeGreaterThan(10);++ // THE REGRESSION ORACLE: the last target row can be scrolled into the+ // viewport. Pre-fix the Dialog had no functioning scroll container, so rows+ // below the fold were unreachable → scrollIntoViewIfNeeded can't surface it+ // and toBeInViewport fails.+ const lastRow = sheet.getByText(LAST_DB, { exact: false }).first();+ await expect(+ lastRow,+ "the last target must be present in the (initially scrolled-off) list",+ ).toHaveCount(1);+ await lastRow.scrollIntoViewIfNeeded();+ await expect(+ lastRow,+ "the last target must be reachable by scrolling the sheet (pre-fix the " ++ "popup was frozen and the bottom targets were unreachable)",+ ).toBeInViewport({ timeout: 5000 });++ // Anti-freeze: the in-sheet search narrows the list. Each target renders as+ // a `rounded-lg border` row inside the scroll region; at baseline there are+ // all 21 rows.+ const targetRows = scrollRegion.locator("div.rounded-lg.border");+ await expect(targetRows).toHaveCount(TARGET_COUNT, { timeout: 5000 });++ const search = sheet.getByPlaceholder("Search").first();+ await expect(search).toBeVisible({ timeout: 5000 });+ await search.click();+ await search.pressSequentially(LAST_DB, { delay: 15 });+ // Filtering down to the single matching target proves the list is live+ // (not a frozen popup).+ await expect(targetRows).toHaveCount(1, { timeout: 5000 });+ await expect(scrollRegion.getByText(LAST_DB, { exact: false })).toBeVisible();++ // Escape closes the sheet.+ await page.keyboard.press("Escape");+ await expect(sheet).toHaveCount(0, { timeout: 5000 });+ });+});diff --git a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.tsindex 553f369112..59b4ac16b1 100644--- a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts+++ b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts@@ -120,3 +120,74 @@ test.describe("Failing task transitions to Failed and shows Retry", () => {await expect(planPage.retryButton).toBeVisible({ timeout: 5_000 });});});++test.describe("Expanded task statement preview is height-bounded, not clipped (BYT-9561)", () => {+ // BYT-9561 (FIXED, #20398): in the deploy Task section, expanding a task showed+ // its SQL statement in a ReadonlyMonaco preview that was hard-clipped —+ // statements taller than ~256px were cut off mid-statement with NO scrollbar,+ // so the rest of the SQL was unreachable. Cause: the wrapper used a CSS clamp+ // (max-h-64 + overflow-hidden) while Monaco's autoHeight sized the editor to+ // full content height (default max 600px), so content between the clamp and+ // Monaco's own height was invisible and unscrollable. The fix makes the+ // ReadonlyMonaco respect its max (256) so the editor itself is bounded and+ // scrolls internally; a "Statement truncated due to large size." hint renders.+ //+ // DeployTaskList auto-expands the FIRST task on load, so a single-task plan+ // renders the statement preview without any extra click.++ test("the statement editor is clamped to ~256px and shows the truncation hint", async () => {+ test.setTimeout(180_000);++ // ~25 lines, content height well above the 256px clamp but below Monaco's+ // 600px default — so pre-fix the editor rendered at full (~475px) height+ // inside the 256px overflow-hidden wrapper, and post-fix it is bounded.+ const marker = `e2e_clip_marker_${Date.now()}`;+ const lines: string[] = [];+ for (let i = 1; i <= 24; i++) {+ lines.push(+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_clip_${i} TEXT;`,+ );+ }+ lines.push(`-- ${marker}`);+ const sql = lines.join("\n");++ await createPlanAndNavigate("E2E Task Clip", sql);++ // The first (only) task auto-expands → its ReadonlyMonaco statement preview+ // renders inside the deploy task list.+ const editor = page.locator(".task-list .monaco-editor").first();+ await expect(editor).toBeVisible({ timeout: 30_000 });+ // Let Monaco settle its auto-height.+ await page.waitForTimeout(1000);++ // Sanity: the statement is genuinely taller than the clamp, so Monaco MUST+ // scroll internally (content height > the rendered editor height). This is+ // what makes the test exercise the clipping path. Pre-fix Monaco rendered at+ // full content height (no internal scroll); post-fix it's clamped and the+ // overflow is handled by Monaco's own scrollbar.+ const metrics = await editor.evaluate((el) => {+ const box = el.getBoundingClientRect();+ const linesEl = el.querySelector(".view-lines");+ // Monaco's scrollable content height (the full editor content).+ const contentHeight = linesEl ? linesEl.scrollHeight : 0;+ return { editorHeight: Math.round(box.height), contentHeight };+ });+ expect(+ metrics.contentHeight,+ "the statement content must be taller than the clamp so internal scroll is " ++ "required (otherwise the clipping bug can't manifest)",+ ).toBeGreaterThan(300);++ // Oracle (the fix): the editor element is height-bounded near its 256px max —+ // not the full ~475px content height. A relational bound (<= ~300, above+ // 256 + chrome, far below the pre-fix ~475) discriminates the fix without+ // pinning an exact pixel. Pre-fix the editor rendered at full content height+ // inside a 256px overflow-hidden wrapper with no internal scroll, so the+ // bottom of the statement was unreachable.+ expect(+ metrics.editorHeight,+ `the expanded task statement editor must be height-bounded near its 256px ` ++ `max (was ${metrics.editorHeight}px, content ${metrics.contentHeight}px).`,+ ).toBeLessThanOrEqual(300);+ });+});diff --git a/frontend/tests/e2e/project-databases/project-databases.spec.ts b/frontend/tests/e2e/project-databases/project-databases.spec.tsnew file mode 100644index 0000000000..de22fce663--- /dev/null+++ b/frontend/tests/e2e/project-databases/project-databases.spec.ts@@ -0,0 +1,142 @@+// Project Databases page — selection action bar permission gating.+//+// 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.+//+// 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+// first — that's the condition the bug needs).++import {+ test,+ expect,+ type Browser,+ type BrowserContext,+ type Page,+} from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import { BytebaseApiClient } from "../framework/api-client";+import { signInBrowserAs } from "../framework/sign-in";++test.setTimeout(180_000);++let env: TestEnv & { api: BytebaseApiClient };+let projectId: string;++const TEST_PASSWORD = "e2e-byt9609-pw-1!"; // NOSONAR — e2e fixture only++const DEV_USER = {+ email: "[email protected]",+ title: "E2E 9609 Dev",+ authFile: ".auth/byt9609-dev.json",+ role: "roles/projectDeveloper",+};+const VIEWER_USER = {+ email: "[email protected]",+ title: "E2E 9609 Viewer",+ authFile: ".auth/byt9609-viewer.json",+ role: "roles/projectViewer",+};++const contexts: BrowserContext[] = [];++async function openColdDatabasesPage(+ browser: Browser,+ authFile: string,+): Promise<Page> {+ // Fresh context + first navigation straight to /databases = cold IAM store,+ // exactly the repro condition (never touch /members first).+ const context = await browser.newContext({ storageState: authFile });+ contexts.push(context);+ const page = await context.newPage();+ return page;+}++// Check the env database's row checkbox so the selection action bar appears.+async function selectDatabaseRow(page: Page): Promise<void> {+ await page.goto(`${env.baseURL}/projects/${projectId}/databases`);+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForLoadState("networkidle").catch(() => {});++ const row = page+ .getByRole("row")+ .filter({ hasText: env.databaseId })+ .first();+ await expect(row).toBeVisible({ timeout: 15_000 });+ await row.getByRole("checkbox").first().click();++ // The sticky SelectionActionBar shows "1 selected" once a row is checked.+ await expect(page.getByText("1 selected").first()).toBeVisible({+ timeout: 10_000,+ });+}++test.beforeAll(async ({ browser }) => {+ env = loadTestEnv();+ projectId = env.project.split("/").pop()!;+ await env.api.login(env.adminEmail, env.adminPassword);++ for (const u of [DEV_USER, VIEWER_USER]) {+ try {+ await env.api.createUser(u.email, TEST_PASSWORD, u.title);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ if (!msg.includes("(409)")) throw err;+ }+ await env.api.appendProjectBinding(env.project, u.role, [`user:${u.email}`]);+ await signInBrowserAs(+ browser,+ env.baseURL,+ u.email,+ TEST_PASSWORD,+ u.authFile,+ );+ }+});++test.afterAll(async () => {+ for (const c of contexts) await c.close();+});++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 ({+ browser,+ }) => {+ const page = await openColdDatabasesPage(browser, DEV_USER.authFile);+ await selectDatabaseRow(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"]) {+ await expect(+ page.getByRole("button", { name, exact: true }),+ `"${name}" must be enabled for a projectDeveloper on a cold Database page`,+ ).toBeEnabled({ timeout: 15_000 });+ }+ });++ test("a projectViewer sees Change Database / Sync Schema DISABLED (the bar genuinely gates on IAM)", async ({+ browser,+ }) => {+ // Vacuity guard: proves the developer's enabled state above reflects real+ // permissions, not a permissions-off regression. projectViewer lacks the+ // change/sync permissions, so those buttons must be disabled.+ const page = await openColdDatabasesPage(browser, VIEWER_USER.authFile);+ await selectDatabaseRow(page);++ for (const name of ["Change Database", "Sync Schema"]) {+ await expect(+ page.getByRole("button", { name, exact: true }),+ `"${name}" must be disabled for a projectViewer`,+ ).toBeDisabled({ timeout: 15_000 });+ }+ });+});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 18ea3ce63c..5bb984d1fb 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@@ -361,22 +361,23 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()// to the editor's content — so the recalled SQL appears in the// prompt.//- // KNOWN-BUG (BYT-9560): the pinia → zustand migration in #20363 changed- // the store from mutable Vue refs to immutable- // `webTerminal.ts:updateWebTerminalQueryItem` (`{...item, ...patch}`).- // `useHistory.ts:push` stores the LIVE-at-push-time reference, but the- // store later replaces that object — leaving history.list[i] pointing- // at the empty initial snapshot. move("up") then writes `""` back to- // the tail, so Up/Down appear to do nothing.+ // HISTORY (BYT-9560): the pinia → zustand migration in #20363 originally+ // broke recall entirely (move("up") wrote "" back to the tail, so Up/Down did+ // nothing). #20394 fixed it — recall and full multi-step navigation now work.+ // All three tests below are live regression locks (no `test.fail()`):+ // - Up on an empty prompt recalls the most recent statement.+ // - Down after Up returns to the empty prompt.+ // - Repeated Up walks back through EVERY prior statement (most-recent →+ // oldest); repeated Down walks forward back to empty. (Verified live.)//- // All three tests below are marked `test.fail()` until BYT-9560 lands.- // When the fix arrives they flip from "expected failure" to a real- // pass automatically — DO NOT remove `test.fail()` until the fix- // commit is in `main` and the test pass is verified.+ // Cadence note: Up takes ~2 presses per step (after a recall the cursor sits+ // at end-of-line → the next Up just repositions it to (1,1), re-arming the+ // `cursorAtFirst` gate, before the following Up recalls). Down is 1 press per+ // step. The multi-step test collapses consecutive duplicates and asserts the+ // reachability/order, not the exact press count — see its body.//- // We assert ONLY the user-visible outcome via `editor.getValue()`- // on the last Monaco. We don't assert on the internal `useHistory`- // index — that's implementation. (Principle A.)+ // We assert ONLY the user-visible outcome (the prompt text on the last+ // Monaco). We don't assert on the internal `useHistory` index. (Principle A.)test.beforeEach(async () => {const projectId = env.project.split("/").pop()!;@@ -404,10 +405,8 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()});test("Up arrow on an empty prompt recalls the most recently executed statement", async () => {- // BYT-9560 (single-step Up recall) is FIXED as of the current build —- // the prior `test.fail()` hold flipped to passing, so this now runs as a- // normal regression lock. (Repeated-Up recall is still broken; that case- // keeps its hold below.)+ // BYT-9560 (single-step Up recall) is FIXED — this is a live regression+ // lock. (Multi-step walk-back also works; see the repeated-Up test below.)test.setTimeout(120_000);// Establish a single executed statement so there is something to@@ -510,34 +509,34 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()expect(await readAdminPromptValue()).toBe("");});- test("Up arrow pressed repeatedly walks further back through history", async () => {- // BYT-9560 — multi-step Up recall is STILL broken (single-step Up/Down- // recall was fixed and those holds were removed). Repeated Up does not- // walk further back through history, so this stays an expected-fail hold.- test.fail();+ test("Up arrow pressed repeatedly walks back through every prior statement", async () => {+ // BYT-9560 (multi-step recall) WORKS — repeated Up reaches every prior+ // command, most-recent → oldest. Verified empirically in the live admin+ // terminal.+ //+ // Cadence nuance (this is why the test collapses consecutive duplicates+ // rather than asserting one step per press): the Up-history keybinding is+ // gated on `cursorAtFirst` = cursor at (line 1, col 1) (utils.ts). A recall+ // drops the statement into the prompt and leaves the cursor at END-of-line,+ // so the *next* Up doesn't recall — Monaco's default ArrowUp just moves the+ // cursor back to (1,1), re-arming the gate — and the Up after that recalls+ // the next item. Net: Up takes ~2 presses per step. Down, gated on+ // `cursorAtLast` (already true at end-of-line after a recall), is a clean+ // 1 press per step. Both reach every entry; the test asserts reachability+ // and order, not the exact press count.test.setTimeout(120_000);- // Run three distinct statements. After each, the terminal pushes- // the executed item into history and appends a fresh IDLE prompt- // — so by the third run, history has 3 entries plus the current- // empty tail.+ // Run three distinct statements. After each, the terminal pushes the+ // executed item into history and appends a fresh IDLE prompt.const first = "SELECT 1 AS one;";const second = "SELECT 2 AS two;";const third = "SELECT 3 AS three;";for (const stmt of [first, second, third]) {await runInAdminTerminal(stmt);- // Wait for THIS result row to appear before running the next —- // otherwise the "running" overlay swallows the next click and- // the second/third statement is lost.- await expect(- page- .getByText(/^1\s+rows?$/i)- .first(),- ).toBeVisible({ timeout: 15_000 });- // Wait until the result row count catches up with the number of- // runs. The result panel renders one "1 rows" footer per- // finished query.+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({+ timeout: 15_000,+ });await page.waitForTimeout(400);}@@ -546,26 +545,40 @@ test.describe("Up/down arrow keys scroll the admin terminal's query history", ()await page.waitForTimeout(150);expect(await readAdminPromptValue()).toBe("");- // Press Up once → should recall the most recent (`third`).- await page.keyboard.press("ArrowUp");- await page.waitForTimeout(200);- expect(await readAdminPromptValue()).toBe(third);-- // Press Up again → should step further back to `second`. This is- // the CUJ that distinguishes "history navigation" from "recall last- // command once" — a real terminal lets the user keep scrolling.- await page.keyboard.press("ArrowUp");- await page.waitForTimeout(200);- expect(await readAdminPromptValue()).toBe(second);-- // Press Up again → `first`.- await page.keyboard.press("ArrowUp");- await page.waitForTimeout(200);- expect(await readAdminPromptValue()).toBe(first);+ // Walk a directional key several times, recording the DISTINCT prompt+ // values in the order they first appear (consecutive duplicates — the+ // cursor-reposition no-op presses — are collapsed). Returns the recall+ // progression.+ const walk = async (key: "ArrowUp" | "ArrowDown", presses = 8) => {+ const seen: string[] = [];+ let prev = await readAdminPromptValue();+ for (let i = 0; i < presses; i++) {+ await page.keyboard.press(key);+ await page.waitForTimeout(200);+ const v = await readAdminPromptValue();+ if (v !== prev) {+ seen.push(v);+ prev = v;+ }+ }+ return seen;+ };- // Press Down once → should advance forward to `second`.- await page.keyboard.press("ArrowDown");- await page.waitForTimeout(200);- expect(await readAdminPromptValue()).toBe(second);+ // Up from the empty prompt must walk back through ALL prior statements,+ // most-recent → oldest, and stop at the oldest (no wrap-around).+ const back = await walk("ArrowUp");+ expect(+ back,+ "repeated Up must recall every prior statement in reverse order " ++ "(most-recent → oldest)",+ ).toEqual([third, second, first]);++ // Down from the oldest must walk forward back through them to the empty+ // prompt.+ const forward = await walk("ArrowDown");+ expect(+ forward,+ "repeated Down must walk forward back to the live (empty) prompt",+ ).toEqual([second, third, ""]);});});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.tsindex 40d7edf0d8..8c954fb052 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts@@ -238,3 +238,94 @@ test.describe("Connection panel exposes Databases + Database Group tabs", () =>).toBeVisible({ timeout: 5000 });});});++test.describe("SQL Editor entry from the database page connects the tab (BYT-9616)", () => {+ // BYT-9616 (FIXED, #20473): opening the SQL Editor from a database detail page+ // (the "SQL Editor" button, which window.open's a new tab at+ // /sql-editor/projects/<p>/instances/<i>/databases/<db>) landed on a tab that+ // was NOT actually connected — Run was grayed out for every database and admin+ // mode couldn't be entered. It only reproduced in a COLD session: the editor+ // shell hydrated databases into the React app store, but isConnectedSQLEditorTab+ // still read the (empty-on-cold-deep-link) Pinia store, so the tab was treated+ // as disconnected. A warm session masked it.+ //+ // The lock uses a FRESH context (cold store, like the incognito repro) and does+ // NOT visit /sql-editor first, then drives the database-page entry button.++ let ctx9616: BrowserContext;+ let dbPage: Page;++ test.beforeAll(async ({ browser }) => {+ // Fresh context = cold SQL-editor store, matching the incognito-only repro.+ ctx9616 = await browser.newContext({ storageState: ".auth/state.json" });+ dbPage = await ctx9616.newPage();+ });++ test.afterAll(async () => {+ await ctx9616?.close();+ });++ test("clicking 'SQL Editor' on the database page opens a connected, runnable tab", async () => {+ test.setTimeout(120_000);++ const projectId = env.project.split("/").pop()!;+ // Database detail page (cold load — do NOT visit /sql-editor first).+ await dbPage.goto(+ `${env.baseURL}/projects/${projectId}/instances/${env.instanceId}/databases/${env.databaseId}`,+ );+ await dbPage.keyboard.press("Escape").catch(() => {});+ await dbPage.waitForTimeout(1500);++ // The "SQL Editor" entry is a <dd> (text = sql-editor.self) with onClick that+ // window.open's a new tab (DatabaseSQLEditorButton.tsx). Scope to the <dd>:+ // DashboardHeader also renders a "SQL Editor" *button* that, on a database+ // route, opens the SAME deep link — so a global getByText("SQL Editor")+ // .first() resolves to the header (it precedes the page content in the DOM,+ // confirmed: 2 exact matches, .first() = a SPAN inside a <button>), and the+ // test would pass even if this database-page entry were disabled or its+ // handler regressed. The <dd> locator exercises the intended entry point.+ const entry = dbPage.locator("dd").filter({ hasText: "SQL Editor" });+ await expect(entry).toBeVisible({ timeout: 10_000 });++ const [popup] = await Promise.all([+ ctx9616.waitForEvent("page"),+ entry.click(),+ ]);+ await popup.waitForLoadState("domcontentloaded");+ await popup.keyboard.press("Escape").catch(() => {});+ await popup.waitForTimeout(2000);++ // The popup must be the SQL-editor DB deep link for this database.+ expect(popup.url()).toContain(+ `/sql-editor/projects/${projectId}/instances/${env.instanceId}/databases/${env.databaseId}`,+ );++ const popupEditor = new SqlEditorPage(popup, env.baseURL);+ await expect(popupEditor.runButton).toBeVisible({ timeout: 15_000 });++ // (1) Type a query, THEN assert Run is enabled. Run is correctly disabled on+ // an EMPTY editor, so the discriminating check is "enabled once a query is+ // present" — pre-fix Run stayed grayed even with a query because the tab was+ // treated as disconnected.+ await popupEditor.setEditorContent("SELECT 1 AS n;");+ await expect(+ popupEditor.runButton,+ "Run must become enabled once a query is typed on the connected tab " ++ "(pre-fix it stayed grayed because the tab was disconnected)",+ ).toBeEnabled({ timeout: 15_000 });++ // (2) Running it returns a result — proves the tab is truly connected.+ await popupEditor.runButton.click();+ await expect(popup.getByText(/^1\s+rows?$/i).first()).toBeVisible({+ timeout: 15_000,+ });++ // (3) Admin mode (the wrench) is reachable — it was unavailable pre-fix.+ await expect(+ popupEditor.adminModeButton,+ "admin-mode wrench must be available on the database-page-opened tab",+ ).toBeVisible({ timeout: 10_000 });++ await popup.close();+ });+});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-export.spec.tsindex 9af7647ea1..89bbeb0eb6 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-export.spec.ts@@ -308,6 +308,73 @@ test.describe("Export gated by policy, JIT enabled (C2, C3, C4)", () => {await page.keyboard.press("Escape");});++ test("submitting a Request-export creates a grant with export=true and unmask=false (BYT-9654 end-to-end)", async () => {+ // BYT-9654 end-to-end: the C4 sibling above proves the drawer PRE-FILL+ // (Export checked, Unmask not). This proves the SUBMITTED grant carries the+ // same capabilities — an export request must not silently escalate into an+ // unmask request that approvers would unknowingly grant.+ await applyExportState({ disableExport: true, jit: true });+ // Unique statement so we can find exactly this grant via the API.+ const marker = Date.now();+ const statement = `SELECT emp_no FROM employee WHERE emp_no = ${marker % 100000} LIMIT 1;`;+ await sqlEditor.runPreparedQuery(statement);++ await page+ .getByRole("button", { name: "Request export", exact: true })+ .first()+ .click();++ const drawer = page+ .getByRole("dialog")+ .filter({ hasText: "Request Data Access" });+ await expect(drawer.getByText("Request Data Access")).toBeVisible({+ timeout: 10_000,+ });+ // Leave the pre-filled capabilities untouched (Export checked, Unmask not).+ await expect(+ drawer.getByRole("checkbox", { name: "Export the query result" }),+ ).toBeChecked();+ await expect(+ drawer.getByRole("checkbox", { name: "See unmasked sensitive data" }),+ ).not.toBeChecked();++ // Reason is the only field the user must fill (targets, query, and a 4h+ // duration are pre-filled by RequestExportButton). The drawer ALSO contains+ // a Monaco editor whose hidden textarea has class "inputarea" — exclude it so+ // we target the real Reason <textarea>.+ const reason = drawer.locator('textarea:not([class*="inputarea"])').first();+ await expect(reason).toBeVisible({ timeout: 10_000 });+ await reason.click();+ await reason.fill("e2e BYT-9654 export request");+ await expect(reason).toHaveValue("e2e BYT-9654 export request");+ const submit = drawer.locator("[data-submit-btn]");+ await expect(submit).toBeEnabled({ timeout: 8000 });+ await submit.click();++ // The created grant (PENDING or ACTIVE) must carry export=true, unmask=false.+ let createdName = "";+ await expect+ .poll(+ async () => {+ const r = await env.api.searchMyAccessGrants(env.project);+ const g = r.accessGrants.find((x) => x.query === statement);+ if (!g) return "not-found";+ createdName = g.name;+ // The API omits `unmask` when false (returns undefined), so coerce to+ // boolean: the contract is export=true, unmask NOT set.+ return `export=${!!g.export},unmask=${!!g.unmask}`;+ },+ {+ timeout: 20_000,+ message: "the submitted Request-export grant should be created",+ },+ )+ .toBe("export=true,unmask=false");++ // Clean up the grant we created so it doesn't leak into sibling describes.+ if (createdName) await env.api.revokeAccessGrant(createdName).catch(() => {});+ });});// --- Gated export, JIT off → no export affordance (C8) --------------------diff --git a/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.tsindex e6b3c24ee9..3a7dfb6208 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts@@ -269,7 +269,8 @@ test.describe("ACCESS pane Request-access button opens the grant drawer", () =>// drawer is opened from the generic "Request access" CTA (no pendingCreate).// Asserting unchecked — not just visible — catches a regression that// pre-checks either capability for a plain request. (The "Request export"- // entry point DOES pre-check both — covered in sql-editor-export.spec.ts.)+ // entry point pre-checks ONLY Export, not Unmask, after BYT-9654/#20516 —+ // covered in sql-editor-export.spec.ts.)const unmaskCheckbox = viewerPage.getByRole("checkbox", {name: "See unmasked sensitive data",});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.tsindex fb2a510a66..81e8c9bfb5 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts@@ -159,3 +159,72 @@ test.describe("QueryContextSettingPopover hidden in admin mode (O1)", () => {await page.waitForTimeout(400);});});++test.describe("Sidebar resize works on first drag (BYT-9611)", () => {+ // BYT-9611 (FIXED, #20461): on the VERY FIRST load of the SQL editor, dragging+ // the vertical divider between the left aside panel and the editor did+ // nothing — the first drag was swallowed. Root cause: the sidebar Panel mixed+ // controlled + uncontrolled sizing (`defaultSize` derived from a `useState`+ // the `onResize` callback updated), so the first drag's resize re-rendered a+ // new defaultSize back into react-resizable-panels and ate the gesture. A+ // second drag then worked.+ //+ // This test asserts the FIRST drag after a fresh load resizes the panel. It+ // must run on a freshly navigated page and be the first separator drag — so+ // it uses its own goto and no earlier test in this file drags the handle.++ test("the first drag of the vertical divider resizes the aside panel", async () => {+ test.setTimeout(120_000);++ const projectId = env.project.split("/").pop()!;+ // Fresh navigation: the bug only manifests on the first drag after load.+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await page.keyboard.press("Escape").catch(() => {});+ await page.waitForTimeout(1000);++ // The PanelGroup is horizontal with a single vertical PanelResizeHandle+ // (Separator → role="separator") between the aside panel and the editor+ // (SQLEditorHomePage.tsx:218).+ const handle = page.getByRole("separator").first();+ await expect(handle).toBeVisible({ timeout: 10_000 });++ const before = await handle.boundingBox();+ expect(before, "resize handle must have a bounding box").not.toBeNull();+ const startX = before!.x + before!.width / 2;+ const startY = before!.y + before!.height / 2;++ // FIRST drag — push the divider ~120px to the right.+ await page.mouse.move(startX, startY);+ await page.mouse.down();+ await page.mouse.move(startX + 120, startY, { steps: 10 });+ await page.mouse.up();+ await page.waitForTimeout(400);++ const after = await handle.boundingBox();+ const delta = after!.x - before!.x;+ // Aside default is 25% (~320px @1280) with a 40% max (~512px), so a 120px+ // drag applies fully. Allow clamping/sub-pixel tolerance: require the FIRST+ // drag to move the divider substantially right. Pre-fix this delta was ~0.+ expect(+ delta,+ `the first drag must resize the aside panel — the divider moved ${Math.round(+ delta,+ )}px (expected > 80). Pre-fix the first drag was swallowed (delta ~0).`,+ ).toBeGreaterThan(80);++ // Lock that resizing keeps working: a second drag back left also moves it.+ const mid = await handle.boundingBox();+ const mx = mid!.x + mid!.width / 2;+ const my = mid!.y + mid!.height / 2;+ await page.mouse.move(mx, my);+ await page.mouse.down();+ await page.mouse.move(mx - 100, my, { steps: 10 });+ await page.mouse.up();+ await page.waitForTimeout(400);+ const back = await handle.boundingBox();+ expect(+ back!.x,+ "a subsequent drag left must move the divider back",+ ).toBeLessThan(after!.x);+ });+});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.tsindex 20ea93ba2b..fd6857d0a2 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts@@ -328,3 +328,110 @@ test.describe("Selecting a row paints visible feedback across the row", () => {).toBeGreaterThan(paintedBefore!);});});++test.describe("Result panel search with zero matches raises a no-result toast (BYT-9603)", () => {+ // BYT-9603 (FIXED, #20478): typing a token that matches nothing in the+ // result set used to give NO feedback — the user couldn't tell whether the+ // search ran and found nothing or simply did nothing. The fix raises an INFO+ // toast "No matching result found" (sql-editor.search-no-result) on the+ // transition into the no-matches state (SingleResultView.tsx:392).+ //+ // The toast is gated on `searchActive && indexes.length === 0 &&+ // !wasInNoResultsRef.current`, so it fires once on entering the empty state+ // — exactly the user-visible signal that was missing before the fix.++ test("typing a non-matching token surfaces the no-result toast; a matching token does not", async () => {+ test.setTimeout(120_000);+ await openFreshConnectedTab();++ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({+ timeout: 10_000,+ });++ // The result toolbar's AdvancedSearch input has an empty placeholder, so+ // anchor it inside the `.result-toolbar` container (SingleResultView.tsx).+ const searchInput = page.locator(".result-toolbar input").first();+ await expect(searchInput).toBeVisible({ timeout: 5000 });+ await searchInput.click();+ // pressSequentially mirrors a real user typing; the search query emit is+ // debounced (~300ms) and the no-result effect runs off the resulting+ // searchParams change.+ await searchInput.pressSequentially("zzz_no_such_value", { delay: 20 });+ await page.keyboard.press("Enter");++ // Oracle: the INFO toast appears. It auto-dismisses (~6s), so assert+ // promptly. This is the exact feedback BYT-9603 added.+ await expect(+ page.getByText("No matching result found").first(),+ ).toBeVisible({ timeout: 5000 });++ // Negative cell: clearing and typing a token that DOES match (the literal+ // "1" is in the single result row) must NOT raise the toast. Wait for the+ // prior toast to clear first so we don't read a stale one.+ await expect(page.getByText("No matching result found")).toHaveCount(0, {+ timeout: 8000,+ });+ await searchInput.click();+ await page.keyboard.press("ControlOrMeta+a");+ await page.keyboard.press("Delete");+ await searchInput.pressSequentially("1", { delay: 20 });+ await page.keyboard.press("Enter");+ await page.waitForTimeout(800);+ await expect(page.getByText("No matching result found")).toHaveCount(0);+ });+});++test.describe("Detail panel scrolls long content to the last line (BYT-9610)", () => {+ // BYT-9610 (FIXED, #20461): the cell Detail drawer used `h-full` on its body+ // wrapper, which is 100% of the Sheet popup even though SheetHeader already+ // consumed ~57px at the top. The inner `flex-1 overflow-auto` scroll region+ // therefore extended ~57px PAST the viewport bottom, so the last few lines of+ // long content rendered off-screen and could never be scrolled into view.+ //+ // The fix (DetailPanel.tsx) switched the wrapper to `flex-1 min-h-0`, so the+ // scroll region fits within the sheet and every line is reachable.++ test("the Detail scroll region fits inside the viewport for long content", async () => {+ test.setTimeout(120_000);+ await openFreshConnectedTab();++ // One row, one cell whose value is 300 newline-separated lines, with a+ // unique marker on the FIRST and LAST lines — far taller than the panel's+ // clamp, so the bottom marker sits well below the fold.+ const TOP = "e2e9610top";+ const BOTTOM = "e2e9610bottom";+ await sqlEditor.runPreparedQuery(+ `SELECT '${TOP}' || E'\\n' || string_agg('line-' || lpad(i::text, 4, '0'), E'\\n') || E'\\n${BOTTOM}' AS payload FROM generate_series(1, 300) i;`,+ );+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({+ timeout: 10_000,+ });++ const cell = page.locator('[data-row-index="0"] [data-col-index="1"]');+ await expect(cell).toBeVisible({ timeout: 5000 });+ await cell.click();++ // Confirm the Detail panel opened: the value renders a SECOND time inside the+ // panel (the top marker now appears in both the cell and the panel).+ await expect(page.getByText(TOP).nth(1)).toBeVisible({ timeout: 10_000 });++ // Bug-defining oracle (mirrors the BYT-9558 sheet-scroll lock): the LAST line+ // of the value must be reachable by scrolling the panel. The panel's copy of+ // the bottom marker is the last occurrence in the DOM (the Sheet portals to+ // the end). Pre-fix the scroll region's bottom sat below the viewport, so the+ // last lines could never be scrolled into view; post-fix the region fits and+ // the bottom marker can be brought into the viewport.+ const bottomInPanel = page.getByText(BOTTOM).last();+ await bottomInPanel.scrollIntoViewIfNeeded();+ await expect(+ bottomInPanel,+ "the last line of the Detail value must be reachable by scrolling the " ++ "panel — pre-fix the scroll region overflowed the viewport bottom and " ++ "the bottom lines were off-screen and unreachable",+ ).toBeInViewport({ timeout: 5000 });++ // Close the sheet so a sibling describe sharing the page starts clean.+ await page.keyboard.press("Escape");+ });+});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.tsindex ca46aaae07..ad19194248 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts@@ -391,3 +391,118 @@ test.describe("Schema Diagram menuitem opens the diagram canvas", () => {await expect(tableCards.first()).toBeVisible({ timeout: 15_000 });});});++test.describe("Schema tree folder labels render on a single line (BYT-9602)", () => {+ // BYT-9602 (FIXED, #20446): the SchemaPane tree had two text branches in+ // CommonNode.tsx — the search-highlight branch (HighlightLabelText) carried+ // `flex-1 truncate pl-[2px] min-w-16`, but the plain-text branch (TextNode+ // folder rows like Tables / Views / Indexes / Foreign keys) was a bare+ // `<span className="pl-[2px]">{text}</span>` with NO truncate. At the default+ // pane width and deep indent, two-word labels wrapped onto two lines inside+ // the fixed-height virtualized rows, so the list looked "crunched" with+ // overlapping text. The fix gave the plain-text branch the same+ // `flex-1 truncate ... min-w-16` contract.+ //+ // Oracle: every folder-row label is single-line — `white-space: nowrap`+ // (the `truncate` contract) AND a label box no taller than one line. The+ // CSS-contract half flips exactly with the fix (pre-fix the plain branch had+ // `white-space: normal`); the geometry half is the user-visible "doesn't+ // wrap" effect (M: a relational single-line bound, not an absolute pixel).++ test("expanded folder-row labels do not wrap to a second line", async () => {+ test.setTimeout(120_000);++ const projectId = env.project.split("/").pop()!;+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await page.waitForTimeout(800);++ await sqlEditor.gutterSchemaTab.click();+ await page.waitForTimeout(800);++ // Expand the public schema so its folder rows (Tables / Views / …) — the+ // plain-text TextNode labels the bug affected — become visible.+ const publicRow = page+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')+ .filter({ hasText: "public" })+ .first();+ await expect(publicRow).toBeVisible({ timeout: 10_000 });+ const tablesFolder = page+ .locator(".bb-schema-tree-row")+ .filter({ hasText: /^Tables$/ })+ .first();+ if (!(await tablesFolder.isVisible().catch(() => false))) {+ await publicRow.click();+ }+ await expect(tablesFolder).toBeVisible({ timeout: 5000 });++ // Inspect the FOLDER-row labels the fix touches — the plain-text TextNode+ // rows whose label is a known grouping-folder name (Tables / Views /+ // Functions / Indexes / Foreign keys / …). We deliberately exclude+ // placeholder rows (e.g. an italic "<Empty>" state) which are a different+ // node type and legitimately not truncate-styled.+ const FOLDER_NAMES = new Set([+ "Tables",+ "Views",+ "Functions",+ "Procedures",+ "Sequences",+ "External Tables",+ "Indexes",+ "Foreign keys",+ "Triggers",+ "Partitions",+ "Columns",+ "Dependencies",+ "Packages",+ ]);+ const labels = await page.evaluate((folderNames: string[]) => {+ const names = new Set(folderNames);+ const rows = Array.from(document.querySelectorAll(".bb-schema-tree-row"));+ const out: Array<{+ text: string;+ whiteSpace: string;+ labelHeight: number;+ }> = [];+ for (const row of rows) {+ for (const span of Array.from(row.querySelectorAll("span"))) {+ const direct = Array.from(span.childNodes)+ .filter((n) => n.nodeType === Node.TEXT_NODE)+ .map((n) => n.textContent ?? "")+ .join("")+ .trim();+ if (!names.has(direct)) continue;+ const cs = getComputedStyle(span);+ out.push({+ text: direct,+ whiteSpace: cs.whiteSpace,+ labelHeight: Math.round(span.getBoundingClientRect().height),+ });+ }+ }+ return out;+ }, [...FOLDER_NAMES]);++ expect(+ labels.length,+ "expanding public must reveal at least one grouping-folder label (e.g. Tables)",+ ).toBeGreaterThan(0);++ // CSS-contract: the fix applies `truncate` (white-space: nowrap) to the+ // plain-text branch. Every folder label must be nowrap (pre-fix: normal → wrap).+ const wrapping = labels.filter((l) => l.whiteSpace === "normal");+ expect(+ wrapping,+ `every schema-tree folder label must be single-line (white-space: nowrap); ` ++ `these still wrap: ${JSON.stringify(wrapping)}`,+ ).toEqual([]);++ // User-visible: no folder label is taller than a single line (~20px;+ // 28px allows padding while still failing a 2-line ~40px wrap).+ const tooTall = labels.filter((l) => l.labelHeight > 28);+ expect(+ tooTall,+ `no schema-tree folder label may wrap to a second line; these are multi-line: ` ++ JSON.stringify(tooTall),+ ).toEqual([]);+ });+});diff --git a/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.tsindex 13ef19cf04..3d06cfbf40 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts@@ -27,6 +27,239 @@ test.afterAll(async () => {await sharedContext?.close();});+test.describe("Share popover copy-link button (BYT-9667)", () => {+ // BYT-9667 (FIXED, #20541): the worksheet Share popover's URL copy icon looked+ // inert — same flat grey background as the addon segments, no hover/click+ // feedback (only a bottom toast). The comment thread added two contracts:+ // (a) the copy button must stay CLICKABLE for PRIVATE worksheets (an interim+ // change disabled it for private — Peter rejected that), and+ // (b) it should be disabled ONLY while the tab has unsaved changes.+ // The fix converts it to the shared ghost Button (white bg, grey on hover via+ // `enabled:hover:bg-control-bg-hover`) and gates disabled-ness purely on+ // `tabStatus !== "CLEAN"` (SharePopoverBody.tsx) — never on share visibility.+ //+ // Note: the Share TRIGGER itself requires a CLEAN tab (EditorAction.tsx+ // `allowShare`), so the only legitimate "disabled" path is a dirty tab, which+ // disables the whole Share button (the copy button is then unreachable).++ // This block needs clipboard permission, which the file's shared context+ // lacks — use a dedicated context (same pattern as sql-editor-export.spec.ts).+ let ctx9667: BrowserContext;+ let page9667: Page;+ let editor9667: SqlEditorPage;+ const TITLE = `e2e-byt9667-${Date.now()}`;+ let worksheet = "";++ test.beforeAll(async ({ browser }) => {+ // Created PRIVATE by default — exactly the regression cell.+ worksheet = (+ await env.api.createWorksheet(env.project, TITLE, env.database, "SELECT 1;")+ ).name;+ ctx9667 = await browser.newContext({+ storageState: ".auth/state.json",+ permissions: ["clipboard-read", "clipboard-write"],+ });+ page9667 = await ctx9667.newPage();+ editor9667 = new SqlEditorPage(page9667, env.baseURL);+ });++ test.afterAll(async () => {+ if (worksheet) await env.api.deleteWorksheet(worksheet);+ await ctx9667?.close();+ });++ test("copy button is enabled for a private worksheet, responds to hover, and copies the deep link", async () => {+ test.setTimeout(120_000);++ const projectId = env.project.split("/").pop()!;+ const sheetUuid = worksheet.split("/").pop()!;+ await editor9667.gotoSheet(projectId, sheetUuid);+ await page9667.waitForTimeout(1500);++ // Tab must be CLEAN so the Share trigger is enabled.+ await expect(editor9667.activeTab()).toContainText(TITLE, {+ timeout: 10_000,+ });++ const shareButton = page9667.getByRole("button", {+ name: "Share",+ exact: true,+ });+ await expect(shareButton).toBeEnabled({ timeout: 10_000 });+ await shareButton.click();++ const copyBtn = page9667.locator("[data-copy-btn]");+ await expect(copyBtn).toBeVisible({ timeout: 5000 });++ // (a) Regression: the copy button stays clickable for a PRIVATE worksheet.+ await expect(+ copyBtn,+ "the copy button must remain enabled for a private worksheet",+ ).toBeEnabled();++ // (b) Visual response: hovering changes the background (white → hover grey).+ // Relational assertion (M) — don't pin an exact rgb, just require a change.+ const bgBefore = await copyBtn.evaluate(+ (el) => getComputedStyle(el).backgroundColor,+ );+ await copyBtn.hover();+ await page9667.waitForTimeout(150);+ const bgHover = await copyBtn.evaluate(+ (el) => getComputedStyle(el).backgroundColor,+ );+ expect(+ bgHover,+ `the copy button must show a hover background change (was the headline ` ++ `bug: static grey, no hover feedback). before=${bgBefore} hover=${bgHover}`,+ ).not.toBe(bgBefore);++ // (c) Clicking copies the worksheet deep link + raises the success toast.+ await copyBtn.click();+ await expect(+ page9667.getByText("The URL is copied to your clipboard").first(),+ ).toBeVisible({ timeout: 5000 });+ const clipboard = await page9667.evaluate(() =>+ navigator.clipboard.readText(),+ );+ expect(clipboard).toMatch(+ new RegExp(`/sql-editor/projects/[^/]+/sheets/${sheetUuid}`),+ );+ });++ test("the Share trigger is disabled while the tab has unsaved changes", async () => {+ test.setTimeout(120_000);++ const projectId = env.project.split("/").pop()!;+ const sheetUuid = worksheet.split("/").pop()!;+ await editor9667.gotoSheet(projectId, sheetUuid);+ await page9667.waitForTimeout(1500);+ await expect(editor9667.activeTab()).toContainText(TITLE, {+ timeout: 10_000,+ });++ // Clean → Share enabled.+ const shareButton = page9667.getByRole("button", {+ name: "Share",+ exact: true,+ });+ await expect(shareButton).toBeEnabled({ timeout: 10_000 });++ // Make the tab dirty by editing the statement.+ await editor9667.codeEditor.click();+ await page9667.waitForTimeout(150);+ await page9667.keyboard.type(" -- dirty", { delay: 10 });+ await page9667.waitForTimeout(300);+ await expect(editor9667.activeTabStatus()).resolves.toBe("DIRTY");++ // The only legitimate disable condition after the fix: a dirty tab disables+ // the Share button entirely.+ await expect(+ shareButton,+ "a dirty tab must disable the Share button (the only legitimate disable)",+ ).toBeDisabled({ timeout: 5000 });+ });+});++test.describe("Multi-select delete shows the dedicated confirm dialog (BYT-9631)", () => {+ // BYT-9631 (FIXED, #20541): selecting multiple worksheets via Multi-select and+ // clicking Delete showed the WRONG dialog — the single-folder "Non-empty+ // folder" prompt ("Do you want to move all worksheets into the root folder or+ // just delete them?") with a "Delete all files" / "Move to root folder"+ // choice. For an explicit multi-selection that was confusing and offered a+ // nonsensical "move to root folder" option. The fix routes multi-delete to a+ // dedicated AlertDialog: "Delete selected items?" / "The selected worksheets+ // and folders will be permanently deleted."++ const STAMP = Date.now();+ const TITLE_A = `e2e-multidel-a-${STAMP}`;+ const TITLE_B = `e2e-multidel-b-${STAMP}`;+ const TITLE_C = `e2e-multidel-c-${STAMP}`;+ let wsA = "";+ let wsB = "";+ let wsC = "";++ test.beforeAll(async () => {+ wsA = (await env.api.createWorksheet(env.project, TITLE_A, env.database, "SELECT 1;")).name;+ wsB = (await env.api.createWorksheet(env.project, TITLE_B, env.database, "SELECT 2;")).name;+ wsC = (await env.api.createWorksheet(env.project, TITLE_C, env.database, "SELECT 3;")).name;+ });++ test.afterAll(async () => {+ // A and B may already be deleted by the test; deleteWorksheet swallows 404.+ for (const ws of [wsA, wsB, wsC]) {+ if (ws) await env.api.deleteWorksheet(ws);+ }+ });++ test("deleting two checked worksheets uses the multi-select dialog, not the non-empty-folder prompt", async () => {+ test.setTimeout(120_000);++ await sqlEditor.gotoHome();+ await page.waitForTimeout(1000);++ const tree = page.locator(".worksheet-tree");+ await expect(tree.getByText(TITLE_A).first()).toBeVisible({+ timeout: 10_000,+ });++ // Enter multi-select via the worksheet row's context menu.+ await tree.getByText(TITLE_A).first().click({ button: "right" });+ const multiSelectItem = page.getByRole("menuitem", {+ name: "Multi-select",+ exact: true,+ });+ await expect(multiSelectItem).toBeVisible({ timeout: 5000 });+ await multiSelectItem.click();+ await page.waitForTimeout(500);++ // Check A and B (a subset — leave C unchecked) via their row checkboxes.+ // Anchor on the LEAF row (the nearest treeitem ancestor of the title text) —+ // filtering treeitems by hasText would also match the enclosing "Mine"+ // folder, whose checkbox is the wrong target.+ for (const title of [TITLE_A, TITLE_B]) {+ const titleText = tree.getByText(title).first();+ await expect(titleText).toBeVisible({ timeout: 5000 });+ const row = titleText.locator(+ 'xpath=ancestor-or-self::*[@role="treeitem"][1]',+ );+ await row.getByRole("checkbox").first().click();+ await page.waitForTimeout(200);+ }++ // Click the multi-select toolbar's Delete button (TrashIcon + "Delete").+ const toolbarDelete = page+ .getByRole("button", { name: "Delete", exact: true })+ .first();+ await expect(toolbarDelete).toBeEnabled({ timeout: 5000 });+ await toolbarDelete.click();++ // The dedicated multi-delete dialog — NOT the non-empty-folder prompt.+ const dialog = page.getByRole("alertdialog");+ await expect(dialog).toBeVisible({ timeout: 5000 });+ await expect(dialog.getByText("Delete selected items?")).toBeVisible();+ await expect(+ dialog.getByText(+ "The selected worksheets and folders will be permanently deleted.",+ ),+ ).toBeVisible();+ // The wrong (pre-fix) dialog must be absent.+ await expect(page.getByText("Non-empty folder")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Delete all files" }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Move to root folder" }),+ ).toHaveCount(0);++ // Confirm the delete via the dedicated dialog. The dialog closing on confirm+ // proves the multi-delete flow ran through the CORRECT path (the BYT-9631+ // fix), rather than the old non-empty-folder "move to root / delete all"+ // branch which this selection never should have hit.+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();+ await expect(dialog).not.toBeVisible({ timeout: 5000 });+ });+});+test.describe("Duplicate", () => {// The duplicate handler in SheetTree.tsx (around line 1152) calls// editorWorksheetStore.createWorksheet({ title, folders, database })diff --git a/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.tsindex a6bc5f8583..c353c264f7 100644--- a/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts+++ b/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts@@ -26,6 +26,7 @@import { test, expect, type BrowserContext, type Page } from "@playwright/test";import { loadTestEnv, type TestEnv } from "../framework/env";import type { BytebaseApiClient } from "../framework/api-client";+import { execSql, getInstancePgPort, querySql } from "../framework/psql";import { SqlEditorPage } from "./sql-editor.page";test.setTimeout(120_000);@@ -188,3 +189,187 @@ test.describe("disableCopyData hides the Copy button on results (M2)", () => {).toBeVisible({ timeout: 5_000 });});});++// --- Automatic data source routes DML to the admin data source (BYT-9557) ----+//+// BYT-9557 (FIXED, #20390): on an instance with BOTH an admin and a read-only+// data source, the SQL editor in "Automatic" mode routed EVERY statement —+// including DDL/DML — to the read-only data source. With "Allow querying the+// admin data source" enabled, a DML statement still failed with a Postgres+// "permission denied" error because it executed as the read-only DB user;+// manually switching to the admin data source made the same statement succeed.+// The fix classifies the statement: read-only statements go to the read-only+// data source, but DDL/DML are routed to the admin data source.+//+// This is the M5 prerequisite the file header deferred (needs an instance with+// both an admin + a read-only data source). It mutates the shared env instance,+// so it adds the RO data source AFTER the admin source (index 0 stays admin, so+// getInstancePgPort is unaffected) and removes it in afterAll.++test.describe("Automatic mode routes DML to the admin data source (BYT-9557)", () => {+ const RO_DS_ID = "e2e-ro-9557";+ const RO_USER = "bb_e2e_ro_9557";+ const RO_PROBE_TABLE = "e2e_9557_probe";+ const RO_PASSWORD = "bytebase"; // NOSONAR — e2e fixture only+ let pgPort = "";+ let adminHost = "";+ let roAdded = false;++ test.beforeAll(async () => {+ test.setTimeout(120_000);+ pgPort = await getInstancePgPort(env);+ const instance = await env.api.getInstance(env.instance);+ adminHost = instance.dataSources?.[0]?.host ?? "/tmp";++ // Create a SELECT-only Postgres user on the sample instance (idempotent).+ // execSql throws synchronously; swallow the pre-create cleanup (the user may+ // not exist yet on a first run).+ try {+ execSql(env.databaseId, pgPort, `DROP OWNED BY ${RO_USER}`);+ } catch {+ /* user may not exist yet */+ }+ try {+ execSql(env.databaseId, pgPort, `DROP USER IF EXISTS ${RO_USER}`);+ } catch {+ /* may fail if it owns objects — DROP OWNED above handles the common case */+ }+ execSql(+ env.databaseId,+ pgPort,+ `CREATE USER ${RO_USER} PASSWORD '${RO_PASSWORD}'`,+ );+ execSql(+ env.databaseId,+ pgPort,+ `GRANT CONNECT ON DATABASE ${env.databaseId} TO ${RO_USER}`,+ );+ execSql(+ env.databaseId,+ pgPort,+ `GRANT USAGE ON SCHEMA public TO ${RO_USER}`,+ );+ execSql(+ env.databaseId,+ pgPort,+ `GRANT SELECT ON ALL TABLES IN SCHEMA public TO ${RO_USER}`,+ );+ // A scratch table OWNED BY the admin (bbsample) that the RO user can only+ // SELECT — never UPDATE. A plain UPDATE of this table thus succeeds only if+ // automatic mode routed the DML to the admin data source (the fix); if it+ // routed to the read-only data source it fails with "permission denied".+ execSql(env.databaseId, pgPort, `DROP TABLE IF EXISTS ${RO_PROBE_TABLE}`);+ execSql(+ env.databaseId,+ pgPort,+ `CREATE TABLE ${RO_PROBE_TABLE} (id int PRIMARY KEY, v text)`,+ );+ execSql(env.databaseId, pgPort, `INSERT INTO ${RO_PROBE_TABLE} VALUES (1, 'before')`);+ execSql(env.databaseId, pgPort, `GRANT SELECT ON ${RO_PROBE_TABLE} TO ${RO_USER}`);++ // Add the READ_ONLY data source pointing at the same Postgres.+ await env.api.addDataSource(env.instance, {+ id: RO_DS_ID,+ type: "READ_ONLY",+ username: RO_USER,+ password: RO_PASSWORD,+ host: adminHost,+ port: pgPort,+ });+ roAdded = true;+ });++ test.afterAll(async () => {+ if (roAdded) await env.api.removeDataSource(env.instance, RO_DS_ID);+ try {+ execSql(env.databaseId, pgPort, `DROP OWNED BY ${RO_USER}`);+ execSql(env.databaseId, pgPort, `DROP USER IF EXISTS ${RO_USER}`);+ } catch {+ /* best-effort teardown */+ }+ try {+ execSql(env.databaseId, pgPort, `DROP TABLE IF EXISTS ${RO_PROBE_TABLE}`);+ } catch {+ /* best-effort teardown */+ }+ });++ test("SELECT routes to the read-only data source; DDL succeeds (routed to admin)", async () => {+ test.setTimeout(120_000);+ // Allow the admin data source for automatic DDL/DML routing.+ await applyQueryDataPolicy({ allowAdminDataSource: true });++ const projectId = env.project.split("/").pop()!;+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await page.waitForTimeout(1200);++ // Sanity oracle: in Automatic mode (the default — empty dataSourceId), a+ // read-only statement routes to the read-only data source, so current_user+ // is the RO user. This also proves the RO data source is wired and selected+ // automatically.+ await sqlEditor.runPreparedQuery("SELECT current_user;");+ const selectCell = page.locator(+ '[data-row-index="0"] [data-col-index="1"]',+ );+ await expect(selectCell).toBeVisible({ timeout: 10_000 });+ await expect(+ selectCell,+ "Automatic mode must route a read-only SELECT to the read-only data source",+ ).toHaveText(RO_USER, { timeout: 5000 });++ // Regression oracle: a plain UPDATE (no RETURNING — so it can't be treated+ // as a read) of the admin-owned scratch table, which the RO user can only+ // SELECT. If automatic mode routed the DML to the read-only data source it+ // fails with "permission denied for table"; the fix routes DML to the ADMIN+ // data source (the table's owner), so it succeeds. Pre-fix this rendered the+ // permission-denied error.+ // Re-open the editor in a fresh tab before the UPDATE. runPreparedQuery's+ // setEditorContent does NOT reliably clear a SECOND statement once a result+ // is on screen: the prior SELECT's text is retained, the editor ends up with+ // "SELECT current_user;UPDATE …", Run executes only the SELECT, and the+ // UPDATE never runs — so the old "no permission-denied error" assertion+ // passed vacuously (no UPDATE → no denial). A fresh editor runs the UPDATE+ // in isolation. (Verified: with the fresh editor the UPDATE executes, the UI+ // shows "rows affected", and the row becomes 'after'.)+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);+ await page.waitForTimeout(1200);+ await sqlEditor.setEditorContent(+ `UPDATE ${RO_PROBE_TABLE} SET v = 'after' WHERE id = 1;`,+ );+ await sqlEditor.runButton.click();++ // Positive oracle anchored to THIS statement's effect: poll the row as the+ // owner until v flips 'before' -> 'after'. This both waits for the UPDATE to+ // resolve and proves it actually applied. If automatic mode (wrongly) routed+ // the DML to the read-only data source it would be permission-denied and v+ // would stay 'before', so the poll would time out and fail — unlike a bare+ // "no error visible yet" assertion, which can pass before the statement even+ // resolves.+ await expect+ .poll(+ () =>+ querySql(+ env.databaseId,+ pgPort,+ `SELECT v FROM ${RO_PROBE_TABLE} WHERE id = 1`,+ ),+ {+ timeout: 15_000,+ message:+ "the admin-routed UPDATE must apply (v='after'); if automatic mode " ++ "routed the DML to the read-only data source it would be denied and " ++ "v would stay 'before'",+ },+ )+ .toBe("after");++ // The UPDATE having landed, the user must also not see a permission-denied+ // error. Safe now — the poll proved the statement resolved, so this is not+ // racing it. Pre-fix this rendered "ERROR: permission denied for table".+ await expect(+ page.getByText(/permission denied/i),+ "the DML must not be denied — it should route to the admin data source, " ++ "not the read-only one (which can only SELECT the admin-owned table)",+ ).toHaveCount(0, { timeout: 5000 });+ });+});diff --git a/frontend/tests/e2e/workspace/workspace-banner.spec.ts b/frontend/tests/e2e/workspace/workspace-banner.spec.tsindex 0106f94cfa..41c4901af8 100644--- a/frontend/tests/e2e/workspace/workspace-banner.spec.ts+++ b/frontend/tests/e2e/workspace/workspace-banner.spec.ts@@ -70,9 +70,11 @@ test.describe("External-URL banner", () => {await page.waitForLoadState("networkidle");// The configure CTA + wrench icon are the visible signal of the- // banner. Both must be absent.+ // banner. Both must be absent. The CTA is a RouterLink (role="link")+ // styled to look like a button (BannerExternalUrl in BannersWrapper.tsx),+ // so query it by the link role.await expect(- page.getByRole("button", { name: /Configure now/i }),+ page.getByRole("link", { name: /Configure now/i }),).toHaveCount(0);});@@ -84,8 +86,11 @@ test.describe("External-URL banner", () => {await page.goto(env.baseURL);await page.waitForLoadState("networkidle");+ // The CTA is a RouterLink styled like a button (buttonVariants), so it has+ // role="link", not role="button". (Pre-fix this looked for a button and+ // never matched, even though the product renders the banner correctly.)const configureNow = page- .getByRole("button", { name: /Configure now/i })+ .getByRole("link", { name: /Configure now/i }).first();await expect(configureNow).toBeVisible({ timeout: 10_000 });diff --git a/frontend/tests/e2e/workspace/workspace-seat-limit.spec.ts b/frontend/tests/e2e/workspace/workspace-seat-limit.spec.tsnew file mode 100644index 0000000000..da41b49f44--- /dev/null+++ b/frontend/tests/e2e/workspace/workspace-seat-limit.spec.ts@@ -0,0 +1,207 @@+// Workspace seat limit — over-limit IAM edits (BYT-9633).+//+// BYT-9633 (FIXED, #20492 / #20497; cherry-picked to 3.18.1): on a seat-limited+// license, an over-limit workspace rejected EVERY IAM edit — including+// seat-neutral ones — so granting roles AND creating service accounts both+// failed with "workspace has N users, exceeding the limit of M". Two root causes:+// (a) the seat count included soft-deleted (deactivated) principals, and+// (b) SetIamPolicy rejected any edit where newCount >= oldCount (not just+// edits that INCREASE the count).+// The fix excludes soft-deleted principals from the count and only rejects edits+// that strictly increase it — so a service account (a `serviceAccount:` member,+// seat-neutral) can be created over-limit, while adding another end user is still+// rejected. (Mirrors backend TestSeatLimitAllowsServiceAccountWhenOverLimit.)+//+// SAFETY: this is the only spec that needs the FREE plan, so it DROPS the license+// in beforeAll and RESTORES it in afterAll. It lives in workspace/ (the last test+// directory) so the drop happens only after every other spec has finished, and+// afterAll re-installs + verifies the license BEFORE anything else so a failure+// here cannot strand later runs. Never reorder this earlier.++import { test, expect } from "@playwright/test";+import { loadTestEnv, type TestEnv } from "../framework/env";+import type { BytebaseApiClient, IamPolicy } from "../framework/api-client";++test.describe.configure({ mode: "serial" });++const FREE_SEAT_LIMIT = 20;+const STAMP = Date.now();+const SEAT_PASSWORD = "e2e-seat-pw-1!"; // NOSONAR — e2e fixture only+const SA_PREFIX = `e2e-seat-bot-${STAMP}`;++let env: TestEnv & { api: BytebaseApiClient };+let workspace = "";+let policySnapshot: IamPolicy | undefined;+const createdUserEmails: string[] = [];+let createdSaEmail = "";+let licenseRestored = false;++test.beforeAll(async () => {+ test.setTimeout(240_000);+ env = loadTestEnv();+ await env.api.login(env.adminEmail, env.adminPassword);+ ({ workspace } = await env.api.getActuatorInfo());++ // Snapshot the workspace IAM policy so afterAll can restore it exactly.+ policySnapshot = await env.api.getWorkspaceIamPolicy(workspace);++ // Push the workspace over the FREE seat limit while still licensed. Create+ // enough ACTIVE users so the distinct user: count is FREE_SEAT_LIMIT + 1.+ const info = await env.api.getActuatorInfo();+ const baseline = info.userCountInIam ?? 1;+ const toCreate = Math.max(FREE_SEAT_LIMIT + 1 - baseline, 1);++ const newMembers: string[] = [];+ for (let i = 0; i < toCreate; i++) {+ const email = `e2e-seat-${STAMP}-${i}@example.com`;+ try {+ await env.api.createUser(email, SEAT_PASSWORD, `Seat ${i}`);+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ if (!msg.includes("(409)")) throw err;+ }+ createdUserEmails.push(email);+ newMembers.push(`user:${email}`);+ }++ // Bind all new users as workspaceMember in one write (over the limit now).+ const policy = await env.api.getWorkspaceIamPolicy(workspace);+ const memberBinding = policy.bindings.find(+ (b) => b.role === "roles/workspaceMember",+ );+ if (memberBinding) {+ memberBinding.members = [+ ...new Set([...(memberBinding.members ?? []), ...newMembers]),+ ];+ } else {+ policy.bindings.push({ role: "roles/workspaceMember", members: newMembers });+ }+ await env.api.setWorkspaceIamPolicy(workspace, policy);++ // Drop the license → FREE plan, 20-seat limit. Now over-limit.+ await env.api.uploadLicense("");+ await expect+ .poll(async () => (await env.api.getSubscription()).plan, {+ timeout: 30_000,+ message: "license drop should put the workspace on the FREE plan",+ })+ .toBe("FREE");+ // Confirm the seat count is genuinely over the FREE limit.+ const overLimit = await env.api.getActuatorInfo();+ expect(+ overLimit.userCountInIam ?? 0,+ "the workspace must be over the FREE seat limit for this test to be meaningful",+ ).toBeGreaterThan(FREE_SEAT_LIMIT);+});++test.afterAll(async () => {+ // RESTORE THE LICENSE FIRST — before any other teardown — so a failure+ // elsewhere can't leave the server on the FREE plan for a subsequent run.+ if (env?.api) {+ const license = process.env.BYTEBASE_E2E_LICENSE ?? "";+ for (let attempt = 0; attempt < 3 && !licenseRestored; attempt++) {+ try {+ await env.api.uploadLicense(license);+ const sub = await env.api.getSubscription();+ if (sub.plan && sub.plan !== "FREE") licenseRestored = true;+ } catch {+ /* retry */+ }+ }+ // Restore the original IAM policy (drops the seat-filler + service-account+ // bindings). Re-fetch first so we write with the CURRENT etag: the snapshot+ // was captured in beforeAll and its etag is stale after the intervening IAM+ // writes (the seat-filler bind here and the service-account bind in the+ // first test), and SetIamPolicy rejects a stale non-empty etag as a+ // concurrent update (CodeAborted) — which a bare `.catch` would silently+ // swallow, leaving the workspace polluted.+ if (policySnapshot) {+ const current = await env.api+ .getWorkspaceIamPolicy(workspace)+ .catch(() => undefined);+ if (current) {+ await env.api+ .setWorkspaceIamPolicy(workspace, {+ bindings: policySnapshot.bindings,+ etag: current.etag,+ })+ .catch(() => {});+ }+ }+ // Deactivate the seat-filler users (best-effort cleanup).+ for (const email of createdUserEmails) {+ await env.api.deleteUser(email).catch(() => {});+ }+ if (createdSaEmail) {+ await env.api.deleteServiceAccount(createdSaEmail).catch(() => {});+ }+ }+});++test.describe("Over-limit workspace can still create a service account (BYT-9633)", () => {+ // We assert against the service endpoints the UI calls (CreateServiceAccount ++ // SetIamPolicy) rather than driving the Settings UI: on the FREE plan the+ // frontend Service Accounts page is feature-gated, which is independent of —+ // and would mask — the seat-limit fix under test. The backend operation is the+ // exact one the customer hit ("could not create a service account / add roles").++ test("creating a service account with a workspace role succeeds over the seat limit", async () => {+ test.setTimeout(60_000);++ // Drive the exact path the page's handleCreate uses — create the service+ // account principal, then bind it into workspace IAM as a `serviceAccount:`+ // member (a SEAT-NEUTRAL member). Pre-fix, SetIamPolicy rejected ANY edit+ // when over-limit (newCount >= oldCount), so this binding popped+ // "exceeding the limit"; the fix only rejects edits that strictly increase+ // the (soft-deleted-excluded) seat count, so a service account is allowed.+ const sa = await env.api.createServiceAccount(workspace, SA_PREFIX, "Seat Bot");+ createdSaEmail = sa.email;++ const policy = await env.api.getWorkspaceIamPolicy(workspace);+ const binding = policy.bindings.find(+ (b) => b.role === "roles/workspaceMember",+ );+ const saMember = `serviceAccount:${sa.email}`;+ if (binding) binding.members = [...binding.members, saMember];+ else+ policy.bindings.push({+ role: "roles/workspaceMember",+ members: [saMember],+ });++ // Must NOT throw "exceeding the limit" — a seat-neutral member is allowed.+ await env.api.setWorkspaceIamPolicy(workspace, policy);+ });++ test("adding another end user over the limit is still rejected (vacuity: the limit is active)", async () => {+ test.setTimeout(60_000);++ // Proves the limit is genuinely enforced — so the SA success above reflects+ // the seat-neutral exemption, not a disabled limit. Adding a NEW user:+ // member strictly increases the count and must be rejected.+ const email = `e2e-seat-overflow-${STAMP}@example.com`;+ try {+ await env.api.createUser(email, SEAT_PASSWORD, "Seat Overflow");+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ if (!msg.includes("(409)")) throw err;+ }+ createdUserEmails.push(email);++ const policy = await env.api.getWorkspaceIamPolicy(workspace);+ const binding = policy.bindings.find(+ (b) => b.role === "roles/workspaceMember",+ );+ if (binding) binding.members = [...binding.members, `user:${email}`];+ else+ policy.bindings.push({+ role: "roles/workspaceMember",+ members: [`user:${email}`],+ });++ await expect(+ env.api.setWorkspaceIamPolicy(workspace, policy),+ "adding another end user over the limit must be rejected",+ ).rejects.toThrow(/exceeding the limit/i);+ });+});