Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(react): migrate editor panel (#20146)
ecmadao53335913394e
diff --git a/docs/superpowers/specs/2026-04-27-sql-editor-react-migration-stage-17-design.md b/docs/superpowers/specs/2026-04-27-sql-editor-react-migration-stage-17-design.mdnew file mode 100644index 0000000000..dc9f203feb--- /dev/null+++ b/docs/superpowers/specs/2026-04-27-sql-editor-react-migration-stage-17-design.md@@ -0,0 +1,340 @@+# SQL Editor React Migration — Stage 17 Design++**Date:** 2026-04-27+**Author:** [email protected]+**Status:** Done (2026-04-27)++## 1. Goal & non-goals++**Goal:** Port every Vue surface inside `EditorPanel/StandardPanel/`,+`EditorPanel/TerminalPanel/`, and the non-`ResultView` leaves under+`EditorPanel/ResultPanel/` to React. After this stage every Monaco+editor surface in the SQL Editor (worksheet + terminal) is React, and+the Vue surface area shrinks to: the host shells (`Panels.vue`,+`StandardPanel.vue`, `TerminalPanel.vue`, `ResultPanel.vue`,+`EditorPanel.vue`), `DatabaseQueryContext.vue`, and everything under+`EditorCommon/ResultView/`.++**Non-goals:**+- `EditorCommon/ResultView/*` — the `VirtualDataTable` (~458 LOC) and+ its sub-components stay Vue. Performance characteristics warrant a+ dedicated spike; deliberately deferred to the *final* migration+ stage.+- The five host shells — they each directly host a Vue ResultView+ descendant, so they fall out for free with the final stage.+- `DiagramPanel.vue` — cytoscape passthrough; separate stage.+- `DatabaseQueryContext.vue` — wraps `ResultViewV1`; defers with+ ResultView.+- `SQLEditorHomePage.vue` and `EditorPanel.vue` — depend on the host+ shells; defer.+- New features or behavioral changes — parity only.++## 2. Inventory++### 2.1 In scope (~960 LOC migrated)++| File | LOC | Migration target | Status |+|---|---|---|---|+| `StandardPanel/SQLEditor.vue` | 401 | `react/components/sql-editor/StandardPanel/SQLEditor.tsx` | ✓ |+| `StandardPanel/EditorMain.vue` | 167 | `react/components/sql-editor/StandardPanel/EditorMain.tsx` | ✓ |+| `StandardPanel/UploadFileButton.vue` | 44 | `react/components/sql-editor/StandardPanel/UploadFileButton.tsx` | ✓ |+| `TerminalPanel/CompactSQLEditor.vue` | 312 | `react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx` | ✓ |++**Bonus migrations** discovered during the upload-button chain port:++| File | LOC | Migration target | Status |+|---|---|---|---|+| `components/misc/SQLUploadButton.vue` | 99 | `react/components/sql-editor/StandardPanel/SQLUploadButton.tsx` | ✓ |+| `components/FileContentPreviewModal.vue` | 100 | `react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx` | ✓ |++### 2.2 Moved out of scope (deferred to the ResultPanel stage)++| File | LOC | Reason for deferral |+|---|---|---|+| `ResultPanel/BatchQuerySelect.vue` | 359 | Hard dependency on `DataExportButton.vue` (414 LOC, no React equivalent — its drawer + form-slot + multi-file-zip download flow is its own port) and on `DatabaseV1Table`'s pre-fetched-list mode (the React `DatabaseTable` only fetches via server filter; would require a new `databases?: Database[]` opt-out path). Both naturally co-migrate with `ResultPanel.vue` since `BatchQuerySelect` is a child of that host shell. |+| `ResultPanel/ContextMenu.vue` | 85 | Coupled to `BatchQuerySelect` via an imperative `ref.show()` API. Migrates as a unit with the parent. |++### 2.2 Stays Vue (this stage)++```+SQLEditorHomePage.vue — still hosts EditorPanel+└── EditorPanel.vue — still hosts Panels+ └── Panels.vue — Stage 16 host+ └── #code-panel slot+ ├── StandardPanel.vue+ │ ├── #1: ReactPageMount("EditorMain") ← swapped+ │ └── #2: ResultPanel.vue+ │ ├── ReactPageMount("BatchQuerySelect") ← swapped+ │ ├── ReactPageMount("ContextMenu") ← swapped+ │ └── DatabaseQueryContext.vue (uses ResultView)+ └── TerminalPanel.vue+ └── loop body:+ ├── ReactPageMount("CompactSQLEditor") ← swapped+ └── ResultViewV1 (Vue, untouched)+```++The five Vue containers gain `ReactPageMount` calls but keep their NSplit / loop / dropdown wiring.++## 3. External deps & primitives++| Vue dep | React replacement | Status |+|---|---|---|+| `MonacoEditor` (Vue) | `MonacoEditor.tsx` (React, 659 LOC) — the React Monaco wrapper used by `ReadonlyMonaco`, `EditorAction`, etc. | ✓ exists |+| `formatSQL` from `@/components/MonacoEditor/sqlFormatter` | Same module, framework-neutral | ✓ |+| `useExecuteSQL` (Vue composable) | Either lift the Vue composable to a JS module (it already runs on Pinia stores) or replicate the body in a React hook | Lift — Phase 1 |+| `AIChatToSQL` (Vue Suspense pane) | Hoisted to a Vue host wrapper (Stage 16 pattern) — for `EditorMain`, the host is `StandardPanel.vue` | Reuse |+| `useAIActions` Monaco command | Already React — `Panels/common/useAIActions.ts` (Stage 16) | ✓ |+| `OpenAIButton` | Already React | ✓ |+| `BBSpin` (Vue spinner) | Same `Loader2` pattern used by other React leaves (`<Loader2 className="animate-spin" />`) | Reuse |+| `NDropdown` (right-click context menu) | shadcn `DropdownMenu` | ✓ |+| `NTabPane` / `NTabs` (BatchQuerySelect tab strip) | shadcn `Tabs` | ✓ |+| `NSplit` (EditorMain editor / AI pane) | Hoisted to `StandardPanel.vue` (stays Vue) | ✓ |+| `useEmitteryEventListener` (Vue composable) | `useEffect` + direct emittery `.on()` — pattern already used in `SchemaPane.tsx` | ✓ |+| `defineAsyncComponent(() => import("./SQLEditor.vue"))` | React lazy via `React.lazy()` + `<Suspense>` boundary | ✓ |++## 4. Architecture & phases++Three phases. Each is independently commit-able and gate-green.++### Phase 1 — `useExecuteSQL` portability + small leaves++**Files added:**+- React `UploadFileButton.tsx` + top-level shim (44 LOC)+- React `ContextMenu.tsx` + top-level shim (85 LOC) — small `DropdownMenu` wrapper around the context menu actions++**Refactor:**+- Verify `useExecuteSQL` is callable from React. If it currently uses+ Vue refs in its return shape, lift the body to a framework-neutral+ function and have the Vue composable be a thin wrapper. The React+ side gets a `useExecuteSQL` React hook that calls the same core.++**Caller swap:**+- `StandardPanel/SQLEditor.vue` line N: replace the Vue+ `<UploadFileButton />` import + render with+ `<ReactPageMount page="UploadFileButton" />` *before* migrating+ `SQLEditor.vue` itself, so the swap is incremental. (Optional —+ could also wait for Phase 3 since `SQLEditor` migrates there.)+- `ResultPanel.vue`: replace the Vue `<ContextMenu />` with+ `<ReactPageMount page="ContextMenu" />`.++**Deliverables:** ~3 `.tsx` + 2 mount shims + 2 tests.++### Phase 2 — `BatchQuerySelect` + `CompactSQLEditor`++**Files added:**+- React `BatchQuerySelect.tsx` + top-level shim (359 LOC). Uses+ shadcn `Tabs`; the close-tab action wires through to Pinia store+ helpers the Vue version already calls (`tabStore.removeTab`,+ `closeOtherBatchQueryItems`, etc.).+- React `CompactSQLEditor.tsx` + top-level shim (312 LOC). Wraps+ `MonacoEditor` with terminal-specific options (single-line, dark+ theme, no minimap, history nav keybindings).++**Caller swaps:**+- `ResultPanel.vue`: replace `<BatchQuerySelect />` with+ `<ReactPageMount page="BatchQuerySelect" />`.+- `TerminalPanel.vue`: replace the inline `<CompactSQLEditor>` inside+ the `v-for` loop with `<ReactPageMount page="CompactSQLEditor" :pageProps="{ ... }" />`.+ Per-query props (`content`, `readonly`, `onExecute`, `onHistory`,+ `onClearScreen`) flow through `pageProps`.++**Deliverables:** 2 `.tsx` + 2 mount shims + 2 tests + 2 caller swaps.++### Phase 3 — `SQLEditor` + `EditorMain`++**Files added:**+- React `SQLEditor.tsx` + top-level shim (401 LOC). Worksheet Monaco+ editor with autocomplete, multi-cursor, Ctrl+Enter execute,+ Cmd+S save, format-on-save, etc. Reuses the existing+ `MonacoEditor.tsx` for the editor instance.+- React `EditorMain.tsx` + top-level shim. Renders:+ - `<EditorAction>` (already React)+ - `<SQLEditor>` (just-migrated)+ - `<Welcome>` (already React) when `tab` is null+ - `<ExecutingHintModal>` + `<SaveSheetModal>` (already React, hidden mounts)+ No AI pane inside (hoisted — see below).++**AI pane hoist (mirrors Stage 16 pattern):**+- `StandardPanel.vue` wraps the React `EditorMain` in a horizontal+ `<NSplit>` when `showAIPanel`:+ ```html+ <NSplit+ v-if="showAIPanel"+ direction="horizontal"+ :size="editorPanelSize.size"+ ...+ >+ <template #1>+ <ReactPageMount page="EditorMain" />+ </template>+ <template #2>+ <Suspense>+ <AIChatToSQL key="ai-chat-to-sql" />+ </Suspense>+ </template>+ </NSplit>+ ```+- React `EditorMain.tsx` sets `uiStore.isShowingCode = true` on mount+ (same flag introduced in Stage 16) so `Panels.vue` doesn't+ *also* try to host the AI pane in CODE view (Panels.vue's gate is+ `view !== 'CODE'`, but we'll add the explicit+ `&& view !== 'CODE'` guard if it isn't there already).++**Caller swap:**+- `StandardPanel.vue`: replace `<EditorMain />` with+ `<ReactPageMount page="EditorMain" />` inside the new horizontal+ NSplit.++**Deliverables:** 2 `.tsx` + 2 mount shims + 2 tests + 1 caller swap ++small `StandardPanel.vue` refactor.++## 5. Per-phase checklist++### Phase 1 — Portability + leaves+- [x] `UploadFileButton.tsx` + shim (with chain: `SQLUploadButton.tsx` + `FileContentPreviewModal.tsx`)+- [x] Delete `StandardPanel/UploadFileButton.vue` + `components/misc/SQLUploadButton.vue` + `components/FileContentPreviewModal.vue`+- [x] Gates green+- [—] `useExecuteSQL` lift: not needed — the Vue composable's body is+ Pinia-store-driven. `reactive({})` and `markRaw()` are no-ops outside+ Vue's reactivity system; the React `EditorMain` calls+ `useExecuteSQL()` directly.+- [↗] `ContextMenu.tsx` migration deferred to the ResultPanel stage (see § 2.2).++### Phase 2 — CompactSQLEditor+- [x] `CompactSQLEditor.tsx` + shim+- [x] `TerminalPanel.vue` swaps `CompactSQLEditor` (per-query `pageProps` flow)+- [x] Delete `TerminalPanel/CompactSQLEditor.vue`+- [x] Gates green+- [↗] `BatchQuerySelect.tsx` deferred to the ResultPanel stage (see § 2.2).++### Phase 3 — SQLEditor + EditorMain+- [x] `SQLEditor.tsx` + shim (worksheet Monaco editor with Cmd+Enter run / Cmd+Shift+Enter run-in-new-tab / Cmd+S save / Cmd+E explain — engine-conditional / AI Monaco actions / format / append-content / set-selection / pendingInsertAtCaret)+- [x] `EditorMain.tsx` + shim (mounts `EditorAction`, `SQLEditor`, `Welcome`, hidden `ExecutingHintModal` + `SaveSheetModal`)+- [x] AI pane hoist landed in `StandardPanel.vue` (Vue `<NSplit>` + `<AIChatToSQL>` wrapping the React `EditorMain`)+- [x] `StandardPanel.vue` swaps `EditorMain` to `ReactPageMount`+- [x] Delete `StandardPanel/EditorMain.vue` + `StandardPanel/SQLEditor.vue`+- [x] Cross-framework `getActiveStatement`: replaced the Vue `defineExpose` ref API with a shared `activeStatementRef` shallowRef in `state.ts` — React `SQLEditor` writes via `onActiveContentChange`, Vue `EditorMain` (now React) reads it from the toolbar Run handler. Mirrors the existing `activeSQLEditorRef` pattern.+- [x] Gates green++## 6. Manual UX verification (after each phase)++- **Phase 1:** Upload a `.sql` file via the editor button; right-click+ a result tab → close / close-others / close-saved actions still+ work.+- **Phase 2:** Run a batch query against multiple databases → tab+ strip renders one tab per database, errors flagged, close-tab and+ keyboard nav (`⌘+W`, `⌘+⇧+W`) behave the same. Switch a tab to ADMIN+ mode → CompactSQLEditor renders dark, executes commands, history+ nav (Ctrl+P / Ctrl+N) works.+- **Phase 3:** WORKSHEET tab → run query (`⌘+Enter`); save sheet+ (`⌘+S`); format SQL; toggle AI panel (now hosted by Vue+ StandardPanel) → `AIChatToSQL` renders to the right; explain code+ via OpenAIButton or Monaco context menu. Welcome screen renders+ when no tab is connected.+- **All:** Switch between WORKSHEET and ADMIN tabs; tab key change+ doesn't leak Monaco instances; no stale event listeners.++## 7. Out of scope (deferred)++- `EditorCommon/ResultView/*` — the perf-sensitive VirtualDataTable.+ Final stage covers this together with the host shells.+- The five host shells (`Panels.vue`, `StandardPanel.vue`,+ `TerminalPanel.vue`, `ResultPanel.vue`, `EditorPanel.vue`) — they+ each transitively host a Vue ResultView descendant; migrating them+ before ResultView would force a React→Vue mount bridge.+- `DiagramPanel.vue` — cytoscape; separate stage.+- `SQLEditorHomePage.vue` — depends on EditorPanel; final stage.+- **`ResultPanel/BatchQuerySelect.vue` + `ResultPanel/ContextMenu.vue`**+ — moved out of Stage 17 mid-stage. `BatchQuerySelect` would require+ porting `DataExportButton.vue` (414 LOC of drawer + form-slot ++ multi-file zip download flow with no React equivalent) and+ extending the React `DatabaseTable` with a pre-fetched-list opt-out+ path; `ContextMenu` is coupled to it via an imperative `ref.show()`+ API. Both naturally co-migrate with `ResultPanel.vue`'s host shell,+ so they roll into the ResultPanel stage rather than expanding+ Stage 17's scope. See § 2.2.++## 8. Risks & open questions++- **`useExecuteSQL` portability.** The Vue composable returns Vue+ refs (loading state, etc.) and uses `watch`/`computed`. Likely+ needs a React-friendly variant. **Mitigation:** if the body is+ pure Pinia + emittery, lift it to a JS function and wrap with a+ React `useState` hook — same pattern as `useAIActions`. If it has+ heavier Vue lifecycle ties, defer the React `EditorMain` for one+ phase and stub a thin event-driven wrapper instead.++- **Async SQLEditor mount.** Vue uses `defineAsyncComponent` to+ lazy-load `SQLEditor.vue`. The React lazy equivalent is+ `React.lazy()` + Suspense boundary. The mount registry already+ lazy-loads via `import.meta.glob`, so a top-level `SQLEditor.tsx`+ shim is automatically lazy. **No new infrastructure needed.**++- **AI pane hoist behavior change.** Today AI pane is inside+ `EditorMain.vue` (next to SQLEditor). After hoist it's inside+ `StandardPanel.vue` (sibling of EditorMain). Layout-wise identical;+ but the hoist creates an extra NSplit boundary. Confirm+ `editorPanelSize` resize math still works — it should, since the+ same Pinia store drives both.++- **Terminal mode `Suspense` per-row.** Vue wraps each+ `CompactSQLEditor` in `<Suspense>` because of its async mount.+ React equivalent: each `<ReactPageMount>` is its own React root,+ so each row is independently mounted. **Pre-existing behavior.**++- **Cross-mount key stability in TerminalPanel loop.** Today Vue+ re-mounts when `query.id` changes. We need to pass `:key="query.id"`+ to `ReactPageMount` and confirm the underlying React root unmounts+ cleanly. **Verify in Phase 2.**++- **`pageProps` for terminal queries.** Each terminal-mode+ `CompactSQLEditor` mount needs the per-query+ `{ content, readonly, onExecute, onHistory, onClearScreen }`. The+ existing `ReactPageMount` `pageProps` mechanism already supports+ this. Vue→React event handlers are normal function props.++- **History keybindings (Ctrl+P / Ctrl+N).** Vue version registers+ Monaco actions for history navigation. Same pattern as Stage 16's+ `useAIActions` — register `editor.addAction` in a `useEffect`.++## 9. Outcomes (2026-04-27)++**Migrated:** `SQLEditor.vue`, `EditorMain.vue`, `UploadFileButton.vue`,+`SQLUploadButton.vue` (chain), `FileContentPreviewModal.vue` (chain),+`CompactSQLEditor.vue` — ~960 LOC of Vue→React.++**Vue surface remaining inside `EditorPanel/`:** `EditorPanel.vue`+(host), `Panels/Panels.vue` (host with `AIChatToSQL`),+`Panels/DiagramPanel/*` (cytoscape, deferred), `StandardPanel.vue`+(host with AI pane hoist), `TerminalPanel.vue` (host),+`ResultPanel/*` (host + `BatchQuerySelect` + `ContextMenu` ++`DatabaseQueryContext`).++**Architectural decisions:**++1. **`useExecuteSQL` reused as-is.** The Vue composable's body is+ Pinia-store-driven; `reactive({})` and `markRaw()` are no-ops+ outside Vue's reactivity system. The React `EditorMain` calls it+ directly — no port required.+2. **`activeStatementRef` shallowRef bridge.** When the toolbar+ Run button fires from React, it can't access the previous Vue+ `sqlEditorRef.value?.getActiveStatement()` because `ReactPageMount`+ doesn't pass refs across frameworks. Added a module-level+ `shallowRef<string>` in `state.ts` (parallel to the existing+ `activeSQLEditorRef`); React `SQLEditor` writes via+ `onActiveContentChange`; Vue / React readers consume `.value`.+3. **AI pane hoisted to `StandardPanel.vue`.** `AIChatToSQL` is+ Vue-only; embedding it in React `EditorMain` would force a+ React→Vue mount bridge. The Vue `<NSplit>` + `<AIChatToSQL>`+ moved one level up so the React panel only owns the editor+ surface — same pattern Stage 16 applied to the schema-object+ panels.+4. **i18n parity.** 3 missing React-locale keys synced from Vue+ (`common.preview`, `sql-editor.select-encoding`,+ `sql-editor.upload-file`).++**Validation:** `pnpm fix` / `pnpm check` / `pnpm type-check` all+green. 285 React tests passing.++**Rolls into next stage:** `BatchQuerySelect.vue` + `ContextMenu.vue`+(see § 7).diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.tsindex 6c82d5f3e0..0c899af298 100644--- a/frontend/src/plugins/ai/logic/useChatByTab.ts+++ b/frontend/src/plugins/ai/logic/useChatByTab.ts@@ -49,8 +49,15 @@ export const useChatByTab = () => {return chat;};+ const emptyChat: AIChatInfo = {+ list: ref([]),+ ready: ref(false),+ selected: ref(undefined),+ };+return computed(() => {- const tab = useSQLEditorTabStore().currentTab!;+ const tab = useSQLEditorTabStore().currentTab;+ if (!tab) return emptyChat;return getChatByTab(tab);});};diff --git a/frontend/src/react/components/monaco/MonacoEditor.tsx b/frontend/src/react/components/monaco/MonacoEditor.tsxindex a332f832c6..2dab62f44f 100644--- a/frontend/src/react/components/monaco/MonacoEditor.tsx+++ b/frontend/src/react/components/monaco/MonacoEditor.tsx@@ -22,6 +22,7 @@ import {import { batchConvertPositionToMonacoPosition } from "@/utils/v1/position";import {createMonacoEditor,+ getResolvedTheme,loadMonacoEditor,setMonacoModelLanguage,} from "./core";@@ -61,6 +62,15 @@ export interface MonacoEditorProps {advices?: AdviceOption[];autoCompleteContext?: AutoCompleteContext;autoFocus?: boolean;+ /**+ * When `true` (default), the editor's height grows with content,+ * clamped to `[min, max]`. When `false`, the inner editor container+ * fills its parent's height (`h-full`) and `min`/`max` are ignored.+ * Use the parent-fill mode for surfaces like the worksheet+ * `SQLEditor`, where the editor is expected to occupy the full+ * height of an `NSplit`/flex column.+ */+ autoHeight?: boolean;className?: string;content: string;cornerPrefix?: ReactNode;@@ -87,6 +97,7 @@ export function MonacoEditor({advices = [],autoCompleteContext,autoFocus = false,+ autoHeight = true,className = "",content,cornerPrefix,@@ -254,6 +265,19 @@ export function MonacoEditor({editorRef.current = editor;const monaco = await loadMonacoEditor();+ // Re-apply the editor's intended theme after construction.+ // Monaco's theme is global — when a previous editor was+ // constructed with a different theme (e.g. CompactSQLEditor's+ // `vs-dark` for admin mode), that theme persists across editor+ // disposal. If the new editor's requested theme isn't+ // registered (the custom `bb` theme is silently swallowed by+ // the vscode-api theme service override in some runtime modes+ // — see `initializeTheme` in core.ts), `setTheme` becomes a+ // no-op and the dark theme stays stuck.+ // `getResolvedTheme` returns the requested theme if it's known+ // to be registered, otherwise falls back to the always-available+ // built-in `vs`.+ monaco.editor.setTheme(getResolvedTheme(optionsRef.current?.theme));const model = await getOrCreateTextModel(generatedFilename,contentRef.current,@@ -359,8 +383,15 @@ export function MonacoEditor({modelRef.current = null;host.remove();};+ // `autoCompleteContext` is intentionally NOT a dep here — its value+ // is consumed by the dedicated `setMetadata` effect below. Keeping+ // it in the dep array forced an editor dispose+recreate on every+ // connection-state hydration, and the new editor lost its LSP+ // metadata because the metadata effect didn't re-fire (the context+ // reference itself was stable across the recreation). Only+ // `shouldEnableLSP` (boolean) is needed here to drive the WS+ // initialization at mount time.}, [- autoCompleteContext,autoFocus,dialect,enableDecorations,@@ -444,14 +475,30 @@ export function MonacoEditor({};}, [lineHighlights]);+ // LSP `setMetadata` — must run *after* the editor + its model are+ // attached so the language server has a document to bind the+ // metadata to. We gate on `ready`, which the big editor effect+ // flips true once `editor.setModel(model)` has run. Mirrors Vue's+ // `useAutoComplete` call site, which lives inside the post-setup+ // path of `MonacoTextModelEditor.vue`.+ //+ // Skipped entirely when the caller does not opt in to SQL LSP via+ // `autoCompleteContext`, so editors like `SchemaEditorLite` that mount+ // a writable Monaco for plain text editing don't initialize the LSP+ // client or send empty `setMetadata` traffic.useEffect(() => {- if (readOnly || !autoCompleteContext) return;+ if (readOnly || !ready) return;const ctx = autoCompleteContext;- const params = {+ if (!ctx) return;+ const params: {+ instanceId: string;+ databaseName: string;+ scene?: string;+ schema?: string;+ } = {instanceId: "",databaseName: "",scene: ctx.scene,- schema: ctx.schema,};const instance = extractInstanceResourceName(ctx.instance);if (instance && instance !== String(UNKNOWN_ID)) {@@ -461,6 +508,9 @@ export function MonacoEditor({if (databaseName && databaseName !== String(UNKNOWN_ID)) {params.databaseName = databaseName;}+ if (ctx.schema !== undefined) {+ params.schema = ctx.schema;+ }const apply = debounce(async () => {const client = await initializeLSPClient();await executeCommand(client, "setMetadata", [params]);@@ -469,16 +519,22 @@ export function MonacoEditor({return () => {apply.cancel();};- }, [autoCompleteContext, readOnly]);+ }, [autoCompleteContext, readOnly, ready]);const height = clampMeasuredHeight(contentHeight);return (- <div className={cn("relative", className)}>+ <div className={cn("relative", autoHeight ? "" : "h-full", className)}><divref={containerRef}- className={cn("w-full overflow-clip rounded-md border text-sm")}- style={{ height }}+ className={cn(+ "w-full overflow-clip text-sm",+ // Match Vue's `bb-monaco-editor` — flush against the host+ // shell with no border or rounded corners. Consumers that+ // want a chrome can wrap the component themselves.+ autoHeight ? "" : "h-full"+ )}+ style={autoHeight ? { height } : undefined}/>{!ready && (<div className="absolute inset-0 flex items-center justify-center rounded-md border bg-background/70">diff --git a/frontend/src/react/components/monaco/ReadonlyMonaco.tsx b/frontend/src/react/components/monaco/ReadonlyMonaco.tsxindex d9d5b090d5..81bff8607f 100644--- a/frontend/src/react/components/monaco/ReadonlyMonaco.tsx+++ b/frontend/src/react/components/monaco/ReadonlyMonaco.tsx@@ -10,6 +10,7 @@ import type {export interface ReadonlyMonacoProps {advices?: AdviceOption[];+ autoHeight?: boolean;content: string;className?: string;filename?: string;@@ -26,6 +27,7 @@ export interface ReadonlyMonacoProps {export function ReadonlyMonaco({advices = [],+ autoHeight = true,content,className = "",filename,@@ -39,6 +41,7 @@ export function ReadonlyMonaco({return (<MonacoEditoradvices={advices}+ autoHeight={autoHeight}className={className}content={content}filename={filename}diff --git a/frontend/src/react/components/monaco/core.ts b/frontend/src/react/components/monaco/core.tsindex 3823d848cb..cf6bd07f0b 100644--- a/frontend/src/react/components/monaco/core.ts+++ b/frontend/src/react/components/monaco/core.ts@@ -13,6 +13,7 @@ export const MonacoEditorReady = monacoEditorReadyDefer.promise;const state = {themeInitialized: false,+ registeredThemes: new Set<string>(["vs", "vs-dark", "hc-black", "hc-light"]),};const initializeTheme = () => {@@ -21,13 +22,35 @@ const initializeTheme = () => {if (!monacoModule) return;try {monacoModule.editor.defineTheme("bb", getBBTheme());+ state.registeredThemes.add("bb");monacoModule.editor.defineTheme("bb-dark", getBBDarkTheme());+ state.registeredThemes.add("bb-dark");} catch {// The VSCode theme service override owns themes in some runtime modes.- // Fall back to the default theme instead of failing editor creation.+ // Whichever theme failed stays out of `state.registeredThemes`, so+ // `getResolvedTheme` will fall back to the built-in `vs` for it.}};+/**+ * Returns the requested theme if it's known to be registered with+ * Monaco, otherwise falls back to the always-available built-in `vs`.+ *+ * Use this anywhere `monaco.editor.setTheme(...)` is called from+ * application code — calling `setTheme` with an unregistered theme+ * name is a silent no-op, which leaves the global theme stuck on+ * whatever was last applied (and Monaco's theme is global, not+ * per-instance, so a stale `vs-dark` from a recently-disposed+ * terminal editor can bleed into a freshly-mounted worksheet editor).+ */+export const getResolvedTheme = (requested?: string): string => {+ const fallback = "vs";+ if (!requested) {+ return state.registeredThemes.has("bb") ? "bb" : fallback;+ }+ return state.registeredThemes.has(requested) ? requested : fallback;+};+const initialize = async () => {await initializeMonacoServices();await loadMonacoEditor();diff --git a/frontend/src/react/components/sql-editor/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/CompactSQLEditor.tsxnew file mode 100644index 0000000000..5748793959--- /dev/null+++ b/frontend/src/react/components/sql-editor/CompactSQLEditor.tsx@@ -0,0 +1 @@+export { CompactSQLEditor } from "./TerminalPanel/CompactSQLEditor";diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsxindex 477a585568..622252fee2 100644--- a/frontend/src/react/components/sql-editor/EditorAction.tsx+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx@@ -140,8 +140,7 @@ export function EditorAction({ onExecute }: Props) {{isAdminMode && (<Buttonvariant="outline"- size="sm"- className="h-7 px-1.5 gap-1 border-dashed"+ className="h-8 px-1.5 gap-1 border-dashed text-sm"onClick={(e) => {e.stopPropagation();exitAdminMode();diff --git a/frontend/src/react/components/sql-editor/EditorMain.tsx b/frontend/src/react/components/sql-editor/EditorMain.tsxnew file mode 100644index 0000000000..ffc582a695--- /dev/null+++ b/frontend/src/react/components/sql-editor/EditorMain.tsx@@ -0,0 +1 @@+export { EditorMain } from "./StandardPanel/EditorMain";diff --git a/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx b/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsxindex 0e8d162e19..886d629330 100644--- a/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx@@ -198,6 +198,7 @@ export function CodeViewer({<div className="flex-1 min-h-0 flex flex-col overflow-hidden">{contentPrefix}<ReadonlyMonaco+ autoHeight={false}content={content}className="flex-1 w-full h-full relative"options={{ automaticLayout: true }}diff --git a/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx b/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsxindex 7e5de3b8bc..50ec8ddf85 100644--- a/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx@@ -116,6 +116,7 @@ export function DefinitionViewer({return (<ReadonlyMonaco+ autoHeight={false}content={content}className="w-full h-full relative"options={{ automaticLayout: true }}diff --git a/frontend/src/react/components/sql-editor/SQLEditor.tsx b/frontend/src/react/components/sql-editor/SQLEditor.tsxnew file mode 100644index 0000000000..b96bd1c2c3--- /dev/null+++ b/frontend/src/react/components/sql-editor/SQLEditor.tsx@@ -0,0 +1 @@+export { SQLEditor } from "./StandardPanel/SQLEditor";diff --git a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsxnew file mode 100644index 0000000000..eacb50f14f--- /dev/null+++ b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx@@ -0,0 +1,139 @@+import { useCallback, useEffect } from "react";+import { useExecuteSQL } from "@/composables/useExecuteSQL";+import { ReadonlyModeNotSupported } from "@/react/components/sql-editor/ReadonlyModeNotSupported";+import { useVueState } from "@/react/hooks/useVueState";+import {+ useConnectionOfCurrentSQLEditorTab,+ useDatabaseV1Store,+ useSQLEditorTabStore,+} from "@/store";+import type { SQLEditorQueryParams } from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";+import { activeStatementRef } from "@/views/sql-editor/EditorPanel/StandardPanel/state";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { EditorAction } from "../EditorAction";+import { ExecutingHintModal } from "../ExecutingHintModal";+import { SaveSheetModal } from "../SaveSheetModal";+import { Welcome } from "../Welcome";+import { SQLEditor } from "./SQLEditor";++interface EditorMainProps {+ /** Open the connection drawer (hosted by SQLEditorHomePage). */+ onChangeConnection: () => void;+}++/**+ * React port of `frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue`.+ *+ * Worksheet shell:+ * - Top toolbar (`EditorAction`, already React)+ * - Body: `SQLEditor` when there's a tab, `Welcome` otherwise+ * - Two hidden React modal mounts (`ExecutingHintModal`, `SaveSheetModal`)+ *+ * AI side pane has been hoisted to `StandardPanel.vue` (Vue host) so+ * the cross-framework boundary stays clean — see Stage 17 design.+ *+ * Calls the existing Vue `useExecuteSQL` composable directly: its body+ * is Pinia-store-driven and the only Vue-specific bits (`reactive`,+ * `markRaw`) behave as no-ops outside Vue's reactivity system.+ */+export function EditorMain({ onChangeConnection }: EditorMainProps) {+ const tabStore = useSQLEditorTabStore();+ const databaseStore = useDatabaseV1Store();+ const { instance } = useConnectionOfCurrentSQLEditorTab();++ const tabId = useVueState(() => tabStore.currentTab?.id);+ const isDisconnected = useVueState(() => tabStore.isDisconnected);+ const engine = useVueState(() => instance.value.engine);++ const allowReadonlyMode =+ !isDisconnected && instanceV1HasReadonlyMode(engine ?? Engine.MYSQL);++ const { execute } = useExecuteSQL();++ const handleExecute = useCallback(+ ({ params, newTab }: { params: SQLEditorQueryParams; newTab: boolean }) => {+ if (newTab) {+ tabStore.cloneTab(tabStore.currentTabId, {+ statement: params.statement,+ });+ }+ requestAnimationFrame(() => {+ void execute(params);+ });+ },+ [tabStore, execute]+ );++ // Run-from-toolbar: pull the active statement that the React+ // `SQLEditor` published to the shared shallowRef.+ const handleExecuteFromActionBar = useCallback(+ (params: SQLEditorQueryParams) => {+ const tab = tabStore.currentTab;+ if (!tab) return;+ const statement =+ activeStatementRef.value || tab.statement || params.statement;+ handleExecute({ params: { ...params, statement }, newTab: false });+ },+ [tabStore, handleExecute]+ );++ // execute-sql event (fired e.g. from the schema-pane "run" affordance)+ useEffect(() => {+ const off = sqlEditorEvents.on(+ "execute-sql",+ async ({ connection, statement, batchQueryContext }) => {+ const database = await databaseStore.getOrFetchDatabaseByName(+ connection.database+ );+ const newTab = tabStore.addTab(+ { connection, statement, batchQueryContext },+ /* beside */ true+ );+ requestAnimationFrame(() => {+ void execute({+ connection: { ...newTab.connection },+ statement,+ engine: getInstanceResource(database).engine,+ explain: false,+ selection: null,+ });+ });+ }+ );+ return () => {+ off();+ };+ }, [databaseStore, tabStore, execute]);++ if (!isDisconnected && !allowReadonlyMode) {+ // Connected to an instance without a read-only data source —+ // surface the admin-mode CTA, matching Vue `EditorMain.vue`'s+ // `<ReactPageMount v-else page="ReadonlyModeNotSupported" />` branch.+ return <ReadonlyModeNotSupported />;+ }++ return (+ <div className="h-full flex flex-col overflow-hidden">+ <EditorAction onExecute={handleExecuteFromActionBar} />+ {tabId ? (+ <div className="flex-1 min-h-0">+ <SQLEditor+ onExecute={(params, newTab) => handleExecute({ params, newTab })}+ />+ </div>+ ) : (+ <div className="flex-1 flex flex-col min-h-0">+ <Welcome onChangeConnection={onChangeConnection} />+ </div>+ )}+ {/* Hidden React modal mounts — their Dialogs portal to overlay+ layer; the inline mounts must not occupy flex space. */}+ <div className="hidden">+ <ExecutingHintModal />+ <SaveSheetModal />+ </div>+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx b/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsxnew file mode 100644index 0000000000..e70f307e54--- /dev/null+++ b/frontend/src/react/components/sql-editor/StandardPanel/FileContentPreviewModal.tsx@@ -0,0 +1,123 @@+import { Loader2 } from "lucide-react";+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { ReadonlyMonaco } from "@/react/components/monaco/ReadonlyMonaco";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/react/components/ui/select";+import { pushNotification } from "@/store";+import { ENCODINGS, type Encoding, readFileAsArrayBuffer } from "@/utils";++interface FileContentPreviewModalProps {+ file: File;+ open: boolean;+ onCancel: () => void;+ onConfirm: (text: string) => void;+}++/**+ * React port of `frontend/src/components/FileContentPreviewModal.vue`.+ * Decodes the file as bytes, exposes an encoding picker, renders the+ * decoded text in a read-only Monaco preview, and emits the chosen+ * statement back to the caller on confirm.+ */+export function FileContentPreviewModal({+ file,+ open,+ onCancel,+ onConfirm,+}: FileContentPreviewModalProps) {+ const { t } = useTranslation();+ const [encoding, setEncoding] = useState<Encoding>("utf-8");+ const [decodedText, setDecodedText] = useState("");+ const [isLoading, setIsLoading] = useState(true);++ useEffect(() => {+ let cancelled = false;+ setIsLoading(true);+ void readFileAsArrayBuffer(file)+ .then(({ arrayBuffer }) => {+ if (cancelled) return;+ const text = new TextDecoder(encoding).decode(arrayBuffer);+ setDecodedText(text);+ })+ .catch((error) => {+ if (cancelled) return;+ console.error(error);+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: "Failed to read file",+ });+ })+ .finally(() => {+ if (cancelled) return;+ setIsLoading(false);+ });+ return () => {+ cancelled = true;+ };+ }, [file, encoding]);++ return (+ <Dialog open={open} onOpenChange={(next) => !next && onCancel()}>+ <DialogContent className="w-[36rem] max-w-[36rem]">+ <DialogTitle>{t("common.preview")}</DialogTitle>+ <div className="py-1 flex flex-col justify-start items-start gap-2">+ <div className="w-full flex flex-row justify-between items-center gap-4">+ <p className="font-medium textlabel whitespace-nowrap">+ {t("sql-editor.select-encoding")}+ </p>+ <Select+ value={encoding}+ onValueChange={(value) => {+ if (typeof value === "string") setEncoding(value as Encoding);+ }}+ >+ <SelectTrigger size="sm" className="w-auto">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {ENCODINGS.map((option) => (+ <SelectItem key={option} value={option}>+ {option}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="w-full overflow-hidden relative h-80 shrink-0 border border-control-border rounded-xs">+ <ReadonlyMonaco content={decodedText} className="w-full h-full" />+ {isLoading ? (+ <div className="absolute inset-0 bg-background/60 flex items-center justify-center">+ <Loader2 className="size-6 animate-spin text-control-light" />+ </div>+ ) : null}+ </div>+ <div className="w-full flex justify-end gap-x-2">+ <Button variant="outline" onClick={onCancel}>+ {t("common.cancel")}+ </Button>+ <Button+ variant="default"+ disabled={isLoading}+ onClick={() => onConfirm(decodedText)}+ >+ {t("common.confirm")}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsxnew file mode 100644index 0000000000..ad628dddec--- /dev/null+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx@@ -0,0 +1,455 @@+import type { IDisposable, IRange } from "monaco-editor";+import * as monaco from "monaco-editor";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { v1 as uuidv1 } from "uuid";+import type {+ IStandaloneCodeEditor,+ MonacoModule,+ Selection as MonacoSelection,+} from "@/components/MonacoEditor";+import {+ extensionNameOfLanguage,+ formatEditorContent,+} from "@/components/MonacoEditor/utils";+import { aiContextEvents } from "@/plugins/ai/logic";+import * as promptUtils from "@/plugins/ai/logic/prompt";+import type { ChatAction } from "@/plugins/ai/types";+import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";+import { useVueState } from "@/react/hooks/useVueState";+import {+ useConnectionOfCurrentSQLEditorTab,+ useSQLEditorTabStore,+ useSQLEditorUIStore,+ useUIStateStore,+ useWorkSheetAndTabStore,+} from "@/store";+import {+ dialectOfEngineV1,+ isValidDatabaseName,+ type SQLEditorQueryParams,+} from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { languageOfEngineV1 } from "@/types/sqlEditor/editor";+import { instanceV1AllowsExplain, nextAnimationFrame } from "@/utils";+import {+ activeSQLEditorRef,+ activeStatementRef,+} from "@/views/sql-editor/EditorPanel/StandardPanel/state";+import { sqlEditorEvents } from "@/views/sql-editor/events";+import { useAIActions } from "../Panels/common/useAIActions";+import { UploadFileButton } from "./UploadFileButton";++const AI_ACTIONS: readonly ChatAction[] = [+ "explain-code",+ "find-problems",+ "new-chat",+];++interface SQLEditorProps {+ onExecute: (params: SQLEditorQueryParams, newTab: boolean) => void;+}++/**+ * React port of `frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue`.+ *+ * Worksheet Monaco editor with full keybinding parity:+ * - Cmd+Enter run / Cmd+Shift+Enter run-in-new-tab+ * - Cmd+S save sheet+ * - Cmd+E explain (or "Dry Run" for BigQuery)+ * - AI right-click actions (explain-code / find-problems / new-chat)+ *+ * Listens to `sqlEditorEvents` for `format-content`,+ * `set-editor-selection`, `append-editor-content`. The active editor+ * instance is published to `activeSQLEditorRef` (Vue `shallowRef`+ * singleton) so the legacy ResultView's ErrorView keeps working.+ *+ * Exposes `getActiveStatement` via `useImperativeHandle` so EditorMain+ * (parent) can read the active selection or full statement when a query+ * is run from the toolbar.+ */+export function SQLEditor({ onExecute }: SQLEditorProps) {+ const tabStore = useSQLEditorTabStore();+ const sheetAndTabStore = useWorkSheetAndTabStore();+ const uiStateStore = useUIStateStore();+ const sqlEditorUIStore = useSQLEditorUIStore();+ const { instance, database } = useConnectionOfCurrentSQLEditorTab();++ const tabId = useVueState(() => tabStore.currentTab?.id);+ const content = useVueState(() => tabStore.currentTab?.statement ?? "");+ const readonly = useVueState(() => sheetAndTabStore.isReadOnly);+ const engine = useVueState(() => instance.value.engine);+ const instanceName = useVueState(() => instance.value.name);+ const databaseName = useVueState(() => database.value.name);+ const schema = useVueState(() => tabStore.currentTab?.connection.schema, {+ deep: true,+ });++ const language = useMemo(+ () => languageOfEngineV1(engine ?? Engine.MYSQL),+ [engine]+ );+ const dialect = useMemo(+ () => dialectOfEngineV1(engine ?? Engine.MYSQL),+ [engine]+ );++ const filename = useMemo(() => {+ const name = tabId || uuidv1();+ const ext = extensionNameOfLanguage(language);+ return `${name}.${ext}`;+ }, [tabId, language]);++ // Clear the stale active statement when switching tabs so the toolbar+ // doesn't execute the previous tab's SQL against the new connection.+ useEffect(() => {+ activeStatementRef.value = "";+ }, [tabId]);++ // ----- live refs -----+ // State-backed so useAIActions re-runs when Monaco is ready.+ const [monacoState, setMonacoState] = useState<MonacoModule | null>(null);+ const [editorState, setEditorState] = useState<IStandaloneCodeEditor | null>(+ null+ );+ const editorRef = useRef<IStandaloneCodeEditor | null>(null);+ const monacoRef = useRef<MonacoModule | null>(null);+ const activeContentRef = useRef<string>(content ?? "");+ activeContentRef.current = content ?? "";+ const onExecuteRef = useRef(onExecute);+ onExecuteRef.current = onExecute;+ const engineRef = useRef(engine);+ engineRef.current = engine;+ const dialectRef = useRef(dialect);+ dialectRef.current = dialect;++ // Publish the live "active statement" — Monaco's delimited+ // statement under the cursor, or the full content as fallback —+ // to the module-level shared ref so the Vue EditorMain toolbar+ // can read it without a React ref.+ const handleActiveContentChange = useCallback((value: string) => {+ activeStatementRef.value = value;+ }, []);++ const getActiveStatement = useCallback(() => {+ return activeStatementRef.value || tabStore.currentTab?.statement || "";+ }, [tabStore]);++ // ----- statement sync -----+ const handleChange = useCallback(+ (value: string) => {+ const tab = tabStore.currentTab;+ if (!tab || value === tab.statement) return;+ tabStore.updateCurrentTab({ statement: value, status: "DIRTY" });+ },+ [tabStore]+ );++ const handleSelectContent = useCallback(+ (value: string) => {+ tabStore.updateCurrentTab({ selectedStatement: value });+ },+ [tabStore]+ );++ // Guard flag so the Vue→Monaco selection watcher below doesn't fire+ // when the change came from the editor itself (would interrupt+ // mouse-drag word selection).+ const selectionFromEditorRef = useRef(false);++ const handleSelectionChange = useCallback(+ (selection: MonacoSelection | null) => {+ const tab = tabStore.currentTab;+ if (!tab) return;+ selectionFromEditorRef.current = true;+ tabStore.updateCurrentTab({ editorState: { selection } });+ },+ [tabStore]+ );++ // Watch tab.editorState.selection — if it changes and the change+ // wasn't driven by the editor itself, push it back into Monaco.+ const tabSelectionString = useVueState(+ () => tabStore.currentTab?.editorState.selection?.toString(),+ { deep: true }+ );+ useEffect(() => {+ if (selectionFromEditorRef.current) {+ selectionFromEditorRef.current = false;+ return;+ }+ const selection = tabStore.currentTab?.editorState.selection;+ if (!selection) return;+ activeSQLEditorRef.value?.setSelection(selection);+ }, [tabSelectionString, tabStore]);++ // ----- save handler (just emits the event so SaveSheetModal opens) -----+ const handleSaveSheet = useCallback(() => {+ const tab = tabStore.currentTab;+ if (!tab) return;+ void sqlEditorEvents.emit("save-sheet", { tab });+ }, [tabStore]);++ // ----- run query -----+ const runQueryAction = useCallback(+ ({ explain, newTab }: { explain: boolean; newTab: boolean }) => {+ const tab = tabStore.currentTab;+ if (!tab) return;+ const statement = getActiveStatement();+ const params: SQLEditorQueryParams = {+ connection: { ...tab.connection },+ statement,+ engine: engineRef.current ?? Engine.MYSQL,+ explain,+ selection: newTab ? null : tab.editorState.selection,+ };+ onExecuteRef.current(params, newTab);+ uiStateStore.saveIntroStateByKey({+ key: "data.query",+ newState: true,+ });+ },+ [tabStore, getActiveStatement, uiStateStore]+ );++ // ----- onReady: register Monaco actions + commands -----+ const handleReady = useCallback(+ (m: MonacoModule, editor: IStandaloneCodeEditor) => {+ monacoRef.current = m;+ editorRef.current = editor;+ setMonacoState(m);+ setEditorState(editor);+ activeSQLEditorRef.value = editor;++ editor.addAction({+ id: "RunQuery",+ label: "Run Query",+ keybindings: [m.KeyMod.CtrlCmd | m.KeyCode.Enter],+ contextMenuGroupId: "operation",+ contextMenuOrder: 1,+ run: () => runQueryAction({ explain: false, newTab: false }),+ });+ editor.addAction({+ id: "RunQueryInNewTab",+ label: "Run Query in New Tab",+ keybindings: [m.KeyMod.CtrlCmd | m.KeyMod.Shift | m.KeyCode.Enter],+ contextMenuGroupId: "operation",+ contextMenuOrder: 1,+ run: () => runQueryAction({ explain: false, newTab: true }),+ });+ // Save command — fire-and-forget; lives with the editor.+ editor.addCommand(m.KeyMod.CtrlCmd | m.KeyCode.KeyS, handleSaveSheet);+ },+ [runQueryAction, handleSaveSheet]+ );++ // ----- AI Monaco actions (explain-code / find-problems / new-chat) -----+ const handleAIAction = useCallback(+ (action: ChatAction) => {+ const newChat = !sqlEditorUIStore.showAIPanel;+ sqlEditorUIStore.showAIPanel = true;+ const statement = getActiveStatement();+ if (!statement) return;+ const tab = tabStore.currentTab;+ const eng = engineRef.current ?? Engine.MYSQL;+ void nextAnimationFrame().then(() => {+ if (action === "explain-code") {+ void aiContextEvents.emit("send-chat", {+ content: promptUtils.explainCode(statement, eng),+ newChat,+ });+ } else if (action === "find-problems") {+ void aiContextEvents.emit("send-chat", {+ content: promptUtils.findProblems(statement, eng),+ newChat,+ });+ } else if (action === "new-chat") {+ const selected = tab?.selectedStatement ?? "";+ if (!selected) return;+ void aiContextEvents.emit("new-conversation", {+ input: ["", promptUtils.wrapStatementMarkdown(selected)].join("\n"),+ });+ }+ });+ },+ [sqlEditorUIStore, getActiveStatement, tabStore]+ );++ useAIActions({+ monaco: monacoState,+ editor: editorState,+ actions: AI_ACTIONS,+ callback: handleAIAction,+ });++ // ----- ExplainQuery action (engine-conditional) -----+ const explainActionRef = useRef<IDisposable | null>(null);+ useEffect(() => {+ const editor = editorRef.current;+ const m = monacoRef.current;+ if (!editor || !m || engine === undefined) return;+ explainActionRef.current?.dispose();+ explainActionRef.current = null;++ const allows =+ instanceV1AllowsExplain(engine) || engine === Engine.BIGQUERY;+ if (!allows) return;+ const isBigQuery = engine === Engine.BIGQUERY;+ const action = editor.addAction({+ id: "ExplainQuery",+ label: isBigQuery ? "Dry Run Query" : "Explain Query",+ keybindings: [m.KeyMod.CtrlCmd | m.KeyCode.KeyE],+ contextMenuGroupId: "operation",+ contextMenuOrder: 0,+ run: () => runQueryAction({ explain: true, newTab: false }),+ });+ explainActionRef.current = action;+ return () => {+ action.dispose();+ explainActionRef.current = null;+ };+ }, [engine, runQueryAction]);++ // ----- pendingInsertAtCaret -----+ const pendingInsertAtCaret = useVueState(+ () => sqlEditorUIStore.pendingInsertAtCaret+ );+ useEffect(() => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ const text = pendingInsertAtCaret;+ if (!text) return;+ sqlEditorUIStore.pendingInsertAtCaret = undefined;++ requestAnimationFrame(() => {+ const selection = editor.getSelection();+ const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;+ const range =+ selection ??+ new monaco.Range(maxLineNumber + 1, 1, maxLineNumber + 1, 1);+ editor.executeEdits("bb.event.insert-at-caret", [+ { forceMoveMarkers: true, text, range },+ ]);+ editor.focus();+ editor.revealLine(range.startLineNumber);+ });+ }, [pendingInsertAtCaret, sqlEditorUIStore]);++ // ----- file upload (triggered by UploadFileButton in cornerPrefix) -----+ const handleUploadFile = useCallback(+ (uploaded: string) => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ const tab = tabStore.currentTab;+ if (!tab) return;+ let text = uploaded;+ if (tab.statement.trim() !== "") {+ text = "\n" + text;+ }+ const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;+ editor.executeEdits("bb.event.upload-file", [+ {+ forceMoveMarkers: true,+ text,+ range: {+ startLineNumber: maxLineNumber + 1,+ startColumn: 1,+ endLineNumber: maxLineNumber + 1,+ endColumn: 1,+ },+ },+ ]);+ const newMaxLineNumber = editor.getModel()?.getLineCount() ?? 0;+ editor.revealLine(newMaxLineNumber);+ },+ [tabStore]+ );++ // ----- event listeners (sqlEditorEvents) -----+ useEffect(() => {+ const offFormat = sqlEditorEvents.on("format-content", () => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ void formatEditorContent(editor, dialectRef.current);+ });+ const offSetSelection = sqlEditorEvents.on(+ "set-editor-selection",+ (selection: IRange) => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ editor.setSelection(selection);+ editor.revealLineNearTop(selection.startLineNumber);+ editor.focus();+ }+ );+ const offAppend = sqlEditorEvents.on(+ "append-editor-content",+ ({ content: appended, select }) => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ const oldStatement = tabStore.currentTab?.statement ?? "";+ const newStatement = [oldStatement, appended]+ .filter((s) => s)+ .join("\n\n");+ editor.setValue(newStatement);+ if (select) {+ const selection = new monaco.Selection(+ oldStatement.split("\n").length + 1,+ 0,+ newStatement.split("\n").length + 1,+ 0+ );+ requestAnimationFrame(() => {+ void sqlEditorEvents.emit("set-editor-selection", selection);+ });+ }+ }+ );+ return () => {+ offFormat();+ offSetSelection();+ offAppend();+ };+ }, [tabStore]);++ // Clear the global refs on unmount.+ useEffect(() => {+ return () => {+ activeSQLEditorRef.value = undefined;+ activeStatementRef.value = "";+ };+ }, []);++ const autoCompleteContext = useMemo(() => {+ if (!instanceName || !databaseName) return undefined;+ if (!isValidDatabaseName(databaseName)) return undefined;+ return {+ instance: instanceName,+ database: databaseName,+ schema: schema ?? undefined,+ scene: "query" as const,+ };+ }, [instanceName, databaseName, schema]);++ return (+ <div className="w-full h-full grow flex flex-col justify-start items-start overflow-hidden">+ <MonacoEditor+ key={filename}+ autoHeight={false}+ className="w-full h-full"+ enableDecorations+ filename={filename}+ content={content ?? ""}+ language={language}+ dialect={dialect}+ readOnly={readonly}+ autoCompleteContext={autoCompleteContext}+ onChange={handleChange}+ onSelectContent={handleSelectContent}+ onSelectionChange={handleSelectionChange}+ onActiveContentChange={handleActiveContentChange}+ onReady={handleReady}+ cornerPrefix={<UploadFileButton onUpload={handleUploadFile} />}+ />+ </div>+ );+}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsxnew file mode 100644index 0000000000..2c3e6c4999--- /dev/null+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLUploadButton.tsx@@ -0,0 +1,117 @@+import type { ChangeEvent, ReactNode } from "react";+import { useCallback, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import { cn } from "@/react/lib/utils";+import { pushNotification } from "@/store";+import { MAX_UPLOAD_FILE_SIZE_MB } from "@/utils";+import { FileContentPreviewModal } from "./FileContentPreviewModal";++interface SQLUploadButtonProps {+ iconOnly?: boolean;+ className?: string;+ children?: ReactNode;+ onUpdateSql: (text: string, filename: string) => void;+}++/**+ * React port of `frontend/src/components/misc/SQLUploadButton.vue`.+ *+ * Hidden `<input type="file">` triggered by clicking the button. After+ * the user picks a file, mounts a preview modal that decodes + shows+ * the content; the parent receives the final text via `onUpdateSql`.+ */+export function SQLUploadButton({+ iconOnly,+ className,+ children,+ onUpdateSql,+}: SQLUploadButtonProps) {+ const { t } = useTranslation();+ const inputRef = useRef<HTMLInputElement>(null);+ const [selectedFile, setSelectedFile] = useState<File | null>(null);++ const cleanup = useCallback(() => {+ setSelectedFile(null);+ if (inputRef.current) {+ inputRef.current.value = "";+ }+ }, []);++ const handleClick = useCallback(() => {+ inputRef.current?.click();+ }, []);++ const handleUpload = useCallback(+ (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.target.files?.[0];+ const cleanupInput = () => {+ // Selecting the same file twice doesn't fire `change` again,+ // so reset the value here too.+ if (inputRef.current) {+ inputRef.current.value = "";+ }+ };+ if (!file) {+ cleanupInput();+ return;+ }+ if (file.size > MAX_UPLOAD_FILE_SIZE_MB * 1024 * 1024) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("issue.upload-sql-file-max-size-exceeded", {+ size: `${MAX_UPLOAD_FILE_SIZE_MB}MB`,+ }),+ });+ cleanupInput();+ return;+ }+ setSelectedFile(file);+ cleanupInput();+ },+ [t]+ );++ const handleConfirm = useCallback(+ (statement: string) => {+ if (selectedFile) {+ onUpdateSql(statement, selectedFile.name);+ }+ cleanup();+ },+ [onUpdateSql, selectedFile, cleanup]+ );++ return (+ <>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className={cn("h-7 px-1", className)}+ onClick={handleClick}+ >+ {children}+ {iconOnly ? null : (+ <span className="ml-1">{t("sql-editor.upload-file")}</span>+ )}+ </Button>+ <input+ ref={inputRef}+ type="file"+ accept=".sql,.txt,application/sql,text/plain"+ className="hidden"+ onChange={handleUpload}+ />+ {selectedFile ? (+ <FileContentPreviewModal+ file={selectedFile}+ open+ onCancel={cleanup}+ onConfirm={handleConfirm}+ />+ ) : null}+ </>+ );+}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsxnew file mode 100644index 0000000000..7058e73186--- /dev/null+++ b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx@@ -0,0 +1,38 @@+import { Upload } from "lucide-react";+import { useCallback } from "react";+import { useTranslation } from "react-i18next";+import { Tooltip } from "@/react/components/ui/tooltip";+import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorTabStore } from "@/store";+import { SQLUploadButton } from "./SQLUploadButton";++interface UploadFileButtonProps {+ onUpload: (content: string) => void;+}++/**+ * React port of+ * `frontend/src/views/sql-editor/EditorPanel/StandardPanel/UploadFileButton.vue`.+ * Tooltip-wrapped icon button that delegates to `SQLUploadButton`.+ */+export function UploadFileButton({ onUpload }: UploadFileButtonProps) {+ const { t } = useTranslation();+ const tabStore = useSQLEditorTabStore();+ const tabId = useVueState(() => tabStore.currentTab?.id);++ const handleUpdateSql = useCallback(+ (content: string) => {+ if (!tabId) return;+ onUpload(content);+ },+ [onUpload, tabId]+ );++ return (+ <Tooltip content={t("sql-editor.upload-file")} side="bottom">+ <SQLUploadButton iconOnly onUpdateSql={handleUpdateSql}>+ <Upload className="size-3" />+ </SQLUploadButton>+ </Tooltip>+ );+}diff --git a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsxindex 3cfc505baa..2881ba35fa 100644--- a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx@@ -55,16 +55,23 @@ export function TabItem({} = useSortable({ id: tab.id });const isCurrentTab = tab.id === currentTabId;- const isAdmin = tab.mode === "ADMIN";// Derive the environment tint (used as the top border on the current tab).- const { database } = getConnectionForSQLEditorTab(tab);- const environment = database ? getDatabaseEnvironment(database) : undefined;- const environmentTint =- environment?.id === String(UNKNOWN_ID) ? undefined : environment;+ // Wrapped in `useVueState` so the tab re-renders when the Pinia+ // database/environment state hydrates async — without this the tab+ // sticks on the fallback `#4f46e5` indigo even after the environment+ // resolves, which is what made the React tabs look more saturated+ // than the Vue version.+ const environmentTintColor = useVueState(() => {+ const { database } = getConnectionForSQLEditorTab(tab);+ if (!database) return undefined;+ const environment = getDatabaseEnvironment(database);+ if (!environment || environment.id === String(UNKNOWN_ID)) return undefined;+ return environment.color || undefined;+ });const backgroundColorRgb = isCurrentTab- ? environmentTint?.color- ? hexToRgb(environmentTint.color).join(", ")+ ? environmentTintColor+ ? hexToRgb(environmentTintColor).join(", "): hexToRgb("#4f46e5").join(", "): "";@@ -90,9 +97,8 @@ export function TabItem({className={cn("tab-item cursor-pointer border-r bg-background relative","gap-x-2",- isAdmin && "bg-dark-bg",isCurrentTab && "current",- hovering && !isAdmin && "bg-control-bg",+ hovering && "bg-control-bg",`status-${tab.status.toLowerCase()}`)}{...attributes}@@ -112,9 +118,7 @@ export function TabItem({<divclassName={cn("body flex items-center justify-between gap-x-2 pl-2 pr-1 border-t h-9",- isCurrentTab ? "pt-0.5 border-t-[3px] bg-background" : "pt-1",- isAdmin && "text-matrix-green-hover",- isAdmin && isCurrentTab && "bg-dark-bg"+ isCurrentTab ? "pt-0.5 border-t-[3px] bg-background" : "pt-1")}style={bodyStyle}>diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsxnew file mode 100644index 0000000000..82c7484faa--- /dev/null+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx@@ -0,0 +1,369 @@+import { debounce } from "lodash-es";+import type { IDisposable } from "monaco-editor";+import * as monaco from "monaco-editor";+import { useCallback, useEffect, useMemo, useRef } from "react";+import type {+ IStandaloneCodeEditor,+ MonacoModule,+} from "@/components/MonacoEditor";+import { formatEditorContent } from "@/components/MonacoEditor/utils";+import { MonacoEditor } from "@/react/components/monaco/MonacoEditor";+import { useVueState } from "@/react/hooks/useVueState";+import {+ useConnectionOfCurrentSQLEditorTab,+ useSQLEditorTabStore,+} from "@/store";+import type { SQLEditorQueryParams } from "@/types";+import { dialectOfEngineV1 } from "@/types";+import { Engine } from "@/types/proto-es/v1/common_pb";+import { languageOfEngineV1 } from "@/types/sqlEditor/editor";+import { instanceV1AllowsExplain } from "@/utils";+import {+ checkCursorAtFirstLine,+ checkCursorAtLast,+ checkCursorAtLastLine,+ checkIsEnterEndsStatement,+} from "@/views/sql-editor/EditorPanel/TerminalPanel/utils";+import { sqlEditorEvents } from "@/views/sql-editor/events";++const MIN_EDITOR_HEIGHT = 40;+const MAX_EDITOR_HEIGHT = 360;++interface CompactSQLEditorProps {+ content: string;+ readonly: boolean;+ onChange: (value: string) => void;+ onExecute: (params: SQLEditorQueryParams) => void;+ onHistory: (direction: "up" | "down", editor: IStandaloneCodeEditor) => void;+ onClearScreen: () => void;+}++/**+ * React port of `frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue`.+ *+ * Terminal-style Monaco editor with a CLI-like prompt:+ * SQL> first_line+ * -> second_line+ *+ * Wires up the same keybindings + context keys as the Vue version:+ * Cmd+Enter (run), Cmd+E (explain / dry-run for BigQuery), Alt+Shift+C+ * (clear screen), Enter-when-statement-ends-with-`;` (run), and+ * Up/Down arrow at top/bottom for history navigation.+ */+export function CompactSQLEditor({+ content,+ readonly,+ onChange,+ onExecute,+ onHistory,+ onClearScreen,+}: CompactSQLEditorProps) {+ const tabStore = useSQLEditorTabStore();+ const { connection, instance, database } =+ useConnectionOfCurrentSQLEditorTab();++ const engine = useVueState(() => instance.value.engine);+ const language = useMemo(+ () => languageOfEngineV1(engine ?? Engine.MYSQL),+ [engine]+ );+ const dialect = useMemo(+ () => dialectOfEngineV1(engine ?? Engine.MYSQL),+ [engine]+ );++ const databaseName = useVueState(() => database.value.name);+ const instanceName = useVueState(() => instance.value.name);+ const schema = useVueState(() => tabStore.currentTab?.connection.schema, {+ deep: true,+ });++ // Latest-prop refs so Monaco actions registered once can read live values.+ const propsRef = useRef({+ content,+ readonly,+ onExecute,+ onHistory,+ onClearScreen,+ });+ propsRef.current = {+ content,+ readonly,+ onExecute,+ onHistory,+ onClearScreen,+ };++ const connectionRef = useRef(connection);+ connectionRef.current = connection;+ const engineRef = useRef(engine);+ engineRef.current = engine;+ const languageRef = useRef(language);+ languageRef.current = language;++ const debouncedEmitChange = useMemo(+ () =>+ debounce((value: string) => {+ // Emit through the latest onChange — kept on a ref to survive+ // debounce flushes that span across prop updates.+ onChangeRef.current?.(value);+ }, 100),+ []+ );+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;++ useEffect(() => {+ return () => debouncedEmitChange.cancel();+ }, [debouncedEmitChange]);++ const handleChange = useCallback(+ (value: string) => debouncedEmitChange(value),+ [debouncedEmitChange]+ );++ const firstLinePrompt = useMemo(() => {+ if (language === "javascript") return "MONGO>";+ if (language === "redis") return "REDIS>";+ return "SQL>";+ }, [language]);++ const editorRef = useRef<IStandaloneCodeEditor | null>(null);++ const handleReady = useCallback(+ (_: MonacoModule, editor: IStandaloneCodeEditor) => {+ editorRef.current = editor;++ const execute = (explain = false) => {+ const c = connectionRef.current;+ propsRef.current.onExecute({+ connection: { ...c.value },+ statement: propsRef.current.content,+ engine: engineRef.current ?? Engine.MYSQL,+ explain,+ selection: null,+ });+ };++ // Context keys that gate keybindings.+ const isTerminalEditor = editor.createContextKey<boolean>(+ "isTerminalEditor",+ true+ );+ isTerminalEditor.set(true);+ const readonlyKey = editor.createContextKey<boolean>(+ "readonly",+ propsRef.current.readonly+ );+ const isEnterEndsStatement = editor.createContextKey<boolean>(+ "isEnterEndsStatement",+ checkIsEnterEndsStatement(editor, languageRef.current)+ );+ const cursorAtLast = editor.createContextKey<boolean>(+ "cursorAtLast",+ checkCursorAtLast(editor)+ );+ const cursorAtFirstLine = editor.createContextKey<boolean>(+ "cursorAtFirstLine",+ checkCursorAtFirstLine(editor)+ );+ const cursorAtLastLine = editor.createContextKey<boolean>(+ "cursorAtLastLine",+ checkCursorAtLastLine(editor)+ );++ const subscriptions: IDisposable[] = [];+ subscriptions.push(+ editor.onDidChangeModelContent(() => {+ isEnterEndsStatement.set(+ checkIsEnterEndsStatement(editor, languageRef.current)+ );+ })+ );+ subscriptions.push(+ editor.onDidChangeCursorPosition(() => {+ cursorAtLast.set(checkCursorAtLast(editor));+ cursorAtFirstLine.set(checkCursorAtFirstLine(editor));+ cursorAtLastLine.set(checkCursorAtLastLine(editor));+ })+ );++ subscriptions.push(+ editor.addAction({+ id: "RunQuery",+ label: "Run Query",+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],+ contextMenuGroupId: "operation",+ contextMenuOrder: 0,+ precondition: "!readonly",+ run: () => execute(false),+ })+ );++ subscriptions.push(+ editor.addAction({+ id: "ClearScreen",+ label: "Clear Screen",+ keybindings: [+ monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyC,+ ],+ contextMenuGroupId: "operation",+ contextMenuOrder: 3,+ precondition: "!readonly",+ run: () => propsRef.current.onClearScreen(),+ })+ );++ // Monaco commands don't return a disposable — they live with the+ // editor instance and clean up when the editor is destroyed.+ // Match the Vue version's fire-and-forget pattern.+ editor.addCommand(+ monaco.KeyCode.Enter,+ () => execute(false),+ "!readonly && isEnterEndsStatement && cursorAtLast && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"+ );+ editor.addCommand(+ monaco.KeyCode.UpArrow,+ () => propsRef.current.onHistory("up", editor),+ "isTerminalEditor && !readonly && !content && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"+ );+ editor.addCommand(+ monaco.KeyCode.DownArrow,+ () => propsRef.current.onHistory("down", editor),+ "isTerminalEditor && !readonly && cursorAtLastLine && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"+ );++ // Stash the readonly key so the outer effect can flip it on+ // prop changes without re-running this whole onReady block.+ readonlyKeyRef.current = readonlyKey;+ explainCleanupRef.current = subscriptions;++ if (!propsRef.current.readonly) {+ requestAnimationFrame(() => editor.focus());+ }+ },+ []+ );++ const readonlyKeyRef = useRef<monaco.editor.IContextKey<boolean> | null>(+ null+ );+ const explainCleanupRef = useRef<IDisposable[]>([]);++ // Keep the readonly context key in sync.+ useEffect(() => {+ readonlyKeyRef.current?.set(readonly);+ }, [readonly]);++ // Engine-conditional Explain Query / Dry Run Query action. Re-registers+ // when the engine flips so the label and visibility track.+ const explainActionRef = useRef<IDisposable | null>(null);+ useEffect(() => {+ const editor = editorRef.current;+ if (!editor || engine === undefined) return;+ explainActionRef.current?.dispose();+ explainActionRef.current = null;++ const allows =+ instanceV1AllowsExplain(engine) || engine === Engine.BIGQUERY;+ if (!allows) return;++ const isBigQuery = engine === Engine.BIGQUERY;+ const label = isBigQuery ? "Dry Run Query" : "Explain Query";++ const action = editor.addAction({+ id: "ExplainQuery",+ label,+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],+ contextMenuGroupId: "operation",+ contextMenuOrder: 1,+ precondition: "!readonly",+ run: () => {+ const c = connectionRef.current;+ propsRef.current.onExecute({+ connection: { ...c.value },+ statement: propsRef.current.content,+ engine,+ explain: true,+ selection: null,+ });+ },+ });+ explainActionRef.current = action;+ return () => {+ action.dispose();+ };+ }, [engine]);++ // Format-content event from useSQLEditorContext (Vue `editorEvents`).+ useEffect(() => {+ const off = sqlEditorEvents.on("format-content", () => {+ const editor = editorRef.current;+ if (!editor) return;+ void formatEditorContent(editor, dialect);+ });+ return () => {+ off();+ };+ }, [dialect]);++ // Cleanup all editor subscriptions on unmount.+ useEffect(() => {+ return () => {+ explainCleanupRef.current.forEach((sub) => sub.dispose());+ explainCleanupRef.current = [];+ };+ }, []);++ const getLineNumber = useCallback(+ (lineNumber: number) => {+ if (lineNumber === 1) return firstLinePrompt;+ return "->";+ },+ [firstLinePrompt]+ );++ const editorOptions =+ useMemo<monaco.editor.IStandaloneEditorConstructionOptions>(+ () => ({+ theme: "vs-dark",+ lineNumbers: getLineNumber,+ lineNumbersMinChars: firstLinePrompt.length + 3,+ cursorStyle: readonly ? "underline" : "block",+ scrollbar: {+ vertical: "hidden",+ horizontal: "hidden",+ alwaysConsumeMouseWheel: false,+ },+ overviewRulerLanes: 0,+ }),+ [readonly, firstLinePrompt, getLineNumber]+ );++ return (+ <div className="whitespace-pre-wrap w-full overflow-hidden">+ <MonacoEditor+ className="w-full h-auto"+ content={content}+ language={language}+ dialect={dialect}+ readOnly={readonly}+ options={editorOptions}+ min={MIN_EDITOR_HEIGHT}+ max={MAX_EDITOR_HEIGHT}+ autoCompleteContext={+ instanceName && databaseName+ ? {+ instance: instanceName,+ database: databaseName,+ schema: schema ?? undefined,+ scene: "query",+ }+ : undefined+ }+ onChange={handleChange}+ onReady={handleReady}+ />+ </div>+ );+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 1ee0a7fd80..1451c02135 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -340,6 +340,7 @@"pending": "Pending","permissions": "Permissions","plan": "Plan",+ "preview": "Preview","previous": "Previous","project": "Project","projects": "Projects",@@ -2690,6 +2691,7 @@"save-sheet-input-placeholder": "Please input a sheet name","search-history-by-statement": "Search by statement","select-a-database-to-start": "Select a database to start",+ "select-encoding": "Select encoding","self": "SQL Editor","show-databases-without-query-permission": "Show databases without query permissions","sync-in-progress": "Sync in progress",@@ -2709,6 +2711,7 @@}},"unmask-warning": "The query result may include unmasked sensitive data.",+ "upload-file": "Upload file","url-copied-to-clipboard": "The URL is copied to your clipboard","view-database-detail": "View database detail","view-detail": "View detail",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex bd47fc4d8a..e6f34d8a4f 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -335,6 +335,7 @@"pending": "Pendiente","permissions": "Permisos","plan": "Plan",+ "preview": "Previsualización","previous": "Previous","project": "Proyecto","projects": "Proyectos",@@ -2676,6 +2677,7 @@"save-sheet-input-placeholder": "Por favor, ingresa un nombre para la hoja","search-history-by-statement": "Búsqueda por enunciado","select-a-database-to-start": "Seleccione una base de datos para comenzar",+ "select-encoding": "Seleccionar codificación","self": "Editor de SQL","show-databases-without-query-permission": "Muestra las bases de datos que no tienen permisos de consulta","sync-in-progress": "Sincronización en progreso",@@ -2695,6 +2697,7 @@}},"unmask-warning": "The query result may include unmasked sensitive data.",+ "upload-file": "Subir archivo","url-copied-to-clipboard": "La URL se copia al portapapeles.","view-database-detail": "Ver detalle de la base de datos","view-detail": "Ver detalle",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex becfeb974c..fe49fdf9a2 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -335,6 +335,7 @@"pending": "保留中","permissions": "権限","plan": "Plan",+ "preview": "プレビュー","previous": "Previous","project": "プロジェクト","projects": "プロジェクト",@@ -2676,6 +2677,7 @@"save-sheet-input-placeholder": "ワークシート名を入力してください","search-history-by-statement": "ステートメントで検索","select-a-database-to-start": "開始するにはデータベースを選択してください",+ "select-encoding": "エンコーディングの選択","self": "SQLエディタ","show-databases-without-query-permission": "クエリ権限のないデータベースを表示します","sync-in-progress": "同期中",@@ -2695,6 +2697,7 @@}},"unmask-warning": "The query result may include unmasked sensitive data.",+ "upload-file": "ファイルをアップロードする","url-copied-to-clipboard": "URLがクリップボードにコピーされました","view-database-detail": "データベースの詳細を表示する","view-detail": "詳細を見る",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex b64c6e5454..41d97bb068 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -335,6 +335,7 @@"pending": "Đang chờ","permissions": "Quyền","plan": "Plan",+ "preview": "Xem trước","previous": "Previous","project": "Dự án","projects": "Dự án",@@ -2676,6 +2677,7 @@"save-sheet-input-placeholder": "Vui lòng nhập tên trang tính","search-history-by-statement": "Tìm kiếm theo câu lệnh","select-a-database-to-start": "Chọn một cơ sở dữ liệu để bắt đầu",+ "select-encoding": "Chọn mã hóa","self": "Trình soạn thảo SQL","show-databases-without-query-permission": "Hiển thị cơ sở dữ liệu không có quyền truy vấn","sync-in-progress": "Đang đồng bộ",@@ -2695,6 +2697,7 @@}},"unmask-warning": "The query result may include unmasked sensitive data.",+ "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","view-database-detail": "Xem chi tiết cơ sở dữ liệu","view-detail": "Xem chi tiết",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 381d90ffb7..79a0dc7000 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -335,6 +335,7 @@"pending": "待审批","permissions": "权限","plan": "Plan",+ "preview": "预览","previous": "上一步","project": "项目","projects": "项目",@@ -2676,6 +2677,7 @@"save-sheet-input-placeholder": "请输入工作表名称","search-history-by-statement": "搜索 SQL 语句","select-a-database-to-start": "选择数据库以开始",+ "select-encoding": "选择编码","self": "SQL 编辑器","show-databases-without-query-permission": "显示没有查询权限的数据库","sync-in-progress": "正在同步",@@ -2695,6 +2697,7 @@}},"unmask-warning": "The query result may include unmasked sensitive data.",+ "upload-file": "上传文件","url-copied-to-clipboard": "URL 已复制到剪贴板","view-database-detail": "查看数据库详情","view-detail": "查看详情",diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vuedeleted file mode 100644index 1a8068462e..0000000000--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/EditorMain.vue+++ /dev/null@@ -1,167 +0,0 @@-<template>- <div class="h-full flex flex-col overflow-hidden justify-start items-stretch">- <template v-if="isDisconnected || allowReadonlyMode">- <ReactPageMount- page="EditorAction"- container-class="w-full"- :onExecute="handleExecuteFromActionBar"- />-- <NSplit- v-if="tab"- :disabled="!showAIPanel"- :size="editorPanelSize.size"- :min="editorPanelSize.min"- :max="editorPanelSize.max"- :resize-trigger-size="3"- @update:size="handleEditorPanelResize"- >- <template #1>- <Suspense>- <SQLEditor ref="sqlEditorRef" @execute="handleExecute" />- <template #fallback>- <div- class="w-full h-full grow flex flex-col items-center justify-center"- >- <BBSpin />- </div>- </template>- </Suspense>- </template>- <template #2>- <div- v-if="showAIPanel"- class="h-full overflow-hidden flex flex-col"- >- <Suspense>- <AIChatToSQL key="ai-chat-to-sql" />- <template #fallback>- <div- class="w-full h-full grow flex flex-col items-center justify-center"- >- <BBSpin />- </div>- </template>- </Suspense>- </div>- </template>- </NSplit>- <div v-else class="flex-1 flex flex-col min-h-0">- <ReactPageMount- page="Welcome"- :onChangeConnection="changeConnection"- />- </div>-- <!-- 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>-- <ReactPageMount v-else page="ReadonlyModeNotSupported" />- </div>-</template>--<script lang="ts" setup>-import { NSplit } from "naive-ui";-import { storeToRefs } from "pinia";-import { computed, defineAsyncComponent, nextTick, ref } from "vue";-import { BBSpin } from "@/bbkit";-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import { useExecuteSQL } from "@/composables/useExecuteSQL";-import { AIChatToSQL } from "@/plugins/ai";-import ReactPageMount from "@/react/ReactPageMount.vue";-import {- useConnectionOfCurrentSQLEditorTab,- useDatabaseV1Store,- useSQLEditorTabStore,-} from "@/store";-import type { SQLEditorQueryParams } from "@/types";-import { getInstanceResource, instanceV1HasReadonlyMode } from "@/utils";-import { useSQLEditorContext } from "../../context";-import { sqlEditorEvents } from "../../events";--const SQLEditor = defineAsyncComponent(() => import("./SQLEditor.vue"));--const tabStore = useSQLEditorTabStore();-const { currentTab: tab, isDisconnected } = storeToRefs(tabStore);-const { instance } = useConnectionOfCurrentSQLEditorTab();-const {- showAIPanel,- editorPanelSize,- handleEditorPanelResize,- showConnectionPanel,- asidePanelTab,-} = useSQLEditorContext();--const changeConnection = () => {- asidePanelTab.value = "SCHEMA";- showConnectionPanel.value = true;-};-const sqlEditorRef = ref<InstanceType<typeof SQLEditor>>();--const allowReadonlyMode = computed(() => {- if (isDisconnected.value) return false;-- return instanceV1HasReadonlyMode(instance.value);-});--const { execute } = useExecuteSQL();--useEmitteryEventListener(- sqlEditorEvents,- "execute-sql",- async ({ connection, statement, batchQueryContext }) => {- const database = await useDatabaseV1Store().getOrFetchDatabaseByName(- connection.database- );- const newTab = tabStore.addTab(- { connection, statement, batchQueryContext },- /* beside */ true- );- nextTick(() => {- execute({- connection: { ...newTab.connection },- statement,- engine: getInstanceResource(database).engine,- explain: false,- selection: null,- });- });- }-);--const handleExecuteFromActionBar = (params: SQLEditorQueryParams) => {- if (!tab.value || !sqlEditorRef.value) {- return;- }- const statement = sqlEditorRef.value.getActiveStatement();- handleExecute({- params: { ...params, statement },- newTab: false,- });-};--const handleExecute = ({- params,- newTab,-}: {- params: SQLEditorQueryParams;- newTab: boolean;-}) => {- if (newTab) {- tabStore.cloneTab(tabStore.currentTabId, {- statement: params.statement,- });- }-- nextTick(() => {- execute(params);- });-};-</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vuedeleted file mode 100644index aece4284fc..0000000000--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/SQLEditor.vue+++ /dev/null@@ -1,401 +0,0 @@-<template>- <div- class="w-full h-full grow flex flex-col justify-start items-start overflow-auto"- >- <MonacoEditor- class="w-full h-full"- :key="filename"- ref="monacoEditorRef"- :enable-decorations="true"- :filename="filename"- :content="content"- :language="language"- :dialect="dialect"- :readonly="readonly"- :auto-complete-context="{- instance: instance.name,- database: database.name,- schema: currentTab?.connection.schema,- scene: 'query',- }"- @update:content="handleUpdateStatement"- @select-content="handleUpdateSelectedStatement"- @update:selection="handleUpdateSelection"- @ready="handleEditorReady"- >- <template #corner-prefix>- <UploadFileButton @upload="handleUploadFile" />- </template>- </MonacoEditor>- </div>-</template>--<script lang="ts" setup>-import { type IDisposable, type IRange, Selection } from "monaco-editor";-import { storeToRefs } from "pinia";-import { v1 as uuidv1 } from "uuid";-import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";-import type {- IStandaloneCodeEditor,- MonacoModule,- Selection as MonacoSelection,-} from "@/components/MonacoEditor";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";-import {- extensionNameOfLanguage,- formatEditorContent,-} from "@/components/MonacoEditor/utils";-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import { useAIActions } from "@/plugins/ai";-import { useAIContext } from "@/plugins/ai/logic";-import * as promptUtils from "@/plugins/ai/logic/prompt";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,- useUIStateStore,- useWorkSheetAndTabStore,-} from "@/store";-import type { SQLDialect, SQLEditorQueryParams } from "@/types";-import { dialectOfEngineV1 } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import {- instanceV1AllowsExplain,- nextAnimationFrame,- useInstanceV1EditorLanguage,-} from "@/utils";-import { useSQLEditorContext } from "../../context";-import { activeSQLEditorRef } from "./state";-import UploadFileButton from "./UploadFileButton.vue";--const emit = defineEmits<{- (- e: "execute",- params: { params: SQLEditorQueryParams; newTab: boolean }- ): void;-}>();--const tabStore = useSQLEditorTabStore();-const sheetAndTabStore = useWorkSheetAndTabStore();-const uiStateStore = useUIStateStore();-const {- showAIPanel,- pendingInsertAtCaret,- events: editorEvents,-} = useSQLEditorContext();-const { currentTab } = storeToRefs(tabStore);-const AIContext = useAIContext();--const monacoEditorRef = ref<InstanceType<typeof MonacoEditor>>();--const content = computed(() => currentTab.value?.statement ?? "");-const { instance, database } = useConnectionOfCurrentSQLEditorTab();-const language = useInstanceV1EditorLanguage(instance);-const dialect = computed((): SQLDialect => {- const engine = instance.value.engine;- return dialectOfEngineV1(engine);-});-const readonly = computed(() => sheetAndTabStore.isReadOnly);--const filename = computed(() => {- const name = currentTab.value?.id || uuidv1();- const ext = extensionNameOfLanguage(language.value);- return `${name}.${ext}`;-});--const handleUpdateStatement = (value: string) => {- const tab = currentTab.value;- if (!tab || value === tab.statement) {- return;- }- // Directly update the reactive tab for immediate UI feedback- tabStore.updateCurrentTab({- statement: value,- status: "DIRTY",- });-};--const handleUpdateSelectedStatement = (value: string) => {- tabStore.updateCurrentTab({- selectedStatement: value,- });-};--// Guard flag to prevent a feedback loop: when the user selects text in the-// editor, handleUpdateSelection stores the selection in the tab store, which-// triggers the watcher below. Without this flag the watcher would call-// setSelection() back on the editor, interrupting an in-progress mouse drag-// and breaking double-click-drag word selection.-let selectionFromEditor = false;--const handleUpdateSelection = (selection: MonacoSelection | null) => {- const tab = currentTab.value;- if (!tab) return;- selectionFromEditor = true;- tabStore.updateCurrentTab({- editorState: {- selection,- },- });-};--const handleSaveSheet = () => {- const tab = currentTab.value;- if (!tab) {- return;- }- editorEvents.emit("save-sheet", { tab });-};--const getActiveStatement = () => {- const tab = tabStore.currentTab;- if (!tab) {- return "";- }- return monacoEditorRef.value?.getActiveStatement() || tab.statement || "";-};--watch(- () => currentTab.value?.editorState.selection?.toString(),- () => {- if (selectionFromEditor) {- selectionFromEditor = false;- return;- }- const selection = tabStore.currentTab?.editorState.selection;- if (!selection) return;- activeSQLEditorRef.value?.setSelection(selection);- }-);--const runQueryAction = ({- explain = false,- newTab = false,-}: {- explain: boolean;- newTab: boolean;-}) => {- const tab = tabStore.currentTab;- if (!tab) {- return;- }- const statement = getActiveStatement();- const params: SQLEditorQueryParams = {- connection: { ...tab.connection },- statement,- engine: instance.value.engine,- explain,- selection: null,- };- if (!newTab) {- params.selection = tab.editorState.selection;- }- emit("execute", { params, newTab });- uiStateStore.saveIntroStateByKey({- key: "data.query",- newState: true,- });-};--const handleEditorReady = (- monaco: MonacoModule,- editor: IStandaloneCodeEditor-) => {- activeSQLEditorRef.value = editor;-- editor.addAction({- id: "RunQuery",- label: "Run Query",- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],- contextMenuGroupId: "operation",- contextMenuOrder: 1,- run: () => runQueryAction({ explain: false, newTab: false }),- });- editor.addAction({- id: "RunQueryInNewTab",- label: "Run Query in New Tab",- keybindings: [- monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.Enter,- ],- contextMenuGroupId: "operation",- contextMenuOrder: 1,- run: () => runQueryAction({ explain: false, newTab: true }),- });- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {- handleSaveSheet();- });- useAIActions(monaco, editor, AIContext, {- actions: ["explain-code", "find-problems", "new-chat"],- callback: async (action) => {- // start new chat if AI panel is not open- // continue current chat otherwise- const newChat = !showAIPanel.value;-- showAIPanel.value = true;- const tab = tabStore.currentTab;- const statement = getActiveStatement();- if (!statement) return;-- await nextAnimationFrame();- if (action === "explain-code") {- AIContext.events.emit("send-chat", {- content: promptUtils.explainCode(statement, instance.value.engine),- newChat,- });- }- if (action === "find-problems") {- AIContext.events.emit("send-chat", {- content: promptUtils.findProblems(statement, instance.value.engine),- newChat,- });- }- if (action === "new-chat") {- const statement = tab?.selectedStatement ?? "";- if (!statement) return;- const inputs = [- "", // just an empty line- promptUtils.wrapStatementMarkdown(statement),- ];- AIContext.events.emit("new-conversation", {- input: inputs.join("\n"),- });- }- },- });-- let explainQueryAction: IDisposable | undefined;- watch(- () => instance.value.engine,- () => {- const shouldShowAction =- instanceV1AllowsExplain(instance.value) ||- instance.value.engine === Engine.BIGQUERY;-- if (shouldShowAction) {- const isBigQuery = instance.value.engine === Engine.BIGQUERY;- const label = isBigQuery ? "Dry Run Query" : "Explain Query";-- // Remove existing action if label changed- if (explainQueryAction) {- explainQueryAction.dispose();- explainQueryAction = undefined;- }-- if (!editor.getAction("ExplainQuery")) {- explainQueryAction = editor.addAction({- id: "ExplainQuery",- label: label,- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],- contextMenuGroupId: "operation",- contextMenuOrder: 0,- run: () => runQueryAction({ explain: true, newTab: false }),- });- }- } else {- explainQueryAction?.dispose();- explainQueryAction = undefined;- }- },- { immediate: true }- );-- watch(- pendingInsertAtCaret,- () => {- const editor = activeSQLEditorRef.value;- if (!editor) return;- const text = pendingInsertAtCaret.value;- if (!text) return;- pendingInsertAtCaret.value = undefined;-- requestAnimationFrame(() => {- const selection = editor.getSelection();- const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;- const range =- selection ??- new monaco.Range(maxLineNumber + 1, 1, maxLineNumber + 1, 1);- editor.executeEdits("bb.event.insert-at-caret", [- {- forceMoveMarkers: true,- text,- range,- },- ]);- editor.focus();- editor.revealLine(range.startLineNumber);- });- },- { immediate: true }- );-};--const handleUploadFile = (content: string) => {- const editor = activeSQLEditorRef.value;- if (!editor) return;- const tab = currentTab.value;- if (!tab) return;- if (tab.statement.trim() !== "") {- content = "\n" + content;- }- const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;- editor.executeEdits("bb.event.upload-file", [- {- forceMoveMarkers: true,- text: content,- range: {- startLineNumber: maxLineNumber + 1,- startColumn: 1,- endLineNumber: maxLineNumber + 1,- endColumn: 1,- },- },- ]);- const newMaxLineNumber = editor.getModel()?.getLineCount() ?? 0;- editor.revealLine(newMaxLineNumber);-};--useEmitteryEventListener(editorEvents, "format-content", () => {- if (activeSQLEditorRef.value) {- formatEditorContent(activeSQLEditorRef.value, dialect.value);- }-});--useEmitteryEventListener(- editorEvents,- "set-editor-selection",- (selection: IRange) => {- activeSQLEditorRef.value?.setSelection(selection);- activeSQLEditorRef.value?.revealLineNearTop(selection.startLineNumber);- activeSQLEditorRef.value?.focus();- }-);--useEmitteryEventListener(- editorEvents,- "append-editor-content",- ({ content, select }: { content: string; select: boolean }) => {- const oldStatement = currentTab.value?.statement ?? "";- const newStatement = [oldStatement, content].filter((s) => s).join("\n\n");- activeSQLEditorRef.value?.setValue(newStatement);-- if (select) {- const selection = new Selection(- oldStatement.split("\n").length + 1,- 0,- newStatement.split("\n").length + 1,- 0- );- nextTick(() => {- editorEvents.emit("set-editor-selection", selection);- });- }- }-);--onBeforeUnmount(() => {- activeSQLEditorRef.value = undefined;-});--defineExpose({- getActiveStatement,-});-</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vueindex 77a716f8c2..cc09cdc6a7 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue@@ -7,7 +7,36 @@:resize-trigger-size="3"><template #1>- <EditorMain />+ <NSplit+ :disabled="!showAIPanel || !tab"+ :size="editorPanelSize.size"+ :min="editorPanelSize.min"+ :max="editorPanelSize.max"+ :resize-trigger-size="3"+ @update:size="handleEditorPanelResize"+ >+ <template #1>+ <ReactPageMount+ page="EditorMain"+ container-class="h-full"+ :page-props="{ onChangeConnection: handleChangeConnection }"+ />+ </template>+ <template v-if="showAIPanel && tab" #2>+ <div class="h-full overflow-hidden flex flex-col">+ <Suspense>+ <AIChatToSQL key="ai-chat-to-sql" />+ <template #fallback>+ <div+ class="w-full h-full grow flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>+ </Suspense>+ </div>+ </template>+ </NSplit></template><template #2><div class="relative h-full">@@ -15,7 +44,38 @@</div></template></NSplit>- <EditorMain v-else class="h-full" />+ <NSplit+ v-else+ class="h-full"+ :disabled="!showAIPanel || !tab"+ :size="editorPanelSize.size"+ :min="editorPanelSize.min"+ :max="editorPanelSize.max"+ :resize-trigger-size="3"+ @update:size="handleEditorPanelResize"+ >+ <template #1>+ <ReactPageMount+ page="EditorMain"+ container-class="h-full"+ :page-props="{ onChangeConnection: handleChangeConnection }"+ />+ </template>+ <template v-if="showAIPanel && tab" #2>+ <div class="h-full overflow-hidden flex flex-col">+ <Suspense>+ <AIChatToSQL key="ai-chat-to-sql" />+ <template #fallback>+ <div+ class="w-full h-full grow flex flex-col items-center justify-center"+ >+ <BBSpin />+ </div>+ </template>+ </Suspense>+ </div>+ </template>+ </NSplit></template></template>@@ -23,13 +83,17 @@import { NSplit } from "naive-ui";import { storeToRefs } from "pinia";import { computed } from "vue";+import { BBSpin } from "@/bbkit";+import { AIChatToSQL } from "@/plugins/ai";+import ReactPageMount from "@/react/ReactPageMount.vue";import {useConnectionOfCurrentSQLEditorTab,useSQLEditorTabStore,+ useSQLEditorUIStore,} from "@/store";import { instanceV1HasReadonlyMode } from "@/utils";+import { useSQLEditorContext } from "../../context";import ResultPanel from "../ResultPanel";-import EditorMain from "./EditorMain.vue";const { currentTab: tab, isDisconnected } = storeToRefs(useSQLEditorTabStore());const { instance } = useConnectionOfCurrentSQLEditorTab();@@ -41,4 +105,16 @@ const { instance } = useConnectionOfCurrentSQLEditorTab();const showResultPanel = computed(() => !isDisconnected.value && instanceV1HasReadonlyMode(instance.value));++// AI side pane is hosted here (Vue) instead of inside the React+// `EditorMain` because `AIChatToSQL` is Vue-only.+const uiStore = useSQLEditorUIStore();+const { showAIPanel, editorPanelSize } = storeToRefs(uiStore);+const handleEditorPanelResize = uiStore.handleEditorPanelResize;++const { showConnectionPanel, asidePanelTab } = useSQLEditorContext();+const handleChangeConnection = () => {+ asidePanelTab.value = "SCHEMA";+ showConnectionPanel.value = true;+};</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/UploadFileButton.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/UploadFileButton.vuedeleted file mode 100644index e0142733a7..0000000000--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/UploadFileButton.vue+++ /dev/null@@ -1,44 +0,0 @@-<template>- <NPopover placement="bottom">- <template #trigger>- <SQLUploadButton- size="tiny"- quaternary- style="--n-padding: 0 4px"- icon-only- @update:sql="handleUploadSQL"- >- <template #icon>- <UploadIcon class="w-3 h-3" />- </template>- </SQLUploadButton>- </template>- <template #default>- <div>{{ $t("sql-editor.upload-file") }}</div>- </template>- </NPopover>-</template>--<script setup lang="ts">-import { UploadIcon } from "lucide-vue-next";-import { NPopover } from "naive-ui";-import { storeToRefs } from "pinia";-import SQLUploadButton from "@/components/misc/SQLUploadButton.vue";-import { useSQLEditorTabStore } from "@/store";--defineProps<{- disabled?: boolean;-}>();--const emit = defineEmits<{- (event: "upload", content: string): void;-}>();--const { currentTab } = storeToRefs(useSQLEditorTabStore());--const handleUploadSQL = (content: string) => {- const tab = currentTab.value;- if (!tab) return;- emit("upload", content);-};-</script>diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.tsindex 0e81fc85ba..145eaf3759 100644--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts+++ b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts@@ -2,3 +2,12 @@ import { shallowRef } from "vue";import { type IStandaloneCodeEditor } from "@/components/MonacoEditor";export const activeSQLEditorRef = shallowRef<IStandaloneCodeEditor>();++/**+ * Tracks the live "active statement" — Monaco's delimited statement+ * under the cursor, or the full editor content as fallback. The React+ * `SQLEditor` writes here via `onActiveContentChange`; Vue `EditorMain`+ * reads it when the toolbar's "Run" button is pressed (since+ * `ReactPageMount` doesn't pass refs across the framework boundary).+ */+export const activeStatementRef = shallowRef<string>("");diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vuedeleted file mode 100644index 4e4b4bde09..0000000000--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/CompactSQLEditor.vue+++ /dev/null@@ -1,312 +0,0 @@-<template>- <div class="whitespace-pre-wrap w-full overflow-hidden">- <MonacoEditor- class="w-full h-auto"- :style="{- 'min-height': `${MIN_EDITOR_HEIGHT}px`,- 'max-height': `${MAX_EDITOR_HEIGHT}px`,- }"- :content="content"- :language="language"- :dialect="dialect"- :readonly="readonly"- :options="EDITOR_OPTIONS"- :auto-height="{- min: MIN_EDITOR_HEIGHT,- max: MAX_EDITOR_HEIGHT,- }"- :auto-complete-context="{- instance: instance.name,- database: database.name,- schema: currentTab?.connection.schema,- scene: 'query',- }"- @update:content="handleChange"- @ready="handleEditorReady"- />- </div>-</template>--<script lang="ts" setup>-import { debounce } from "lodash-es";-import type { editor as Editor, IDisposable } from "monaco-editor";-import * as monaco from "monaco-editor";-import { storeToRefs } from "pinia";-import { computed, nextTick, ref, toRef, watch } from "vue";-import type {- IStandaloneCodeEditor,- MonacoModule,-} from "@/components/MonacoEditor";-import MonacoEditor from "@/components/MonacoEditor/MonacoEditor.vue";-import {- formatEditorContent,- useEditorContextKey,-} from "@/components/MonacoEditor/utils";-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/store";-import type { SQLDialect, SQLEditorQueryParams } from "@/types";-import { dialectOfEngineV1 } from "@/types";-import { Engine } from "@/types/proto-es/v1/common_pb";-import { instanceV1AllowsExplain, useInstanceV1EditorLanguage } from "@/utils";-import { useSQLEditorContext } from "../../context";-import {- checkCursorAtFirstLine,- checkCursorAtLast,- checkCursorAtLastLine,- checkIsEnterEndsStatement,-} from "./utils";--const props = defineProps<{- content: string;- readonly: boolean;-}>();--const emit = defineEmits<{- (e: "update:content", content: string): void;- (e: "execute", params: SQLEditorQueryParams): void;- (e: "history", direction: "up" | "down", editor: IStandaloneCodeEditor): void;- (e: "clear-screen"): void;-}>();--const MIN_EDITOR_HEIGHT = 40; // ~= 1 line-const MAX_EDITOR_HEIGHT = 360; // ~= 2 lines--const tabStore = useSQLEditorTabStore();--const { events: editorEvents } = useSQLEditorContext();-const { connection, instance, database } = useConnectionOfCurrentSQLEditorTab();-const language = useInstanceV1EditorLanguage(instance);-const { currentTab } = storeToRefs(tabStore);-const pendingFormatContentCommand = ref(false);-const dialect = computed((): SQLDialect => {- const engine = instance.value.engine;- return dialectOfEngineV1(engine);-});--const firstLinePrompt = computed(() => {- const lang = language.value;- if (lang === "javascript") return "MONGO>";- if (lang === "redis") return "REDIS>";- return "SQL>";-});--const getLineNumber = (lineNumber: number) => {- /*- Show a SQL CLI like command prompt.- SQL> first_line- -> second_line- -> more_lines- */- if (lineNumber === 1) {- return firstLinePrompt.value;- }- return "->";-};--// Debounced version for better performance-const debouncedEmitUpdate = debounce((value: string) => {- emit("update:content", value);-}, 100);--const handleChange = (value: string) => {- // Use debounced emit to reduce excessive updates- debouncedEmitUpdate(value);-};--const execute = (explain = false) => {- emit("execute", {- connection: { ...connection.value },- statement: props.content,- engine: instance.value.engine,- explain,- selection: null,- });-};--const handleEditorReady = (_: MonacoModule, editor: IStandaloneCodeEditor) => {- // Mark this as a terminal editor to scope keybindings- useEditorContextKey(editor, "isTerminalEditor", true);- useEditorContextKey(editor, "readonly", toRef(props, "readonly"));-- editor.addAction({- id: "RunQuery",- label: "Run Query",- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.Enter],- contextMenuGroupId: "operation",- contextMenuOrder: 0,- precondition: "!readonly",- run: () => execute(false),- });-- let explainQueryAction: IDisposable | undefined;- watch(- () => instance.value.engine,- () => {- const shouldShowAction =- instanceV1AllowsExplain(instance.value) ||- instance.value.engine === Engine.BIGQUERY;-- if (shouldShowAction) {- const isBigQuery = instance.value.engine === Engine.BIGQUERY;- const label = isBigQuery ? "Dry Run Query" : "Explain Query";-- // Remove existing action if label changed- if (explainQueryAction) {- explainQueryAction.dispose();- explainQueryAction = undefined;- }-- if (!editor.getAction("ExplainQuery")) {- explainQueryAction = editor.addAction({- id: "ExplainQuery",- label: label,- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyE],- contextMenuGroupId: "operation",- contextMenuOrder: 1,- precondition: "!readonly",- run: () => execute(true),- });- }- } else {- explainQueryAction?.dispose();- explainQueryAction = undefined;- }- },- { immediate: true }- );-- editor.addAction({- id: "ClearScreen",- label: "Clear Screen",- keybindings: [- monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyC,- ],- contextMenuGroupId: "operation",- contextMenuOrder: 3,- precondition: "!readonly",- run: () => emit("clear-screen"),- });-- // Create an editor context value to check if the SQL ends with semicolon ";"- const isEnterEndsStatement = useEditorContextKey(- editor,- "isEnterEndsStatement",- checkIsEnterEndsStatement(editor, language.value)- );- editor.onDidChangeModelContent(() => {- isEnterEndsStatement.set(checkIsEnterEndsStatement(editor, language.value));- });- // Another editor context value to check if the cursor is at the end of the- // editor.- const cursorAtLast = useEditorContextKey(- editor,- "cursorAtLast",- checkCursorAtLast(editor)- );- editor.onDidChangeCursorPosition(() => {- cursorAtLast.set(checkCursorAtLast(editor));- });- editor.addCommand(- monaco.KeyCode.Enter,- () => {- // When- // - the SQL ends with ";"- // - and the cursor is at the end of the editor- // - then press "Enter"- // We trigger the "execute" event- execute(false);- },- // Tell the editor this should be only- // triggered when both of the two conditions are satisfied.- "!readonly && isEnterEndsStatement && cursorAtLast && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"- );-- const cursorAtFirstLine = useEditorContextKey(- editor,- "cursorAtFirstLine",- checkCursorAtFirstLine(editor)- );- const cursorAtLastLine = useEditorContextKey(- editor,- "cursorAtLastLine",- checkCursorAtLastLine(editor)- );- editor.onDidChangeCursorPosition(() => {- cursorAtFirstLine?.set(checkCursorAtFirstLine(editor));- });- editor.onDidChangeCursorPosition(() => {- cursorAtLastLine?.set(checkCursorAtLastLine(editor));- });- editor.addCommand(- monaco.KeyCode.UpArrow,- () => {- // When- // - the cursor is at the first line- // - then press "CtrlCmd + Up"- // We trigger the "history" event- emit("history", "up", editor);- },- // Tell the editor this should be only- // triggered when both of the two conditions are satisfied.- "isTerminalEditor && !readonly && !content && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"- );- editor.addCommand(- monaco.KeyCode.DownArrow,- () => {- // When- // - the cursor is at the last line- // - then press "CtrlCmd + Down"- // We trigger the "history" event- emit("history", "down", editor);- },- // Tell the editor this should be only- // triggered when both of the two conditions are satisfied.- "isTerminalEditor && !readonly && cursorAtLastLine && editorTextFocus && !suggestWidgetVisible && !renameInputVisible && !inSnippetMode && !quickFixWidgetVisible"- );-- watch(- pendingFormatContentCommand,- (pending) => {- if (pending) {- formatEditorContent(editor, dialect.value);- nextTick(() => {- pendingFormatContentCommand.value = false;- });- }- },- { immediate: true }- );-- if (!props.readonly) {- nextTick(() => editor.focus());- }-};--useEmitteryEventListener(editorEvents, "format-content", () => {- pendingFormatContentCommand.value = true;-});--const EDITOR_OPTIONS = computed<Editor.IStandaloneEditorConstructionOptions>(- () => ({- theme: "vs-dark",- lineNumbers: getLineNumber,- lineNumbersMinChars: firstLinePrompt.value.length + 3,- cursorStyle: props.readonly ? "underline" : "block",- scrollbar: {- vertical: "hidden",- horizontal: "hidden",- alwaysConsumeMouseWheel: false,- },- overviewRulerLanes: 0,- })-);-</script>--<style lang="postcss" scoped>-.bb-compact-sql-editor :deep(.monaco-editor .line-numbers) {- padding-right: 0 !important;-}-</style>diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vueindex 7608d2b12e..0359dac794 100644--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue+++ b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue@@ -15,28 +15,21 @@:data-height="queryListHeight"><div v-for="query in queryList" :key="query.id" class="relative">- <Suspense>- <CompactSQLEditor- v-model:content="query.statement"- class="min-h-8"- :class="[- isEditableQueryItem(query)- ? 'active-editor'- : 'read-only-editor',- ]"- :readonly="!isEditableQueryItem(query)"- @execute="handleExecute"- @history="handleHistory"- @clear-screen="handleClearScreen"- />- <template #fallback>- <div- class="w-full min-h-8 flex flex-col items-center justify-center"- >- <BBSpin />- </div>- </template>- </Suspense>+ <ReactPageMount+ page="CompactSQLEditor"+ container-class="w-full"+ :class="+ isEditableQueryItem(query) ? 'active-editor' : 'read-only-editor'+ "+ :pageProps="{+ content: query.statement,+ readonly: !isEditableQueryItem(query),+ onChange: (value: string) => (query.statement = value),+ onExecute: handleExecute,+ onHistory: handleHistory,+ onClearScreen: handleClearScreen,+ }"+ /><ResultViewV1v-if="query.params && query.resultSet"class="p-2"@@ -80,14 +73,7 @@<script lang="ts" setup>import { useElementSize } from "@vueuse/core";-import {- computed,- defineAsyncComponent,- ref,- unref,- watch,- watchEffect,-} from "vue";+import { computed, ref, unref, watch, watchEffect } from "vue";import { BBSpin } from "@/bbkit";import type { IStandaloneCodeEditor } from "@/components/MonacoEditor";import ReactPageMount from "@/react/ReactPageMount.vue";@@ -100,10 +86,6 @@ import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";import { ResultViewV1 } from "../../EditorCommon";import { useHistory } from "./useHistory";-const CompactSQLEditor = defineAsyncComponent(- () => import("./CompactSQLEditor.vue")-);-const tabStore = useSQLEditorTabStore();const webTerminalStore = useWebTerminalStore();const databaseStore = useDatabaseV1Store();