Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(sql-editor): runtime theme switching (dev-only) + token migration & UI polish (#20602)
ecmadaobe0bbb68ecab
diff --git a/docs/superpowers/specs/2026-06-09-sql-editor-theme-pattern-design.md b/docs/superpowers/specs/2026-06-09-sql-editor-theme-pattern-design.mdindex 10255b0b5c..ca0ef363dd 100644--- a/docs/superpowers/specs/2026-06-09-sql-editor-theme-pattern-design.md+++ b/docs/superpowers/specs/2026-06-09-sql-editor-theme-pattern-design.md@@ -12,10 +12,34 @@ preference, and the `ThemeSelect` toolbar switcher all landed as designed. Thefollowing diverged during implementation (driven by how the codingame VSCode Monacoruntime and the real DOM behave):-- **Catalog reduced to two themes: `light` + `dark`.** Solarized×2, Monokai, and Nord- were dropped — two polished themes beat six half-finished ones. `syntax` is therefore- unused in practice: both presets omit it and inherit `vs`/`vs-dark` verbatim (the- `SyntaxPalette` machinery stays for the documented custom-theme future).+- **Catalog: `light`, `dark`, and `solarized-dark`.** Solarized Dark shipped as the first+ named theme; the other originally-planned named themes (Solarized Light, Monokai, Nord)+ were not authored.+- **The Monaco `editor`/`syntax` theme layer was removed entirely.** This app runs Monaco+ through the codingame VSCode theme service, which **ignores `monaco.editor.defineTheme`**,+ so per-theme editor colors and syntax palettes never reach the canvas. The+ `SQLEditorTheme.editor` / `.syntax` fields and the `EditorChromeColors` / `SyntaxPalette`+ types are **deleted**; `buildMonacoTheme` now carries only the `vs`/`vs-dark` base + the+ word-highlight reset. A theme is just `{ id, name, monacoBase, tokens }`. (Authentic+ per-theme editor syntax would require registering real VSCode themes — a documented+ follow-up; see Future work.)+- **Editor background follows the chrome via a transparent canvas.** Because the canvas+ can't be themed through `defineTheme`, a scoped CSS rule makes the Monaco editor+ (`.sqleditor--wrapper .monaco-editor` + `-background` + `.margin`) transparent so it+ shows the chrome `--color-background`; syntax token colors come from the `vs`/`vs-dark`+ base. Transparent (not an opaque token) so Monaco's own overlays (current line,+ selection) still composite on top.+ - **Portaled editors opt in via a marker class.** The rule's primary selector is+ `.sqleditor--wrapper`-scoped, so a SQL-Editor `MonacoEditor` that portals outside+ that subtree (the access-request drawer's editor, mounted in the overlay root) would+ otherwise keep the opaque `vs`/`vs-dark` canvas and mismatch a named theme's chrome+ bg (e.g. Solarized Dark's teal). Such editors add the `sqleditor--monaco-transparent`+ marker class (a second selector on the same rule) plus `bg-background`, so the canvas+ shows the active theme's `--color-background` — consistent with the worksheet editor.+- **Theme names are literal labels; the switcher is dev-only.** `ThemeSelect` is gated+ behind `isDev()` (hidden in production), so theme names aren't translated:+ `SQLEditorTheme.name` is a plain display string (no i18n key) — built-ins, proper-noun+ presets (Solarized Dark), and future user-named custom themes all just set it.- **Monaco theming is per-editor + a *change-only* controller, not a mount-time global`setTheme`.** Calling `monaco.editor.setTheme` while an editor is still constructingraces the codingame theme service and throws → the editor falls back to a read-only@@ -53,6 +77,13 @@ runtime and the real DOM behave):and the one genuine terminal-vs-worksheet *layout* difference uses an explicit `compact`prop (`TerminalPanel` → `ResultView` → `SingleResultView`), not the theme. Net: colorsare 100% token-driven and a custom theme is just another token map.+- **Native controls follow `color-scheme`, not the tokens.** Browser/OS-drawn controls —+ `<input type="datetime-local">` calendar popups, scrollbars, native `<select>` popups —+ ignore our `--color-*` tokens entirely. The only lever is the CSS `color-scheme`+ property, so every theme-application site sets it from a `themeColorScheme(theme)`+ helper (`vs-dark → "dark"`): `SQLEditorThemeScope` (editor body, terminal), the request+ drawers' inline `SheetContent` style, and the overlay layer root. Without it a dark+ theme would show a white native date picker over the dark drawer.Net new files vs. the design: `theme/useSQLEditorOverlayTheme.ts`. The `getResolvedTheme`base-fallback is unit-tested in `monaco/core.test.ts`.@@ -66,21 +97,24 @@ named pre-defined themes ship alongside it. The model is shaped so that user-def**custom themes** can be added later with no re-architecture — a custom theme is justanother theme object.-> **Shipped reality:** the catalog was reduced to **two** themes (`light` + `dark`)-> before merge, and the `isDark` property was removed entirely — see-> [Implementation notes — as shipped](#implementation-notes--as-shipped) above, which-> is authoritative wherever it conflicts with the original design below.+> **Shipped reality:** the catalog ships **three** themes (`light`, `dark`,+> `solarized-dark`); the Monaco `editor`/`syntax` layer **and** `isDark` were removed; and+> theme `name` is a plain literal label (no i18n). The detailed `editor`/`syntax`/+> six-theme architecture in §1–§6 below is the **original design** — see+> [Implementation notes — as shipped](#implementation-notes--as-shipped) above, which is+> authoritative wherever it conflicts.-This phase ships a **catalog of pre-defined preset themes** (below), each with its-authentic Monaco syntax palette. Custom-theme editing UI, a "System" option, and-backend persistence are explicitly out of scope (see [Future work](#future-work)).+This phase ships a small **catalog of pre-defined preset themes** (below). Custom-theme+editing UI, a "System" option, and backend persistence are explicitly out of scope (see+[Future work](#future-work)).### Theme catalog| id | name | monacoBase | notes || --- | --- | --- | --- || `light` | Default Light | `vs` | today's `:root`/`bb` look, verbatim — the default |-| `dark` | Default Dark | `vs-dark` | Bytebase dark, inherits `vs-dark` chrome + tokens |+| `dark` | Default Dark | `vs-dark` | Bytebase dark, inherits `vs-dark` editor + chrome tokens |+| `solarized-dark` | Solarized Dark | `vs-dark` | first named theme; chrome only (editor stays `vs-dark` base) |## Locked decisions@@ -88,8 +122,8 @@ backend persistence are explicitly out of scope (see [Future work](#future-work)| --- | --- || End goal | Build the foundation for runtime-switchable themes || Scope | SQL Editor only — chrome + Monaco + result views |-| Granularity | Preset themes only — `light` + `dark` shipped (catalog above) |-| Syntax fidelity | Each named theme ships its full, authentic Monaco syntax palette |+| Granularity | Preset themes only — `light`, `dark`, `solarized-dark` shipped (catalog above) |+| Syntax fidelity | **Chrome only.** The codingame Monaco runtime ignores per-theme `defineTheme` colors, so editor **syntax** stays the `vs`/`vs-dark` base; the editor background follows the chrome via a transparent canvas. (Per-theme syntax would need real VSCode themes — see Future work.) || Token scoping | Scoped override — re-declare `--color-*` on the SQL Editor container || Persistence | localStorage, client-only, workspace-scoped || Theme representation | Approach A — theme is a plain JS token map; both layers derive from it |@@ -357,6 +391,26 @@ default (light) tokens. Visual tests (§ Testing) enumerate covered vs deferred(If app-scope chrome lands later, the whole portal problem disappears: tokens applied atapp root cascade into the shared overlay root automatically.)+> **As shipped — superseded by the overlay-root approach.** Rather than wrapping each+> portal in its own nested scope, `useSQLEditorOverlayTheme` themes the shared overlay+> *layer root* once with the **active** theme (so it also covers the Base-UI-internal+> popups that couldn't be re-scoped individually — they're no longer a follow-up). Two+> consequences for the surfaces above:+> - **`RequestRoleSheet` is theme-injected by its host via an explicit prop.** It's shared+> with non-SQL-Editor pages (`MembersPage`, `ComponentPermissionGuard`), so it must NOT+> read the active theme itself (leaks the SQL-Editor theme onto those pages) and must NOT+> read the shared theme *context* (any ambient `SQLEditorThemeScope` ancestor would bleed+> in). Instead it takes an optional `theme` prop and applies it as inline vars on its+> `SheetContent` (the Sheet portals to the overlay root, so inline-on-content is what+> reaches the portaled DOM). Only the SQL-Editor host (`RequestDrawerHost`) passes it —+> the **active** theme. With no prop, `SheetContent` is left unstyled and inherits+> `:root`, so the drawer **always** renders in the default light app theme outside the+> SQL Editor, regardless of any ambient scope.+> - **`AccessGrantRequestDrawer` keeps an explicit nested scope + inline `sheetStyle`,+> both keyed off the *active* theme** (it's SQL-Editor-only, so that's safe and also+> themes its embedded Monaco). Its Monaco additionally opts into the transparent-canvas+> rule via the `sqleditor--monaco-transparent` marker class.+**Nested admin scope.** Wrap `<TerminalPanel>`'s root div (`TerminalPanel.tsx:206`) in anested `SQLEditorThemeScope` whose theme is the **resolved admin theme**:@@ -605,13 +659,30 @@ MONACO (single global, driven by foreground panel — cannot be per-scope):## Future work (out of scope)-- Custom theme editor (color pickers / JSON), validation, and storage of arbitrary- palettes. The model already supports it — only UI + persistence of custom objects- is missing.+- **Custom theme editor — planned next.** A user-defined theme is just another+ `SQLEditorTheme` object, so the application/override path (scope cascade + Monaco)+ needs no change; the editor UI's only job is to *produce* a valid object+ (color pickers / JSON), guarded by the existing `validateTheme`. Confirmed direction+ (2026-06-15) — not built in v1. Landing it cleanly relies on three seams this design+ already establishes; keep them intact:+ 1. **Single resolution point** — `resolveThemeId(id)` is the only place that turns an+ id into a theme. Grow its source from `PRESET_BY_ID` → `{ …presets, …custom }` in+ that one spot; everything downstream takes the resolved object.+ 2. **`SQLEditorTheme` stays plain serializable data** (token map of `"r g b"` strings+ + hex strings — no functions/refs), so it persists to localStorage now and maps+ cleanly to a proto/`Setting` later.+ 3. **Runtime Monaco registration** — presets are `defineTheme`'d once at init+ (`monaco/core.ts`); custom themes need the same `defineTheme("bb-<id>", …)` on+ create/edit (else `getResolvedTheme` falls back to `bb-light`).++ The `name` field is already a plain literal label (no i18n — the switcher is dev-only,+ so theme names aren't translated), so a custom theme just sets `name` to the user's+ string; nothing special is needed there.+- **Backend / cross-device persistence — later (not now).** Confirmed direction+ (2026-06-15): the selected id + any custom theme objects move from localStorage to a+ user/workspace `Setting`, with localStorage as the offline/default fallback. No proto+ or store-shape change in v1; the serializable model (seam #2 above) makes this additive.- "System" preset following `prefers-color-scheme`.-- Backend/cross-device persistence of the theme choice.-- The deferred Base-UI-internal portal popups (ConnectChooser dropdown, EllipsisCell- tooltip) — re-scope their content under a dark/named theme.### Extensibility to app scopediff --git a/frontend/src/assets/css/tailwind.css b/frontend/src/assets/css/tailwind.cssindex 427eaa3974..eacf0ee854 100644--- a/frontend/src/assets/css/tailwind.css+++ b/frontend/src/assets/css/tailwind.css@@ -20,7 +20,11 @@::before,::backdrop,::file-selector-button {- border-color: var(--color-gray-200, currentcolor);+ /* Default border color uses the semantic --color-block-border token so it+ follows a scoped theme (e.g. the SQL Editor dark theme). The token is an+ "r g b" triple, so it MUST be wrapped in rgb(); the fallback is the old+ gray-200 value, so nothing changes outside a themed scope. */+ border-color: rgb(var(--color-block-border, 229 231 235));}/* Thin scrollbars globally */@@ -421,3 +425,30 @@body[data-bb-screenshot-active] [data-screenshot-hide] {display: none !important;}++/* SQL Editor: keep the Monaco canvas background in sync with the active theme.+ This app runs Monaco through the codingame VSCode theme service, which+ ignores `monaco.editor.defineTheme`, so our per-theme `editor.background`+ never reaches the canvas — the editor stays on the built-in vs/vs-dark base.+ That mismatches any named theme whose chrome background isn't `#1e1e1e`+ (e.g. Solarized Dark's teal).++ We make the base layers TRANSPARENT (not an opaque token color) so the SQL+ Editor's themed chrome shows through — matching the active theme for free —+ while leaving Monaco's own overlays (current-line, selection) compositing on+ top. An opaque background here instead covers the current-line highlight.+ (Syntax token colors are still owned by the VSCode theme service / TextMate.)+ `!important` overrides the theme service's `--vscode-editor-background` rule.++ Covers every editor under the SQL Editor root (`.sqleditor--wrapper`) plus any+ SQL-Editor Monaco that portals OUTSIDE that subtree (e.g. the access-request+ drawer's editor, which mounts in the overlay root) and so opts in explicitly+ via the `sqleditor--monaco-transparent` marker class on its container. */+.sqleditor--wrapper .monaco-editor,+.sqleditor--wrapper .monaco-editor .monaco-editor-background,+.sqleditor--wrapper .monaco-editor .margin,+.sqleditor--monaco-transparent .monaco-editor,+.sqleditor--monaco-transparent .monaco-editor .monaco-editor-background,+.sqleditor--monaco-transparent .monaco-editor .margin {+ background-color: transparent !important;+}diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex fc2b7e3824..556a6f427f 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2872,6 +2872,9 @@"table-empty-placeholder": "Click Run to execute the query.","table-view": "Table view","text-format": "Text format",+ "theme": {+ "self": "Theme"+ },"unable-to-connect-database": "Unable to connect to database {{name}}","upload-file": "Upload file","url-copied-to-clipboard": "The URL is copied to your clipboard",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex aa81c4852f..83ab89c921 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2872,6 +2872,9 @@"table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.","table-view": "Vista de tabla","text-format": "Formato de texto",+ "theme": {+ "self": "Tema"+ },"unable-to-connect-database": "No se puede conectar a la base de datos {{name}}","upload-file": "Subir archivo","url-copied-to-clipboard": "La URL se copia al portapapeles.",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 67582c34c3..caa2199f25 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2872,6 +2872,9 @@"table-empty-placeholder": "「実行」をクリックしてクエリを実行します。","table-view": "テーブルビュー","text-format": "テキスト形式",+ "theme": {+ "self": "テーマ"+ },"unable-to-connect-database": "データベース {{name}} に接続できません","upload-file": "ファイルをアップロードする","url-copied-to-clipboard": "URLがクリップボードにコピーされました",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 6b18b446eb..44636a981b 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2872,6 +2872,9 @@"table-empty-placeholder": "Nhấp vào Chạy để thực hiện truy vấn.","table-view": "Chế độ xem bảng","text-format": "Định dạng văn bản",+ "theme": {+ "self": "Giao diện"+ },"unable-to-connect-database": "Không thể kết nối đến cơ sở dữ liệu {{name}}","upload-file": "Tải lên tệp","url-copied-to-clipboard": "URL đã được sao chép vào bảng nhớ tạm của bạn",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex 3e45f8314e..aff15631a1 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2872,6 +2872,9 @@"table-empty-placeholder": "点击 \"运行\" 执行查询","table-view": "表格视图","text-format": "文本格式",+ "theme": {+ "self": "主题"+ },"unable-to-connect-database": "无法连接到数据库 {{name}}","upload-file": "上传文件","url-copied-to-clipboard": "URL 已复制到剪贴板",diff --git a/frontend/src/react/components/DatabaseResourceSelector.tsx b/frontend/src/react/components/DatabaseResourceSelector.tsxindex 52f5294332..300d26f2d6 100644--- a/frontend/src/react/components/DatabaseResourceSelector.tsx+++ b/frontend/src/react/components/DatabaseResourceSelector.tsx@@ -815,7 +815,7 @@ export function DatabaseResourceSelector({return (<div className="border border-control-border rounded-sm overflow-hidden">- <div className="bg-gray-50 border-b border-control-border px-2 py-1.5">+ <div className="bg-control-bg border-b border-control-border px-2 py-1.5"><AdvancedSearchplaceholder={t("common.filter")}params={searchParams}@@ -825,7 +825,7 @@ export function DatabaseResourceSelector({</div><div className="flex" style={{ height: "min(24rem, 60vh)" }}><div className="flex-1 flex flex-col border-r border-control-border min-w-0">- <div className="flex items-center justify-between px-3 py-1.5 bg-gray-50 border-b border-control-border text-xs text-control-light">+ <div className="flex items-center justify-between px-3 py-1.5 bg-control-bg border-b border-control-border text-xs text-control-light"><buttontype="button"className="text-accent hover:underline cursor-pointer"@@ -854,7 +854,7 @@ export function DatabaseResourceSelector({return (<div key={db.name}>- <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-gray-50 group">+ <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-control-bg group"><buttontype="button"className="shrink-0 w-4 h-4 flex items-center justify-center text-control-light hover:text-control cursor-pointer"@@ -922,7 +922,7 @@ export function DatabaseResourceSelector({return (<div key={schema.name}>- <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-gray-50">+ <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-control-bg"><buttontype="button"className="shrink-0 w-4 h-4 flex items-center justify-center text-control-light hover:text-control cursor-pointer"@@ -974,7 +974,7 @@ export function DatabaseResourceSelector({</div></div><div className="flex-1 flex flex-col min-w-0">- <div className="flex items-center px-3 py-1.5 bg-gray-50 border-b border-control-border text-xs text-control-light">+ <div className="flex items-center px-3 py-1.5 bg-control-bg border-b border-control-border text-xs text-control-light"><span>{value.length} {t("common.items", { count: value.length })}{" "}{t("common.selected").toLowerCase()}@@ -990,7 +990,7 @@ export function DatabaseResourceSelector({{value.map((r) => (<divkey={`${r.databaseFullName}/${r.schema ?? ""}/${r.table ?? ""}/${(r.columns ?? []).join("\0")}`}- className="flex items-center gap-x-1 px-2 py-1 text-sm hover:bg-gray-50 group rounded-sm"+ className="flex items-center gap-x-1 px-2 py-1 text-sm hover:bg-control-bg group rounded-sm"><span className="flex-1 truncate">{resourceLabel(r)}</span><button@@ -1036,7 +1036,7 @@ function TableNode({}) {return (<div>- <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-gray-50">+ <div className="flex items-center gap-x-1 px-2 py-1 hover:bg-control-bg">{includeColumns && columns.length > 0 ? (<buttontype="button"@@ -1065,7 +1065,7 @@ function TableNode({{columns.map((column) => (<divkey={column.name}- className="flex items-center gap-x-1 px-2 py-1 hover:bg-gray-50"+ className="flex items-center gap-x-1 px-2 py-1 hover:bg-control-bg"><span className="shrink-0 w-4" /><Checkboxdiff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsxindex 13c725ad46..02e9b36e68 100644--- a/frontend/src/react/components/monaco/MonacoEditor.tsx+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx@@ -116,7 +116,10 @@ export interface MonacoEditorProps {// Marker class for the active-statement highlight. Used both to render the// decoration and to identify (and clear) all such decorations on the shared// model, regardless of which editor lifecycle created them.-const ACTIVE_STATEMENT_DECORATION_CLASS = "bg-gray-200";+// `bg-control-bg-hover` is `#e5e7eb` in light (identical to the old gray-200,+// so no app-wide change) and a themed gray in dark so the highlight isn't a+// near-white block on the dark editor surface.+const ACTIVE_STATEMENT_DECORATION_CLASS = "bg-control-bg-hover";export function MonacoEditor({advices = [],diff --git a/frontend/src/react/components/monaco/core.test.ts b/frontend/src/react/components/monaco/core.test.tsindex 44deb27edf..aae310d026 100644--- a/frontend/src/react/components/monaco/core.test.ts+++ b/frontend/src/react/components/monaco/core.test.ts@@ -1,5 +1,9 @@import { beforeEach, describe, expect, test, vi } from "vitest";-import { createMonacoDiffEditor, createMonacoEditor } from "./core";+import {+ createMonacoDiffEditor,+ createMonacoEditor,+ getResolvedTheme,+} from "./core";const mocks = vi.hoisted(() => {const readOnlyContribution = { dispose: vi.fn() };@@ -16,7 +20,12 @@ const mocks = vi.hoisted(() => {editor: {create: vi.fn(() => editor),createDiffEditor: vi.fn(() => diffEditor),- defineTheme: vi.fn(),+ // Simulate the codingame VSCode theme service that silently rejects+ // custom themes in some runtime modes: defineTheme throws, so no `bb-*`+ // theme registers and getResolvedTheme must fall back to each theme's base.+ defineTheme: vi.fn(() => {+ throw new Error("theme registration swallowed");+ }),},};return {@@ -32,12 +41,16 @@ vi.mock("./services", () => ({initializeMonacoServices: vi.fn(async () => undefined),}));-vi.mock("./themes/bb", () => ({- getBBTheme: vi.fn(() => ({})),+vi.mock("@/react/components/sql-editor/theme/presets", () => ({+ PRESETS: [+ { id: "light", monacoBase: "vs" },+ { id: "dark", monacoBase: "vs-dark" },+ ],}));-vi.mock("./themes/bb-dark", () => ({- getBBDarkTheme: vi.fn(() => ({})),+vi.mock("@/react/components/sql-editor/theme/derive", () => ({+ buildMonacoTheme: vi.fn(() => ({})),+ monacoThemeName: vi.fn((p: { id: string }) => `bb-${p.id}`),}));vi.mock("monaco-editor", () => mocks.monaco);@@ -84,4 +97,19 @@ describe("monaco core", () => {}));});++ test("getResolvedTheme falls back to a theme's own base when it failed to register", async () => {+ // Creating any editor runs initializeTheme, which records each preset's+ // base and (here) fails to register the custom themes.+ await createMonacoEditor({ container: document.createElement("div") });++ // A dark theme that didn't register must fall back to `vs-dark`, NOT the+ // light `vs` — this is the bug that left the editor light under a dark theme.+ expect(getResolvedTheme("bb-dark")).toBe("vs-dark");+ // A light theme falls back to `vs`; the default (no arg) resolves the same.+ expect(getResolvedTheme("bb-light")).toBe("vs");+ expect(getResolvedTheme()).toBe("vs");+ // An unknown name with no recorded base falls back to the built-in `vs`.+ expect(getResolvedTheme("bb-unknown")).toBe("vs");+ });});diff --git a/frontend/src/react/components/monaco/core.ts b/frontend/src/react/components/monaco/core.tsindex a624b401b2..1aba0d2ef8 100644--- a/frontend/src/react/components/monaco/core.ts+++ b/frontend/src/react/components/monaco/core.ts@@ -1,9 +1,12 @@import type * as MonacoType from "monaco-editor";+import {+ buildMonacoTheme,+ monacoThemeName,+} from "@/react/components/sql-editor/theme/derive";+import { PRESETS } from "@/react/components/sql-editor/theme/presets";import type { Language } from "@/types";import { defer } from "@/utils";import { initializeMonacoServices } from "./services";-import { getBBTheme } from "./themes/bb";-import { getBBDarkTheme } from "./themes/bb-dark";let monacoModule: typeof MonacoType | undefined;const monacoLoadDefer = defer<typeof MonacoType>();@@ -14,21 +17,28 @@ export const MonacoEditorReady = monacoEditorReadyDefer.promise;const state = {themeInitialized: false,registeredThemes: new Set<string>(["vs", "vs-dark", "hc-black", "hc-light"]),+ // The Monaco base ("vs" | "vs-dark") for each generated theme name. When a+ // custom theme fails to register (the codingame VSCode theme service silently+ // ignores `defineTheme` in some runtime modes), `getResolvedTheme` falls back+ // to the theme's OWN base — so a dark theme falls back to `vs-dark`, not the+ // light `vs`. Recorded for every preset whether or not registration succeeds.+ themeBase: new Map<string, "vs" | "vs-dark">(),};const initializeTheme = () => {if (state.themeInitialized) return;state.themeInitialized = true;if (!monacoModule) return;- try {- monacoModule.editor.defineTheme("bb", getBBTheme());- state.registeredThemes.add("bb");- monacoModule.editor.defineTheme("bb-dark", getBBDarkTheme());- state.registeredThemes.add("bb-dark");- } catch {- // The VSCode theme service override owns themes in some runtime modes.- // Whichever theme failed stays out of `state.registeredThemes`, so- // `getResolvedTheme` will fall back to the built-in `vs` for it.+ for (const preset of PRESETS) {+ const name = monacoThemeName(preset);+ state.themeBase.set(name, preset.monacoBase);+ try {+ monacoModule.editor.defineTheme(name, buildMonacoTheme(preset));+ state.registeredThemes.add(name);+ } catch {+ // The vscode theme-service override owns themes in some runtime modes;+ // an un-registered theme falls back to its base via getResolvedTheme.+ }}};@@ -43,12 +53,11 @@ const initializeTheme = () => {* per-instance, so a stale `vs-dark` from a recently-disposed* terminal editor can bleed into a freshly-mounted worksheet editor).*/-export const getResolvedTheme = (requested?: string): string => {- const fallback = "vs";- if (!requested) {- return state.registeredThemes.has("bb") ? "bb" : fallback;- }- return state.registeredThemes.has(requested) ? requested : fallback;+export const getResolvedTheme = (requested = "bb-light"): string => {+ if (state.registeredThemes.has(requested)) return requested;+ // Custom theme not registered → use its own base (vs / vs-dark), so a dark+ // theme never falls back to the light `vs`.+ return state.themeBase.get(requested) ?? "vs";};const initialize = async () => {@@ -135,7 +144,7 @@ export const defaultEditorOptions =return {renderValidationDecorations: "on",accessibilitySupport: "off",- theme: "bb",+ theme: "bb-light",tabSize: 2,insertSpaces: true,autoClosingQuotes: "never",@@ -176,7 +185,7 @@ export const defaultDiffEditorOptions =enableSplitViewResizing: false,accessibilitySupport: "off",renderValidationDecorations: "on",- theme: "bb",+ theme: "bb-light",autoClosingQuotes: "never",folding: false,automaticLayout: true,diff --git a/frontend/src/react/components/monaco/themes/bb-dark.ts b/frontend/src/react/components/monaco/themes/bb-dark.tsdeleted file mode 100644index 5b35262e8a..0000000000--- a/frontend/src/react/components/monaco/themes/bb-dark.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { editor as Editor } from "monaco-editor";-import { callCssVariable } from "@/utils";--export const getBBDarkTheme = (): Editor.IStandaloneThemeData => ({- base: "vs-dark",- inherit: true,- rules: [- {- foreground: callCssVariable("--color-matrix-green-hover"),- token: "keyword",- },- ],- colors: {- "editor.foreground": callCssVariable("--color-matrix-green"),- "editorCursor.foreground": callCssVariable("--color-matrix-green-hover"),- "editorLineNumber.foreground": callCssVariable("--color-matrix-green"),- "editorLineNumber.activeForeground": callCssVariable(- "--color-matrix-green-hover"- ),- "editor.wordHighlightBackground": "#00000000",- "editor.wordHighlightStrongBackground": "#00000000",- },-});diff --git a/frontend/src/react/components/monaco/themes/bb.ts b/frontend/src/react/components/monaco/themes/bb.tsdeleted file mode 100644index d39bcab798..0000000000--- a/frontend/src/react/components/monaco/themes/bb.ts+++ /dev/null@@ -1,18 +0,0 @@-import type { editor as Editor } from "monaco-editor";-import { callCssVariable } from "@/utils";--export const getBBTheme = (): Editor.IStandaloneThemeData => ({- base: "vs",- inherit: true,- rules: [],- colors: {- "editor.background": "#fffffe00",- "editorCursor.foreground": callCssVariable("--color-accent"),- "editorLineNumber.foreground": callCssVariable(- "--color-control-placeholder"- ),- "editorLineNumber.activeForeground": callCssVariable("--color-main"),- "editor.wordHighlightBackground": "#00000000",- "editor.wordHighlightStrongBackground": "#00000000",- },-});diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxindex c5787e4736..8a028199d7 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -57,7 +57,9 @@ vi.mock("@/react/stores/sqlEditor/editor", () => ({selector({ project: mocks.project }),}));-// Zustand tab store — imperative getter to derive default targets.+// Zustand tab store — imperative getter to derive default targets, plus the+// reactive hook consumed by useActiveSQLEditorTheme (drives the drawer's Monaco+// theme). The tab has no mode, so the active theme resolves to the default.vi.mock("@/react/stores/sqlEditor/tab", () => ({getSQLEditorTabsState: () => ({currentTabId: "tab1",@@ -65,6 +67,16 @@ vi.mock("@/react/stores/sqlEditor/tab", () => ({["tab1", { connection: { database: mocks.currentTabDatabase } }],]),}),+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { mode?: string }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", {}]]),+ }),}));vi.mock("@/react/stores/sqlEditor", () => ({diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex d8b19714bc..d99755488b 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -5,6 +5,13 @@ import { useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { accessGrantServiceClientConnect } from "@/connect";import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";+import {+ monacoThemeName,+ themeColorScheme,+ themeToCssVars,+} from "@/react/components/sql-editor/theme/derive";+import { SQLEditorThemeScope } from "@/react/components/sql-editor/theme/SQLEditorThemeScope";+import { useActiveSQLEditorTheme } from "@/react/components/sql-editor/theme/useActiveSQLEditorTheme";import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { Checkbox } from "@/react/components/ui/checkbox";@@ -114,6 +121,23 @@ function AccessGrantRequestDrawerInner({const project = useSQLEditorEditorState((s) => s.project);+ // Re-theme the drawer chrome since the Sheet portals outside the SQL Editor+ // chrome DOM subtree, so the chrome CSS vars don't cascade here. Use the+ // ACTIVE theme (the dark admin fallback in admin mode), not the selected+ // root theme — otherwise opening the drawer from an admin tab renders light+ // chrome over the dark terminal. This also keeps the chrome consistent with+ // the embedded Monaco below, which already uses the active theme.+ const active = useActiveSQLEditorTheme();++ // The embedded Monaco MUST carry the active SQL Editor theme. Monaco's+ // setTheme is global: a <MonacoEditor> mounting with no theme resets the+ // shared Monaco theme to bb-light, flipping the whole editor to light the+ // moment the drawer opens. Passing the active theme keeps it consistent.+ const monacoOptions = useMemo(+ () => ({ theme: monacoThemeName(active) }),+ [active]+ );+const defaultTargets = useMemo(() => {if (stableProps.targets && stableProps.targets.length > 0) {return stableProps.targets;@@ -230,7 +254,7 @@ function AccessGrantRequestDrawerInner({};return (- <>+ <SQLEditorThemeScope theme={active} asContents><SheetHeader><SheetTitle>{t("sql-editor.request-data-access")}</SheetTitle></SheetHeader>@@ -260,11 +284,16 @@ function AccessGrantRequestDrawerInner({description={t("sql-editor.only-select-allowed")}/><MonacoEditor- className="border rounded-[3px] h-40"+ // Drawer Monaco portals outside `.sqleditor--wrapper`, so opt the+ // canvas into the transparent-background rule and back it with the+ // themed `bg-background` (from `sheetStyle`'s `--color-background`)+ // so it matches the active theme like the worksheet editor.+ className="border rounded-[3px] h-40 bg-background sqleditor--monaco-transparent"content={query}language="sql"autoCompleteContext={autoCompleteContext}onChange={setQuery}+ options={monacoOptions}/></div>@@ -345,7 +374,7 @@ function AccessGrantRequestDrawerInner({{t("common.submit")}</Button></SheetFooter>- </>+ </SQLEditorThemeScope>);}@@ -366,9 +395,28 @@ export function AccessGrantRequestDrawer({// Freeze props while drawer is open so inner form stays stable during close animationconst stableProps = propsRef.current;+ // The Sheet portals to the app-global overlay root, so the SQL Editor scope's+ // CSS vars don't cascade to it. Apply them directly on SheetContent so the+ // panel background AND its form contents follow the active theme. ACTIVE (not+ // the selected root theme) so an admin tab's dark fallback themes the drawer;+ // these inline vars would otherwise override the dark vars that+ // useSQLEditorOverlayTheme writes to the overlay root.+ const active = useActiveSQLEditorTheme();+ const sheetStyle = useMemo(+ () => ({+ ...themeToCssVars(active.tokens),+ // Native controls (date pickers, scrollbars) follow color-scheme.+ colorScheme: themeColorScheme(active),+ }),+ [active]+ );+return (<Sheet open={true} onOpenChange={(next) => !next && onClose()}>- <SheetContent width="standard">+ {/* text-main gives the drawer a themed default text color (it portals+ outside the SQL Editor wrapper that sets one), so un-classed text like+ checkbox labels and selected values follow the theme. */}+ <SheetContent width="standard" style={sheetStyle} className="text-main"><AccessGrantRequestDrawerInnerkey={`${targets?.join(",")}-${query}-${unmask}-${exportResult}`}stableProps={stableProps}diff --git a/frontend/src/react/components/sql-editor/ConnectChooser.tsx b/frontend/src/react/components/sql-editor/ConnectChooser.tsxindex 5253af002c..3348b91f1e 100644--- a/frontend/src/react/components/sql-editor/ConnectChooser.tsx+++ b/frontend/src/react/components/sql-editor/ConnectChooser.tsx@@ -18,6 +18,7 @@ import {import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";import { SearchInput } from "@/react/components/ui/search-input";import { cn } from "@/react/lib/utils";+import { ConnectionChooserButton } from "./ConnectionChooserButton";export type { ComboboxOption };@@ -198,18 +199,9 @@ export function ConnectChooser({return (<>- <button+ <ConnectionChooserButtonref={triggerRef}- type="button"- className={cn(- "inline-flex items-center justify-end gap-1 px-2 h-8 text-sm",- "border border-accent text-accent",- "hover:bg-accent/5 focus:bg-accent/5",- "rounded-none first:rounded-l-xs last:rounded-r-xs",- "[&:not(:last-child)]:border-r-0",- "transition-colors",- isChosen ? "max-w-[12rem]" : "max-w-none"- )}+ className={isChosen ? "max-w-[12rem]" : "max-w-none"}aria-label={placeholder}aria-expanded={open}onClick={() => setOpen((v) => !v)}@@ -227,7 +219,7 @@ export function ConnectChooser({{placeholder}</span>)}- </button>+ </ConnectionChooserButton>{open && createPortal(dropdownContent, getLayerRoot("overlay"))}</>);diff --git a/frontend/src/react/components/sql-editor/ConnectionChooserButton.tsx b/frontend/src/react/components/sql-editor/ConnectionChooserButton.tsxnew file mode 100644index 0000000000..6ae4619266--- /dev/null+++ b/frontend/src/react/components/sql-editor/ConnectionChooserButton.tsx@@ -0,0 +1,36 @@+import type { ComponentProps } from "react";+import { Button } from "@/react/components/ui/button";+import { cn } from "@/react/lib/utils";++/**+ * Trigger button shared by the SQL Editor connection controls+ * (`DatabaseChooser` + `ConnectChooser`), which render side by side as one+ * joined, accent-outlined segmented group. Wraps the shared <Button> so both+ * inherit its Base UI button semantics (focus/disabled handling) while keeping+ * the segmented-group look — no Button variant matches it, so the accent+ * border/text and group rounding come through className (merged last).+ */+export function ConnectionChooserButton({+ className,+ ...props+}: ComponentProps<typeof Button>) {+ return (+ <Button+ type="button"+ variant="outline"+ className={cn(+ "h-8 justify-end gap-1 px-2",+ "border-accent text-accent hover:bg-accent/5 focus:bg-accent/5",+ // Joined group: square inner edges, only the group's outer corners+ // round, and inner borders collapse so adjacent segments share one.+ "rounded-none first:rounded-l-xs last:rounded-r-xs",+ "[&:not(:last-child)]:border-r-0",+ // Keep the group flat — suppress Button's offset focus ring, which+ // would otherwise draw around a single segment.+ "focus-visible:ring-0",+ className+ )}+ {...props}+ />+ );+}diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsxindex 594fb65d1d..9cc0115a77 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx@@ -677,7 +677,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {<DatabaseHoverPanel offsetX={10} offsetY={4} margin={4} />{treeStoreState !== "READY" && (- <div className="absolute inset-0 bg-white/75 flex items-center justify-center">+ <div className="absolute inset-0 bg-background/75 flex items-center justify-center"><span className="text-control text-sm">{t("sql-editor.loading-databases")}</span>diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsxindex 2ae3e1d3db..15ca45d9d4 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx@@ -94,7 +94,7 @@ export function DatabaseHoverPanel({<divref={popoverRef}className={cn(- "fixed border border-gray-100 rounded-sm bg-white p-2 shadow-sm transition-all text-sm",+ "fixed border border-block-border rounded-sm bg-background p-2 shadow-sm transition-all text-sm",LAYER_SURFACE_CLASS,!show && "pointer-events-none opacity-0")}@@ -111,7 +111,7 @@ export function DatabaseHoverPanel({style={{ gridTemplateColumns: "auto 1fr" }}><div className="contents">- <div className="text-gray-500 font-medium">+ <div className="text-control-light font-medium">{t("common.environment")}</div><div className="text-main text-right flex justify-end">@@ -121,7 +121,7 @@ export function DatabaseHoverPanel({</div></div><div className="contents">- <div className="text-gray-500 font-medium">+ <div className="text-control-light font-medium">{t("common.instance")}</div><div className="text-main text-right truncate">@@ -130,7 +130,7 @@ export function DatabaseHoverPanel({</div>{!hasProjectContext && (<div className="contents">- <div className="text-gray-500 font-medium">+ <div className="text-control-light font-medium">{t("common.project")}</div><div className="text-main text-right truncate">@@ -139,14 +139,14 @@ export function DatabaseHoverPanel({</div>)}<div className="contents">- <div className="text-gray-500 font-medium">+ <div className="text-control-light font-medium">{t("common.labels")}</div><div className="text-main flex flex-row justify-end flex-wrap gap-1">{Object.entries(database.labels).map(([key, value]) => (<divkey={key}- className="text-xs py-px px-1 bg-gray-200/75 rounded-xs"+ className="text-xs py-px px-1 bg-control-bg rounded-xs"><span>{key}</span>{value ? (diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.tsxindex 6baac595fb..9f30d44343 100644--- a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx@@ -2,9 +2,9 @@ import { ChevronRight, Database, SquareStack } from "lucide-react";import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";+import { ConnectionChooserButton } from "@/react/components/sql-editor/ConnectionChooserButton";import { Tooltip } from "@/react/components/ui/tooltip";import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";-import { cn } from "@/react/lib/utils";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {@@ -54,19 +54,10 @@ export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {};return (- <button- type="button"+ <ConnectionChooserButtondisabled={disabled || !projectContextReady}onClick={handleClick}- className={cn(- "inline-flex items-center justify-end gap-1 px-2 h-8 text-sm",- "border border-accent text-accent",- "hover:bg-accent/5 focus:bg-accent/5",- "rounded-none first:rounded-l-xs last:rounded-r-xs",- "[&:not(:last-child)]:border-r-0",- "disabled:opacity-50 disabled:cursor-not-allowed",- "transition-colors overflow-hidden"- )}+ className="overflow-hidden">{isConnected ? (<div className="flex flex-row items-center text-control truncate">@@ -90,6 +81,6 @@ export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {) : (<span>{t("sql-editor.select-a-database-to-start")}</span>)}- </button>+ </ConnectionChooserButton>);}diff --git a/frontend/src/react/components/sql-editor/EditorAction.test.tsx b/frontend/src/react/components/sql-editor/EditorAction.test.tsxindex da3b4adaf6..379893fa4d 100644--- a/frontend/src/react/components/sql-editor/EditorAction.test.tsx+++ b/frontend/src/react/components/sql-editor/EditorAction.test.tsx@@ -74,6 +74,7 @@ vi.mock("@/react/stores/sqlEditor/editor", () => ({vi.mock("@/utils", () => ({isWorksheetWritableV1: mocks.isWorksheetWritableV1,keyboardShortcutStr: mocks.keyboardShortcutStr,+ isDev: () => true,}));vi.mock("@/views/sql-editor/events", () => ({diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsxindex 38e4117996..9e5278d731 100644--- a/frontend/src/react/components/sql-editor/EditorAction.tsx+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx@@ -21,13 +21,14 @@ import {} from "@/react/stores/sqlEditor/tab";import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";-import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";+import { isDev, isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";import { AdminModeButton } from "./AdminModeButton";import { ChooserGroup } from "./ChooserGroup";import { OpenAIButton } from "./OpenAIButton";import { QueryContextSettingPopover } from "./QueryContextSettingPopover";import { SharePopoverBody } from "./SharePopoverBody";+import { ThemeSelect } from "./ThemeSelect";type Props = {readonly onExecute?: (params: SQLEditorQueryParams) => void;@@ -241,6 +242,8 @@ export function EditorAction({ onExecute }: Props) {)}</div><div className="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">+ {/* Theme switcher is dev-only until the theme feature ships. */}+ {isDev() && <ThemeSelect />}<ChooserGroup /><OpenAIButtonsize="sm"diff --git a/frontend/src/react/components/sql-editor/Panels/common/EllipsisCell.tsx b/frontend/src/react/components/sql-editor/Panels/common/EllipsisCell.tsxindex e78fa51ce6..dfe1729d4e 100644--- a/frontend/src/react/components/sql-editor/Panels/common/EllipsisCell.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/EllipsisCell.tsx@@ -67,7 +67,7 @@ export function EllipsisCell({maxWidth: "min(33vw, 320px)",}}className={cn(- "rounded-sm bg-gray-900 px-2.5 py-1.5 text-xs font-normal text-white shadow-md whitespace-pre-wrap break-all pointer-events-none",+ "rounded-sm bg-main px-2.5 py-1.5 text-xs font-normal text-main-text shadow-md whitespace-pre-wrap break-all pointer-events-none",LAYER_SURFACE_CLASS)}>diff --git a/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsxindex 48ba8ba889..27174ade28 100644--- a/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx+++ b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx@@ -9,6 +9,7 @@ import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";import type { DatabaseResource, Permission } from "@/types";import type { Project } from "@/types/proto-es/v1/project_service_pb";import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";+import { useActiveSQLEditorTheme } from "./theme/useActiveSQLEditorTheme";type RequestRoleArgs = {project: Project;@@ -57,6 +58,14 @@ export function RequestDrawerHost({ children }: { children: ReactNode }) {[]);+ // This host only renders inside the SQL Editor, so resolve the ACTIVE theme+ // (the dark admin fallback in admin mode) and hand it to RequestRoleSheet as+ // an explicit prop. RequestRoleSheet is shared with non-SQL-Editor pages, so+ // it stays light unless a host passes a theme — this is the only caller that+ // does. (AccessGrantRequestDrawer is SQL-Editor-only and reads the active+ // theme itself.)+ const activeTheme = useActiveSQLEditorTheme();+return (<RequestDrawerHostContext.Provider value={value}>{children}@@ -67,6 +76,7 @@ export function RequestDrawerHost({ children }: { children: ReactNode }) {requiredPermissions={roleArgs.requiredPermissions}initialRole={roleArgs.initialRole}initialDatabaseResources={roleArgs.initialDatabaseResources}+ theme={activeTheme}onClose={() => setRoleArgs(null)}/>)}diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsxindex 7fa0dec173..abcddb27b9 100644--- a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx@@ -35,6 +35,19 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));+// RequestDrawerHost (imported transitively for `useRequestDrawerHost`) now pulls+// in the active-theme hook, which reaches the editor/app stores + i18n. This+// test only exercises button behavior, so stub the hook to keep the module graph+// light (the drawers themselves are already mocked below).+vi.mock("./theme/useActiveSQLEditorTheme", () => ({+ useActiveSQLEditorTheme: () => ({+ id: "light",+ name: "Default Light",+ monacoBase: "vs",+ tokens: {},+ }),+}));+vi.mock("@/store", () => ({useSubscriptionV1Store: mocks.useSubscriptionV1Store,hasFeature: mocks.hasFeature,diff --git a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsxindex f0f567f17b..97299261d2 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx@@ -72,7 +72,7 @@ export function DatabaseQueryContext({if (isExecuting) {return (- <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80">+ <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-background/80"><div className="flex items-center gap-x-1"><Loader2 className="size-5 animate-spin mr-1" /><span>{t("sql-editor.executing-query")}</span>@@ -90,7 +90,7 @@ export function DatabaseQueryContext({if (context.status === "CANCELLED") {return (- <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80">+ <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-background/80"><Buttonsize="sm"variant="outline"diff --git a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsxindex f70b464fad..f424317979 100644--- a/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/DetailPanel.tsx@@ -66,8 +66,7 @@ function useLocalStorageBoolean(export function DetailPanel({ rows, columns }: DetailPanelProps) {const { t } = useTranslation();- const { dark, detail, disallowCopyingData, setDetail } =- useSQLResultViewContext();+ const { detail, disallowCopyingData, setDetail } = useSQLResultViewContext();const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();const [copied, setCopied] = useState(false);@@ -192,7 +191,7 @@ export function DetailPanel({ rows, columns }: DetailPanelProps) {// and the content code block don't bleed to the sheet's// raw edges."flex-1 min-h-0 flex flex-col gap-y-2 px-6 py-4",- dark ? "text-white" : "text-main"+ "text-main")}><div className="flex items-center justify-between gap-x-4">diff --git a/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsx b/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsxindex d9b276de5b..d53dfa875a 100644--- a/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/EmptyView.tsx@@ -1,19 +1,9 @@import { useTranslation } from "react-i18next";-import { cn } from "@/react/lib/utils";-interface EmptyViewProps {- dark: boolean;-}--export function EmptyView({ dark }: EmptyViewProps) {+export function EmptyView() {const { t } = useTranslation();return (- <div- className={cn(- "text-md font-normal",- dark ? "text-matrix-green-hover" : "text-control-light"- )}- >+ <div className="text-md font-normal text-control-light">{t("sql-editor.no-data-available")}</div>);diff --git a/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsxindex e5b92291a3..471e25e1e0 100644--- a/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx@@ -11,7 +11,6 @@ import { sqlEditorEvents } from "@/views/sql-editor/events";import { PostgresError } from "./PostgresError";interface ErrorViewProps {- dark: boolean;error: string | undefined;executeParams?: SQLEditorQueryParams;resultSet?: SQLResultSetV1;@@ -19,7 +18,6 @@ interface ErrorViewProps {}export function ErrorView({- dark,error,executeParams,resultSet,@@ -107,7 +105,7 @@ export function ErrorView({<divclassName={cn("w-full text-md font-normal flex flex-col gap-2 text-sm",- dark ? "text-matrix-green-hover" : "text-control-light"+ "text-control-light")}><Alert variant="error" className="w-full">diff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex 4ca09c5ef5..a053e8900e 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -48,7 +48,9 @@ export interface ResultViewProps {database: Database;resultSet?: SQLResultSetV1;loading?: boolean;- dark?: boolean;+ // Compact layout (fixed-height result body) for the terminal / admin panel.+ // The worksheet panel leaves this false to keep the flex-grow layout.+ compact?: boolean;}type ViewMode = "SINGLE-RESULT" | "MULTI-RESULT" | "EMPTY" | "ERROR";@@ -65,7 +67,7 @@ export function ResultView({database,resultSet,loading,- dark = false,+ compact = false,}: ResultViewProps) {const { t } = useTranslation();const project = useSQLEditorEditorState((s) => s.project);@@ -237,7 +239,7 @@ export function ResultView({<divclassName={cn("relative flex flex-col justify-start items-start pb-1 overflow-y-auto h-full w-full",- dark && "dark bg-dark-bg"+ "bg-background")}>{executeParams && resultSet && !showPlaceholder && (@@ -245,7 +247,6 @@ export function ResultView({{viewMode === "SINGLE-RESULT" &&(resultSet.results[0]?.error ? (<ErrorView- dark={dark}error={resultSet.results[0].error}executeParams={executeParams}resultSet={resultSet}@@ -253,7 +254,6 @@ export function ResultView({/>) : (<SingleResultView- dark={dark}disallowCopyingData={disallowCopyingData}params={executeParams}database={database}@@ -265,6 +265,7 @@ export function ResultView({requestExportSlot={!showExport ? requestExportButton : undefined}+ compact={compact}/>))}@@ -318,7 +319,6 @@ export function ResultView({>{result.error ? (<ErrorView- dark={dark}error={result.error}executeParams={executeParams}resultSet={resultSet}@@ -326,7 +326,6 @@ export function ResultView({/>) : (<SingleResultView- dark={dark}disallowCopyingData={disallowCopyingData}params={executeParams}database={database}@@ -334,6 +333,7 @@ export function ResultView({showExport={false}maximumExportCount={queryDataPolicy?.maximumResultRows}onExport={handleExport}+ compact={compact}/>)}</TabsPanel>@@ -341,11 +341,10 @@ export function ResultView({</Tabs>)}- {viewMode === "EMPTY" && <EmptyView dark={dark} />}+ {viewMode === "EMPTY" && <EmptyView />}{viewMode === "ERROR" && (<ErrorView- dark={dark}error={resultSet.error}executeParams={executeParams}resultSet={resultSet}diff --git a/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsxindex ef4e1be0fc..4e14698829 100644--- a/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SelectionCopyTooltips.tsx@@ -48,18 +48,13 @@ export function SelectionCopyTooltips() {return (<div- // `bg-background` is the light page bg and doesn't dark-switch- // automatically. The tip is `absolute h-full` over the result- // toolbar — without an opaque dark bg under it the white shows- // through admin mode's `bg-dark-bg`. Match the result-view chrome- // for both themes.- className="w-full absolute h-full bg-background dark:bg-dark-bg flex flex-row justify-start items-center text-control dark:text-gray-100"+ className="w-full absolute h-full bg-background flex flex-row justify-start items-center text-control"onClick={(e) => {e.preventDefault();e.stopPropagation();}}>- <InfoIcon size={16} className="mr-2 text-control dark:text-gray-100" />+ <InfoIcon size={16} className="mr-2 text-control" /><p className="text-sm flex flex-row justify-start items-center gap-1">{tokens.map((token, i) => {if (token === "action") {@@ -68,11 +63,7 @@ export function SelectionCopyTooltips() {key={i}size="sm"variant="outline"- // `outline` is `bg-transparent + text-control` and the- // tip sits over `bg-dark-bg` in admin mode → invisible.- // Force an opaque dark surface with a light shortcut- // label so the keyboard hint reads against the toolbar.- className="h-6 px-2 gap-x-1 dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:disabled:opacity-100"+ className="h-6 px-2 gap-x-1 bg-control-bg text-control border-control-border"disabled>{isMac ? (@@ -141,18 +132,7 @@ export function SelectionCopyTooltips() {})}</p><div className="ml-1">- {/*- * `ghost` is `text-control` with no background — invisible- * label against the admin-mode dark backdrop. Lift the label- * to a light gray and give it a hover surface so the cancel- * action is reachable.- */}- <Button- size="sm"- variant="ghost"- className="dark:text-gray-100 dark:hover:bg-gray-700"- onClick={deselect}- >+ <Button size="sm" variant="ghost" onClick={deselect}>{t("sql-editor.cancel-selection")}</Button></div>diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex be31ebc711..15e4e2a552 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -89,7 +89,6 @@ import {} from "./VirtualDataTable";export interface SingleResultViewProps {- dark: boolean;disallowCopyingData: boolean;params: SQLEditorQueryParams;database: Database;@@ -103,6 +102,9 @@ export interface SingleResultViewProps {// Rendered in the toolbar when `showExport` is false — e.g. a// "Request export" affordance when the policy disables direct export.requestExportSlot?: ReactNode;+ // Compact layout (fixed-height, non-growing body) used by the terminal /+ // admin result panel. Defaults to the flex-grow worksheet layout.+ compact?: boolean;}type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";@@ -118,7 +120,7 @@ type ViewMode = "RESULT" | "EMPTY" | "AFFECTED-ROWS" | "ERROR";* them twice and doubled the 100k-row allocation on large result sets.*/export function SingleResultView(props: SingleResultViewProps) {- const { dark, disallowCopyingData, database, result } = props;+ const { disallowCopyingData, database, result } = props;const engine = getInstanceResource(database).engine;const [noSQLTableView, setNoSQLTableView] = useLocalStorageBoolean(STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW,@@ -197,7 +199,6 @@ export function SingleResultView(props: SingleResultViewProps) {return (<SQLResultViewProvider- dark={dark}disallowCopyingData={disallowCopyingData}engine={engine}schema={props.params.connection.schema}@@ -233,7 +234,6 @@ interface SingleResultViewInnerProps extends SingleResultViewProps {}function SingleResultViewInner({- dark,disallowCopyingData,params,database,@@ -252,6 +252,7 @@ function SingleResultViewInner({supportsTableViewToggle,noSQLTableView,setNoSQLTableView,+ compact = false,}: SingleResultViewInnerProps) {const { t } = useTranslation();const project = useSQLEditorEditorState((s) => s.project);@@ -513,7 +514,7 @@ function SingleResultViewInner({<divclassName={cn("text-md font-normal flex items-center gap-x-1",- dark ? "text-matrix-green-hover" : "text-control-light"+ "text-control-light")}><span>{String(extractSQLRowValuePlain(result.rows[0].values[0]))}</span>@@ -523,7 +524,7 @@ function SingleResultViewInner({}if (viewMode === "EMPTY") {- return <EmptyView dark={dark} />;+ return <EmptyView />;}return (@@ -543,7 +544,7 @@ function SingleResultViewInner({<>{result.error && (<Alert variant="error" className="w-full mb-2">- <ErrorView dark={dark} error={result.error} />+ <ErrorView error={result.error} /></Alert>)}@@ -591,15 +592,11 @@ function SingleResultViewInner({{!disallowCopyingData && rows.length > 0 && (// Split button: the main action copies as plain text (TSV); the// dropdown caret (hover) offers CSV and, for SQL engines, SQL.- // `variant="outline"` is `bg-transparent + text-control`, which- // disappears inside the admin-mode dark backdrop. Force an- // opaque light-on-dark surface in `.dark` to match the Vue- // toolbar's contrast (light gray bg + dark text).<div className="flex items-center"><Buttonsize="sm"variant="outline"- className="h-7 px-2 rounded-r-none border-r-0 dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:hover:bg-gray-600"+ className="h-7 px-2 rounded-r-none border-r-0 bg-control-bg text-control border-control-border hover:bg-control-bg-hover"onClick={() => copy("all", formatAsText)}><CopyIcon className="size-4" />@@ -614,7 +611,7 @@ function SingleResultViewInner({size="sm"variant="outline"aria-label={t("common.copy")}- className="h-7 w-6 px-0 rounded-l-none dark:bg-gray-700 dark:text-gray-100 dark:border-zinc-600 dark:hover:bg-gray-600"+ className="h-7 w-6 px-0 rounded-l-none bg-control-bg text-control border-control-border hover:bg-control-bg-hover"><ChevronDownIcon className="size-4" /></Button>@@ -664,7 +661,9 @@ function SingleResultViewInner({<divclassName={cn("w-full flex flex-col relative",- dark ? "h-80 overflow-hidden" : "flex-1 min-h-0 overflow-y-auto"+ compact+ ? "h-80 overflow-hidden"+ : "flex-1 min-h-0 overflow-y-auto")}>{vertical ? (diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsxindex 25935f583a..8c4f6798a1 100644--- a/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataBlock.tsx@@ -144,13 +144,13 @@ export const VirtualDataBlock = forwardRef<transform: `translateY(${virtualRow.start}px)`,}}>- <p className="font-bold text-control-light dark:text-gray-300 overflow-hidden whitespace-nowrap mb-1">+ <p className="font-bold text-control-light overflow-hidden whitespace-nowrap mb-1">******************************** {rowIndex + 1}. row********************************</p><divclassName={cn(- "py-2 px-3 bg-control-bg dark:bg-gray-700 rounded relative",+ "py-2 px-3 bg-control-bg rounded relative",isActive && "border-2 border-accent/20 bg-accent/10!")}>@@ -163,7 +163,7 @@ export const VirtualDataBlock = forwardRef<return (<divkey={column.id}- className="flex items-start text-control-light dark:text-gray-300 text-sm"+ className="flex items-start text-control-light text-sm"><div className="min-w-28 text-left flex items-center font-medium pt-1"><div className="flex items-center gap-x-1">@@ -225,16 +225,10 @@ function CopyJSONButton({return (<div className="absolute right-2 top-2 z-10 opacity-70 hover:opacity-100"><Tooltip content={label}>- {/*- * In admin mode the row card is `dark:bg-gray-700`, and the- * `ghost` variant's `text-control` icon nearly disappears- * against it. Force a light icon + visible hover surface inside- * the `.dark` parent so the action is reachable.- */}<Buttonsize="sm"variant="ghost"- className="size-7 p-0 dark:text-gray-100 dark:hover:bg-gray-600"+ className="size-7 p-0"onClick={handleCopy}>{copied ? (diff --git a/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsxindex 71f86a7c6f..350208020b 100644--- a/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/VirtualDataTable.tsx@@ -268,11 +268,11 @@ export const VirtualDataTable = forwardRef<<ResultCopyContextMenu><divref={containerRef}- className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border dark:border-zinc-500"+ className="relative w-full flex-1 min-h-0 overflow-auto rounded-sm border border-block-border">{/* Header */}<div- className="sticky top-0 z-1 bg-control-bg dark:bg-gray-700 flex shadow-sm"+ className="sticky top-0 z-1 bg-control-bg flex shadow-sm"style={{ minWidth: minRowWidth }}>{/* Index header */}@@ -308,10 +308,11 @@ export const VirtualDataTable = forwardRef<}onClick={(e) => handleSelectColumn(e, columnIndex)}className={cn(- "px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light dark:text-gray-300 tracking-wider",+ "px-3 py-1.5 min-w-8 text-left text-xs font-medium text-control-light tracking-wider",!selectionDisabled &&- "cursor-pointer hover:bg-control-bg-hover dark:hover:bg-gray-800",- isSelected && "bg-accent/10! dark:bg-accent/40!"+ "cursor-pointer hover:bg-control-bg-hover",+ // NOTE: opacity may need visual tuning on dark themes+ isSelected && "bg-accent/10!")}><div className="flex items-center min-w-0 gap-x-1">@@ -394,9 +395,10 @@ export const VirtualDataTable = forwardRef<{/* Index cell */}<divclassName={cn(- "relative flex items-center shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-r border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",- isActive && "bg-accent/10! dark:bg-accent/40!",- rowSelected && "bg-accent/20! dark:bg-accent/40!"+ "relative flex items-center shrink-0 text-sm text-control leading-5 whitespace-nowrap break-all border-block-border border-r border-b group-even:bg-control-bg/40",+ // NOTE: opacity may need visual tuning on dark themes+ isActive && "bg-accent/10!",+ rowSelected && "bg-accent/20!")}data-col-index={0}style={{@@ -418,8 +420,9 @@ export const VirtualDataTable = forwardRef<aria-label={`Select row ${rowIndex + 1}`}onClick={(e) => handleSelectRow(e, rowIndex)}className={cn(- "absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 hover:bg-accent/10 dark:bg-white/10 dark:hover:bg-accent/40",- rowSelected && "bg-accent/20! dark:bg-accent/40!"+ "absolute inset-y-0 left-0 w-3 cursor-pointer bg-accent/5 hover:bg-accent/10",+ // NOTE: opacity may need visual tuning on dark themes+ rowSelected && "bg-accent/20!")}/>)}@@ -433,12 +436,13 @@ export const VirtualDataTable = forwardRef<<divkey={`${rowIndex}-${columnIndex + 1}`}className={cn(- "relative shrink-0 text-sm dark:text-gray-100 leading-5 whitespace-nowrap break-all border-block-border dark:border-zinc-500 border-b group-even:bg-control-bg/40 dark:group-even:bg-gray-700/50",+ "relative shrink-0 text-sm text-control leading-5 whitespace-nowrap break-all border-block-border border-b group-even:bg-control-bg/40",!isLastCol && "border-r",// Match the Vue version: an active (search-matched) row// highlights every cell in that row, not just the index// column.- isActive && "bg-accent/10! dark:bg-accent/40!"+ // NOTE: opacity may need visual tuning on dark themes+ isActive && "bg-accent/10!")}data-col-index={columnIndex + 1}style={{@@ -493,7 +497,7 @@ function HeaderCell({<divonClick={onClick}className={cn(- "group relative shrink-0 border-block-border dark:border-zinc-500",+ "group relative shrink-0 border-block-border",borderRight ? "border-x" : "border-l",className)}diff --git a/frontend/src/react/components/sql-editor/ResultView/context.tsx b/frontend/src/react/components/sql-editor/ResultView/context.tsxindex fe70492c12..7c8aefb753 100644--- a/frontend/src/react/components/sql-editor/ResultView/context.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/context.tsx@@ -36,7 +36,7 @@ import {import type { ResultTableColumn, ResultTableRow } from "./types";// =============================================================================-// SQLResultViewContext (dark / disallowCopyingData / detail-cell)+// SQLResultViewContext (disallowCopyingData / detail-cell)// =============================================================================export interface ResultViewDetail {@@ -45,7 +45,6 @@ export interface ResultViewDetail {}export interface SQLResultViewContext {- dark: boolean;disallowCopyingData: boolean;detail: ResultViewDetail | undefined;setDetail: (detail: ResultViewDetail | undefined) => void;@@ -133,7 +132,6 @@ const NON_SQL_ENGINES = new Set<Engine>([]);interface SQLResultViewProviderProps {- dark?: boolean;disallowCopyingData?: boolean;engine: Engine;// Connected schema, used to qualify the generated INSERT's table name.@@ -145,7 +143,7 @@ interface SQLResultViewProviderProps {/*** Per-instance provider for one `<ResultView>` mount. Owns:- * - The dark/disallowCopying flags + the detail-cell state+ * - The disallowCopying flag + the detail-cell state* - The binary-format Map (per-cell and per-column overrides)* - The selection state + row/column/cell toggles + clipboard copy*@@ -153,7 +151,6 @@ interface SQLResultViewProviderProps {* `useBinaryFormatContext`, and `useSelectionContext`.*/export function SQLResultViewProvider({- dark = false,disallowCopyingData = false,engine,schema,@@ -166,8 +163,8 @@ export function SQLResultViewProvider({// ---- SQLResultViewContext ----const [detail, setDetail] = useState<ResultViewDetail | undefined>(undefined);const sqlResultView = useMemo<SQLResultViewContext>(- () => ({ dark, disallowCopyingData, detail, setDetail }),- [dark, disallowCopyingData, detail]+ () => ({ disallowCopyingData, detail, setDetail }),+ [disallowCopyingData, detail]);// ---- BinaryFormatContext ----diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsxindex 92f8f90b40..86606fe2fc 100644--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx@@ -14,6 +14,10 @@ import { AsidePanel } from "@/react/components/sql-editor/AsidePanel";import { ConnectionPanel } from "@/react/components/sql-editor/ConnectionPanel";import { Panels } from "@/react/components/sql-editor/Panels/Panels";import { TabList } from "@/react/components/sql-editor/TabList";+import {+ SQLEditorThemeScope,+ useSQLEditorTheme,+} from "@/react/components/sql-editor/theme/SQLEditorThemeScope";import {getLayerRoot,LAYER_BACKDROP_CLASS,@@ -78,6 +82,9 @@ export function SQLEditorHomePage() {: undefined;const tab = useCurrentSQLEditorTab();const isDisconnected = useIsDisconnected();+ // Read the active theme once so portaled overlays (which mount outside the+ // chrome DOM subtree) can re-write the chrome CSS vars on their own root.+ const theme = useSQLEditorTheme();const [windowWidth, setWindowWidth] = useState(() => window.innerWidth);useEffect(() => {@@ -158,40 +165,45 @@ export function SQLEditorHomePage() {const mobileToggle = hideSidebar? createPortal(- <button- type="button"- className={cn(- "fixed rounded-full border border-control-border shadow-lg w-10 h-10 bottom-16 flex items-center justify-center bg-white hover:bg-control-bg cursor-pointer transition-all",- LAYER_SURFACE_CLASS,- sidebarExpanded ? "left-[80%] -translate-x-5" : "left-4"- )}- style={{- transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)",- transitionDuration: "300ms",- }}- onClick={() => setSidebarExpanded((prev) => !prev)}- aria-label={sidebarExpanded ? "Collapse sidebar" : "Expand sidebar"}- >- <ChevronLeft+ <SQLEditorThemeScope theme={theme} asContents>+ <button+ type="button"className={cn(- "w-6 h-6 transition-transform",- !sidebarExpanded && "-scale-100"+ "fixed rounded-full border border-control-border shadow-lg w-10 h-10 bottom-16 flex items-center justify-center bg-background hover:bg-control-bg cursor-pointer transition-all",+ LAYER_SURFACE_CLASS,+ sidebarExpanded ? "left-[80%] -translate-x-5" : "left-4")}- />- </button>,+ style={{+ transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)",+ transitionDuration: "300ms",+ }}+ onClick={() => setSidebarExpanded((prev) => !prev)}+ aria-label={sidebarExpanded ? "Collapse sidebar" : "Expand sidebar"}+ >+ <ChevronLeft+ className={cn(+ "w-6 h-6 transition-transform",+ !sidebarExpanded && "-scale-100"+ )}+ />+ </button>+ </SQLEditorThemeScope>,getLayerRoot("overlay")): null;return (- <div className="sqleditor--wrapper w-full flex-1 overflow-hidden flex flex-col">+ <div className="sqleditor--wrapper w-full flex-1 overflow-hidden flex flex-col bg-background text-main">{mobileToggle}{hideSidebar &&sidebarExpanded &&createPortal(- <>+ <SQLEditorThemeScope theme={theme} asContents><div- className={cn("fixed inset-0 bg-black/40", LAYER_BACKDROP_CLASS)}+ className={cn(+ "fixed inset-0 bg-overlay/40",+ LAYER_BACKDROP_CLASS+ )}onClick={() => setSidebarExpanded(false)}/><div@@ -204,7 +216,7 @@ export function SQLEditorHomePage() {><AsidePanel /></div>- </>,+ </SQLEditorThemeScope>,getLayerRoot("overlay"))}<PanelGroup orientation="horizontal" className="h-full">diff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsxindex 398fe80338..2505306d34 100644--- a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx@@ -1,12 +1,33 @@-import { useEffect, useState } from "react";+import { type ReactNode, useEffect, useState } from "react";import { BannersWrapper } from "@/react/components/BannersWrapper";import { useEnsureWorkspaceCommonData } from "@/react/hooks/useEnsureWorkspaceCommonData";import { router } from "@/react/router";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { provideSheetContext } from "@/views/sql-editor/Sheet";import { RequestDrawerHost } from "./RequestDrawerHost";import { SQLEditorRouteShell } from "./SQLEditorRouteShell";+import { resolveThemeId } from "./theme/presets";+import { SQLEditorThemeScope } from "./theme/SQLEditorThemeScope";+import { useMonacoThemeController } from "./theme/useMonacoThemeController";+import { useSQLEditorOverlayTheme } from "./theme/useSQLEditorOverlayTheme";import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";+function SQLEditorThemeRoot({ children }: Readonly<{ children: ReactNode }>) {+ const themeId = useSQLEditorEditorState((s) => s.themeId);+ // Live-applies the theme on switch. It deliberately does NOT call setTheme on+ // mount — editors theme themselves at construction via options.theme — so it+ // never races Monaco construction (see useMonacoThemeController).+ useMonacoThemeController();+ // Themes all portaled overlays (dialogs, drawer, Select/Popover popups) that+ // render outside the SQL Editor DOM subtree.+ useSQLEditorOverlayTheme();+ return (+ <SQLEditorThemeScope theme={resolveThemeId(themeId)} asContents>+ {children}+ </SQLEditorThemeScope>+ );+}+/*** React port of `frontend/src/layouts/SQLEditorLayout.vue`.*@@ -55,13 +76,15 @@ export function SQLEditorLayout() {that the React layering policy now forbids. */}<ulid="sql-editor-debug"- className="hidden text-xs font-mono max-h-[33vh] max-w-[40vw] overflow-auto fixed bottom-0 right-0 p-2 bg-white/50 border border-gray-400"+ className="hidden text-xs font-mono max-h-[33vh] max-w-[40vw] overflow-auto fixed bottom-0 right-0 p-2 bg-background/50 border border-control-border"/><BannersWrapper />{ready && (- <RequestDrawerHost>- <SQLEditorRouteShell />- </RequestDrawerHost>+ <SQLEditorThemeRoot>+ <RequestDrawerHost>+ <SQLEditorRouteShell />+ </RequestDrawerHost>+ </SQLEditorThemeRoot>)}</div>);diff --git a/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsxindex 1458e9747a..d46a27c261 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/FlatTableList.tsx@@ -166,12 +166,12 @@ export function FlatTableList({<TableIcon className="size-3.5 shrink-0" /><span className="truncate">{item.schema ? (- <span className="text-gray-500">{item.schema}.</span>+ <span className="text-control-light">{item.schema}.</span>) : null}<span>{item.metadata.name}</span></span></div>- <div className="flex items-center gap-2 text-xs text-gray-500 shrink-0 ml-2">+ <div className="flex items-center gap-2 text-xs text-control-light shrink-0 ml-2"><span>{item.metadata.columns.length} cols</span>{item.metadata.columns.length > 0 ? (<Button@@ -203,10 +203,10 @@ export function FlatTableList({</div>{isExpanded ? (- <div className="pl-4 pr-2 bg-gray-50 border-l-2 border-gray-200">+ <div className="pl-4 pr-2 bg-control-bg border-l-2 border-block-border">{item.metadata.columns.length > 0 ? (<div className="py-1">- <div className="text-xs font-medium text-gray-600 mb-1">+ <div className="text-xs font-medium text-control-light mb-1">{t("database.columns")}</div>{item.metadata.columns.map((column) => (@@ -215,17 +215,19 @@ export function FlatTableList({className="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"><div className="flex items-center gap-1">- <ColumnIcon className="size-3 text-gray-400" />+ <ColumnIcon className="size-3 text-control-placeholder" /><span>{column.name}</span></div>- <span className="text-gray-500">{column.type}</span>+ <span className="text-control-light">+ {column.type}+ </span></div>))}</div>) : null}{item.metadata.indexes && item.metadata.indexes.length > 0 ? (- <div className="py-1 border-t border-gray-200">- <div className="text-xs font-medium text-gray-600 mb-1">+ <div className="py-1 border-t border-block-border">+ <div className="text-xs font-medium text-control-light mb-1">{t("database.indexes")}</div>{item.metadata.indexes.map((index) => (@@ -234,10 +236,10 @@ export function FlatTableList({className="flex flex-wrap items-center justify-between gap-1 py-0.5 text-xs pl-2"><div className="flex items-center gap-1">- <IndexIcon className="size-3 text-gray-400" />+ <IndexIcon className="size-3 text-control-placeholder" /><span>{index.name}</span></div>- <span className="text-gray-500">+ <span className="text-control-light">{index.unique ? "UNIQUE" : ""}{" "}{index.primary ? "PRIMARY" : ""}</span>diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsxindex 8f234f7906..71df2f3cc4 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/HoverPanel.tsx@@ -139,7 +139,7 @@ export function HoverPanel({<divref={popoverRef}className={cn(- "fixed border border-gray-100 rounded-sm bg-white p-2 shadow-sm transition-[top] text-sm",+ "fixed border border-block-border rounded-sm bg-background p-2 shadow-sm transition-[top] text-sm",LAYER_SURFACE_CLASS,!show && "invisible pointer-events-none")}diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsxindex 4551c641d6..d1d9566c3c 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/InfoItem.tsx@@ -19,7 +19,7 @@ export function InfoItem({ title, titleSlot, children }: Props) {className="w-full grid gap-x-4 items-center"style={{ gridTemplateColumns: "auto 1fr" }}>- <div className="text-gray-500 font-medium whitespace-nowrap">+ <div className="text-control-light font-medium whitespace-nowrap">{titleSlot ?? title}</div><div className="text-right flex items-center justify-end min-w-0">diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsxindex 0ce95d761f..27f0b3224f 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/icons.tsx@@ -40,7 +40,7 @@ export function ExternalTableIcon({ className }: IconProps) {export function ViewIcon({ className }: IconProps) {return (<div className={cn("relative", baseSize, className)}>- <Table className={cn(baseSize, "text-gray-400")} />+ <Table className={cn(baseSize, "text-control-placeholder")} /><GlassesclassName="absolute bottom-0 right-0 w-3/4 h-3/4 fill-white"stroke="rgb(var(--color-accent))"@@ -51,12 +51,18 @@ export function ViewIcon({ className }: IconProps) {}export function ProcedureIcon({ className }: IconProps) {- return <Parentheses className={cn(baseSize, "text-gray-400", className)} />;+ return (+ <Parentheses+ className={cn(baseSize, "text-control-placeholder", className)}+ />+ );}export function FunctionIcon({ className }: IconProps) {return (- <SquareFunction className={cn(baseSize, "text-gray-400", className)} />+ <SquareFunction+ className={cn(baseSize, "text-control-placeholder", className)}+ />);}@@ -68,7 +74,7 @@ export function SequenceIcon({ className }: IconProps) {return (<divclassName={cn(- "relative w-4 h-4 inline-flex items-center justify-center text-gray-500",+ "relative w-4 h-4 inline-flex items-center justify-center text-control-light",className)}>@@ -84,11 +90,13 @@ export function TriggerIcon({ className }: IconProps) {}export function PackageIcon({ className }: IconProps) {- return <Package className={cn(baseSize, "text-gray-400", className)} />;+ return (+ <Package className={cn(baseSize, "text-control-placeholder", className)} />+ );}export function ForeignKeyIcon({ className }: IconProps) {- return <Link className={cn("size-3.5 text-gray-500", className)} />;+ return <Link className={cn("size-3.5 text-control-light", className)} />;}export function TablePartitionIcon({ className }: IconProps) {@@ -120,10 +128,10 @@ export function IndexIcon({ className }: IconProps) {}/**- * Vue's CheckIcon is tabler/check at 12px in `text-gray-500`.+ * Vue's CheckIcon is tabler/check at 12px in `text-control-light`.*/export function CheckConstraintIcon({ className }: IconProps) {- return <Check className={cn("size-3.5 text-gray-500", className)} />;+ return <Check className={cn("size-3.5 text-control-light", className)} />;}// ColumnIcon is shared with SchemaEditorLite; both surfaces must renderdiff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsxindex a6471df553..14963a3cbb 100644--- a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx@@ -175,7 +175,7 @@ export function SharePopoverBody({ worksheet }: Props) {"border flex flex-row justify-start items-center px-2 py-1 rounded-sm",allowChangeAccess? "hover:border-accent"- : "border-gray-200 text-gray-400"+ : "border-control-border text-control-placeholder")}><strong>{currentAccess.label}</strong>@@ -190,8 +190,8 @@ export function SharePopoverBody({ worksheet }: Props) {data-option-rowclassName={cn("p-2 rounded-xs flex justify-between",- allowChangeAccess && "cursor-pointer hover:bg-gray-200",- option.value === currentAccess.value && "bg-gray-200"+ allowChangeAccess && "cursor-pointer hover:bg-control-bg",+ option.value === currentAccess.value && "bg-control-bg")}onClick={() => handleChangeAccess(option)}>@@ -229,7 +229,7 @@ export function SharePopoverBody({ worksheet }: Props) {type="text"readOnlyvalue={sharedTabLink}- className="flex-1 min-w-0 h-full px-2 bg-white text-control text-sm cursor-text appearance-none border-0 shadow-none outline-hidden focus:outline-hidden focus:ring-0 focus:border-0 focus:shadow-none"+ className="flex-1 min-w-0 h-full px-2 bg-background text-control text-sm cursor-text appearance-none border-0 shadow-none outline-hidden focus:outline-hidden focus:ring-0 focus:border-0 focus:shadow-none"/>{/* Copy button — enabled whenever the shared worksheet has a link.Gated on the shared worksheet (sharedTabLink), NOT the current tab's@@ -243,7 +243,7 @@ export function SharePopoverBody({ worksheet }: Props) {data-copy-btndisabled={!sharedTabLink}onClick={handleCopyLink}- className="h-full rounded-none border-l border-control-border bg-white enabled:hover:bg-control-bg-hover enabled:hover:text-main disabled:bg-control-bg focus-visible:ring-inset focus-visible:ring-offset-0"+ className="h-full rounded-none border-l border-control-border bg-background enabled:hover:bg-control-bg-hover enabled:hover:text-main disabled:bg-control-bg focus-visible:ring-inset focus-visible:ring-offset-0"><Copy className="size-4" /></Button>diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsxindex eb2d13ff71..8d91c2849c 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx@@ -33,6 +33,8 @@ import { languageOfEngineV1 } from "@/types/sqlEditor/editor";import { instanceV1AllowsExplain, nextAnimationFrame } from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";import { useAIActions } from "../Panels/common/useAIActions";+import { monacoThemeName } from "../theme/derive";+import { useActiveSQLEditorTheme } from "../theme/useActiveSQLEditorTheme";import { computeAppendedSelection } from "./appendSelection";import { activeSQLEditorRef, activeStatementRef } from "./state";import { UploadFileButton } from "./UploadFileButton";@@ -430,6 +432,12 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {};}, [instanceName, databaseName, schema]);+ const activeTheme = useActiveSQLEditorTheme();+ const editorOptions = useMemo(+ () => ({ theme: monacoThemeName(activeTheme) }),+ [activeTheme]+ );+return (<div className="w-full h-full grow flex flex-col justify-start items-start overflow-hidden"><MonacoEditor@@ -443,6 +451,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {dialect={dialect}readOnly={readonly}autoCompleteContext={autoCompleteContext}+ options={editorOptions}onChange={handleChange}onSelectContent={handleSelectContent}onSelectionChange={handleSelectionChange}diff --git a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsxindex 7d5ae27552..82d59277f9 100644--- a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx@@ -66,17 +66,19 @@ export function TabItem({if (!environment || environment.id === String(UNKNOWN_ID)) return undefined;return environment.color || undefined;});- const backgroundColorRgb = isCurrentTab- ? environmentTintColor+ // Per-environment tint only. The active-tab fallback (no env color) is+ // themed via the `accent` token classes below instead of a hardcoded indigo,+ // so it stays readable in dark themes.+ const envColorRgb =+ isCurrentTab && environmentTintColor? hexToRgb(environmentTintColor).join(", ")- : hexToRgb("#4f46e5").join(", ")- : "";+ : "";- const bodyStyle = backgroundColorRgb+ const bodyStyle = envColorRgb? {- backgroundColor: `rgba(${backgroundColorRgb}, 0.1)`,- borderTopColor: `rgb(${backgroundColorRgb})`,- color: `rgb(${backgroundColorRgb})`,+ backgroundColor: `rgba(${envColorRgb}, 0.1)`,+ borderTopColor: `rgb(${envColorRgb})`,+ color: `rgb(${envColorRgb})`,}: undefined;@@ -115,7 +117,12 @@ export function TabItem({<divclassName={cn("body flex items-center justify-between gap-x-2 pl-2 pr-1 border-t h-9",- isCurrentTab ? "pt-0.5 border-t-[3px] bg-background" : "pt-1"+ isCurrentTab ? "pt-0.5 border-t-[3px] bg-background" : "pt-1",+ // Active tab without a per-environment color: accent token (adapts to+ // light/dark) replaces the old hardcoded indigo that was dim on dark.+ isCurrentTab &&+ !envColorRgb &&+ "border-accent text-accent bg-accent/10")}style={bodyStyle}>diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsxindex 2a1211649e..4b5ddfdbf8 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx@@ -16,6 +16,8 @@ import { Engine } from "@/types/proto-es/v1/common_pb";import { languageOfEngineV1 } from "@/types/sqlEditor/editor";import { instanceV1AllowsExplain } from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";+import { monacoThemeName } from "../theme/derive";+import { useActiveSQLEditorTheme } from "../theme/useActiveSQLEditorTheme";import {checkCursorAtFirst,checkCursorAtLast,@@ -320,10 +322,12 @@ export function CompactSQLEditor({[firstLinePrompt]);+ const activeTheme = useActiveSQLEditorTheme();+const editorOptions =useMemo<monaco.editor.IStandaloneEditorConstructionOptions>(() => ({- theme: "vs-dark",+ theme: monacoThemeName(activeTheme),lineNumbers: getLineNumber,lineNumbersMinChars: firstLinePrompt.length + 3,cursorStyle: readonly ? "underline" : "block",@@ -334,7 +338,7 @@ export function CompactSQLEditor({},overviewRulerLanes: 0,}),- [readonly, firstLinePrompt, getLineNumber]+ [activeTheme, readonly, firstLinePrompt, getLineNumber]);return (diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsxindex 750369590e..d84a1d945e 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx+++ b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx@@ -14,6 +14,8 @@ import {} from "@/react/stores/sqlEditor/tab";import { getWebTerminalQuerySession } from "@/react/stores/sqlEditor/webTerminal-service";import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";+import { SQLEditorThemeScope } from "../theme/SQLEditorThemeScope";+import { useActiveSQLEditorTheme } from "../theme/useActiveSQLEditorTheme";import { CompactSQLEditor } from "./CompactSQLEditor";import { useHistory } from "./useHistory";@@ -37,6 +39,7 @@ import { useHistory } from "./useHistory";*/export function TerminalPanel() {const { t } = useTranslation();+ const adminTheme = useActiveSQLEditorTheme();const batchGetOrFetchDatabases = useAppStore((s) => s.batchGetOrFetchDatabases);@@ -203,70 +206,72 @@ export function TerminalPanel() {);return (- <div className="flex h-full w-full flex-col justify-start items-stretch overflow-hidden bg-dark-bg">- <EditorAction />- {!isDisconnected ? (- <div- ref={containerRef}- className="w-full flex-1 overflow-y-auto bg-dark-bg"- >- <div ref={stackRef} className="w-full flex flex-col">- {queryList.map((query) => {- const editable = isEditableQueryItem(query);- const database = query.params?.connection.database- ? getDatabaseByName(query.params.connection.database)- : undefined;- return (- <div key={query.id} className="relative">- <CompactSQLEditor- content={query.statement}- readonly={!editable}- onChange={handleChangeFor.get(query.id) ?? noop}- onExecute={handleExecute}- onHistory={handleHistory}- onClearScreen={handleClearScreen}- />- {query.params && query.resultSet && database && (- <div className="p-2 w-full flex-1 min-h-0">- <ResultView- executeParams={query.params}- resultSet={query.resultSet}- database={database}- loading={query.status === "RUNNING"}- dark- />- </div>- )}- {query.resultSet?.error && (- <div className="p-2 pb-1 text-md font-normal text-matrix-green-hover">- {t("sql-editor.connection-lost")}- </div>- )}- {query.status === "RUNNING" && (- <div className="absolute inset-0 bg-black/20 flex justify-center items-center gap-2">- <Loader2 className="size-5 animate-spin text-control-light" />- {query === currentQuery && expired && (- <button- type="button"- className="text-gray-400 cursor-pointer hover:underline text-sm select-none"- onClick={handleCancelQuery}- >- {t("common.cancel")}- </button>- )}- </div>- )}- </div>- );- })}+ <SQLEditorThemeScope theme={adminTheme} className="h-full w-full">+ <div className="flex h-full w-full flex-col justify-start items-stretch overflow-hidden bg-background">+ <EditorAction />+ {!isDisconnected ? (+ <div+ ref={containerRef}+ className="w-full flex-1 overflow-y-auto bg-background"+ >+ <div ref={stackRef} className="w-full flex flex-col">+ {queryList.map((query) => {+ const editable = isEditableQueryItem(query);+ const database = query.params?.connection.database+ ? getDatabaseByName(query.params.connection.database)+ : undefined;+ return (+ <div key={query.id} className="relative">+ <CompactSQLEditor+ content={query.statement}+ readonly={!editable}+ onChange={handleChangeFor.get(query.id) ?? noop}+ onExecute={handleExecute}+ onHistory={handleHistory}+ onClearScreen={handleClearScreen}+ />+ {query.params && query.resultSet && database && (+ <div className="p-2 w-full flex-1 min-h-0">+ <ResultView+ executeParams={query.params}+ resultSet={query.resultSet}+ database={database}+ loading={query.status === "RUNNING"}+ compact+ />+ </div>+ )}+ {query.resultSet?.error && (+ <div className="p-2 pb-1 text-md font-normal text-matrix-green-hover">+ {t("sql-editor.connection-lost")}+ </div>+ )}+ {query.status === "RUNNING" && (+ <div className="absolute inset-0 bg-overlay/20 flex justify-center items-center gap-2">+ <Loader2 className="size-5 animate-spin text-control-light" />+ {query === currentQuery && expired && (+ <button+ type="button"+ className="text-control-placeholder cursor-pointer hover:underline text-sm select-none"+ onClick={handleCancelQuery}+ >+ {t("common.cancel")}+ </button>+ )}+ </div>+ )}+ </div>+ );+ })}+ </div></div>- </div>- ) : (- <div className="flex-1 flex flex-col min-h-0">- <ConnectionHolder />- </div>- )}- </div>+ ) : (+ <div className="flex-1 flex flex-col min-h-0">+ <ConnectionHolder />+ </div>+ )}+ </div>+ </SQLEditorThemeScope>);}diff --git a/frontend/src/react/components/sql-editor/ThemeSelect.test.tsx b/frontend/src/react/components/sql-editor/ThemeSelect.test.tsxnew file mode 100644index 0000000000..4f5cf0d5fa--- /dev/null+++ b/frontend/src/react/components/sql-editor/ThemeSelect.test.tsx@@ -0,0 +1,152 @@+import type { ReactElement } from "react";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),+ editorState: {+ themeId: "light",+ },+ setThemeId: vi.fn(),+}));++vi.mock("react-i18next", () => ({+ useTranslation: mocks.useTranslation,+}));++vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: unknown) => unknown) =>+ selector(mocks.editorState),+ getSQLEditorEditorState: () => ({+ setThemeId: mocks.setThemeId,+ }),+}));++vi.mock("@/react/components/ui/select", () => ({+ Select: ({+ children,+ value,+ onValueChange,+ }: {+ children: React.ReactNode;+ value?: string;+ onValueChange?: (v: string) => void;+ }) => (+ <div+ data-testid="select-root"+ data-value={value}+ data-change-handler={onValueChange ? "true" : "false"}+ >+ {children}+ </div>+ ),+ SelectTrigger: ({+ children,+ "aria-label": ariaLabel,+ }: {+ children: React.ReactNode;+ "aria-label"?: string;+ size?: string;+ }) => (+ <button data-testid="select-trigger" aria-label={ariaLabel}>+ {children}+ </button>+ ),+ SelectValue: () => <span data-testid="select-value" />,+ SelectContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="select-content">{children}</div>+ ),+ SelectItem: ({+ children,+ value,+ }: {+ children: React.ReactNode;+ value?: string;+ }) => (+ <div data-testid="select-item" data-value={value}>+ {children}+ </div>+ ),+}));++let ThemeSelect: typeof import("./ThemeSelect").ThemeSelect;++const renderIntoContainer = (element: ReactElement) => {+ const container = document.createElement("div");+ const root = createRoot(container);+ document.body.appendChild(container);+ return {+ container,+ render: () => {+ act(() => {+ root.render(element);+ });+ },+ unmount: () => {+ act(() => {+ root.unmount();+ });+ container.remove();+ },+ };+};++beforeEach(async () => {+ vi.clearAllMocks();+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });+ mocks.editorState = { themeId: "light" };+ ({ ThemeSelect } = await import("./ThemeSelect"));+});++describe("ThemeSelect", () => {+ test("renders the select trigger with correct aria-label", () => {+ const { container, render, unmount } = renderIntoContainer(<ThemeSelect />);+ render();++ const trigger = container.querySelector("[data-testid='select-trigger']");+ expect(trigger).not.toBeNull();+ expect(trigger?.getAttribute("aria-label")).toBe("sql-editor.theme.self");++ unmount();+ });++ test("current themeId is forwarded to Select value", () => {+ mocks.editorState = { themeId: "dark" };+ const { container, render, unmount } = renderIntoContainer(<ThemeSelect />);+ render();++ const root = container.querySelector("[data-testid='select-root']");+ expect(root?.getAttribute("data-value")).toBe("dark");++ unmount();+ });++ test("renders one SelectItem per PRESET", async () => {+ const { PRESETS } = await import("./theme/presets");+ const { container, render, unmount } = renderIntoContainer(<ThemeSelect />);+ render();++ const items = container.querySelectorAll("[data-testid='select-item']");+ expect(items.length).toBe(PRESETS.length);++ unmount();+ });++ test("renders each preset's literal name (no i18n on theme names)", () => {+ const { container, render, unmount } = renderIntoContainer(<ThemeSelect />);+ render();++ const items = container.querySelectorAll("[data-testid='select-item']");+ const lightItem = Array.from(items).find(+ (el) => el.getAttribute("data-value") === "light"+ );+ expect(lightItem?.textContent).toBe("Default Light");++ unmount();+ });+});diff --git a/frontend/src/react/components/sql-editor/ThemeSelect.tsx b/frontend/src/react/components/sql-editor/ThemeSelect.tsxnew file mode 100644index 0000000000..e504dccac9--- /dev/null+++ b/frontend/src/react/components/sql-editor/ThemeSelect.tsx@@ -0,0 +1,57 @@+import { useTranslation } from "react-i18next";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/react/components/ui/select";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";+import { PRESETS } from "./theme/presets";++// NOTE: preset names below are rendered as literal strings, NOT i18n keys, by+// design. This switcher is dev-only (mounted behind `isDev()`), so end users+// never see it; the names are largely proper nouns (e.g. "Solarized Dark") that+// aren't translated anyway; and future user-defined custom themes will carry+// arbitrary user-provided names. Only the switcher's own chrome label is+// localized (`sql-editor.theme.self`). See the theme design doc's as-shipped+// notes. (Intentional exception to the AGENTS.md "all UI text in locales" rule.)+export function ThemeSelect() {+ const { t } = useTranslation();+ const themeId = useSQLEditorEditorState((s) => s.themeId);++ return (+ <Select+ value={themeId}+ onValueChange={(value) => {+ if (typeof value === "string") {+ getSQLEditorEditorState().setThemeId(value);+ }+ }}+ >+ <SelectTrigger+ size="sm"+ className="h-8"+ aria-label={t("sql-editor.theme.self")}+ >+ {/* Render the preset's display name, not the raw id ("light"). */}+ <SelectValue>+ {(value) => {+ const preset = PRESETS.find((p) => p.id === value);+ return preset ? preset.name : String(value ?? "");+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {PRESETS.map((preset) => (+ <SelectItem key={preset.id} value={preset.id}>+ {preset.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ );+}diff --git a/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.test.tsx b/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.test.tsxnew file mode 100644index 0000000000..0ccbe03591--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.test.tsx@@ -0,0 +1,48 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, test } from "vitest";+import { PRESET_BY_ID } from "./presets";+import { SQLEditorThemeScope, useSQLEditorTheme } from "./SQLEditorThemeScope";++function Probe() {+ const theme = useSQLEditorTheme();+ return <span data-testid="id">{theme.id}</span>;+}++describe("SQLEditorThemeScope", () => {+ test("writes the theme tokens as inline CSS vars on its container", () => {+ const { container } = render(+ <SQLEditorThemeScope theme={PRESET_BY_ID.dark}>+ <div>child</div>+ </SQLEditorThemeScope>+ );+ const el = container.firstChild as HTMLElement;+ expect(el.style.getPropertyValue("--color-background")).toBe(+ PRESET_BY_ID.dark.tokens["--color-background"]+ );+ });++ test("provides the theme via context", () => {+ render(+ <SQLEditorThemeScope theme={PRESET_BY_ID.dark}>+ <Probe />+ </SQLEditorThemeScope>+ );+ expect(screen.getByTestId("id").textContent).toBe("dark");+ });++ test("nested scope overrides the parent for context consumers", () => {+ render(+ <SQLEditorThemeScope theme={PRESET_BY_ID.light}>+ <SQLEditorThemeScope theme={PRESET_BY_ID.dark}>+ <Probe />+ </SQLEditorThemeScope>+ </SQLEditorThemeScope>+ );+ expect(screen.getByTestId("id").textContent).toBe("dark");+ });++ test("default context value is the light theme", () => {+ render(<Probe />);+ expect(screen.getByTestId("id").textContent).toBe("light");+ });+});diff --git a/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.tsx b/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.tsxnew file mode 100644index 0000000000..40d8e759b6--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/SQLEditorThemeScope.tsx@@ -0,0 +1,50 @@+import { createContext, type ReactNode, useContext, useMemo } from "react";+import { cn } from "@/react/lib/utils";+import { themeColorScheme, themeToCssVars } from "./derive";+import { PRESET_BY_ID } from "./presets";+import type { SQLEditorTheme } from "./types";++const SQLEditorThemeContext = createContext<SQLEditorTheme>(PRESET_BY_ID.light);++export const useSQLEditorTheme = (): SQLEditorTheme =>+ useContext(SQLEditorThemeContext);++type Props = {+ readonly theme: SQLEditorTheme;+ readonly children: ReactNode;+ readonly className?: string;+ // Render the container with `display: contents` (no box) — inline CSS custom+ // properties still cascade to children, so tokens scope without affecting+ // layout. Use for the root and portal wrappers where an extra box would+ // disturb sizing.+ readonly asContents?: boolean;+};++/**+ * Provides `theme` via context AND writes its chrome tokens as inline CSS+ * custom properties so descendant Tailwind classes (text-control, bg-*, …)+ * re-theme via cascade. Nest it to override a subtree (admin terminal, portals).+ */+export function SQLEditorThemeScope({+ theme,+ children,+ className,+ asContents = false,+}: Props) {+ const style = useMemo(+ () => ({+ ...themeToCssVars(theme.tokens),+ // Native controls (date pickers, scrollbars) follow color-scheme, not our+ // --color-* tokens — set it so they match a dark theme too.+ colorScheme: themeColorScheme(theme),+ }),+ [theme]+ );+ return (+ <SQLEditorThemeContext.Provider value={theme}>+ <div className={cn(asContents && "contents", className)} style={style}>+ {children}+ </div>+ </SQLEditorThemeContext.Provider>+ );+}diff --git a/frontend/src/react/components/sql-editor/theme/derive.test.ts b/frontend/src/react/components/sql-editor/theme/derive.test.tsnew file mode 100644index 0000000000..8e1612c845--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/derive.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from "vitest";+import {+ buildMonacoTheme,+ monacoThemeName,+ resolveAdminTheme,+ themeToCssVars,+ validateTheme,+} from "./derive";+import type { SQLEditorTheme } from "./types";+import { SQL_EDITOR_THEME_TOKENS } from "./types";++// Minimal complete fixture (token values arbitrary but every key present).+const fixture = (over: Partial<SQLEditorTheme> = {}): SQLEditorTheme => {+ const tokens = Object.fromEntries(+ SQL_EDITOR_THEME_TOKENS.map((k) => [k, "1 2 3"])+ ) as SQLEditorTheme["tokens"];+ return {+ id: "fixture",+ name: "Fixture",+ monacoBase: "vs",+ tokens,+ ...over,+ };+};++describe("themeToCssVars", () => {+ test("maps every chrome token to a --color-* CSS property", () => {+ const vars = themeToCssVars(fixture().tokens);+ expect(vars["--color-control"]).toBe("1 2 3");+ expect(Object.keys(vars)).toHaveLength(SQL_EDITOR_THEME_TOKENS.length);+ });+});++describe("monacoThemeName", () => {+ test("prefixes the theme id", () => {+ expect(monacoThemeName(fixture({ id: "monokai" }))).toBe("bb-monokai");+ });+});++describe("buildMonacoTheme", () => {+ test("carries the base and the word-highlight reset, no rules", () => {+ const data = buildMonacoTheme(fixture({ monacoBase: "vs-dark" }));+ expect(data.base).toBe("vs-dark");+ expect(data.inherit).toBe(true);+ expect(data.rules).toEqual([]);+ expect(data.colors["editor.wordHighlightBackground"]).toBe("#00000000");+ });+});++describe("resolveAdminTheme", () => {+ test("keeps a dark selected theme", () => {+ const dark = fixture({ id: "monokai", monacoBase: "vs-dark" });+ expect(resolveAdminTheme(dark).id).toBe("monokai");+ });+ test("falls back to the dark preset for a light selected theme", () => {+ const light = fixture({ id: "light", monacoBase: "vs" });+ expect(resolveAdminTheme(light).id).toBe("dark");+ });+});++describe("validateTheme", () => {+ test("passes a complete theme", () => {+ expect(() => validateTheme(fixture())).not.toThrow();+ });+ test("throws when a chrome token is missing", () => {+ const bad = fixture();+ // @ts-expect-error intentionally drop a token+ delete bad.tokens["--color-accent"];+ expect(() => validateTheme(bad)).toThrow(/--color-accent/);+ });+});diff --git a/frontend/src/react/components/sql-editor/theme/derive.ts b/frontend/src/react/components/sql-editor/theme/derive.tsnew file mode 100644index 0000000000..e9286aa4ed--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/derive.ts@@ -0,0 +1,71 @@+import type { editor as Editor } from "monaco-editor";+import type { CSSProperties } from "react";+import { PRESET_BY_ID } from "./presets";+import type { SQLEditorTheme } from "./types";+import { SQL_EDITOR_THEME_TOKENS } from "./types";++/** Chrome: tokens → inline CSS custom properties for a container's `style`. */+export function themeToCssVars(+ tokens: SQLEditorTheme["tokens"]+): CSSProperties & Record<string, string> {+ const vars: Record<string, string> = {};+ for (const token of SQL_EDITOR_THEME_TOKENS) {+ vars[token] = tokens[token];+ }+ return vars as CSSProperties & Record<string, string>;+}++/** Monaco theme name registered via defineTheme + used by setTheme. */+export function monacoThemeName(theme: SQLEditorTheme): string {+ return `bb-${theme.id}`;+}++/**+ * Monaco: a theme → registered standalone theme data. The editor canvas is+ * owned by the codingame VSCode theme service (which ignores per-theme colors+ * passed to `defineTheme`), so this only carries the base (`vs`/`vs-dark`) plus+ * the long-standing "no word-highlight box" reset. The editor background comes+ * from the chrome `--color-background` via the transparent-canvas CSS; syntax+ * token colors come from the base.+ */+export function buildMonacoTheme(+ theme: SQLEditorTheme+): Editor.IStandaloneThemeData {+ return {+ base: theme.monacoBase,+ inherit: true,+ rules: [],+ colors: {+ "editor.wordHighlightBackground": "#00000000",+ "editor.wordHighlightStrongBackground": "#00000000",+ },+ };+}++/**+ * Admin foreground resolution: keep dark themes (those keyed off the+ * `vs-dark` Monaco base), else fall back to the dark preset.+ */+export function resolveAdminTheme(selected: SQLEditorTheme): SQLEditorTheme {+ return selected.monacoBase === "vs-dark" ? selected : PRESET_BY_ID.dark;+}++/**+ * The CSS `color-scheme` for a theme. Apply it (`style.colorScheme`) alongside+ * the token vars so the platform renders NATIVE controls — date pickers,+ * scrollbars, `<select>` popups — to match. These are drawn by the browser/OS+ * and can't be styled with our `--color-*` tokens; `color-scheme` is the only+ * lever. Keyed off the Monaco base so a dark theme reports `dark`.+ */+export function themeColorScheme(theme: SQLEditorTheme): "dark" | "light" {+ return theme.monacoBase === "vs-dark" ? "dark" : "light";+}++/** Throws if any chrome token is missing. */+export function validateTheme(theme: SQLEditorTheme): void {+ for (const token of SQL_EDITOR_THEME_TOKENS) {+ if (typeof theme.tokens[token] !== "string") {+ throw new TypeError(`theme "${theme.id}" missing chrome token ${token}`);+ }+ }+}diff --git a/frontend/src/react/components/sql-editor/theme/presets/dark.ts b/frontend/src/react/components/sql-editor/theme/presets/dark.tsnew file mode 100644index 0000000000..4c46e27500--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/presets/dark.ts@@ -0,0 +1,38 @@+import type { SQLEditorTheme } from "../types";++export const dark: SQLEditorTheme = {+ id: "dark",+ name: "Default Dark",+ monacoBase: "vs-dark",+ tokens: {+ "--color-control": "229 231 235",+ "--color-control-hover": "243 244 246",+ "--color-control-light": "209 213 219",+ "--color-control-light-hover": "229 231 235",+ "--color-control-bg": "55 65 81",+ "--color-control-bg-hover": "75 85 99",+ "--color-control-placeholder": "156 163 175",+ "--color-control-border": "82 82 91",+ "--color-accent": "99 102 241",+ "--color-accent-hover": "129 140 248",+ "--color-accent-disabled": "67 56 202",+ "--color-accent-text": "255 255 255",+ "--color-main": "244 244 245",+ "--color-main-hover": "212 212 216",+ "--color-main-text": "24 24 27",+ "--color-background": "30 30 30",+ "--color-block-border": "63 63 70",+ "--color-link-hover": "63 63 70",+ "--color-info": "96 165 250",+ "--color-info-hover": "147 197 253",+ "--color-warning": "251 191 36",+ "--color-warning-hover": "253 224 71",+ "--color-error": "248 113 113",+ "--color-error-hover": "252 165 165",+ "--color-success": "74 222 128",+ "--color-success-hover": "134 239 172",+ "--color-matrix-green": "0 204 0",+ "--color-matrix-green-hover": "136 255 136",+ "--color-dark-bg": "30 30 30",+ },+};diff --git a/frontend/src/react/components/sql-editor/theme/presets/index.ts b/frontend/src/react/components/sql-editor/theme/presets/index.tsnew file mode 100644index 0000000000..a385ae94c5--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/presets/index.ts@@ -0,0 +1,16 @@+import type { SQLEditorTheme } from "../types";+import { dark } from "./dark";+import { light } from "./light";+import { solarizedDark } from "./solarized-dark";++// Display order in the switcher.+export const PRESETS: SQLEditorTheme[] = [light, dark, solarizedDark];++export const PRESET_BY_ID: Record<string, SQLEditorTheme> = Object.fromEntries(+ PRESETS.map((p) => [p.id, p])+);++export const DEFAULT_THEME_ID = "light";++export const resolveThemeId = (id: string | undefined): SQLEditorTheme =>+ (id && PRESET_BY_ID[id]) || PRESET_BY_ID[DEFAULT_THEME_ID];diff --git a/frontend/src/react/components/sql-editor/theme/presets/light.ts b/frontend/src/react/components/sql-editor/theme/presets/light.tsnew file mode 100644index 0000000000..1be36bad3a--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/presets/light.ts@@ -0,0 +1,38 @@+import type { SQLEditorTheme } from "../types";++export const light: SQLEditorTheme = {+ id: "light",+ name: "Default Light",+ monacoBase: "vs",+ tokens: {+ "--color-control": "82 82 91",+ "--color-control-hover": "24 24 27",+ "--color-control-light": "113 113 122",+ "--color-control-light-hover": "82 82 91",+ "--color-control-bg": "243 244 246",+ "--color-control-bg-hover": "229 231 235",+ "--color-control-placeholder": "161 161 170",+ "--color-control-border": "209 213 219",+ "--color-accent": "79 70 229",+ "--color-accent-hover": "55 48 163",+ "--color-accent-disabled": "165 180 252",+ "--color-accent-text": "255 255 255",+ "--color-main": "24 24 27",+ "--color-main-hover": "63 63 70",+ "--color-main-text": "255 255 255",+ "--color-background": "255 255 255",+ "--color-block-border": "229 231 235",+ "--color-link-hover": "229 231 235",+ "--color-info": "37 99 235",+ "--color-info-hover": "29 78 216",+ "--color-warning": "245 158 11",+ "--color-warning-hover": "180 83 9",+ "--color-error": "220 38 38",+ "--color-error-hover": "185 28 28",+ "--color-success": "22 163 74",+ "--color-success-hover": "21 128 61",+ "--color-matrix-green": "0 204 0",+ "--color-matrix-green-hover": "136 255 136",+ "--color-dark-bg": "30 30 30",+ },+};diff --git a/frontend/src/react/components/sql-editor/theme/presets/presets.test.ts b/frontend/src/react/components/sql-editor/theme/presets/presets.test.tsnew file mode 100644index 0000000000..3b15cf2455--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/presets/presets.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from "vitest";+import { validateTheme } from "../derive";+import {+ DEFAULT_THEME_ID,+ PRESET_BY_ID,+ PRESETS,+ resolveThemeId,+} from "./index";++describe("theme presets catalog", () => {+ test("every preset is structurally complete", () => {+ for (const preset of PRESETS) {+ expect(() => validateTheme(preset)).not.toThrow();+ }+ });+ test("ids are unique", () => {+ const ids = PRESETS.map((p) => p.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+ test("contains the presets in display order", () => {+ expect(PRESETS.map((p) => p.id)).toEqual([+ "light",+ "dark",+ "solarized-dark",+ ]);+ });+ test("default theme exists and is light", () => {+ expect(DEFAULT_THEME_ID).toBe("light");+ expect(PRESET_BY_ID[DEFAULT_THEME_ID]).toBeDefined();+ });+});++describe("resolveThemeId", () => {+ test("returns the matching preset for a known id", () => {+ expect(resolveThemeId("dark")).toBe(PRESET_BY_ID["dark"]);+ });+ test("falls back to the default for undefined", () => {+ expect(resolveThemeId(undefined)).toBe(PRESET_BY_ID[DEFAULT_THEME_ID]);+ });+ test("falls back to the default for an unknown id", () => {+ expect(resolveThemeId("nonexistent")).toBe(PRESET_BY_ID[DEFAULT_THEME_ID]);+ });+});diff --git a/frontend/src/react/components/sql-editor/theme/presets/solarized-dark.ts b/frontend/src/react/components/sql-editor/theme/presets/solarized-dark.tsnew file mode 100644index 0000000000..0155cbc5e9--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/presets/solarized-dark.ts@@ -0,0 +1,44 @@+import type { SQLEditorTheme } from "../types";++// Ethan Schoonover's Solarized Dark palette.+// base03 #002b36 base02 #073642 base01 #586e75 base00 #657b83+// base0 #839496 base1 #93a1a1 base2 #eee8d5 base3 #fdf6e3+// yellow #b58900 orange #cb4b16 red #dc322f magenta #d33682+// violet #6c71c4 blue #268bd2 cyan #2aa198 green #859900+// Starting values — tunable visually via the dev theme switcher.+export const solarizedDark: SQLEditorTheme = {+ id: "solarized-dark",+ name: "Solarized Dark",+ monacoBase: "vs-dark",+ tokens: {+ "--color-control": "131 148 150", // base0+ "--color-control-hover": "147 161 161", // base1+ "--color-control-light": "88 110 117", // base01+ "--color-control-light-hover": "101 123 131", // base00+ "--color-control-bg": "7 54 66", // base02+ "--color-control-bg-hover": "18 71 84",+ "--color-control-placeholder": "88 110 117", // base01+ "--color-control-border": "30 80 92",+ "--color-accent": "38 139 210", // blue+ "--color-accent-hover": "77 163 222",+ "--color-accent-disabled": "44 100 130",+ "--color-accent-text": "253 246 227", // base3+ "--color-main": "147 161 161", // base1+ "--color-main-hover": "131 148 150", // base0+ "--color-main-text": "0 43 54", // base03 (text on a base1 surface)+ "--color-background": "0 43 54", // base03+ "--color-block-border": "18 71 84",+ "--color-link-hover": "18 71 84",+ "--color-info": "38 139 210", // blue+ "--color-info-hover": "77 163 222",+ "--color-warning": "181 137 0", // yellow+ "--color-warning-hover": "204 153 0",+ "--color-error": "220 50 47", // red+ "--color-error-hover": "233 90 88",+ "--color-success": "133 153 0", // green+ "--color-success-hover": "163 184 30",+ "--color-matrix-green": "0 204 0",+ "--color-matrix-green-hover": "136 255 136",+ "--color-dark-bg": "0 43 54", // base03+ },+};diff --git a/frontend/src/react/components/sql-editor/theme/types.ts b/frontend/src/react/components/sql-editor/theme/types.tsnew file mode 100644index 0000000000..d0690f952e--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/types.ts@@ -0,0 +1,56 @@+// All chrome token names, for iteration/validation. Single source of truth —+// the SQLEditorThemeToken union is derived from this array so they can never+// diverge.+export const SQL_EDITOR_THEME_TOKENS = [+ "--color-control",+ "--color-control-hover",+ "--color-control-light",+ "--color-control-light-hover",+ "--color-control-bg",+ "--color-control-bg-hover",+ "--color-control-placeholder",+ "--color-control-border",+ "--color-accent",+ "--color-accent-hover",+ "--color-accent-disabled",+ "--color-accent-text",+ "--color-main",+ "--color-main-hover",+ "--color-main-text",+ "--color-background",+ "--color-block-border",+ "--color-link-hover",+ "--color-info",+ "--color-info-hover",+ "--color-warning",+ "--color-warning-hover",+ "--color-error",+ "--color-error-hover",+ "--color-success",+ "--color-success-hover",+ "--color-matrix-green",+ "--color-matrix-green-hover",+ "--color-dark-bg",+] as const;++// The SQL-Editor subset of the existing --color-* names. Every preset MUST+// fill all of these (enforced by validateTheme).+export type SQLEditorThemeToken = (typeof SQL_EDITOR_THEME_TOKENS)[number];++export interface SQLEditorTheme {+ id: string;+ // Literal display label, shown as-is (the theme switcher is dev-only, so+ // theme names aren't translated). Built-ins, proper-noun presets, and future+ // user-named custom themes all just set this.+ name: string;+ // Picks the Monaco editor base. The editor canvas is themed by the codingame+ // VSCode theme service (which ignores `monaco.editor.defineTheme`), so a theme+ // only chooses light vs dark here — the editor background then shows the+ // chrome `--color-background` through the transparent-canvas CSS, and syntax+ // token colors come from the base. (Per-theme editor/syntax palettes were+ // removed: they never reached the canvas in this runtime.)+ monacoBase: "vs" | "vs-dark";+ // Chrome layer: the SQL-Editor `--color-*` token values for this theme,+ // each a "r g b" triple (Tailwind resolves to `rgb(var(--color-x) / <alpha>)`).+ tokens: Record<SQLEditorThemeToken, string>;+}diff --git a/frontend/src/react/components/sql-editor/theme/useActiveSQLEditorTheme.ts b/frontend/src/react/components/sql-editor/theme/useActiveSQLEditorTheme.tsnew file mode 100644index 0000000000..23875d5776--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/useActiveSQLEditorTheme.ts@@ -0,0 +1,20 @@+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";+import { resolveAdminTheme } from "./derive";+import { resolveThemeId } from "./presets";+import type { SQLEditorTheme } from "./types";++/**+ * The SQL Editor theme that should currently apply to the foreground code+ * surface: the selected theme in worksheet mode, or its admin resolution+ * (selected-if-dark-else-dark) in admin mode. Used both for the chrome's+ * Monaco theme name and to drive the global Monaco theme controller.+ */+export function useActiveSQLEditorTheme(): SQLEditorTheme {+ const themeId = useSQLEditorEditorState((s) => s.themeId);+ const mode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const selected = resolveThemeId(themeId);+ return mode === "ADMIN" ? resolveAdminTheme(selected) : selected;+}diff --git a/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.ts b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.tsnew file mode 100644index 0000000000..9b173904d8--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/useMonacoThemeController.ts@@ -0,0 +1,43 @@+import { useEffect, useRef } from "react";+import {+ getResolvedTheme,+ loadMonacoEditor,+} from "@/react/components/monaco/core";+import { monacoThemeName } from "./derive";+import type { SQLEditorTheme } from "./types";+import { useActiveSQLEditorTheme } from "./useActiveSQLEditorTheme";++/**+ * Live-applies the active SQL Editor theme to Monaco's (global) theme when the+ * user switches themes while editors are already mounted.+ *+ * IMPORTANT: it must NOT call `monaco.editor.setTheme` on the initial mount.+ * Each SQL Editor Monaco instance already sets its own theme at construction via+ * its `options.theme`; calling the global `setTheme` *while an editor is still+ * constructing* races the codingame VSCode theme service and throws, which makes+ * the editor fall back to its read-only `<pre>`. So we only re-apply on a GENUINE+ * theme change (prev exists and differs). This also makes the effect safe under+ * React StrictMode's double-invoke — the replay runs with `prev === theme` and is+ * skipped.+ */+export function useMonacoThemeController() {+ const theme = useActiveSQLEditorTheme();+ const prevThemeRef = useRef<SQLEditorTheme | null>(null);++ useEffect(() => {+ const prev = prevThemeRef.current;+ prevThemeRef.current = theme;+ // Initial mount (prev === null) or StrictMode replay / no real change+ // (prev === theme): editors apply the theme themselves at construction.+ if (prev === null || prev === theme) return;++ let cancelled = false;+ void loadMonacoEditor().then((monaco) => {+ if (cancelled) return;+ monaco.editor.setTheme(getResolvedTheme(monacoThemeName(theme)));+ });+ return () => {+ cancelled = true;+ };+ }, [theme]);+}diff --git a/frontend/src/react/components/sql-editor/theme/useSQLEditorOverlayTheme.ts b/frontend/src/react/components/sql-editor/theme/useSQLEditorOverlayTheme.tsnew file mode 100644index 0000000000..fb8d47a90a--- /dev/null+++ b/frontend/src/react/components/sql-editor/theme/useSQLEditorOverlayTheme.ts@@ -0,0 +1,47 @@+import { useEffect } from "react";+import { getLayerRoot } from "@/react/components/ui/layer";+import { themeColorScheme, themeToCssVars } from "./derive";+import { useActiveSQLEditorTheme } from "./useActiveSQLEditorTheme";++/**+ * Themes the app-global "overlay" layer root while the SQL Editor is mounted, so+ * EVERY overlay that portals there follows the SQL Editor theme: dialogs (Save+ * Sheet, etc.), the request drawer, and the Base-UI Select/Popover/Tooltip+ * popups. These surfaces render outside the SQL Editor's DOM subtree, so the+ * scope's CSS vars can't cascade to them — setting the vars (plus a themed+ * default text color for un-classed text like checkbox labels) on the shared+ * overlay root is the single place that reaches all of them.+ *+ * Uses the **active** theme (the dark admin fallback in admin mode), not just+ * the selected one. The overlay root is global and admin's foreground is the+ * dark terminal that overlays sit over, so this mirrors how the global Monaco+ * theme is driven — otherwise a light-selected admin tab renders light popups+ * over the dark terminal.+ *+ * Reverted on unmount / theme change so the rest of the app's overlays are+ * unaffected. In the light theme the vars equal :root, so this is a visual no-op+ * outside a dark/named theme.+ */+export function useSQLEditorOverlayTheme() {+ const theme = useActiveSQLEditorTheme();++ useEffect(() => {+ const root = getLayerRoot("overlay");+ if (!root) return;+ const vars = themeToCssVars(theme.tokens);+ for (const [key, value] of Object.entries(vars)) {+ root.style.setProperty(key, value as string);+ }+ root.style.setProperty("color", "rgb(var(--color-main))");+ // Native controls (date pickers, scrollbars) in portaled popups follow+ // color-scheme, not our --color-* tokens.+ root.style.colorScheme = themeColorScheme(theme);+ return () => {+ for (const key of Object.keys(vars)) {+ root.style.removeProperty(key);+ }+ root.style.removeProperty("color");+ root.style.colorScheme = "";+ };+ }, [theme]);+}diff --git a/frontend/src/react/pages/settings/MembersPage.tsx b/frontend/src/react/pages/settings/MembersPage.tsxindex 4c7ec92349..0342627825 100644--- a/frontend/src/react/pages/settings/MembersPage.tsx+++ b/frontend/src/react/pages/settings/MembersPage.tsx@@ -2151,8 +2151,14 @@ export function MembersPage({ projectId }: { projectId?: string }) {? (roleList.find((r) => r.name === PresetRoleType.PROJECT_OWNER)?.permissions ?? []): [];+ // Require a non-empty owner permission set: when roleList is empty (roles+ // still loading, or listRoles failed and the loader continued with []), a+ // vacuous every() would otherwise report "full access" and wrongly block a+ // non-owner from the request-role flow. Falling through to false keeps the+ // request flow reachable (it has its own permission guard).const hasFullProjectAccess =!!project &&+ ownerPermissions.length > 0 &&ownerPermissions.every((permission) =>hasProjectPermissionV2(project, permission as Permission));diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.tsxindex 2932037ca6..4df2cfce0b 100644--- a/frontend/src/react/pages/settings/RequestRoleSheet.tsx+++ b/frontend/src/react/pages/settings/RequestRoleSheet.tsx@@ -18,6 +18,11 @@ import { ExprEditor } from "@/react/components/ExprEditor";import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";import { RoleSelect } from "@/react/components/RoleSelect";import { DDLWarningCallout } from "@/react/components/role-grant/DDLWarningCallout";+import {+ themeColorScheme,+ themeToCssVars,+} from "@/react/components/sql-editor/theme/derive";+import type { SQLEditorTheme } from "@/react/components/sql-editor/theme/types";import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";import { ExpirationPicker } from "@/react/components/ui/expiration-picker";@@ -90,6 +95,14 @@ export interface RequestRoleSheetProps {* switch to ALL or EXPRESSION mode if they want to broaden the scope.*/initialDatabaseResources?: DatabaseResource[];+ /**+ * SQL-Editor theme to apply to the drawer chrome. Set ONLY by the SQL-Editor+ * host (`RequestDrawerHost`) to the active theme (dark admin fallback+ * included). Omitted by every other caller (MembersPage,+ * ComponentPermissionGuard, …) so the drawer always renders in the default+ * (light) app theme outside the SQL Editor.+ */+ theme?: SQLEditorTheme;onClose: () => void;}@@ -110,10 +123,32 @@ const databaseModeLabelKey = (mode: DatabaseMode): string => {};export function RequestRoleSheet(props: Readonly<RequestRoleSheetProps>) {- const { open, project, onClose } = props;+ const { open, project, theme, onClose } = props;+ // The Sheet portals to the app-global overlay root, so a SQL-Editor theme+ // scope's CSS vars don't cascade in via the DOM — apply them inline on+ // SheetContent instead, and ONLY when a `theme` is explicitly passed (by the+ // SQL-Editor host). With no `theme`, leave SheetContent unstyled so it+ // inherits `:root` and always renders in the default light app theme outside+ // the SQL Editor — regardless of any ambient theme scope.+ const sheetStyle = useMemo(+ () =>+ theme+ ? {+ ...themeToCssVars(theme.tokens),+ // Native controls (the datetime picker, scrollbars) follow+ // color-scheme, not our --color-* tokens.+ colorScheme: themeColorScheme(theme),+ }+ : undefined,+ [theme]+ );return (<Sheet open={open} onOpenChange={(next) => !next && onClose()}>- <SheetContent width="standard">+ <SheetContent+ width="standard"+ style={sheetStyle}+ className={theme ? "text-main" : undefined}+ >{/* Base UI's Dialog.Portal unmounts after the close animation,so the inner form mounts/unmounts with the Sheet's lifecyclewithout needing an explicit {open && ...} guard. The `key`@@ -133,6 +168,8 @@ function RequestRoleForm({}: Readonly<Omit<RequestRoleSheetProps, "open">>) {const { t } = useTranslation();const currentUser = useCurrentUser();+ // Theming is handled by the outer RequestRoleSheet (inline vars on+ // SheetContent); this form just inherits them.const [role, setRole] = useState(initialRole);const [reason, setReason] = useState("");const [expirationTimestamp, setExpirationTimestamp] = useState<diff --git a/frontend/src/react/stores/sqlEditor/editor.test.ts b/frontend/src/react/stores/sqlEditor/editor.test.tsindex 2202496d90..f2e8d37de9 100644--- a/frontend/src/react/stores/sqlEditor/editor.test.ts+++ b/frontend/src/react/stores/sqlEditor/editor.test.ts@@ -1,8 +1,10 @@import { afterEach, beforeEach, describe, expect, test } from "vitest";+import { DEFAULT_THEME_ID } from "@/react/components/sql-editor/theme/presets";import {STORAGE_KEY_SQL_EDITOR_REDIS_NODE,STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,storageKeySqlEditorLastProject,+ storageKeySqlEditorTheme,} from "@/utils/storage-keys";import {getSQLEditorEditorState,@@ -45,6 +47,7 @@ beforeEach(() => {redisCommandOption: 1,isShowExecutingHint: false,executingHintDatabase: undefined,+ themeId: "light",});});@@ -120,3 +123,18 @@ describe("useSQLEditorEditorStore", () => {expect(calls).toBeGreaterThanOrEqual(3);});});++describe("theme persistence", () => {+ test("setThemeId updates state and persists", () => {+ getSQLEditorEditorState().setThemeId("dark");+ expect(useSQLEditorEditorStore.getState().themeId).toBe("dark");+ expect(storage.get(storageKeySqlEditorTheme(""))).toBe(+ JSON.stringify("dark")+ );+ });++ test("setThemeId rejects an unknown id and falls back to the default", () => {+ getSQLEditorEditorState().setThemeId("does-not-exist");+ expect(useSQLEditorEditorStore.getState().themeId).toBe(DEFAULT_THEME_ID);+ });+});diff --git a/frontend/src/react/stores/sqlEditor/editor.ts b/frontend/src/react/stores/sqlEditor/editor.tsindex 057b1ebee6..75427569b8 100644--- a/frontend/src/react/stores/sqlEditor/editor.ts+++ b/frontend/src/react/stores/sqlEditor/editor.ts@@ -1,6 +1,10 @@import { useSyncExternalStore } from "react";import { create, type StoreApi, type UseBoundStore } from "zustand";import { immer } from "zustand/middleware/immer";+import {+ DEFAULT_THEME_ID,+ PRESET_BY_ID,+} from "@/react/components/sql-editor/theme/presets";import { useAppStore } from "@/react/stores/app";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";@@ -8,6 +12,7 @@ import {STORAGE_KEY_SQL_EDITOR_REDIS_NODE,STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,storageKeySqlEditorLastProject,+ storageKeySqlEditorTheme,workspaceCacheScope,} from "@/utils/storage-keys";@@ -18,6 +23,7 @@ export interface SQLEditorEditorState {redisCommandOption: QueryOption_RedisRunCommandsOn;isShowExecutingHint: boolean;executingHintDatabase: Database | undefined;+ themeId: string;setProject: (project: string) => void;setProjectContextReady: (ready: boolean) => void;@@ -25,6 +31,7 @@ export interface SQLEditorEditorState {setRedisCommandOption: (option: QueryOption_RedisRunCommandsOn) => void;setShowExecutingHint: (show: boolean) => void;setExecutingHintDatabase: (db: Database | undefined) => void;+ setThemeId: (id: string) => void;}const DEFAULT_RESULT_ROWS_LIMIT = 1000;@@ -78,6 +85,22 @@ const readProject = () =>"");+const themeKey = () => {+ const state = useAppStore.getState();+ const isSaaS =+ typeof state?.isSaaSMode === "function" ? state.isSaaSMode() : false;+ return storageKeySqlEditorTheme(+ workspaceCacheScope(isSaaS, state?.currentUser?.workspace ?? "")+ );+};++const readThemeId = () =>+ safeRead<string>(+ themeKey(),+ (v) => (typeof v === "string" && PRESET_BY_ID[v] ? v : undefined),+ DEFAULT_THEME_ID+ );+const readResultRowsLimit = () =>safeRead<number>(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,@@ -107,6 +130,7 @@ export const useSQLEditorEditorStore: UseBoundStore<redisCommandOption: readRedisOption(),isShowExecutingHint: false,executingHintDatabase: undefined,+ themeId: readThemeId(),setProject(project) {set((s) => {@@ -126,6 +150,14 @@ export const useSQLEditorEditorStore: UseBoundStore<});safeWrite(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT, limit);},+ setThemeId(id) {+ // Ignore ids not in the catalog so a stale/garbage value can't break theming.+ const next = PRESET_BY_ID[id] ? id : DEFAULT_THEME_ID;+ set((s) => {+ s.themeId = next;+ });+ safeWrite(themeKey(), next);+ },setRedisCommandOption(option) {set((s) => {s.redisCommandOption = option;diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.tsindex 97c3093f7f..97e507996a 100644--- a/frontend/src/utils/storage-keys.ts+++ b/frontend/src/utils/storage-keys.ts@@ -69,6 +69,9 @@ export const storageKeyContextMenu = (key: string) => `bb.context-menu.${key}`;// unique only within a workspace (so they collide across workspaces in SaaS).export const storageKeySqlEditorLastProject = (scope: string) =>withScope("bb.sql-editor.last-project", scope);+// Workspace-scoped like other SQL Editor prefs.+export const storageKeySqlEditorTheme = (scope: string) =>+ withScope("bb.sql-editor.theme", scope);export const storageKeySqlEditorTabs = (scope: string,project: string,