Skip to content

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

test(e2e): comprehensive Bytebase frontend e2e suite (#20490)

zchpeter569119f01ef0
diff --git a/frontend/tests/e2e/AGENTS.md b/frontend/tests/e2e/AGENTS.md
index 476ce757af..e6cb4b4296 100644
--- a/frontend/tests/e2e/AGENTS.md
+++ b/frontend/tests/e2e/AGENTS.md
@@ -145,9 +145,377 @@ Get the correct port from `getInstance(env.instance)` rather than hardcoding the
## Known Constraints
- **Sample-data bootstrap**: tests run against data provisioned by `SetupSample` (called from `globalSetup`). The two sample Postgres instances (`test-sample-instance`, `prod-sample-instance`) come up on `PORT+3` / `PORT+4`.
-- **Free plan by default**: the freshly signed-up workspace has no enterprise license. Specs that exercise gated features (masking, classification, etc.) need one. Set `BYTEBASE_E2E_LICENSE` to a license JWT before running and `globalSetup` will install it via `PATCH /v1/subscription/license`; the bootstrap then sets `env.hasLicense = true`. The JWT must be signed by Bytebase's license RSA key — not stored in this repo; ask Bytebase ops for a dev/test license. Without the env var, `env.hasLicense` is false and the bootstrap logs a warning. Enterprise-gated specs must call `test.skip(!env.hasLicense, "…")` in their `beforeAll` (see `masking-exemption.spec.ts` for the pattern) so they're skipped rather than failed on free-plan setups.
+- **License required**: the suite exercises enterprise-only features (masking, JIT, approval workflow, query-data-policy, database groups) and does NOT run on the free plan. Set `BYTEBASE_E2E_LICENSE` to a license JWT signed by Bytebase's license key (ask Bytebase ops for a dev/test license; not stored in this repo); `globalSetup` installs it via `PATCH /v1/subscription/license`. If the env var is absent the bootstrap throws and the whole run stops — there is no per-spec `test.skip` fallback.
- **Serial execution**: `fullyParallel: false` + `workers: 1`. Tests within and across files are sequential.
- **`psql` dependency**: must be on PATH for DDL/DML setup.
- **Unix-like OS only**: the sample Postgres uses Unix sockets in `/tmp`.
- **Admin credentials**: hardcoded `[email protected]` / `12345678`. The first user created via `/v1/auth/signup` becomes workspace admin, so e2e signs up this fixture.
- **DBA fixture**: `[email protected]` / `12345678` is created during `globalSetup` and granted `roles/workspaceDBA`. Used as the second approver by plan-detail approval specs. If a spec needs additional users (developer, QA, etc.), provision them the same way in `mode-start-new-bytebase.ts` — don't assume they exist.
+
+---
+
+<!-- Merged from the former PRINCIPLES.md (QA finding/writing doctrine). -->
+
+## QA Principles — Field Manual
+
+Doctrine for pre-release regression QA. Distilled from gaps between what methodical
+walks find and what humans file. Two parts:
+
+- **Part I** — principles for *finding* bugs (during exploration)
+- **Part II** — principles for *writing* tests (once a bug is reproduced)
+
+
+---
+
+### Who we are
+
+> We are QA engineers in pre-release regression. Our defining trait is **curiosity
+> tempered by logic**. We touch every button to see what happens; we also know what
+> *should* happen and why — by deducing from sibling screens, from commit history,
+> from the user's mental model. We trust what users see over what the codebase
+> asserts. We are skeptical: a button that renders is not a button that works.
+> We are persistent: a bug noticed once but not yet reproduced is not yet found.
+> Everything below follows from this.
+
+---
+
+## Part I — Principles for finding bugs
+
+Ranked from most to least important. Grouped by tier for skimming, but the order
+within and across tiers reflects impact.
+
+### Tier 1 — Mindset (foundational)
+
+These are not techniques. They are who you have to *be* before any technique helps.
+
+#### 1. Be curious — touch every clickable thing
+
+Open every dropdown, click every checkbox, type into every input, right-click
+everywhere. Explore paths the docs don't list. Curiosity is the source of finding;
+without it, no method produces anything. A page is "checked" only after you have
+probed every interactive element on it.
+
+**In practice:** enumerate every `button`, `input`, `checkbox`, `dropdown`,
+`menuitem`, and right-click target on the screen before declaring it covered.
+
+#### 2. Be logical — reason about expected behavior
+
+Curiosity without logic is noise. Before flagging anything, ask: *what should this
+screen do, and why?* Deduce expected behavior from related views, from how comparable
+products work, from the underlying data model, from commit history. Cross-reference:
+if X holds on screen A, screen B's behavior must follow. *New* is not *broken*;
+*weird* is not always *bug* — but verify with reasoning, not assumption.
+
+**In practice:** when a behavior looks off, write down "I expected X because Y"
+before declaring it a defect. If your *why* is "it just feels wrong," you haven't
+reasoned yet.
+
+#### 3. Be the user — narrate the experience
+
+Stop describing what the codebase does. Describe what a person sees and feels.
+"I clicked Run and waited five seconds for nothing to happen" surfaces bugs that
+"Run button has class X" never will. Users notice in 30 seconds what exhaustive
+automation misses in an hour.
+
+**In practice:** after each interaction, ask "what would a customer say happened
+just now?" If the answer is interesting, file it.
+
+### Tier 2 — Coverage (what to test)
+
+Once you have the right mindset, these principles direct *where* to look.
+
+#### 4. Stress what looks static
+
+Static screens pass. Bugs hide under load. For every input field: try empty,
+near-empty, full-to-the-limit, beyond-the-limit, unicode, emoji, very long strings,
+special characters. For every button: click rapidly, click many times in succession,
+click during loading, click while another action is in flight. For every list or
+table: empty state, one item, hundreds, thousands. Bugs that are invisible at rest
+become loud under pressure.
+
+**In practice:** every CUJ has a "stressed" variant. Add it deliberately, don't
+wait to discover it.
+
+**Enumerate, don't just stress.** Before declaring an area covered, list every
+clickable leaf (button, icon, toggle, menuitem) in that area and click each one
+once. Coverage holes — like a Schema-diagram tab nobody opened, or a Copy button
+nobody clicked in admin mode — come from following CUJs without enumeration.
+
+#### 5. Test sequences, not just isolated actions
+
+Bugs cluster at the boundaries between actions, not inside them. Build interaction
+graphs: *switch context → return → re-engage*. *Open dialog → cancel → reopen*.
+*Trigger A → trigger B in flight → trigger A again*. The third action in a chain
+is where state corruption lives. A test of "X works" and "Y works" does not prove
+that "X then Y" works.
+
+**In practice:** for every pair of major actions, walk A→B and B→A. For every
+modal, sidebar, or tab, test the re-engagement path after closing.
+
+**Side-effects across unrelated views.** Open view A → trigger an unrelated action
+in B → return to A and assert A is unchanged. Each half is "correct" in isolation —
+the bug only exists when both views are alive at the same time. Example: opening
+the History sidebar then running a query in the editor silently nuked the history
+list. Running and history-search worked fine alone.
+
+#### 6. Vary the data, not just the queries
+
+Renderers break on shapes other than the happy case. The same surface against
+different data — NULLs, wide rows, deeply-nested objects, binary, errors, large
+strings, special characters, multi-statement, empty result — exercises a different
+code path each time. A single happy-path test is a smoke test, not a stress test.
+
+**In practice:** keep a "data variety" pass per result-rendering surface. Each
+variant is its own test.
+
+#### 7. Test from real user states, not just admin
+
+Admin bypasses most gates. The interesting bugs live at permission boundaries —
+visible only to scoped users. Maintain a fixture user roster (no-membership, viewer,
+developer, admin) and run the same tour as each. The bugs that ship are the ones
+admins can't see.
+
+**In practice:** every CUJ touching permissions runs at least twice — admin and
+non-admin. Helpers for grant/revoke make this cheap.
+
+#### 8. Let the diff drive the work
+
+The bug surface is what changed. `git log` since the previous release ranks risk.
+Weight exploration time toward high-delta surfaces; do not spend cycles on code
+that has been stable for a year.
+
+**In practice:** read the diff before designing CUJs. Score each CUJ by lines-changed
+in its surface area. Walk highest-risk first while you're still fresh.
+
+### Tier 3 — Observation (how to see)
+
+Curiosity and coverage put you in front of the bug. These principles ensure you
+*see* it.
+
+#### 9. Look at the screen, not just the DOM
+
+JS evals tell you what's *there*. Screenshots tell you what a user *sees*. They
+disagree more often than you'd expect: contrast, overlap, truncation, two-line
+expansion of single-line widgets, disabled-looking-but-clickable controls. Most
+visual bugs are invisible to DOM-only inspection.
+
+**In practice:** after every meaningful state change, capture a screenshot and
+read it like an image, not a log. Describe what you see in plain language before
+moving on.
+
+**And read every word.** Form labels, dropdown options, helper text, version
+banners, confirm-dialog titles — read them one by one. Duplicate wording (a field
+labeled "Expiration" with a "4 hours" dropdown that *also* says "hours" inline),
+backwards version banners ("New version 3.17.1 available" while you're on 3.18),
+and placebo confirm dialogs ("Confirm to delete this worksheet?" with no body
+text) all hide in plain text we breeze past.
+
+#### 10. Record video for transient bugs
+
+Some bugs only exist in motion: a button that blinks on hover, a modal that flashes
+and disappears, an overlay that flickers during a race condition, an animation that
+stutters. Screenshots miss these entirely. Run a screen recorder for every
+exploratory session; review at half speed when something feels off.
+
+**In practice:** keep a video capture running continuously. Mark timestamps when
+something feels off; review and trim before filing.
+
+#### 11. Profile network per action
+
+Every user click has a request budget. Anything fanning out to `List*` endpoints on
+a simple switch, or repeating identical requests, or firing more than a handful of
+calls on a navigation — is suspect. Performance regressions hide from functional
+tests.
+
+**In practice:** capture `performance.getEntriesByType('resource')` before and
+after each action; diff the count and the URLs.
+
+#### 12. Read commit messages — they name risk surfaces
+
+Each "refactor: migrate X" is a hypothesis to test. Each "fix: cannot Y" is a
+region of recent fragility. Commit history is the engineering team's confession
+about where the bugs were; it tells you where the next ones probably are. Use it.
+
+**In practice:** before exploring an area, `git log --oneline <prev-release>..HEAD -- <area>`.
+Treat each commit as a target.
+
+### Tier 4 — Discipline (how to verify honestly)
+
+Once you think you have a finding, these principles prevent self-deception.
+
+#### 13. Distinguish "wired up" from "works"
+
+Three layers before ✓: render (DOM exists), interactive (click registers a state
+change), end-to-end (action produces a user-visible outcome). Do not conflate
+them. Many automation tools fire events that the framework's handlers do not
+register — the click looks made but nothing happens downstream.
+
+**In practice:** for every control, confirm a state change after the click —
+not just that the click was issued.
+
+#### 14. When DOM and screen disagree, trust the screen
+
+The user sees the screen. If your selector reports one thing and the rendered
+output shows another, your selector is wrong — not the product. Stop debugging
+the product; debug your observation.
+
+**In practice:** when JS state surprises you, screenshot first, then debug the
+selector. The image is ground truth.
+
+#### 15. Compare across surfaces — same widget, every page
+
+The same button, the same icon, the same toggle should render the same way on
+every page that uses it. The Issues-page Save button should look like the
+SQL-Editor Save button should look like the Settings-page Save button — same
+size, same color, same hover state, same affordance. Single-surface walks miss
+this entire bug class because they only ever see one instance of each widget.
+
+Visual consistency is *the* tell of a well-maintained design system; lapses are
+*the* tell of a recent migration that didn't quite finish.
+
+**In practice:** keep a list of widgets that should be identical (Save, Cancel,
+the avatar dropdown, status badges, etc.) and screenshot each one on at least
+three different surfaces. Diff the images visually; mismatches are bugs.
+
+---
+
+## Part II — Principles for writing tests
+
+Once a bug is reproduced or a CUJ is validated, the next job is locking it in
+durable `.spec.ts` code. These conventions cover both bug-lock tests and CUJ
+tests.
+
+#### A. Assert outcomes, not implementation
+
+Check the user-observable thing. Tests survive refactors only when they verify
+what the user sees, not what the codebase happens to render.
+
+- Bad: `expect(button).toHaveClass('bg-accent')`
+- Good: `await expect(page.getByText('Exit admin mode')).toBeVisible()`
+
+#### B. Bug-lock tests must fail on the buggy build
+
+A passing bug-lock test is a broken test. Each must fail with a message that
+pinpoints the bug. Use `test.fail()` when the bug is known-unfixed. **Never use
+`test.skip()`** — skipping hides regressions instead of catching them.
+
+#### C. Tests own their fixtures, not discover them
+
+Create your own schema, tables, rows in `beforeAll`; drop in `afterAll`. Don't
+discover demo data — discovery-based tests fail when seed data drifts.
+
+#### D. Integration sequences > isolated actions
+
+One spec doing `switch tab → click sidebar → switch project → return → click sidebar`
+catches state-corruption bugs that three isolated specs would miss. Tests should
+read like user stories, not unit tests.
+
+#### E. Visual assertions via screenshot baselines
+
+For visual bugs (icon contrast, overlap, truncation), add
+`await expect(page).toHaveScreenshot('export-dialog.png')` baselines. No JS
+assertion catches "icons too light." Add explicit baselines per visual surface,
+not just on failure.
+
+#### F. Test by role, not just by admin
+
+Build `loginAs('sqlEditorReadUser')` and friends. Same spec, multiple users.
+Permission bugs only surface this way. Use API-based role grant/revoke in
+`beforeAll`/`afterAll` so tests don't lean on seeded IAM.
+
+#### G. Parameterize data-variety in result tests
+
+One spec, many cases: NULL, JSON, binary, wide-row, error, large-string. Each
+a different test case via `test.describe.each`. Closes the gap that single
+happy-path tests leave open.
+
+#### H. Network-budget assertions
+
+For dialogs and switches that shouldn't refetch:
+
+```typescript
+expect(networkLog.count).toBeLessThanOrEqual(N);
+```
+
+Catches performance regressions. Use Playwright's `page.on('request')` per spec.
+
+#### I. One concept per test; name = user behavior
+
+Names become the spec doc. Write them as sentences a PM could read.
+
+- Bad: `'handleClick fires updateCurrentTab'`
+- Good: `'clicking 10000-rows preset updates the displayed export limit'`
+
+#### J. Test boundaries, not just happy paths
+
+Every input gets: empty, max, min, special-chars. Most missed bugs are boundary
+issues. Empty-state, one-item, hundreds, thousands all deserve their own test
+case.
+
+#### K. Test the test before trusting it
+
+Mutate the production code (delete the handler, change the value) and re-run.
+If the test still passes, it isn't actually checking the thing.
+
+#### L. Self-contained state
+
+No test depends on another's leftovers. Every spec sets up and tears down its
+own DB schema, worksheets, IAM bindings. Independence is the only way tests
+survive at scale.
+
+#### M. Assert visual relationships, not absolute thresholds
+
+When a bug is "X looks wrong against Y", phrase the test as a comparison
+between X and Y — not as X must equal some specific value. The fix could pick
+any reasonable shade, size, or position; your test should pass for every
+reasonable choice, not just the one you happened to expect.
+
+- Bad: `expect(maxChannel(block)).toBeLessThan(80)` — pins "dark" to a
+ specific RGB threshold; fails if the design system later picks a slightly
+ lighter dark, even though the user-visible problem is solved.
+- Good: `expect(maxChannelDelta(block, shell)).toBeLessThan(100)` — asserts
+ the block harmonizes with its container. Any reasonable theme passes.
+
+This applies anywhere the bug is contextual: a misaligned button (test
+relative position to its row, not absolute pixels), a row highlight that
+matches the wrong column (test the row container's bg vs the surrounding
+rows, not a literal rgb), a tooltip overlapping its trigger (test
+bounding-rect intersection, not absolute coordinates), an inconsistent
+icon size across surfaces (compare across instances, not against `16px`).
+
+Why this matters: thresholds tied to specific values rot fast — the design
+system revises them and the test fails for a reason unrelated to the bug.
+Relational assertions capture the user's actual judgment ("does this look
+out of place?") and survive any tweak that preserves the relationship. The
+failure message is also more useful: "block (rgb 243/244/246) differs from
+shell (rgb 30/30/30) by 216 channels" tells a future maintainer what was
+wrong; "max channel was 246, expected <80" tells them only that you guessed
+80.
+
+---
+
+### Quick reference — mapping principles to bug categories
+
+| Bug class | Principles that catch it |
+|---|---|
+| Visual / layout / contrast | #09 screen · #10 video · E visual baselines · M visual relationships |
+| Permission / role-gated | #07 real user states · F test by role |
+| State corruption / sequence | #05 sequences · D integration sequences |
+| Performance / network | #11 network profiling · H budgets |
+| Render edge cases (data) | #06 data variety · G parameterized data |
+| Stress / load / rapid clicks | #04 stress · J boundary tests |
+| "Wired but broken" | #13 wired vs works · #14 trust screen · K test the test |
+| New regression in migrated code | #08 diff-driven · #12 read commits |
+| Out-of-theme / inconsistent styling | #15 cross-surface compare · M visual relationships |
+| Anything subtle a user notices | #03 be the user · #01 curiosity · #02 logic |
+
+---
+
+### Closing
+
+A QA engineer who follows none of these but is genuinely curious will still find
+more bugs than one who follows all of them mechanically. The mindset principles
+in Tier 1 are necessary; the rest are amplifiers. Curiosity tempered by logic,
+applied to the real user's experience — that is the entire craft.
+
+The methods are just shape we give to a habit.
diff --git a/frontend/tests/e2e/README.md b/frontend/tests/e2e/README.md
index 4f3a6ab2bf..66453c7b19 100644
--- a/frontend/tests/e2e/README.md
+++ b/frontend/tests/e2e/README.md
@@ -34,22 +34,71 @@ pnpm exec playwright test masking-exemption
| `BYTEBASE_BIN` | No | `./bytebase-build/bytebase` | Path to pre-built binary |
| `BYTEBASE_STARTUP_TIMEOUT` | No | `300000` (5 min) | Server startup timeout in ms |
| `BYTEBASE_HEADED` | No | — | Set to `1` for headed browser |
+| `BYTEBASE_E2E_LICENSE` | **Yes** | — | Enterprise license JWT (see below) |
| `CI` | No | — | Enables CI-specific reporter |
+### Enterprise license (`BYTEBASE_E2E_LICENSE`)
+
+The suite exercises enterprise-only features (masking, JIT drawer, approval
+rules, query-data-policy gates like `disableExport` / `disableCopyData`,
+database groups). A license is **required** — without `BYTEBASE_E2E_LICENSE`
+the run fails fast in global setup. There is no free-plan fallback.
+
+The license JWT is signed by Bytebase's license RSA key — ask
+Bytebase ops for a dev/test license. **Never commit it to the repo
+or paste it into chat / issue trackers / memory files.**
+
+Recommended local options (pick one):
+
+```bash
+# (a) Out-of-repo file + on-demand env (recommended)
+mkdir -p ~/.config/bytebase
+chmod 700 ~/.config/bytebase
+echo '<your-jwt>' > ~/.config/bytebase/e2e-license
+chmod 600 ~/.config/bytebase/e2e-license
+
+# Then when running the suite:
+BYTEBASE_E2E_LICENSE=$(cat ~/.config/bytebase/e2e-license) \
+ pnpm exec playwright test
+
+# (b) direnv (auto-loaded on cd into the repo)
+echo 'export BYTEBASE_E2E_LICENSE=$(cat ~/.config/bytebase/e2e-license)' \
+ >> .envrc
+direnv allow
+
+# (c) Shell rc / login profile (always available)
+# Add to ~/.zshrc.local or similar gitignored file:
+export BYTEBASE_E2E_LICENSE='<your-jwt>'
+```
+
+Do **not** put the JWT in `frontend/.env*` or any file inside the
+repo, even if gitignored — too easy to accidentally commit, and
+`.env*` files inside repos are commonly opened by IDEs / pasted
+into screenshots.
+
## Directory Layout
```
frontend/tests/e2e/
├── README.md — this file (human docs)
-├── AGENTS.md — conventions for AI agents / contributors
+├── AGENTS.md — conventions + QA doctrine for AI agents / contributors
├── framework/ — shared test infrastructure
│ ├── api-client.ts — Bytebase v1 REST API wrapper
│ ├── env.ts — TestEnv interface, serialization
│ ├── mode-start-new-bytebase.ts — server lifecycle (start/stop/cleanup)
│ ├── global-setup.ts — starts the server before any tests
│ ├── global-teardown.ts — stops the server after all tests
-│ └── setup-project.ts — auth + discovery (runs as a Playwright setup project)
-└── masking-exemption/ — feature test suite
+│ ├── setup-project.ts — auth + discovery (runs as a Playwright setup project)
+│ ├── seed-test-data.ts — workspace-level baseline seeded once per boot
+│ ├── sign-in.ts — POST-login helper that captures per-user storageState
+│ └── psql.ts — psql-over-Unix-socket helpers for DDL/DML setup
+├── sql-editor/ — SQL Editor suite (connection, result, tabs, worksheet,
+│ schema, admin-mode, history, jit, permissions,
+│ workspace-gates, batch, misc) + sql-editor.page.ts
+├── plan-detail/ — plan detail suite (checks, rollout, sections, tasks)
+│ + plan-detail.page.ts, plan-helpers.ts
+├── workspace/ — workspace-level suite (external-URL banner)
+└── masking-exemption/ — masking exemption suite
├── masking-exemption.spec.ts
└── masking-exemption.page.ts
```
diff --git a/frontend/tests/e2e/framework/api-client.ts b/frontend/tests/e2e/framework/api-client.ts
index cec163e0d4..dfcf75e066 100644
--- a/frontend/tests/e2e/framework/api-client.ts
+++ b/frontend/tests/e2e/framework/api-client.ts
@@ -3,6 +3,17 @@ export interface ApiClientOptions {
credentials?: { email: string; password: string }; // Optional only during server startup before credentials are known
}
+export interface IamBinding {
+ role: string;
+ members: string[];
+ condition?: { expression: string; title?: string };
+}
+
+export interface IamPolicy {
+ bindings: IamBinding[];
+ etag?: string;
+}
+
export class BytebaseApiClient {
private baseURL: string;
private token = "";
@@ -77,6 +88,75 @@ export class BytebaseApiClient {
await this.request<unknown>("POST", "/v1/actuator:setupSample", {});
}
+ // Generic workspace setting upsert. Mirrors the frontend store's
+ // `upsertSetting({ name, value })` in store/modules/v1/setting.ts —
+ // same endpoint, same body shape, just exposed for tests that need to
+ // configure workspace-level state in beforeAll.
+ //
+ // `name` is the bare enum value (e.g., "WORKSPACE_PROFILE",
+ // "WORKSPACE_APPROVAL") — `settings/` is prefixed here.
+ // `updateMaskPath` is the gRPC field mask path (e.g.,
+ // "value.workspace_profile.external_url" or "value.workspace_approval").
+ async upsertSetting(
+ name: string,
+ value: unknown,
+ updateMaskPath: string,
+ ): Promise<void> {
+ await this.request<unknown>(
+ "PATCH",
+ `/v1/settings/${name}?updateMask=${encodeURIComponent(updateMaskPath)}&allowMissing=true`,
+ { name: `settings/${name}`, value },
+ );
+ }
+
+ // Convenience wrapper for the most common workspace-setting call.
+ // Silences the "Bytebase has not configured --external-url" banner
+ // (frontend BannersWrapper.tsx checks `serverInfo.externalUrl` for a
+ // truthy value).
+ async setWorkspaceExternalUrl(externalUrl: string): Promise<void> {
+ await this.upsertSetting(
+ "WORKSPACE_PROFILE",
+ { workspaceProfile: { externalUrl } },
+ "value.workspace_profile.external_url",
+ );
+ }
+
+ // Read a setting; returns null on 404 (setting never set on this server).
+ async getSetting(name: string): Promise<{ name: string; value?: unknown } | null> {
+ try {
+ return await this.request<{ name: string; value?: unknown }>(
+ "GET",
+ `/v1/settings/${name}`,
+ );
+ } catch {
+ return null;
+ }
+ }
+
+ // Creates a new project with the given resourceId and title. Used by the
+ // seed-test-data fixture to ensure tests have ≥ 2 projects (the
+ // project-switcher CUJ in connection.spec.ts needs an alternative to the
+ // default "Sample Project").
+ async createProject(
+ projectId: string,
+ title: string,
+ settings: { allowRequestRole?: boolean; allowJustInTimeAccess?: boolean } = {},
+ ): Promise<{ name: string }> {
+ return this.request<{ name: string }>(
+ "POST",
+ `/v1/projects?projectId=${projectId}`,
+ {
+ title,
+ ...(settings.allowRequestRole !== undefined && {
+ allowRequestRole: settings.allowRequestRole,
+ }),
+ ...(settings.allowJustInTimeAccess !== undefined && {
+ allowJustInTimeAccess: settings.allowJustInTimeAccess,
+ }),
+ },
+ );
+ }
+
// Installs an enterprise license JWT. The JWT must be signed by Bytebase's
// license RSA key — generate it out of band; this client only uploads it.
async uploadLicense(license: string): Promise<void> {
@@ -142,9 +222,21 @@ export class BytebaseApiClient {
}
async upsertPolicy(parent: string, policyType: string, policy: unknown) {
- // Derive the oneof field name from policyType: "masking_exemption" → "masking_exemption_policy"
- // The backend expects the updateMask to target the specific policy oneof field.
- const updateMask = `${policyType}_policy`;
+ // The URL segment is the lowercased enum name (e.g. "data_query") but
+ // the updateMask must reference the proto FIELD name in the Policy
+ // oneof — which is NOT always `${policyType}_policy`. For most
+ // policies the two coincide (masking_exemption → masking_exemption_policy),
+ // but `data_query` maps to `query_data_policy` (words reversed —
+ // see proto/v1/v1/org_policy_service.proto). Map explicitly so the
+ // gateway accepts the mask.
+ const fieldByType: Record<string, string> = {
+ rollout: "rollout_policy",
+ masking_exemption: "masking_exemption_policy",
+ masking_rule: "masking_rule_policy",
+ data_query: "query_data_policy",
+ tag: "tag_policy",
+ };
+ const updateMask = fieldByType[policyType] ?? `${policyType}_policy`;
return this.request<unknown>(
"PATCH",
`/v1/${parent}/policies/${policyType}?allowMissing=true&updateMask=${updateMask}`,
@@ -185,6 +277,40 @@ export class BytebaseApiClient {
});
}
+ // Note: createUser is defined earlier in this file (added by the demo
+ // -> signup migration on main, signature `(email, password, title)`).
+ // Tests that previously used the local duplicate `(email, title, password)`
+ // must use the canonical signature now.
+
+ // IAM — project. Read the current policy, mutate bindings (typically
+ // by appending), and POST it back. Caller is responsible for
+ // preserving the etag and any existing bindings they care about.
+ async getProjectIamPolicy(project: string): Promise<IamPolicy> {
+ return this.request<IamPolicy>("GET", `/v1/${project}:getIamPolicy`);
+ }
+
+ async setProjectIamPolicy(project: string, policy: IamPolicy): Promise<IamPolicy> {
+ return this.request<IamPolicy>(
+ "POST",
+ `/v1/${project}:setIamPolicy`,
+ { resource: project, policy, etag: policy.etag ?? "" },
+ );
+ }
+
+ // Convenience: append a single binding (members + optional condition)
+ // to a project's IAM policy without disturbing existing bindings.
+ // Re-fetches before the write to pick up any concurrent etag bump.
+ async appendProjectBinding(
+ project: string,
+ role: string,
+ members: string[],
+ condition?: { expression: string; title?: string },
+ ): Promise<void> {
+ const current = await this.getProjectIamPolicy(project);
+ current.bindings.push({ role, members, condition: condition ?? { expression: "" } });
+ await this.setProjectIamPolicy(project, current);
+ }
+
// Service Accounts
async createServiceAccount(parent: string, serviceAccountId: string, title: string) {
return this.request<{ name: string; email: string }>("POST",
@@ -207,6 +333,34 @@ export class BytebaseApiClient {
try { await this.request<unknown>("DELETE", `/v1/workloadIdentities/${email}`); } catch { /* ignore */ }
}
+ // Database groups — a project-scoped collection of databases selected
+ // by a CEL condition (e.g. `resource.database_name.startsWith("hr_")`).
+ // The SQL editor's connection panel surfaces groups under the
+ // "Database Group" tab so users can run a query against all matching
+ // databases at once (batch query).
+ async createDatabaseGroup(
+ project: string,
+ groupId: string,
+ title: string,
+ conditionExpression: string,
+ ): Promise<{ name: string }> {
+ // The proto binds `body: "database_group"` on CreateDatabaseGroup,
+ // so the HTTP body is the DatabaseGroup payload directly (not
+ // wrapped under `databaseGroup`).
+ return this.request<{ name: string }>(
+ "POST",
+ `/v1/${project}/databaseGroups?databaseGroupId=${groupId}`,
+ {
+ title,
+ databaseExpr: { expression: conditionExpression },
+ },
+ );
+ }
+
+ async deleteDatabaseGroup(name: string): Promise<void> {
+ try { await this.request<unknown>("DELETE", `/v1/${name}`); } catch { /* ignore */ }
+ }
+
// Sheets
async createSheet(project: string, content: string): Promise<string> {
const b64 = Buffer.from(content).toString("base64");
@@ -216,6 +370,38 @@ export class BytebaseApiClient {
return resp.name;
}
+ // Worksheets — distinct from Sheets. SQL Editor's left sidebar tree shows
+ // Worksheets, identified by `projects/{project}/worksheets/{uuid}`. The
+ // UUID portion is what the editor URL takes (`/sheets/{uuid}` confusingly
+ // routes to a worksheet).
+ async createWorksheet(project: string, title: string, database: string, content: string): Promise<{ name: string }> {
+ const b64 = Buffer.from(content).toString("base64");
+ return this.request<{ name: string }>(
+ "POST", `/v1/${project}/worksheets`,
+ { title, database, content: b64, visibility: "PRIVATE" },
+ );
+ }
+
+ async deleteWorksheet(name: string): Promise<void> {
+ try { await this.request<unknown>("DELETE", `/v1/${name}`); } catch { /* ignore */ }
+ }
+
+ // Locate a database by short name (e.g., "family_prod") across every
+ // instance reachable to the test user. Used by tests that need a database
+ // outside the env-discovered default (e.g., R7 needs both hr_prod and a
+ // MySQL family_prod).
+ async findDatabaseByShortName(shortName: string): Promise<{ database: string; instance: string; engine: string } | null> {
+ const { instances } = await this.listInstances();
+ for (const inst of instances) {
+ const { databases } = await this.listDatabases(inst.name);
+ const match = databases.find((d) => d.name.endsWith(`/${shortName}`));
+ if (match) {
+ return { database: match.name, instance: inst.name, engine: inst.engine };
+ }
+ }
+ return null;
+ }
+
// Plans
async createPlan(project: string, title: string, specs: { id: string; targets: string[]; sheet: string }[]): Promise<{ name: string }> {
return this.request<{ name: string }>("POST", `/v1/${project}/plans`, {
@@ -232,7 +418,16 @@ export class BytebaseApiClient {
}
async runPlanChecks(planName: string): Promise<void> {
- await this.request("POST", `/v1/${planName}:runPlanChecks`, {});
+ try {
+ await this.request("POST", `/v1/${planName}:runPlanChecks`, {});
+ } catch (err) {
+ // Once a rollout exists, the server rejects `runPlanChecks` with
+ // "cannot run plan checks because plan already has a rollout".
+ // That state implies checks already completed at issue-creation
+ // time — calling again is unnecessary, so swallow this case.
+ const msg = err instanceof Error ? err.message : String(err);
+ if (!msg.includes("already has a rollout")) throw err;
+ }
}
async getPlanCheckRun(planName: string): Promise<{ status: string; results: { status: string; type: string; title: string }[] }> {
@@ -255,11 +450,58 @@ export class BytebaseApiClient {
}
// Project settings
- async updateProjectSettings(project: string, settings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean }): Promise<void> {
+ async updateProjectSettings(
+ project: string,
+ settings: {
+ requireIssueApproval?: boolean;
+ requirePlanCheckNoError?: boolean;
+ allowJustInTimeAccess?: boolean;
+ allowRequestRole?: boolean;
+ // When license is installed, project.allow_self_approval defaults
+ // to false → an issue's creator cannot approve their own issue
+ // (403 "cannot approve because self-approval is not allowed for
+ // this project"). Tests that have a single admin both create and
+ // approve must flip this to true.
+ allowSelfApproval?: boolean;
+ // DATA_CLASSIFICATION config id the project uses. Must reference a config
+ // already defined in the DATA_CLASSIFICATION setting (UpdateProject
+ // validates it exists).
+ dataClassificationConfigId?: string;
+ },
+ ): Promise<void> {
const fields: string[] = [];
- if (settings.requireIssueApproval !== undefined) fields.push("require_issue_approval");
- if (settings.requirePlanCheckNoError !== undefined) fields.push("require_plan_check_no_error");
- await this.request("PATCH", `/v1/${project}?update_mask=${fields.join(",")}`, settings);
+ const body: Record<string, unknown> = { name: project };
+ if (settings.requireIssueApproval !== undefined) {
+ fields.push("require_issue_approval");
+ body.requireIssueApproval = settings.requireIssueApproval;
+ }
+ if (settings.requirePlanCheckNoError !== undefined) {
+ fields.push("require_plan_check_no_error");
+ body.requirePlanCheckNoError = settings.requirePlanCheckNoError;
+ }
+ if (settings.allowJustInTimeAccess !== undefined) {
+ fields.push("allow_just_in_time_access");
+ body.allowJustInTimeAccess = settings.allowJustInTimeAccess;
+ }
+ if (settings.allowRequestRole !== undefined) {
+ fields.push("allow_request_role");
+ body.allowRequestRole = settings.allowRequestRole;
+ }
+ if (settings.allowSelfApproval !== undefined) {
+ fields.push("allow_self_approval");
+ body.allowSelfApproval = settings.allowSelfApproval;
+ }
+ if (settings.dataClassificationConfigId !== undefined) {
+ fields.push("data_classification_config_id");
+ body.dataClassificationConfigId = settings.dataClassificationConfigId;
+ }
+ if (fields.length === 0) {
+ throw new Error("updateProjectSettings: no fields specified");
+ }
+ // Use the camelCase `updateMask` query key (the grpc-gateway form the
+ // other helpers in this file use) with snake_case field paths, so the mask
+ // is bound explicitly rather than relying on a body-derived fallback.
+ await this.request("PATCH", `/v1/${project}?updateMask=${fields.join(",")}`, body);
}
async getProject(project: string): Promise<Record<string, unknown>> {
@@ -267,19 +509,48 @@ export class BytebaseApiClient {
}
// Review config
- async getReviewConfig(name: string): Promise<{ name: string; rules: { type: string; level: string; engine: string; payload: string }[] }> {
- return this.request("GET", `/v1/${name}`);
+ // Upsert (create-or-update) a ReviewConfig. Mirrors the UI's
+ // updateReviewConfig(allowMissing=true) call from
+ // store/modules/sqlReview.ts. Lets tests own their review-config
+ // fixture rather than relying on a demo-seeded one.
+ //
+ // The rule's `payload` field, despite being present on GET responses,
+ // is rejected as "unknown" on PATCH bodies — omit it. Per-rule
+ // configuration that needs a payload would go via a separate update.
+ async upsertReviewConfig(
+ configId: string,
+ title: string,
+ rules: { type: string; level: string; engine: string }[],
+ enabled = true,
+ ): Promise<{ name: string }> {
+ const name = `reviewConfigs/${configId}`;
+ return this.request<{ name: string }>(
+ "PATCH",
+ `/v1/${name}?allowMissing=true&updateMask=title,enabled,rules`,
+ { name, title, enabled, rules },
+ );
}
- async updateReviewConfigRuleLevel(configName: string, ruleType: string, engine: string, newLevel: string): Promise<void> {
- const config = await this.getReviewConfig(configName);
- for (const rule of config.rules) {
- if (rule.type === ruleType && rule.engine === engine) {
- rule.level = newLevel;
- break;
- }
- }
- await this.request("PATCH", `/v1/${configName}?update_mask=rules`, { rules: config.rules });
+ async deleteReviewConfig(name: string): Promise<void> {
+ try { await this.request<unknown>("DELETE", `/v1/${name}`); } catch { /* ignore */ }
+ }
+
+ // Bind a ReviewConfig to a project (or environment / instance) by
+ // upserting a TagPolicy on the resource with the well-known key
+ // `bb.tag.review_config` → `reviewConfigs/<id>`. Mirrors the UI's
+ // upsertReviewConfigTag() helper in store/modules/sqlReview.ts.
+ async upsertReviewConfigTag(resource: string, reviewConfigName: string): Promise<void> {
+ await this.request<unknown>(
+ "PATCH",
+ `/v1/${resource}/policies/tag?allowMissing=true&updateMask=tag_policy`,
+ {
+ name: `${resource}/policies/tag`,
+ type: "TAG",
+ tagPolicy: {
+ tags: { "bb.tag.review_config": reviewConfigName },
+ },
+ },
+ );
}
// Multi-user helper
diff --git a/frontend/tests/e2e/framework/env.ts b/frontend/tests/e2e/framework/env.ts
index fd7fe98fd2..2e004b9f33 100644
--- a/frontend/tests/e2e/framework/env.ts
+++ b/frontend/tests/e2e/framework/env.ts
@@ -8,10 +8,6 @@ export interface TestEnv {
baseURL: string;
adminEmail: string;
adminPassword: string;
- // True iff an enterprise license was installed via BYTEBASE_E2E_LICENSE
- // during globalSetup. Specs that depend on gated features (masking,
- // classification) should `test.skip(!env.hasLicense, ...)` when false.
- hasLicense: boolean;
project: string;
instance: string;
instanceId: string;
diff --git a/frontend/tests/e2e/framework/global-setup.ts b/frontend/tests/e2e/framework/global-setup.ts
index d073738ab2..ae3c138556 100644
--- a/frontend/tests/e2e/framework/global-setup.ts
+++ b/frontend/tests/e2e/framework/global-setup.ts
@@ -3,9 +3,9 @@ import { cleanupOrphans, startServer } from "./mode-start-new-bytebase";
async function globalSetup() {
cleanupOrphans();
- const { baseURL, adminEmail, adminPassword, hasLicense } = await startServer();
+ const { baseURL, adminEmail, adminPassword } = await startServer();
saveTestEnv({
- baseURL, adminEmail, adminPassword, hasLicense,
+ baseURL, adminEmail, adminPassword,
project: "", instance: "", instanceId: "", database: "", databaseId: "",
});
}
diff --git a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts
index a61b5b37c6..4fc54b4e4d 100644
--- a/frontend/tests/e2e/framework/mode-start-new-bytebase.ts
+++ b/frontend/tests/e2e/framework/mode-start-new-bytebase.ts
@@ -69,24 +69,49 @@ function checkPort(port: number): Promise<boolean> {
});
}
-// True when something is actively listening on the port. Inverse of checkPort.
+// True when something is actively listening on the port. The bytebase
+// sample-postgres processes are started with `-h ""` (no TCP listen) +
+// `-k /tmp` (Unix socket directory), so a TCP probe ALWAYS fails even
+// when the postgres is up and answering queries — verified by reading
+// the `ps -ef` output of a running e2e instance. Probe the Unix socket
+// at /tmp/.s.PGSQL.${port} first; fall back to TCP for any environment
+// that does configure TCP (CI containers, future flag changes).
function isPortListening(port: number): Promise<boolean> {
return new Promise((resolve) => {
- const socket = new net.Socket();
- socket.setTimeout(500);
- socket.once("connect", () => {
- socket.destroy();
- resolve(true);
- });
- socket.once("timeout", () => {
- socket.destroy();
- resolve(false);
- });
- socket.once("error", () => {
- socket.destroy();
- resolve(false);
- });
- socket.connect(port, "127.0.0.1");
+ // Try the Unix socket first.
+ const unixPath = `/tmp/.s.PGSQL.${port}`;
+ const unix = new net.Socket();
+ let unixDone = false;
+ unix.setTimeout(500);
+ const done = (value: boolean) => {
+ if (unixDone) return;
+ unixDone = true;
+ unix.destroy();
+ if (value) {
+ resolve(true);
+ return;
+ }
+ // Fallback: TCP probe.
+ const tcp = new net.Socket();
+ tcp.setTimeout(500);
+ tcp.once("connect", () => {
+ tcp.destroy();
+ resolve(true);
+ });
+ tcp.once("timeout", () => {
+ tcp.destroy();
+ resolve(false);
+ });
+ tcp.once("error", () => {
+ tcp.destroy();
+ resolve(false);
+ });
+ tcp.connect(port, "127.0.0.1");
+ };
+ unix.once("connect", () => done(true));
+ unix.once("timeout", () => done(false));
+ unix.once("error", () => done(false));
+ unix.connect(unixPath);
});
}
@@ -133,8 +158,19 @@ export async function startServer(): Promise<{
baseURL: string;
adminEmail: string;
adminPassword: string;
- hasLicense: boolean;
}> {
+ // License is REQUIRED (the suite is enterprise-only). Verify it's present
+ // BEFORE booting the server, so a missing license fails fast and never
+ // orphans a server process.
+ const license = process.env.BYTEBASE_E2E_LICENSE?.trim();
+ if (!license) {
+ throw new Error(
+ "BYTEBASE_E2E_LICENSE is required to run the e2e suite. Set it to a valid " +
+ "enterprise license JWT (signed by Bytebase's license key) and re-run. " +
+ "The suite does not run on the free plan.",
+ );
+ }
+
// Check both CWD-relative and repo-root-relative paths
const candidates = [
process.env.BYTEBASE_BIN,
@@ -203,21 +239,10 @@ export async function startServer(): Promise<{
// Signup sets cookies only; this api-client uses bearer tokens.
await api.login(ADMIN_EMAIL, ADMIN_PASSWORD);
- // Phase 3b: Install an enterprise license if one was provided via
- // BYTEBASE_E2E_LICENSE. Specs that exercise gated features (masking,
- // classification) require this; specs read env.hasLicense and skip
- // themselves when it's false. See frontend/tests/e2e/AGENTS.md for how
- // to obtain a dev license.
- const license = process.env.BYTEBASE_E2E_LICENSE?.trim();
- const hasLicense = Boolean(license);
- if (license) {
- await api.uploadLicense(license);
- } else {
- // eslint-disable-next-line no-console
- console.warn(
- "[e2e bootstrap] BYTEBASE_E2E_LICENSE not set — workspace will run on the free plan. Enterprise-gated specs will skip themselves."
- );
- }
+ // Phase 3b: Install the enterprise license. Its presence was verified at
+ // the top of startServer (before boot); install it now that the API client
+ // is logged in. See frontend/tests/e2e/AGENTS.md for a dev license.
+ await api.uploadLicense(license);
// Phase 3c: Provision the DBA fixture user that plan-detail approval
// specs use as the second approver. The previous demo dump pre-seeded
@@ -270,7 +295,7 @@ export async function startServer(): Promise<{
"Sample Postgres instances did not start listening on PORT+3 / PORT+4."
);
- return { baseURL, adminEmail: ADMIN_EMAIL, adminPassword: ADMIN_PASSWORD, hasLicense };
+ return { baseURL, adminEmail: ADMIN_EMAIL, adminPassword: ADMIN_PASSWORD };
}
export function stopServer(): void {
diff --git a/frontend/tests/e2e/framework/psql.ts b/frontend/tests/e2e/framework/psql.ts
new file mode 100644
index 0000000000..fa8e160429
--- /dev/null
+++ b/frontend/tests/e2e/framework/psql.ts
@@ -0,0 +1,36 @@
+import { execFileSync } from "child_process";
+import type { TestEnv } from "./env";
+import type { BytebaseApiClient } from "./api-client";
+
+// Resolve the Postgres port for the database's instance by reading the data
+// source from the API. Avoids hardcoding PORT+3 / PORT+4 offsets which would
+// break if discovery picks the "test" sample instance instead of "prod".
+export async function getInstancePgPort(
+ env: TestEnv & { api: BytebaseApiClient },
+): Promise<string> {
+ const instance = await env.api.getInstance(env.instance);
+ const port = instance.dataSources?.[0]?.port;
+ if (!port) {
+ throw new Error(`Instance ${env.instance} has no data source port`);
+ }
+ return port;
+}
+
+// Execute SQL via psql over the Unix socket on the sample Postgres instance.
+// Used for DDL/DML setup and teardown — Bytebase's query API is read-only.
+// Callers that interpolate non-constant values MUST validate them first
+// (see masking-exemption's assertSafeSqlIdentifier).
+export function execSql(dbName: string, port: string, sql: string): void {
+ execFileSync(
+ "psql",
+ [
+ "-h", "/tmp",
+ "-p", port,
+ "-U", "bbsample",
+ "-d", dbName,
+ "-v", "ON_ERROR_STOP=1",
+ "-c", sql,
+ ],
+ { stdio: "pipe" },
+ );
+}
diff --git a/frontend/tests/e2e/framework/seed-test-data.ts b/frontend/tests/e2e/framework/seed-test-data.ts
new file mode 100644
index 0000000000..96622b96f6
--- /dev/null
+++ b/frontend/tests/e2e/framework/seed-test-data.ts
@@ -0,0 +1,86 @@
+import { BytebaseApiClient } from "./api-client";
+
+// External URL we set on the workspace_profile setting so the
+// "Bytebase has not configured --external-url" banner stops rendering.
+// The frontend's BannersWrapper.tsx checks `serverInfo.externalUrl`
+// truthiness; any non-empty URL silences the banner.
+const TEST_EXTERNAL_URL = "https://e2e.bytebase.test";
+
+/**
+ * Provisions WORKSPACE-LEVEL baseline data on top of `api.setupSample()`.
+ * Called once per disposable server boot from setup-project.ts.
+ *
+ * Scope is intentionally narrow: only changes that EVERY spec wants. Any
+ * per-spec test data (extra projects, feature flag flips, masking config
+ * etc.) lives in the spec's own beforeAll so one spec's setup can't
+ * shift another spec's expectations.
+ *
+ * Goal:
+ * - Silence the external-URL banner (so its wrench-icon "Configure now"
+ * button doesn't shadow the SQL editor's admin-mode wrench locator).
+ *
+ * Specifically does NOT:
+ * - Create extra projects (would change the SQL editor's default
+ * landing project; see the worksheet specs that gotoHome() and
+ * expect to land on `project-sample`).
+ * - Flip per-project feature flags (allowRequestRole,
+ * allowJustInTimeAccess) — those are SUT for individual specs.
+ */
+export async function seedTestData(api: BytebaseApiClient): Promise<void> {
+ try {
+ await api.setWorkspaceExternalUrl(TEST_EXTERNAL_URL);
+ } catch (err) {
+ // The setting may not exist yet on a fresh server; updateMask
+ // semantics + allowMissing on the gateway should make PATCH a
+ // create-or-update. Surface the error so a test infra change
+ // doesn't silently drop the banner-suppression.
+ throw new Error(
+ `seedTestData: failed to set external URL — ${err instanceof Error ? err.message : err}`,
+ );
+ }
+
+ // Enterprise license auto-activates a built-in workspace approval
+ // "Fallback Rule" (Moderate · Requires project owner approval when
+ // no other rules match) that fires for every CHANGE_DATABASE plan.
+ // Without it, requireIssueApproval=false projects auto-create the
+ // rollout — that's the baseline tests assume. Free plan has no rule
+ // at all, so clearing here is a no-op there but makes the licensed
+ // baseline match the free-plan one. Tests that DO want approval set
+ // their own rule in beforeAll and restore on afterAll.
+ try {
+ await api.upsertSetting(
+ "WORKSPACE_APPROVAL",
+ { workspaceApproval: { rules: [] } },
+ "value.workspace_approval",
+ );
+ } catch {
+ // Free plan: setting won't accept rules without license; rules
+ // would already be empty on that path. Swallow silently.
+ }
+}
+
+// Re-exported identifiers used by tests that need their own additional
+// project. Created on-demand by `ensureSecondaryProject()` — kept here
+// so specs share a single canonical name/title.
+export const SECONDARY_PROJECT_ID = "e2e-secondary";
+export const SECONDARY_PROJECT_TITLE = "E2E Secondary";
+
+/**
+ * Creates the secondary project on demand. Idempotent (tolerates "already
+ * exists" on rerun). Use from spec beforeAll when the test depends on a
+ * 2nd project being present (e.g. the project-switcher CUJ).
+ *
+ * Why this is on-demand rather than in seedTestData: creating a 2nd
+ * project at global setup time alters the SQL editor's default landing
+ * project on /sql-editor (no URL params), which silently breaks any
+ * spec that uses gotoHome() and expects `project-sample`. Per-spec
+ * creation avoids that side effect.
+ */
+export async function ensureSecondaryProject(api: BytebaseApiClient): Promise<void> {
+ try {
+ await api.createProject(SECONDARY_PROJECT_ID, SECONDARY_PROJECT_TITLE);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (!msg.includes("(409)") && !msg.includes("already exists")) throw err;
+ }
+}
diff --git a/frontend/tests/e2e/framework/setup-project.ts b/frontend/tests/e2e/framework/setup-project.ts
index ec24f5f92a..f59657ffa6 100644
--- a/frontend/tests/e2e/framework/setup-project.ts
+++ b/frontend/tests/e2e/framework/setup-project.ts
@@ -2,6 +2,7 @@ import { test as setup, expect } from "@playwright/test";
import * as fs from "fs";
import * as path from "path";
import { loadTestEnv, saveTestEnv } from "./env";
+import { seedTestData } from "./seed-test-data";
const AUTH_FILE = path.join(__dirname, "../../../.auth/state.json");
@@ -9,6 +10,14 @@ setup("authenticate and discover", async ({ page }) => {
const env = loadTestEnv();
await env.api.login(env.adminEmail, env.adminPassword);
+ // Provision baseline data on top of the new bootstrap's setupSample:
+ // silence the external-URL banner so its wrench-icon button doesn't
+ // shadow the editor's admin wrench locator, and create a secondary
+ // project so the project-switcher CUJ has an alternative target.
+ // The previous demo dump pre-seeded these things; the post-demo
+ // bootstrap leaves them off, so we own the seed here.
+ await seedTestData(env.api);
+
// Browser login for auth cookies
await page.goto(`${env.baseURL}/auth/signin`);
if (page.url().includes("/auth")) {
@@ -63,7 +72,25 @@ setup("authenticate and discover", async ({ page }) => {
saveTestEnv({ ...env, project, instance, instanceId, database, databaseId });
- // Save browser auth state
+ // Pin the SQL editor's "last viewed project" by visiting the sample
+ // project once. Without this pin, gotoHome() in later specs lands on
+ // whatever `SQLEditorRouteShell.fallbackToFirstProject` returns —
+ // `head(projects)` from a list sorted by created_time DESC. Any spec
+ // that creates an additional project (e.g. connection.spec.ts's
+ // project-switcher fixture) would silently shift the default project
+ // for every later spec, breaking gotoHome-based worksheet/sidebar
+ // tests that assume `project-sample`. Visiting the URL exercises the
+ // real `setProject()` path which writes to localStorage in whatever
+ // shape `useLocalStorage` expects — safer than hand-rolling the JSON
+ // format.
+ const projectId = project.split("/").pop()!;
+ await page.goto(
+ `${env.baseURL}/sql-editor/projects/${projectId}/instances/${instanceId}/databases/${databaseId}`,
+ );
+ await page.waitForLoadState("networkidle").catch(() => {});
+ await page.waitForTimeout(1500);
+
+ // Save browser auth state (now includes the pinned last-project key)
const authDir = path.dirname(AUTH_FILE);
if (!fs.existsSync(authDir)) fs.mkdirSync(authDir, { recursive: true });
await page.context().storageState({ path: AUTH_FILE });
diff --git a/frontend/tests/e2e/framework/sign-in.ts b/frontend/tests/e2e/framework/sign-in.ts
new file mode 100644
index 0000000000..2d214da4a1
--- /dev/null
+++ b/frontend/tests/e2e/framework/sign-in.ts
@@ -0,0 +1,50 @@
+import type { Browser } from "@playwright/test";
+
+// Sign a user into a fresh BrowserContext and persist its storageState to
+// `storagePath`.
+//
+// Why POST /v1/auth/login rather than filling the sign-in form: the React
+// auth form's inputs aren't reliably reachable via role/name selectors, so
+// a form-driven login hangs. `web: true` is the switch that tells
+// finalizeLogin() to return the JWT as an HTTP-only cookie instead of only
+// in the response body — without it the response is a well-formed 200 but
+// the context has no cookies, so the UI stays logged out and any subsequent
+// page.goto() bounces to /auth (see backend/api/v1/auth_service.go).
+//
+// Also pre-warms "/" to set the localStorage flag that suppresses the
+// "New version" modal before capturing storageState.
+export async function signInBrowserAs(
+ browser: Browser,
+ baseURL: string,
+ email: string,
+ password: string,
+ storagePath: string,
+): Promise<void> {
+ const context = await browser.newContext();
+ try {
+ const resp = await context.request.post(`${baseURL}/v1/auth/login`, {
+ data: { email, password, web: true },
+ headers: { "Content-Type": "application/json" },
+ });
+ if (!resp.ok()) {
+ throw new Error(
+ `login failed for ${email}: ${resp.status()} ${await resp.text()}`,
+ );
+ }
+ const page = await context.newPage();
+ await page.goto(`${baseURL}/`);
+ await page.evaluate(() => {
+ localStorage.setItem(
+ "bb.release",
+ JSON.stringify({
+ ignoreRemindModalTillNextRelease: true,
+ nextCheckTs: Date.now() + 86_400_000,
+ }),
+ );
+ });
+ await context.storageState({ path: storagePath });
+ await page.close();
+ } finally {
+ await context.close();
+ }
+}
diff --git a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts
index 503d4fa876..630cdb3ddb 100644
--- a/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts
+++ b/frontend/tests/e2e/masking-exemption/masking-exemption.spec.ts
@@ -1,7 +1,7 @@
-import { execFileSync } from "child_process";
import { test, expect, type Page, type BrowserContext } from "@playwright/test";
import { loadTestEnv, type TestEnv } from "../framework/env";
import { BytebaseApiClient } from "../framework/api-client";
+import { getInstancePgPort, execSql } from "../framework/psql";
import { MaskingExemptionPage, GrantExemptionPage, SqlEditorPage } from "./masking-exemption.page";
// Give all tests generous timeouts (Mode B's disposable server can be slow)
@@ -49,6 +49,14 @@ const ROW_PK = 1;
const CLASSIFICATION_VALUE = "ClassValueABCDE";
const SEMANTIC_TYPE_VALUE = "SemValueABCDE";
const CLASSIFICATION_LEVEL = "1-2"; // matches demo classification rules
+// Built-in semantic-type ID used in the previous demo dump. The new
+// bootstrap doesn't seed it, so we register it ourselves via the
+// SEMANTIC_TYPES workspace setting before applying it via catalog.
+const SEMANTIC_TYPE_ID = "bb.default-partial";
+// Classification-masking fixtures (the new bootstrap doesn't pre-seed them).
+const CLASSIFICATION_CONFIG_ID = "e2e-classification-config";
+const CLASSIFICATION_LEVEL_NUM = 2; // numeric level CLASSIFICATION_LEVEL ("1-2") maps to
+const CLASSIFICATION_RULE_ID = "e2e00000-0000-4000-8000-000000000001"; // UUID for the workspace masking rule
// Validate SQL identifiers/literal values. Only permits characters safe to
// inline into a SQL string without escaping: letters, digits, underscores.
@@ -66,35 +74,121 @@ for (const [name, value] of Object.entries({
assertSafeSqlIdentifier(value, name);
}
-// Get the Postgres port for the database's instance by reading the data source
-// from the API. Avoids hardcoding offsets (PORT+3 vs PORT+4) which would break
-// if discovery picks the "test" sample instance instead of "prod".
-async function getInstancePgPort(env: TestEnv & { api: BytebaseApiClient }): Promise<string> {
- const instance = await env.api.getInstance(env.instance);
- const port = instance.dataSources?.[0]?.port;
- if (!port) {
- throw new Error(`Instance ${env.instance} has no data source port`);
- }
- return port;
+// Register a semantic type via the SEMANTIC_TYPES workspace setting so
+// the catalog update below can reference it. Without this, applying a
+// column with semanticType="bb.default-partial" fails with "semantic
+// type id not found" — the previous demo dump pre-seeded the type but
+// the new bootstrap doesn't.
+async function ensureSemanticType(env: TestEnv & { api: BytebaseApiClient }): Promise<void> {
+ await env.api.upsertSetting(
+ "SEMANTIC_TYPES",
+ {
+ semanticType: {
+ types: [
+ {
+ id: SEMANTIC_TYPE_ID,
+ title: "E2E Partial Mask",
+ description: "Used by masking-exemption e2e tests",
+ algorithm: {
+ rangeMask: {
+ slices: [{ start: 0, end: 3, substitution: "***" }],
+ },
+ },
+ },
+ ],
+ },
+ },
+ "value.semantic_type",
+ );
+}
+
+// Seed the workspace fixtures the classification -> masking path needs (the
+// post-#20393 bootstrap no longer pre-seeds them, unlike the old demo dump):
+// 1. a DATA_CLASSIFICATION config mapping classification id CLASSIFICATION_LEVEL
+// ("1-2") to a numeric level,
+// 2. the test project pointing at that config (projects carry a
+// dataClassificationConfigId; the masking evaluator resolves the config
+// from it, with no fallback), and
+// 3. a workspace MASKING_RULE whose CEL `classification_level == N` applies
+// the semantic type to columns at that level.
+async function ensureClassificationFixtures(
+ env: TestEnv & { api: BytebaseApiClient },
+): Promise<void> {
+ await env.api.upsertSetting(
+ "DATA_CLASSIFICATION",
+ {
+ dataClassification: {
+ configs: [
+ {
+ id: CLASSIFICATION_CONFIG_ID,
+ title: "E2E Classification",
+ levels: [
+ { title: "Level 1", level: 1 },
+ { title: "Level 2", level: 2 },
+ ],
+ classification: {
+ [CLASSIFICATION_LEVEL]: {
+ id: CLASSIFICATION_LEVEL,
+ title: "E2E Internal",
+ level: CLASSIFICATION_LEVEL_NUM,
+ },
+ },
+ },
+ ],
+ },
+ },
+ "value.data_classification",
+ );
+ // Link the project to the config (it must exist first — UpdateProject validates it).
+ await env.api.updateProjectSettings(env.project, {
+ dataClassificationConfigId: CLASSIFICATION_CONFIG_ID,
+ });
+ // Workspace masking rule: any column at the level gets the semantic type.
+ const { workspace } = await env.api.getActuatorInfo();
+ await env.api.upsertPolicy(workspace, "masking_rule", {
+ type: "MASKING_RULE",
+ maskingRulePolicy: {
+ rules: [
+ {
+ id: CLASSIFICATION_RULE_ID,
+ condition: {
+ expression: `resource.classification_level == ${CLASSIFICATION_LEVEL_NUM}`,
+ title: "e2e classification masking",
+ },
+ semanticType: SEMANTIC_TYPE_ID,
+ },
+ ],
+ },
+ });
}
-// Execute SQL via psql over Unix socket on the sample Postgres instance.
-// Used for DDL/DML setup and teardown — Bytebase's query API is read-only.
-function execSql(dbName: string, port: string, sql: string): void {
- execFileSync("psql", [
- "-h", "/tmp",
- "-p", port,
- "-U", "bbsample",
- "-d", dbName,
- "-v", "ON_ERROR_STOP=1",
- "-c", sql,
- ], { stdio: "pipe" });
+// Remove the workspace masking rule so it can't affect later specs. (The
+// project's config link and the DATA_CLASSIFICATION setting are harmless once
+// the rule is gone — no column outside this spec carries the classification —
+// and the disposable server is torn down anyway.)
+async function clearClassificationFixtures(
+ env: TestEnv & { api: BytebaseApiClient },
+): Promise<void> {
+ try {
+ const { workspace } = await env.api.getActuatorInfo();
+ await env.api.upsertPolicy(workspace, "masking_rule", {
+ type: "MASKING_RULE",
+ maskingRulePolicy: { rules: [] },
+ });
+ } catch (err) {
+ console.warn(
+ `clearClassificationFixtures: ${err instanceof Error ? err.message : err}`,
+ );
+ }
}
async function createMaskingTestData(env: TestEnv & { api: BytebaseApiClient }): Promise<MaskingTestData> {
const dbName = env.databaseId;
const port = await getInstancePgPort(env);
+ await ensureSemanticType(env);
+ await ensureClassificationFixtures(env);
+
// Drop anything leftover from a previous run, then create fresh schema/table/row.
// All interpolated identifiers are validated constants (see assertSafeSqlIdentifier above).
execSql(dbName, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);
@@ -122,7 +216,7 @@ async function createMaskingTestData(env: TestEnv & { api: BytebaseApiClient }):
columns: {
columns: [
{ name: CLASSIFICATION_COLUMN, classification: CLASSIFICATION_LEVEL },
- { name: SEMANTIC_TYPE_COLUMN, semanticType: "bb.default-partial" },
+ { name: SEMANTIC_TYPE_COLUMN, semanticType: SEMANTIC_TYPE_ID },
],
},
}],
@@ -186,12 +280,7 @@ async function revokeAllExemptions(): Promise<void> {
test.beforeAll(async ({ browser }) => {
env = loadTestEnv();
- // Masking and classification are enterprise-gated; without a license the
- // policies cannot be created, so skip the entire suite rather than failing.
- test.skip(
- !env.hasLicense,
- "BYTEBASE_E2E_LICENSE not set — masking specs require an enterprise license"
- );
+ // Masking and classification are enterprise-gated; the license is installed at bootstrap (required to run this suite).
projectId = env.project.split("/").pop()!;
await env.api.login(env.adminEmail, env.adminPassword);
@@ -209,6 +298,7 @@ test.afterAll(async () => {
await revokeAllExemptions().catch((err) => {
console.warn(`afterAll revokeAllExemptions: ${err instanceof Error ? err.message : err}`);
});
+ await clearClassificationFixtures(env);
await dropMaskingTestData(env);
});
@@ -437,6 +527,13 @@ test.describe("E2E Masking Verification", () => {
expect(await sqlEditor.resultContainsText(target.knownUnmaskedValue)).toBe(false);
};
+ // Classification-based masking: col_classification carries classification id
+ // "1-2" (set in the catalog above); ensureClassificationFixtures seeds the
+ // DATA_CLASSIFICATION config that maps "1-2" -> level 2, links the project to
+ // that config, and installs a workspace MASKING_RULE
+ // (`classification_level == 2` -> the semantic type). So this column masks
+ // via the classification -> rule path, distinct from col_semantic's direct
+ // semantic_type.
test("classification-based masking: cycle via UI", async () => {
await runMaskingCycle(maskingData.classificationColumn, "e2e classification masking test");
});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts
deleted file mode 100644
index ff81077ba9..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-approval-blocker.spec.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-let issueName: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let planPage: PlanDetailPage;
-let shouldSkip = false;
-let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- // Capture both settings before mutating.
- const project = await env.api.getProject(env.project);
- originalSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
-
- // Require approval so the approval flow is generated; disable plan-check gate
- // so the SQL check result doesn't block us independently.
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: true,
- requirePlanCheckNoError: false,
- });
-
- // Unique column name avoids collisions across runs.
- const columnName = `e2e_approval_${Date.now()}`;
- const sheetName = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
- );
-
- const specId = `spec-${Date.now()}`;
- const plan = await env.api.createPlan(
- env.project,
- `E2E Approval Blocker Test ${Date.now()}`,
- [{ id: specId, targets: [env.database], sheet: sheetName }]
- );
- planId = plan.name.split("/").pop()!;
-
- const issue = await env.api.createIssue(
- env.project,
- "E2E Approval Blocker",
- plan.name
- );
- issueName = issue.name;
-
- // Run plan checks — this triggers SQL classification which drives the
- // approval flow generation. Without this call the approvalStatus may
- // stay "SKIPPED" (no matching rule) rather than becoming "PENDING".
- await env.api.runPlanChecks(plan.name);
-
- // Wait for the approval flow to reach PENDING. If it instead reaches
- // SKIPPED (no approval rule matched), the suite is skipped gracefully
- // so it doesn't produce false failures in environments without the
- // required policy.
- const deadline = Date.now() + 30_000;
- let lastStatus = "";
- while (Date.now() < deadline) {
- const freshIssue = await env.api.getIssue(issueName);
- lastStatus = freshIssue.approvalStatus;
- if (lastStatus === "PENDING" || lastStatus === "SKIPPED" || lastStatus === "APPROVED") break;
- await new Promise((resolve) => setTimeout(resolve, 1000));
- }
-
- if (lastStatus === "SKIPPED" || lastStatus === "APPROVED") {
- // No approval rule matched, or auto-approved — skip this blocker suite.
- shouldSkip = true;
- return;
- }
-
- if (lastStatus !== "PENDING") {
- throw new Error(
- `Timed out waiting for approvalStatus "PENDING" on issue "${issueName}"; last status: "${lastStatus}"`
- );
- }
-
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-});
-
-test.afterAll(async () => {
- await sharedContext?.close();
- // Restore both settings to the values captured before the test mutated them.
- await env.api
- .updateProjectSettings(env.project, originalSettings)
- .catch((err: unknown) => {
- console.warn(
- `afterAll updateProjectSettings: ${err instanceof Error ? err.message : err}`
- );
- });
-});
-
-test.describe("Plan Detail: Approval Blocker", () => {
- test.describe.configure({ mode: "serial" });
-
- test("deploy section shows approval pending when required", async () => {
- test.skip(shouldSkip, "No approval rule matched — environment lacks required policy");
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
-
- // The deploy section should surface the approval gate message.
- const deployArea = page.getByText("Deploy").locator("..");
- await expect(
- deployArea.getByText(/Approval flow must be done/i)
- ).toBeVisible({ timeout: 15_000 });
-
- // A "Pending" indicator should also be visible somewhere in the deploy area.
- await expect(deployArea.getByText(/Pending/i).first()).toBeVisible();
- });
-
- test("no manual create rollout button when approval is pending and required", async () => {
- test.skip(shouldSkip, "No approval rule matched");
- // The button must NOT exist (or must be hidden) when approval is blocking.
- // Use a short timeout — if it's present the test fails fast.
- await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
- timeout: 3_000,
- });
- });
-
- test("sidebar shows Under review", async () => {
- test.skip(shouldSkip, "No approval rule matched");
- await expect(
- page.getByRole("complementary").getByText(/Under review/i)
- ).toBeVisible();
- });
-
- test("after approving both steps, deploy section updates", async () => {
- test.skip(shouldSkip, "No approval rule matched");
- // First approval: admin (Project Owner / first approver in the flow).
- await env.api.approveIssue(issueName);
-
- // Second approval: DBA role.
- const dbaApi = await BytebaseApiClient.asUser(
- env.baseURL,
- "12345678"
- );
- await dbaApi.approveIssue(issueName);
-
- // Reload so the browser picks up the updated approval state.
- await page.reload();
- await page.waitForLoadState("networkidle");
-
- // After both approvals, the sidebar should reflect "Approved" or the page
- // may show a rollout (auto-created if checks also passed). Either way,
- // the approval is no longer "Pending".
- await expect(
- page.getByText(/Approved|Approval is complete/i).first()
- ).toBeVisible({ timeout: 15_000 });
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts
deleted file mode 100644
index 2112a7823b..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-byt9160-check-consistency.spec.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let planPage: PlanDetailPage;
-let shouldSkip = false;
-let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-
-// Counts captured by test 1, consumed by test 2
-let spec1SuccessCount = 0;
-let spec2SuccessCount = 0;
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- // Capture and set permissive settings
- const project = await env.api.getProject(env.project);
- originalSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: false,
- requirePlanCheckNoError: false,
- });
-
- const ts = Date.now();
-
- // Create two sheets with distinct SQL
- const sheetA = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9160a_${ts} TEXT;`
- );
- const sheetB = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9160b_${ts} INTEGER NOT NULL DEFAULT 0;`
- );
-
- // Discover a second database on a different instance
- const { instances } = await env.api.listInstances();
- // env.instance is like "instances/test-sample-instance" — extract its name
- const primaryInstanceName = env.instance; // e.g. "instances/prod-sample-instance"
-
- let secondDatabase: string | null = null;
-
- for (const inst of instances) {
- if (inst.name === primaryInstanceName) continue;
- if (inst.name.includes("bytebase-meta")) continue;
- if (inst.engine !== "POSTGRES") continue;
- try {
- const { databases } = await env.api.listDatabases(inst.name);
- // Only pick databases that belong to our project
- const candidate = databases.find((db) => db.project === env.project);
- if (candidate) {
- secondDatabase = candidate.name;
- break;
- }
- } catch {
- // Instance unreachable — skip
- }
- }
-
- if (!secondDatabase) {
- // No second instance/database available — flag to skip all tests
- shouldSkip = true;
- return;
- }
-
- // Create plan with 2 specs:
- // Spec A — single target (env.database), sheet A
- // Spec B — two targets (env.database + secondDatabase, overlapping), sheet B
- const plan = await env.api.createPlan(
- env.project,
- `E2E BYT-9160 Check Consistency ${ts}`,
- [
- { id: `spec-a-${ts}`, targets: [env.database], sheet: sheetA },
- {
- id: `spec-b-${ts}`,
- targets: [env.database, secondDatabase],
- sheet: sheetB,
- },
- ]
- );
- planId = plan.name.split("/").pop()!;
-
- // Create issue so the plan gets a full lifecycle context
- await env.api.createIssue(env.project, "E2E BYT-9160 Check Consistency", plan.name);
-
- // Run plan checks
- await env.api.runPlanChecks(plan.name);
-
- // Poll until plan checks are DONE (max 60 s).
- // getPlanCheckRun returns 404 before the first run completes — catch and retry.
- let checksDone = false;
- const deadline = Date.now() + 60_000;
- while (Date.now() < deadline) {
- try {
- const checkRun = await env.api.getPlanCheckRun(plan.name);
- if (checkRun.status === "DONE") { checksDone = true; break; }
- } catch {
- // Check run not created yet — retry
- }
- await new Promise((r) => setTimeout(r, 2000));
- }
- if (!checksDone) {
- throw new Error(`Plan checks did not reach DONE within 60s for ${plan.name}`);
- }
-
- // Open the shared browser context
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-});
-
-test.afterAll(async () => {
- await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
- await sharedContext?.close();
-});
-
-test.describe("Plan Detail: Check Count Consistency (BYT-9160)", () => {
- test.describe.configure({ mode: "serial" });
-
- test("spec #2 has more check results than spec #1", async () => {
- test.skip(shouldSkip, "No second database available for multi-spec plan");
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
-
- // Helper: read the success count digit next to "Success" text in the inline Checks h3 area.
- // Uses evaluate to find the count reliably regardless of nesting.
- const readInlineSuccessCount = async (): Promise<number> => {
- return page.evaluate(() => {
- // Find all elements with text "Success" that are near an h3 "Checks"
- const all = Array.from(document.querySelectorAll("*"));
- for (const el of all) {
- if (el.children.length > 0) continue; // leaf nodes only
- if (el.textContent?.trim() !== "Success") continue;
- // Walk siblings and parent siblings to find a digit
- const parent = el.parentElement;
- if (!parent) continue;
- const siblings = Array.from(parent.querySelectorAll("*"));
- for (const s of siblings) {
- if (s === el) continue;
- const t = s.textContent?.trim();
- if (t && /^\d+$/.test(t)) {
- // Check that this is near an h3 "Checks" (within 5 parents)
- let node: Element | null = parent;
- for (let i = 0; i < 5 && node; i++) {
- if (node.querySelector("h3")?.textContent?.includes("Checks")) {
- return parseInt(t, 10);
- }
- node = node.parentElement;
- }
- }
- }
- }
- return 0;
- });
- };
-
- // Spec #1 is already selected
- await expect(page.getByText("Success").first()).toBeVisible({ timeout: 15_000 });
- spec1SuccessCount = await readInlineSuccessCount();
- expect(spec1SuccessCount).toBeGreaterThan(0);
-
- // Click spec #2 tab. Use exact match to avoid matching "Issue #..." text
- // (issue numbers in demo are 100+, so "#2" is unambiguous).
- await page.getByText("#2", { exact: true }).first().click();
- await page.waitForLoadState("networkidle");
- await expect(page.getByText("Success").first()).toBeVisible({ timeout: 10_000 });
- spec2SuccessCount = await readInlineSuccessCount();
-
- // Spec #2 targets two databases, so it must produce more check results
- expect(spec2SuccessCount).toBeGreaterThan(0);
- expect(spec2SuccessCount).toBeGreaterThan(spec1SuccessCount);
- });
-
- // BYT-9160: sidebar always shows the last spec's counts regardless of which
- // spec tab is selected. Mark fixme until the bug is resolved.
- test.fixme("sidebar check counts match selected spec #1 (BYT-9160)", async () => {
- // Select spec #1
- await planPage.specTab(1).click();
- await expect(planPage.inlineCheckCount("Success")).toBeVisible({ timeout: 10_000 });
-
- const sidebarRaw = await planPage.sidebarCheckCount("Success").textContent();
- const inlineRaw = await planPage.inlineCheckCount("Success").textContent();
-
- const sidebarCount = parseInt(sidebarRaw ?? "0", 10);
- const inlineCount = parseInt(inlineRaw ?? "0", 10);
-
- // Sidebar should reflect spec #1 — not spec #2's larger count.
- // This assertion FAILS because sidebar shows spec #2's count (the bug).
- expect(sidebarCount).toBe(inlineCount);
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts
deleted file mode 100644
index bce0328efc..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-byt9161-section-preservation.spec.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let planPage: PlanDetailPage;
-let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- const project = await env.api.getProject(env.project);
- originalSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: false,
- requirePlanCheckNoError: false,
- });
-
- const ts = Date.now();
-
- const sheet = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_9161_${ts} TEXT;`
- );
-
- const plan = await env.api.createPlan(
- env.project,
- `E2E BYT-9161 Section Preservation ${ts}`,
- [{ id: `spec-${ts}`, targets: [env.database], sheet }]
- );
- planId = plan.name.split("/").pop()!;
-
- await env.api.createIssue(env.project, `E2E BYT-9161 Section Preservation ${ts}`, plan.name);
-
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
- await planPage.createRolloutWithBypass();
- await page.waitForLoadState("networkidle");
-});
-
-test.afterAll(async () => {
- await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
- await sharedContext?.close();
-});
-
-test.describe("Plan Detail: Section Expansion Preservation (BYT-9161)", () => {
- test.describe.configure({ mode: "serial" });
-
- test("sections expanded after rollout creation", async () => {
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
- });
-
- test("clicking View details preserves section state", async () => {
- // Open the task detail panel via the "View details" link in the Deploy section
- const viewDetailsLink = page
- .getByRole("link", { name: "View details" })
- .first();
- if (await viewDetailsLink.isVisible({ timeout: 5_000 }).catch(() => false)) {
- await viewDetailsLink.click();
- await page.waitForLoadState("networkidle");
- } else {
- // Fallback: look for any clickable detail trigger in the deploy area
- const detailButton = page
- .getByText("View details")
- .first();
- if (await detailButton.isVisible({ timeout: 3_000 }).catch(() => false)) {
- await detailButton.click();
- await page.waitForLoadState("networkidle");
- }
- }
-
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-
- test("closing detail panel preserves section state", async () => {
- // Close the detail panel using Escape first; fall back to a close button
- const closeButton = page
- .getByRole("button", { name: "Close" })
- .or(page.locator("[aria-label='Close']"))
- .first();
-
- if (await closeButton.isVisible({ timeout: 2_000 }).catch(() => false)) {
- await closeButton.click();
- } else {
- await page.keyboard.press("Escape");
- }
- // Wait for the drawer to fully close. If the drawer class doesn't match,
- // reload the page to guarantee a clean state rather than silently proceeding.
- const drawerHidden = await expect(page.locator(".n-drawer-container"))
- .toBeHidden({ timeout: 5_000 })
- .then(() => true)
- .catch(() => false);
- if (!drawerHidden) {
- // Drawer didn't close — reload to ensure section state assertions are meaningful
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
- }
-
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-
- test("collapsing one section doesn't affect others", async () => {
- // Reload page to guarantee clean state (no lingering drawers from previous test)
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
- // Collapse the Changes section
- const changesToggle = planPage.getSectionToggle("Changes");
- if (await changesToggle.isVisible({ timeout: 3_000 }).catch(() => false)) {
- const text = await changesToggle.textContent();
- if (text?.includes("Hide")) {
- await changesToggle.click();
- await expect(changesToggle).toHaveText(/Show details/, { timeout: 5_000 });
- }
- }
-
- expect(await planPage.isSectionExpanded("Changes")).toBe(false);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
-
- // Re-expand Changes so subsequent tests start from a consistent state
- const changesToggleAfter = planPage.getSectionToggle("Changes");
- if (await changesToggleAfter.isVisible({ timeout: 3_000 }).catch(() => false)) {
- const text = await changesToggleAfter.textContent();
- if (text?.includes("Show")) {
- await changesToggleAfter.click();
- await expect(changesToggleAfter).toHaveText(/Hide details/, { timeout: 5_000 });
- }
- }
- });
-
- test("navigation away and back preserves section state", async () => {
- // Navigate to the issues list
- await page.goto(`${env.baseURL}/projects/${projectId}/issues`);
- await page.waitForLoadState("networkidle");
-
- // Navigate back to the plan
- await planPage.goto(projectId, planId);
- await page.waitForLoadState("networkidle");
-
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts
deleted file mode 100644
index 9139fc86c4..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-checks-blocker.spec.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-let issueName: string;
-let planURL: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let shouldSkip = false;
-let originalRuleLevel = "WARNING";
-let originalProjectSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-let planPage: PlanDetailPage;
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- // Capture original project settings before mutating.
- const project = await env.api.getProject(env.project);
- originalProjectSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
-
- // Enable approval + plan-check gate
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: true,
- requirePlanCheckNoError: true,
- });
-
- // Capture original rule level before mutating, so afterAll restores the exact value.
- const config = await env.api.getReviewConfig("reviewConfigs/sql-review-sample-policy");
- const rule = config.rules.find((r) => r.type === "COLUMN_NO_NULL" && r.engine === "POSTGRES");
- originalRuleLevel = rule?.level ?? "WARNING";
-
- // Upgrade COLUMN_NO_NULL to ERROR so checks will fail
- await env.api.updateReviewConfigRuleLevel(
- "reviewConfigs/sql-review-sample-policy",
- "COLUMN_NO_NULL",
- "POSTGRES",
- "ERROR"
- );
-
- // Create sheet — nullable TEXT column triggers COLUMN_NO_NULL ERROR
- const columnName = `e2e_checks_${Date.now()}`;
- const sheetName = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
- );
-
- // Create the plan
- const specId = `spec-${Date.now()}`;
- const plan = await env.api.createPlan(env.project, `E2E Checks Blocker Test ${Date.now()}`, [
- { id: specId, targets: [env.database], sheet: sheetName },
- ]);
- planId = plan.name.split("/").pop()!;
- planURL = `${env.baseURL}/projects/${projectId}/plans/${planId}`;
-
- // Create an issue backed by the plan
- const issue = await env.api.createIssue(env.project, "E2E Checks Blocker", plan.name);
- issueName = issue.name;
-
- // Run plan checks to trigger the SQL review errors
- await env.api.runPlanChecks(plan.name);
-
- // Poll until approval is no longer CHECKING
- const deadline = Date.now() + 60_000;
- let approvalStatus = "CHECKING";
- while (Date.now() < deadline) {
- const issueData = await env.api.getIssue(issueName);
- approvalStatus = issueData.approvalStatus;
- if (approvalStatus !== "CHECKING") break;
- await new Promise((r) => setTimeout(r, 1000));
- }
-
- // If PENDING, approve both steps (Project Owner + DBA)
- if (approvalStatus === "PENDING") {
- await env.api.approveIssue(issueName);
- const dbaApi = await BytebaseApiClient.asUser(env.baseURL, "[email protected]", "12345678");
- await dbaApi.approveIssue(issueName);
- }
-
- // Verify approval is APPROVED. If the environment has no matching approval
- // rule, status may be SKIPPED — skip the suite rather than false-fail.
- const finalIssue = await env.api.getIssue(issueName);
- if (finalIssue.approvalStatus === "SKIPPED") {
- shouldSkip = true;
- return;
- }
- if (finalIssue.approvalStatus !== "APPROVED") {
- throw new Error(
- `Expected approvalStatus "APPROVED" but got "${finalIssue.approvalStatus}" on issue "${issueName}"`
- );
- }
-
- // Open the shared browser context
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-});
-
-test.afterAll(async () => {
- // Restore project settings to the values captured before the test mutated them.
- await env.api.updateProjectSettings(env.project, originalProjectSettings);
-
- // Restore COLUMN_NO_NULL rule to the level captured before the test mutated it.
- await env.api.updateReviewConfigRuleLevel(
- "reviewConfigs/sql-review-sample-policy",
- "COLUMN_NO_NULL",
- "POSTGRES",
- originalRuleLevel
- );
-
- await sharedContext?.close();
-});
-
-test.describe("Plan Detail: Checks Blocker (BYT-9159)", () => {
- test.describe.configure({ mode: "serial" });
-
- test("checks show ERROR result", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED — environment lacks matching rule");
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
-
- await expect(page.getByText(/Error|Failed/i).first()).toBeVisible({ timeout: 15_000 });
- });
-
- test("approval shows Done", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED");
- await expect(
- page.getByText(/Approved|Done/i).first()
- ).toBeVisible({ timeout: 10_000 });
- });
-
- test("deploy section says checks are blocking", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED");
- await expect(page.getByText("Failed checks are blocking")).toBeVisible({ timeout: 10_000 });
- });
-
- test("no manual create rollout button when checks required and failed (BYT-9159)", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED");
- await expect(planPage.manualCreateRolloutButton).not.toBeVisible({ timeout: 3_000 });
- });
-
- test("button appears after disabling check requirement", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED");
- await env.api.updateProjectSettings(env.project, { requirePlanCheckNoError: false });
-
- await page.goto(planURL);
- await page.waitForLoadState("networkidle");
- await planPage.dismissModals();
-
- await expect(planPage.manualCreateRolloutButton).toBeVisible({ timeout: 10_000 });
- });
-
- test("deploy text confirms checks are optional", async () => {
- test.skip(shouldSkip, "Approval resolved to SKIPPED");
- await expect(page.getByText(/Failed checks won't block/i)).toBeVisible({ timeout: 10_000 });
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts
new file mode 100644
index 0000000000..d3d194617c
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-checks.spec.ts
@@ -0,0 +1,294 @@
+// Plan detail — SQL review / plan checks.
+//
+// Covers:
+// - WARNING-level rule produces an inline warning count but does NOT
+// block rollout creation (auto-rollout still happens).
+// - ERROR-level rule with `requirePlanCheckNoError=true` blocks the
+// auto-rollout with NO "Manually create rollout" button; relaxing the
+// gate (requirePlanCheckNoError=false) reveals the manual-create button.
+// - Multi-spec plans: smoke test that each spec tab is selectable and
+// renders an inline check summary (BYT-9160 context; NOT a strict
+// regression lock — see the in-test comment).
+//
+// Each test owns its review config + project TagPolicy via API, and
+// cleans up in afterEach so a sibling test doesn't inherit state.
+
+import {
+ test,
+ expect,
+ type Page,
+ type BrowserContext,
+} from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+import { waitForPlanChecksDone } from "./plan-helpers";
+
+test.setTimeout(180_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: {
+ requireIssueApproval?: boolean;
+ requirePlanCheckNoError?: boolean;
+} = {};
+
+// Track per-test review configs so afterEach can delete them.
+let createdReviewConfigs: string[] = [];
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ // No approval gate by default; individual tests flip
+ // requirePlanCheckNoError as needed.
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ sharedContext = await browser.newContext({
+ storageState: ".auth/state.json",
+ });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterEach(async () => {
+ // Remove the project's TagPolicy so the next test starts with no
+ // review config attached. Then delete the configs we created.
+ await env.api.deletePolicy(env.project, "tag").catch(() => {});
+ for (const name of createdReviewConfigs) {
+ await env.api.deleteReviewConfig(name).catch(() => {});
+ }
+ createdReviewConfigs = [];
+ // Restore permissive plan-check setting; individual tests may have
+ // flipped it.
+ await env.api
+ .updateProjectSettings(env.project, { requirePlanCheckNoError: false })
+ .catch(() => {});
+});
+
+test.afterAll(async () => {
+ await env.api
+ .updateProjectSettings(env.project, originalSettings)
+ .catch(() => {});
+ await sharedContext?.close();
+});
+
+// Build a review config with a single COLUMN_NO_NULL rule on POSTGRES at
+// the given level (WARNING or ERROR), bind it to the test project via a
+// TagPolicy, and return its resource name so afterEach can delete it.
+async function attachReviewConfig(
+ level: "WARNING" | "ERROR",
+): Promise<string> {
+ const id = `e2e-${level.toLowerCase()}-${Date.now()}`;
+ const cfg = await env.api.upsertReviewConfig(
+ id,
+ `E2E ${level} Review Config`,
+ [{ type: "COLUMN_NO_NULL", level, engine: "POSTGRES" }],
+ /* enabled */ true,
+ );
+ await env.api.upsertReviewConfigTag(env.project, cfg.name);
+ createdReviewConfigs.push(cfg.name);
+ return cfg.name;
+}
+
+// Poll the latest planCheckRun on `planName` until status === "DONE",
+// then navigate to the plan detail page. Returns the planId.
+async function createPlanAndWaitForChecks(
+ titlePrefix: string,
+ specs: { id: string; targets: string[]; sql: string }[],
+): Promise<string> {
+ const ts = Date.now();
+ const planSpecs = await Promise.all(
+ specs.map(async (s) => ({
+ id: s.id,
+ targets: s.targets,
+ sheet: await env.api.createSheet(env.project, s.sql),
+ })),
+ );
+ const plan = await env.api.createPlan(
+ env.project,
+ `${titlePrefix} ${ts}`,
+ planSpecs,
+ );
+ const planName = plan.name;
+ const planId = planName.split("/").pop()!;
+ await env.api.createIssue(env.project, `${titlePrefix} ${ts}`, planName);
+ await env.api.runPlanChecks(planName);
+
+ await waitForPlanChecksDone(env.api, planName);
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ return planId;
+}
+
+test.describe("WARNING-level review rule", () => {
+ test("violating SQL produces a warning but does not block auto-rollout", async () => {
+ await attachReviewConfig("WARNING");
+
+ const ts = Date.now();
+ await createPlanAndWaitForChecks("E2E Checks Warning", [
+ {
+ id: `spec-${ts}`,
+ targets: [env.database],
+ // Nullable TEXT with no default → trips COLUMN_NO_NULL.
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_warn_${ts} TEXT;`,
+ },
+ ]);
+
+ // CHANGES summary line carries the warning count ("1 passed, 1 warning").
+ // Scope the search to the plan body and match a numeric warning count.
+ await expect(
+ page.getByText(/\d+\s+warning/i).first(),
+ ).toBeVisible({ timeout: 15_000 });
+
+ // Rollout still auto-created — DEPLOY is "Not started", no manual
+ // create button needed.
+ await expect(planPage.deploySection).toBeVisible();
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 3_000,
+ });
+ });
+});
+
+test.describe("ERROR-level review rule with requirePlanCheckNoError=true", () => {
+ // Product contract observed on free-plan setupSample (2026-05):
+ // - ERROR check + requirePlanCheckNoError=true: rollout is BLOCKED.
+ // DEPLOY surfaces "Checks must pass. Failed" with helper text
+ // "Failed checks are blocking automatic rollout creation." NO
+ // "Manually create rollout" button is offered — the user must
+ // either fix the SQL or relax the gate.
+ // - When the gate is relaxed (requirePlanCheckNoError=false), the
+ // manual create button DOES appear so the user can bypass the
+ // failed checks intentionally.
+ // Both halves are covered here so a regression on either side fails
+ // loudly.
+
+ test("with gate on, rollout is blocked and no manual-create option is shown", async () => {
+ await attachReviewConfig("ERROR");
+ await env.api.updateProjectSettings(env.project, {
+ requirePlanCheckNoError: true,
+ });
+
+ const ts = Date.now();
+ await createPlanAndWaitForChecks("E2E Checks Error Gate-On", [
+ {
+ id: `spec-${ts}`,
+ targets: [env.database],
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_err_on_${ts} TEXT;`,
+ },
+ ]);
+
+ // The ERROR check is surfaced in the CHANGES "Checks" summary as an Error entry.
+ await expect(planPage.checksSummary()).toContainText("Error", {
+ timeout: 15_000,
+ });
+ // DEPLOY explains the block.
+ await expect(
+ page.getByText(/Failed checks are blocking/i).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ // No manual create path is offered in this state.
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 3_000,
+ });
+ });
+
+ test("relaxing the gate (requirePlanCheckNoError=false) reveals the manual-create button", async () => {
+ await attachReviewConfig("ERROR");
+ // Gate OFF — failed checks no longer block; user can bypass.
+ await env.api.updateProjectSettings(env.project, {
+ requirePlanCheckNoError: false,
+ });
+
+ const ts = Date.now();
+ await createPlanAndWaitForChecks("E2E Checks Error Gate-Off", [
+ {
+ id: `spec-${ts}`,
+ targets: [env.database],
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_err_off_${ts} TEXT;`,
+ },
+ ]);
+
+ await expect(planPage.checksSummary()).toContainText("Error", {
+ timeout: 15_000,
+ });
+ await expect(planPage.manualCreateRolloutButton).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+});
+
+test.describe("Per-spec scoping (BYT-9160)", () => {
+ // BYT-9160 was a per-spec rendering bug: the right sidebar always showed
+ // the LAST spec's check counts regardless of which spec tab was selected.
+ // The React migration REMOVED that right sidebar. Per-spec data now lives
+ // in the CHANGES editor (the statement + inline advice markers, scoped to
+ // the selected spec via planCheckRunListForSpec), while check COUNTS are
+ // shown PLAN-WIDE (PlanDetailAggregateChecks: one Success/Warning/Error
+ // summary that opens a results drawer). There is no per-spec count to
+ // compare anymore, so the surviving contract is: selecting a spec shows
+ // THAT spec's statement, not a stale sibling's. The two specs carry
+ // uniquely-stamped columns, so the BYT-9160-class regression (stale
+ // per-spec content on tab switch) fails loudly.
+ test("each spec tab shows its own statement; checks render plan-wide", async () => {
+ const ts = Date.now();
+ const colA = `e2e_spec_a_${ts}`;
+ const colB = `e2e_spec_b_${ts}`;
+ await createPlanAndWaitForChecks("E2E Per-Spec", [
+ {
+ id: `spec-a-${ts}`,
+ targets: [env.database],
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colA} TEXT;`,
+ },
+ {
+ id: `spec-b-${ts}`,
+ targets: [env.database],
+ sql: `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colB} TEXT;`,
+ },
+ ]);
+
+ // Expand CHANGES so the spec tabs + statement editor are reachable.
+ await planPage.expandSection("Changes");
+
+ // Joined text of every mounted Monaco surface. The CHANGES statement
+ // editor renders only the SELECTED spec (PlanDetailStatementSection is
+ // driven by selectedSpec), so this reflects the active spec's statement.
+ const readStatement = (): Promise<string> =>
+ page.evaluate(() =>
+ Array.from(document.querySelectorAll('[role="code"]'))
+ .flatMap((c) => Array.from(c.querySelectorAll(".view-line")))
+ .map((l) => l.textContent ?? "")
+ .join("\n"),
+ );
+
+ // Spec #1 selected: its statement shows; spec #2's does not.
+ await planPage.specTab(1).click();
+ await expect.poll(readStatement, { timeout: 15_000 }).toContain(colA);
+ expect(await readStatement()).not.toContain(colB);
+
+ // Switching to spec #2 swaps the CHANGES content to spec #2's statement.
+ // The BYT-9160 regression would leave spec #1's content rendered here.
+ await planPage.specTab(2).click();
+ await expect.poll(readStatement, { timeout: 15_000 }).toContain(colB);
+ expect(await readStatement()).not.toContain(colA);
+
+ // Check counts are now a single plan-wide summary (the per-spec sidebar
+ // is gone); confirm it renders.
+ await expect(page.getByText("Success").first()).toBeVisible({
+ timeout: 15_000,
+ });
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts
deleted file mode 100644
index 26c8cf233a..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-lifecycle.spec.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let planPage: PlanDetailPage;
-let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- // Capture and set permissive project settings
- const project = await env.api.getProject(env.project);
- originalSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: false,
- requirePlanCheckNoError: false,
- });
-
- // Create a dedicated sheet for this test
- const columnName = `e2e_lifecycle_${Date.now()}`;
- const sheetName = await env.api.createSheet(
- env.project,
- `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${columnName} TEXT;`
- );
-
- // Create the plan
- const specId = `spec-${Date.now()}`;
- const plan = await env.api.createPlan(env.project, `E2E Lifecycle Test ${Date.now()}`, [
- { id: specId, targets: [env.database], sheet: sheetName },
- ]);
- planId = plan.name.split("/").pop()!;
-
- // Create an issue backed by the plan (required to drive the lifecycle UI)
- await env.api.createIssue(env.project, "E2E Lifecycle", plan.name);
-
- // Open the shared browser context
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-});
-
-test.afterAll(async () => {
- await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
- await sharedContext?.close();
-});
-
-test.describe("Plan Detail: Lifecycle + Section Preservation", () => {
- test.describe.configure({ mode: "serial" });
-
- test("navigate to plan and see all three phases", async () => {
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
-
- await expect(planPage.changesSection).toBeVisible();
- await expect(planPage.reviewSection).toBeVisible();
- await expect(planPage.deploySection).toBeVisible();
- });
-
- test("sections are expanded by default", async () => {
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-
- test("create rollout with bypass", async () => {
- await planPage.createRolloutWithBypass();
- await expect(page.getByText(/Not started|Deploying/i).first()).toBeVisible({ timeout: 15_000 });
- });
-
- test("sections remain expanded after rollout creation (BYT-9161)", async () => {
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-
- test("run task and wait for completion", async () => {
- await planPage.runTask();
- await expect(page.getByText("Done").first()).toBeVisible({ timeout: 30_000 });
- });
-
- test("sidebar shows Done status after completion", async () => {
- await expect(page.getByRole("complementary").getByText(/Done/i).first()).toBeVisible();
- });
-
- test("state preserved after navigation away and back", async () => {
- await page.goto(`${env.baseURL}/projects/${projectId}/issues`);
- await page.waitForLoadState("networkidle");
-
- await planPage.goto(projectId, planId);
- await expect(planPage.deploySection).toBeVisible();
- });
-
- test("sections still expanded after navigation (BYT-9161)", async () => {
- // After task completion phases may auto-collapse — either expanded or
- // the toggle is absent (section is always open). Both are acceptable.
- const changesExpanded = await planPage.isSectionExpanded("Changes");
- // isSectionExpanded returns true when toggle is absent (no collapse control)
- // so any truthy result — or explicit true — satisfies the regression check.
- expect(changesExpanded).toBe(true);
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts
new file mode 100644
index 0000000000..4c758cb1cc
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-rollout.spec.ts
@@ -0,0 +1,301 @@
+// Plan detail — rollout creation across (approval, plan-check) gates.
+//
+// The user contract: a rollout transitions through specific states based
+// on project settings + plan-check outcomes:
+// - Permissive (no approval gate, no plan-check gate)
+// → rollout auto-creates on issue creation.
+// - Approval gate ON, no plan-check failures
+// → rollout blocked until each approval-flow step completes; on the
+// last approval the rollout auto-creates.
+// - Approval + plan-check gate with an ERROR-level SQL review rule
+// → after approval, the rollout STAYS fully blocked: DEPLOY shows
+// "Failed checks are blocking automatic rollout creation" and NO
+// "Manually create rollout" button is offered. The user must fix
+// the SQL or relax requirePlanCheckNoError (which then reveals the
+// manual-create button).
+//
+// Approval rules are workspace-level settings (`WORKSPACE_APPROVAL`); the
+// new bootstrap leaves them empty, so each test that needs an approval
+// flow configures one in `beforeAll` and restores in `afterAll`.
+
+import {
+ test,
+ expect,
+ type Page,
+ type BrowserContext,
+} from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+import { waitForPlanChecksDone } from "./plan-helpers";
+
+test.setTimeout(180_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalProjectSettings: {
+ requireIssueApproval?: boolean;
+ requirePlanCheckNoError?: boolean;
+ allowSelfApproval?: boolean;
+} = {};
+let originalApprovalSetting: unknown = null;
+let createdReviewConfigs: string[] = [];
+
+// Workspace approval rule used by the approval-gated tests. Single-step
+// workspaceAdmin approval matched against `CHANGE_DATABASE` plans (the
+// enum value covers DDL/DML — see proto `setting_service.proto`). The
+// admin who created the issue (env.adminEmail) can self-approve, which
+// is sufficient to verify the state transition without a second user.
+const APPROVAL_RULE = {
+ source: "CHANGE_DATABASE",
+ condition: { expression: "true" },
+ template: {
+ flow: { roles: ["roles/workspaceAdmin"] },
+ title: "E2E Approval",
+ description: "Single-step workspaceAdmin approval",
+ },
+};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ const project = await env.api.getProject(env.project);
+ originalProjectSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ allowSelfApproval: !!project.allowSelfApproval,
+ };
+
+ // Snapshot WORKSPACE_APPROVAL so per-test mutations can be restored.
+ const existing = await env.api.getSetting("WORKSPACE_APPROVAL");
+ originalApprovalSetting = existing?.value ?? null;
+
+ sharedContext = await browser.newContext({
+ storageState: ".auth/state.json",
+ });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ // Restore project settings.
+ await env.api
+ .updateProjectSettings(env.project, originalProjectSettings)
+ .catch(() => {});
+
+ // Restore workspace approval rules. If none existed, clear our rule.
+ await env.api
+ .upsertSetting(
+ "WORKSPACE_APPROVAL",
+ originalApprovalSetting ?? { workspaceApproval: { rules: [] } },
+ "value.workspace_approval",
+ )
+ .catch(() => {});
+
+ // Clean up any review configs / tag policies created mid-test.
+ await env.api.deletePolicy(env.project, "tag").catch(() => {});
+ for (const name of createdReviewConfigs) {
+ await env.api.deleteReviewConfig(name).catch(() => {});
+ }
+ createdReviewConfigs = [];
+
+ await sharedContext?.close();
+});
+
+// Helper — create a plan + issue against env.database; run plan checks;
+// wait for them to complete; navigate to the detail page. Returns the
+// plan's resource name + id so callers can poll approval state.
+async function createIssueWithChecks(
+ titlePrefix: string,
+ sql: string,
+): Promise<{ planName: string; planId: string; issueName: string }> {
+ const ts = Date.now();
+ const sheet = await env.api.createSheet(env.project, sql);
+ const plan = await env.api.createPlan(
+ env.project,
+ `${titlePrefix} ${ts}`,
+ [{ id: `spec-${ts}`, targets: [env.database], sheet }],
+ );
+ const planName = plan.name;
+ const planId = planName.split("/").pop()!;
+ const issue = await env.api.createIssue(
+ env.project,
+ `${titlePrefix} ${ts}`,
+ planName,
+ );
+ await env.api.runPlanChecks(planName);
+
+ await waitForPlanChecksDone(env.api, planName);
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ return { planName, planId, issueName: issue.name };
+}
+
+test.describe("Permissive settings", () => {
+ test.beforeAll(async () => {
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+ });
+
+ test("rollout auto-creates on issue creation; no manual button", async () => {
+ const ts = Date.now();
+ await createIssueWithChecks(
+ "E2E Rollout Permissive",
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_perm_${ts} TEXT;`,
+ );
+
+ // DEPLOY section visible + task ready to run; no manual create btn.
+ await expect(planPage.deploySection).toBeVisible({ timeout: 10_000 });
+ await expect(
+ page.getByText(/Not started|Pending/i).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 3_000,
+ });
+ });
+});
+
+test.describe("Approval required, no plan-check gate", () => {
+ // WORKSPACE_APPROVAL is an ENTERPRISE feature (FEATURE_APPROVAL_WORKFLOW);
+ // mutating it returns 403 on the free plan. The license is installed at bootstrap.
+ test.beforeAll(async () => {
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: true,
+ requirePlanCheckNoError: false,
+ // Default with license is false → demo@ (issue creator) gets a
+ // 403 trying to approve their own issue. We're doing single-
+ // admin approval for test simplicity; flip on.
+ allowSelfApproval: true,
+ });
+ await env.api.upsertSetting(
+ "WORKSPACE_APPROVAL",
+ { workspaceApproval: { rules: [APPROVAL_RULE] } },
+ "value.workspace_approval",
+ );
+ });
+
+ test("issue blocks until admin approves; afterward rollout auto-creates", async () => {
+ const { planName, issueName } = await createIssueWithChecks(
+ "E2E Rollout Approval",
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_appr_${Date.now()} TEXT;`,
+ );
+ void planName;
+
+ // Approval flow generation can take a moment after plan checks finish.
+ const deadline = Date.now() + 30_000;
+ let status = "";
+ while (Date.now() < deadline) {
+ status = (await env.api.getIssue(issueName)).approvalStatus;
+ if (status === "PENDING" || status === "APPROVED" || status === "SKIPPED") {
+ break;
+ }
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ // Fail closed: after configuring the approval rule (beforeAll), the issue
+ // MUST be PENDING. A non-PENDING status means rule matching / approval-flow
+ // generation regressed — assert it loudly rather than skipping, which would
+ // hide exactly the approval-gate failure this test exists to catch.
+ expect(
+ status,
+ `issue ${issueName} must be PENDING after configuring a workspace approval rule (last status=${status})`,
+ ).toBe("PENDING");
+
+ // While pending: no rollout, no manual create button.
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 5_000,
+ });
+
+ // Approve. Reload so the UI picks up the new state.
+ await env.api.approveIssue(issueName);
+ await page.reload();
+ await page.waitForLoadState("networkidle");
+
+ // Auto-rollout proceeds (no plan-check failures to block).
+ await expect(planPage.deploySection).toBeVisible({ timeout: 15_000 });
+ await expect(
+ page.getByText(/Not started|Pending/i).first(),
+ ).toBeVisible({ timeout: 15_000 });
+ });
+});
+
+test.describe("Approval + plan-check gate with ERROR-level SQL review", () => {
+ let reviewConfigName = "";
+
+ test.beforeAll(async () => {
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: true,
+ requirePlanCheckNoError: true,
+ allowSelfApproval: true,
+ });
+ await env.api.upsertSetting(
+ "WORKSPACE_APPROVAL",
+ { workspaceApproval: { rules: [APPROVAL_RULE] } },
+ "value.workspace_approval",
+ );
+
+ const id = `e2e-rollout-error-${Date.now()}`;
+ const cfg = await env.api.upsertReviewConfig(
+ id,
+ "E2E Rollout ERROR Review Config",
+ [{ type: "COLUMN_NO_NULL", level: "ERROR", engine: "POSTGRES" }],
+ );
+ reviewConfigName = cfg.name;
+ createdReviewConfigs.push(cfg.name);
+ await env.api.upsertReviewConfigTag(env.project, reviewConfigName);
+ });
+
+ test("after approval, plan-check failure keeps the rollout fully blocked (no manual-create)", async () => {
+ const { issueName } = await createIssueWithChecks(
+ "E2E Rollout Approval+Error",
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_appr_err_${Date.now()} TEXT;`,
+ );
+
+ // Wait for approval state to materialize.
+ const deadline = Date.now() + 30_000;
+ let status = "";
+ while (Date.now() < deadline) {
+ status = (await env.api.getIssue(issueName)).approvalStatus;
+ if (status === "PENDING" || status === "APPROVED" || status === "SKIPPED") {
+ break;
+ }
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ // Fail closed (same contract as the approval test above): a configured
+ // approval rule must put the issue in PENDING; assert rather than skip so a
+ // regression in approval-flow generation fails loudly.
+ expect(
+ status,
+ `issue ${issueName} must be PENDING after configuring a workspace approval rule (last status=${status})`,
+ ).toBe("PENDING");
+
+ await env.api.approveIssue(issueName);
+ await page.reload();
+ await page.waitForLoadState("networkidle");
+
+ // Product contract: with requirePlanCheckNoError=true and an ERROR
+ // rule, even after the approval flow completes the rollout stays
+ // fully blocked. DEPLOY shows "Checks must pass. Failed" with the
+ // helper text "Failed checks are blocking automatic rollout
+ // creation." NO "Manually create rollout" button is offered — the
+ // user must either fix the SQL or relax the gate. (Symmetric to
+ // the `with gate on` test in plan-detail-checks.spec.ts.)
+ await expect(planPage.checksSummary()).toContainText("Error", {
+ timeout: 15_000,
+ });
+ await expect(
+ page.getByText(/Failed checks are blocking/i).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await expect(planPage.manualCreateRolloutButton).not.toBeVisible({
+ timeout: 3_000,
+ });
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-sections.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-sections.spec.ts
new file mode 100644
index 0000000000..c20fbfc1e8
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-sections.spec.ts
@@ -0,0 +1,144 @@
+// Plan detail — section UI (expand/collapse + preservation).
+//
+// Covers:
+// - CHANGES auto-collapses once an auto-rollout has been created;
+// it must remain expandable on demand.
+// - Collapsing one section doesn't change the state of others.
+// - Section state survives a navigation away and back to the same plan
+// (BYT-9161 regression lock).
+
+import {
+ test,
+ expect,
+ type Page,
+ type BrowserContext,
+} from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+let planId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: {
+ requireIssueApproval?: boolean;
+ requirePlanCheckNoError?: boolean;
+} = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Permissive settings → rollout auto-creates on issue creation.
+ // CHANGES then collapses to "Show details" by default — that's the
+ // state under test.
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ const ts = Date.now();
+ const sheet = await env.api.createSheet(
+ env.project,
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS e2e_sections_${ts} TEXT;`,
+ );
+ const plan = await env.api.createPlan(
+ env.project,
+ `E2E Sections ${ts}`,
+ [{ id: `spec-${ts}`, targets: [env.database], sheet }],
+ );
+ planId = plan.name.split("/").pop()!;
+ await env.api.createIssue(env.project, `E2E Sections ${ts}`, plan.name);
+
+ sharedContext = await browser.newContext({
+ storageState: ".auth/state.json",
+ });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+});
+
+test.afterAll(async () => {
+ await env.api
+ .updateProjectSettings(env.project, originalSettings)
+ .catch(() => {});
+ await sharedContext?.close();
+});
+
+test.describe("Section UI", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("CHANGES collapses by default once the rollout is auto-created", async () => {
+ // With permissive settings the rollout exists immediately, and the
+ // page's focus shifts to DEPLOY — CHANGES auto-collapses. Verify
+ // the toggle reads "Show details".
+ await expect(planPage.changesSection).toBeVisible({ timeout: 10_000 });
+ expect(await planPage.isSectionExpanded("Changes")).toBe(false);
+ expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
+ });
+
+ test("expandSection makes CHANGES visible again", async () => {
+ await planPage.expandSection("Changes");
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+ });
+
+ test("collapsing one section doesn't affect siblings (BYT-9161 lock)", async () => {
+ // Start clean.
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ await planPage.expandSection("Changes");
+
+ const changesToggle = planPage.getSectionToggle("Changes");
+ if (
+ await changesToggle.isVisible({ timeout: 3_000 }).catch(() => false)
+ ) {
+ await changesToggle.click();
+ await expect(changesToggle).toHaveText(/Show details/, {
+ timeout: 5_000,
+ });
+ }
+
+ // CHANGES is now collapsed; DEPLOY must still be expanded.
+ expect(await planPage.isSectionExpanded("Changes")).toBe(false);
+ expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
+ });
+
+ // Cross-navigation behavior: when the user leaves the plan and comes
+ // back, `usePlanDetailPage.ts:210-212` re-runs `focusPhase(currentPhase)`
+ // on the routePageKey change. With a rollout in place, currentPhase
+ // is "deploy" — so DEPLOY stays expanded and CHANGES/REVIEW collapse
+ // back to their default. This is intentional UX (focus follows the
+ // user-relevant phase), not a regression of BYT-9161.
+ test("navigation away and back re-focuses the current phase (DEPLOY when rollout exists)", async () => {
+ // Manually expand CHANGES so its post-nav state is observably
+ // different from the auto-focus result.
+ await planPage.expandSection("Changes");
+ expect(await planPage.isSectionExpanded("Changes")).toBe(true);
+
+ await page.goto(`${env.baseURL}/projects/${projectId}/issues`);
+ await page.waitForLoadState("networkidle");
+
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+
+ // DEPLOY is the auto-focused phase post-nav.
+ expect(await planPage.isSectionExpanded("Deploy")).toBe(true);
+ // CHANGES auto-collapses to default — our in-page expansion does
+ // NOT persist across the route change (by design).
+ expect(await planPage.isSectionExpanded("Changes")).toBe(false);
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts
deleted file mode 100644
index fe32d2d87a..0000000000
--- a/frontend/tests/e2e/plan-detail/plan-detail-task-failure.spec.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { test, expect, type Page, type BrowserContext } from "@playwright/test";
-import { loadTestEnv, type TestEnv } from "../framework/env";
-import { BytebaseApiClient } from "../framework/api-client";
-import { PlanDetailPage } from "./plan-detail.page";
-
-test.setTimeout(120_000);
-
-let env: TestEnv & { api: BytebaseApiClient };
-let projectId: string;
-let planId: string;
-
-let sharedContext: BrowserContext;
-let page: Page;
-let planPage: PlanDetailPage;
-let originalSettings: { requireIssueApproval?: boolean; requirePlanCheckNoError?: boolean } = {};
-
-test.beforeAll(async ({ browser }) => {
- env = loadTestEnv();
- projectId = env.project.split("/").pop()!;
- await env.api.login(env.adminEmail, env.adminPassword);
-
- // Capture and set permissive project settings
- const project = await env.api.getProject(env.project);
- originalSettings = {
- requireIssueApproval: !!project.requireIssueApproval,
- requirePlanCheckNoError: !!project.requirePlanCheckNoError,
- };
- await env.api.updateProjectSettings(env.project, {
- requireIssueApproval: false,
- requirePlanCheckNoError: false,
- });
-
- // Create a sheet targeting a nonexistent table — will fail at execution time
- const tableName = `nonexistent_table_e2e_${Date.now()}`;
- const sheetName = await env.api.createSheet(
- env.project,
- `ALTER TABLE ${tableName} ADD COLUMN c1 TEXT;`
- );
-
- // Create the plan
- const specId = `spec-${Date.now()}`;
- const plan = await env.api.createPlan(env.project, `E2E Task Failure Test ${Date.now()}`, [
- { id: specId, targets: [env.database], sheet: sheetName },
- ]);
- planId = plan.name.split("/").pop()!;
-
- // Create an issue backed by the plan (required to drive the lifecycle UI)
- await env.api.createIssue(env.project, "E2E Task Failure", plan.name);
-
- // Open the shared browser context
- sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
- page = await sharedContext.newPage();
- planPage = new PlanDetailPage(page, env.baseURL);
-});
-
-test.afterAll(async () => {
- await env.api.updateProjectSettings(env.project, originalSettings).catch(() => {});
- await sharedContext?.close();
-});
-
-test.describe("Plan Detail: Task Failure (CUJ 4)", () => {
- test.describe.configure({ mode: "serial" });
-
- test("navigate and create rollout", async () => {
- await planPage.goto(projectId, planId);
- await planPage.dismissModals();
- await planPage.createRolloutWithBypass();
- await expect(page.getByText(/Not started|Deploying/i).first()).toBeVisible({ timeout: 15_000 });
- });
-
- test("run task that will fail", async () => {
- await planPage.runTask();
- await expect(page.getByText("Failed").first()).toBeVisible({ timeout: 30_000 });
- });
-
- test("task shows Failed status", async () => {
- await expect(page.getByText("Failed").first()).toBeVisible();
- });
-
- test("Retry button is visible", async () => {
- await expect(planPage.retryButton).toBeVisible();
- });
-
- test("sidebar shows Failed", async () => {
- await expect(page.getByRole("complementary").getByText("Failed").first()).toBeVisible();
- });
-
- test("sections remain expanded after failure (BYT-9161)", async () => {
- expect(await planPage.isSectionExpanded("Changes")).toBe(true);
- expect(await planPage.isSectionExpanded("Review")).toBe(true);
- });
-});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts
new file mode 100644
index 0000000000..553f369112
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts
@@ -0,0 +1,122 @@
+// Plan detail — task execution.
+//
+// Covers the task lifecycle once a rollout exists (auto-created here
+// via permissive project settings):
+// - Running a successful task transitions to Done.
+// - Running a failing task (nonexistent target) transitions to Failed
+// and surfaces a Retry button.
+
+import {
+ test,
+ expect,
+ type Page,
+ type BrowserContext,
+} from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+import { PlanDetailPage } from "./plan-detail.page";
+
+test.setTimeout(180_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+
+let sharedContext: BrowserContext;
+let page: Page;
+let planPage: PlanDetailPage;
+let originalSettings: {
+ requireIssueApproval?: boolean;
+ requirePlanCheckNoError?: boolean;
+} = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Permissive — both tests want a rollout to be auto-created so they
+ // can drive task execution directly. We only mutate project settings;
+ // each describe creates its own plan.
+ const project = await env.api.getProject(env.project);
+ originalSettings = {
+ requireIssueApproval: !!project.requireIssueApproval,
+ requirePlanCheckNoError: !!project.requirePlanCheckNoError,
+ };
+ await env.api.updateProjectSettings(env.project, {
+ requireIssueApproval: false,
+ requirePlanCheckNoError: false,
+ });
+
+ sharedContext = await browser.newContext({
+ storageState: ".auth/state.json",
+ });
+ page = await sharedContext.newPage();
+ planPage = new PlanDetailPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await env.api
+ .updateProjectSettings(env.project, originalSettings)
+ .catch(() => {});
+ await sharedContext?.close();
+});
+
+// Helper — create a plan + issue against env.database with the given SQL,
+// navigate to its detail page. Returns the plan id for re-navigation.
+async function createPlanAndNavigate(
+ titlePrefix: string,
+ sql: string,
+): Promise<string> {
+ const ts = Date.now();
+ const sheet = await env.api.createSheet(env.project, sql);
+ const plan = await env.api.createPlan(
+ env.project,
+ `${titlePrefix} ${ts}`,
+ [{ id: `spec-${ts}`, targets: [env.database], sheet }],
+ );
+ const planId = plan.name.split("/").pop()!;
+ await env.api.createIssue(env.project, `${titlePrefix} ${ts}`, plan.name);
+ await planPage.goto(projectId, planId);
+ await planPage.dismissModals();
+ return planId;
+}
+
+test.describe("Successful task transitions to Done", () => {
+ test("Run → Done", async () => {
+ const colName = `e2e_tasks_ok_${Date.now()}`;
+ await createPlanAndNavigate(
+ "E2E Task Success",
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${colName} TEXT;`,
+ );
+
+ await expect(
+ page.getByText(/Not started|Pending/i).first(),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await planPage.runTask();
+ await expect(page.getByText("Done").first()).toBeVisible({
+ timeout: 60_000,
+ });
+ });
+});
+
+test.describe("Failing task transitions to Failed and shows Retry", () => {
+ test("Run → Failed + Retry button visible", async () => {
+ const missingTable = `nonexistent_table_e2e_${Date.now()}`;
+ await createPlanAndNavigate(
+ "E2E Task Failure",
+ `ALTER TABLE ${missingTable} ADD COLUMN c1 TEXT;`,
+ );
+
+ await expect(
+ page.getByText(/Not started|Pending/i).first(),
+ ).toBeVisible({ timeout: 15_000 });
+
+ await planPage.runTask();
+ await expect(page.getByText("Failed").first()).toBeVisible({
+ timeout: 30_000,
+ });
+
+ await expect(planPage.retryButton).toBeVisible({ timeout: 5_000 });
+ });
+});
diff --git a/frontend/tests/e2e/plan-detail/plan-detail.page.ts b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
index 8b3ddda011..907fe64db1 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail.page.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail.page.ts
@@ -5,11 +5,8 @@ export class PlanDetailPage {
readonly baseURL: string;
readonly changesSection: Locator;
- readonly reviewSection: Locator;
readonly deploySection: Locator;
readonly manualCreateRolloutButton: Locator;
- readonly bypassWarningsCheckbox: Locator;
- readonly confirmRolloutButton: Locator;
readonly retryButton: Locator;
// The plan/issue title input rendered in PlanDetailHeader. It is an
// <input> bound to the plan or issue title — first textbox on the page.
@@ -20,11 +17,8 @@ export class PlanDetailPage {
this.baseURL = baseURL;
this.changesSection = page.getByText("Changes").first();
- this.reviewSection = page.getByText("Review").first();
this.deploySection = page.getByText("Deploy").first();
this.manualCreateRolloutButton = page.getByRole("button", { name: "Manually create rollout" });
- this.bypassWarningsCheckbox = page.getByRole("checkbox", { name: "Bypass warnings" });
- this.confirmRolloutButton = page.getByRole("dialog").getByRole("button", { name: "Confirm" });
this.retryButton = page.getByRole("button", { name: "Retry" });
this.headerTitle = page.getByRole("textbox").first();
}
@@ -50,17 +44,6 @@ export class PlanDetailPage {
}
}
- async createRolloutWithBypass() {
- await this.manualCreateRolloutButton.click();
- await this.bypassWarningsCheckbox.check();
- // Arm the response waiter BEFORE clicking so a fast response isn't missed.
- const responsePromise = this.page.waitForResponse(
- (r) => r.url().includes("Rollout") && r.status() < 400
- );
- await this.confirmRolloutButton.click();
- await responsePromise;
- }
-
async runTask() {
// Match only buttons with exact text "Run" (not "Run check", "Run Tasks").
// Use getByRole with exact name to avoid substring matches.
@@ -92,30 +75,39 @@ export class PlanDetailPage {
return true;
}
- specTab(n: number): Locator {
- return this.page.getByText("Changes").locator("..").getByText(`#${n}`).first();
+ // Click "Show details" if collapsed; no-op when already expanded or when no
+ // toggle exists (always-open section). When the rollout already exists the
+ // CHANGES section auto-collapses by default — call this before reading any
+ // content inside CHANGES (check counts, spec tabs).
+ async expandSection(sectionName: string): Promise<void> {
+ const toggle = this.getSectionToggle(sectionName);
+ if (!(await toggle.isVisible({ timeout: 1000 }).catch(() => false))) return;
+ const text = (await toggle.textContent()) ?? "";
+ if (text.includes("Show")) {
+ await toggle.click();
+ await expect(toggle).toHaveText(/Hide details/, { timeout: 5_000 });
+ }
}
- // Returns the count number for the given status (Warning/Success/Error)
- // in the inline Checks area (h3 level, not sidebar h4).
- inlineCheckCount(status: string): Locator {
+ // Spec tabs render as `<button>N. <Kind></button>` (e.g.
+ // "1. Database Change") inside the CHANGES section. The "1." and
+ // "Database Change" pieces live in separate child spans — so plain
+ // textContent has no separator. Matching the BUTTON's accessible name
+ // (which inserts the space) via getByRole sidesteps that.
+ //
+ // Caller must expandSection("Changes") first if a rollout exists,
+ // since the section auto-collapses in that state and the tab won't be
+ // in the visible DOM.
+ specTab(n: number): Locator {
return this.page
- .getByRole("heading", { name: "Checks", level: 3 })
- .locator("../..")
- .getByText(status)
- .locator("..")
- .getByText(/^\d+$/);
+ .getByRole("button", { name: new RegExp(`^${n}\\.\\s+\\w`) })
+ .first();
}
- // Returns the count number for the given status (Warning/Success/Error)
- // in the sidebar Checks area (h4 level).
- sidebarCheckCount(status: string): Locator {
- return this.page
- .getByRole("complementary")
- .getByRole("heading", { name: "Checks", level: 4 })
- .locator("..")
- .getByText(status)
- .locator("..")
- .getByText(/^\d+$/);
+ // The plan-wide "Checks" summary button in the CHANGES section. Shows
+ // Success/Warning/Error entries (each rendered only when its count > 0)
+ // and opens the results drawer on click. Distinct from "Run checks".
+ checksSummary(): Locator {
+ return this.page.getByRole("button", { name: "Checks", exact: true });
}
}
diff --git a/frontend/tests/e2e/plan-detail/plan-helpers.ts b/frontend/tests/e2e/plan-detail/plan-helpers.ts
new file mode 100644
index 0000000000..b424a7ab6c
--- /dev/null
+++ b/frontend/tests/e2e/plan-detail/plan-helpers.ts
@@ -0,0 +1,31 @@
+import type { BytebaseApiClient } from "../framework/api-client";
+
+// Poll the latest planCheckRun on `planName` until status === "DONE" or the
+// timeout elapses. The check run is created asynchronously after
+// runPlanChecks(), so getPlanCheckRun may briefly 404 — we swallow and
+// retry. Tuned in one place so a slow-CI timeout bump applies to every
+// caller (plan-detail-checks + plan-detail-rollout).
+export async function waitForPlanChecksDone(
+ api: BytebaseApiClient,
+ planName: string,
+ timeoutMs = 60_000,
+): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ let lastStatus = "<none>";
+ while (Date.now() < deadline) {
+ try {
+ const run = await api.getPlanCheckRun(planName);
+ lastStatus = run.status;
+ if (run.status === "DONE") return;
+ } catch {
+ /* check run not created yet — keep polling */
+ }
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ // Fail closed: returning silently here would let the caller assert against
+ // an unfinished plan and fail far from the cause. Throw so the failure
+ // points at the stuck plan check, not a downstream UI timeout.
+ throw new Error(
+ `plan checks for ${planName} did not reach DONE within ${timeoutMs}ms (last status: ${lastStatus})`,
+ );
+}
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.ts
new file mode 100644
index 0000000000..18ea3ce63c
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-admin-mode.spec.ts
@@ -0,0 +1,571 @@
+// SQL Editor — admin mode terminal.
+//
+// Covers the admin-mode toggle (the wrench button) and the dark-theme
+// terminal it opens: visibility/disabled state of the wrench, entering
+// admin mode, executing a query in the terminal, exiting back to the
+// worksheet, and the result panel's theme harmony (BYT-9496 lock).
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Vertical display preserves the admin-mode dark theme", () => {
+ // BYT-9496 (sub-bug R44a): in admin mode, toggling the "Vertical
+ // display" switch on a result panel re-renders the panel as the
+ // transposed key:value layout — but the new layout uses generic
+ // light-theme tokens (`bg-control-bg`) instead of the dark terminal
+ // tokens (`bg-dark-bg`) used by the surrounding admin shell. The
+ // result is a white-background, black-text block dropped into the
+ // middle of an otherwise dark terminal.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r44-byt9496-admin-mode/
+ // - 03-notes.txt
+ // - 02-vertical-display-theme-break.png
+
+ test("vertical-display result panel keeps a dark background in admin mode", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(500);
+
+ // Enter admin mode via the wrench button (AdminModeButton.tsx).
+ await expect(sqlEditor.adminModeButton).toBeVisible({ timeout: 10_000 });
+ await sqlEditor.adminModeButton.click();
+ await page.waitForTimeout(800);
+
+ // The admin terminal renders an editable CompactSQLEditor at the
+ // bottom of the query stack. There may be other Monaco instances
+ // in the page (the underlying worksheet's editor stays mounted),
+ // so we anchor by `.last()` to target the prompt.
+ //
+ // CompactSQLEditor.tsx:220 wires plain Enter to RunQuery via a
+ // Monaco addCommand whose precondition is
+ // "!readonly && isEnterEndsStatement && cursorAtLast && editorTextFocus"
+ // — so for a statement that ends with `;` (ours does), pressing
+ // Enter at the end of the line submits instead of inserting a
+ // newline.
+ await runInAdminTerminal(
+ "SELECT emp_no, first_name, last_name FROM employee LIMIT 3;",
+ );
+
+ // Wait for the result panel to render (a "Vertical display" toggle
+ // only appears once a result is on screen).
+ await page
+ .getByText("Vertical display", { exact: true })
+ .first()
+ .waitFor({ timeout: 15_000 });
+
+ // Find the Vertical display switch in the result panel header.
+ // The Switch primitive (Base UI) renders as `role="switch"` — we
+ // scope to the row containing the "Vertical display" label so we
+ // don't accidentally toggle the noSQL "table-view" switch above it.
+ const verticalRow = page
+ .locator("div.flex.items-center.gap-x-1")
+ .filter({ hasText: "Vertical display" })
+ .first();
+ await expect(verticalRow).toBeVisible({ timeout: 10_000 });
+ const verticalSwitch = verticalRow.getByRole("switch");
+ await expect(verticalSwitch).toBeVisible({ timeout: 5000 });
+ await verticalSwitch.click();
+ await page.waitForTimeout(500);
+
+ // After toggle, the result body switches from VirtualDataTable to
+ // VirtualDataBlock. Each VirtualDataBlock row is wrapped in a
+ // `data-index="N"` div whose first child holds the asterisk header
+ // and whose second child is the `bg-control-bg rounded` data card.
+ // We anchor by `data-index` (unique to the block view — the table
+ // view uses `data-row-index`) so we don't accidentally sample the
+ // terminal shell or some other element that happens to share a
+ // class fragment.
+ await page
+ .locator("[data-index]")
+ .first()
+ .waitFor({ timeout: 10_000 });
+ const sample = await page.evaluate(() => {
+ // Terminal shell wraps everything in admin mode with bg-dark-bg.
+ const shell = document.querySelector(".bg-dark-bg");
+ if (!shell) return { reason: "admin terminal shell not found" };
+ const shellBg = getComputedStyle(shell).backgroundColor;
+
+ // VirtualDataBlock row: outer is `data-index="N"`, inner data
+ // card is the second child div (the first child is the asterisk
+ // <p>). Sample the inner card — its background is the bug locus.
+ const blockRow = document.querySelector("[data-index]");
+ if (!blockRow) return { reason: "vertical block row not found" };
+ // Walk children to find the data card div (skip the <p> header).
+ const blockCard = Array.from(blockRow.children).find(
+ (child) => child.tagName === "DIV",
+ );
+ if (!blockCard) return { reason: "vertical block card not found" };
+ const blockBg = getComputedStyle(blockCard).backgroundColor;
+
+ // Parse rgb(), rgba(), AND lab() — Chromium 124+ emits lab() for
+ // some Tailwind tokens so the legacy rgb-only regex returns null
+ // and the test reports a false failure. For lab(L a b), convert
+ // to approximate sRGB via the L-only luminance (a/b are tiny for
+ // near-neutral grays which is what the SQL editor's dark-theme
+ // tokens are). L is 0–100; mapping linearly to 0–255 is plenty
+ // for the harmony assertion below.
+ const parse = (s: string) => {
+ const rgb = s.match(/rgba?\(([^)]+)\)/);
+ if (rgb) {
+ const parts = rgb[1].split(",").map((p) => parseFloat(p.trim()));
+ return { r: parts[0], g: parts[1], b: parts[2], a: parts[3] ?? 1 };
+ }
+ const lab = s.match(/^lab\(\s*([\d.\-]+)\s+([\d.\-]+)\s+([\d.\-]+)/);
+ if (lab) {
+ const L = parseFloat(lab[1]);
+ const gray = Math.round((L / 100) * 255);
+ return { r: gray, g: gray, b: gray, a: 1 };
+ }
+ return null;
+ };
+ const shellRgb = parse(shellBg);
+ const blockRgb = parse(blockBg);
+
+ // Per-channel absolute deltas. The visible "wrong-theme" pop in
+ // the QA evidence is driven by channel mismatch — a black-on-
+ // white block inside a dark shell will diverge by ~240 on every
+ // channel, while a properly themed block (any reasonable shade
+ // the design system picks) stays close to the shell.
+ const channelDeltas =
+ shellRgb && blockRgb
+ ? {
+ r: Math.abs(shellRgb.r - blockRgb.r),
+ g: Math.abs(shellRgb.g - blockRgb.g),
+ b: Math.abs(shellRgb.b - blockRgb.b),
+ }
+ : null;
+ return {
+ shellBg,
+ blockBg,
+ channelDeltas,
+ maxChannelDelta: channelDeltas
+ ? Math.max(channelDeltas.r, channelDeltas.g, channelDeltas.b)
+ : null,
+ blockClassName: blockCard.className,
+ };
+ });
+
+ expect(
+ sample.maxChannelDelta,
+ `must locate both shell and block to compare colors ` +
+ `(shell="${sample.shellBg}", block="${sample.blockBg}")`,
+ ).not.toBeNull();
+
+ // Bug-defining assertion: the vertical block's background must
+ // visually harmonize with the admin shell — same broad theme
+ // family, not the inverse. We don't pin "dark" as an absolute
+ // RGB threshold; the design system might pick any reasonable
+ // shade for the fix. What we DO require is low contrast against
+ // the shell.
+ //
+ // Threshold 100 (per channel) is generous: bg-control-bg vs
+ // bg-dark-bg differs by ~240 on every channel, while a properly
+ // themed block (e.g., a bg-dark-block one shade lighter than the
+ // shell, or a translucent overlay) stays well under 100.
+ expect(
+ sample.maxChannelDelta!,
+ `vertical block must visually harmonize with the admin shell ` +
+ `(shell="${sample.shellBg}", block="${sample.blockBg}", ` +
+ `per-channel deltas=${JSON.stringify(sample.channelDeltas)}) — ` +
+ `max channel difference of ${sample.maxChannelDelta} suggests the ` +
+ `block dropped out of the dark theme`,
+ ).toBeLessThan(100);
+ });
+});
+
+test.describe("Wrench button is visible for admin users on a connected worksheet", () => {
+ // AdminModeButton renders only when allowAdmin && tab.mode ===
+ // "WORKSHEET" (AdminModeButton.tsx). For the demo admin user with
+ // a real DB connection, the button must be present and enabled.
+
+ test("admin user on a connected DB sees an enabled wrench", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ await expect(sqlEditor.adminModeButton).toBeVisible({ timeout: 10_000 });
+ await expect(sqlEditor.adminModeButton).toBeEnabled();
+ });
+});
+
+test.describe("Wrench is not clickable when no database is connected", () => {
+ // The user contract: you can't enter admin mode without picking a
+ // DB first. AdminModeButton.tsx implements this two ways depending
+ // on context — it returns `null` when there's no current tab, and
+ // it renders `disabled` when the tab is in WORKSHEET mode but
+ // `tabStore.isDisconnected`. Either is a valid "not clickable"
+ // state; both satisfy the contract.
+
+ test("opening the SQL editor without a DB leaves the wrench unusable", async () => {
+ test.setTimeout(120_000);
+
+ await sqlEditor.gotoHome();
+ await page.waitForTimeout(800);
+
+ const visible = await sqlEditor.adminModeButton
+ .isVisible()
+ .catch(() => false);
+ if (visible) {
+ // Visible-but-disabled flavor (tab exists, no connection).
+ await expect(sqlEditor.adminModeButton).toBeDisabled();
+ } else {
+ // Hidden flavor (no current tab → AdminModeButton returns null).
+ await expect(sqlEditor.adminModeButton).toHaveCount(0);
+ }
+ });
+});
+
+test.describe("Clicking the wrench enters the admin terminal", () => {
+ // After the click, the editor swaps from WORKSHEET to ADMIN mode.
+ // TerminalPanel mounts in place of the standard editor — the dark
+ // shell (.bg-dark-bg) and the "SQL>" prompt are the visible
+ // signals. The "Exit admin mode" toolbar button also appears.
+
+ test("admin terminal mounts with dark shell and SQL> prompt", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ await expect(sqlEditor.adminModeButton).toBeVisible({ timeout: 10_000 });
+ await sqlEditor.adminModeButton.click();
+ await page.waitForTimeout(800);
+
+ await expect(page.locator(".bg-dark-bg").first()).toBeVisible({ timeout: 10_000 });
+ // The CompactSQLEditor renders "SQL>" as a sibling line-decoration.
+ await expect(page.getByText(/SQL>/).first()).toBeVisible({ timeout: 5000 });
+ await expect(
+ page.getByRole("button", { name: "Exit admin mode", exact: true }),
+ ).toBeVisible({ timeout: 5000 });
+ });
+});
+
+test.describe("Running SELECT 42 in the admin terminal returns a 1-row result", () => {
+ // After entering admin mode, the user types SQL into the bottom
+ // CompactSQLEditor and presses Enter (when the statement ends with
+ // `;`) — the terminal executes against the ADMIN data source and
+ // appends a result panel above the prompt. We verify a 1-row
+ // result with the literal "42".
+
+ test("Enter on a `;`-terminated statement executes and shows the row", 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.adminModeButton.click();
+ await page.waitForTimeout(800);
+
+ await runInAdminTerminal("SELECT 42 AS answer;");
+
+ // Result panel renders with the literal "42".
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 15_000,
+ });
+ await expect(
+ page.locator('[data-row-index="0"] [data-col-index="1"]'),
+ ).toContainText("42", { timeout: 5000 });
+ });
+});
+
+test.describe("Exit admin mode returns to the worksheet view", () => {
+ // The "Exit admin mode" button in the admin toolbar swaps the tab
+ // back to WORKSHEET. The dark terminal goes away; the standard
+ // worksheet editor (`role="code"` Monaco) is the visible surface
+ // again.
+
+ test("clicking Exit admin mode dismounts the terminal", 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.adminModeButton.click();
+ await page.waitForTimeout(800);
+ await expect(page.locator(".bg-dark-bg").first()).toBeVisible({ timeout: 10_000 });
+
+ const exitBtn = page.getByRole("button", {
+ name: "Exit admin mode",
+ exact: true,
+ });
+ await exitBtn.click();
+ await page.waitForTimeout(800);
+
+ // Dark shell unmounts. (TerminalPanel renders TWO bg-dark-bg
+ // descendants — the outer wrapper and the inner scroll area.
+ // Both must vanish, so we check count rather than .first().)
+ await expect(page.locator(".bg-dark-bg")).toHaveCount(0);
+ // Wrench is back (worksheet mode) and enabled (still connected).
+ await expect(sqlEditor.adminModeButton).toBeVisible({ timeout: 5000 });
+ await expect(sqlEditor.adminModeButton).toBeEnabled();
+ });
+});
+
+// Helpers shared by the arrow-key history tests below. Each one drives
+// the LAST role="code" Monaco (the editable prompt — older terminal rows
+// are read-only) the same way `setEditorContent` would on a worksheet,
+// but explicitly targets `.last()`.
+async function runInAdminTerminal(statement: string): Promise<void> {
+ // The admin terminal's editable prompt is the LAST role="code" Monaco
+ // (older rows are read-only). setEditorContent({ which: "last" }) runs the
+ // click → select-all → delete → insert sequence; we add the Enter.
+ await sqlEditor.setEditorContent(statement, { which: "last" });
+ await page.waitForTimeout(150);
+ await sqlEditor.codeEditor.last().press("Enter");
+}
+
+// Read the current statement out of the LAST Monaco (the editable prompt).
+async function readAdminPromptValue(): Promise<string> {
+ return await sqlEditor.readEditorContent({ which: "last" });
+}
+
+test.describe("Up/down arrow keys scroll the admin terminal's query history", () => {
+ // CUJ (Batch 7 addition): the admin-mode terminal is meant to behave
+ // like a real CLI — after a few queries you should be able to press
+ // Up to recall the last command, Up again to step further back, and
+ // Down to come forward to a fresh prompt.
+ //
+ // Wiring (CompactSQLEditor.tsx + useHistory.ts):
+ // - Up arrow runs `onHistory("up", editor)` when the editor is
+ // focused (Monaco `addCommand` precondition).
+ // - Down arrow runs `onHistory("down", editor)` when the cursor is
+ // on the last line.
+ // - `useHistory.move()` writes the recalled statement back into the
+ // live tail item's `statement` field, which the React tree binds
+ // 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.
+ //
+ // 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.
+ //
+ // 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.)
+
+ test.beforeEach(async () => {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+ await sqlEditor.adminModeButton.click();
+ await page.waitForTimeout(800);
+ await expect(page.locator(".bg-dark-bg").first()).toBeVisible({
+ timeout: 10_000,
+ });
+ });
+
+ test.afterEach(async () => {
+ // Leave admin mode so the next test's beforeAll-shared page returns
+ // to a worksheet starting state. (Page is reused across tests in
+ // this file via the file-level `sharedContext` + `page`.)
+ const exitBtn = page.getByRole("button", {
+ name: "Exit admin mode",
+ exact: true,
+ });
+ if (await exitBtn.isVisible().catch(() => false)) {
+ await exitBtn.click();
+ await page.waitForTimeout(400);
+ }
+ });
+
+ 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.)
+ test.setTimeout(120_000);
+
+ // Establish a single executed statement so there is something to
+ // recall. After it finishes, the terminal appends a fresh IDLE
+ // prompt as the new editable row — the editor is empty there.
+ const stmt = "SELECT 11 AS recall_target;";
+ await runInAdminTerminal(stmt);
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 15_000,
+ });
+
+ // Focus the new (empty) prompt and press Up.
+ const prompt = sqlEditor.codeEditor.last();
+ await prompt.click();
+ await page.waitForTimeout(150);
+ expect(await readAdminPromptValue()).toBe("");
+
+ await page.keyboard.press("ArrowUp");
+ await page.waitForTimeout(200);
+
+ // CUJ assertion: the prompt now holds the previously executed
+ // statement, ready to re-run.
+ expect(await readAdminPromptValue()).toBe(stmt);
+
+ // Visual-contrast guard: the recalled text must render in a color
+ // that's distinguishable from the terminal's dark background. A
+ // user reported on 2026-05-25 that on their build the recall
+ // looked broken — they suspected the text might be the same color
+ // as the bg. We pin that case shut: every visible token on the
+ // recalled line must be at least 60 channels away from the shell
+ // background. (Verified channel deltas were ≥176 on the working
+ // build, so 60 is generous headroom while still failing loudly if
+ // a future theme regression matches text to bg.)
+ const contrast = await page.evaluate(() => {
+ const parse = (s: string) => {
+ const m = s.match(/rgba?\(([^)]+)\)/);
+ if (!m) return null;
+ const [r, g, b] = m[1].split(",").map((v) => parseFloat(v.trim()));
+ return { r, g, b };
+ };
+ const codes = document.querySelectorAll('[role="code"]');
+ const last = codes[codes.length - 1];
+ const line = last?.querySelector(".view-lines .view-line");
+ const shell = document.querySelector(".bg-dark-bg");
+ if (!line || !shell)
+ return { reason: "missing line or shell" } as { reason: string };
+ const shellRgb = parse(getComputedStyle(shell).backgroundColor);
+ const tokens = Array.from(line.querySelectorAll("span")).filter(
+ (s) =>
+ s.children.length === 0 && (s.textContent ?? "").trim().length > 0,
+ );
+ let minDelta = Infinity;
+ let worst = "";
+ for (const t of tokens) {
+ const rgb = parse(getComputedStyle(t).color);
+ if (!rgb || !shellRgb) continue;
+ const d = Math.max(
+ Math.abs(rgb.r - shellRgb.r),
+ Math.abs(rgb.g - shellRgb.g),
+ Math.abs(rgb.b - shellRgb.b),
+ );
+ if (d < minDelta) {
+ minDelta = d;
+ worst = `"${t.textContent}" @ ${getComputedStyle(t).color}`;
+ }
+ }
+ return { minDelta, worst };
+ });
+ expect(
+ "reason" in contrast ? Infinity : contrast.minDelta,
+ `recalled text must contrast with the dark terminal shell ` +
+ `(worst token: ${"worst" in contrast ? contrast.worst : "n/a"})`,
+ ).toBeGreaterThan(60);
+ });
+
+ test("Down arrow after Up returns the prompt to empty", async () => {
+ // BYT-9560 (single-step Down-after-Up) is FIXED — the prior `test.fail()`
+ // hold flipped to passing, so this runs as a normal regression lock now.
+ test.setTimeout(120_000);
+
+ const stmt = "SELECT 22 AS down_target;";
+ await runInAdminTerminal(stmt);
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 15_000,
+ });
+
+ const prompt = sqlEditor.codeEditor.last();
+ await prompt.click();
+ await page.waitForTimeout(150);
+
+ await page.keyboard.press("ArrowUp");
+ await page.waitForTimeout(200);
+ expect(await readAdminPromptValue()).toBe(stmt);
+
+ // `useHistory.move("down")` resets `tail.statement` to "" when the
+ // index reaches the tail (length-1). The user-visible effect is
+ // that pressing Down returns to a fresh prompt.
+ await page.keyboard.press("ArrowDown");
+ await page.waitForTimeout(200);
+ 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.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.
+ 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 page.waitForTimeout(400);
+ }
+
+ const prompt = sqlEditor.codeEditor.last();
+ await prompt.click();
+ 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);
+
+ // Press Down once → should advance forward to `second`.
+ await page.keyboard.press("ArrowDown");
+ await page.waitForTimeout(200);
+ expect(await readAdminPromptValue()).toBe(second);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts
new file mode 100644
index 0000000000..67b77deb68
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-batch.spec.ts
@@ -0,0 +1,327 @@
+// SQL Editor — multi-DB / batch query behaviors (subset of Batch 11).
+//
+// Covers (this iteration):
+// - C4 switch-DB no-remount — switching the active tab's connection
+// via the breadcrumb preserves Monaco's editor content; the tab is
+// re-pointed, not re-created.
+// - C8 multi-member DatabaseGroup renders in the connection panel
+// under the "Database Group" tab.
+// - C9 single-member DatabaseGroup also renders (groups with one
+// match are not collapsed into the regular Databases tab).
+// - D4 batch query result tabs — one tab per group member after Run.
+// - D10 batch export — "Batch export" button opens a multi-DB export
+// drawer.
+// - C15 FlatTableList — once a database exceeds the 1000-table
+// threshold, SchemaPane switches to a flat list of `.bb-flat-table-row`
+// rows (search-only, no tree).
+//
+// Deferred (need fixture/harness work):
+// - D16 NoSQL MongoDB JSON view — blocked on the engine matrix
+// (Batch 10) work; the disposable server only ships PG.
+
+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 { getInstancePgPort, execSql } from "../framework/psql";
+import { SqlEditorPage } from "./sql-editor.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Switching DB connection preserves editor content (C4)", () => {
+ // The disposable server provisions two HR sample databases (hr_prod
+ // on prod-sample-instance, hr_test on test-sample-instance). We use
+ // whichever DB env.database resolved to as the source and pick the
+ // other as the target — the contract is engine-/instance-agnostic.
+
+ test("typing into Monaco then switching DBs keeps the SQL body intact", async () => {
+ const sourceShort = env.databaseId;
+ const targetShort = sourceShort === "hr_prod" ? "hr_test" : "hr_prod";
+
+ const target = await env.api.findDatabaseByShortName(targetShort);
+ test.skip(
+ !target,
+ `target DB ${targetShort} not present — needs both hr_prod and hr_test`,
+ );
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // Type a unique marker statement. The unique suffix lets us anchor
+ // a getByText locator without false positives from other tests'
+ // residue in the same browser context.
+ const STAMP = `e2e_switch_${Date.now()}`;
+ const MARKER = `SELECT 1 AS ${STAMP};`;
+ await sqlEditor.setEditorContent(MARKER);
+ await page.waitForTimeout(300);
+
+ // Sanity: the marker is in Monaco. readEditorContent walks the DOM
+ // `.view-line`s ("longest" pane); `window.monaco` is not exposed on
+ // the React bundle. Single-line content is fully in the DOM.
+ expect(
+ await sqlEditor.readEditorContent({ which: "longest" }),
+ ).toBe(MARKER);
+
+ // Open the breadcrumb connection panel, click the target DB row.
+ const breadcrumb = page
+ .locator("button")
+ .filter({ hasText: sourceShort })
+ .first();
+ await expect(breadcrumb).toBeVisible({ timeout: 10_000 });
+ await breadcrumb.click();
+
+ const connectionPanel = page.getByRole("dialog");
+ await expect(connectionPanel).toBeVisible({ timeout: 5_000 });
+ const targetRow = connectionPanel
+ .getByText(targetShort, { exact: true })
+ .first();
+ await expect(targetRow).toBeVisible({ timeout: 10_000 });
+ await targetRow.click();
+
+ // Wait for the breadcrumb to reflect the new connection — the
+ // signal that the connection switch actually applied to the tab.
+ await expect(
+ page.locator("button").filter({ hasText: targetShort }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await page.waitForTimeout(500);
+
+ // C4: editor content survives the switch (tab was re-pointed,
+ // not re-mounted).
+ expect(
+ await sqlEditor.readEditorContent({ which: "longest" }),
+ "switching the active tab's DB connection must NOT remount Monaco — content stays",
+ ).toBe(MARKER);
+ });
+});
+
+// DatabaseGroup tests (C8/C9). Groups are project-scoped CEL-condition
+// matchers — a group with `database_name.startsWith("hr_")` covers both
+// hr_test and hr_prod (multi-member); `database_name == "hr_prod"`
+// covers exactly one (single-member). Both should appear in the
+// connection panel's "Database Group" tab regardless of match count.
+test.describe("Connection panel Database Group tab (C8/C9)", () => {
+ let multiGroup = "";
+ let singleGroup = "";
+
+ test.beforeAll(async () => {
+ // C8/C9 exercise DatabaseGroups (FEATURE_DATABASE_GROUPS), which is
+ // enterprise-only. The license is installed at bootstrap, so the feature is available.
+ const ts = Date.now();
+ const multi = await env.api.createDatabaseGroup(
+ env.project,
+ `e2e-multi-${ts}`,
+ `E2E Multi ${ts}`,
+ // hr_test + hr_prod both start with "hr_"
+ 'resource.database_name.startsWith("hr_")',
+ );
+ multiGroup = multi.name;
+
+ const single = await env.api.createDatabaseGroup(
+ env.project,
+ `e2e-single-${ts}`,
+ `E2E Single ${ts}`,
+ `resource.database_name == "${env.databaseId}"`,
+ );
+ singleGroup = single.name;
+ });
+
+ test.afterAll(async () => {
+ if (multiGroup) await env.api.deleteDatabaseGroup(multiGroup);
+ if (singleGroup) await env.api.deleteDatabaseGroup(singleGroup);
+ });
+
+ // Helper — open the SQL editor on env.database, then click the
+ // breadcrumb to open the connection panel and switch to the Database
+ // Group tab. Returns the panel dialog locator scoped to the tab
+ // content.
+ async function openDatabaseGroupTab() {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(500);
+
+ const breadcrumb = page
+ .locator("button")
+ .filter({ hasText: env.databaseId })
+ .first();
+ await expect(breadcrumb).toBeVisible({ timeout: 10_000 });
+ await breadcrumb.click();
+
+ const panel = page.getByRole("dialog");
+ await expect(panel).toBeVisible({ timeout: 5_000 });
+ await panel
+ .getByRole("tab", { name: "Database Group", exact: true })
+ .click();
+ await page.waitForTimeout(500);
+ return panel;
+ }
+
+ test("multi-member group renders in the Database Group tab (C8)", async () => {
+ const panel = await openDatabaseGroupTab();
+ // Group title was set to `E2E Multi <ts>`. Match by the stable
+ // prefix so timestamp differences across runs don't matter.
+ await expect(
+ panel.getByText(/E2E Multi/).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ test("single-member group renders in the Database Group tab (C9)", async () => {
+ const panel = await openDatabaseGroupTab();
+ await expect(
+ panel.getByText(/E2E Single/).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ // D4 — Running a query against a multi-member DBGroup produces one
+ // result tab per member database (BatchQuerySelect renders the tab
+ // strip above the result panel). The "E2E Multi" group covers both
+ // hr_test and hr_prod, so we expect ≥ 2 tabs after Run.
+ test("multi-member group runs as batch query and renders one tab per database (D4)", async () => {
+ const panel = await openDatabaseGroupTab();
+ const groupRow = panel.getByText(/E2E Multi/).first();
+ await expect(groupRow).toBeVisible({ timeout: 10_000 });
+ await groupRow.click();
+ // Panel auto-closes after selection; give the tab store a moment to
+ // attach the multi-database context.
+ await page.waitForTimeout(800);
+
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+
+ // BatchQuerySelect rendering signal: the "Batch export" button is
+ // present alongside one button per queried database. The DB tabs
+ // are plain <button name="hr_prod"> elements (the breadcrumb's
+ // button is "Prod Prod Sample Instance hr_prod", so exact match
+ // disambiguates).
+ await expect(
+ page.getByRole("button", { name: /Batch export/i }).first(),
+ ).toBeVisible({ timeout: 15_000 });
+ await expect(
+ page.getByRole("button", { name: "hr_prod", exact: true }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ await expect(
+ page.getByRole("button", { name: "hr_test", exact: true }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+
+ // D10 — Clicking "Batch export" after a batch query opens an export
+ // drawer that lets the user pick a format and trigger a multi-DB
+ // export. We assert only the drawer opens with the expected sections
+ // (Databases / Statement / Format); the actual download mechanics
+ // live in a separate codepath best exercised by a unit test.
+ test("Batch export button opens the multi-DB export drawer (D10)", async () => {
+ const panel = await openDatabaseGroupTab();
+ await panel.getByText(/E2E Multi/).first().click();
+ await page.waitForTimeout(800);
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+
+ const batchExportBtn = page
+ .getByRole("button", { name: /Batch export/i })
+ .first();
+ await expect(batchExportBtn).toBeVisible({ timeout: 15_000 });
+ await batchExportBtn.click();
+
+ // The drawer header carries the export action's title; the
+ // standard DataExportButton drawer uses "Export Data" (i18n key
+ // `export-data.export-data`).
+ const drawer = page.getByRole("dialog").last();
+ await expect(
+ drawer.getByText(/Export\s+Data/i).first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ // The drawer's "Select database" table lists both queried DBs as
+ // selectable rows — scope to the drawer so we skip hidden debug
+ // <li> elements elsewhere on the page that contain the DB name.
+ await expect(
+ drawer.getByRole("cell", { name: "hr_prod", exact: true }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ await expect(
+ drawer.getByRole("cell", { name: "hr_test", exact: true }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+});
+
+// C15 — Once a database has more than FLAT_TABLE_THRESHOLD (=1000)
+// tables, SchemaPane swaps the hierarchical tree for FlatTableList
+// (search-only, virtualized rows with the `bb-flat-table-row` class).
+// We create a dedicated schema with 1001 tables via a single psql
+// DO-loop (fast — single round-trip), sync the database so Bytebase's
+// catalog picks them up, then assert the flat layout renders.
+test.describe("Schema pane switches to FlatTableList above 1000 tables (C15)", () => {
+ const TEST_SCHEMA = "e2e_c15";
+ const TABLE_COUNT = 1001;
+
+ test.beforeAll(async () => {
+ const port = await getInstancePgPort(env);
+ // Drop any leftover schema from a previous run, then create the
+ // schema + 1001 tables in a single round-trip via a DO block.
+ execSql(env.databaseId, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);
+ execSql(env.databaseId, port, `CREATE SCHEMA ${TEST_SCHEMA}`);
+ execSql(
+ env.databaseId,
+ port,
+ `DO $$
+ BEGIN
+ FOR i IN 1..${TABLE_COUNT} LOOP
+ EXECUTE format('CREATE TABLE ${TEST_SCHEMA}.t_%s (id INT)', i);
+ END LOOP;
+ END $$;`,
+ );
+ // Force Bytebase to rescan so its in-memory schema metadata
+ // reflects the 1001 new tables.
+ await env.api.syncDatabase(env.database);
+ });
+
+ test.afterAll(async () => {
+ try {
+ const port = await getInstancePgPort(env);
+ execSql(env.databaseId, port, `DROP SCHEMA IF EXISTS ${TEST_SCHEMA} CASCADE`);
+ // Re-sync so other specs running later don't see ghost tables in
+ // Bytebase's cached metadata.
+ await env.api.syncDatabase(env.database);
+ } catch (err) {
+ // Server may have been torn down by globalTeardown.
+ console.warn(`C15 afterAll cleanup: ${err instanceof Error ? err.message : err}`);
+ }
+ });
+
+ test("FlatTableList renders once table count exceeds 1000", async () => {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await sqlEditor.gutterSchemaTab.click();
+ // The schema fetch is async; the flat list mounts only after
+ // metadata loads with > 1000 tables.
+ await expect(
+ page.locator(".bb-flat-table-row").first(),
+ ).toBeVisible({ timeout: 30_000 });
+
+ // Searching by our test prefix narrows the list — verify one of
+ // our generated rows is reachable (anchors that flat-list search
+ // works, not just that any row exists).
+ const search = page.getByPlaceholder("Search").first();
+ await expect(search).toBeVisible({ timeout: 5_000 });
+ await search.fill("t_500");
+ await page.waitForTimeout(600); // debounced filter
+
+ // Search results show `<schema>.<table>` per row; matching the
+ // fully-qualified name avoids any false match on shorter substrings.
+ await expect(
+ page.locator(".bb-flat-table-row").filter({ hasText: `${TEST_SCHEMA}.t_500` }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts
new file mode 100644
index 0000000000..40d7edf0d8
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-connection.spec.ts
@@ -0,0 +1,240 @@
+// SQL Editor — connection lifecycle (CUJ coverage).
+//
+// Verifies the user-facing contracts of opening, restoring, and
+// switching SQL Editor connections. These are happy-path flows: each
+// test should PASS today, and a regression in routing / project
+// context / connection-panel state surfaces as a failure here.
+//
+// Scope: CUJs C1, C2, C3, C5, C13 from PHASE-4-PLAN.md (Batch 5,
+// Arc 1 — "Open + connect"). C6 schema dropdown and C7 BatchQuerySelect
+// are deferred to a follow-up extension of this file.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+import {
+ ensureSecondaryProject,
+ SECONDARY_PROJECT_TITLE,
+} from "../framework/seed-test-data";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Cold-open lands on the SQL Editor home view", () => {
+ // C1 — visiting /sql-editor with no project / sheet / database in
+ // the URL must render the editor shell (project picker visible,
+ // gutter rail visible) without a hard redirect or a blank page.
+ // The user opens the editor from the nav and expects to land in a
+ // usable state.
+
+ test("opens with project picker and gutter rail rendered", async () => {
+ test.setTimeout(120_000);
+
+ await sqlEditor.gotoHome();
+ await page.waitForTimeout(800);
+
+ // Project picker is rendered as a Combobox with `.project-select`.
+ // (AsidePanel.tsx mounts <ProjectSelect className="...project-select"/>.)
+ await expect(page.locator(".project-select").first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // Gutter rail buttons are stable user-facing labels (Worksheet /
+ // Schema / History gutter tabs).
+ await expect(sqlEditor.gutterWorksheetTab).toBeVisible();
+ await expect(sqlEditor.gutterSchemaTab).toBeVisible();
+ await expect(sqlEditor.gutterHistoryTab).toBeVisible();
+
+ // The URL is either the home route or auto-redirected to a default
+ // project (whichever the SQL editor's bootstrap picked) — not a
+ // last-visited deep link the user can't recognize. Both shapes are
+ // user-recoverable; what matters is that we landed inside
+ // /sql-editor and not somewhere else (404, /auth, /settings).
+ expect(page.url()).toMatch(/\/sql-editor(\/projects\/[^/]+)?\/?$/);
+ });
+});
+
+test.describe("Opening a worksheet by UUID restores its title in a tab", () => {
+ // C2 — deep-linking into /projects/<p>/sheets/<uuid> must hydrate
+ // the worksheet and render its title as the active tab. This is the
+ // shareable-link contract: a URL pasted from chat / the Recent menu
+ // must reproducibly land the user on that worksheet.
+
+ const SOURCE_TITLE = `e2e-cuj-c2-${Date.now()}`;
+ const SOURCE_CONTENT = "SELECT 1;";
+
+ let sourceWorksheet = "";
+
+ test.beforeAll(async () => {
+ const created = await env.api.createWorksheet(
+ env.project,
+ SOURCE_TITLE,
+ env.database,
+ SOURCE_CONTENT,
+ );
+ sourceWorksheet = created.name;
+ });
+
+ test.afterAll(async () => {
+ if (sourceWorksheet) await env.api.deleteWorksheet(sourceWorksheet);
+ });
+
+ test("active tab text matches the worksheet title after deep-link", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ const sheetUuid = sourceWorksheet.split("/").pop()!;
+ await sqlEditor.gotoSheet(projectId, sheetUuid);
+ await page.waitForTimeout(1500);
+
+ await expect(sqlEditor.activeTab()).toContainText(SOURCE_TITLE, {
+ timeout: 10_000,
+ });
+ });
+});
+
+test.describe("Instance-only URL lands without a connected database", () => {
+ // C3 — visiting /projects/<p>/instances/<i> (no /databases/<db>) is
+ // a partial connection: the user picked an instance but hasn't
+ // chosen a database yet. The breadcrumb should show "Select a
+ // database to start" rather than acting as if the user is connected.
+
+ test('breadcrumb shows the "select a database" prompt', async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await page.goto(
+ `${env.baseURL}/sql-editor/projects/${projectId}/instances/${env.instanceId}`,
+ );
+ await page.waitForTimeout(1500);
+
+ // DatabaseChooser renders `t("sql-editor.select-a-database-to-start")`
+ // when the connection has an instance but no database. We anchor by
+ // the visible label to keep the test resilient to translation
+ // refactors that don't change the user-facing copy.
+ await expect(
+ page.getByText("Select a database to start", { exact: true }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+});
+
+test.describe("Project switcher updates the editor's project context", () => {
+ // C5 — choosing a different project from the picker must update the
+ // editor's project context (URL changes to /projects/<newProj>) so
+ // the sidebar tree, schema panel, and worksheet list all refresh
+ // against the new project's databases.
+ //
+ // The post-demo bootstrap (#20393) only creates one sample project
+ // ("Sample Project" / `project-sample`); the switcher needs a SECOND
+ // project to be a meaningful test. We provision it on-demand here
+ // (NOT in the global seedTestData) so that adding a second project
+ // doesn't shift the SQL editor's default landing project for other
+ // specs (e.g. sql-editor-worksheet.spec.ts uses gotoHome() and
+ // assumes `project-sample` is current).
+
+ test.beforeAll(async () => {
+ // Created on demand and intentionally NOT deleted afterward.
+ // ensureSecondaryProject is idempotent (tolerates 409) and the disposable
+ // server is fresh per run. A soft delete would reserve the resource ID,
+ // and a Playwright CI retry reuses the SAME server — the swallowed-409
+ // recreate would then leave the switcher with no visible second project.
+ // Leaving it in place is retry-stable; no later spec enumerates projects.
+ await ensureSecondaryProject(env.api);
+ });
+
+ test("picking a different project switches the editor's project context", async () => {
+ test.setTimeout(120_000);
+
+ // Navigate to the discovered project explicitly (not gotoHome) so
+ // the test starts in a deterministic place even after the
+ // secondary project briefly becomes the default-landing target.
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // The Combobox primitive (combobox.tsx) renders the trigger as a
+ // bare <div> with onClick — no implicit role="combobox". We click
+ // the wrapper directly. Options inside the dropdown are <button>
+ // elements containing the project label text.
+ const projectSelectTrigger = page.locator(".project-select").first();
+ await expect(projectSelectTrigger).toBeVisible({ timeout: 10_000 });
+
+ // Pick the secondary project — different from the env default.
+ await projectSelectTrigger.click();
+ // Each project option's accessible name combines label + slug
+ // (e.g., "Sample Project project-sample"), so `exact: true` on
+ // the label alone won't match. We match the button containing the
+ // label as visible text — narrower than role-only and still
+ // resilient to slug renames.
+ const option = page
+ .getByRole("button")
+ .filter({ hasText: SECONDARY_PROJECT_TITLE })
+ .first();
+ await expect(option).toBeVisible({ timeout: 5000 });
+ await option.click();
+
+ // The editor's project context switches to the picked project — the
+ // project-select trigger now displays it. (The SQL-editor route is
+ // database-centric: the URL's project segment only changes once a
+ // database in the new project is opened, so an empty project like the
+ // secondary one keeps the prior DB URL while the context switches.)
+ await expect(projectSelectTrigger).toContainText(SECONDARY_PROJECT_TITLE, {
+ timeout: 10_000,
+ });
+ });
+});
+
+test.describe("Connection panel exposes Databases + Database Group tabs", () => {
+ // C13 — clicking the breadcrumb opens a connection-panel Sheet that
+ // lets the user pick from a database tree (Databases tab) OR a
+ // saved database group (Database Group tab). Both tabs must be
+ // present so the user can route the active tab to either kind of
+ // target.
+
+ test("both tabs render after opening the connection panel", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // Click the breadcrumb to open the connection panel. The
+ // breadcrumb currently shows the env / instance / db chain; we
+ // anchor by the database short name (env.databaseId) which the
+ // chooser renders verbatim.
+ const breadcrumb = page
+ .locator("button")
+ .filter({ hasText: env.databaseId })
+ .first();
+ await expect(breadcrumb).toBeVisible({ timeout: 10_000 });
+ await breadcrumb.click();
+
+ const connectionPanel = page.getByRole("dialog");
+ await expect(connectionPanel).toBeVisible({ timeout: 5000 });
+
+ await expect(
+ connectionPanel.getByRole("tab", { name: "Databases", exact: true }),
+ ).toBeVisible({ timeout: 5000 });
+ await expect(
+ connectionPanel.getByRole("tab", {
+ name: "Database Group",
+ exact: true,
+ }),
+ ).toBeVisible({ timeout: 5000 });
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-history.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-history.spec.ts
new file mode 100644
index 0000000000..41c4fd2260
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-history.spec.ts
@@ -0,0 +1,90 @@
+// SQL Editor — query history sidebar.
+//
+// Covers the History gutter pane's contract: the visible history list
+// must reflect persisted history, and running a new query must NOT
+// nuke the rendered list (the list either keeps the prior entries or
+// updates to include the new one).
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Running a query preserves the History sidebar list", () => {
+ // BYT-9495: when the user has the History gutter pane open and runs a
+ // query, the history list immediately empties to the "No history
+ // found" placeholder, even though the underlying data is intact (a
+ // page reload restores the list). Caused by the post-run query
+ // history fetch racing with the panel's own fetch and clobbering its
+ // local list state.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r41-byt9495-history-nuked/
+ // - 01-history-tab-before-run.png (list populated)
+ // - 02-history-tab-after-run.png (list shows "No history found")
+ // - 03-history-tab-after-reload-restored.png (data is intact)
+
+ test("history list keeps showing entries after a query runs", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+
+ // Run an initial query so there's at least one history entry to
+ // observe. Disposable test servers start with an empty history list,
+ // so we cannot rely on demo-seeded entries.
+ await sqlEditor.runQuery("SELECT 1;");
+ await page.waitForTimeout(500);
+
+ // Open the History gutter pane.
+ await sqlEditor.gutterHistoryTab.click();
+ // Wait for the panel to fetch + render the entry we just created.
+ // HistoryPane.tsx renders each entry as a [data-history-row] div.
+ const historyRows = page.locator("[data-history-row]");
+ await expect(historyRows.first()).toBeVisible({ timeout: 10_000 });
+ const initialCount = await historyRows.count();
+ expect(
+ initialCount,
+ "history pane should show at least one entry after the first run",
+ ).toBeGreaterThanOrEqual(1);
+
+ // The bug repro: with the History pane open, run another query.
+ // The pane's local state should incorporate the new entry — not
+ // collapse to the empty-state placeholder.
+ await sqlEditor.runQuery("SELECT 2;");
+ await page.waitForTimeout(1500);
+
+ // Bug-defining assertion: the empty-state placeholder must NOT be
+ // showing. With the bug present, the placeholder text appears even
+ // though the second query's history entry was persisted server-side.
+ await expect(
+ page.getByText("No history found", { exact: true }),
+ "history pane must not collapse to empty state after running a query",
+ ).toHaveCount(0);
+
+ // Stronger assertion: the rendered list must contain at least the
+ // entries we have a right to expect (≥ 1). The fix may dedupe or
+ // reorder entries; we don't pin the exact count.
+ const finalCount = await historyRows.count();
+ expect(
+ finalCount,
+ "history pane must keep rendering entries after running a query",
+ ).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts
new file mode 100644
index 0000000000..64b5df5a0d
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-jit.spec.ts
@@ -0,0 +1,263 @@
+// SQL Editor — JIT access flow (Batch 8, L-series + H1 CUJs).
+//
+// Covers:
+// - L1 / L2 RequestQueryButton label switches to "Request just-in-time
+// access" when project.allowJustInTimeAccess is on AND the missing
+// permission is exactly bb.sql.select (the JIT path).
+// - L4 ACCESS pane shows the "Request access" CTA when JIT is enabled.
+// - L5 AccessGrantRequestDrawer renders Databases / Statement / Expiration
+// / Reason fields when opened from the pane.
+// - L6 ACCESS gutter tab appears only while JIT is on.
+// - H1 Gutter tab count flips between 3 (no JIT) and 4 (with JIT).
+//
+// Deferred (out of this batch):
+// - L3 full JIT Unmask flow — request → admin approve → re-run.
+// Requires a multi-actor handoff (requestor user creates grant,
+// admin user approves, requestor re-runs and sees unmasked data),
+// plus seeded masked columns. Worth its own spec; punted to a
+// later session.
+// - L7 MaskingReasonPopover — requires the demo to ship a column
+// with a non-empty maskingReason; the discovered Postgres project
+// in this branch's demo does not have one out of the box. Will
+// pair with L3 when masking-test data is set up.
+
+import {
+ test,
+ expect,
+ 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";
+import { SqlEditorPage } from "./sql-editor.page";
+
+test.setTimeout(180_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+
+// Single test user — projectViewer on env.project, so they can mount
+// the editor but lack bb.sql.select. The JIT switch on the project
+// toggles whether their Request-button reads as JIT or non-JIT.
+//
+// We use a fresh, file-scoped user so we don't have to coordinate with
+// sql-editor-permissions.spec.ts (which manages its own e2e users).
+const TEST_PASSWORD = "e2e-jit-pw-1!"; // NOSONAR — e2e fixture only
+const VIEWER_USER = {
+ email: "[email protected]",
+ title: "E2E JIT Viewer",
+ authFile: ".auth/jit-viewer.json",
+};
+
+let viewerCtx: BrowserContext;
+let viewerPage: Page;
+let viewerEditor: SqlEditorPage;
+
+// Admin-side context used to flip allowJustInTimeAccess between
+// describe blocks. We keep one shared admin page for screenshots in
+// case of debugging, but the JIT toggle itself goes through the API
+// client — flipping via UI would require a separate `/projects/<id>`
+// navigation that we can avoid.
+let adminCtx: BrowserContext;
+let adminPage: Page;
+
+async function setJIT(enabled: boolean): Promise<void> {
+ // Also set allowRequestRole=true: the JIT label tests below need a
+ // RequestQueryButton to render at all (the component returns null
+ // when allowRequestRole is false — see RequestQueryButton.tsx:131,
+ // 159-161). The new sample project is born with allowRequestRole=false;
+ // the JIT tests are about the LABEL flipping, not about whether the
+ // button shows up.
+ await env.api.updateProjectSettings(env.project, {
+ allowRequestRole: true,
+ allowJustInTimeAccess: enabled,
+ });
+ // Force-reload the viewer's page so the store picks up the new
+ // project flag. The SQL Editor caches project state per-tab; flipping
+ // the flag via API does not in-flight invalidate that cache.
+ await viewerEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await viewerPage.waitForTimeout(1500);
+}
+
+test.beforeAll(async ({ browser }) => {
+ test.setTimeout(180_000);
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Provision the test user — idempotent on 409 for Playwright retries.
+ try {
+ await env.api.createUser(VIEWER_USER.email, TEST_PASSWORD, VIEWER_USER.title);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (!msg.includes("(409)")) throw err;
+ }
+ await env.api.appendProjectBinding(
+ env.project,
+ "roles/projectViewer",
+ [`user:${VIEWER_USER.email}`],
+ );
+
+ await signInBrowserAs(
+ browser,
+ env.baseURL,
+ VIEWER_USER.email,
+ TEST_PASSWORD,
+ VIEWER_USER.authFile,
+ );
+ viewerCtx = await browser.newContext({ storageState: VIEWER_USER.authFile });
+ viewerPage = await viewerCtx.newPage();
+ viewerEditor = new SqlEditorPage(viewerPage, env.baseURL);
+
+ adminCtx = await browser.newContext({ storageState: ".auth/state.json" });
+ adminPage = await adminCtx.newPage();
+
+ // Start from a known-off JIT state so the test ordering is
+ // deterministic. Each describe block flips the flag explicitly.
+ await env.api.updateProjectSettings(env.project, {
+ allowJustInTimeAccess: false,
+ });
+});
+
+test.afterAll(async () => {
+ // Best-effort: turn JIT off (so other specs don't inherit the
+ // flipped state) and detach contexts. We deliberately DO NOT delete
+ // the test user — Playwright's worker semantics caused the
+ // file-level beforeAll to fire again between describe blocks in an
+ // earlier iteration, and after the first run deleting the user left the
+ // row in a "deactivated" state, which then blocked
+ // /v1/auth/login on the rerun ("user has been deactivated"). The
+ // disposable bytebase server is torn down by globalTeardown at the
+ // end of the run, so leaving the row in place is safe.
+ try {
+ await env.api.updateProjectSettings(env.project, {
+ allowRequestRole: false,
+ allowJustInTimeAccess: false,
+ });
+ } catch {
+ /* ignore */
+ }
+ await viewerCtx?.close();
+ await adminCtx?.close();
+});
+
+// L6 + H1 — the ACCESS gutter tab only renders when the project has
+// `allowJustInTimeAccess` enabled, so the gutter count flips between
+// 3 (Worksheet/Schema/History) and 4 (+ Access).
+test.describe("ACCESS gutter tab follows the project's allowJustInTimeAccess flag", () => {
+ test("with JIT off, the gutter has 3 tabs and no Access tab", async () => {
+ await setJIT(false);
+
+ await expect(viewerEditor.gutterWorksheetTab).toBeVisible({ timeout: 10_000 });
+ await expect(viewerEditor.gutterSchemaTab).toBeVisible();
+ await expect(viewerEditor.gutterHistoryTab).toBeVisible();
+ // ACCESS tab is conditionally rendered — must be absent here.
+ await expect(viewerEditor.gutterAccessTab).toHaveCount(0);
+ });
+
+ test("with JIT on, the gutter exposes an ACCESS tab in addition to the 3 defaults", async () => {
+ await setJIT(true);
+
+ await expect(viewerEditor.gutterWorksheetTab).toBeVisible({ timeout: 10_000 });
+ await expect(viewerEditor.gutterSchemaTab).toBeVisible();
+ await expect(viewerEditor.gutterHistoryTab).toBeVisible();
+ await expect(viewerEditor.gutterAccessTab).toBeVisible();
+ });
+});
+
+// L1 / L2 — RequestQueryButton's `useJIT` is true when
+// project.allowJustInTimeAccess is on AND the missing permissions are
+// exactly bb.sql.select. The visible label switches from
+// "Request query" to "Request just-in-time access" accordingly.
+test.describe("RequestQueryButton label tracks the project's JIT flag", () => {
+ test("with JIT off, running a forbidden SELECT shows the non-JIT 'Request query' CTA", async () => {
+ await setJIT(false);
+ await viewerEditor.runPreparedQuery("SELECT 1;");
+ await viewerPage.waitForTimeout(800);
+
+ await expect(
+ viewerPage.getByRole("button", { name: "Request query", exact: true }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await expect(
+ viewerPage.getByRole("button", { name: /Request just-in-time/i }),
+ ).toHaveCount(0);
+ });
+
+ test("with JIT on, running a forbidden SELECT shows the JIT 'Request just-in-time access' CTA", async () => {
+ await setJIT(true);
+ await viewerEditor.runPreparedQuery("SELECT 1;");
+ await viewerPage.waitForTimeout(800);
+
+ await expect(
+ viewerPage
+ .getByRole("button", { name: /Request just-in-time access/i })
+ .first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await expect(
+ viewerPage.getByRole("button", { name: "Request query", exact: true }),
+ ).toHaveCount(0);
+ });
+});
+
+// L4 + L5 — the ACCESS pane (visible only when JIT is on) renders a
+// "Request access" button at its top-right. Clicking it opens the
+// AccessGrantRequestDrawer with the four expected sections.
+//
+// REQUIRES ENTERPRISE LICENSE: the button is gated by
+// `disabled={!hasJITFeature || disabled}` in AccessPane.tsx — without
+// BYTEBASE_E2E_LICENSE, hasJITFeature is false and the click is a no-op
+// (Playwright's `force: true` bypasses actionability checks but does NOT
+// override the HTML `disabled` attribute, so onClick never fires and the
+// drawer never opens). The license is installed at bootstrap, so the feature is available here.
+test.describe("ACCESS pane Request-access button opens the grant drawer", () => {
+ test("opening the ACCESS tab and clicking Request access opens a drawer with Databases / Statement / Expiration / Reason", async () => {
+ await setJIT(true);
+
+ // Click the ACCESS gutter tab to mount the pane.
+ await viewerEditor.gutterAccessTab.click();
+ await viewerPage.waitForTimeout(500);
+
+ // The pane's primary action — label from
+ // `sql-editor.request-access` ("Request Access" in en-US).
+ const requestAccessBtn = viewerPage
+ .getByRole("button", { name: /Request Access/i })
+ .first();
+ await expect(requestAccessBtn).toBeVisible({ timeout: 10_000 });
+ // PermissionGuard renders the button as disabled when JIT feature
+ // is unlicensed. The demo build ships the feature on (sample data
+ // includes JIT grants), so we expect enabled — but assert via a
+ // try/catch fallback so a future license change doesn't bury the
+ // structural CUJ. The CUJ here is "the button is present and
+ // wired", which already shows that the pane is on the right
+ // surface.
+ await requestAccessBtn.click({ force: true });
+ await viewerPage.waitForTimeout(500);
+
+ // Drawer header — i18n key `sql-editor.request-data-access`.
+ await expect(
+ viewerPage.getByText("Request Data Access", { exact: true }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ // L5: the four labelled regions inside the drawer. Each is a
+ // headline above its input — we match the label as a substring
+ // because the rendered text is `<label>Databases *</label>` and
+ // similar (the trailing `*` is the required-field marker, not a
+ // separate element). Anchoring to the start of the line via a
+ // regex keeps the match unambiguous (matches "Databases *" or
+ // "Databases" alone, not "Some Databases List").
+ for (const label of ["Databases", "Statement", "Expiration", "Reason"]) {
+ const re = new RegExp(`^${label}(\\s*\\*)?\\s*$`);
+ await expect(
+ viewerPage.getByText(re).first(),
+ `drawer must contain a "${label}" section`,
+ ).toBeVisible({ timeout: 5000 });
+ }
+
+ // Close the drawer so any follow-up test doesn't inherit it.
+ // The drawer is dismissed by clicking outside (Base UI Sheet) or
+ // by an explicit Cancel — we use Escape which the Sheet honors.
+ await viewerPage.keyboard.press("Escape");
+ await viewerPage.waitForTimeout(300);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts
new file mode 100644
index 0000000000..fb2a510a66
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-misc.spec.ts
@@ -0,0 +1,161 @@
+// SQL Editor — misc shell behaviors (subset of Batch 9 AI/misc CUJs).
+//
+// Covers:
+// - H3 ?panel=<tab> URL query restores the aside panel on first load
+// (SQLEditorRouteShell.tsx:402 reads the param and overrides the
+// localStorage-persisted tab).
+// - H4 Clicking the gutter tabs switches the visible aside panel
+// (Worksheet ↔ Schema ↔ History).
+// - H5 The SQL editor's gutter logo opens in a new tab
+// (target=_blank + rel=noopener noreferrer) — GutterBar.tsx:49.
+// - O1 The QueryContextSettingPopover trigger ("(limit N)") is hidden
+// in admin mode — EditorAction.tsx:171 wraps it in a `!isAdminMode`
+// block.
+//
+// Deferred from Batch 9 (need separate iteration):
+// - K1/K2 AI Assistant menu + chat mocking.
+// - O2 popover content + O4 MaxRowCountSelect preset switching.
+// - H2 last-visited-tab localStorage (harder to isolate from the
+// framework's pinned project).
+// - N1 unsaved-leave guard, N5 welcome screen, N6 language submenu,
+// N10 quickstart non-blocking.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Aside panel URL restoration (H3)", () => {
+ // Locks `?panel=<tab>` deep-link restoration: landing on the SQL editor
+ // with `?panel=schema` must activate the Schema gutter panel rather than
+ // the persisted-default (WORKSHEET) tab. Restoration runs on the
+ // `project-context-ready` event in SQLEditorRouteShell.tsx. Previously
+ // skipped on a stale "fails under license" note; re-verified passing under
+ // an enterprise license both in isolation and in the full suite, so it now
+ // runs as a live regression lock. H4 below covers the gutter-click path.
+ test("?panel=schema activates the Schema gutter tab on first load", async () => {
+ const projectId = env.project.split("/").pop()!;
+ await page.goto(
+ `${env.baseURL}/sql-editor/projects/${projectId}/instances/${env.instanceId}/databases/${env.databaseId}?panel=schema`,
+ );
+ await page.keyboard.press("Escape").catch(() => {});
+ await page.waitForTimeout(1500);
+
+ // Schema gutter button is visible regardless; the assertion is that
+ // its panel is the active one. SchemaPane mounts a `.bb-schema-tree`
+ // (or a tree row with `data-node-meta-type="schema"`) so we anchor
+ // on a known schema-pane DOM marker.
+ await expect(
+ page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .first(),
+ ).toBeVisible({ timeout: 10_000 });
+ });
+});
+
+test.describe("Gutter tab switching (H4)", () => {
+ test("clicking each gutter tab swaps the visible aside panel", async () => {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+
+ // Start by clicking Worksheet — the worksheet tree shows the
+ // "Search Sheets" textbox and Mine/Shared/Draft folders.
+ await sqlEditor.gutterWorksheetTab.click();
+ await expect(
+ page.getByPlaceholder("Search Sheets").first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ // Switch to Schema — schema rows render.
+ await sqlEditor.gutterSchemaTab.click();
+ await expect(
+ page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .first(),
+ ).toBeVisible({ timeout: 10_000 });
+ // And the worksheet "Search Sheets" input must NOT be visible.
+ await expect(page.getByPlaceholder("Search Sheets")).toHaveCount(0);
+
+ // Switch to History — empty state placeholder OR an existing
+ // [data-history-row]; both are valid (we run on a fresh server so
+ // history may or may not be populated).
+ await sqlEditor.gutterHistoryTab.click();
+ await page.waitForTimeout(500);
+ const hasRows = await page.locator("[data-history-row]").count();
+ const hasEmpty = await page
+ .getByText("No history found", { exact: true })
+ .count();
+ expect(
+ hasRows + hasEmpty,
+ "history pane must render either rows or its empty-state placeholder",
+ ).toBeGreaterThan(0);
+ });
+});
+
+test.describe("Gutter logo opens in a new tab (H5)", () => {
+ test("logo anchor has target=_blank and rel=noopener noreferrer", async () => {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+
+ // The gutter logo is the only <img alt="Bytebase"> on the page;
+ // walk up to its anchor parent.
+ const logoAnchor = page
+ .locator("a")
+ .filter({ has: page.locator('img[alt="Bytebase"]') })
+ .first();
+ await expect(logoAnchor).toBeVisible({ timeout: 10_000 });
+ await expect(logoAnchor).toHaveAttribute("target", "_blank");
+ await expect(logoAnchor).toHaveAttribute(
+ "rel",
+ /noopener.*noreferrer|noreferrer.*noopener/,
+ );
+ });
+});
+
+test.describe("QueryContextSettingPopover hidden in admin mode (O1)", () => {
+ test("entering admin mode hides the '(limit N)' Run-button affordance", async () => {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+
+ // In worksheet mode, "(limit N)" appears next to Run.
+ await expect(page.getByText(/\(limit\s+\d+\)/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // Enter admin mode — EditorAction.tsx replaces the Run + popover
+ // group with the Exit-admin button.
+ await sqlEditor.adminModeButton.click();
+ await page.waitForTimeout(800);
+
+ // No "(limit N)" text anywhere — the popover trigger isn't rendered.
+ await expect(page.getByText(/\(limit\s+\d+\)/i)).toHaveCount(0);
+ await expect(
+ page.getByRole("button", { name: "Exit admin mode", exact: true }),
+ ).toBeVisible({ timeout: 5_000 });
+
+ // Exit so any sibling test landing on the same page starts in
+ // worksheet mode.
+ await page
+ .getByRole("button", { name: "Exit admin mode", exact: true })
+ .click();
+ await page.waitForTimeout(400);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-permissions.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-permissions.spec.ts
new file mode 100644
index 0000000000..f984900aea
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-permissions.spec.ts
@@ -0,0 +1,316 @@
+// SQL Editor — permission-gated UI (Batch 8, I-series CUJs).
+//
+// Covers:
+// - I1 admin wrench absent for projectDeveloper
+// - I4 RequestQueryButton ("Request query") on a non-JIT project
+// where the user lacks bb.sql.select
+// - I9 Sidebar surfaces the same Request-query affordance when the
+// user lands on a database they have no access to
+// - I10 admin wrench absent for sqlEditorUser
+// - I11 INSERT denied (no "EditorHint" modal, just an inline error
+// with the missing permission)
+//
+// Per AGENTS.md doctrine "F. Test by role, not just by admin", we
+// create dedicated test users via the User API in `beforeAll`, grant
+// each the minimal role we want to verify, log them in via fresh
+// BrowserContexts (one per role) so their auth state is isolated, and
+// delete them in `afterAll`. We never lean on the demo dump's seeded
+// `[email protected]` / `[email protected]` (we don't know their
+// passwords) and never share a context across roles.
+//
+// Skipped from the agreed list:
+// - I5: requires a workspace gate (workspace-level allowQueryWithoutMembership)
+// not exposed via the public API in this branch — deferred.
+
+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";
+import { SqlEditorPage } from "./sql-editor.page";
+
+test.setTimeout(180_000);
+
+// One workspace-scoped client logged in as the demo admin — owns user
+// lifecycle + IAM grants.
+let env: TestEnv & { api: BytebaseApiClient };
+let projectId: string;
+
+// Fixed test-user identities. The password is shared across all of them
+// to keep auth-state setup terse; it's a fresh string with no
+// production meaning. Real demo passwords are unknown.
+const TEST_PASSWORD = "e2e-perms-pw-1!"; // NOSONAR — e2e fixture only
+
+const DEV_USER = {
+ email: "[email protected]",
+ title: "E2E Perms Dev",
+ authFile: ".auth/perms-dev.json",
+};
+const SQL_EDITOR_USER = {
+ email: "[email protected]",
+ title: "E2E Perms SqlEditor",
+ authFile: ".auth/perms-sqledit.json",
+};
+const READ_ONLY_USER = {
+ email: "[email protected]",
+ title: "E2E Perms Reader",
+ authFile: ".auth/perms-reader.json",
+};
+const NO_MEMBERSHIP_USER = {
+ email: "[email protected]",
+ title: "E2E Perms NoProj",
+ authFile: ".auth/perms-noproj.json",
+};
+
+type RoleContext = {
+ context: BrowserContext;
+ page: Page;
+ sqlEditor: SqlEditorPage;
+};
+
+const roleContexts = new Map<string, RoleContext>();
+
+async function openAs(
+ browser: Browser,
+ user: { email: string; authFile: string },
+): Promise<RoleContext> {
+ const context = await browser.newContext({ storageState: user.authFile });
+ const page = await context.newPage();
+ const sqlEditor = new SqlEditorPage(page, env.baseURL);
+ return { context, page, sqlEditor };
+}
+
+// beforeAll runs 4 user creates + 3 IAM grants + 4 API logins + 4
+// page.goto + 4 storage-state writes + 4 context opens. Sequentially
+// that's well past Playwright's default 30s hook budget; we bump it
+// once here so a slow disposable server doesn't false-fail the gate.
+test.beforeAll(async ({ browser }) => {
+ test.setTimeout(180_000);
+ env = loadTestEnv();
+ projectId = env.project.split("/").pop()!;
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Provision the four test users. Make this idempotent: if a previous
+ // test in this same worker (e.g., due to a Playwright retry) already
+ // created the row, createUser returns 409 — we tolerate it and
+ // continue, because the server instance is the same.
+ for (const u of [DEV_USER, SQL_EDITOR_USER, READ_ONLY_USER, NO_MEMBERSHIP_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;
+ }
+ }
+
+ // Grant project-scoped roles on env.project (discovered Postgres project).
+ // - DEV_USER: projectDeveloper (no bb.sql.admin → wrench hidden)
+ // - SQL_EDITOR_USER: sqlEditorUser (read+DML, no admin → wrench hidden)
+ // - READ_ONLY_USER: sqlEditorReadUser (read only — INSERT denied)
+ // - NO_MEMBERSHIP_USER: projectViewer.
+ // Why not "no project role at all"? The SQL Editor route guard
+ // demands bb.projects.getIamPolicy on the targeted project; a pure
+ // workspaceMember (the default for allUsers) gets bounced to a
+ // "Missing required permissions" wall before any editor UI mounts,
+ // making the Request-query CUJ impossible to assert. projectViewer
+ // passes the route guard but lacks bb.sql.select / bb.sql.dml, so
+ // RequestQueryButton renders as the affordance.
+ await env.api.appendProjectBinding(
+ env.project,
+ "roles/projectDeveloper",
+ [`user:${DEV_USER.email}`],
+ );
+ await env.api.appendProjectBinding(
+ env.project,
+ "roles/sqlEditorUser",
+ [`user:${SQL_EDITOR_USER.email}`],
+ );
+ await env.api.appendProjectBinding(
+ env.project,
+ "roles/sqlEditorReadUser",
+ [`user:${READ_ONLY_USER.email}`],
+ );
+ await env.api.appendProjectBinding(
+ env.project,
+ "roles/projectViewer",
+ [`user:${NO_MEMBERSHIP_USER.email}`],
+ );
+
+ // Pre-warm browser sign-ins so individual tests just load storage state.
+ for (const u of [DEV_USER, SQL_EDITOR_USER, READ_ONLY_USER, NO_MEMBERSHIP_USER]) {
+ await signInBrowserAs(browser, env.baseURL, u.email, TEST_PASSWORD, u.authFile);
+ roleContexts.set(u.email, await openAs(browser, u));
+ }
+});
+
+test.afterAll(async () => {
+ for (const rc of roleContexts.values()) {
+ await rc.context.close();
+ }
+ roleContexts.clear();
+ // Best-effort: revert allowRequestRole on the sample project (this
+ // file's Request-query describe flips it) so downstream specs don't
+ // inherit a mutated flag. Skip IAM cleanup and user deletion entirely:
+ //
+ // - DELETE /v1/users/{email} marks the row as deactivated rather
+ // than purging it, so a subsequent beforeAll re-run on the same
+ // server hits 401 "user has been deactivated". This bit us in
+ // earlier batches; the disposable server is torn down by
+ // globalTeardown anyway, so leaving the rows in place is safe.
+ try {
+ await env.api.updateProjectSettings(env.project, {
+ allowRequestRole: false,
+ });
+ } catch {
+ /* ignore */
+ }
+});
+
+// I1 — projectDeveloper role grants project-write permissions but NOT
+// `bb.sql.admin`. `useSQLEditorStore.allowAdmin` is the gate for the
+// wrench button (AdminModeButton.tsx returns null when allowAdmin is
+// false), so opening the editor as a projectDeveloper means no wrench.
+test.describe("Admin-mode wrench is hidden for projectDeveloper users", () => {
+ test("opening a connected DB as a developer shows the toolbar without a wrench", async () => {
+ const rc = roleContexts.get(DEV_USER.email)!;
+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await rc.page.waitForTimeout(1500);
+
+ // The Save / Share / row-limit toolbar must be in the DOM (proves
+ // we actually landed on the editor and the page isn't still
+ // loading). Wrench is the per-permission element under test.
+ await expect(rc.sqlEditor.saveButton).toBeVisible({ timeout: 10_000 });
+ // The wrench locator filters by `lucide-wrench` SVG. For a user
+ // without bb.sql.admin, that SVG should be absent from the
+ // editor toolbar entirely.
+ await expect(rc.sqlEditor.adminModeButton).toHaveCount(0);
+ });
+});
+
+// I10 — sqlEditorUser has bb.sql.select + bb.sql.update + bb.sql.delete
+// but not bb.sql.admin. Same wrench-absence assertion as I1, different
+// role — the two roles are checked separately because they each
+// represent a real user persona ops gives out.
+test.describe("Admin-mode wrench is hidden for sqlEditorUser users", () => {
+ test("opening a connected DB as a sqlEditorUser shows the toolbar without a wrench", async () => {
+ const rc = roleContexts.get(SQL_EDITOR_USER.email)!;
+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await rc.page.waitForTimeout(1500);
+
+ await expect(rc.sqlEditor.saveButton).toBeVisible({ timeout: 10_000 });
+ await expect(rc.sqlEditor.adminModeButton).toHaveCount(0);
+ });
+});
+
+// I11 — sqlEditorReadUser has bb.sql.select only. Running an INSERT
+// returns a permission-denied error; we don't expect a hint modal
+// (those are reserved for the "executingHint" recoverable flow). The
+// inline error in the result panel is the user-visible signal.
+test.describe("INSERT is denied with an inline error for sqlEditorReadUser", () => {
+ test("running INSERT in a read-only project surfaces a 'no permission' error", async () => {
+ const rc = roleContexts.get(READ_ONLY_USER.email)!;
+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await rc.page.waitForTimeout(1500);
+
+ // Type a one-off INSERT against a table that may or may not exist
+ // — we don't care about the SQL parsing result; we care that the
+ // permission gate trips BEFORE the query reaches the database.
+ // The runQuery helper waits for either a row-count footer (which
+ // won't happen) or an inline error pane.
+ await rc.sqlEditor.runPreparedQuery(
+ "INSERT INTO _e2e_does_not_exist DEFAULT VALUES;",
+ );
+
+ // The error pane renders the permission detail somewhere in the
+ // result region. We accept any of the common shapes: an explicit
+ // "permission" mention, the role name, or the request-query CTA.
+ // The strong assertion is that the row-count footer DID NOT appear
+ // (Run reached an error state) AND a request affordance is offered.
+ const permissionMention = rc.page.getByText(
+ /(permission denied|no.*permission|bb\.sql\.(update|delete|create|admin|insert)|missing.*permission)/i,
+ );
+ const requestCTA = rc.page.getByRole("button", { name: /Request query|Request just-in-time/i });
+ const anySignal = permissionMention.or(requestCTA).first();
+ await expect(anySignal).toBeVisible({ timeout: 10_000 });
+
+ // No N-rows footer (proves the query did not succeed).
+ await expect(rc.page.getByText(/^\d+\s+rows?$/i)).toHaveCount(0);
+ });
+});
+
+// I4 — RequestQueryButton has a two-axis gate:
+// - `project.allowRequestRole === false` → component returns null (no
+// Request button at all, regardless of permission state).
+// - `project.allowRequestRole === true` AND user lacks bb.sql.select →
+// the button renders. Label switches on `useJIT` (non-JIT label is
+// "Request query" — covered here; JIT label is in sql-editor-jit.spec.ts).
+//
+// The new bootstrap creates `project-sample` with `allowRequestRole=false`
+// by default (sampleinstance/manager.go:171 uses an empty Setting). We
+// exercise BOTH halves of the gate so a future regression on either side
+// is caught:
+// D1 ("…off → no button"): projectViewer + allowRequestRole=false →
+// no Request query button (the negative case the framework relies on).
+// D2 ("…on → button"): flip allowRequestRole=true via API, re-navigate,
+// verify the button now renders. afterEach flips it back.
+
+test.describe("Request-query CTA respects project.allowRequestRole", () => {
+ test.afterEach(async () => {
+ // Always restore to the default-off state so other tests in this
+ // file (and downstream specs that share env.project) inherit a
+ // known baseline.
+ await env.api
+ .updateProjectSettings(env.project, { allowRequestRole: false })
+ .catch(() => {});
+ });
+
+ test("with allowRequestRole=false, projectViewer running a forbidden SELECT sees NO Request query button", async () => {
+ // Confirm the seeded state (sample project is created with
+ // allowRequestRole=false). RequestQueryButton's `if (!available)
+ // return null` then suppresses both the non-JIT and JIT variants.
+ await env.api.updateProjectSettings(env.project, { allowRequestRole: false });
+
+ const rc = roleContexts.get(NO_MEMBERSHIP_USER.email)!;
+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await rc.page.waitForTimeout(2000);
+ await rc.sqlEditor.runPreparedQuery("SELECT 1;");
+ await rc.page.waitForTimeout(800);
+
+ // Neither label should appear — the component returned null.
+ await expect(
+ rc.page.getByRole("button", { name: "Request query", exact: true }),
+ ).toHaveCount(0);
+ await expect(
+ rc.page.getByRole("button", { name: /Request just-in-time/i }),
+ ).toHaveCount(0);
+ });
+
+ test("with allowRequestRole=true, projectViewer running a forbidden SELECT sees the 'Request query' button", async () => {
+ // Flip the project's allowRequestRole on. Once the editor re-reads
+ // the project (we force a fresh navigation), the button renders.
+ await env.api.updateProjectSettings(env.project, { allowRequestRole: true });
+
+ const rc = roleContexts.get(NO_MEMBERSHIP_USER.email)!;
+ await rc.sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await rc.page.waitForTimeout(2000);
+ await rc.sqlEditor.runPreparedQuery("SELECT 1;");
+ await rc.page.waitForTimeout(800);
+
+ // Non-JIT label — `sql-editor.request-query` → "Request query".
+ await expect(
+ rc.page.getByRole("button", { name: "Request query", exact: true }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ // JIT variant must NOT show — this project has
+ // allowJustInTimeAccess=false (its default), so `useJIT` resolves
+ // to false and the label switch picks the non-JIT side.
+ await expect(
+ rc.page.getByRole("button", { name: /Request just-in-time/i }),
+ ).toHaveCount(0);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts
new file mode 100644
index 0000000000..20ea93ba2b
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-result.spec.ts
@@ -0,0 +1,330 @@
+// SQL Editor — query result rendering and interaction.
+//
+// Covers what happens after the user clicks Run: how the result panel
+// renders rows, multi-statement tabs, errors, NULL placeholders,
+// sort, the per-cell Detail panel, and the row-selection visual
+// affordance. Mix of CUJ coverage (happy paths that should pass) and
+// a bug-lock (BYT-9478 row-selection highlight) marked inline.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+// Each test re-enters the connected DB URL via gotoWithDb. The SQL
+// editor opens a fresh worksheet tab on that route, isolating each
+// test from the previous test's editor content + result state.
+// Reusing the same browser context (no new context per test) keeps the
+// run fast; the per-test navigation is what gives state isolation.
+async function openFreshConnectedTab(): Promise<void> {
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+}
+
+test.describe("Single-row result renders one data row", () => {
+ // The smallest possible happy path: a literal SELECT 1 returns a
+ // single row and the result panel renders it. If this breaks,
+ // almost every other result test below is also broken.
+
+ test("SELECT 1 produces a 1-row result", 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,
+ });
+ await expect(page.locator('[data-row-index="0"]').first()).toContainText(
+ "1",
+ { timeout: 5000 },
+ );
+ });
+});
+
+test.describe("Multi-statement query renders one result tab per statement", () => {
+ // Running two SELECTs separated by `;` produces a Query #1 / Query
+ // #2 tab list, and clicking a tab switches the visible result to
+ // that statement's rows.
+
+ test("Query #1 and Query #2 tabs both render and switch", async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ await sqlEditor.runPreparedQuery(
+ "SELECT 1 AS first; SELECT 2 AS second;",
+ );
+
+ const tab1 = page.getByRole("tab", { name: /Query\s*#1/i }).first();
+ const tab2 = page.getByRole("tab", { name: /Query\s*#2/i }).first();
+ await expect(tab1).toBeVisible({ timeout: 10_000 });
+ await expect(tab2).toBeVisible();
+
+ // Default tab is Query #1 — its row should show the literal "1".
+ await expect(page.locator('[data-row-index="0"]').first()).toContainText(
+ "1",
+ { timeout: 5000 },
+ );
+
+ // Switch to Query #2 — the row should now show "2".
+ await tab2.click();
+ await expect(page.locator('[data-row-index="0"]').first()).toContainText(
+ "2",
+ { timeout: 5000 },
+ );
+ });
+});
+
+test.describe("Bad SQL renders an inline error pane", () => {
+ // When the statement fails to parse or execute, the user must see
+ // an error message inline (not silently get an empty result, not
+ // crash the panel).
+
+ test("syntax error surfaces an ERROR card, no rows", async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ await sqlEditor.runPreparedQuery("SEELECT 1;");
+
+ await expect(page.getByText(/ERROR[: ]/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+ await expect(page.locator("[data-row-index]")).toHaveCount(0);
+ });
+});
+
+test.describe("NULL values render with a visible NULL marker", () => {
+ // When the result contains a SQL NULL, the cell must show "NULL"
+ // (or some other unambiguous placeholder) — never an empty cell
+ // that the user mistakes for an empty string.
+
+ test('SELECT NULL renders a "NULL" cell, not blank', async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ await sqlEditor.runPreparedQuery("SELECT NULL AS empty_col;");
+
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+ // The NULL marker is rendered inside the data cell at column 1.
+ // We anchor by row 0 / col-index 1 (col 0 is the row-number cell).
+ const cell = page.locator(
+ '[data-row-index="0"] [data-col-index="1"]',
+ );
+ await expect(cell).toBeVisible({ timeout: 5000 });
+ await expect(cell).toContainText(/NULL/i);
+ });
+});
+
+test.describe("Clicking a column header sorts the result", () => {
+ // Header click toggles a sort indicator and reorders the rendered
+ // rows.
+
+ test("clicking the header reorders rows by that column", async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ // Initial order is descending so the sort click visibly reorders
+ // the rows. UNION'd literals would be returned in (engine-defined)
+ // ascending order, which would mask the sort effect entirely.
+ await sqlEditor.runPreparedQuery(
+ "SELECT n FROM (VALUES (1), (2), (3)) AS t(n) ORDER BY n DESC;",
+ );
+ await expect(page.getByText(/^3\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ const readFirstColumn = async () =>
+ page.evaluate(() =>
+ Array.from(
+ document.querySelectorAll(
+ '[data-row-index] [data-col-index="1"]',
+ ),
+ )
+ .map((c) => c.textContent?.trim() ?? "")
+ .filter(Boolean),
+ );
+ const before = await readFirstColumn();
+ expect(
+ before,
+ "initial order should be desc per ORDER BY DESC",
+ ).toEqual(["3", "2", "1"]);
+
+ // VirtualDataTable.tsx renders the header sort toggle as a
+ // <span role="button"> wrapping a Lucide ArrowDownWideNarrow /
+ // ArrowUpWideNarrow icon. With one column ("n"), there's exactly
+ // one such icon visible — anchor on the SVG class. Clicking the
+ // SVG bubbles up to the role="button" parent's onClick.
+ const sortIcon = page
+ .locator(
+ "svg.lucide-arrow-down-wide-narrow, svg.lucide-arrow-up-wide-narrow",
+ )
+ .first();
+ await expect(sortIcon).toBeVisible({ timeout: 5000 });
+
+ // SingleResultView.tsx:163 cycles sort state: undefined → desc →
+ // asc → desc → … (no clear-back-to-undefined). Our baseRows are
+ // already desc thanks to ORDER BY DESC, so the FIRST click sets
+ // sortState=desc (no visible reorder); the SECOND click sets
+ // asc and the rows flip. Two clicks is the user-visible path.
+ await sortIcon.click();
+ await page.waitForTimeout(200);
+ await sortIcon.click();
+ await page.waitForTimeout(400);
+
+ const after = await readFirstColumn();
+
+ expect(after, "sorted ascending after second click").toEqual([
+ "1",
+ "2",
+ "3",
+ ]);
+ expect(after).not.toEqual(before);
+ });
+});
+
+test.describe("Cell click opens the Detail panel for that cell", () => {
+ // Clicking a result cell opens a Detail side panel showing that
+ // cell's full value. Useful for long strings / JSON / binary that
+ // would be truncated in the inline grid.
+
+ test("clicking a cell opens the Detail panel and shows the value", async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ const known = "e2e-detail-marker";
+ await sqlEditor.runPreparedQuery(`SELECT '${known}' AS marker;`);
+ 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();
+
+ // The Detail panel is mounted into the result area when
+ // setDetail(...) fires. The cell value is rendered inside the
+ // panel — we look for the marker text appearing twice on screen
+ // (once in the cell, once in the panel).
+ await expect(page.getByText(known).nth(1)).toBeVisible({
+ timeout: 5000,
+ });
+ });
+});
+
+test.describe("Selecting a row paints visible feedback across the row", () => {
+ // BYT-9478: in the result grid, clicking the row-select button
+ // (the 12px bg-accent/5 hairline at the left of every row) only
+ // tints the index column. The rest of the row stays transparent,
+ // so the user has no visual confirmation that the row is selected.
+ // Combined with the row-number column's permanent decorative stripe,
+ // the "selection" is indistinguishable from baseline rendering.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r43-byt9478-row-purple/
+ // - 03-notes.txt
+ // - 02-multirow-select-row3.png
+
+ const TARGET_ROW_INDEX = 2; // 0-based; visible row 3
+
+ test("clicking the row-select hairline tints every cell in that row", async () => {
+ test.setTimeout(120_000);
+ await openFreshConnectedTab();
+
+ await sqlEditor.runPreparedQuery(
+ "SELECT emp_no, first_name, last_name FROM employee LIMIT 5;",
+ );
+
+ // Wait for the virtual row we plan to select to mount.
+ const targetRow = page.locator(
+ `[data-row-index="${TARGET_ROW_INDEX}"]`,
+ );
+ await expect(targetRow).toBeVisible({ timeout: 10_000 });
+
+ // The selection trigger is a 12px-wide button with aria-label
+ // "Select row N" rendered absolutely inside the index cell. Its
+ // position (left:0 of the index cell) is what produces the
+ // permanent left-edge stripe — clicking it toggles the row's
+ // selected state.
+ const selectButton = targetRow.getByRole("button", {
+ name: `Select row ${TARGET_ROW_INDEX + 1}`,
+ exact: true,
+ });
+ await expect(selectButton).toBeVisible({ timeout: 5000 });
+
+ // Bug-defining contract (BYT-9478): selecting a row must paint the DATA
+ // cells, not just the index cell. The fix lives on the inner TableCell
+ // (`selected && "bg-accent/20!"`), one level inside the [data-col-index]
+ // wrapper.
+ //
+ // We assert a RELATIONAL delta, not an absolute "something is painted":
+ // every EVEN data row already carries a permanent `group-even` zebra
+ // stripe on the [data-col-index] wrapper, so "is the cell subtree
+ // non-transparent?" is already true even with the bug present. Instead
+ // we count non-transparent backgrounds in the cell's subtree before vs.
+ // after selecting and require the count to GROW — selection added paint
+ // that wasn't there before. This is parity- and color-format-agnostic
+ // (the constant zebra stripe cancels out) and fails if the `bg-accent/20`
+ // handler is ever deleted (AGENTS.md K + M).
+ const countPaintedInCell = (rowIdx: number, colIdx: number) =>
+ page.evaluate(
+ ({ rowIdx, colIdx }) => {
+ const row = document.querySelector(`[data-row-index="${rowIdx}"]`);
+ if (!row) return null;
+ const cell = row.querySelector(`[data-col-index="${colIdx}"]`);
+ if (!cell) return null;
+ const TRANSPARENT = new Set(["rgba(0, 0, 0, 0)", "transparent", ""]);
+ const isPainted = (node: Element) =>
+ !TRANSPARENT.has(getComputedStyle(node).backgroundColor);
+ let painted = isPainted(cell) ? 1 : 0;
+ for (const desc of Array.from(cell.querySelectorAll("*"))) {
+ if (isPainted(desc)) painted++;
+ }
+ return painted;
+ },
+ { rowIdx, colIdx },
+ );
+
+ const paintedBefore = await countPaintedInCell(TARGET_ROW_INDEX, 2);
+ expect(
+ paintedBefore,
+ "target row's data cell must be locatable before selecting",
+ ).not.toBeNull();
+
+ await selectButton.click();
+ // Move the mouse off the row so a transient `group-hover` background
+ // can't be mistaken for selection paint; selection persists regardless.
+ await page.mouse.move(0, 0);
+ await page.waitForTimeout(300);
+
+ const paintedAfter = await countPaintedInCell(TARGET_ROW_INDEX, 2);
+ expect(
+ paintedAfter!,
+ `selecting the row must add a visible background to its data cell ` +
+ `(non-transparent elements in the cell subtree: before=` +
+ `${paintedBefore}, after=${paintedAfter}). With the bug present ` +
+ `only the index cell tints, so the data cell's subtree gains no ` +
+ `paint and the count is unchanged.`,
+ ).toBeGreaterThan(paintedBefore!);
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts
new file mode 100644
index 0000000000..ca46aaae07
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-schema.spec.ts
@@ -0,0 +1,393 @@
+// SQL Editor — schema browsing.
+//
+// Covers the Schema gutter pane (tree of schemas / tables / columns,
+// search input) and the Schema Diagram canvas opened from it. These
+// surfaces are how the user finds out what's in a database without
+// running SQL — and how they jump from a known table to an editor
+// with a SELECT skeleton.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Schema Diagram fits all table cards into the viewport on mount", () => {
+ // BYT-9481: the schema diagram is mounted with no auto-fit applied,
+ // so most table cards land off-screen on a wide virtual canvas. The
+ // user sees one or two cards on the left and assumes the diagram is
+ // empty or broken — they must zoom out manually to discover the rest.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r42-byt9481-schema-diagram/
+ // - 02-card-positions.txt (DOM-measured card positions, only 1 of N visible)
+ // - 01-schema-diagram-full-view.png
+
+ test("every table card lands inside the viewport at default zoom", async () => {
+ // BYT-9481 is queued as not-high-priority. The fix is flaky on
+ // main — auto-fit sometimes runs early enough to land all cards
+ // in view, often it doesn't. Mark expected-fail so the suite
+ // stays green; a real fix will surface as "Expected to fail, but
+ // passed" → flip the marker off.
+ test.fail();
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // Open the Schema gutter pane → right-click the "public" schema row
+ // → click the "Schema Diagram" menu item. This is the canonical user
+ // path; opening the diagram via URL or programmatic store mutation
+ // would skip the same mount lifecycle that triggers (or skips)
+ // fit-to-view.
+ await sqlEditor.gutterSchemaTab.click();
+ await page.waitForTimeout(800);
+
+ // Schema rows in the gutter are rendered as `.bb-schema-tree-row`
+ // with `data-node-meta-type="schema"`; the public schema's row is
+ // the one whose text matches "public" exactly.
+ const schemaRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .filter({ hasText: "public" })
+ .first();
+ await expect(schemaRow).toBeVisible({ timeout: 10_000 });
+ await schemaRow.click({ button: "right" });
+
+ const diagramMenuItem = page.getByRole("menuitem", {
+ name: "Schema Diagram",
+ exact: true,
+ });
+ await expect(diagramMenuItem).toBeVisible({ timeout: 5000 });
+ await diagramMenuItem.click();
+
+ // Wait for the diagram canvas + at least one table card to mount.
+ const diagramRoot = page.locator(".bb-react-schema-diagram");
+ await expect(diagramRoot).toBeVisible({ timeout: 10_000 });
+ const tableCards = page.locator('[data-bb-node-type="table"]');
+ await expect(tableCards.first()).toBeVisible({ timeout: 15_000 });
+ // Give the canvas a beat to settle (any mount-time fitView would
+ // run synchronously after the first render commit).
+ await page.waitForTimeout(800);
+
+ // Bug-defining assertion: every card's bounding rect must fit
+ // within the viewport. With the bug present, only the leftmost
+ // card sits inside the canvas; every other card has right > innerWidth.
+ const result = await page.evaluate(() => {
+ const cards = Array.from(
+ document.querySelectorAll('[data-bb-node-type="table"]'),
+ );
+ const innerWidth = window.innerWidth;
+ const innerHeight = window.innerHeight;
+ const offscreen: Array<{
+ id: string;
+ left: number;
+ right: number;
+ top: number;
+ bottom: number;
+ }> = [];
+ for (const c of cards) {
+ const r = c.getBoundingClientRect();
+ // A card is "off-screen" if any of its edges lies outside the
+ // viewport by more than 1px (tolerance for sub-pixel rounding).
+ const offRight = r.right > innerWidth + 1;
+ const offLeft = r.left < -1;
+ const offBottom = r.bottom > innerHeight + 1;
+ const offTop = r.top < -1;
+ if (offRight || offLeft || offBottom || offTop) {
+ offscreen.push({
+ id: c.getAttribute("data-bb-node-id") ?? "?",
+ left: Math.round(r.left),
+ right: Math.round(r.right),
+ top: Math.round(r.top),
+ bottom: Math.round(r.bottom),
+ });
+ }
+ }
+ return { totalCards: cards.length, innerWidth, innerHeight, offscreen };
+ });
+
+ expect(
+ result.totalCards,
+ "schema diagram must render at least one table card",
+ ).toBeGreaterThan(0);
+
+ expect(
+ result.offscreen,
+ `every table card must fit within the ${result.innerWidth}x${result.innerHeight} ` +
+ `viewport on mount — auto-fit must run. ` +
+ `${result.offscreen.length} of ${result.totalCards} cards are off-screen: ` +
+ JSON.stringify(result.offscreen.slice(0, 5)),
+ ).toEqual([]);
+ });
+});
+
+test.describe("Clicking a schema row reveals its child folders", () => {
+ // Single-click on a schema row toggles expand on/off (SchemaPane.tsx:
+ // toggleNode). When the user clicks "public" on a Postgres database,
+ // the row's children — Tables / Views / Functions / Sequences group
+ // folders — should become visible. The contract is "schemas in the
+ // tree are explorable in-place" — clicking once gets the user one
+ // level deeper.
+
+ test("clicking the public schema reveals its grouping folders", 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);
+
+ const publicRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .filter({ hasText: "public" })
+ .first();
+ await expect(publicRow).toBeVisible({ timeout: 10_000 });
+
+ // The "Tables" group folder is a child of public — anchor on it.
+ // It exists for any Postgres schema. Probe whether the schema is
+ // already expanded: if so, re-clicking would collapse it.
+ const tablesFolder = page
+ .locator(".bb-schema-tree-row")
+ .filter({ hasText: /^Tables$/ })
+ .first();
+ const wasExpanded = await tablesFolder.isVisible();
+ if (!wasExpanded) {
+ await publicRow.click();
+ }
+ await expect(tablesFolder).toBeVisible({ timeout: 5000 });
+ });
+});
+
+test.describe("Schema search filters the schema tree", () => {
+ // Typing into the schema panel's search box filters the visible
+ // tree to nodes whose name matches the query. Asserts a known
+ // table appears for an exact match and a known sibling disappears.
+
+ test('searching for "employee" hides non-matching tables', 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);
+
+ // The schema tree input has placeholder t("common.search") = "Search".
+ // It's the only Search-placeholder textbox visible inside the
+ // schema gutter pane (the worksheet pane uses "Search Sheets").
+ const searchBox = page.getByPlaceholder("Search").first();
+ await expect(searchBox).toBeVisible({ timeout: 10_000 });
+ await searchBox.fill("employee");
+ await page.waitForTimeout(800); // debounced filter
+
+ const employeeRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="table"]')
+ .filter({ hasText: /^employee$/ })
+ .first();
+ await expect(employeeRow).toBeVisible({ timeout: 5000 });
+
+ // A sibling table that doesn't match — hr_prod has "department"
+ // alongside "employee". After the filter, "department" must NOT
+ // be in the visible tree.
+ await expect(
+ page
+ .locator('.bb-schema-tree-row[data-node-meta-type="table"]')
+ .filter({ hasText: /^department$/ }),
+ ).toHaveCount(0);
+
+ // Reset for any sibling describe sharing the page.
+ await searchBox.fill("");
+ await page.waitForTimeout(400);
+ });
+});
+
+test.describe("Right-click on a schema opens a sub-panel for each metadata view", () => {
+ // Right-clicking a schema row in the Schema gutter exposes a menu
+ // of metadata views. Each item opens a new editor-area tab whose
+ // panel is dedicated to that view (Info / Tables / Functions /
+ // Procedures / External tables / Schema Diagram per
+ // SchemaPane/availableActions.tsx). Each opens a different React
+ // component inside Panels.tsx — we verify a unique-per-panel
+ // anchor is reachable after the click.
+
+ // Each row's `verify` function returns a locator that exists ONLY
+ // when that specific panel has finished mounting. The verify is
+ // intentionally loose (a known table name / function name / etc.
+ // from the hr_prod demo seed) — tightening it to internal class
+ // names would make the test brittle to design tweaks.
+ const cases: Array<{
+ menuLabel: string;
+ verify: (p: Page) => ReturnType<Page["locator"]>;
+ }> = [
+ {
+ menuLabel: "Info",
+ // Info panel surfaces schema metadata fields with stable labels
+ // ("Encoding", "Sync status", etc.) regardless of seed data.
+ verify: (p) => p.getByText("Encoding", { exact: true }).first(),
+ },
+ {
+ menuLabel: "Tables",
+ // Tables panel lists every table in the schema; "employee" is
+ // a known seed entry. It renders as a plain text cell, not a
+ // link, so anchor by text + table-row context.
+ verify: (p) =>
+ p
+ .locator("table")
+ .getByText("employee", { exact: true })
+ .first(),
+ },
+ {
+ menuLabel: "Functions",
+ // hr_prod doesn't seed user functions, so the panel may render
+ // an empty state. The new tab's title is the most stable signal:
+ // SchemaPane/actions.tsx:420 sets it to `[<db>] <action>`.
+ verify: (p) =>
+ p.locator("[data-tab-id]").filter({ hasText: "Functions" }).first(),
+ },
+ {
+ menuLabel: "Procedures",
+ verify: (p) =>
+ p.locator("[data-tab-id]").filter({ hasText: "Procedures" }).first(),
+ },
+ ];
+
+ for (const c of cases) {
+ test(`opens the ${c.menuLabel} sub-panel`, 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);
+
+ const publicRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .filter({ hasText: "public" })
+ .first();
+ await expect(publicRow).toBeVisible({ timeout: 10_000 });
+ await publicRow.click({ button: "right" });
+
+ const menuItem = page.getByRole("menuitem", {
+ name: c.menuLabel,
+ exact: true,
+ });
+ await expect(menuItem).toBeVisible({ timeout: 5000 });
+ await menuItem.click();
+ await page.waitForTimeout(800);
+
+ await expect(c.verify(page)).toBeVisible({ timeout: 10_000 });
+ });
+ }
+});
+
+test.describe("Right-click on a table opens its detail in a new tab", () => {
+ // Right-clicking a leaf table row in the schema tree exposes a
+ // "View detail" action that opens a new editor-area tab whose
+ // Tables panel is focused on that specific table (header /
+ // breadcrumb names the table). This is the user's path from
+ // "I see a table name" to "I'm reading its column metadata".
+
+ test('right-click employee → "View detail" opens a tab named for the table', 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);
+
+ // Type the table name into the schema search to surface "employee"
+ // without having to walk the public → Tables hierarchy.
+ const search = page.getByPlaceholder("Search").first();
+ await expect(search).toBeVisible({ timeout: 10_000 });
+ await search.fill("employee");
+ await page.waitForTimeout(800);
+
+ const employeeRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="table"]')
+ .filter({ hasText: /^employee$/ })
+ .first();
+ await expect(employeeRow).toBeVisible({ timeout: 10_000 });
+ await employeeRow.click({ button: "right" });
+
+ const viewDetail = page.getByRole("menuitem", {
+ name: "View detail",
+ exact: true,
+ });
+ await expect(viewDetail).toBeVisible({ timeout: 5000 });
+ await viewDetail.click();
+
+ // viewDetail() opens a new editor-area tab titled `Detail for <type>
+ // <name>` (SchemaPane/actions.tsx). Assert on that NEW TAB — a bare
+ // getByText("employee") is already satisfied by the still-filtered
+ // sidebar row (search isn't cleared until below), so the old assertion
+ // passed even if the tab never opened. Anchoring on the tab strip
+ // distinguishes "wired" from "actually opened the detail".
+ await expect(
+ page
+ .locator("[data-tab-id]")
+ .filter({ hasText: /Detail for table\s+employee/i })
+ .first(),
+ ).toBeVisible({ timeout: 10_000 });
+
+ await search.fill("");
+ await page.waitForTimeout(400);
+ });
+});
+
+test.describe("Schema Diagram menuitem opens the diagram canvas", () => {
+ // The "Schema Diagram" menu item on a schema row routes to the
+ // DiagramPanel, which mounts the SchemaDiagram canvas with one
+ // node per table. We assert at least one table card renders — the
+ // mount-time auto-fit contract is covered by the BYT-9481 lock test
+ // in the first describe of this file.
+
+ test("Schema Diagram action mounts the canvas with at least one table card", 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);
+
+ const publicRow = page
+ .locator('.bb-schema-tree-row[data-node-meta-type="schema"]')
+ .filter({ hasText: "public" })
+ .first();
+ await expect(publicRow).toBeVisible({ timeout: 10_000 });
+ await publicRow.click({ button: "right" });
+
+ await page
+ .getByRole("menuitem", { name: "Schema Diagram", exact: true })
+ .click();
+
+ const diagramRoot = page.locator(".bb-react-schema-diagram");
+ await expect(diagramRoot).toBeVisible({ timeout: 10_000 });
+ const tableCards = page.locator('[data-bb-node-type="table"]');
+ await expect(tableCards.first()).toBeVisible({ timeout: 15_000 });
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts
new file mode 100644
index 0000000000..79bc320ff3
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-tabs.spec.ts
@@ -0,0 +1,392 @@
+// SQL Editor — tab strip behavior.
+//
+// Covers the top tab strip's contract:
+// - Active tab text reflects the live worksheet state (title + connection)
+// - Tab strip remains scrollable when more tabs open than fit the viewport
+// - Right-click on a tab opens the close-actions context menu
+// - Closing a tab with unsaved changes prompts for confirmation
+// - Unsaved tabs carry a `status-dirty` class that the icon binds to
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Active tab text tracks the live connection", () => {
+ // BYT-9392 (originally surfaced as SUP-197): when the user switches
+ // the database connection on a worksheet via the breadcrumb picker,
+ // the breadcrumb, schema tree, and schema dropdown all update to the
+ // new database — but the TAB TITLE keeps showing the old DB name.
+ //
+ // This is a "trust the screen" / wrong-DB-write hazard. A user typing
+ // a destructive statement (UPDATE/DELETE/TRUNCATE/DDL) while
+ // orienting on the tab title believes they target the previously-
+ // bound DB; the query actually executes against the new connection.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r07-tab-title-stale/
+ // - 02-notes.txt
+ // - 01-tab-says-hrprod-actually-familyprod.png
+ //
+ // Test environment note: the QA evidence repro was hr_prod → family_prod
+ // (Postgres → MySQL across instances). The disposable test server's
+ // --demo seed includes only Postgres sample instances (hr_prod,
+ // hr_test). This test uses the available pair hr_prod → hr_test.
+ // The bug is engine-agnostic: the title binding has no engine-
+ // specific code path.
+
+ const SOURCE_DB_SHORT = "hr_prod";
+ const TARGET_DB_SHORT = "hr_test";
+ // Title intentionally embeds the source DB name verbatim — that is
+ // the entire premise of the bug (the title is set once at create
+ // time and never re-derived when the connection changes).
+ const WORKSHEET_TITLE = `${SOURCE_DB_SHORT} e2e-tab-title-${Date.now()}`;
+
+ let sourceWorksheet = "";
+
+ test.beforeAll(async () => {
+ const source = await env.api.findDatabaseByShortName(SOURCE_DB_SHORT);
+ const target = await env.api.findDatabaseByShortName(TARGET_DB_SHORT);
+ if (!source) {
+ throw new Error(
+ `Setup failed: no database named ${SOURCE_DB_SHORT} found in any instance`,
+ );
+ }
+ if (!target) {
+ throw new Error(
+ `Setup failed: no database named ${TARGET_DB_SHORT} found in any instance`,
+ );
+ }
+ // Resolve project from the source DB record so a project rename in
+ // the demo seed doesn't break the test.
+ const dbRecord = await env.api
+ .listDatabases(source.instance)
+ .then((res) => res.databases.find((d) => d.name === source.database));
+ const project =
+ (dbRecord as { project?: string } | undefined)?.project ?? env.project;
+
+ const created = await env.api.createWorksheet(
+ project,
+ WORKSHEET_TITLE,
+ source.database,
+ "SELECT 1;",
+ );
+ sourceWorksheet = created.name;
+ });
+
+ test.afterAll(async () => {
+ if (sourceWorksheet) {
+ await env.api.deleteWorksheet(sourceWorksheet);
+ }
+ });
+
+ test("tab title is the worksheet name and does NOT pick up the new DB name after a connection switch", async () => {
+ test.setTimeout(120_000);
+ const sourceUuid = sourceWorksheet.split("/").pop()!;
+ const projectId = sourceWorksheet.split("/")[1];
+ await sqlEditor.gotoSheet(projectId, sourceUuid);
+ await page.waitForTimeout(2000);
+
+ // Sanity: tab title reflects the worksheet's name on first open.
+ // (The name happens to contain SOURCE_DB_SHORT because we composed
+ // it that way at create time — that's purely incidental.)
+ await expect(sqlEditor.activeTab()).toContainText(WORKSHEET_TITLE, {
+ timeout: 10_000,
+ });
+
+ // Open the breadcrumb connection picker and switch to the target.
+ const breadcrumb = page
+ .locator("button")
+ .filter({ hasText: SOURCE_DB_SHORT })
+ .first();
+ await expect(breadcrumb).toBeVisible({ timeout: 5000 });
+ await breadcrumb.click();
+
+ const connectionPanel = page.getByRole("dialog");
+ await expect(connectionPanel).toBeVisible({ timeout: 5000 });
+ const targetRow = connectionPanel
+ .getByText(TARGET_DB_SHORT, { exact: true })
+ .first();
+ await expect(targetRow).toBeVisible({ timeout: 10_000 });
+ await targetRow.click();
+
+ // Breadcrumb tracks the live connection — wait for it to flip to
+ // the target before reading the tab text.
+ await expect(
+ page.locator("button").filter({ hasText: TARGET_DB_SHORT }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ await page.waitForTimeout(500);
+
+ // Current product behavior (R7 fix): the tab title is the
+ // worksheet name and is NOT augmented with the live DB. So after
+ // switching to TARGET_DB_SHORT (hr_test), the tab still shows the
+ // original worksheet title and does NOT contain TARGET_DB_SHORT —
+ // the DB info lives in the breadcrumb only.
+ await expect(sqlEditor.activeTab()).toContainText(WORKSHEET_TITLE, {
+ timeout: 5000,
+ });
+ await expect(sqlEditor.activeTab()).not.toContainText(TARGET_DB_SHORT);
+ });
+});
+
+test.describe("Tab strip scrolls when tabs overflow the viewport", () => {
+ // BYT-9457 (3.18 regression — 3.17.1 had a working scrollbar): when
+ // enough tabs open to exceed the strip's width, the horizontal
+ // scrollbar disappears and the leftmost tabs are clipped with no way
+ // for the user to scroll back to them.
+ //
+ // Root cause is structural in TabList.tsx: the inner row that wraps
+ // the TabItem list has `overflow-hidden flex-nowrap`. The outer
+ // scroller above it has `overflow-x-auto`, but its descendant's
+ // `overflow-hidden` short-circuits scrollbar rendering and clips the
+ // leftmost tabs visually even when the user attempts to scroll.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/f03-byt9457-tab-scroller/
+ // - 03-notes.txt
+ // - 01-narrow-900px-tabs-need-scroll.png
+ // - 02-wide-1440px-tabs-fit.png
+ //
+ // Why this matters: the work in clipped tabs is effectively orphaned —
+ // the user can't switch to those tabs without closing the visible ones
+ // first. Combined with worksheet-level data-loss bugs (e.g. duplicate
+ // dropping content), unsaved work in inaccessible tabs disappears.
+
+ // Reset viewport in afterAll — sibling describes share the page
+ // and would inherit the narrow viewport otherwise.
+ const DEFAULT_VIEWPORT = { width: 1280, height: 720 };
+ const NARROW_VIEWPORT = { width: 900, height: 700 };
+ const TARGET_TAB_COUNT = 8;
+ const WORKSHEET_TITLE_PREFIX = `e2e-tabs-${Date.now()}-`;
+
+ let createdWorksheets: string[] = [];
+
+ test.beforeAll(async () => {
+ // Pre-create the worksheets via API with a real DB connection.
+ // Clicking the in-page "+" Add button creates worksheets WITHOUT a
+ // database (worksheetStore.createWorksheet({}) — TabList.tsx:163),
+ // which makes the editor pop the connection panel after each click
+ // and starves the loop. Pre-created worksheets bypass that path
+ // entirely and become tabs the moment we navigate to them.
+ for (let i = 0; i < TARGET_TAB_COUNT; i++) {
+ const created = await env.api.createWorksheet(
+ env.project,
+ `${WORKSHEET_TITLE_PREFIX}${i}`,
+ env.database,
+ `SELECT ${i};`,
+ );
+ createdWorksheets.push(created.name);
+ }
+ });
+
+ test.afterAll(async () => {
+ if (page) {
+ await page.setViewportSize(DEFAULT_VIEWPORT).catch(() => {});
+ }
+ for (const name of createdWorksheets) {
+ await env.api.deleteWorksheet(name);
+ }
+ createdWorksheets = [];
+ });
+
+ test("horizontal scrollbar is reachable with enough tabs to overflow", async () => {
+ test.setTimeout(120_000);
+
+ await page.setViewportSize(NARROW_VIEWPORT);
+
+ // Open all the pre-created worksheets as tabs by navigating to each
+ // sheet URL in turn. The SQL editor remembers open tabs per project
+ // (tabStore.openTabList), so subsequent navigations append to the
+ // strip rather than replacing the active tab.
+ const projectId = env.project.split("/").pop()!;
+ for (const name of createdWorksheets) {
+ const uuid = name.split("/").pop()!;
+ await sqlEditor.gotoSheet(projectId, uuid);
+ }
+ await page.waitForTimeout(500);
+
+ // Sanity: every worksheet became a tab.
+ const tabCount = await sqlEditor.tabCount();
+ expect(
+ tabCount,
+ `every pre-created worksheet should appear as a tab (got ${tabCount})`,
+ ).toBeGreaterThanOrEqual(TARGET_TAB_COUNT);
+
+ // The outer scrollable container is the only direct child of
+ // .bb-sql-editor-tab-list with overflow-x-auto (TabList.tsx renders
+ // it as a single scrollRef wrapping the DndContext + tabs row).
+ const outerScroller = page
+ .locator(".bb-sql-editor-tab-list .overflow-x-auto")
+ .first();
+ await expect(outerScroller).toBeVisible({ timeout: 5000 });
+
+ const dims = await outerScroller.evaluate((el) => {
+ // The inner row sits two levels down: scroller > DndContext div >
+ // SortableContext div > inner row. Find the first descendant with
+ // [data-tab-id] and walk up to its parent — that's the row whose
+ // computed overflow-x is the bug locus.
+ const tab = el.querySelector("[data-tab-id]");
+ const innerRow = tab?.parentElement;
+ return {
+ scrollWidth: el.scrollWidth,
+ clientWidth: el.clientWidth,
+ outerOverflowX: getComputedStyle(el).overflowX,
+ innerOverflowX: innerRow ? getComputedStyle(innerRow).overflowX : null,
+ };
+ });
+
+ // Sanity: the outer scroller is configured to scroll horizontally.
+ expect(
+ dims.outerOverflowX,
+ "outer scroller must allow horizontal scroll",
+ ).toMatch(/auto|scroll/);
+
+ // Bug-defining assertion 1: the inner row that holds the tabs must
+ // not clip overflow. With `overflow-x: hidden` on the inner row,
+ // the outer scrollbar never appears and the leftmost tabs are
+ // permanently clipped — even when the user tries to drag-scroll.
+ // This is the structural fix; PR #20326 (BYT-9495's fix) and the
+ // BYT-9457 fix both touch this region.
+ expect(
+ dims.innerOverflowX,
+ `inner tab row must not clip overflow ` +
+ `(got overflow-x=${JSON.stringify(dims.innerOverflowX)})`,
+ ).not.toBe("hidden");
+
+ // Bug-defining assertion 2 (consequence of #1): with the inner
+ // clipping, the outer scroller never sees more content than fits
+ // its viewport — scrollWidth collapses to clientWidth even with N
+ // overflowing tabs visibly clipped on screen. After the fix, the
+ // outer's scrollWidth should reflect the sum of tab widths and
+ // exceed clientWidth.
+ expect(
+ dims.scrollWidth,
+ `outer scroller must see overflow (got ${tabCount} tabs but ` +
+ `scrollWidth=${dims.scrollWidth} === clientWidth=${dims.clientWidth} ` +
+ `— inner overflow-hidden is masking the content width)`,
+ ).toBeGreaterThan(dims.clientWidth);
+ });
+});
+
+test.describe("Right-click on a tab opens the close-actions menu", () => {
+ // Right-click on a tab in the strip opens a Base UI dropdown menu
+ // with the standard set of close actions and (for worksheet tabs)
+ // a Rename item. Six items total when Rename is shown.
+
+ test("the menu lists Close / Close others / Close to the right / Close saved / Close all / Rename", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // Right-click the active tab (created by gotoWithDb).
+ await sqlEditor.activeTab().click({ button: "right" });
+
+ const expected = [
+ "Close",
+ "Close others",
+ "Close to the right",
+ "Close saved",
+ "Close all",
+ "Rename",
+ ];
+ for (const label of expected) {
+ await expect(
+ page.getByRole("menuitem", { name: label, exact: true }),
+ `menu must include "${label}"`,
+ ).toBeVisible({ timeout: 5000 });
+ }
+ });
+});
+
+test.describe("Closing a tab with unsaved changes prompts for confirmation", () => {
+ // When the user clicks the X on a tab with `status: DIRTY`, the
+ // editor must NOT close it silently — an AlertDialog appears and
+ // the close only proceeds after the user confirms. Without the
+ // confirmation, work would be lost on misclick.
+
+ test("dirty tab close opens an alert dialog before closing", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ // Type into Monaco to mark the tab dirty (status changes from
+ // CLEAN → DIRTY on the first keystroke). setEditorContent uses
+ // insertText to dispatch a real input event, so the dirty-state
+ // tracker actually fires.
+ await sqlEditor.setEditorContent("SELECT 1;");
+ await page.waitForTimeout(300);
+ expect(
+ await sqlEditor.activeTabStatus(),
+ "tab must be DIRTY before we attempt to close it",
+ ).toBe("DIRTY");
+
+ // The trailing icon swap: when the tab is DIRTY and not hovered,
+ // the suffix renders a Circle (unsaved indicator). Hovering the
+ // suffix div swaps it to the X close button (Suffix.tsx:
+ // hovering ? "close" : icon). React's onMouseEnter only fires
+ // when entering the suffix element itself — hovering the parent
+ // tab doesn't bubble — so we hover the suffix container and then
+ // click the X that appears.
+ const suffix = sqlEditor.activeTab().locator(".suffix").first();
+ await suffix.hover();
+ const closeIcon = suffix.locator("svg.lucide-x").first();
+ await expect(closeIcon).toBeVisible({ timeout: 5000 });
+ await closeIcon.click();
+
+ // The unsaved-changes alert appears; closing it via Cancel
+ // leaves the tab in place (no work lost).
+ const dialog = page.getByRole("alertdialog");
+ await expect(dialog).toBeVisible({ timeout: 5000 });
+ // Cancel keeps the tab.
+ await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
+ await expect(dialog).not.toBeVisible({ timeout: 5000 });
+ await expect(sqlEditor.activeTab()).toBeVisible();
+ });
+});
+
+test.describe("Unsaved tabs carry the status-dirty class", () => {
+ // The DIRTY status is what TabItem uses to render the dirty-state
+ // affordance (the dot icon instead of the file icon). Asserting on
+ // the className keeps the regression check stable even if the icon
+ // swap changes shape.
+
+ test("typing into Monaco flips the active tab to status-dirty", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await page.waitForTimeout(800);
+
+ expect(
+ await sqlEditor.activeTabStatus(),
+ "tab starts CLEAN before any edits",
+ ).toBe("CLEAN");
+
+ await sqlEditor.setEditorContent("SELECT 1;");
+ await page.waitForTimeout(300);
+
+ expect(
+ await sqlEditor.activeTabStatus(),
+ "tab must flip to DIRTY after typing into Monaco",
+ ).toBe("DIRTY");
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts b/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts
new file mode 100644
index 0000000000..13ef19cf04
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-worksheet.spec.ts
@@ -0,0 +1,331 @@
+// SQL Editor — worksheet operations.
+//
+// Covers worksheet-level actions taken from the sidebar tree:
+// create, duplicate, delete, save, search. Tests in this file each
+// set up their own worksheet via the API and drop it in afterAll,
+// never reusing demo data.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+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();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+test.describe("Duplicate", () => {
+ // The duplicate handler in SheetTree.tsx (around line 1152) calls
+ // editorWorksheetStore.createWorksheet({ title, folders, database })
+ // and is missing the `content` (or `statement`) field. As a result the
+ // duplicated worksheet inherits the title and connection but its body
+ // is empty — a silent data-loss bug visible only after clicking into
+ // the new tab.
+ //
+ // Bug evidence: .playwright-cli/qa-session-2026-05-12/r25-r26-duplicate/
+ // - 02-after-duplicate-empty.png
+ // - 03-notes.txt
+
+ const SOURCE_CONTENT = "SELECT 42;";
+ const SOURCE_TITLE = `e2e-duplicate-${Date.now()}`;
+
+ let sourceWorksheet = "";
+ let duplicateWorksheet = "";
+
+ test.beforeAll(async () => {
+ const created = await env.api.createWorksheet(
+ env.project,
+ SOURCE_TITLE,
+ env.database,
+ SOURCE_CONTENT,
+ );
+ sourceWorksheet = created.name;
+ });
+
+ test.afterAll(async () => {
+ if (sourceWorksheet) await env.api.deleteWorksheet(sourceWorksheet);
+ if (duplicateWorksheet) await env.api.deleteWorksheet(duplicateWorksheet);
+ });
+
+ test("duplicating a worksheet preserves the SQL body", async () => {
+ // R26 — Duplicate drops the SQL body. Queued as not-high-priority;
+ // mark expected-fail until the SheetTree.tsx duplicate handler is
+ // patched to pass `content` through. Passing here will re-flag it
+ // for marker removal.
+ test.fail();
+ test.setTimeout(120_000);
+ const sourceUuid = sourceWorksheet.split("/").pop()!;
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoSheet(projectId, sourceUuid);
+ await page.waitForTimeout(1500);
+
+ // Sanity: the source tab matches what we created. Without this, a
+ // failure later would conflate setup error with the bug.
+ await expect(sqlEditor.activeTab()).toContainText(SOURCE_TITLE, {
+ timeout: 10_000,
+ });
+
+ // Right-click the source row in the sidebar tree to open the
+ // worksheet context menu. Anchor by the unique title text.
+ const sourceRow = page
+ .locator(".worksheet-tree")
+ .getByText(SOURCE_TITLE)
+ .first();
+ await expect(sourceRow).toBeVisible({ timeout: 10_000 });
+ await sourceRow.click({ button: "right" });
+
+ const duplicateItem = page.getByRole("menuitem", {
+ name: "Duplicate",
+ exact: true,
+ });
+ await expect(duplicateItem).toBeVisible({ timeout: 5000 });
+ await duplicateItem.click();
+
+ // The AlertDialog ("Confirm to duplicate this worksheet?") opens.
+ const dialog = page.getByRole("alertdialog");
+ await expect(dialog).toBeVisible({ timeout: 5000 });
+
+ // Capture the duplicated UUID from the URL change so afterAll can
+ // clean up regardless of whether the assertion below passes.
+ const projectPrefix = env.project;
+ const urlPromise = page.waitForURL(
+ (url) => {
+ const m = url.pathname.match(/\/sheets\/([0-9a-f-]+)/i);
+ return !!m && m[1] !== sourceUuid;
+ },
+ { timeout: 10_000 },
+ );
+
+ await dialog.getByRole("button", { name: "Confirm", exact: true }).click();
+ await urlPromise;
+
+ const newUuid = page.url().match(/\/sheets\/([0-9a-f-]+)/i)?.[1];
+ if (newUuid) {
+ duplicateWorksheet = `${projectPrefix}/worksheets/${newUuid}`;
+ }
+
+ // Wait for Monaco on the new tab to settle before reading its value.
+ await expect(sqlEditor.codeEditor).toBeVisible({ timeout: 10_000 });
+ await page.waitForTimeout(1000);
+
+ // Read the duplicated tab's content from the DOM. `window.monaco` is
+ // NOT exposed on the production React bundle, so a getEditors() read
+ // always yields "" — which would make this expected-fail hold pass
+ // forever, even once the SheetTree duplicate handler is fixed. The DOM
+ // reader walks the rendered `.view-lines`; "longest" ignores empty side
+ // panes so a fixed duplicate (carrying the SQL body) is actually seen.
+ const editorValue = await sqlEditor.readEditorContent({ which: "longest" });
+
+ expect(editorValue).toBe(SOURCE_CONTENT);
+ });
+});
+
+test.describe("Right-click → Delete prompts for confirmation and removes the worksheet", () => {
+ // Deleting a worksheet from the sidebar must surface a confirm
+ // dialog before the destructive action. After confirmation, the
+ // worksheet vanishes from the sidebar tree.
+
+ const TARGET_TITLE = `e2e-delete-${Date.now()}`;
+
+ let createdWorksheet = "";
+
+ test.beforeAll(async () => {
+ const created = await env.api.createWorksheet(
+ env.project,
+ TARGET_TITLE,
+ env.database,
+ "SELECT 'to-delete';",
+ );
+ createdWorksheet = created.name;
+ });
+
+ test.afterAll(async () => {
+ // If the test deleted the worksheet, the API delete here is a
+ // no-op. If the test failed before deletion, this cleans up.
+ if (createdWorksheet) {
+ await env.api.deleteWorksheet(createdWorksheet);
+ }
+ });
+
+ test("confirming the alert removes the worksheet from the sidebar", async () => {
+ test.setTimeout(120_000);
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoHome();
+ await page.waitForTimeout(800);
+
+ // The worksheet appears in the sidebar tree under "Mine" — find
+ // by its unique title.
+ const row = page
+ .locator(".worksheet-tree")
+ .getByText(TARGET_TITLE)
+ .first();
+ await expect(row).toBeVisible({ timeout: 10_000 });
+ await row.click({ button: "right" });
+
+ const deleteItem = page.getByRole("menuitem", {
+ name: "Delete",
+ exact: true,
+ });
+ await expect(deleteItem).toBeVisible({ timeout: 5000 });
+ await deleteItem.click();
+
+ const dialog = page.getByRole("alertdialog");
+ await expect(dialog).toBeVisible({ timeout: 5000 });
+ // The destructive confirm reads "Delete" (matches the action) —
+ // not "Confirm" like the duplicate-worksheet dialog uses.
+ await dialog.getByRole("button", { name: "Delete", exact: true }).click();
+ await expect(dialog).not.toBeVisible({ timeout: 5000 });
+
+ // The row must disappear from the sidebar tree.
+ await expect(
+ page.locator(".worksheet-tree").getByText(TARGET_TITLE),
+ ).toHaveCount(0, { timeout: 10_000 });
+
+ // Mark the worksheet as already deleted so afterAll doesn't
+ // double-delete (deleteWorksheet swallows errors but log noise
+ // would suggest a real problem).
+ void projectId;
+ createdWorksheet = "";
+ });
+});
+
+test.describe("Sidebar search filters the worksheet list", () => {
+ // Typing into the "Search Sheets" input filters the visible
+ // worksheet rows to those whose title matches the keyword.
+ // Non-matching rows must disappear; matching rows must stay.
+
+ // Two worksheets with distinct unique tokens — the search keyword
+ // matches one and excludes the other.
+ const STAMP = Date.now();
+ const NEEDLE_TITLE = `e2e-search-needle-${STAMP}`;
+ const HAYSTACK_TITLE = `e2e-search-other-${STAMP}`;
+ let needleWorksheet = "";
+ let haystackWorksheet = "";
+
+ test.beforeAll(async () => {
+ needleWorksheet = (
+ await env.api.createWorksheet(
+ env.project,
+ NEEDLE_TITLE,
+ env.database,
+ "SELECT 1;",
+ )
+ ).name;
+ haystackWorksheet = (
+ await env.api.createWorksheet(
+ env.project,
+ HAYSTACK_TITLE,
+ env.database,
+ "SELECT 2;",
+ )
+ ).name;
+ });
+
+ test.afterAll(async () => {
+ if (needleWorksheet) await env.api.deleteWorksheet(needleWorksheet);
+ if (haystackWorksheet) await env.api.deleteWorksheet(haystackWorksheet);
+ });
+
+ test('typing "needle" hides the non-matching worksheet', async () => {
+ test.setTimeout(120_000);
+
+ await sqlEditor.gotoHome();
+ await page.waitForTimeout(800);
+
+ // Both worksheets visible at baseline.
+ await expect(
+ page.locator(".worksheet-tree").getByText(NEEDLE_TITLE),
+ ).toBeVisible({ timeout: 10_000 });
+ await expect(
+ page.locator(".worksheet-tree").getByText(HAYSTACK_TITLE),
+ ).toBeVisible();
+
+ // The Search Sheets input is a textbox in the worksheet pane.
+ const search = page.getByPlaceholder("Search Sheets").first();
+ await expect(search).toBeVisible({ timeout: 5000 });
+ await search.fill("needle");
+ // Search is debounced (DEBOUNCE_SEARCH_DELAY constant in the
+ // worksheet store). Wait for the filter to settle.
+ await page.waitForTimeout(800);
+
+ // Needle stays, haystack disappears.
+ await expect(
+ page.locator(".worksheet-tree").getByText(NEEDLE_TITLE),
+ ).toBeVisible();
+ await expect(
+ page.locator(".worksheet-tree").getByText(HAYSTACK_TITLE),
+ ).toHaveCount(0);
+
+ // Reset for any sibling describe sharing the page.
+ await search.fill("");
+ await page.waitForTimeout(400);
+ });
+});
+
+test.describe("Mine / Shared / Draft folders collapse and re-expand", () => {
+ // Each top-level folder in the worksheet tree (Mine, Shared, Draft)
+ // is independently collapsible. Clicking a folder header toggles
+ // its expanded state — its children disappear, and clicking again
+ // brings them back.
+
+ const STAMP = Date.now();
+ const TITLE = `e2e-collapse-${STAMP}`;
+ let createdWorksheet = "";
+
+ test.beforeAll(async () => {
+ // Create one worksheet under Mine so we have a child whose
+ // visibility we can probe.
+ createdWorksheet = (
+ await env.api.createWorksheet(
+ env.project,
+ TITLE,
+ env.database,
+ "SELECT 1;",
+ )
+ ).name;
+ });
+
+ test.afterAll(async () => {
+ if (createdWorksheet) await env.api.deleteWorksheet(createdWorksheet);
+ });
+
+ test("clicking Mine hides its children, clicking again restores them", async () => {
+ test.setTimeout(120_000);
+
+ await sqlEditor.gotoHome();
+ await page.waitForTimeout(800);
+
+ const child = page.locator(".worksheet-tree").getByText(TITLE).first();
+ await expect(child).toBeVisible({ timeout: 10_000 });
+
+ const mineFolder = page
+ .locator(".worksheet-tree")
+ .getByRole("treeitem")
+ .filter({ hasText: /^Mine$/ })
+ .first();
+ await expect(mineFolder).toBeVisible({ timeout: 5000 });
+
+ // First click collapses Mine — child should disappear from the
+ // rendered tree.
+ await mineFolder.click();
+ await expect(child).toHaveCount(0, { timeout: 5000 });
+
+ // Second click re-expands.
+ await mineFolder.click();
+ await expect(child).toBeVisible({ timeout: 5000 });
+ });
+});
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.ts
new file mode 100644
index 0000000000..a6bc5f8583
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor-workspace-gates.spec.ts
@@ -0,0 +1,190 @@
+// SQL Editor — workspace-level QueryDataPolicy gates (Batch 9, M-series).
+//
+// Covers:
+// - M1 disableExport hides the result toolbar's Export button.
+// - M2 disableCopyData hides the Copy button on a non-empty result.
+//
+// Both fields live on a `QueryDataPolicy` policy attached to the
+// workspace resource (PolicyType.DATA_QUERY). We capture the current
+// policy in `beforeAll`, mutate per-test, and restore on `afterEach` so
+// other specs see the original baseline.
+//
+// Deferred from this batch (need separate investigation):
+// - M3 maximumResultRows enforcement — frontend caps the row-limit
+// input (QueryContextSettingPopover) but backend enforcement is
+// less obvious; whose responsibility under what circumstances?
+// - M5 allowAdminDataSource gating the admin radio — requires an
+// environment with both admin + readonly data sources.
+// - M8 admin bypass on no-readonly — needs a fixture user without
+// readonly access; the I-series user provisioning pattern applies.
+//
+// LICENSE GATE: `FEATURE_QUERY_POLICY` / `FEATURE_RESTRICT_COPYING_DATA`
+// gate UI controls; mutations of QueryDataPolicy may also be backend-
+// gated. We try the mutation and skip the test gracefully if the API
+// returns 403.
+
+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 { SqlEditorPage } from "./sql-editor.page";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let workspace = "";
+let sharedContext: BrowserContext;
+let page: Page;
+let sqlEditor: SqlEditorPage;
+
+// Snapshot of the original QueryDataPolicy body so afterEach can restore.
+// Stored as the raw policy resource so we can re-PATCH with the same shape.
+let originalQueryDataPolicy: {
+ disableExport?: boolean;
+ disableCopyData?: boolean;
+ allowAdminDataSource?: boolean;
+ maximumResultRows?: number;
+} = {};
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ await env.api.login(env.adminEmail, env.adminPassword);
+ ({ workspace } = await env.api.getActuatorInfo());
+
+ // Snapshot the current workspace-level QueryDataPolicy (may not exist
+ // yet on a fresh server — getPolicy returns null on 404).
+ const existing = await env.api.getPolicy(`${workspace}/policies/data_query`);
+ if (existing && typeof existing === "object") {
+ originalQueryDataPolicy = (existing as {
+ queryDataPolicy?: typeof originalQueryDataPolicy;
+ }).queryDataPolicy ?? {};
+ }
+
+ sharedContext = await browser.newContext({ storageState: ".auth/state.json" });
+ page = await sharedContext.newPage();
+ sqlEditor = new SqlEditorPage(page, env.baseURL);
+});
+
+test.afterAll(async () => {
+ await sharedContext?.close();
+});
+
+// Restore the original policy (or remove ours) after every test so
+// state from one gate test doesn't shift another's baseline.
+test.afterEach(async () => {
+ await env.api
+ .upsertPolicy(workspace, "data_query", {
+ name: `${workspace}/policies/data_query`,
+ type: "DATA_QUERY",
+ resourceType: "WORKSPACE",
+ queryDataPolicy: {
+ disableExport: originalQueryDataPolicy.disableExport ?? false,
+ disableCopyData: originalQueryDataPolicy.disableCopyData ?? false,
+ allowAdminDataSource:
+ originalQueryDataPolicy.allowAdminDataSource ?? false,
+ maximumResultRows: originalQueryDataPolicy.maximumResultRows ?? 0,
+ },
+ })
+ .catch(() => {
+ /* ignore — license gate may reject; baseline already in place */
+ });
+});
+
+// Helper — try to apply a workspace-level QueryDataPolicy mutation. If
+// the gateway returns 403 (FEATURE_QUERY_POLICY / FEATURE_RESTRICT_COPYING_DATA
+// require enterprise), test skips so we don't false-fail on free plan.
+async function applyQueryDataPolicy(
+ patch: Partial<typeof originalQueryDataPolicy>,
+): Promise<void> {
+ await env.api.upsertPolicy(workspace, "data_query", {
+ name: `${workspace}/policies/data_query`,
+ type: "DATA_QUERY",
+ resourceType: "WORKSPACE",
+ queryDataPolicy: {
+ // Preserve all other fields; only mutate the ones the test cares
+ // about.
+ disableExport:
+ patch.disableExport ?? originalQueryDataPolicy.disableExport ?? false,
+ disableCopyData:
+ patch.disableCopyData ??
+ originalQueryDataPolicy.disableCopyData ??
+ false,
+ allowAdminDataSource:
+ patch.allowAdminDataSource ??
+ originalQueryDataPolicy.allowAdminDataSource ??
+ false,
+ maximumResultRows:
+ patch.maximumResultRows ??
+ originalQueryDataPolicy.maximumResultRows ??
+ 0,
+ },
+ });
+}
+
+test.describe("disableExport hides the result toolbar Export button (M1)", () => {
+ test("setting disableExport=true removes the Export button from a non-empty result", async () => {
+ // QueryDataPolicy enforcement is enterprise-gated; the license is installed at bootstrap.
+ await applyQueryDataPolicy({ disableExport: true });
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // No Export button in the result toolbar.
+ await expect(
+ page.getByRole("button", { name: /^Export/ }),
+ ).toHaveCount(0);
+ });
+
+ test("with disableExport=false (baseline) the Export button is present", async () => {
+ await applyQueryDataPolicy({ disableExport: false }).catch(() => {});
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ await expect(
+ page.getByRole("button", { name: /^Export/ }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+});
+
+test.describe("disableCopyData hides the Copy button on results (M2)", () => {
+ test("setting disableCopyData=true removes the Copy button", async () => {
+ await applyQueryDataPolicy({ disableCopyData: true });
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ // Copy button (rendered when !disallowCopyingData && rows.length > 0)
+ // must NOT be in the toolbar. Anchor exact-match so "Copy others"
+ // etc. don't bleed in.
+ await expect(
+ page.getByRole("button", { name: "Copy", exact: true }),
+ ).toHaveCount(0);
+ });
+
+ test("with disableCopyData=false (baseline) the Copy button is present", async () => {
+ await applyQueryDataPolicy({ disableCopyData: false }).catch(() => {});
+
+ const projectId = env.project.split("/").pop()!;
+ await sqlEditor.gotoWithDb(projectId, env.instanceId, env.databaseId);
+ await sqlEditor.runPreparedQuery("SELECT 1 AS n;");
+ await expect(page.getByText(/^1\s+rows?$/i).first()).toBeVisible({
+ timeout: 10_000,
+ });
+
+ await expect(
+ page.getByRole("button", { name: "Copy", exact: true }).first(),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+});
diff --git a/frontend/tests/e2e/sql-editor/sql-editor.page.ts b/frontend/tests/e2e/sql-editor/sql-editor.page.ts
new file mode 100644
index 0000000000..d59be7bd87
--- /dev/null
+++ b/frontend/tests/e2e/sql-editor/sql-editor.page.ts
@@ -0,0 +1,191 @@
+import { type Page, type Locator } from "@playwright/test";
+
+// Page object for the React-migrated SQL Editor.
+// Replaces the helpers that previously lived alongside the Vue components.
+export class SqlEditorPage {
+ readonly page: Page;
+ private baseURL: string;
+
+ readonly codeEditor: Locator;
+ readonly runButton: Locator;
+ readonly saveButton: Locator;
+ readonly adminModeButton: Locator;
+ readonly gutterWorksheetTab: Locator;
+ readonly gutterSchemaTab: Locator;
+ readonly gutterHistoryTab: Locator;
+ readonly gutterAccessTab: Locator;
+
+ constructor(page: Page, baseURL = "") {
+ this.page = page;
+ this.baseURL = baseURL;
+ // Monaco-editor exposes role="code" on the editor surface.
+ // Clicking this is the only reliable way to give the editor focus —
+ // .focus() on the ime-text-area is insufficient (Monaco's focus chain
+ // does not fire) and the role="textbox" wrapper is not the input.
+ this.codeEditor = page.getByRole("code");
+ // The Run button is rendered as an icon-only <button> with a
+ // lucide-play SVG. The visible label is the row-limit dropdown
+ // ("(limit 1000)"), not "Run" — so we locate by play icon.
+ this.runButton = page.locator("button").filter({ has: page.locator("svg.lucide-play") }).first();
+ this.saveButton = page.getByRole("button", { name: "Save", exact: true });
+ // AdminModeButton has a lucide-wrench icon and renders only when
+ // editorStore.allowAdmin && currentTab.mode === "WORKSHEET".
+ //
+ // Scoping note: the workspace-level "Bytebase has not configured
+ // --external-url" banner (frontend/src/react/components/BannersWrapper.tsx)
+ // ALSO renders a button with a lucide-wrench icon ("Configure now").
+ // The framework's seed-test-data fixture silences that banner by
+ // setting an external URL during setup, but we still anchor by the
+ // editor's own warning-color class (`border-warning`, applied in
+ // frontend/src/react/components/sql-editor/AdminModeButton.tsx:53)
+ // so the locator stays correct even if a future build re-introduces
+ // the banner.
+ this.adminModeButton = page
+ .locator("button.border-warning")
+ .filter({ has: page.locator("svg.lucide-wrench") })
+ .first();
+ this.gutterWorksheetTab = page.getByRole("button", { name: "Worksheet", exact: true });
+ this.gutterSchemaTab = page.getByRole("button", { name: "Schema", exact: true });
+ this.gutterHistoryTab = page.getByRole("button", { name: "History", exact: true });
+ // ACCESS gutter tab only renders when project.allowJustInTimeAccess=true.
+ // The button's screen-reader name comes from i18n key
+ // `sql-editor.jit` → "Just-In-Time Access" (not the shorter "Access"
+ // — that's the label of an entirely different "Data Access" sidebar
+ // entry in the workspace nav).
+ this.gutterAccessTab = page.getByRole("button", {
+ name: "Just-In-Time Access",
+ exact: true,
+ });
+ }
+
+ async gotoHome() {
+ await this.page.goto(`${this.baseURL}/sql-editor`);
+ await this.page.keyboard.press("Escape").catch(() => {});
+ await this.page.waitForLoadState("networkidle").catch(() => {});
+ }
+
+ async gotoWithDb(projectId: string, instanceId: string, dbName: string) {
+ // Direct DB URL avoids stale editor state from prior navigations.
+ await this.page.goto(
+ `${this.baseURL}/sql-editor/projects/${projectId}/instances/${instanceId}/databases/${dbName}`
+ );
+ await this.page.keyboard.press("Escape").catch(() => {});
+ await this.page.waitForTimeout(2000);
+ }
+
+ async gotoSheet(projectId: string, sheetUuid: string) {
+ await this.page.goto(
+ `${this.baseURL}/sql-editor/projects/${projectId}/sheets/${sheetUuid}`
+ );
+ await this.page.keyboard.press("Escape").catch(() => {});
+ await this.page.waitForTimeout(1000);
+ }
+
+ // Type a query into Monaco. Each keystroke costs a network turn on
+ // CDP; keep queries short. Uses delay: 10 to avoid dropped keys.
+ async typeQuery(sql: string) {
+ await this.codeEditor.click();
+ await this.page.waitForTimeout(150);
+ await this.page.keyboard.press("ControlOrMeta+a");
+ await this.page.waitForTimeout(50);
+ await this.page.keyboard.press("Delete");
+ await this.page.waitForTimeout(50);
+ await this.page.keyboard.type(sql, { delay: 10 });
+ await this.page.waitForTimeout(200);
+ }
+
+ async runQuery(sql: string) {
+ await this.typeQuery(sql);
+ await this.runButton.click();
+ // Result is either an N-rows footer (success) or an inline ERROR card.
+ await Promise.race([
+ this.page.getByText(/\d+ rows?/i).first().waitFor({ timeout: 15000 }),
+ this.page.getByText(/ERROR[: ]/).first().waitFor({ timeout: 15000 }),
+ ]).catch(() => {});
+ await this.page.waitForTimeout(300);
+ }
+
+ // Replace the active Monaco editor's content reliably. `keyboard.type`
+ // with delay<30ms/key occasionally drops the first character (e.g.,
+ // turning "SELECT" into "SEECT") and the resulting syntax error masks
+ // any downstream assertion. `insertText` paints the whole string into
+ // the focused control in a single CDP call AND fires the synthetic
+ // input event, so Monaco's dirty-state tracking and Run-button enable
+ // logic both update — unlike a raw `monaco.editor.getEditors()[i].setValue`
+ // call which the editor treats as programmatic and ignores.
+ async setEditorContent(
+ sql: string,
+ opts: { which?: "first" | "last" } = {},
+ ): Promise<void> {
+ // `which: "last"` targets the admin terminal's editable prompt (the
+ // last role="code"); older terminal rows are read-only.
+ const editor =
+ opts.which === "last" ? this.codeEditor.last() : this.codeEditor;
+ await editor.click();
+ await this.page.waitForTimeout(150);
+ await this.page.keyboard.press("ControlOrMeta+a");
+ await this.page.waitForTimeout(50);
+ await this.page.keyboard.press("Delete");
+ await this.page.waitForTimeout(50);
+ await this.page.keyboard.insertText(sql);
+ await this.page.waitForTimeout(200);
+ }
+
+ // Read a Monaco editor's content by walking the DOM. `window.monaco` is
+ // NOT exposed on the production React bundle, so any read MUST go through
+ // the rendered `.view-lines` (a `monaco.editor.getEditors()` read returns
+ // undefined and silently yields ""). `which`:
+ // - "first" the first role="code" surface (the worksheet editor)
+ // - "last" the last surface (the admin terminal's editable prompt)
+ // - "longest" the surface with the most content (ignores empty panes)
+ async readEditorContent(
+ opts: { which?: "first" | "last" | "longest" } = {},
+ ): Promise<string> {
+ const which = opts.which ?? "first";
+ return await this.page.evaluate((which) => {
+ const codes = Array.from(document.querySelectorAll('[role="code"]'));
+ if (codes.length === 0) return "";
+ const textOf = (code: Element): string =>
+ Array.from(code.querySelectorAll(".view-lines .view-line"))
+ .map((l) => (l.textContent ?? "").replace(/ /g, " "))
+ .join("\n");
+ const texts = codes.map(textOf);
+ let value: string;
+ if (which === "last") value = texts[texts.length - 1] ?? "";
+ else if (which === "longest")
+ value = texts.reduce((best, v) => (v.length >= best.length ? v : best), "");
+ else value = texts[0] ?? "";
+ return value.trim();
+ }, which);
+ }
+
+ async runPreparedQuery(sql: string): Promise<void> {
+ await this.setEditorContent(sql);
+ await this.runButton.click();
+ await Promise.race([
+ this.page.getByText(/\d+ rows?/i).first().waitFor({ timeout: 15000 }),
+ this.page.getByText(/ERROR[: ]/).first().waitFor({ timeout: 15000 }),
+ ]).catch(() => {});
+ await this.page.waitForTimeout(300);
+ }
+
+ // Returns number of [data-tab-id] elements currently in the DOM.
+ async tabCount(): Promise<number> {
+ return await this.page.locator("[data-tab-id]").count();
+ }
+
+ // Returns the active (current) tab element, or null if none.
+ activeTab(): Locator {
+ return this.page.locator("[data-tab-id].current").first();
+ }
+
+ // Tab status is encoded as a class on [data-tab-id]: "status-dirty"
+ // when unsaved, "status-clean" otherwise (per TabList state model).
+ async activeTabStatus(): Promise<"DIRTY" | "CLEAN" | "UNKNOWN"> {
+ const cls = (await this.activeTab().getAttribute("class")) ?? "";
+ if (cls.includes("status-dirty")) return "DIRTY";
+ if (cls.includes("status-clean")) return "CLEAN";
+ return "UNKNOWN";
+ }
+
+}
diff --git a/frontend/tests/e2e/workspace/workspace-banner.spec.ts b/frontend/tests/e2e/workspace/workspace-banner.spec.ts
new file mode 100644
index 0000000000..0106f94cfa
--- /dev/null
+++ b/frontend/tests/e2e/workspace/workspace-banner.spec.ts
@@ -0,0 +1,100 @@
+// Workspace-level external-URL banner.
+//
+// BannersWrapper.tsx (line 352) renders the "Bytebase has not configured
+// --external-url" banner when `serverInfo.externalUrl` is empty AND the
+// frontend is NOT in dev mode. The banner ships a wrench icon + a
+// "Configure now" button that links to the workspace general settings.
+//
+// `seedTestData` silences the banner by setting a workspace external_url
+// during setup-project. This spec is the defense-in-depth pair:
+// 1. With external_url set (the default state) — banner is absent.
+// 2. With external_url cleared — banner is visible with the wrench +
+// "Configure now" + dismiss controls.
+//
+// We capture the original external_url in beforeAll and restore it in
+// afterAll so the rest of the suite continues with seeded state.
+
+import {
+ test,
+ expect,
+ type Page,
+ type BrowserContext,
+} from "@playwright/test";
+import { loadTestEnv, type TestEnv } from "../framework/env";
+import { BytebaseApiClient } from "../framework/api-client";
+
+test.setTimeout(120_000);
+
+let env: TestEnv & { api: BytebaseApiClient };
+let sharedContext: BrowserContext;
+let page: Page;
+let originalExternalUrl = "";
+
+test.beforeAll(async ({ browser }) => {
+ env = loadTestEnv();
+ await env.api.login(env.adminEmail, env.adminPassword);
+
+ // Snapshot the workspace external_url so we can restore it after the
+ // "banner-on" test clears it.
+ const setting = await env.api.getSetting("WORKSPACE_PROFILE");
+ originalExternalUrl =
+ (
+ (setting?.value as { workspaceProfile?: { externalUrl?: string } })
+ ?.workspaceProfile?.externalUrl ?? ""
+ );
+
+ sharedContext = await browser.newContext({
+ storageState: ".auth/state.json",
+ });
+ page = await sharedContext.newPage();
+});
+
+test.afterAll(async () => {
+ // Always restore the seeded URL — other specs (and the framework's
+ // own admin-mode wrench locator scoping) depend on the banner being
+ // silenced.
+ if (originalExternalUrl) {
+ await env.api.setWorkspaceExternalUrl(originalExternalUrl).catch(() => {});
+ }
+ await sharedContext?.close();
+});
+
+test.describe("External-URL banner", () => {
+ test.describe.configure({ mode: "serial" });
+
+ test("with external_url set, the banner is not rendered", async () => {
+ // Sanity: seedTestData should have run and set a URL already.
+ expect(originalExternalUrl).not.toBe("");
+
+ await page.goto(env.baseURL);
+ await page.waitForLoadState("networkidle");
+
+ // The configure CTA + wrench icon are the visible signal of the
+ // banner. Both must be absent.
+ await expect(
+ page.getByRole("button", { name: /Configure now/i }),
+ ).toHaveCount(0);
+ });
+
+ test("clearing external_url makes the banner appear with wrench + Configure now", async () => {
+ // Empty string flips `needConfigureExternalUrl()` to true on the
+ // server-info store.
+ await env.api.setWorkspaceExternalUrl("");
+
+ await page.goto(env.baseURL);
+ await page.waitForLoadState("networkidle");
+
+ const configureNow = page
+ .getByRole("button", { name: /Configure now/i })
+ .first();
+ await expect(configureNow).toBeVisible({ timeout: 10_000 });
+
+ // The button hosts a Wrench svg from lucide-react. Scope to the
+ // button so we don't match an unrelated wrench elsewhere on the
+ // page (e.g., the SQL editor's admin-mode button on other routes,
+ // though it shouldn't be rendered on the landing page).
+ await expect(
+ configureNow.locator("svg.lucide-wrench"),
+ ).toBeVisible({ timeout: 5_000 });
+ });
+});