Skip to content

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

refactor: migrate SQL Editor action bar (#20119)

ecmadaod13df33e1ca0
diff --git a/docs/superpowers/specs/2026-04-24-sql-editor-react-migration-stage-13-design.md b/docs/superpowers/specs/2026-04-24-sql-editor-react-migration-stage-13-design.md
new file mode 100644
index 0000000000..5dc43688a0
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-24-sql-editor-react-migration-stage-13-design.md
@@ -0,0 +1,216 @@
+# SQL Editor React Migration — Stage 13 Design
+
+**Date:** 2026-04-24
+**Author:** [email protected]
+**Status:** Draft
+
+## 1. Goal & non-goals
+
+**Goal:** Retire the top editor toolbar (`EditorAction.vue` + its sub-components) and the remaining SQL-Editor-level placeholder surfaces (`SQLEditorHomePage.vue`, `ReadonlyModeNotSupported.vue`, `SheetConnectionIcon.vue`, orphaned placeholders) by porting them to React end-to-end.
+
+After this stage, every in-scope file listed below is React; only Vue parents that still host React via `ReactPageMount` remain temporarily.
+
+**Non-goals:**
+- Migrating `EditorPanel.vue`, `StandardPanel.vue`, `EditorMain.vue`, `TerminalPanel.vue`, or `TabList/*`. They stay Vue — they will mount the new React `EditorAction` via `ReactPageMount`.
+- Migrating `SQLEditor.vue` (Monaco wrapper), the `ResultView` subtree, the Panels (`TablesPanel`, `ViewsPanel`, etc.), or the `SchemaPane` tree — separate stages.
+- Refactoring the existing Pinia stores (`useSQLEditorStore`, `useSQLEditorTabStore`, `useWorkSheetStore`, `useSQLEditorContext`). We read/write them via `useVueState` / direct method calls as we already do in Stages 11/12.
+- Adding new features — behavioral + visual parity only.
+
+## 2. Inventory (what's in scope)
+
+| # | File | LOC | Complexity | Notes |
+|---|---|---|---|---|
+| 1 | `frontend/src/views/sql-editor/Disconnected.vue` | 1 | trivial | Orphan. Delete. |
+| 2 | `frontend/src/views/sql-editor/GettingStarted.vue` | 1 | trivial | Orphan. Delete. |
+| 3 | `frontend/src/views/sql-editor/EditorPanel/ReadonlyModeNotSupported.vue` | 24 | low | Uses Vue `AdminModeButton.vue`. |
+| 4 | `frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue` | 24 | low | Consumed by `TabList/TabItem/Prefix.vue`. |
+| 5 | ~~`SQLEditorHomePage.vue`~~ | ~~197~~ | — | **Deferred** — turned out to be the root container that hosts `AsidePanel`, `TabList`, `EditorPanel`, `ConnectionPanel`, `Drawer`, `Quickstart`, `IAMRemindModal`, all still Vue. Migrating it requires those children to be React first. Late-stage target. |
+| 6 | `frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue` | 55 | low | Presentational; inline into parent. |
+| 7 | `frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue` | 164 | medium | Consumed by `EditorAction`, `CodeViewer`, `ViewDetail`. |
+| 8 | `frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue` | 188 | medium | Modal body. |
+| 9 | `frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue` | 24 | low | Wraps `ExecuteHint` in a BBModal. Currently rendered inline in `EditorMain.vue`. |
+| 10 | `frontend/src/views/sql-editor/EditorCommon/EditorAction.vue` | 316 | medium-high | Primary target. Consumed by `EditorMain.vue` + `TerminalPanel.vue`. Emits `execute`. |
+| 11 | `frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue` | 63 | low | React version already exists (`AdminModeButton.tsx`); Vue version is dead after callers migrate. |
+
+Already-React pieces this stage reuses without modification:
+- `QueryContextSettingPopover.tsx` (Stage 10)
+- `ChooserGroup.tsx` (Stage 9-ish)
+- `AdminModeButton.tsx` (already React)
+- `SharePopoverBody.tsx` (existing; we use it directly now, no `ReactPageMount` round-trip)
+
+## 3. Phase breakdown
+
+Each phase is commit-able and lint/type-check/test green on its own.
+
+### Phase 1 — Placeholder cleanup (quick wins)
+
+**Deliverables:**
+- Delete `Disconnected.vue`, `GettingStarted.vue` (confirmed unused).
+- Port `ReadonlyModeNotSupported.vue` → `frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx`.
+ - Composes React `NoPermissionPlaceholder` (create if missing — tiny; otherwise inline the "no permission" styling), `InstanceV1Name` equivalent (already used elsewhere in React — reuse), and `AdminModeButton.tsx`.
+ - Swap `EditorMain.vue`'s `<ReadonlyModeNotSupported v-else />` → `<ReactPageMount v-else page="ReadonlyModeNotSupported" />`.
+- Port `SheetConnectionIcon.vue` → `SheetConnectionIcon.tsx`.
+ - Swap the one caller (`TabList/TabItem/Prefix.vue`) to `<ReactPageMount page="SheetConnectionIcon" :tab="tab" />`.
+- Delete Vue originals after swapping.
+
+**Tests (new):** `ReadonlyModeNotSupported.test.tsx`, `SheetConnectionIcon.test.tsx`, `SQLEditorHomePage.test.tsx`. Pattern: mock stores/router and assert core strings + key interactions.
+
+**Dependencies needed:** Any missing Base UI / shadcn primitives should already exist (`Button`, `Tooltip`). No new primitives required.
+
+### Phase 2 — OpenAIButton
+
+**Deliverables:**
+- Port `OpenAIButton/OpenAIButton.vue` + `Button.vue` → `frontend/src/react/components/sql-editor/OpenAIButton.tsx` (merge both into one file — `Button.vue` is purely presentational).
+- Wraps the existing AI plugin state (pinia store `useAIContextStore` / similar — check the source for exact store).
+- Swap callers one at a time:
+ - `EditorAction.vue` — keep Vue until Phase 4, but swap the import to `<ReactPageMount page="OpenAIButton" :statement="..." />`. Or defer the swap to Phase 4 (cleaner).
+ - `EditorPanel/Panels/common/CodeViewer.vue` — swap to `ReactPageMount`.
+ - `EditorPanel/Panels/ViewsPanel/ViewDetail.vue` — swap to `ReactPageMount`.
+
+**Tests (new):** `OpenAIButton.test.tsx` — covers: feature-flag gating, button disabled when disconnected, click opens the AI chat panel (mock emit).
+
+**Delete:** `OpenAIButton/Button.vue`, `OpenAIButton/OpenAIButton.vue`, `OpenAIButton/index.ts`, and the dir afterwards.
+
+### Phase 3 — ExecuteHint + ExecutingHintModal
+
+**Deliverables:**
+- Port `ExecuteHint.vue` → `frontend/src/react/components/sql-editor/ExecuteHint.tsx`. Body of the confirmation modal: "do you want to run admin mode?" + `AdminModeButton` action.
+- Port `ExecutingHintModal.vue` → `frontend/src/react/components/sql-editor/ExecutingHintModal.tsx`.
+ - Replaces `BBModal` with the shadcn `Dialog` primitive.
+ - Reads `sqlEditorStore.isShowExecutingHint` / `executingHintDatabase` via `useVueState`.
+- Swap `EditorMain.vue`'s `<ExecutingHintModal />` → `<ReactPageMount page="ExecutingHintModal" />`.
+- Delete Vue `ExecuteHint.vue` + `ExecutingHintModal.vue`.
+
+**Tests (new):** `ExecutingHintModal.test.tsx` — renders when flag true, closes on OK, delegates to `AdminModeButton`.
+
+### Phase 4 — EditorAction toolbar (primary target)
+
+**Deliverables:**
+- Port `EditorAction.vue` → `frontend/src/react/components/sql-editor/EditorAction.tsx`.
+
+**Layout (parity with Vue):**
+```
+action-left:
+ - [ADMIN mode?] Exit-Admin-Mode button
+ - [WORKSHEET mode?] ButtonGroup: Run-button (with query limit) + QueryContextSettingPopover
+ - AdminModeButton (icon-only)
+ - [showSheetsFeature?] Save button (with Save hover tooltip + Cmd/Ctrl+S shortcut hint)
+ - [showSheetsFeature?] Share button (hover tooltip "Share" + click popover → SharePopoverBody)
+action-right:
+ - ChooserGroup (already React)
+ - OpenAIButton (from Phase 2)
+```
+
+**Primitives used (all exist):**
+- `Button` / `ButtonGroup` (our shadcn lib — check if we need to add a `ButtonGroup` wrapper; otherwise compose with `flex gap-0`)
+- `Tooltip` (for hover titles)
+- `Popover` (for Save hover + Share click)
+- `Dialog` (via `FeatureModal` — already React)
+- `ReactPageMount` is gone from this subtree — direct imports only
+
+**State reads** (via `useVueState`):
+- `currentTab`, `isDisconnected` (tab store)
+- `instance` (connection)
+- `resultRowsLimit` (sql-editor store)
+- `worksheet` (via `getWorksheetByName`)
+- `showConnectionPanel`, `asidePanelTab` (sql-editor context for share handlers — unchanged)
+
+**Props:**
+```ts
+type Props = {
+ readonly onExecute: (params: SQLEditorQueryParams) => void;
+};
+```
+
+**Caller swaps:**
+- `EditorMain.vue`: `<EditorAction @execute="handleExecuteFromActionBar" />` → `<ReactPageMount page="EditorAction" :onExecute="handleExecuteFromActionBar" />`
+- `TerminalPanel.vue`: `<EditorAction />` → `<ReactPageMount page="EditorAction" :onExecute="noop" />` (or an admin-mode-safe no-op; verify original behaviour — the `TerminalPanel` doesn't pass `@execute`, so it runs in ADMIN mode where the Run button is not rendered anyway).
+
+**Share popover wiring:**
+- Use React `Popover` + `SharePopoverBody` directly (the existing React component already works; no `ReactPageMount` round-trip needed inside React code).
+- Hover tooltip + click popover are two distinct interactions — use `Tooltip` outside / inside `Popover` per the Vue structure.
+
+**Tests (new):** `EditorAction.test.tsx` — 5 scenarios:
+1. Renders Run button when connected + non-empty statement; disabled otherwise.
+2. Clicking Run fires `onExecute` with the tab's statement + connection.
+3. Save button disabled when status === 'CLEAN'; enabled when dirty; click emits `save-sheet` event.
+4. Share popover opens on click when `allowShare` is true.
+5. In ADMIN mode, the Exit-Admin button renders (not the Run button).
+
+### Phase 5 — Cleanup
+
+- Delete Vue originals:
+ - `EditorAction.vue`
+ - `AdminModeButton.vue` (all callers now React after Phases 1, 3, 4)
+ - Empty directories if any.
+- Update `frontend/src/views/sql-editor/EditorCommon/index.ts` to drop the re-exports.
+- `rg "EditorAction\.vue|OpenAIButton\.vue|ExecuteHint\.vue|ExecutingHintModal\.vue|SheetConnectionIcon\.vue|ReadonlyModeNotSupported\.vue|SQLEditorHomePage\.vue|Disconnected\.vue|GettingStarted\.vue"` — confirm zero results.
+- Gates: `pnpm fix && pnpm type-check && pnpm test --run src/react/components/sql-editor src/views/sql-editor && pnpm check` all green.
+
+## 4. Per-phase checklist
+
+### Phase 1
+- [ ] `ReadonlyModeNotSupported.tsx` + test
+- [ ] `SheetConnectionIcon.tsx` + test
+- [ ] `SQLEditorHomePage.tsx` + test
+- [ ] Delete the four Vue files
+- [ ] Swap `EditorMain.vue` + `TabItem/Prefix.vue` + `SQLEditorPage.vue` (or router entry) to `ReactPageMount`
+- [ ] Gates green
+
+### Phase 2
+- [ ] `OpenAIButton.tsx` + test
+- [ ] Swap 3 callers to `ReactPageMount` (or inline direct import when the caller is already React)
+- [ ] Delete Vue `OpenAIButton/*`
+- [ ] Gates green
+
+### Phase 3
+- [ ] `ExecuteHint.tsx` (no separate test if trivial)
+- [ ] `ExecutingHintModal.tsx` + test
+- [ ] Swap `EditorMain.vue` to `ReactPageMount page="ExecutingHintModal"`
+- [ ] Delete 2 Vue files
+- [ ] Gates green
+
+### Phase 4
+- [ ] `EditorAction.tsx` + 5 tests
+- [ ] Swap `EditorMain.vue` + `TerminalPanel.vue`
+- [ ] `OpenAIButton` imported directly (not via `ReactPageMount`) since we're in React
+- [ ] `SharePopoverBody` imported directly
+- [ ] Gates green
+
+### Phase 5
+- [ ] Delete Vue `EditorAction.vue`, `AdminModeButton.vue`
+- [ ] Prune `EditorCommon/index.ts`
+- [ ] `rg` search confirms zero remaining references
+- [ ] `pnpm fix && type-check && test && check` all green
+
+## 5. Manual UX verification (after all phases)
+
+1. Empty editor (no tab): Welcome + Run button disabled; saves a draft on Cmd/Ctrl+S.
+2. Connected + non-empty SQL: Run button enabled; click executes; result panel appears.
+3. Run button shows limit indicator; QueryContextSettingPopover opens next to Run.
+4. Switch to ADMIN mode (via AdminModeButton) → Run button replaced by "Exit Admin Mode".
+5. Save button — disabled when status=CLEAN; Cmd/Ctrl+S triggers save; toast confirms.
+6. Share button — hover shows "Share" tooltip; click opens `SharePopoverBody`; toggling visibility persists.
+7. ChooserGroup on the right — selects environment/database/schema.
+8. OpenAIButton — disabled when disconnected; click toggles the AI side panel.
+9. ExecutingHintModal — run a DML on a restricted DB → modal appears → confirm opens Admin Mode.
+10. ReadonlyModeNotSupported — connect to instance without readonly → placeholder renders with AdminModeButton.
+11. Tab bar — each tab's SheetConnectionIcon renders correct state glyph.
+12. Landing page — open SQL Editor with no project selected → SQLEditorHomePage renders.
+
+## 6. Out of scope (deferred)
+
+- `SQLEditorPage.vue` itself — the top-level route. Stays Vue; only hosts React inside.
+- `EditorMain.vue`, `StandardPanel.vue`, `EditorPanel.vue`, `TerminalPanel.vue` — stay Vue.
+- `TabList/*` — separate stage.
+- `SchemaPane` tree + node types — separate stage.
+- `ResultView` + `VirtualDataTable` — separate stage.
+- `SQLEditor.vue` Monaco wrapper — complex; separate stage.
+
+## 7. Risks & open questions
+
+- **OpenAIButton AI store:** the exact pinia store driving the AI chat panel needs verification. Use `useVueState` to read it. If the AI panel is controlled from a React context we've already introduced, prefer that.
+- **FeatureModal:** currently imported from `@/components/FeatureGuard` (Vue). Check if a React equivalent exists; if not, mount via `<ReactPageMount>` OR port a thin React wrapper in Phase 4.
+- **Keyboard shortcut:** `Cmd/Ctrl+S` binding is currently registered globally via Vue's `useKeyboardShortcut` (or similar). Ensure we don't double-register from React; likely the binding lives in a composable invoked by the parent Vue tree, unchanged.
+- **TerminalPanel execute handler:** the Vue `<EditorAction />` in `TerminalPanel.vue` doesn't pass `@execute`. In React, `onExecute` must be an explicit required prop, so callers pass a no-op. Document this in the component comment.
+- **SharePopoverBody** is already React and mounted elsewhere (in SheetTree via `ReactPageMount` historically, now directly). Phase 4 uses it directly — verify no props-API drift from its last use site.
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 6c83ade0e6..7cf3f9e384 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -2478,9 +2478,7 @@
"exit": "Exit admin mode",
"self": "Admin mode"
},
- "allow-admin-mode-only": "Instance {instance} is accessible in admin mode only.",
"and-n-more-databases": "and {n} more databases",
- "and-submit-an-issue": "and submit an issue",
"batch-export": {
"failed-for-db": "Failed to export data for {db}",
"self": "Batch export",
@@ -2515,7 +2513,6 @@
"copy-selected-results": "Copy selected data by {action} or {button}",
"copy-url": "Copy URL",
"current-connection": "Current connection",
- "ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in {environment}, please submit a Data Change Plan for approval.",
"download-as-file": "Download as {file}",
"duration-day": "{days} day",
"duration-days": "{days} days",
@@ -2624,7 +2621,6 @@
"table-empty-placeholder": "Click Run to execute the query.",
"table-view": "Table view",
"text-format": "Text format",
- "to-enable-admin-mode": "to enable the admin mode",
"unmask-warning": "User will access unmasked data through this query",
"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.json
index 5d5d934eea..1205c1ca9e 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -2478,9 +2478,7 @@
"exit": "Salir del modo administrador",
"self": "Modo administrador"
},
- "allow-admin-mode-only": "La instancia {instance} solo es accesible en modo administrador.",
"and-n-more-databases": "and {n} more databases",
- "and-submit-an-issue": "y enviar un problema",
"batch-export": {
"failed-for-db": "No se pudieron exportar los datos de {db}",
"self": "Exportación por lotes",
@@ -2515,7 +2513,6 @@
"copy-selected-results": "Copiar datos seleccionados por {action} o {button}",
"copy-url": "Copiar URL",
"current-connection": "Conexión actual",
- "ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en {environment}, envíe un Plan de Cambio de Datos para su aprobación.",
"download-as-file": "Descargar como {file}",
"duration-day": "{days} day",
"duration-days": "{days} days",
@@ -2624,7 +2621,6 @@
"table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.",
"table-view": "Table view",
"text-format": "Formato de texto",
- "to-enable-admin-mode": "para habilitar el modo administrador",
"unmask-warning": "El usuario accederá a datos sin enmascarar a través de esta consulta",
"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.json
index b089cf88df..3f7f0f3ebb 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -2478,9 +2478,7 @@
"exit": "管理者モードを終了する",
"self": "管理者モード"
},
- "allow-admin-mode-only": "インスタンス {instance} には管理者モードでのみアクセスできます。",
"and-n-more-databases": "and {n} more databases",
- "and-submit-an-issue": "そしてイシューを提出してください",
"batch-export": {
"failed-for-db": "{db} のデータのエクスポートに失敗しました",
"self": "一括エクスポート",
@@ -2515,7 +2513,6 @@
"copy-selected-results": "選択したデータを{action}または{button}でコピーします",
"copy-url": "URLをコピー",
"current-connection": "現在の接続",
- "ddl-dml-requires-data-change-plan": "{environment} で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。",
"download-as-file": "{file} 形式でダウンロード",
"duration-day": "{days} day",
"duration-days": "{days} days",
@@ -2624,7 +2621,6 @@
"table-empty-placeholder": "「実行」をクリックしてクエリを実行します。",
"table-view": "Table view",
"text-format": "テキスト形式",
- "to-enable-admin-mode": "管理者モードを有効にするには",
"unmask-warning": "ユーザーはこのクエリでマスク解除されたデータにアクセスします",
"upload-file": "ファイルをアップロードする",
"url-copied-to-clipboard": "URLがクリップボードにコピーされました",
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index af1d4c888b..e470811703 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -2478,9 +2478,7 @@
"exit": "Thoát chế độ quản trị",
"self": "Chế độ quản trị"
},
- "allow-admin-mode-only": "Phiên bản {instance} chỉ có thể truy cập ở chế độ quản trị.",
"and-n-more-databases": "and {n} more databases",
- "and-submit-an-issue": "và gửi một vấn đề",
"batch-export": {
"failed-for-db": "Không xuất được dữ liệu cho {db}",
"self": "Xuất hàng loạt",
@@ -2515,7 +2513,6 @@
"copy-selected-results": "Sao chép dữ liệu đã chọn bằng {action} hoặc {button}",
"copy-url": "Sao chép URL",
"current-connection": "Kết nối hiện tại",
- "ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong {environment}, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.",
"download-as-file": "Tải xuống dưới dạng {file}",
"duration-day": "{days} day",
"duration-days": "{days} days",
@@ -2624,7 +2621,6 @@
"table-empty-placeholder": "Nhấp vào Chạy để thực hiện truy vấn.",
"table-view": "Table view",
"text-format": "Định dạng văn bản",
- "to-enable-admin-mode": "để bật chế độ quản trị",
"unmask-warning": "Người dùng sẽ truy cập dữ liệu chưa được che giấu qua truy vấn này",
"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.json
index 3ecbbd29dc..7ec4070e4b 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -2478,9 +2478,7 @@
"exit": "退出管理员模式",
"self": "管理员模式"
},
- "allow-admin-mode-only": "实例{instance}只能通过管理员模式访问。",
"and-n-more-databases": "及其他 {n} 个数据库",
- "and-submit-an-issue": "并提交一个工单",
"batch-export": {
"failed-for-db": "无法导出 {db} 的数据",
"self": "批量导出",
@@ -2515,7 +2513,6 @@
"copy-selected-results": "通过 {action} 或 {button} 来快速复制选定的数据",
"copy-url": "复制 URL",
"current-connection": "当前连接",
- "ddl-dml-requires-data-change-plan": "如需在 {environment} 中执行 DDL/DML 语句,请创建变更计划以获得审批。",
"download-as-file": "下载为 {file} 格式",
"duration-day": "{days} 天",
"duration-days": "{days} 天",
@@ -2624,7 +2621,6 @@
"table-empty-placeholder": "点击 ”运行“ 执行查询",
"table-view": "Table view",
"text-format": "文本格式",
- "to-enable-admin-mode": "来开启管理员模式",
"unmask-warning": "用户将通过此查询访问未脱敏的数据",
"upload-file": "上传文件",
"url-copied-to-clipboard": "URL 已复制到剪贴板",
diff --git a/frontend/src/plugins/ai/components/ProvideAIContext.vue b/frontend/src/plugins/ai/components/ProvideAIContext.vue
index c273f108c9..b95bc2dab8 100644
--- a/frontend/src/plugins/ai/components/ProvideAIContext.vue
+++ b/frontend/src/plugins/ai/components/ProvideAIContext.vue
@@ -4,7 +4,6 @@
<script lang="ts" setup>
import { create } from "@bufbuild/protobuf";
-import Emittery from "emittery";
import { storeToRefs } from "pinia";
import { computed, onMounted, reactive, ref, toRef } from "vue";
import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
@@ -19,7 +18,12 @@ import {
Setting_SettingName,
} from "@/types/proto-es/v1/setting_service_pb";
import { wrapRefAsPromise } from "@/utils";
-import { provideAIContext, useChatByTab, useCurrentChat } from "../logic";
+import {
+ aiContextEvents,
+ provideAIContext,
+ useChatByTab,
+ useCurrentChat,
+} from "../logic";
import { useConversationStore } from "../store";
import type { AIContext, AIContextEvents } from "../types";
@@ -51,7 +55,9 @@ const databaseMetadata = useMetadata(
false /* !skipCache */
);
-const events: AIContextEvents = new Emittery();
+// Reuse the module-level singleton so React consumers (e.g. OpenAIButton.tsx)
+// share this event bus without needing Vue's provide/inject.
+const events: AIContextEvents = aiContextEvents;
const chat = useChatByTab();
const showHistoryDialog = toRef(state, "showHistoryDialog");
const pendingSendChat = ref<{ content: string }>();
diff --git a/frontend/src/plugins/ai/logic/events.ts b/frontend/src/plugins/ai/logic/events.ts
new file mode 100644
index 0000000000..16c488397a
--- /dev/null
+++ b/frontend/src/plugins/ai/logic/events.ts
@@ -0,0 +1,10 @@
+import Emittery from "emittery";
+import type { AIContextEvents } from "../types";
+
+/**
+ * Module-level AI event bus. Imported by both the Vue ProvideAIContext
+ * (which wires it into the Vue-injected context) and React consumers that
+ * can't participate in Vue's provide/inject. Single shared instance so
+ * emit/on from either side reaches the other.
+ */
+export const aiContextEvents: AIContextEvents = new Emittery();
diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.ts
index 053b526698..4c72723616 100644
--- a/frontend/src/plugins/ai/logic/index.ts
+++ b/frontend/src/plugins/ai/logic/index.ts
@@ -1,4 +1,5 @@
export * from "./context";
+export * from "./events";
export * from "./useChatByTab";
export * from "./useDynamicSuggestions";
export * from "./utils";
diff --git a/frontend/src/react/ReactPageMount.vue b/frontend/src/react/ReactPageMount.vue
index 9f2783a2f5..534254b205 100644
--- a/frontend/src/react/ReactPageMount.vue
+++ b/frontend/src/react/ReactPageMount.vue
@@ -1,5 +1,5 @@
<template>
- <div ref="container" class="h-full" />
+ <div ref="container" :class="containerClass" />
</template>
<script lang="ts" setup>
@@ -8,10 +8,20 @@ defineOptions({ inheritAttrs: false });
import { computed, onMounted, onUnmounted, ref, useAttrs, watch } from "vue";
import { useI18n } from "vue-i18n";
-const props = defineProps<{
- page: string;
- pageProps?: Record<string, unknown>;
-}>();
+// `containerClass` defaults to `h-full` so full-height pages (Welcome,
+// HistoryPane, AccessPane, etc.) keep the previous behavior. Callers that
+// mount a natural-height surface (e.g. a toolbar inside a flex-col) should
+// override with something like `w-full` so the wrapper doesn't stretch to
+// fill its flex-column parent.
+const props = withDefaults(
+ defineProps<{
+ page: string;
+ pageProps?: Record<string, unknown>;
+ containerClass?: string;
+ }>(),
+ { containerClass: "h-full" }
+);
+const containerClass = computed(() => props.containerClass);
const attrs = useAttrs();
const { locale } = useI18n();
diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.tsx
index a41068b2e1..9fd7ef3619 100644
--- a/frontend/src/react/components/sql-editor/AdminModeButton.tsx
+++ b/frontend/src/react/components/sql-editor/AdminModeButton.tsx
@@ -9,6 +9,7 @@ import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";
type AdminModeButtonProps = {
readonly size?: "sm" | "default";
readonly hideText?: boolean;
+ readonly onEnter?: () => void;
};
/**
@@ -19,6 +20,7 @@ type AdminModeButtonProps = {
export function AdminModeButton({
size = "default",
hideText = false,
+ onEnter,
}: AdminModeButtonProps) {
const { t } = useTranslation();
const editorStore = useSQLEditorStore();
@@ -36,6 +38,7 @@ export function AdminModeButton({
const handleClick = () => {
tabStore.updateCurrentTab({ mode: "ADMIN" });
+ onEnter?.();
};
return (
diff --git a/frontend/src/react/components/sql-editor/EditorAction.test.tsx b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
new file mode 100644
index 0000000000..77bda7919f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/EditorAction.test.tsx
@@ -0,0 +1,328 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useTranslation: vi.fn(() => ({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ })),
+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),
+ useSQLEditorTabStore: vi.fn(),
+ useSQLEditorStore: vi.fn(),
+ useUIStateStore: vi.fn(),
+ useWorkSheetStore: vi.fn(),
+ useWorkSheetAndTabStore: vi.fn(),
+ useConnectionOfCurrentSQLEditorTab: vi.fn(),
+ isWorksheetWritableV1: vi.fn(() => true),
+ keyboardShortcutStr: vi.fn((s: string) => s),
+ emit: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+ useSQLEditorStore: mocks.useSQLEditorStore,
+ useUIStateStore: mocks.useUIStateStore,
+ useWorkSheetStore: mocks.useWorkSheetStore,
+ useWorkSheetAndTabStore: mocks.useWorkSheetAndTabStore,
+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+}));
+
+vi.mock("@/utils", () => ({
+ isWorksheetWritableV1: mocks.isWorksheetWritableV1,
+ keyboardShortcutStr: mocks.keyboardShortcutStr,
+}));
+
+vi.mock("@/views/sql-editor/events", () => ({
+ sqlEditorEvents: { emit: mocks.emit },
+}));
+
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ disabled,
+ className,
+ "aria-label": ariaLabel,
+ }: {
+ children: React.ReactNode;
+ onClick?: (e: React.MouseEvent) => void;
+ disabled?: boolean;
+ className?: string;
+ "aria-label"?: string;
+ }) => (
+ <button
+ data-testid="button"
+ aria-label={ariaLabel}
+ className={className}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/tooltip", () => ({
+ Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+}));
+
+vi.mock("@/react/components/ui/popover", () => ({
+ Popover: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="popover">{children}</div>
+ ),
+ PopoverTrigger: ({ render }: { render?: React.ReactElement }) => (
+ <div data-testid="popover-trigger">{render}</div>
+ ),
+ PopoverContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="popover-content">{children}</div>
+ ),
+}));
+
+vi.mock("./AdminModeButton", () => ({
+ AdminModeButton: () => <div data-testid="admin-mode-button" />,
+}));
+vi.mock("./ChooserGroup", () => ({
+ ChooserGroup: () => <div data-testid="chooser-group" />,
+}));
+vi.mock("./OpenAIButton", () => ({
+ OpenAIButton: () => <div data-testid="openai-button" />,
+}));
+vi.mock("./QueryContextSettingPopover", () => ({
+ QueryContextSettingPopover: ({ disabled }: { disabled?: boolean }) => (
+ <div
+ data-testid="query-context-setting-popover"
+ data-disabled={String(disabled)}
+ />
+ ),
+}));
+vi.mock("./SharePopoverBody", () => ({
+ SharePopoverBody: () => <div data-testid="share-popover-body" />,
+}));
+
+let EditorAction: typeof import("./EditorAction").EditorAction;
+
+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();
+ },
+ };
+};
+
+type SetupOptions = {
+ mode?: "WORKSHEET" | "ADMIN";
+ isDisconnected?: boolean;
+ statement?: string;
+ status?: "CLEAN" | "DIRTY" | "SAVING";
+ worksheet?: string;
+ engine?: Engine;
+ table?: string;
+};
+
+const setup = (options: SetupOptions = {}) => {
+ const {
+ mode = "WORKSHEET",
+ isDisconnected = false,
+ statement = "SELECT 1",
+ status = "DIRTY",
+ worksheet,
+ engine = Engine.POSTGRES,
+ table,
+ } = options;
+
+ const currentTab = {
+ id: "t1",
+ mode,
+ statement,
+ selectedStatement: "",
+ status,
+ worksheet,
+ connection: { database: "databases/db1", table },
+ editorState: { selection: null },
+ };
+ const updateCurrentTab = vi.fn();
+ const saveIntroStateByKey = vi.fn();
+
+ mocks.useSQLEditorTabStore.mockReturnValue({
+ currentTab,
+ isDisconnected,
+ updateCurrentTab,
+ });
+ mocks.useSQLEditorStore.mockReturnValue({ resultRowsLimit: 500 });
+ mocks.useUIStateStore.mockReturnValue({ saveIntroStateByKey });
+ mocks.useWorkSheetStore.mockReturnValue({
+ getWorksheetByName: vi.fn(() => ({
+ name: worksheet ?? "",
+ database: "databases/db1",
+ })),
+ });
+ mocks.useWorkSheetAndTabStore.mockReturnValue({
+ currentSheet: worksheet ? { name: worksheet, title: "sheet" } : undefined,
+ });
+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({
+ instance: { value: { engine } },
+ });
+
+ mocks.useVueState.mockImplementation((getter) => getter());
+
+ return { currentTab, updateCurrentTab, saveIntroStateByKey };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.useTranslation.mockReturnValue({
+ t: (key: string, fallback?: string) => fallback ?? key,
+ });
+ mocks.isWorksheetWritableV1.mockReturnValue(true);
+ ({ EditorAction } = await import("./EditorAction"));
+});
+
+describe("EditorAction", () => {
+ test("1. Run button fires onExecute with current statement + connection", () => {
+ setup();
+ const onExecute = vi.fn();
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={onExecute} />
+ );
+ render();
+
+ const runButton = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.textContent?.includes("limit")) as
+ | HTMLButtonElement
+ | undefined;
+ expect(runButton).not.toBeUndefined();
+ expect(runButton?.disabled).toBe(false);
+
+ act(() => {
+ runButton?.click();
+ });
+
+ expect(onExecute).toHaveBeenCalledWith(
+ expect.objectContaining({
+ statement: "SELECT 1",
+ engine: Engine.POSTGRES,
+ explain: false,
+ })
+ );
+
+ unmount();
+ });
+
+ test("2. Run button is disabled when disconnected OR statement empty", () => {
+ setup({ statement: "" });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={vi.fn()} />
+ );
+ render();
+
+ const runButton = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.textContent?.includes("limit")) as
+ | HTMLButtonElement
+ | undefined;
+ expect(runButton?.disabled).toBe(true);
+
+ unmount();
+ });
+
+ test("3. In ADMIN mode, renders Exit-Admin button instead of Run", () => {
+ const { updateCurrentTab } = setup({ mode: "ADMIN" });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={vi.fn()} />
+ );
+ render();
+
+ const exitBtn = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.textContent?.includes("sql-editor.admin-mode.exit")) as
+ | HTMLButtonElement
+ | undefined;
+ expect(exitBtn).not.toBeUndefined();
+
+ // No Run button
+ const runButton = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.textContent?.includes("limit"));
+ expect(runButton).toBeUndefined();
+
+ act(() => {
+ exitBtn?.click();
+ });
+ expect(updateCurrentTab).toHaveBeenCalledWith({ mode: "WORKSHEET" });
+
+ unmount();
+ });
+
+ test("4. Save button disabled when status=CLEAN; emits save-sheet when dirty", () => {
+ const { currentTab } = setup({ status: "DIRTY" });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={vi.fn()} />
+ );
+ render();
+
+ const saveBtn = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.getAttribute("aria-label") === "common.save") as
+ | HTMLButtonElement
+ | undefined;
+ expect(saveBtn).not.toBeUndefined();
+ expect(saveBtn?.disabled).toBe(false);
+
+ act(() => {
+ saveBtn?.click();
+ });
+ expect(mocks.emit).toHaveBeenCalledWith("save-sheet", { tab: currentTab });
+
+ unmount();
+ });
+
+ test("5. Share button disabled when disconnected or empty statement", () => {
+ setup({ isDisconnected: true });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <EditorAction onExecute={vi.fn()} />
+ );
+ render();
+
+ const shareBtn = Array.from(
+ container.querySelectorAll("[data-testid='button']")
+ ).find((el) => el.getAttribute("aria-label") === "common.share") as
+ | HTMLButtonElement
+ | undefined;
+ expect(shareBtn).not.toBeUndefined();
+ expect(shareBtn?.disabled).toBe(true);
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsx
new file mode 100644
index 0000000000..10563681cc
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx
@@ -0,0 +1,258 @@
+import { ChevronLeft, Play, Save, Share2 } from "lucide-react";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/react/components/ui/button";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/react/components/ui/popover";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useUIStateStore,
+ useWorkSheetAndTabStore,
+ useWorkSheetStore,
+} from "@/store";
+import type { SQLEditorQueryParams } from "@/types";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import { 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";
+
+type Props = {
+ readonly onExecute?: (params: SQLEditorQueryParams) => void;
+};
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorCommon/EditorAction.vue.
+ * Top toolbar in the SQL editor: Run / QueryContextSettingPopover /
+ * AdminModeButton / Save / Share / ChooserGroup / OpenAIButton.
+ *
+ * `onExecute` is optional because `TerminalPanel.vue` mounts the toolbar in
+ * ADMIN mode where the Run button is not rendered.
+ */
+export function EditorAction({ onExecute }: Props) {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const editorStore = useSQLEditorStore();
+ const uiStateStore = useUIStateStore();
+ const worksheetStore = useWorkSheetStore();
+ const sheetAndTabStore = useWorkSheetAndTabStore();
+ const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();
+
+ const [shareOpen, setShareOpen] = useState(false);
+
+ const currentTab = useVueState(() => tabStore.currentTab);
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+ const instance = useVueState(() => instanceRef.value);
+ const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);
+ const currentWorksheet = useVueState(() => sheetAndTabStore.currentSheet);
+
+ const mode = currentTab?.mode;
+ const isAdminMode = mode === "ADMIN";
+ const showSheetsFeature = mode === "WORKSHEET";
+ const isEmptyStatement = !currentTab || currentTab.statement === "";
+
+ const queryTip =
+ instance.engine === Engine.COSMOSDB && !currentTab?.connection.table
+ ? t("database.table.select-tip")
+ : "";
+
+ const allowQuery = (() => {
+ if (isDisconnected) return false;
+ if (isEmptyStatement) return false;
+ if (instance.engine === Engine.COSMOSDB) {
+ return !!currentTab?.connection.table;
+ }
+ return true;
+ })();
+
+ const canWriteSheet = (() => {
+ if (!currentTab?.worksheet) return false;
+ const sheet = worksheetStore.getWorksheetByName(currentTab.worksheet);
+ return sheet ? isWorksheetWritableV1(sheet) : false;
+ })();
+
+ const allowSave = (() => {
+ if (!showSheetsFeature || !currentTab) return false;
+ if (currentTab.worksheet) {
+ if (!canWriteSheet) return false;
+ const sheet = worksheetStore.getWorksheetByName(currentTab.worksheet);
+ if (sheet && sheet.database !== currentTab.connection.database) {
+ return true;
+ }
+ }
+ // Only disable when status is CLEAN (nothing to save).
+ // SAVING is allowed — manual save will abort auto-save and proceed.
+ return currentTab.status !== "CLEAN";
+ })();
+
+ const allowShare = (() => {
+ if (!currentTab) return false;
+ if (currentTab.status !== "CLEAN") return false;
+ if (isEmptyStatement || isDisconnected) return false;
+ if (currentTab.worksheet && !canWriteSheet) return false;
+ return true;
+ })();
+
+ const showQueryContextSettingPopover =
+ !!currentTab && !!instance && !isAdminMode;
+
+ const handleRunQuery = () => {
+ if (!currentTab || !onExecute) return;
+ const statement = currentTab.selectedStatement || currentTab.statement;
+ onExecute({
+ statement,
+ connection: { ...currentTab.connection },
+ engine: instance.engine,
+ explain: false,
+ selection: currentTab.editorState.selection,
+ });
+ uiStateStore.saveIntroStateByKey({
+ key: "data.query",
+ newState: true,
+ });
+ };
+
+ const exitAdminMode = () => {
+ // Inlined to avoid pulling `@/types` (monaco-editor transitive) into the
+ // React bundle. Matches `DEFAULT_SQL_EDITOR_TAB_MODE` in `@/types/sqlEditor/tab`.
+ tabStore.updateCurrentTab({ mode: "WORKSHEET" });
+ };
+
+ const handleClickSave = () => {
+ if (!currentTab) return;
+ void sqlEditorEvents.emit("save-sheet", { tab: currentTab });
+ };
+
+ return (
+ <div className="w-full flex flex-wrap gap-y-2 justify-between sm:items-center p-2 border-b bg-background">
+ <div className="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center">
+ {isAdminMode && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-1.5 gap-1 border-dashed"
+ onClick={(e) => {
+ e.stopPropagation();
+ exitAdminMode();
+ }}
+ >
+ <ChevronLeft className="size-4" />
+ <span>{t("sql-editor.admin-mode.exit")}</span>
+ </Button>
+ )}
+
+ {!isAdminMode && (
+ <div className="inline-flex">
+ {queryTip ? (
+ <Tooltip content={queryTip} side="bottom">
+ <Button
+ variant="default"
+ size="sm"
+ className={cn("h-7 px-1.5 gap-1 rounded-r-none")}
+ disabled={!allowQuery}
+ onClick={handleRunQuery}
+ >
+ <Play className="size-4 fill-current" />
+ <span className="inline-flex items-center">
+ (limit&nbsp;{resultRowsLimit})
+ </span>
+ </Button>
+ </Tooltip>
+ ) : (
+ <Button
+ variant="default"
+ size="sm"
+ className={cn("h-7 px-1.5 gap-1 rounded-r-none")}
+ disabled={!allowQuery}
+ onClick={handleRunQuery}
+ >
+ <Play className="size-4 fill-current" />
+ <span className="inline-flex items-center">
+ (limit&nbsp;{resultRowsLimit})
+ </span>
+ </Button>
+ )}
+ <QueryContextSettingPopover
+ disabled={!showQueryContextSettingPopover || !allowQuery}
+ />
+ </div>
+ )}
+
+ <AdminModeButton size="sm" hideText />
+
+ {showSheetsFeature && (
+ <>
+ <Tooltip
+ content={
+ <span className="inline-flex items-center gap-1">
+ <span>{t("common.save")}</span>
+ <span>({keyboardShortcutStr("cmd_or_ctrl+S")})</span>
+ </span>
+ }
+ side="bottom"
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-1.5"
+ disabled={!allowSave}
+ onClick={handleClickSave}
+ aria-label={t("common.save")}
+ >
+ <Save className="size-4" />
+ </Button>
+ </Tooltip>
+
+ <Popover
+ open={shareOpen}
+ onOpenChange={(next) => {
+ if (!allowShare && next) return;
+ setShareOpen(next);
+ }}
+ >
+ <Tooltip content={t("common.share")} side="bottom">
+ <PopoverTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 px-1.5"
+ disabled={!allowShare}
+ aria-label={t("common.share")}
+ >
+ <Share2 className="size-4" />
+ </Button>
+ }
+ />
+ </Tooltip>
+ <PopoverContent align="end" sideOffset={4}>
+ <SharePopoverBody
+ worksheet={currentWorksheet}
+ onUpdated={() => setShareOpen(false)}
+ />
+ </PopoverContent>
+ </Popover>
+ </>
+ )}
+ </div>
+ <div className="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center">
+ <ChooserGroup />
+ <OpenAIButton
+ size="sm"
+ statement={currentTab?.selectedStatement || currentTab?.statement}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
new file mode 100644
index 0000000000..36d34a8969
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx
@@ -0,0 +1,134 @@
+import { Trans, useTranslation } from "react-i18next";
+import { v4 as uuidv4 } from "uuid";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
+import { Alert } from "@/react/components/ui/alert";
+import { Button } from "@/react/components/ui/button";
+import { useVueState } from "@/react/hooks/useVueState";
+import { router } from "@/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
+import {
+ pushNotification,
+ useDatabaseV1Store,
+ useProjectV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useStorageStore,
+} from "@/store";
+import { unknownProject } from "@/types";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import {
+ extractDatabaseResourceName,
+ extractProjectResourceName,
+ getDatabaseEnvironment,
+} from "@/utils";
+import { AdminModeButton } from "./AdminModeButton";
+
+type Props = {
+ readonly database?: Database;
+ readonly onClose: () => void;
+};
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue.
+ * Body of the "DDL/DML requires a plan" confirmation surface.
+ */
+export function ExecuteHint({ database, onClose }: Props) {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const editorStore = useSQLEditorStore();
+ const databaseStore = useDatabaseV1Store();
+ const projectStore = useProjectV1Store();
+ const storageStore = useStorageStore();
+
+ const allowAdmin = useVueState(() => editorStore.allowAdmin);
+
+ const environment = database ? getDatabaseEnvironment(database) : undefined;
+
+ const gotoCreateIssue = async () => {
+ const connectedDatabase = tabStore.currentTab?.connection.database ?? "";
+ if (!connectedDatabase) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("sql-editor.no-database-selected"),
+ });
+ return;
+ }
+
+ onClose();
+
+ const db = await databaseStore.getOrFetchDatabaseByName(connectedDatabase);
+ // Fall back to `unknownProject()` (enforceIssueTitle=true) if the project
+ // fetch rejects so the plan page opens with a blank title.
+ const project = await projectStore
+ .getOrFetchProjectByName(db.project)
+ .catch(() => unknownProject());
+
+ const tab = tabStore.currentTab;
+ const statement = tab?.selectedStatement || tab?.statement || "";
+ const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;
+ storageStore.put(sqlStorageKey, statement);
+ const { databaseName } = extractDatabaseResourceName(db.name);
+
+ const query: Record<string, string> = {
+ template: "bb.plan.change-database",
+ databaseList: db.name,
+ sqlStorageKey,
+ };
+ applyPlanTitleToQuery(
+ query,
+ project,
+ () => `[${databaseName}] ${t("issue.title.change-from-sql-editor")}`
+ );
+
+ const route = router.resolve({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(db.project),
+ planId: "create",
+ specId: "placeholder",
+ },
+ query,
+ });
+ window.open(route.fullPath, "_blank");
+ };
+
+ return (
+ <div className="w-[28rem]">
+ <Alert variant="info">
+ <section className="flex flex-col gap-y-2">
+ <p>{t("sql-editor.only-select-allowed")}</p>
+ {database && environment && (
+ <p>
+ <Trans
+ t={t}
+ i18nKey="sql-editor.ddl-dml-requires-data-change-plan"
+ components={{
+ environment: (
+ <span className="font-medium">{environment.title}</span>
+ ),
+ }}
+ />
+ </p>
+ )}
+ </section>
+ </Alert>
+
+ <div className="mt-4 flex justify-between">
+ {allowAdmin && (
+ <div className="flex justify-start items-center gap-x-2">
+ <AdminModeButton onEnter={onClose} />
+ </div>
+ )}
+ <div className="flex flex-1 justify-end items-center gap-x-2">
+ <Button variant="outline" onClick={onClose}>
+ {t("common.close")}
+ </Button>
+ <Button onClick={() => void gotoCreateIssue()}>
+ {t("plan.create-plan")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx
new file mode 100644
index 0000000000..f95639d8aa
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx
@@ -0,0 +1,163 @@
+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 })),
+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),
+ useSQLEditorStore: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ useSQLEditorStore: mocks.useSQLEditorStore,
+}));
+
+vi.mock("@/react/components/ui/dialog", () => ({
+ Dialog: ({
+ children,
+ open,
+ onOpenChange,
+ }: {
+ children: React.ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
+ <div
+ data-testid="dialog"
+ data-open={String(open ?? false)}
+ data-close-handler={onOpenChange ? "true" : "false"}
+ onClick={() => onOpenChange?.(false)}
+ >
+ {open ? children : null}
+ </div>
+ ),
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dialog-content">{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <h2 data-testid="dialog-title">{children}</h2>
+ ),
+}));
+
+// ExecuteHint pulls the router and many stores; mock it to a placeholder so
+// the modal's open/close behavior can be verified independently.
+vi.mock("./ExecuteHint", () => ({
+ ExecuteHint: ({
+ database,
+ onClose,
+ }: {
+ database?: { name: string };
+ onClose: () => void;
+ }) => (
+ <div
+ data-testid="execute-hint"
+ data-database={database?.name ?? ""}
+ onClick={onClose}
+ />
+ ),
+}));
+
+let ExecutingHintModal: typeof import("./ExecutingHintModal").ExecutingHintModal;
+
+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();
+ },
+ };
+};
+
+const setup = (
+ options: { show?: boolean; database?: { name: string } } = {}
+) => {
+ const store = {
+ isShowExecutingHint: options.show ?? false,
+ executingHintDatabase: options.database,
+ };
+ mocks.useSQLEditorStore.mockReturnValue(store);
+ mocks.useVueState.mockImplementation((getter) => getter());
+ return store;
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
+ ({ ExecutingHintModal } = await import("./ExecutingHintModal"));
+});
+
+describe("ExecutingHintModal", () => {
+ test("dialog is closed when isShowExecutingHint is false", () => {
+ setup({ show: false });
+ const { container, render, unmount } = renderIntoContainer(
+ <ExecutingHintModal />
+ );
+ render();
+
+ const dialog = container.querySelector("[data-testid='dialog']");
+ expect(dialog?.getAttribute("data-open")).toBe("false");
+ expect(container.querySelector("[data-testid='execute-hint']")).toBeNull();
+
+ unmount();
+ });
+
+ test("dialog is open + ExecuteHint rendered when isShowExecutingHint is true", () => {
+ setup({ show: true, database: { name: "databases/db1" } });
+ const { container, render, unmount } = renderIntoContainer(
+ <ExecutingHintModal />
+ );
+ render();
+
+ const dialog = container.querySelector("[data-testid='dialog']");
+ expect(dialog?.getAttribute("data-open")).toBe("true");
+
+ const hint = container.querySelector("[data-testid='execute-hint']");
+ expect(hint).not.toBeNull();
+ expect(hint?.getAttribute("data-database")).toBe("databases/db1");
+
+ unmount();
+ });
+
+ test("closing the dialog flips isShowExecutingHint to false", () => {
+ const store = setup({ show: true });
+ const { container, render, unmount } = renderIntoContainer(
+ <ExecutingHintModal />
+ );
+ render();
+
+ // Simulate close by clicking the ExecuteHint stub (invokes onClose).
+ act(() => {
+ container
+ .querySelector("[data-testid='execute-hint']")
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+
+ expect(store.isShowExecutingHint).toBe(false);
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx
new file mode 100644
index 0000000000..40c0a51015
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx
@@ -0,0 +1,37 @@
+import { useTranslation } from "react-i18next";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useSQLEditorStore } from "@/store";
+import { ExecuteHint } from "./ExecuteHint";
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue.
+ * Shows the ExecuteHint body inside a Dialog when the user attempts a DDL/DML
+ * against a database that requires a change plan.
+ */
+export function ExecutingHintModal() {
+ const { t } = useTranslation();
+ const editorStore = useSQLEditorStore();
+
+ const show = useVueState(() => editorStore.isShowExecutingHint);
+ const database = useVueState(() => editorStore.executingHintDatabase);
+
+ const handleClose = () => {
+ editorStore.isShowExecutingHint = false;
+ };
+
+ return (
+ <Dialog open={show} onOpenChange={(next) => !next && handleClose()}>
+ <DialogContent className="w-auto max-w-none p-6">
+ <DialogTitle>{t("common.action-required")}</DialogTitle>
+ <div className="mt-3">
+ <ExecuteHint database={database} onClose={handleClose} />
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
new file mode 100644
index 0000000000..fbd3683f09
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx
@@ -0,0 +1,310 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),
+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),
+ useSQLEditorTabStore: vi.fn(),
+ useSQLEditorUIStore: vi.fn(),
+ useSettingV1Store: vi.fn(),
+ useConnectionOfCurrentSQLEditorTab: vi.fn(),
+ hasWorkspacePermissionV2: vi.fn(() => true),
+ nextAnimationFrame: vi.fn(() => Promise.resolve()),
+ emit: vi.fn(),
+ explainCode: vi.fn((s: string) => `EXPLAIN:${s}`),
+ findProblems: vi.fn((s: string) => `FIND:${s}`),
+ routerPush: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ useSQLEditorTabStore: mocks.useSQLEditorTabStore,
+ useSQLEditorUIStore: mocks.useSQLEditorUIStore,
+ useSettingV1Store: mocks.useSettingV1Store,
+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+}));
+
+vi.mock("@/utils", () => ({
+ hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,
+ nextAnimationFrame: mocks.nextAnimationFrame,
+}));
+
+vi.mock("@/plugins/ai/logic", () => ({
+ aiContextEvents: { emit: mocks.emit },
+}));
+
+vi.mock("@/plugins/ai/logic/prompt", () => ({
+ explainCode: mocks.explainCode,
+ findProblems: mocks.findProblems,
+}));
+
+vi.mock("@/router", () => ({
+ router: { push: mocks.routerPush },
+}));
+
+vi.mock("@/router/dashboard/workspaceSetting", () => ({
+ SETTING_ROUTE_WORKSPACE_GENERAL: "settings.workspace.general",
+}));
+
+// Minimal primitive stubs.
+vi.mock("@/react/components/ui/button", () => ({
+ Button: ({
+ children,
+ onClick,
+ disabled,
+ "aria-disabled": ariaDisabled,
+ "aria-label": ariaLabel,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ disabled?: boolean;
+ "aria-disabled"?: boolean;
+ "aria-label"?: string;
+ }) => (
+ <button
+ data-testid="button"
+ aria-label={ariaLabel}
+ disabled={disabled}
+ aria-disabled={ariaDisabled}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+vi.mock("@/react/components/ui/popover", () => ({
+ Popover: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="popover">{children}</div>
+ ),
+ PopoverTrigger: ({ render }: { render?: React.ReactElement }) => (
+ <div data-testid="popover-trigger">{render}</div>
+ ),
+ PopoverContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="popover-content">{children}</div>
+ ),
+}));
+
+vi.mock("@/react/components/ui/dropdown-menu", () => ({
+ DropdownMenu: ({
+ children,
+ open,
+ }: {
+ children: React.ReactNode;
+ open?: boolean;
+ }) => (
+ <div data-testid="dropdown-menu" data-open={String(open ?? false)}>
+ {children}
+ </div>
+ ),
+ DropdownMenuTrigger: ({ render }: { render?: React.ReactElement }) => (
+ <div data-testid="dropdown-menu-trigger">{render}</div>
+ ),
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="dropdown-menu-content">{children}</div>
+ ),
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ disabled,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ disabled?: boolean;
+ }) => (
+ <button
+ data-testid="dropdown-menu-item"
+ disabled={disabled}
+ onClick={onClick}
+ >
+ {children}
+ </button>
+ ),
+}));
+
+let OpenAIButton: typeof import("./OpenAIButton").OpenAIButton;
+
+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();
+ },
+ };
+};
+
+// Default state: connected, worksheet mode, AI enabled, showAIPanel=false
+type VueStateValues = {
+ isDisconnected: boolean;
+ currentMode: string | undefined;
+ showAIPanel: boolean;
+ instance: { engine: Engine };
+ openAIEnabled: boolean;
+};
+
+const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {
+ const values: VueStateValues = {
+ isDisconnected: false,
+ currentMode: "WORKSHEET",
+ showAIPanel: false,
+ instance: { engine: Engine.POSTGRES },
+ openAIEnabled: true,
+ ...overrides,
+ };
+
+ const uiStore = { showAIPanel: values.showAIPanel };
+ const tabStore = {
+ isDisconnected: values.isDisconnected,
+ currentTab: { mode: values.currentMode },
+ };
+ const settingStore = {
+ getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),
+ getSettingByName: vi.fn(),
+ };
+
+ mocks.useSQLEditorTabStore.mockReturnValue(tabStore);
+ mocks.useSQLEditorUIStore.mockReturnValue(uiStore);
+ mocks.useSettingV1Store.mockReturnValue(settingStore);
+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({
+ instance: { value: values.instance },
+ });
+
+ // Order of useVueState calls: isDisconnected, currentMode, showAIPanel, instance, openAIEnabled
+ const ordered = [
+ values.isDisconnected,
+ values.currentMode,
+ values.showAIPanel,
+ values.instance,
+ values.openAIEnabled,
+ ];
+ let idx = 0;
+ mocks.useVueState.mockImplementation(() => ordered[idx++]);
+
+ return { uiStore, tabStore, settingStore };
+};
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
+ mocks.hasWorkspacePermissionV2.mockReturnValue(true);
+ ({ OpenAIButton } = await import("./OpenAIButton"));
+});
+
+describe("OpenAIButton", () => {
+ test("renders nothing when disconnected", () => {
+ setupDefaultMocks({ isDisconnected: true });
+ const { container, render, unmount } = renderIntoContainer(
+ <OpenAIButton />
+ );
+ render();
+
+ expect(container.querySelector("[data-testid='button']")).toBeNull();
+
+ unmount();
+ });
+
+ test("renders nothing when not in WORKSHEET mode", () => {
+ setupDefaultMocks({ currentMode: "ADMIN" });
+ const { container, render, unmount } = renderIntoContainer(
+ <OpenAIButton />
+ );
+ render();
+
+ expect(container.querySelector("[data-testid='button']")).toBeNull();
+
+ unmount();
+ });
+
+ test("shows disabled button + configure popover when AI not configured", () => {
+ setupDefaultMocks({ openAIEnabled: false });
+ const { container, render, unmount } = renderIntoContainer(
+ <OpenAIButton />
+ );
+ render();
+
+ const button = container.querySelector(
+ "[data-testid='button']"
+ ) as HTMLButtonElement | null;
+ expect(button).not.toBeNull();
+ expect(button?.getAttribute("aria-disabled")).toBeTruthy();
+
+ // Popover body includes the not-configured key
+ expect(container.textContent).toContain("plugin.ai.not-configured.self");
+
+ unmount();
+ });
+
+ test("click toggles showAIPanel when enabled", () => {
+ const { uiStore } = setupDefaultMocks();
+ const { container, render, unmount } = renderIntoContainer(
+ <OpenAIButton />
+ );
+ render();
+
+ const button = container.querySelector(
+ "[data-testid='button']"
+ ) as HTMLButtonElement | null;
+ expect(button).not.toBeNull();
+
+ act(() => {
+ button?.click();
+ });
+
+ expect(uiStore.showAIPanel).toBe(true);
+
+ unmount();
+ });
+
+ test("selecting explain-code action emits send-chat with prompt", async () => {
+ const { uiStore } = setupDefaultMocks();
+ const { container, render, unmount } = renderIntoContainer(
+ <OpenAIButton statement="SELECT 1" />
+ );
+ render();
+
+ const items = container.querySelectorAll(
+ "[data-testid='dropdown-menu-item']"
+ );
+ // First item = explain-code
+ const explainItem = items[0] as HTMLButtonElement | undefined;
+ expect(explainItem?.textContent).toBe("plugin.ai.actions.explain-code");
+
+ await act(async () => {
+ explainItem?.click();
+ });
+
+ expect(uiStore.showAIPanel).toBe(true);
+ expect(mocks.explainCode).toHaveBeenCalledWith("SELECT 1", Engine.POSTGRES);
+ expect(mocks.emit).toHaveBeenCalledWith("send-chat", {
+ content: "EXPLAIN:SELECT 1",
+ newChat: true,
+ });
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
new file mode 100644
index 0000000000..6e413d9a9c
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx
@@ -0,0 +1,275 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { aiContextEvents } from "@/plugins/ai/logic";
+import * as promptUtils from "@/plugins/ai/logic/prompt";
+import type { ChatAction } from "@/plugins/ai/types";
+import { Button } from "@/react/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/react/components/ui/dropdown-menu";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/react/components/ui/popover";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { router } from "@/router";
+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSettingV1Store,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+} from "@/store";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";
+
+type Size = "sm" | "default";
+
+type Props = {
+ /**
+ * Restricts the popselect to the provided subset of actions. When omitted
+ * all built-in actions (explain-code, find-problems) render.
+ */
+ readonly actions?: ChatAction[];
+ /** The SQL statement the assistant should reason about. */
+ readonly statement?: string;
+ readonly size?: Size;
+};
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorCommon/OpenAIButton/*.vue.
+ * Shows an AI-assistant toggle when the editor is connected + in worksheet
+ * mode. Clicking the button toggles the AI panel; the attached dropdown
+ * offers shortcuts that seed the chat with a prompt.
+ */
+export function OpenAIButton({ actions, statement, size = "default" }: Props) {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const settingV1Store = useSettingV1Store();
+ const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();
+
+ // Make sure the AI setting is resolved before we gate the enabled state.
+ useEffect(() => {
+ void settingV1Store.getOrFetchSettingByName(
+ Setting_SettingName.AI,
+ true /* silent */
+ );
+ }, [settingV1Store]);
+
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+ const currentMode = useVueState(() => tabStore.currentTab?.mode);
+ const showAIPanel = useVueState(() => uiStore.showAIPanel);
+ const instance = useVueState(() => instanceRef.value);
+ const openAIEnabled = useVueState(() => {
+ const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);
+ return setting?.value?.value?.case === "ai"
+ ? setting.value.value.value.enabled
+ : false;
+ });
+
+ const [menuOpen, setMenuOpen] = useState(false);
+
+ if (isDisconnected || currentMode !== "WORKSHEET") {
+ return null;
+ }
+
+ const buttonVariant = showAIPanel ? "default" : "outline";
+
+ const icon = (
+ <svg
+ viewBox="0 0 320 320"
+ fill="currentColor"
+ stroke="none"
+ className="size-4"
+ aria-hidden="true"
+ >
+ <path d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z" />
+ </svg>
+ );
+
+ const buttonClass = cn(
+ "h-7 px-1.5 gap-1",
+ showAIPanel && "bg-accent/10 text-accent hover:bg-accent/20"
+ );
+
+ const handleToggle = () => {
+ uiStore.showAIPanel = !uiStore.showAIPanel;
+ };
+
+ // ---- Disabled state: AI feature not configured ---------------------------
+ if (!openAIEnabled) {
+ return (
+ <AINotConfiguredButton size={size} icon={icon} className={buttonClass} />
+ );
+ }
+
+ // ---- Enabled state -------------------------------------------------------
+ const allActions: { value: ChatAction; label: string }[] = [
+ { value: "explain-code", label: t("plugin.ai.actions.explain-code") },
+ { value: "find-problems", label: t("plugin.ai.actions.find-problems") },
+ ];
+ const visibleActions = actions
+ ? allActions.filter((o) => actions.includes(o.value))
+ : allActions;
+ const hasActions = visibleActions.length > 0;
+
+ const handleSelect = async (action: ChatAction) => {
+ setMenuOpen(false);
+ const newChat = !showAIPanel;
+ uiStore.showAIPanel = true;
+
+ if (!statement) return;
+ await nextAnimationFrame();
+ if (action === "explain-code") {
+ void aiContextEvents.emit("send-chat", {
+ content: promptUtils.explainCode(statement, instance.engine),
+ newChat,
+ });
+ } else if (action === "find-problems") {
+ void aiContextEvents.emit("send-chat", {
+ content: promptUtils.findProblems(statement, instance.engine),
+ newChat,
+ });
+ }
+ };
+
+ const renderButton = (onClick?: () => void) => (
+ <Button
+ variant={buttonVariant}
+ size={size}
+ className={buttonClass}
+ aria-label={t("plugin.ai.ai-assistant")}
+ onClick={onClick}
+ >
+ {icon}
+ </Button>
+ );
+
+ if (!hasActions) {
+ return renderButton(handleToggle);
+ }
+
+ return (
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
+ <DropdownMenuTrigger
+ render={renderButton(handleToggle)}
+ onContextMenu={(e) => {
+ // Right-click opens the action menu; left-click is handled by the
+ // button's onClick and toggles the AI panel.
+ e.preventDefault();
+ setMenuOpen(true);
+ }}
+ />
+ <DropdownMenuContent align="end" sideOffset={4}>
+ <div className="px-3 py-1.5 text-xs font-semibold text-control-light">
+ {t("plugin.ai.ai-assistant")}
+ </div>
+ {visibleActions.map((opt) => (
+ <DropdownMenuItem
+ key={opt.value}
+ disabled={!statement}
+ onClick={() => {
+ void handleSelect(opt.value);
+ }}
+ >
+ {opt.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/** Hover-triggered popover shown when AI is not configured. */
+function AINotConfiguredButton({
+ size,
+ icon,
+ className,
+}: {
+ size: "sm" | "default";
+ icon: React.ReactNode;
+ className: string;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const closeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const allowConfigure = hasWorkspacePermissionV2("bb.settings.set");
+
+ const handleEnter = useCallback(() => {
+ if (closeTimerRef.current !== null) clearTimeout(closeTimerRef.current);
+ setOpen(true);
+ }, []);
+
+ const handleLeave = useCallback(() => {
+ closeTimerRef.current = setTimeout(() => setOpen(false), 150);
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (closeTimerRef.current !== null) clearTimeout(closeTimerRef.current);
+ },
+ []
+ );
+
+ return (
+ <Popover open={open}>
+ <PopoverTrigger
+ render={
+ <Button
+ variant="outline"
+ size={size}
+ aria-disabled
+ className={cn(className, "opacity-50 cursor-default")}
+ aria-label={t("plugin.ai.ai-assistant")}
+ onMouseEnter={handleEnter}
+ onMouseLeave={handleLeave}
+ >
+ {icon}
+ </Button>
+ }
+ />
+ <PopoverContent
+ align="end"
+ className="max-w-[20rem]"
+ onMouseEnter={handleEnter}
+ onMouseLeave={handleLeave}
+ >
+ <div className="flex flex-col">
+ <div className="border-b pb-1 font-semibold">
+ {t("plugin.ai.ai-assistant")}
+ </div>
+ <div className="pt-2 flex flex-col text-control-light">
+ <p>
+ {t("plugin.ai.not-configured.self")}{" "}
+ {allowConfigure ? (
+ <Button
+ variant="link"
+ size="sm"
+ tabIndex={-1}
+ className="h-auto p-0 text-accent"
+ onClick={() => {
+ setOpen(false);
+ void router.push({
+ name: SETTING_ROUTE_WORKSPACE_GENERAL,
+ hash: "#ai-assistant",
+ });
+ }}
+ >
+ {t("plugin.ai.not-configured.go-to-configure")}
+ </Button>
+ ) : (
+ t("plugin.ai.not-configured.contact-admin-to-configure")
+ )}
+ </p>
+ </div>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx
new file mode 100644
index 0000000000..4bb96726a6
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx
@@ -0,0 +1,130 @@
+import type { ReactElement, ReactNode } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ useTranslation: vi.fn(() => ({ t: (key: string) => key })),
+ useVueState: vi.fn<(getter: () => unknown) => unknown>(),
+ useConnectionOfCurrentSQLEditorTab: vi.fn(),
+ Trans: vi.fn(),
+}));
+
+vi.mock("react-i18next", () => ({
+ useTranslation: mocks.useTranslation,
+ Trans: ({
+ i18nKey,
+ components,
+ }: {
+ i18nKey: string;
+ components?: Record<string, ReactNode>;
+ }) => (
+ <span data-testid="trans" data-key={i18nKey}>
+ {components?.instance ?? null}
+ </span>
+ ),
+}));
+
+vi.mock("@/react/hooks/useVueState", () => ({
+ useVueState: mocks.useVueState,
+}));
+
+vi.mock("@/store", () => ({
+ useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,
+ // Transitive imports from AdminModeButton — provide stubs.
+ useSQLEditorStore: vi.fn(() => ({ allowAdmin: false })),
+ useSQLEditorTabStore: vi.fn(() => ({
+ currentTab: undefined,
+ isDisconnected: true,
+ updateCurrentTab: vi.fn(),
+ })),
+}));
+
+vi.mock("@/components/InstanceForm/constants", () => ({
+ EngineIconPath: {
+ [Engine.POSTGRES]: "/icons/postgres.svg",
+ } as Record<string, string>,
+}));
+
+// AdminModeButton is covered by its own tests; stub it here so we don't pull
+// in the full tree of its deps.
+vi.mock("./AdminModeButton", () => ({
+ AdminModeButton: () => <button data-testid="admin-mode-button" />,
+}));
+
+let ReadonlyModeNotSupported: typeof import("./ReadonlyModeNotSupported").ReadonlyModeNotSupported;
+
+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.useVueState.mockImplementation((getter) => getter());
+ mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({
+ instance: {
+ value: {
+ name: "instances/pg1",
+ title: "Production PG",
+ engine: Engine.POSTGRES,
+ },
+ },
+ });
+ ({ ReadonlyModeNotSupported } = await import("./ReadonlyModeNotSupported"));
+});
+
+describe("ReadonlyModeNotSupported", () => {
+ test("renders the missing-permission heading + instance display + admin-mode button", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <ReadonlyModeNotSupported />
+ );
+ render();
+
+ // i18n keys surface as their key text via the stubbed t()
+ expect(container.textContent).toContain(
+ "common.missing-required-permission"
+ );
+
+ // Trans component passed the i18n key
+ const trans = container.querySelector("[data-testid='trans']");
+ expect(trans?.getAttribute("data-key")).toBe(
+ "sql-editor.allow-admin-mode-only"
+ );
+
+ // Instance title renders inside the trans slot
+ expect(container.textContent).toContain("Production PG");
+
+ // Engine icon renders
+ const img = container.querySelector("img");
+ expect(img?.getAttribute("src")).toBe("/icons/postgres.svg");
+
+ // AdminModeButton mounted
+ expect(
+ container.querySelector("[data-testid='admin-mode-button']")
+ ).not.toBeNull();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx
new file mode 100644
index 0000000000..5180f6a688
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx
@@ -0,0 +1,49 @@
+import { ShieldAlert } from "lucide-react";
+import { Trans, useTranslation } from "react-i18next";
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useConnectionOfCurrentSQLEditorTab } from "@/store";
+import { AdminModeButton } from "./AdminModeButton";
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorPanel/ReadonlyModeNotSupported.vue.
+ * Shown when the current tab targets an instance without read-only mode —
+ * prompts the user to switch to admin mode instead.
+ */
+export function ReadonlyModeNotSupported() {
+ const { t } = useTranslation();
+ const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();
+ const instance = useVueState(() => instanceRef.value);
+
+ return (
+ <div className="w-full h-full flex flex-col items-center justify-center gap-y-2 p-4">
+ <div className="flex items-center gap-x-2 text-error">
+ <ShieldAlert className="size-6" />
+ <span className="text-base font-medium">
+ {t("common.missing-required-permission")}
+ </span>
+ </div>
+ <div className="text-sm text-control-light flex items-center gap-x-1">
+ <Trans
+ t={t}
+ i18nKey="sql-editor.allow-admin-mode-only"
+ components={{
+ instance: (
+ <span className="inline-flex items-center gap-x-1 font-medium text-control">
+ {EngineIconPath[instance.engine] && (
+ <img
+ src={EngineIconPath[instance.engine]}
+ alt=""
+ className="size-4"
+ />
+ )}
+ <span>{instance.title}</span>
+ </span>
+ ),
+ }}
+ />
+ </div>
+ <AdminModeButton />
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SheetConnectionIcon.test.tsx b/frontend/src/react/components/sql-editor/SheetConnectionIcon.test.tsx
new file mode 100644
index 0000000000..b48001a1df
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SheetConnectionIcon.test.tsx
@@ -0,0 +1,110 @@
+import type { ReactElement } from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+import type { SQLEditorTab } from "@/types";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ isConnectedSQLEditorTab: vi.fn<(tab: SQLEditorTab) => boolean>(),
+ getConnectionForSQLEditorTab:
+ vi.fn<
+ (tab: SQLEditorTab) => { instance: { engine: Engine } | undefined }
+ >(),
+}));
+
+vi.mock("@/utils", () => ({
+ isConnectedSQLEditorTab: mocks.isConnectedSQLEditorTab,
+ getConnectionForSQLEditorTab: mocks.getConnectionForSQLEditorTab,
+}));
+
+vi.mock("@/components/InstanceForm/constants", () => ({
+ EngineIconPath: {
+ [Engine.POSTGRES]: "/icons/postgres.svg",
+ } as Record<string, string>,
+}));
+
+let SheetConnectionIcon: typeof import("./SheetConnectionIcon").SheetConnectionIcon;
+
+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();
+ },
+ };
+};
+
+const dummyTab = { id: "t1" } as unknown as SQLEditorTab;
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ ({ SheetConnectionIcon } = await import("./SheetConnectionIcon"));
+});
+
+describe("SheetConnectionIcon", () => {
+ test("renders engine icon when connected", () => {
+ mocks.isConnectedSQLEditorTab.mockReturnValue(true);
+ mocks.getConnectionForSQLEditorTab.mockReturnValue({
+ instance: { engine: Engine.POSTGRES },
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <SheetConnectionIcon tab={dummyTab} />
+ );
+ render();
+
+ const img = container.querySelector("img");
+ expect(img).not.toBeNull();
+ expect(img?.getAttribute("src")).toBe("/icons/postgres.svg");
+
+ unmount();
+ });
+
+ test("renders unlink icon when disconnected", () => {
+ mocks.isConnectedSQLEditorTab.mockReturnValue(false);
+ mocks.getConnectionForSQLEditorTab.mockReturnValue({ instance: undefined });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <SheetConnectionIcon tab={dummyTab} />
+ );
+ render();
+
+ expect(container.querySelector("img")).toBeNull();
+ expect(container.querySelector("svg")).not.toBeNull();
+
+ unmount();
+ });
+
+ test("renders unlink icon when instance engine has no icon path", () => {
+ mocks.isConnectedSQLEditorTab.mockReturnValue(true);
+ mocks.getConnectionForSQLEditorTab.mockReturnValue({
+ instance: { engine: Engine.ENGINE_UNSPECIFIED },
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <SheetConnectionIcon tab={dummyTab} />
+ );
+ render();
+
+ expect(container.querySelector("img")).toBeNull();
+ expect(container.querySelector("svg")).not.toBeNull();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/react/components/sql-editor/SheetConnectionIcon.tsx b/frontend/src/react/components/sql-editor/SheetConnectionIcon.tsx
new file mode 100644
index 0000000000..53109b051e
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SheetConnectionIcon.tsx
@@ -0,0 +1,29 @@
+import { Unlink } from "lucide-react";
+import { EngineIconPath } from "@/components/InstanceForm/constants";
+import type { SQLEditorTab } from "@/types";
+import { getConnectionForSQLEditorTab, isConnectedSQLEditorTab } from "@/utils";
+
+type Props = {
+ readonly tab: SQLEditorTab;
+};
+
+/**
+ * Replaces frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue.
+ * Renders the engine icon when the tab has a live connection, otherwise the
+ * "unlink" glyph.
+ */
+export function SheetConnectionIcon({ tab }: Props) {
+ const connected = isConnectedSQLEditorTab(tab);
+ const { instance } = getConnectionForSQLEditorTab(tab);
+
+ if (connected && instance && EngineIconPath[instance.engine]) {
+ return (
+ <img
+ src={EngineIconPath[instance.engine]}
+ alt=""
+ className="size-4 shrink-0"
+ />
+ );
+ }
+ return <Unlink className="size-4 shrink-0" />;
+}
diff --git a/frontend/src/react/components/sql-editor/SheetTree.tsx b/frontend/src/react/components/sql-editor/SheetTree.tsx
index 2d8988c667..1d1ab7adce 100644
--- a/frontend/src/react/components/sql-editor/SheetTree.tsx
+++ b/frontend/src/react/components/sql-editor/SheetTree.tsx
@@ -86,10 +86,14 @@ export type SheetTreeHandle = {
type Props = {
readonly view: SheetViewMode;
+ // Multi-select state is only wired on the "my" tree (matches the Vue
+ // v-model binding). When the callbacks are absent, the context-menu
+ // "Multi-select" action is hidden so shared/draft rows cannot populate
+ // the `my` tree's checkedNodes (which feeds Delete + Move-to-folder).
readonly multiSelectMode?: boolean;
readonly checkedNodes?: WorksheetFolderNode[];
- readonly onMultiSelectModeChange: (next: boolean) => void;
- readonly onCheckedNodesChange: (nodes: WorksheetFolderNode[]) => void;
+ readonly onMultiSelectModeChange?: (next: boolean) => void;
+ readonly onCheckedNodesChange?: (nodes: WorksheetFolderNode[]) => void;
readonly ref?: Ref<SheetTreeHandle>;
};
@@ -134,21 +138,41 @@ function toTreeData(
}
/**
- * Count rows that react-arborist will render: the node itself, plus all
- * descendants of expanded folders. Matches naive-ui NTree's natural-height
- * behavior so stacked SheetTrees don't reserve react-arborist's 300px default.
+ * Count rows that react-arborist will actually render so the Tree's fixed
+ * viewport can be sized naturally (instead of its 300px default).
+ *
+ * - When `keyword` is empty, count the node plus descendants of expanded
+ * folders — arborist hides collapsed children.
+ * - When `keyword` is set, arborist filters visible nodes to matches +
+ * their ancestors regardless of expand state. Mirror that here so the
+ * viewport shrinks during search; otherwise the tree reserves the full
+ * pre-filter height and leaves a large empty block under the matches.
*/
function countVisibleRows(
node: WorksheetFolderNode,
- expandedKeys: Set<string>
+ expandedKeys: Set<string>,
+ keyword: string,
+ searchMatch: (node: WorksheetFolderNode, term: string) => boolean
): number {
- let count = 1;
- if (expandedKeys.has(node.key)) {
- for (const child of node.children) {
- count += countVisibleRows(child, expandedKeys);
+ if (!keyword) {
+ let count = 1;
+ if (expandedKeys.has(node.key)) {
+ for (const child of node.children) {
+ count += countVisibleRows(child, expandedKeys, keyword, searchMatch);
+ }
}
+ return count;
+ }
+
+ let childCount = 0;
+ for (const child of node.children) {
+ childCount += countVisibleRows(child, expandedKeys, keyword, searchMatch);
}
- return count;
+ const selfMatches = searchMatch(node, keyword);
+ if (selfMatches || childCount > 0) {
+ return 1 + childCount;
+ }
+ return 0;
}
// Generate unique folder name based on existing children
@@ -240,7 +264,13 @@ export function SheetTree({
handleContextMenu,
handleSharePanelShow,
handleClickOutside: handleContextMenuClickOutside,
- } = useDropdown(view, worksheetFilter);
+ } = useDropdown(
+ view,
+ worksheetFilter,
+ // Only expose the "Multi-select" entry when the parent wires the
+ // multi-select callbacks — i.e. on the `my` tree inside WorksheetPane.
+ !!onMultiSelectModeChange && !!onCheckedNodesChange
+ );
// ---- Menu anchor ----------------------------------------------------------
// Base UI's popup hover-floating interaction closes the menu on
@@ -362,11 +392,23 @@ export function SheetTree({
// Row height must match the <Tree rowHeight={...}> prop below.
const ROW_HEIGHT = 26;
- // Natural-height sizing so stacked SheetTrees don't each reserve the Tree
- // primitive's 300px default viewport.
+ // primitive's 300px default viewport. Must account for both expand state
+ // AND the search filter — when the keyword is active, arborist hides
+ // non-matching rows, so the viewport should shrink accordingly.
+ const nodeMatches = useCallback(
+ (node: WorksheetFolderNode, term: string): boolean =>
+ filterNode(folderContext.rootPath.value)(term, node),
+ [folderContext.rootPath.value]
+ );
const treeHeight = useMemo(
- () => countVisibleRows(sheetTree, new Set(expandedKeysArray)) * ROW_HEIGHT,
- [sheetTree, expandedKeysArray]
+ () =>
+ countVisibleRows(
+ sheetTree,
+ new Set(expandedKeysArray),
+ worksheetFilter.keyword,
+ nodeMatches
+ ) * ROW_HEIGHT,
+ [sheetTree, expandedKeysArray, worksheetFilter.keyword, nodeMatches]
);
// ---- Expand/collapse toggle -----------------------------------------------
@@ -658,7 +700,7 @@ export function SheetTree({
}
const removed = await handleDeleteFolders(folders, worksheets);
if (removed) {
- onMultiSelectModeChange(false);
+ onMultiSelectModeChange?.(false);
}
},
[folderContext, handleDeleteFolders, onMultiSelectModeChange]
@@ -732,8 +774,10 @@ export function SheetTree({
});
break;
case "multi-select":
- onMultiSelectModeChange(true);
- onCheckedNodesChange(revealNodes(contextMenuNode, (n) => n));
+ // Guarded — the menu item is only surfaced when the callbacks exist
+ // (the "my" tree); the optional-chaining is a belt-and-braces safety.
+ onMultiSelectModeChange?.(true);
+ onCheckedNodesChange?.(revealNodes(contextMenuNode, (n) => n));
break;
default:
break;
@@ -967,13 +1011,13 @@ export function SheetTree({
: revealNodes(folderNode, (n) => n);
if (e.target.checked) {
const existing = new Set(checkedNodes.map((n) => n.key));
- onCheckedNodesChange([
+ onCheckedNodesChange?.([
...checkedNodes,
...affected.filter((n) => !existing.has(n.key)),
]);
} else {
const affectedKeys = new Set(affected.map((n) => n.key));
- onCheckedNodesChange(
+ onCheckedNodesChange?.(
checkedNodes.filter((n) => !affectedKeys.has(n.key))
);
}
diff --git a/frontend/src/react/components/sql-editor/WorksheetPane.tsx b/frontend/src/react/components/sql-editor/WorksheetPane.tsx
index 3945c37ee0..ddd4a0a133 100644
--- a/frontend/src/react/components/sql-editor/WorksheetPane.tsx
+++ b/frontend/src/react/components/sql-editor/WorksheetPane.tsx
@@ -208,12 +208,11 @@ export function WorksheetPane() {
/>
)}
{views.map((view) => (
- <SheetTree
- key={view}
- view={view}
- onMultiSelectModeChange={setMultiSelectMode}
- onCheckedNodesChange={setCheckedNodes}
- />
+ // Non-"my" trees intentionally omit multi-select callbacks. Vue
+ // bound v-model only on the `my` tree; wiring them everywhere let
+ // a shared/draft right-click populate the my tree's checkedNodes,
+ // which the toolbar's Delete + Move-to-folder flows act on.
+ <SheetTree key={view} view={view} />
))}
{!hasAnyView && (
<div className="mt-10 text-center text-sm text-control-light">
diff --git a/frontend/src/react/components/sql-editor/useDropdown.ts b/frontend/src/react/components/sql-editor/useDropdown.ts
index a4fe340035..5fb5803f63 100644
--- a/frontend/src/react/components/sql-editor/useDropdown.ts
+++ b/frontend/src/react/components/sql-editor/useDropdown.ts
@@ -56,7 +56,12 @@ export type MenuItem =
export function useDropdown(
viewMode: SheetViewMode,
- worksheetFilter: WorksheetFilter
+ worksheetFilter: WorksheetFilter,
+ // Only the "my" tree is wired to the parent's multi-select state. For
+ // other views (shared / draft) the context-menu entry is hidden so a
+ // right-click on a shared worksheet cannot populate the my tree's
+ // checkedNodes — which the toolbar's Delete + Move-to-folder flows act on.
+ canMultiSelect = false
) {
const { t } = useTranslation();
@@ -133,10 +138,12 @@ export function useDropdown(
}
);
}
- items.push({
- key: "multi-select",
- label: t("sql-editor.tab.context-menu.actions.multi-select"),
- });
+ if (canMultiSelect) {
+ items.push({
+ key: "multi-select",
+ label: t("sql-editor.tab.context-menu.actions.multi-select"),
+ });
+ }
} else {
if (allowCreateNew) {
items.push({
@@ -151,10 +158,12 @@ export function useDropdown(
label: t("sql-editor.tab.context-menu.actions.add-worksheet"),
});
}
- items.push({
- key: "multi-select",
- label: t("sql-editor.tab.context-menu.actions.multi-select"),
- });
+ if (canMultiSelect) {
+ items.push({
+ key: "multi-select",
+ label: t("sql-editor.tab.context-menu.actions.multi-select"),
+ });
+ }
}
if (currentNode.editable) {
items.push(
@@ -173,7 +182,15 @@ export function useDropdown(
return items.map(
(item): MenuItem => ({ type: "item", key: item.key, label: item.label })
);
- }, [viewMode, currentNode, worksheetEntity, me, allowCreateNew, t]);
+ }, [
+ viewMode,
+ currentNode,
+ worksheetEntity,
+ me,
+ allowCreateNew,
+ canMultiSelect,
+ t,
+ ]);
// ------------------------------------------------------------------
// Handlers
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 86a22260f8..0b39df5ad6 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -196,6 +196,7 @@
"show-diff": "Show diff"
},
"common": {
+ "action-required": "Action Required",
"activated": "Activated",
"active": "Active",
"add": "Add",
@@ -795,7 +796,8 @@
"sync-status": "Sync status",
"sync-status-failed": "Sync failed",
"table": {
- "select": "Select table"
+ "select": "Select table",
+ "select-tip": "Please select a table to start."
},
"transfer-project": "Transfer Project",
"unassign": "Unassign",
@@ -1417,6 +1419,7 @@
},
"title": {
"change-database": "Change database",
+ "change-from-sql-editor": "Change from SQL Editor",
"request-role": "Request role",
"request-specific-role": "Request \"{{role}}\" role"
},
@@ -1510,6 +1513,7 @@
"checks": {
"self": "Checks"
},
+ "create-plan": "Create Plan",
"editor": {
"save-changes-before-continuing": "Please save or cancel your changes before continuing"
},
@@ -1588,6 +1592,20 @@
"plan.targets.title": "Targets",
"plan.targets.view-all": "View all ({{count}})",
"plan.view-discussion": "View discussion",
+ "plugin": {
+ "ai": {
+ "actions": {
+ "explain-code": "Explain code",
+ "find-problems": "Find problems"
+ },
+ "ai-assistant": "AI Assistant",
+ "not-configured": {
+ "contact-admin-to-configure": "Please contact your org administrator.",
+ "go-to-configure": "Go to configure",
+ "self": "AI Assistant is not configured."
+ }
+ }
+ },
"policy": {
"environment-tier": {
"description": "The environment will appear differently from other environments.",
@@ -2523,8 +2541,10 @@
"activate-confirm": "Are you sure you want to activate this access grant?",
"add-a-new-instance": "Add new instance",
"admin-mode": {
+ "exit": "Exit admin mode",
"self": "Admin mode"
},
+ "allow-admin-mode-only": "Instance <instance></instance> is accessible in admin mode only.",
"and-n-more-databases": "and {{n}} more databases",
"batch-query": {
"batch": "Batch"
@@ -2532,6 +2552,7 @@
"choose-folder": "Choose or create folder",
"choose-folder-tips": "You can create a new folder by entering a non-existent path. The folders should be joined with a \"/\".",
"connect-to-a-database": "Connect to database",
+ "ddl-dml-requires-data-change-plan": "To execute DDL/DML statements in <environment></environment>, please submit a Data Change Plan for approval.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
@@ -2548,6 +2569,7 @@
"jit": "Just-In-Time Access",
"link-access": "Link access",
"no-access-requests": "No access requests",
+ "no-database-selected": "No database selected",
"no-history-found": "No history found",
"only-select-allowed": "Only read-only statements are allowed to execute.",
"private": "Private",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 8c123b07cd..e3e527cbb9 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -195,6 +195,7 @@
"show-diff": "Mostrar diferencias"
},
"common": {
+ "action-required": "Acción requerida",
"activated": "Activado",
"active": "Activo",
"add": "Agregar",
@@ -788,7 +789,8 @@
"sync-status": "Estado de sincronización",
"sync-status-failed": "Sincronización fallida",
"table": {
- "select": "Seleccionar tabla"
+ "select": "Seleccionar tabla",
+ "select-tip": "Seleccione una mesa para comenzar."
},
"transfer-project": "Transferir proyecto",
"unassign": "Desasignar",
@@ -1409,6 +1411,7 @@
},
"title": {
"change-database": "Modificar base de datos",
+ "change-from-sql-editor": "Modificar desde el editor SQL",
"request-role": "Solicitar rol",
"request-specific-role": "Solicitar rol \"{{role}}\""
},
@@ -1502,6 +1505,7 @@
"checks": {
"self": "Verificaciones"
},
+ "create-plan": "Crear plan",
"editor": {
"save-changes-before-continuing": "Guarde o cancele sus cambios antes de continuar."
},
@@ -1580,6 +1584,20 @@
"plan.targets.title": "Objetivos",
"plan.targets.view-all": "Ver todo ({{count}})",
"plan.view-discussion": "Ver discusión",
+ "plugin": {
+ "ai": {
+ "actions": {
+ "explain-code": "Explicar el código",
+ "find-problems": "encontrar problemas"
+ },
+ "ai-assistant": "Asistente de IA",
+ "not-configured": {
+ "contact-admin-to-configure": "Comuníquese con el administrador de su organización.",
+ "go-to-configure": "Ir a configurar",
+ "self": "El Asistente AI no está configurado."
+ }
+ }
+ },
"policy": {
"environment-tier": {
"description": "El entorno aparecerá de manera diferente a otros entornos.",
@@ -2509,8 +2527,10 @@
"activate-confirm": "Are you sure you want to activate this access grant?",
"add-a-new-instance": "Agregar nueva instancia",
"admin-mode": {
+ "exit": "Salir del modo administrador",
"self": "Modo administrador"
},
+ "allow-admin-mode-only": "La instancia <instance></instance> solo es accesible en modo administrador.",
"and-n-more-databases": "and {{n}} more databases",
"batch-query": {
"batch": "Lote"
@@ -2518,6 +2538,7 @@
"choose-folder": "Seleccionar o crear una carpeta",
"choose-folder-tips": "Puedes crear una nueva carpeta introduciendo una ruta que no exista. Las carpetas deben unirse con una barra diagonal (\"/\").",
"connect-to-a-database": "Conectar a base de datos",
+ "ddl-dml-requires-data-change-plan": "Para ejecutar sentencias DDL/DML en <environment></environment>, envíe un Plan de Cambio de Datos para su aprobación.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
@@ -2534,6 +2555,7 @@
"jit": "Just-In-Time Access",
"link-access": "Acceso al enlace",
"no-access-requests": "No access requests",
+ "no-database-selected": "No se ha seleccionado una base de datos",
"no-history-found": "No se encontró historial",
"only-select-allowed": "Solo se permiten ejecutar declaraciones de solo lectura.",
"private": "Privado",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 1b2210396f..cb5e35477b 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -195,6 +195,7 @@
"show-diff": "違いを表示"
},
"common": {
+ "action-required": "対応が必要",
"activated": "有効化しました",
"active": "アクティブ",
"add": "追加",
@@ -788,7 +789,8 @@
"sync-status": "同期ステータス",
"sync-status-failed": "同期に失敗しました",
"table": {
- "select": "テーブルを選択"
+ "select": "テーブルを選択",
+ "select-tip": "開始するにはテーブルを選択してください。"
},
"transfer-project": "プロジェクトの転送",
"unassign": "割り当てを解除する",
@@ -1409,6 +1411,7 @@
},
"title": {
"change-database": "データベースの変更",
+ "change-from-sql-editor": "SQL エディタからの変更",
"request-role": "ロールをリクエスト",
"request-specific-role": "「{{role}}」ロールをリクエスト"
},
@@ -1502,6 +1505,7 @@
"checks": {
"self": "チェック"
},
+ "create-plan": "プランを作成",
"editor": {
"save-changes-before-continuing": "続行する前に変更を保存またはキャンセルしてください"
},
@@ -1580,6 +1584,20 @@
"plan.targets.title": "対象",
"plan.targets.view-all": "すべて表示 ({{count}})",
"plan.view-discussion": "ディスカッションを見る",
+ "plugin": {
+ "ai": {
+ "actions": {
+ "explain-code": "コードの説明",
+ "find-problems": "問題を見つける"
+ },
+ "ai-assistant": "AI アシスタント",
+ "not-configured": {
+ "contact-admin-to-configure": "組織の管理者に問い合わせてください。",
+ "go-to-configure": "設定に移動",
+ "self": "AI アシスタントが設定されていません。"
+ }
+ }
+ },
"policy": {
"environment-tier": {
"description": "この環境を他の環境とは異なって見えるようにします。",
@@ -2509,8 +2527,10 @@
"activate-confirm": "Are you sure you want to activate this access grant?",
"add-a-new-instance": "新しいインスタンスを追加",
"admin-mode": {
+ "exit": "管理者モードを終了する",
"self": "管理者モード"
},
+ "allow-admin-mode-only": "インスタンス <instance></instance> には管理者モードでのみアクセスできます。",
"and-n-more-databases": "and {{n}} more databases",
"batch-query": {
"batch": "バッチ"
@@ -2518,6 +2538,7 @@
"choose-folder": "フォルダを選択または作成",
"choose-folder-tips": "存在しないパスを入力することで新しいフォルダを作成できます。フォルダは「/」で結合する必要があります。",
"connect-to-a-database": "データベースに接続",
+ "ddl-dml-requires-data-change-plan": "<environment></environment> で DDL/DML ステートメントを実行するには、承認のためデータ変更プランを送信してください。",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
@@ -2534,6 +2555,7 @@
"jit": "Just-In-Time Access",
"link-access": "リンクアクセス",
"no-access-requests": "No access requests",
+ "no-database-selected": "データベースが選択されていません",
"no-history-found": "まだ履歴がありません",
"only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます",
"private": "プライベート",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 3eb9fbc1ef..ea3c20a0a1 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -195,6 +195,7 @@
"show-diff": "Hiển thị khác biệt"
},
"common": {
+ "action-required": "Cần thực hiện hành động",
"activated": "Đã kích hoạt",
"active": "Hoạt động",
"add": "Thêm",
@@ -788,7 +789,8 @@
"sync-status": "Trạng thái đồng bộ",
"sync-status-failed": "Đồng bộ thất bại",
"table": {
- "select": "Chọn bảng"
+ "select": "Chọn bảng",
+ "select-tip": "Vui lòng chọn một bảng để bắt đầu."
},
"transfer-project": "Chuyển dự án",
"unassign": "Hủy gán",
@@ -1409,6 +1411,7 @@
},
"title": {
"change-database": "Thay đổi cơ sở dữ liệu",
+ "change-from-sql-editor": "Thay đổi từ SQL Editor",
"request-role": "Yêu cầu vai trò",
"request-specific-role": "Yêu cầu vai trò \"{{role}}\""
},
@@ -1502,6 +1505,7 @@
"checks": {
"self": "Kiểm tra"
},
+ "create-plan": "Tạo kế hoạch",
"editor": {
"save-changes-before-continuing": "Vui lòng lưu hoặc hủy thay đổi của bạn trước khi tiếp tục"
},
@@ -1580,6 +1584,20 @@
"plan.targets.title": "Mục tiêu",
"plan.targets.view-all": "Xem tất cả ({{count}})",
"plan.view-discussion": "Xem thảo luận",
+ "plugin": {
+ "ai": {
+ "actions": {
+ "explain-code": "Giải thích mã",
+ "find-problems": "Tìm vấn đề"
+ },
+ "ai-assistant": "Trợ lý AI",
+ "not-configured": {
+ "contact-admin-to-configure": "Vui lòng liên hệ với quản trị viên tổ chức của bạn.",
+ "go-to-configure": "Đi tới cấu hình",
+ "self": "Trợ lý AI chưa được định cấu hình."
+ }
+ }
+ },
"policy": {
"environment-tier": {
"description": "Môi trường sẽ xuất hiện khác với các môi trường khác.",
@@ -2509,8 +2527,10 @@
"activate-confirm": "Are you sure you want to activate this access grant?",
"add-a-new-instance": "Thêm phiên bản mới",
"admin-mode": {
+ "exit": "Thoát chế độ quản trị",
"self": "Chế độ quản trị"
},
+ "allow-admin-mode-only": "Phiên bản <instance></instance> chỉ có thể truy cập ở chế độ quản trị.",
"and-n-more-databases": "and {{n}} more databases",
"batch-query": {
"batch": "Hàng loạt"
@@ -2518,6 +2538,7 @@
"choose-folder": "Chọn hoặc tạo thư mục",
"choose-folder-tips": "Bạn có thể tạo một thư mục mới bằng cách nhập một đường dẫn không tồn tại. Các thư mục phải được nối bằng dấu \"/\".",
"connect-to-a-database": "Kết nối cơ sở dữ liệu",
+ "ddl-dml-requires-data-change-plan": "Để thực thi câu lệnh DDL/DML trong <environment></environment>, vui lòng gửi Kế hoạch Thay đổi Dữ liệu để được phê duyệt.",
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
@@ -2534,6 +2555,7 @@
"jit": "Just-In-Time Access",
"link-access": "Truy cập liên kết",
"no-access-requests": "No access requests",
+ "no-database-selected": "Chưa chọn cơ sở dữ liệu",
"no-history-found": "Không tìm thấy lịch sử",
"only-select-allowed": "Chỉ cho phép thực thi câu lệnh chỉ đọc.",
"private": "Riêng tư",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 48a02e8636..c891b0311e 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -195,6 +195,7 @@
"show-diff": "显示差异"
},
"common": {
+ "action-required": "需要操作",
"activated": "已激活",
"active": "开启",
"add": "添加",
@@ -788,7 +789,8 @@
"sync-status": "同步状态",
"sync-status-failed": "同步失败",
"table": {
- "select": "选择表"
+ "select": "选择表",
+ "select-tip": "请选择一个表来开始查询。"
},
"transfer-project": "转移项目",
"unassign": "取消分配",
@@ -1409,6 +1411,7 @@
},
"title": {
"change-database": "变更数据库",
+ "change-from-sql-editor": "从 SQL 编辑器变更",
"request-role": "申请角色",
"request-specific-role": "申请 \"{{role}}\" 角色"
},
@@ -1502,6 +1505,7 @@
"checks": {
"self": "检查"
},
+ "create-plan": "创建计划",
"editor": {
"save-changes-before-continuing": "请保存或取消更改,然后再继续"
},
@@ -1580,6 +1584,20 @@
"plan.targets.title": "目标",
"plan.targets.view-all": "查看全部 ({{count}})",
"plan.view-discussion": "查看讨论",
+ "plugin": {
+ "ai": {
+ "actions": {
+ "explain-code": "解释代码",
+ "find-problems": "找出问题"
+ },
+ "ai-assistant": "AI 助手",
+ "not-configured": {
+ "contact-admin-to-configure": "请联系您的组织管理员。",
+ "go-to-configure": "前往配置",
+ "self": "AI 助手尚未配置。"
+ }
+ }
+ },
"policy": {
"environment-tier": {
"description": "使该环境在显示上不同于其他环境。",
@@ -2509,8 +2527,10 @@
"activate-confirm": "确定要激活此访问授权吗?",
"add-a-new-instance": "添加新实例",
"admin-mode": {
+ "exit": "退出管理员模式",
"self": "管理员模式"
},
+ "allow-admin-mode-only": "实例<instance></instance>只能通过管理员模式访问。",
"and-n-more-databases": "及其他 {{n}} 个数据库",
"batch-query": {
"batch": "批量"
@@ -2518,6 +2538,7 @@
"choose-folder": "选择或创建文件夹",
"choose-folder-tips": "您可以通过输入不存在的路径来创建新文件夹。文件夹之间应以\"/\"连接。",
"connect-to-a-database": "连接数据库",
+ "ddl-dml-requires-data-change-plan": "如需在 <environment></environment> 中执行 DDL/DML 语句,请创建变更计划以获得审批。",
"duration-day": "{{days}} 天",
"duration-days": "{{days}} 天",
"duration-hours": "{{hours}} 小时",
@@ -2534,6 +2555,7 @@
"jit": "即时访问",
"link-access": "链接访问权限",
"no-access-requests": "暂无访问请求",
+ "no-database-selected": "未选择数据库",
"no-history-found": "暂无历史记录",
"only-select-allowed": "只允许执行只读语句",
"private": "私有",
diff --git a/frontend/src/views/sql-editor/Disconnected.vue b/frontend/src/views/sql-editor/Disconnected.vue
deleted file mode 100644
index 42dc004b1a..0000000000
--- a/frontend/src/views/sql-editor/Disconnected.vue
+++ /dev/null
@@ -1 +0,0 @@
-<template>Select a database to connect</template>
diff --git a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue b/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
deleted file mode 100644
index 26357f8c1d..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/AdminModeButton.vue
+++ /dev/null
@@ -1,63 +0,0 @@
-<template>
- <NButton
- v-if="showButton"
- :size="props.size"
- type="warning"
- :ghost="true"
- :disabled="isDisconnected"
- @click.stop="enterAdminMode"
- >
- <template #icon>
- <WrenchIcon class="w-4 h-4" />
- </template>
- <span v-if="!hideText">{{ $t("sql-editor.admin-mode.self") }}</span>
- </NButton>
-</template>
-
-<script lang="ts" setup>
-import { WrenchIcon } from "lucide-vue-next";
-import { type ButtonProps, NButton } from "naive-ui";
-import { storeToRefs } from "pinia";
-import type { PropType } from "vue";
-import { computed } from "vue";
-import { useSQLEditorStore, useSQLEditorTabStore } from "@/store";
-
-const emit = defineEmits<{
- (e: "enter"): void;
-}>();
-
-const props = defineProps({
- size: {
- type: String as PropType<ButtonProps["size"]>,
- default: "medium",
- },
- hideText: {
- type: Boolean,
- default: false,
- },
-});
-
-const tabStore = useSQLEditorTabStore();
-const editorStore = useSQLEditorStore();
-
-const { currentTab, isDisconnected } = storeToRefs(tabStore);
-
-const showButton = computed(() => {
- if (!editorStore.allowAdmin) return false;
- const mode = currentTab.value?.mode;
- return mode === "WORKSHEET";
-});
-
-const enterAdminMode = async () => {
- const tab = currentTab.value;
- if (!tab) {
- return;
- }
-
- tabStore.updateCurrentTab({
- mode: "ADMIN",
- });
-
- emit("enter");
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue b/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
deleted file mode 100644
index 79cc5d4ab0..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/EditorAction.vue
+++ /dev/null
@@ -1,316 +0,0 @@
-<template>
- <div
- class="w-full flex flex-wrap gap-y-2 justify-between sm:items-center p-2 border-b bg-white"
- v-bind="$attrs"
- >
- <div
- class="action-left gap-x-2 flex overflow-x-auto sm:overflow-x-hidden items-center"
- >
- <NButton
- v-if="currentTab?.mode === 'ADMIN'"
- size="small"
- type="default"
- :dashed="true"
- style="--n-padding: 0 8px 0 3px"
- @click.stop="exitAdminMode"
- >
- <template #icon>
- <ChevronLeftIcon class="w-4 h-4 text-control" />
- </template>
- <span>{{ $t("sql-editor.admin-mode.exit") }}</span>
- </NButton>
-
- <NButtonGroup v-if="currentTab?.mode !== 'ADMIN'">
- <NTooltip :disabled="!queryTip">
- <template #trigger>
- <NButton
- :disabled="!allowQuery"
- type="primary"
- size="small"
- style="--n-padding: 0 5px"
- @click="handleRunQuery"
- >
- <template #icon>
- <PlayIcon class="w-4 h-4 fill-current!" />
- </template>
- <template #default>
- <div class="inline-flex items-center">
- <span>(</span>
- <span>limit&nbsp;{{ resultRowsLimit }}</span>
- <span>)</span>
- </div>
- </template>
- </NButton>
- </template>
- <span class="text-sm">
- {{ queryTip }}
- </span>
- </NTooltip>
- <ReactPageMount
- page="QueryContextSettingPopover"
- :disabled="!showQueryContextSettingPopover || !allowQuery"
- />
- </NButtonGroup>
-
- <ReactPageMount page="AdminModeButton" size="sm" :hideText="true" />
-
- <template v-if="showSheetsFeature">
- <NPopover placement="bottom">
- <template #trigger>
- <NButton
- :strong="allowSave"
- :disabled="!allowSave"
- size="small"
- style="--n-padding: 0 5px"
- @click="handleClickSave"
- >
- <template #icon>
- <SaveIcon class="w-4 h-4" />
- </template>
- </NButton>
- </template>
- <template #default>
- <div class="flex items-center gap-1">
- <span>{{ $t("common.save") }}</span>
- <span>({{ keyboardShortcutStr("cmd_or_ctrl+S") }})</span>
- </div>
- </template>
- </NPopover>
- <NPopover
- trigger="click"
- placement="bottom-end"
- :show-arrow="false"
- :disabled="false"
- >
- <template #trigger>
- <NPopover placement="bottom" trigger="hover">
- <template #trigger>
- <NButton
- :strong="allowShare"
- :disabled="!allowShare"
- size="small"
- style="--n-padding: 0 5px"
- >
- <template #icon>
- <Share2Icon class="w-4 h-4" />
- </template>
- </NButton>
- </template>
- <template #default>
- <div class="flex items-center gap-1">
- <span>{{ $t("common.share") }}</span>
- </div>
- </template>
- </NPopover>
- </template>
- <template #default>
- <ReactPageMount page="SharePopoverBody"
- :worksheet="sheetAndTabStore.currentSheet" />
- </template>
- </NPopover>
- </template>
- </div>
- <div
- class="action-right gap-x-2 flex overflow-x-auto sm:overflow-x-hidden sm:justify-end items-center"
- >
- <ReactPageMount page="ChooserGroup" />
-
- <OpenAIButton
- size="small"
- :statement="currentTab?.selectedStatement || currentTab?.statement"
- />
- </div>
- </div>
-
- <FeatureModal
- :open="!!state.requiredFeatureName"
- :feature="state.requiredFeatureName"
- @cancel="state.requiredFeatureName = undefined"
- />
-</template>
-
-<script lang="ts" setup>
-import {
- ChevronLeftIcon,
- PlayIcon,
- SaveIcon,
- Share2Icon,
-} from "lucide-vue-next";
-import { NButton, NButtonGroup, NPopover, NTooltip } from "naive-ui";
-import { storeToRefs } from "pinia";
-import { computed, reactive } from "vue";
-import { useI18n } from "vue-i18n";
-import { FeatureModal } from "@/components/FeatureGuard";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useUIStateStore,
- useWorkSheetAndTabStore,
- useWorkSheetStore,
-} from "@/store";
-import {
- DEFAULT_SQL_EDITOR_TAB_MODE,
- type SQLEditorQueryParams,
-} from "@/types";
-import { Engine } from "@/types/proto-es/v1/common_pb";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";
-import { useSQLEditorContext } from "../context";
-import OpenAIButton from "./OpenAIButton";
-
-interface LocalState {
- requiredFeatureName?: PlanFeature;
-}
-
-defineOptions({
- inheritAttrs: false,
-});
-
-const emit = defineEmits<{
- (e: "execute", params: SQLEditorQueryParams): void;
-}>();
-
-const state = reactive<LocalState>({});
-const tabStore = useSQLEditorTabStore();
-const uiStateStore = useUIStateStore();
-const { events } = useSQLEditorContext();
-const { resultRowsLimit } = storeToRefs(useSQLEditorStore());
-const sheetAndTabStore = useWorkSheetAndTabStore();
-
-const { currentTab, isDisconnected } = storeToRefs(tabStore);
-
-const isEmptyStatement = computed(() => {
- const tab = currentTab.value;
- if (!tab) {
- return true;
- }
- return tab.statement === "";
-});
-const { instance } = useConnectionOfCurrentSQLEditorTab();
-const { t } = useI18n();
-
-const showSheetsFeature = computed(() => {
- const mode = currentTab.value?.mode;
- return mode === "WORKSHEET";
-});
-
-const queryTip = computed(() => {
- if (
- instance.value.engine === Engine.COSMOSDB &&
- !currentTab.value?.connection.table
- ) {
- return t("database.table.select-tip");
- }
- return "";
-});
-
-const allowQuery = computed(() => {
- if (isDisconnected.value) return false;
- if (isEmptyStatement.value) return false;
-
- if (instance.value.engine === Engine.COSMOSDB) {
- return !!currentTab.value?.connection.table;
- }
-
- return true;
-});
-
-const canWriteSheet = computed(() => {
- if (!currentTab.value || !currentTab.value.worksheet) {
- return false;
- }
- const sheet = useWorkSheetStore().getWorksheetByName(
- currentTab.value.worksheet
- );
- if (!sheet) {
- return false;
- }
- return isWorksheetWritableV1(sheet);
-});
-
-const allowSave = computed(() => {
- if (!showSheetsFeature.value) {
- return false;
- }
- const tab = currentTab.value;
- if (!tab) {
- return false;
- }
-
- if (tab.worksheet) {
- if (!canWriteSheet.value) {
- return false;
- }
- const sheet = useWorkSheetStore().getWorksheetByName(tab.worksheet);
- if (sheet && sheet.database !== tab.connection.database) {
- return true;
- }
- }
- // Only disable when status is CLEAN (nothing to save)
- // SAVING is allowed - manual save will abort auto-save and proceed
- if (tab.status === "CLEAN") {
- return false;
- }
-
- return true;
-});
-
-const allowShare = computed(() => {
- const tab = currentTab.value;
- if (!tab) return false;
- if (tab.status !== "CLEAN") return false;
- if (isEmptyStatement.value) return false;
- if (isDisconnected.value) return false;
- if (tab.worksheet) {
- if (!canWriteSheet.value) {
- return false;
- }
- }
- return true;
-});
-
-const showQueryContextSettingPopover = computed(() => {
- const tab = currentTab.value;
- if (!tab) {
- return false;
- }
- return instance.value && tab.mode !== "ADMIN";
-});
-
-const handleRunQuery = () => {
- const tab = currentTab.value;
- if (!tab) {
- return;
- }
- const statement = tab.selectedStatement || tab.statement;
- emit("execute", {
- statement,
- connection: { ...tab.connection },
- engine: instance.value.engine,
- explain: false,
- selection: tab.editorState.selection,
- });
- uiStateStore.saveIntroStateByKey({
- key: "data.query",
- newState: true,
- });
-};
-
-const exitAdminMode = () => {
- tabStore.updateCurrentTab({
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- });
-};
-
-const handleClickSave = () => {
- const tab = currentTab.value;
- if (!tab) {
- return;
- }
- events.emit("save-sheet", {
- tab,
- });
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue b/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
deleted file mode 100644
index 749fc060a3..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ExecuteHint.vue
+++ /dev/null
@@ -1,188 +0,0 @@
-<template>
- <div class="execute-hint w-112">
- <NAlert type="info">
- <section class="flex flex-col gap-y-2">
- <p>
- {{ $t("sql-editor.only-select-allowed") }}
- </p>
- <p v-if="database">
- <i18n-t keypath="sql-editor.ddl-dml-requires-data-change-plan">
- <template #environment>
- <EnvironmentV1Name
- :environment="getDatabaseEnvironment(database)"
- />
- </template>
- </i18n-t>
- </p>
- </section>
- </NAlert>
-
- <div class="execute-hint-content mt-4 flex justify-between">
- <div
- v-if="actions.issue && actions.admin"
- class="flex justify-start items-center gap-x-2"
- >
- <AdminModeButton @enter="$emit('close')" />
- </div>
- <div class="flex flex-1 justify-end items-center gap-x-2">
- <NButton @click="handleClose">{{ $t("common.close") }}</NButton>
- <NButton
- v-if="actions.issue"
- type="primary"
- @click="handleClickCreateIssue"
- >
- {{ descriptions.action }}
- </NButton>
- <AdminModeButton v-else @enter="$emit('close')" />
- </div>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { NAlert, NButton } from "naive-ui";
-import { v4 as uuidv4 } from "uuid";
-import { computed } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
-import { EnvironmentV1Name } from "@/components/v2";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
-import {
- useDatabaseV1Store as databaseV1Store,
- useProjectV1Store as projectV1Store,
- pushNotification,
- useStorageStore as storageStoreAccessor,
- useSQLEditorStore,
- useSQLEditorTabStore,
-} from "@/store";
-import { unknownProject } from "@/types";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import {
- extractDatabaseResourceName,
- extractProjectResourceName,
- getDatabaseEnvironment,
-} from "@/utils";
-import AdminModeButton from "./AdminModeButton.vue";
-
-withDefaults(
- defineProps<{
- database?: Database | undefined;
- }>(),
- { database: undefined }
-);
-
-const emit = defineEmits<{
- (e: "close"): void;
-}>();
-
-const router = useRouter();
-const { t } = useI18n();
-const tabStore = useSQLEditorTabStore();
-const editorStore = useSQLEditorStore();
-// Store accessors imported under non-`use*` aliases so SonarCloud's
-// React-hook-rule (typescript:S6440) doesn't misfire on these Pinia
-// calls in a Vue SFC. Pinia stores are module-level singletons; the
-// accessor name is cosmetic. Kept consistent across ExecuteHint.vue
-// and SQLEditorHomePage.vue.
-const databaseStore = databaseV1Store();
-const projectStore = projectV1Store();
-const storageStore = storageStoreAccessor();
-
-const statement = computed(() => {
- const tab = tabStore.currentTab;
- return tab?.selectedStatement || tab?.statement || "";
-});
-
-const actions = computed(() => {
- type Actions = {
- admin: boolean;
- issue: boolean;
- };
- const actions: Actions = {
- admin: false,
- issue: true,
- };
- if (editorStore.allowAdmin) {
- actions.admin = true;
- }
-
- return actions;
-});
-
-const descriptions = computed(() => {
- const descriptions = {
- want: t("plan.create-plan").toLowerCase(),
- action: "",
- reaction: "",
- };
- const { admin, issue } = actions.value;
- if (issue) {
- descriptions.action = t("plan.create-plan");
- descriptions.reaction = t("sql-editor.and-submit-an-issue");
- } else if (admin) {
- descriptions.action = t("sql-editor.admin-mode.self");
- descriptions.reaction = t("sql-editor.to-enable-admin-mode");
- }
- return descriptions;
-});
-
-const handleClose = () => {
- emit("close");
-};
-
-const gotoCreateIssue = async () => {
- const database = tabStore.currentTab?.connection.database ?? "";
- if (!database) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("sql-editor.no-database-selected"),
- });
- return;
- }
-
- emit("close");
-
- const db = await databaseStore.getOrFetchDatabaseByName(database);
- // Project-fetch-failed cell: if the project lookup rejects (transient
- // network/permission failure), still open the plan page using the
- // already-known `db.project`. Fall back to `unknownProject()` which
- // has `enforceIssueTitle=true` — that is the safe governance default:
- // the launcher drops `query.name` so the plan page opens with a blank
- // title and the user types a deliberate one before submitting. Backend
- // remains the source of truth on submit.
- const project = await projectStore
- .getOrFetchProjectByName(db.project)
- .catch(() => unknownProject());
- const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;
- storageStore.put(sqlStorageKey, statement.value);
- const { databaseName } = extractDatabaseResourceName(db.name);
-
- const query: Record<string, string> = {
- template: "bb.plan.change-database",
- databaseList: db.name,
- sqlStorageKey,
- };
- applyPlanTitleToQuery(
- query,
- project,
- () => `[${databaseName}] ${t("issue.title.change-from-sql-editor")}`
- );
-
- const route = router.resolve({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- params: {
- projectId: extractProjectResourceName(db.project),
- planId: "create",
- specId: "placeholder",
- },
- query,
- });
- window.open(route.fullPath, "_blank");
-};
-
-const handleClickCreateIssue = () => {
- gotoCreateIssue();
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue b/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue
deleted file mode 100644
index 110ed6aa55..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/ExecutingHintModal.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <BBModal
- v-if="sqlEditorStore.isShowExecutingHint"
- :title="$t('common.action-required')"
- @close="handleClose"
- >
- <ExecuteHint
- :database="sqlEditorStore.executingHintDatabase"
- @close="handleClose"
- />
- </BBModal>
-</template>
-
-<script lang="ts" setup>
-import { BBModal } from "@/bbkit";
-import { useSQLEditorStore } from "@/store";
-import ExecuteHint from "./ExecuteHint.vue";
-
-const sqlEditorStore = useSQLEditorStore();
-
-const handleClose = () => {
- sqlEditorStore.isShowExecutingHint = false;
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue
deleted file mode 100644
index ac85ceb6be..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/Button.vue
+++ /dev/null
@@ -1,55 +0,0 @@
-<template>
- <NButton
- tag="div"
- v-bind="{
- ...buttonProps,
- ...$attrs,
- }"
- style="--n-icon-size: 16px; --n-padding: 0 6px"
- @click="$emit('click')"
- >
- <template #icon>
- <svg
- xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 320 320"
- fill="currentColor"
- stroke="none"
- class="w-4 h-4"
- >
- <path
- xmlns="http://www.w3.org/2000/svg"
- d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z"
- />
- </svg>
- </template>
- </NButton>
-</template>
-
-<script setup lang="ts">
-import { type ButtonProps, NButton } from "naive-ui";
-import { computed } from "vue";
-import { useSQLEditorContext } from "../../context";
-
-defineOptions({
- inheritAttrs: false,
-});
-
-defineEmits<{
- (event: "click"): void;
-}>();
-
-const { showAIPanel } = useSQLEditorContext();
-
-const buttonProps = computed(() => {
- const buttonProps: ButtonProps = {
- tag: "div",
- };
- if (showAIPanel.value) {
- buttonProps.type = "primary";
- buttonProps.secondary = true;
- } else {
- buttonProps.type = "default";
- }
- return buttonProps;
-});
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue
deleted file mode 100644
index 441b052cd6..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/OpenAIButton.vue
+++ /dev/null
@@ -1,164 +0,0 @@
-<template>
- <template v-if="showButton">
- <template v-if="openAIEnabled">
- <NPopselect
- v-if="options.length > 0"
- placement="bottom-end"
- :options="options"
- @update:value="handleSelect"
- >
- <Button v-bind="$attrs" @click="handleClickButton" />
- <template #header>
- <span class="font-semibold">{{ $t("plugin.ai.ai-assistant") }}</span>
- </template>
- </NPopselect>
- <Button v-else v-bind="$attrs" @click="handleClickButton" />
- </template>
- <NPopover v-if="!openAIEnabled" placement="bottom-end">
- <template #trigger>
- <Button v-bind="$attrs" :disabled="true" />
- </template>
- <template #default>
- <div class="flex flex-col">
- <div class="pb-1 border-b">
- <span class="font-semibold">
- {{ $t("plugin.ai.ai-assistant") }}
- </span>
- </div>
- <div class="pt-2 max-w-[20rem] flex flex-col text-gray-500">
- <p>
- {{ $t("plugin.ai.not-configured.self") }}
- <NButton
- v-if="allowConfigure"
- size="small"
- text
- type="primary"
- class="inline-block"
- @click="goConfigure"
- >
- {{ $t("plugin.ai.not-configured.go-to-configure") }}
- </NButton>
- <template v-else>
- {{ $t("plugin.ai.not-configured.contact-admin-to-configure") }}
- </template>
- </p>
- </div>
- </div>
- </template>
- </NPopover>
- </template>
-</template>
-
-<script setup lang="ts">
-import { NButton, NPopover, NPopselect, type SelectOption } from "naive-ui";
-import { computed, onMounted } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import type { ChatAction } from "@/plugins/ai";
-import { useAIContext } from "@/plugins/ai/logic";
-import * as promptUtils from "@/plugins/ai/logic/prompt";
-import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useSettingV1Store,
- useSQLEditorTabStore,
-} from "@/store";
-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
-import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";
-import { useSQLEditorContext } from "../../context";
-import Button from "./Button.vue";
-
-defineOptions({
- inheritAttrs: false,
-});
-
-const props = defineProps<{
- actions?: ChatAction[];
- statement?: string;
-}>();
-
-const { t } = useI18n();
-const router = useRouter();
-const tabStore = useSQLEditorTabStore();
-const settingV1Store = useSettingV1Store();
-
-onMounted(async () => {
- await settingV1Store.getOrFetchSettingByName(Setting_SettingName.AI, true);
-});
-
-const openAIEnabled = computed(() => {
- const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);
- return setting?.value?.value?.case === "ai"
- ? setting.value.value.value.enabled
- : false;
-});
-
-const { showAIPanel } = useSQLEditorContext();
-const { instance } = useConnectionOfCurrentSQLEditorTab();
-const { events } = useAIContext();
-
-const options = computed(() => {
- const { statement } = props;
- const options: (SelectOption & { value: ChatAction })[] = [
- {
- value: "explain-code",
- label: t("plugin.ai.actions.explain-code"),
- disabled: !statement,
- },
- {
- value: "find-problems",
- label: t("plugin.ai.actions.find-problems"),
- disabled: !statement,
- },
- ];
- return options.filter((opt) => {
- if (props.actions && !props.actions.includes(opt.value)) return false;
- return true;
- });
-});
-
-const showButton = computed(() => {
- return !tabStore.isDisconnected && tabStore.currentTab?.mode === "WORKSHEET";
-});
-
-const allowConfigure = computed((): boolean => {
- return hasWorkspacePermissionV2("bb.settings.set");
-});
-
-const handleSelect = async (action: ChatAction) => {
- // start new chat if AI panel is not open
- // continue current chat otherwise
- const newChat = !showAIPanel.value;
-
- showAIPanel.value = true;
- if (action === "explain-code" || action === "find-problems") {
- const { statement } = props;
- if (!statement) return;
-
- await nextAnimationFrame();
- if (action === "explain-code") {
- events.emit("send-chat", {
- content: promptUtils.explainCode(statement, instance.value.engine),
- newChat,
- });
- }
- if (action === "find-problems") {
- events.emit("send-chat", {
- content: promptUtils.findProblems(statement, instance.value.engine),
- newChat,
- });
- }
- }
-};
-
-const handleClickButton = () => {
- showAIPanel.value = !showAIPanel.value;
-};
-
-const goConfigure = () => {
- router.push({
- name: SETTING_ROUTE_WORKSPACE_GENERAL,
- hash: "#ai-assistant",
- });
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.ts b/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.ts
deleted file mode 100644
index f03377592e..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/OpenAIButton/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import OpenAIButton from "./OpenAIButton.vue";
-
-export default OpenAIButton;
diff --git a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue b/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
deleted file mode 100644
index 1f2f70bc65..0000000000
--- a/frontend/src/views/sql-editor/EditorCommon/SheetConnectionIcon.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <div v-if="connected && instance" class="w-4">
- <EngineIcon custom-class="w-full" :engine="instance.engine" />
- </div>
- <UnlinkIcon v-else />
-</template>
-
-<script setup lang="ts">
-import { UnlinkIcon } from "lucide-vue-next";
-import { computed } from "vue";
-import { EngineIcon } from "@/components/Icon";
-import { type SQLEditorTab } from "@/types";
-import { getConnectionForSQLEditorTab, isConnectedSQLEditorTab } from "@/utils";
-
-const props = defineProps<{
- tab: SQLEditorTab;
-}>();
-
-const connected = computed(() => isConnectedSQLEditorTab(props.tab));
-
-const instance = computed(
- () => getConnectionForSQLEditorTab(props.tab).instance
-);
-</script>
diff --git a/frontend/src/views/sql-editor/EditorCommon/index.ts b/frontend/src/views/sql-editor/EditorCommon/index.ts
index 53c7d4fd6f..c139c9bb8e 100644
--- a/frontend/src/views/sql-editor/EditorCommon/index.ts
+++ b/frontend/src/views/sql-editor/EditorCommon/index.ts
@@ -1,16 +1,4 @@
-import EditorAction from "./EditorAction.vue";
-import ExecutingHintModal from "./ExecutingHintModal.vue";
-import OpenAIButton from "./OpenAIButton/OpenAIButton.vue";
-import { ResultViewV1 } from "./ResultView";
-import SheetConnectionIcon from "./SheetConnectionIcon.vue";
-
-export {
- EditorAction,
- ExecutingHintModal,
- ResultViewV1,
- SheetConnectionIcon,
- OpenAIButton,
-};
+export { ResultViewV1 } from "./ResultView";
export * from "./hover-state";
export * from "./utils";
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
index 057b190cc4..e178edb7d7 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue
@@ -39,8 +39,9 @@
>
{{ $t("sql-editor.format") }}
</NCheckbox>
- <OpenAIButton
- size="small"
+ <ReactPageMount
+ page="OpenAIButton"
+ size="sm"
:statement="selectedStatement || view.definition"
:actions="['explain-code']"
/>
@@ -81,6 +82,7 @@ import { computed, h, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { ColumnIcon, ViewIcon } from "@/components/Icon";
import { SearchBox } from "@/components/v2";
+import ReactPageMount from "@/react/ReactPageMount.vue";
import type {
Database,
DatabaseMetadata,
@@ -88,7 +90,6 @@ import type {
ViewMetadata,
} from "@/types/proto-es/v1/database_service_pb";
import { STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT } from "@/utils";
-import { OpenAIButton } from "@/views/sql-editor/EditorCommon";
import { useCurrentTabViewStateContext } from "../../context/viewState";
import ColumnsTable from "./ColumnsTable.vue";
import DefinitionViewer from "./DefinitionViewer.vue";
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
index 9e3637d92c..54dd88d992 100644
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue
@@ -18,8 +18,9 @@
<NCheckbox v-model:checked="format">
{{ $t("sql-editor.format") }}
</NCheckbox>
- <OpenAIButton
- size="small"
+ <ReactPageMount
+ page="OpenAIButton"
+ size="sm"
:statement="selectedStatement || content"
:actions="['explain-code']"
/>
@@ -84,6 +85,7 @@ import formatSQL from "@/components/MonacoEditor/sqlFormatter";
import { AIChatToSQL, useAIActions } from "@/plugins/ai";
import { useAIContext } from "@/plugins/ai/logic";
import * as promptUtils from "@/plugins/ai/logic/prompt";
+import ReactPageMount from "@/react/ReactPageMount.vue";
import { dialectOfEngineV1 } from "@/types";
import type { Database } from "@/types/proto-es/v1/database_service_pb";
import {
@@ -93,7 +95,6 @@ import {
type VueClass,
} from "@/utils";
import { useSQLEditorContext } from "@/views/sql-editor/context";
-import { OpenAIButton } from "@/views/sql-editor/EditorCommon";
const props = defineProps<{
db: Database;
diff --git a/frontend/src/views/sql-editor/EditorPanel/ReadonlyModeNotSupported.vue b/frontend/src/views/sql-editor/EditorPanel/ReadonlyModeNotSupported.vue
deleted file mode 100644
index a9ccde4b86..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ReadonlyModeNotSupported.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <div class="w-full h-full flex flex-col items-center justify-center gap-y-2">
- <NoPermissionPlaceholder />
- <i18n-t
- class="textinfolabel flex items-center"
- keypath="sql-editor.allow-admin-mode-only"
- tag="div"
- >
- <template #instance>
- <InstanceV1Name :instance="instance" :link="false" />
- </template>
- </i18n-t>
- <AdminModeButton />
- </div>
-</template>
-
-<script lang="ts" setup>
-import NoPermissionPlaceholder from "@/components/Permission/NoPermissionPlaceholder.vue";
-import { InstanceV1Name } from "@/components/v2";
-import { useConnectionOfCurrentSQLEditorTab } from "@/store";
-import AdminModeButton from "../EditorCommon/AdminModeButton.vue";
-
-const { instance } = useConnectionOfCurrentSQLEditorTab();
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue
index 758b6050ce..1a8068462e 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue
@@ -1,7 +1,11 @@
<template>
<div class="h-full flex flex-col overflow-hidden justify-start items-stretch">
<template v-if="isDisconnected || allowReadonlyMode">
- <EditorAction @execute="handleExecuteFromActionBar" />
+ <ReactPageMount
+ page="EditorAction"
+ container-class="w-full"
+ :onExecute="handleExecuteFromActionBar"
+ />
<NSplit
v-if="tab"
@@ -49,17 +53,17 @@
/>
</div>
- <ExecutingHintModal />
-
- <!-- SaveSheetModal renders a React Dialog via portal; the inline mount
- must not occupy flex space or it steals height from the Welcome
- pane above (ReactPageMount's container is `class="h-full"`). -->
+ <!-- Both modals portal their Dialog popup via React; their inline
+ mount must not occupy flex space, otherwise ReactPageMount's
+ default `h-full` container steals height from the editor/NSplit
+ above (see the Welcome / AI-panel height bugs). -->
<div class="hidden">
+ <ReactPageMount page="ExecutingHintModal" />
<ReactPageMount page="SaveSheetModal" />
</div>
</template>
- <ReadonlyModeNotSupported v-else />
+ <ReactPageMount v-else page="ReadonlyModeNotSupported" />
</div>
</template>
@@ -80,9 +84,7 @@ import {
import type { SQLEditorQueryParams } from "@/types";
import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";
import { useSQLEditorContext } from "../../context";
-import { EditorAction, ExecutingHintModal } from "../../EditorCommon";
import { sqlEditorEvents } from "../../events";
-import ReadonlyModeNotSupported from "../ReadonlyModeNotSupported.vue";
const SQLEditor = defineAsyncComponent(() => import("./SQLEditor.vue"));
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue
index 381e5e91f4..7608d2b12e 100644
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue
+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue
@@ -2,7 +2,7 @@
<div
class="flex h-full w-full flex-col justify-start items-stretch overflow-hidden bg-dark-bg"
>
- <EditorAction />
+ <ReactPageMount page="EditorAction" container-class="w-full" />
<div
v-if="!tabStore.isDisconnected"
@@ -97,7 +97,7 @@ import {
useWebTerminalStore,
} from "@/store";
import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";
-import { EditorAction, ResultViewV1 } from "../../EditorCommon";
+import { ResultViewV1 } from "../../EditorCommon";
import { useHistory } from "./useHistory";
const CompactSQLEditor = defineAsyncComponent(
diff --git a/frontend/src/views/sql-editor/GettingStarted.vue b/frontend/src/views/sql-editor/GettingStarted.vue
deleted file mode 100644
index 7507ad33e0..0000000000
--- a/frontend/src/views/sql-editor/GettingStarted.vue
+++ /dev/null
@@ -1 +0,0 @@
-<template>Select a database or create a worksheet to start</template>
diff --git a/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue b/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
index 9d6256dbc5..b1c09c0e43 100644
--- a/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
+++ b/frontend/src/views/sql-editor/TabList/TabItem/Prefix.vue
@@ -8,17 +8,17 @@
/>
<WrenchIcon v-if="tab.mode === 'ADMIN'" class="w-4 h-4" />
</template>
- <SheetConnectionIcon :tab="tab" class="w-4 h-4" />
+ <ReactPageMount page="SheetConnectionIcon" :tab="tab" />
</div>
</template>
<script lang="ts" setup>
import { PencilLineIcon, UsersIcon, WrenchIcon } from "lucide-vue-next";
import { computed } from "vue";
+import ReactPageMount from "@/react/ReactPageMount.vue";
import { useWorkSheetStore } from "@/store";
import type { SQLEditorTab } from "@/types";
import { useSheetContext } from "@/views/sql-editor/Sheet";
-import { SheetConnectionIcon } from "../../EditorCommon";
const props = defineProps<{
tab: SQLEditorTab;