Skip to content

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

refactor(react): migrate other sql editor components to react (#20270)

ecmadaobbd1721e1360
diff --git a/docs/superpowers/specs/2026-05-08-sql-editor-react-migration-stage-21-design.md b/docs/superpowers/specs/2026-05-08-sql-editor-react-migration-stage-21-design.md
new file mode 100644
index 0000000000..9449686ac4
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-08-sql-editor-react-migration-stage-21-design.md
@@ -0,0 +1,269 @@
+# Stage 21 — SQL Editor host-shell flip (Vue → React)
+
+**Date:** 2026-05-08
+**Status:** Design — not yet started
+**Predecessor:** Stage 20 ("ResultView spike", merged in PR #20227)
+
+This is the final scheduled stage of the bottom-up SQL Editor React
+migration. After it, every host shell that currently uses
+`<ReactPageMount>` to mount a single React child becomes a React
+component directly. The AI plugin (`@/plugins/ai/components/*`) stays
+Vue-mounted via a new reverse-direction bridge (`VueMount`); porting it
+is deferred to a separate Stage 22 effort if/when desired.
+
+## 1. Why this is mostly mechanical
+
+Every shell already does the same thing: render a `<ReactPageMount
+page="…">` whose page is the entire interactive surface. The Vue
+wrappers exist only because Vue used to host the inner content; now
+they're routing pass-throughs.
+
+The only non-trivial work is:
+1. Building the reverse-direction `<VueMount>` bridge so the AI plugin
+ can sit inside a React shell without porting it.
+2. Wiring the React root into the existing Vue Router entry point
+ (`SQLEditorHomePage` is the route target).
+
+Everything else is a per-file flip that should compile after one pass
+through the file plus updating callers.
+
+## 2. Scope (~759 LOC of Vue, plus ~50 LOC of new bridge code)
+
+| File | LOC | What it does today | Post-Stage-21 |
+|---|---|---|---|
+| `views/sql-editor/SQLEditorHomePage.vue` | 195 | Top-level: workspace switcher + sidebar + `<RouterView>` for SQL editor sub-routes | React `SQLEditorHomePage.tsx` |
+| `views/sql-editor/SQLEditorPage.vue` | 34 | Trivial wrapper around `<EditorPanel>` | React `SQLEditorPage.tsx` |
+| `views/sql-editor/EditorPanel/EditorPanel.vue` | 35 | Trivial wrapper, picks `StandardPanel` vs `TerminalPanel` based on tab mode | React `EditorPanel.tsx` |
+| `views/sql-editor/EditorPanel/Panels.vue` | 205 | Splitter / layout. Hosts `<AIChatToSQL>` (AI plugin) via Vue child | React `Panels.tsx` + `<VueMount>` for AI plugin |
+| `views/sql-editor/EditorPanel/StandardPanel.vue` | 120 | Wraps React `<EditorMain>` + React `<ResultPanel>` (today via `<ReactPageMount>`) plus AI hoist | React `StandardPanel.tsx` + `<VueMount>` for AI |
+| `views/sql-editor/EditorPanel/TerminalPanel.vue` | 184 | Wraps `<CompactSQLEditor>`, `<ConnectionHolder>`, `<ResultViewPage>` (all React); plus history/cancel UI | React `TerminalPanel.tsx` |
+| `views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue` | 298 | Wraps `BatchQuerySelect` (React) + per-database `<DatabaseQueryContext>` (Vue, mounts ResultView) inside an `NTabs` | React `ResultPanel.tsx` directly mounting `ResultView` |
+| `views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue` | 125 | Today wraps `<ReactPageMount page="ResultViewPage">` + EXECUTING/CANCELLED states | React `DatabaseQueryContext.tsx` (or inlined into `ResultPanel.tsx`) |
+
+Plus a tail item:
+
+- `frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue` (17
+ LOC, inline SVG) — last surviving Vue file under SchemaDiagram. Used
+ by `DatabaseEditor.vue` (already deprecated) and SQL Editor sub-tab
+ buttons. Inline the SVG into the React caller(s) and delete.
+
+## 3. The reverse-direction `<VueMount>` bridge
+
+`<ReactPageMount.vue>` lets Vue host a React component. Stage 21 needs
+the inverse — React shells host the AI plugin (`<AIChatToSQL>`) which
+stays Vue. Build a small `VueMount.tsx` mirroring the existing pattern.
+
+### Shape
+
+```tsx
+// frontend/src/react/components/VueMount.tsx
+import { useEffect, useRef } from "react";
+import { type Component, createApp, type App } from "vue";
+
+interface VueMountProps {
+ /** The Vue component to mount. */
+ component: Component;
+ /** Props forwarded to the Vue component. Re-mounted-in-place when the
+ * reference changes — Vue's `app.unmount()` then `createApp(...).mount()`. */
+ props?: Record<string, unknown>;
+ className?: string;
+}
+
+export function VueMount({ component, props, className }: VueMountProps) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const appRef = useRef<App | null>(null);
+
+ useEffect(() => {
+ if (!containerRef.current) return;
+ const app = createApp(component, props);
+ // Inherit i18n + Pinia from the host app — pass via `provide` or
+ // re-install the same plugins. Simplest: reuse the global Vue app's
+ // pinia + i18n instances by importing them.
+ // (Implementation note: the existing Vue app exposes its `pinia` and
+ // `i18n` via module-level imports. Apply them here so stores match.)
+ app.mount(containerRef.current);
+ appRef.current = app;
+ return () => {
+ app.unmount();
+ appRef.current = null;
+ };
+ }, [component, props]);
+
+ return <div ref={containerRef} className={className} />;
+}
+```
+
+### What needs to be solved before this works
+
+1. **Pinia store sharing.** The AI plugin reads `useSQLEditorTabStore`,
+ `useCurrentUserV1`, etc. The Vue app installs Pinia at startup; a
+ freshly-created `createApp` doesn't share that store. Pattern: import
+ the singleton `pinia` instance from `@/store` and `app.use(pinia)`
+ inside `VueMount` so the new app shares the same store registry.
+2. **i18n sharing.** Same shape — import the existing `i18n` instance
+ and `app.use(i18n)`. The React tree already calls
+ `i18n.changeLanguage()` via `react-i18next`; the Vue mount picks up
+ the same language because it's the same instance.
+3. **Vue Router?** Probably not needed — the AI plugin doesn't render
+ route-driven content, it's a chat panel. If it does use
+ `useRoute()`, install the singleton router too.
+4. **Re-render strategy.** When `props` reference changes (parent React
+ re-renders), do we unmount/remount the Vue app or update its props?
+ Vue 3 supports `app._instance.props.foo = bar` but it's brittle.
+ Cleaner: depend the `useEffect` on a `JSON.stringify(props)` or
+ memoize the props object, and unmount+remount on change. The AI
+ plugin re-renders rarely so the cost is fine.
+5. **Layer/portal stacking.** The AI plugin's overlays (modals, tooltips)
+ should respect the React layer policy at
+ `frontend/src/react/components/ui/layer.ts`. Either pass them through
+ (Vue overlays mount into the same DOM) or accept that the AI plugin
+ keeps its own stacking order until Stage 22.
+
+The bridge is ~50 LOC plus a careful look at points 1-4. **This is the
+risk in Stage 21** — everything else is a flip.
+
+## 4. Per-file flip plan
+
+Order: bottom-up (leaves first), so each PR's mounted child is already
+React when its parent flips.
+
+### 4.1. `DatabaseQueryContext.vue` → `DatabaseQueryContext.tsx`
+
+Today: 125 LOC, mostly the EXECUTING/CANCELLED states + a
+`ReactPageMount` for `ResultViewPage`.
+
+After: a React component that does the same thing — show a spinner
+during EXECUTING, a "click to retry" panel during CANCELLED, otherwise
+render `<ResultView>` directly. The `ReactPageMount` indirection
+disappears entirely; the new file imports `ResultView` from the
+sibling React tree.
+
+Notes:
+- The `useExecuteSQL` composable is already called from React in
+ `EditorMain.tsx`; the same pattern works here.
+- The polling timer (`useCurrentTimestamp`) is already a Vue composable
+ with no Pinia dependency — port to a React `useState` + `setInterval`
+ hook. Or just inline the elapsed-time calculation into the React
+ component since this is the only consumer.
+
+### 4.2. `ResultPanel.vue` → `ResultPanel.tsx`
+
+Today: NTabs over per-context `<DatabaseQueryContext>`, plus the
+`BatchQuerySelect` React mount, plus a custom right-click context menu
+(`NDropdown`) for closing tabs.
+
+After: shadcn `<Tabs>` from `@/react/components/ui/tabs.tsx` (already
+used by Stage 20's `ResultView`), `BatchQuerySelect` and
+`DatabaseQueryContext` (now React) imported directly, custom context
+menu wired through the existing `ContextMenu` React primitive (built
+in Stage 18).
+
+### 4.3. `TerminalPanel.vue` → `TerminalPanel.tsx`
+
+Today: a list-of-queries view with each query rendered as
+`<CompactSQLEditor>` + `<ResultViewPage>`-via-`ReactPageMount`. Plus
+history navigation and cancel UI.
+
+After: same shape, `<ResultView>` imported directly. The `useHistory`
+composable migrates to a React hook (no Pinia dependency).
+
+### 4.4. `StandardPanel.vue` → `StandardPanel.tsx`
+
+Today: `<EditorMain>` (React, via `ReactPageMount`) + `<ResultPanel>`
+(Vue, but trivial after step 4.2) + `<AIChatToSQL>` (Vue, AI plugin).
+
+After: React component, both children direct React imports, AI plugin
+via `<VueMount component={AIChatToSQL} props={...} />`.
+
+### 4.5. `Panels.vue` → `Panels.tsx`
+
+Today: splitter layout between `<EditorPanel>`/`<StandardPanel>`,
+`<DiagramPanel>` (React via `ReactPageMount`), `<AIChatToSQL>` hoist.
+
+After: React, splitter via `react-resizable-panels` (already a peer in
+this codebase per `package.json`), AI hoist via `<VueMount>`.
+
+### 4.6. `EditorPanel.vue` → `EditorPanel.tsx`
+
+Trivial — picks `StandardPanel` vs `TerminalPanel` based on tab mode.
+No state, no children of its own.
+
+### 4.7. `SQLEditorPage.vue` → `SQLEditorPage.tsx`
+
+Trivial wrapper around `<EditorPanel>`.
+
+### 4.8. `SQLEditorHomePage.vue` → `SQLEditorHomePage.tsx` + Vue Router shim
+
+This is the route target. The route entry in `frontend/src/router/`
+points at `SQLEditorHomePage.vue`. Two options:
+
+- **A. Keep the route as a Vue file** (`SQLEditorHomePage.vue` becomes
+ a 5-line shim that mounts the React root via `<ReactPageMount
+ page="SQLEditorHomePage">`). Cheapest. Recommended.
+- **B. Migrate the route into a React Router setup**. The codebase
+ already has a partial React Router shell at
+ `@/react/router` (per `IAMRemindDialog.tsx`'s `useNavigate` usage),
+ but the SQL Editor route is still in Vue Router. Out of scope.
+
+Pick A. The route file ends up looking like every other `ReactPageMount`
+shim Stages 18-20 already established.
+
+### 4.9. `SchemaDiagramIcon.vue` (17 LOC)
+
+Inline the SVG into its callers (`viewState.tsx` Vue JSX; the host shell
+sub-tab button which is now React after this stage). Delete the file.
+
+## 5. Pre-stage checklist
+
+Before any of the per-file flips, land:
+
+1. **`VueMount.tsx`** with the four pitfalls (Pinia, i18n, props
+ re-render, layer stacking) explicitly handled. A test seed that
+ mounts a trivial `<button>{{ count }}</button>` Vue component inside
+ React, asserts the rendered DOM, and verifies a Pinia-store-reading
+ Vue component sees the same store as the rest of the app.
+2. **Inventory of `<AIChatToSQL>`'s contract** — what props does it
+ take? What stores does it read? What events does it emit upward?
+ The bridge has to support that contract.
+3. **Decide on the `props` re-render strategy** (point 4 above).
+ Document it in `VueMount.tsx`'s JSDoc.
+
+## 6. Acceptance criteria
+
+- All eight `.vue` files listed in §2 deleted.
+- `frontend/src/views/sql-editor/` directory contains zero `.vue` files
+ (or only the `SQLEditorHomePage.vue` route-shim per option A in §4.8).
+- AI plugin functional inside the new React shells (regression-test:
+ open AI chat panel, ask a question, see the response stream).
+- `VueMount.tsx` covered by at least one unit test.
+- Type-check + lint green.
+- Manual smoke test of every SQL Editor surface: standard panel,
+ terminal panel, batch query, result view (single + multi), schema
+ pane, schema diagram, AI chat. (The Stage 18 walkthrough routine
+ template is reusable.)
+
+## 7. Risks
+
+1. **`VueMount` bridge complexity.** Sharing Pinia + i18n + router
+ instances between two Vue apps in the same page is unusual. If
+ stores end up duplicated, we get the kind of "two sources of truth"
+ bugs that are hard to trace.
+2. **Vue Router pass-through.** `SQLEditorHomePage.vue` is the route
+ target; if the React component doesn't render `<RouterView>`
+ correctly, sub-routes (history/audit views inside SQL Editor)
+ break.
+3. **Re-render storms in the AI plugin's `VueMount`.** If parent React
+ re-renders frequently and we unmount/remount the Vue tree on every
+ re-render, the AI chat history gets nuked. Memoize the `props`
+ object aggressively.
+4. **Naive UI layer leakage.** The AI plugin uses Naive UI overlays.
+ Once it lives inside a React tree it might portal into a non-layer
+ `document.body` root and stack incorrectly. Worth a manual check
+ after the `StandardPanel` flip.
+
+## 8. After Stage 21
+
+The SQL Editor's only Vue surface is the AI plugin under the
+`<VueMount>` bridge. **Stage 22 (optional)** — port the AI plugin if
+the maintenance cost of the bridge outweighs the porting cost. The
+roadmap memory tracks this as conditional, not mandatory.
diff --git a/frontend/pnpm-workspace.yaml b/frontend/pnpm-workspace.yaml
index 52e7472b2e..f99863c61a 100644
--- a/frontend/pnpm-workspace.yaml
+++ b/frontend/pnpm-workspace.yaml
@@ -8,4 +8,11 @@ peerDependencyRules:
allowBuilds:
core-js: true
esbuild: true
- leveldown: true
+ # `pouchdb` pulls leveldown in transitively ([email protected] via
+ # [email protected], plus [email protected] directly) for Node-side use, but
+ # the frontend only runs pouchdb in the browser via `level-js`/IndexedDB
+ # — the native binding is never loaded at runtime. [email protected] is
+ # deprecated and fails to build on Node 24 / Apple Silicon. Explicit
+ # `false` opts out of the build without triggering pnpm 11's
+ # ERR_PNPM_IGNORED_BUILDS error.
+ leveldown: false
diff --git a/frontend/src/components/IAMRemindModal.vue b/frontend/src/components/IAMRemindModal.vue
deleted file mode 100644
index 9d826bed6b..0000000000
--- a/frontend/src/components/IAMRemindModal.vue
+++ /dev/null
@@ -1,176 +0,0 @@
-<template>
- <BBModal
- :show="state.showModal"
- :title="$t('remind.role-expire.title')"
- @close="onClose"
- >
- <div class="w-120 max-w-[calc(100vw-10rem)]">
- <div class="flex flex-col gap-y-2">
- <p>{{ $t("remind.role-expire.content") }}</p>
- <ul class="list-disc textinfolabel ml-4">
- <li v-for="(data, i) in pendingExpireRoles" :key="i">
- {{ displayRoleTitle(data.role.name) }}:
- <span class="text-red-400">
- {{ formatAbsoluteDateTime(data.expiration.valueOf()) }}
- </span>
- </li>
- </ul>
- </div>
- <NCheckbox v-model:checked="state.checked" class="mt-6">
- <span class="textinfolabel">
- {{ $t("remind.role-expire.checkbox") }}
- </span>
- </NCheckbox>
-
- <div class="mt-7 flex justify-end gap-x-2">
- <NButton @click="onClose">
- {{ $t("common.dismiss") }}
- </NButton>
- <NButton v-if="!isInProjectPage" type="primary" @click="onClick">
- {{ $t("remind.role-expire.go-to-project") }}
- </NButton>
- </div>
- </div>
- </BBModal>
-</template>
-
-<script lang="tsx" setup>
-import dayjs from "dayjs";
-import { orderBy } from "lodash-es";
-import { NButton, NCheckbox } from "naive-ui";
-import { computed, reactive, watch } from "vue";
-import { useRoute, useRouter } from "vue-router";
-import { BBModal } from "@/bbkit";
-import {
- useCurrentUserV1,
- useProjectIamPolicyStore,
- useProjectV1Store,
- useRoleStore,
-} from "@/store";
-import type { Role } from "@/types/proto-es/v1/role_service_pb";
-import {
- autoProjectRoute,
- displayRoleTitle,
- filterBindingsByUserName,
- formatAbsoluteDateTime,
- storageKeyIamRemind,
- useDynamicLocalStorage,
-} from "@/utils";
-import { convertFromExpr } from "@/utils/issue/cel";
-
-const props = defineProps<{
- projectName: string;
-}>();
-
-const state = reactive<{
- showModal: boolean;
- checked: boolean;
-}>({
- showModal: false,
- checked: false,
-});
-
-const route = useRoute();
-const router = useRouter();
-const me = useCurrentUserV1();
-const iamRemindState = useDynamicLocalStorage<
- Map<string /* {project}.{pending expired roles} */, boolean /* show remind */>
->(
- computed(() => storageKeyIamRemind(me.value.email)),
- new Map()
-);
-const projectStore = useProjectV1Store();
-const roleStore = useRoleStore();
-const projectIamPolicyStore = useProjectIamPolicyStore();
-
-const project = computed(() =>
- projectStore.getProjectByName(props.projectName)
-);
-
-const isInProjectPage = computed(() => {
- return route.path.startsWith(`/${props.projectName}`);
-});
-
-const pendingExpireRoles = computed(
- (): {
- role: Role;
- expiration: dayjs.Dayjs;
- }[] => {
- const policy = projectIamPolicyStore.getProjectIamPolicy(props.projectName);
- const bindings = filterBindingsByUserName({
- policy,
- name: me.value.name,
- ignoreGroup: true,
- });
-
- const results: {
- role: Role;
- expiration: dayjs.Dayjs;
- }[] = [];
-
- for (const binding of bindings) {
- const role = roleStore.getRoleByName(binding.role);
- if (!role) {
- continue;
- }
- if (!binding.parsedExpr) {
- continue;
- }
- const conditionExpr = convertFromExpr(binding.parsedExpr);
- if (!conditionExpr.expiredTime) {
- continue;
- }
- const expiration = dayjs(conditionExpr.expiredTime);
- const now = dayjs();
-
- if (now.isBefore(expiration) && now.add(2, "days").isAfter(expiration)) {
- results.push({
- role,
- expiration,
- });
- }
- }
-
- return orderBy(
- results,
- [(data) => data.expiration.toDate().getTime()],
- "asc"
- );
- }
-);
-
-const key = computed(() => {
- if (pendingExpireRoles.value.length === 0) {
- return "";
- }
- return `${props.projectName}.${pendingExpireRoles.value.map((data) => data.role.name).join("&")}`;
-});
-
-watch(
- () => key.value,
- (key) => {
- if (!key) {
- return;
- }
- if (!iamRemindState.value.has(key)) {
- iamRemindState.value.set(key, true);
- }
- state.showModal = iamRemindState.value.get(key) ?? false;
- },
- { immediate: true }
-);
-
-const onClose = () => {
- if (state.checked) {
- iamRemindState.value.set(key.value, false);
- }
- state.showModal = false;
-};
-
-const onClick = () => {
- state.showModal = false;
- router.push({
- ...autoProjectRoute(project.value),
- });
-};
-</script>
diff --git a/frontend/src/components/ProvideSQLEditorContext.test.ts b/frontend/src/components/ProvideSQLEditorContext.test.ts
deleted file mode 100644
index 51a3269d9c..0000000000
--- a/frontend/src/components/ProvideSQLEditorContext.test.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-import { mount } from "@vue/test-utils";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-import { defineComponent, h, nextTick, reactive } from "vue";
-
-const mocks = vi.hoisted(() => ({
- route: {
- name: "sql-editor.project",
- fullPath: "/sql-editor/projects/prod",
- params: { project: "prod" },
- query: {},
- matched: [] as Array<{ meta: { requiredPermissionList?: () => string[] } }>,
- },
- routerReplace: vi.fn(),
- maybeSwitchProject: vi.fn(async (project: string) => {
- if (mocks.editorStore) {
- mocks.editorStore.project = project;
- }
- return true;
- }),
- editorStore: undefined as
- | {
- project: string;
- projectContextReady: boolean;
- allowViewALLProjects: boolean;
- storedLastViewedProject: string;
- setProject: (project: string) => void;
- }
- | undefined,
- reactGuardAllows: true,
-}));
-
-vi.mock("@vueuse/core", () => ({
- useLocalStorage: (_key: string, initial: unknown) => ({ value: initial }),
-}));
-
-vi.mock("vue-router", async (importOriginal) => {
- const actual = await importOriginal<typeof import("vue-router")>();
- return {
- ...actual,
- useRoute: () => mocks.route,
- useRouter: () => ({
- replace: mocks.routerReplace,
- }),
- };
-});
-
-vi.mock("@/react/ReactPageMount.vue", async () => {
- const { defineComponent, h, onMounted, ref } = await import("vue");
- return {
- default: defineComponent({
- name: "MockReactPageMount",
- props: {
- page: {
- type: String,
- required: true,
- },
- pageProps: {
- type: Object,
- default: undefined,
- },
- },
- setup(props) {
- const target = ref<HTMLDivElement | null>(null);
- onMounted(() => {
- props.pageProps?.onReady?.(
- mocks.reactGuardAllows ? target.value : null
- );
- });
- return () =>
- h("div", { "data-testid": "react-permission-shell" }, [
- h("div", {
- ref: target,
- "data-testid": "react-permission-target",
- class: props.pageProps?.targetClassName,
- }),
- !mocks.reactGuardAllows &&
- h("div", { "data-testid": "react-permission-denied" }),
- ]);
- },
- }),
- };
-});
-
-vi.mock("@/bbkit", async () => {
- const { defineComponent, h } = await import("vue");
- return {
- BBSpin: defineComponent({
- name: "MockBBSpin",
- setup() {
- return () => h("div", { "data-testid": "sql-editor-spinner" });
- },
- }),
- };
-});
-
-vi.mock("@/plugins/ai", async () => {
- const { defineComponent, h } = await import("vue");
- return {
- ProvideAIContext: defineComponent({
- name: "MockProvideAIContext",
- setup(_, { slots }) {
- return () =>
- h("div", { "data-testid": "provide-ai-context" }, slots.default?.());
- },
- }),
- };
-});
-
-vi.mock("@/composables/useEmitteryEventListener", () => ({
- useEmitteryEventListener: vi.fn(),
-}));
-
-vi.mock("@/composables/useRouteChangeGuard", () => ({
- useRouteChangeGuard: vi.fn(),
-}));
-
-vi.mock("@/plugins/i18n", () => ({
- t: (key: string) => key,
-}));
-
-vi.mock("vue-i18n", () => ({
- useI18n: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock("@/router/sqlEditor", () => ({
- SQL_EDITOR_DATABASE_MODULE: "sql-editor.database",
- SQL_EDITOR_HOME_MODULE: "sql-editor.home",
- SQL_EDITOR_INSTANCE_MODULE: "sql-editor.instance",
- SQL_EDITOR_PROJECT_MODULE: "sql-editor.project",
- SQL_EDITOR_WORKSHEET_MODULE: "sql-editor.worksheet",
-}));
-
-vi.mock("@/store/modules/sqlEditor/legacy/migration", () => ({
- migrateLegacyCache: vi.fn(async () => undefined),
-}));
-
-vi.mock("@/views/sql-editor/context", async () => {
- const { ref } = await import("vue");
- return {
- ASIDE_PANEL_TABS: ["WORKSHEET", "CONNECTION"],
- useSQLEditorContext: () => ({
- asidePanelTab: ref("WORKSHEET"),
- events: {},
- maybeSwitchProject: mocks.maybeSwitchProject,
- }),
- };
-});
-
-vi.mock("@/types", () => ({
- DEFAULT_SQL_EDITOR_TAB_MODE: "READONLY",
- BASIC_WORKSPACE_PERMISSIONS: [],
- isValidDatabaseName: (name?: string) => name?.startsWith("instances/"),
- isValidInstanceName: (name?: string) => name?.startsWith("instances/"),
- isValidProjectName: (name?: string) => name?.startsWith("projects/"),
-}));
-
-vi.mock("@/utils", () => ({
- emptySQLEditorConnection: () => ({}),
- extractDatabaseResourceName: (name: string) => ({
- instance: name.split("/databases/")[0],
- databaseName: name.split("/databases/")[1] ?? "",
- }),
- extractInstanceResourceName: (name: string) => name.split("/").pop() ?? name,
- extractProjectResourceName: (name: string) => name.split("/").pop() ?? name,
- extractWorksheetConnection: vi.fn(async () => ({})),
- extractWorksheetID: (name: string) => name.split("/").pop() ?? name,
- getDefaultPagination: () => 100,
- getSheetStatement: () => "",
- isWorksheetReadableV1: () => true,
- STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB: "bb.sql-editor.sidebar-tab",
- suggestedTabTitleForSQLEditorConnection: () => "tab",
-}));
-
-vi.mock("@/store", () => ({
- pushNotification: vi.fn(),
- usePermissionStore: () => ({
- currentPermissions: new Set<string>(["bb.test"]),
- currentPermissionsInProjectV1: () => new Set<string>(["bb.test"]),
- }),
- useActuatorV1Store: () => ({
- serverInfo: { defaultProject: "projects/default" },
- }),
- useDatabaseV1Store: () => ({
- getOrFetchDatabaseByName: vi.fn(async (name: string) => ({
- name,
- project: "projects/prod",
- })),
- }),
- useProjectV1Store: () => ({
- fetchProjectList: vi.fn(async () => ({
- projects: [{ name: "projects/prod" }],
- })),
- getProjectByName: (name: string) => ({
- name,
- allowRequestRole: true,
- }),
- }),
- useSQLEditorStore: () => mocks.editorStore,
- useSQLEditorTabStore: () => ({
- openTabList: [],
- currentTab: undefined,
- getTabByWorksheet: vi.fn(),
- updateTab: vi.fn(),
- addTab: vi.fn(),
- initProject: vi.fn(async () => undefined),
- }),
- useWorkSheetStore: () => ({
- getOrFetchWorksheetByName: vi.fn(async () => undefined),
- getWorksheetByName: vi.fn(() => undefined),
- }),
-}));
-
-import ProvideSQLEditorContext from "./ProvideSQLEditorContext.vue";
-
-const mountContext = () =>
- mount(ProvideSQLEditorContext, {
- attachTo: document.body,
- global: {
- stubs: {
- RouterView: defineComponent({
- name: "MockRouterView",
- setup() {
- return () =>
- h("div", { "data-testid": "sql-editor-route-content" });
- },
- }),
- },
- },
- });
-
-beforeEach(() => {
- document.body.innerHTML = '<ul id="sql-editor-debug"></ul>';
- mocks.routerReplace.mockClear();
- mocks.maybeSwitchProject.mockClear();
- mocks.reactGuardAllows = true;
- mocks.route.name = "sql-editor.project";
- mocks.route.fullPath = "/sql-editor/projects/prod";
- mocks.route.params = { project: "prod" };
- mocks.route.query = {};
- mocks.editorStore = reactive({
- project: "projects/prod",
- projectContextReady: false,
- allowViewALLProjects: true,
- storedLastViewedProject: "projects/prod",
- setProject(project: string) {
- this.project = project;
- },
- });
-});
-
-afterEach(() => {
- document.body.innerHTML = "";
-});
-
-describe("ProvideSQLEditorContext permission shell bridge", () => {
- test("renders the loading state until project context is ready", () => {
- mountContext();
-
- expect(
- document.body.querySelector("[data-testid='sql-editor-spinner']")
- ).not.toBeNull();
- expect(
- document.body.querySelector("[data-testid='sql-editor-route-content']")
- ).toBeNull();
- });
-
- test("teleports SQL Editor route content into the React permission target", async () => {
- mountContext();
- await nextTick();
-
- mocks.editorStore!.projectContextReady = true;
- await nextTick();
- await nextTick();
-
- const target = document.body.querySelector(
- "[data-testid='react-permission-target']"
- );
- const content = document.body.querySelector(
- "[data-testid='sql-editor-route-content']"
- );
-
- expect(target?.contains(content)).toBe(true);
- expect(target?.className).toContain("h-full");
- expect(target?.className).toContain("flex");
- expect(
- document.body.querySelector("[data-testid='provide-ai-context']")
- ).not.toBeNull();
- });
-
- test("withholds SQL Editor route content when the React guard denies access", async () => {
- mocks.reactGuardAllows = false;
- mountContext();
- await nextTick();
-
- mocks.editorStore!.projectContextReady = true;
- await nextTick();
- await nextTick();
-
- expect(
- document.body.querySelector("[data-testid='react-permission-denied']")
- ).not.toBeNull();
- expect(
- document.body.querySelector("[data-testid='sql-editor-route-content']")
- ).toBeNull();
- });
-});
diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vue
deleted file mode 100644
index 7c7cee5da0..0000000000
--- a/frontend/src/components/ProvideSQLEditorContext.vue
+++ /dev/null
@@ -1,436 +0,0 @@
-<template>
- <teleport to="#sql-editor-debug">
- <li>[ProvideContext]project: {{ editorStore.project }}</li>
- <li>
- [ProvideContext]projectContextReady:
- {{ editorStore.projectContextReady }}
- </li>
- <li>
- [ProvideContext]allowViewALLProjects:
- {{ editorStore.allowViewALLProjects }}
- </li>
- </teleport>
-
- <Suspense>
- <template v-if="editorStore.projectContextReady">
- <ReactPageMount
- page="RoutePermissionGuardShell"
- :page-props="{
- project,
- routeKey: route.fullPath,
- className: 'm-6',
- targetClassName: 'h-full min-h-0 flex flex-col',
- onReady: handlePermissionReady,
- }"
- />
- <teleport v-if="routePermissionTarget" :to="routePermissionTarget">
- <ProvideAIContext>
- <router-view />
- </ProvideAIContext>
- </teleport>
- </template>
- <div v-else class="flex items-center justify-center h-screen">
- <BBSpin />
- </div>
- </Suspense>
-</template>
-
-<script lang="ts" setup>
-import { useLocalStorage } from "@vueuse/core";
-import { debounce, head, omit } from "lodash-es";
-import { computed, nextTick, onMounted, shallowRef, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { useRoute, useRouter } from "vue-router";
-import { BBSpin } from "@/bbkit";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { useRouteChangeGuard } from "@/composables/useRouteChangeGuard";
-import { ProvideAIContext } from "@/plugins/ai";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import {
- SQL_EDITOR_DATABASE_MODULE,
- SQL_EDITOR_HOME_MODULE,
- SQL_EDITOR_INSTANCE_MODULE,
- SQL_EDITOR_PROJECT_MODULE,
- SQL_EDITOR_WORKSHEET_MODULE,
-} from "@/router/sqlEditor";
-import {
- pushNotification,
- useActuatorV1Store,
- useDatabaseV1Store,
- useProjectV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
- useWorkSheetStore,
-} from "@/store";
-import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
-import {
- DEFAULT_SQL_EDITOR_TAB_MODE,
- isValidDatabaseName,
- isValidInstanceName,
- isValidProjectName,
-} from "@/types";
-import {
- emptySQLEditorConnection,
- extractDatabaseResourceName,
- extractInstanceResourceName,
- extractProjectResourceName,
- extractWorksheetConnection,
- extractWorksheetID,
- getDefaultPagination,
- getSheetStatement,
- isWorksheetReadableV1,
- STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,
- suggestedTabTitleForSQLEditorConnection,
-} from "@/utils";
-import {
- ASIDE_PANEL_TABS,
- type AsidePanelTab,
- useSQLEditorContext,
-} from "@/views/sql-editor/context";
-
-const { t } = useI18n();
-const route = useRoute();
-const router = useRouter();
-const actuatorStore = useActuatorV1Store();
-const projectStore = useProjectV1Store();
-const databaseStore = useDatabaseV1Store();
-const editorStore = useSQLEditorStore();
-const worksheetStore = useWorkSheetStore();
-const tabStore = useSQLEditorTabStore();
-const routePermissionTarget = shallowRef<HTMLElement | null>(null);
-const {
- asidePanelTab,
- events: editorEvents,
- maybeSwitchProject,
-} = useSQLEditorContext();
-
-const handlePermissionReady = (target: HTMLElement | null) => {
- routePermissionTarget.value = target;
-};
-
-useRouteChangeGuard(
- computed(() => {
- return (
- tabStore.openTabList.find((tab) => tab.status !== "CLEAN") !== undefined
- );
- }),
- `${t("sql-editor.tab.unsaved-worksheet")} ${t("common.leave-without-saving")}`
-);
-
-const fallbackToFirstProject = async () => {
- const { projects } = await projectStore.fetchProjectList({
- pageSize: getDefaultPagination(),
- filter: {
- excludeDefault: true,
- },
- });
- return head(projects)?.name ?? actuatorStore.serverInfo?.defaultProject ?? "";
-};
-
-const initializeProject = async () => {
- const projectInQuery = route.query.project as string;
- const projectInParams = route.params.project as string;
- let project: string = "";
- let initializeSuccess = false;
-
- if (typeof projectInQuery === "string" && projectInQuery) {
- // Legacy "?project={project}"
- project = `projects/${projectInQuery}`;
- } else if (typeof projectInParams === "string" && projectInParams) {
- // "/sql-editor/projects/{project}"
- project = `projects/${projectInParams}`;
- } else {
- // plain "/sql-editor"
- project = editorStore.storedLastViewedProject;
- }
-
- initializeSuccess = !!(await maybeSwitchProject(project));
- if (!initializeSuccess) {
- // Maybe the cached project name is valid, but users cannot get it any more (removed, not permission, etc).
- // So we need to fallback to the first accessible project.
- project = await fallbackToFirstProject();
- initializeSuccess = !!(await maybeSwitchProject(project));
- }
-
- if (!initializeSuccess) {
- // clear last visit project.
- editorStore.setProject("");
- }
- return editorStore.project;
-};
-
-const project = computed(() => {
- const proj = projectStore.getProjectByName(editorStore.project);
- if (!isValidProjectName(proj.name)) {
- return;
- }
- return proj;
-});
-
-watch(
- () => route.fullPath,
- () => {
- routePermissionTarget.value = null;
- },
- { flush: "sync" }
-);
-
-const switchWorksheet = async (sheetName: string) => {
- const openedSheetTab = tabStore.getTabByWorksheet(sheetName);
-
- const sheet = await worksheetStore.getOrFetchWorksheetByName(sheetName);
- if (!sheet) {
- if (openedSheetTab) {
- // If a sheet is open in a tab but it returns 404 NOT_FOUND
- // that means the sheet has been deleted somewhere else.
- // We need to turn the sheet to an unsaved tab.
- tabStore.updateTab(openedSheetTab.id, {
- worksheet: "",
- status: "DIRTY",
- });
- }
- return false;
- }
- if (!isWorksheetReadableV1(sheet)) {
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: t("common.access-denied"),
- });
- return false;
- }
-
- const connection = await extractWorksheetConnection(sheet);
- tabStore.addTab({
- id: openedSheetTab?.id,
- connection,
- worksheet: sheet.name,
- title: sheet.title,
- statement: getSheetStatement(sheet),
- status: "CLEAN",
- });
- return true;
-};
-
-const prepareSheet = async () => {
- const projectId = route.params.project;
- const sheetId = route.params.sheet;
- if (typeof projectId !== "string" || !projectId) {
- return false;
- }
- if (typeof sheetId !== "string" || !sheetId) {
- return false;
- }
-
- await maybeSwitchProject(`projects/${projectId}`);
- return await switchWorksheet(`projects/${projectId}/worksheets/${sheetId}`);
-};
-
-const prepareConnectionParams = async () => {
- if (
- ![SQL_EDITOR_INSTANCE_MODULE, SQL_EDITOR_DATABASE_MODULE].includes(
- route.name as string
- )
- ) {
- return false;
- }
-
- const databaseName = `instances/${route.params.instance}/databases/${route.params.database}`;
- if (!isValidDatabaseName(databaseName)) {
- return false;
- }
-
- const database =
- await useDatabaseV1Store().getOrFetchDatabaseByName(databaseName);
- await maybeSwitchProject(database.project);
- // connected to db
- const { instance } = extractDatabaseResourceName(database.name);
- const connection = {
- instance,
- database: database.name,
- };
- tabStore.addTab({
- connection,
- mode: DEFAULT_SQL_EDITOR_TAB_MODE,
- title: suggestedTabTitleForSQLEditorConnection(connection),
- });
- return true;
-};
-
-const initializeConnectionFromQuery = async () => {
- // Priority:
- // 1. idFromSlug in sheetSlug
- // 2. instanceId and databaseId in connectionSlug
- // 3. database in global filter
- // 4. disconnected
- if (await prepareSheet()) {
- return;
- }
- if (await prepareConnectionParams()) {
- return;
- }
-
- // Keep disconnected otherwise
- // We don't need to `selectOrAddTempTab` here since we already have the
- // default tab.
-};
-
-// Keep the URL synced with connection
-// 1. /sql-editor/projects/{project}/sheets/{sheet} - saved sheets
-// 2. /sql-editor/projects/{project}/instances/{instance}/databases/{database} - unsaved tabs
-// 3. /sql-editor/projects/{project} - disconnected tabs
-const syncURLWithConnection = () => {
- const connection = computed(
- () => tabStore.currentTab?.connection ?? emptySQLEditorConnection()
- );
- watch(
- [
- () => editorStore.project,
- () => tabStore.currentTab?.worksheet,
- () => connection.value?.instance,
- () => connection.value?.database,
- () => connection.value?.schema,
- () => connection.value?.table,
- ],
- async ([
- projectName,
- sheetName,
- instanceName,
- databaseName,
- schema,
- table,
- ]) => {
- const query = omit(
- route.query,
- "filter",
- "project",
- "schema",
- "database",
- "panel"
- );
-
- if (sheetName) {
- const sheet = worksheetStore.getWorksheetByName(sheetName);
- if (sheet) {
- router.replace({
- name: SQL_EDITOR_WORKSHEET_MODULE,
- params: {
- project: extractProjectResourceName(sheet.project),
- sheet: extractWorksheetID(sheet.name),
- },
- query,
- });
- return;
- } else {
- const tab = tabStore.currentTab;
- if (tab) {
- tab.worksheet = "";
- tab.status = "DIRTY";
- }
- }
- }
- if (isValidDatabaseName(databaseName)) {
- const database =
- await databaseStore.getOrFetchDatabaseByName(databaseName);
- if (schema) {
- query.schema = schema;
- }
- if (table) {
- query.table = table;
- query.schema = schema ?? "";
- }
- const dbResource = extractDatabaseResourceName(database.name);
- router.replace({
- name: SQL_EDITOR_DATABASE_MODULE,
- params: {
- project: extractProjectResourceName(database.project),
- instance: extractInstanceResourceName(dbResource.instance),
- database: dbResource.databaseName,
- },
- query,
- });
- return;
- }
- if (isValidInstanceName(instanceName)) {
- if (table) {
- query.table = table;
- query.schema = schema ?? "";
- }
- router.replace({
- name: SQL_EDITOR_INSTANCE_MODULE,
- params: {
- project: extractProjectResourceName(editorStore.project),
- instance: extractInstanceResourceName(instanceName),
- },
- query,
- });
- return;
- }
- if (isValidProjectName(projectName)) {
- router.replace({
- name: SQL_EDITOR_PROJECT_MODULE,
- params: {
- project: extractProjectResourceName(projectName),
- },
- query,
- });
- return;
- }
- router.replace({
- name: SQL_EDITOR_HOME_MODULE,
- });
- },
- { immediate: true }
- );
-};
-
-const restoreLastVisitedSidebarTab = () => {
- const storedLastVisitedSidebarTab = useLocalStorage<AsidePanelTab>(
- STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,
- "WORKSHEET"
- );
-
- // Check for ?panel= query param to allow deep-linking to a specific tab.
- const panelQuery = route.query.panel;
- if (typeof panelQuery === "string" && panelQuery) {
- const tab = panelQuery.toUpperCase() as AsidePanelTab;
- if (ASIDE_PANEL_TABS.includes(tab)) {
- asidePanelTab.value = tab;
- } else {
- asidePanelTab.value = storedLastVisitedSidebarTab.value;
- }
- } else {
- asidePanelTab.value = storedLastVisitedSidebarTab.value;
- }
-
- watch(
- asidePanelTab,
- debounce((tab: AsidePanelTab) => {
- storedLastVisitedSidebarTab.value = tab;
- }, 100)
- );
-};
-
-onMounted(async () => {
- editorStore.projectContextReady = false;
- const project = await initializeProject();
-
- await migrateLegacyCache();
- await tabStore.initProject(project);
- await initializeConnectionFromQuery();
- syncURLWithConnection();
-});
-
-useEmitteryEventListener(
- editorEvents,
- "project-context-ready",
- ({ project }) => {
- if (!project) {
- return;
- }
- nextTick(() => {
- restoreLastVisitedSidebarTab();
- });
- }
-);
-</script>
diff --git a/frontend/src/components/Quickstart.vue b/frontend/src/components/Quickstart.vue
deleted file mode 100644
index 000d45cdea..0000000000
--- a/frontend/src/components/Quickstart.vue
+++ /dev/null
@@ -1,338 +0,0 @@
-<template>
- <div
- v-if="showQuickstart"
- class="py-2 px-4 w-full shrink-0 border-t border-block-border hidden lg:block bg-yellow-50"
- >
- <p
- class="text-sm font-medium text-gray-900 flex items-center justify-between"
- >
- <span
- >🎈 {{ $t("quick-start.self") }} - {{ $t("quick-start.guide") }}</span
- >
-
- <button class="btn-icon" @click.prevent="() => hideQuickstart()">
- <XIcon class="w-4 h-4" />
- </button>
- </p>
- <div class="mt-2" aria-hidden="true">
- <div class="overflow-hidden rounded-full bg-gray-200">
- <div
- class="h-2 rounded-full bg-indigo-600"
- :style="{ width: percent }"
- />
- </div>
- <div
- class="mt-2 hidden grid-cols-4 text-sm font-medium text-gray-600 sm:grid"
- :style="{
- gridTemplateColumns: `repeat(${introList.length}, minmax(0, 1fr))`,
- }"
- >
- <component
- :is="intro.link ? 'router-link' : 'div'"
- v-for="(intro, index) in introList"
- :key="index"
- :to="intro.link"
- active-class=""
- exact-active-class=""
- class="group cursor-pointer flex items-center gap-x-1 text-sm font-medium"
- :class="[
- index === 0 && 'justify-start',
- index > 0 && index < introList.length - 1 && 'justify-center',
- index === introList.length - 1 && 'justify-end',
- isTaskActive(index)
- ? 'text-indigo-600'
- : 'text-control-light group-hover:text-control-light-hover',
- unref(intro.done) && 'line-through',
- ]"
- @click="intro.click"
- >
- <span
- class="relative h-5 w-5 inline-flex items-center justify-center"
- >
- <template v-if="intro.done.value">
- <CheckCircleIcon
- class="w-4 h-auto text-success group-hover:text-success-hover"
- />
- </template>
- <template v-else-if="isTaskActive(index)">
- <span class="relative flex h-3 w-3">
- <span
- class="absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"
- style="animation: ping 2s cubic-bezier(0, 0, 0.2, 1) infinite"
- ></span>
- <span
- class="relative inline-flex rounded-full h-3 w-3 bg-indigo-500"
- ></span>
- </span>
- </template>
- <template v-else>
- <div
- class="h-2 w-2 bg-gray-300 rounded-full group-hover:bg-gray-400"
- ></div>
- </template>
- </span>
- <span class="inline-flex">
- {{ unref(intro.name) }}
- </span>
- </component>
- </div>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { computedAsync } from "@vueuse/core";
-import { CheckCircleIcon, XIcon } from "lucide-vue-next";
-import type { Ref } from "vue";
-import { computed, unref } from "vue";
-import { useI18n } from "vue-i18n";
-import { type RouteLocationRaw, useRouter } from "vue-router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
-import {
- DATABASE_ROUTE_DASHBOARD,
- ENVIRONMENT_V1_ROUTE_DASHBOARD,
- INSTANCE_ROUTE_DASHBOARD,
- PROJECT_V1_ROUTE_DASHBOARD,
- WORKSPACE_ROUTE_USERS,
-} from "@/router/dashboard/workspaceRoutes";
-import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
-import {
- pushNotification,
- useActuatorV1Store,
- useIssueV1Store,
- useProjectIamPolicyStore,
- useProjectV1Store,
- useUIStateStore,
- useWorkSheetStore,
-} from "@/store";
-import { projectNamePrefix } from "@/store/modules/v1/common";
-import type { Permission } from "@/types";
-import { isValidProjectName, UNKNOWN_PROJECT_NAME } from "@/types";
-import {
- extractProjectResourceName,
- hasProjectPermissionV2,
- hasWorkspacePermissionV2,
-} from "@/utils";
-
-// The name of the sample project.
-const SAMPLE_PROJECT_NAME = "project-sample";
-const SAMPLE_ISSUE_ID = "101";
-const SAMPLE_SHEET_ID = "101";
-
-type IntroItem = {
- name: string | Ref<string>;
- link: RouteLocationRaw;
- done: Ref<boolean>;
- click?: () => void;
- hide?: boolean;
- requiredPermissions?: Permission[];
-};
-
-const { t } = useI18n();
-const projectStore = useProjectV1Store();
-const uiStateStore = useUIStateStore();
-const actuatorStore = useActuatorV1Store();
-const issueStore = useIssueV1Store();
-const worksheetStore = useWorkSheetStore();
-const projectIamPolicyStore = useProjectIamPolicyStore();
-const router = useRouter();
-
-const sampleProject = computedAsync(async () => {
- if (!actuatorStore.quickStartEnabled) {
- return;
- }
- const project = await projectStore.getOrFetchProjectByName(
- `${projectNamePrefix}${SAMPLE_PROJECT_NAME}`,
- true /* silent */
- );
- if (!isValidProjectName(project.name)) {
- return;
- }
- await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);
- return project;
-});
-
-const sampleIssue = computedAsync(async () => {
- if (!sampleProject.value) {
- return;
- }
- const issue = await issueStore.fetchIssueByName(
- `${sampleProject.value.name}/issues/${SAMPLE_ISSUE_ID}`,
- true /* silent */
- );
- return issue;
-});
-
-const sampleWorksheet = computedAsync(async () => {
- if (!sampleProject.value) {
- return;
- }
- const sheet = await worksheetStore.getOrFetchWorksheetByName(
- `${sampleProject.value.name}/sheets/${SAMPLE_SHEET_ID}`,
- true /* silent */
- );
- return sheet;
-});
-
-const introList = computed(() => {
- const introList: IntroItem[] = [
- {
- name: computed(() => t("quick-start.view-an-issue")),
- link: {
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: {
- projectId: extractProjectResourceName(
- sampleProject.value?.name ?? UNKNOWN_PROJECT_NAME
- ),
- issueId: SAMPLE_ISSUE_ID,
- },
- },
- done: computed(() => uiStateStore.getIntroStateByKey("issue.visit")),
- hide: !sampleIssue.value,
- requiredPermissions: ["bb.issues.get", "bb.projects.get"],
- },
- {
- name: computed(() => t("quick-start.query-data")),
- link: {
- name: SQL_EDITOR_WORKSHEET_MODULE,
- params: {
- project: SAMPLE_PROJECT_NAME,
- sheet: SAMPLE_SHEET_ID,
- },
- },
- done: computed(() => uiStateStore.getIntroStateByKey("data.query")),
- hide: !sampleWorksheet.value,
- requiredPermissions: [
- "bb.sql.select",
- "bb.projects.get",
- "bb.worksheets.get",
- ],
- },
- {
- name: computed(() => t("quick-start.visit-project")),
- link: {
- name: PROJECT_V1_ROUTE_DASHBOARD,
- },
- done: computed(() => uiStateStore.getIntroStateByKey("project.visit")),
- requiredPermissions: ["bb.projects.list"],
- },
- {
- name: computed(() => t("quick-start.visit-environment")),
- link: {
- name: ENVIRONMENT_V1_ROUTE_DASHBOARD,
- },
- done: computed(() =>
- uiStateStore.getIntroStateByKey("environment.visit")
- ),
- requiredPermissions: ["bb.settings.getEnvironment"],
- },
- {
- name: computed(() => t("quick-start.visit-instance")),
- link: {
- name: INSTANCE_ROUTE_DASHBOARD,
- },
- done: computed(() => uiStateStore.getIntroStateByKey("instance.visit")),
- requiredPermissions: ["bb.instances.list"],
- },
- {
- name: computed(() => t("quick-start.visit-database")),
- link: {
- name: DATABASE_ROUTE_DASHBOARD,
- },
- done: computed(() => uiStateStore.getIntroStateByKey("database.visit")),
- requiredPermissions: ["bb.databases.list"],
- },
- {
- name: computed(() => t("quick-start.visit-member")),
- link: {
- name: WORKSPACE_ROUTE_USERS,
- },
- done: computed(() => uiStateStore.getIntroStateByKey("member.visit")),
- requiredPermissions: ["bb.workspaces.getIamPolicy", "bb.users.list"],
- },
- ];
-
- return introList.filter((item) => {
- if (item.hide) {
- return false;
- }
- const route = router.resolve(item.link);
- const permissions = item.requiredPermissions ?? [];
- if (!!route.params["project"] || !!route.params["projectId"]) {
- if (!sampleProject.value) {
- return false;
- }
- return permissions.every((permission) =>
- hasProjectPermissionV2(sampleProject.value!, permission)
- );
- }
- return permissions.every(hasWorkspacePermissionV2);
- });
-});
-
-const showQuickstart = computed(() => {
- if (!actuatorStore.quickStartEnabled) {
- return false;
- }
- return !uiStateStore.getIntroStateByKey("hidden");
-});
-
-const currentStep = computed(() => {
- let i = 0;
- const list = introList.value;
- while (i < list.length && list[i].done.value) {
- i++;
- }
- return i;
-});
-
-const isTaskActive = (index: number): boolean => {
- for (let i = index - 1; i >= 0; i--) {
- if (!introList.value[i].done.value) {
- return false;
- }
- }
- return !introList.value[index].done.value;
-};
-
-const progress = computed(() => {
- return {
- current: currentStep.value,
- total: introList.value.length,
- };
-});
-
-const percent = computed(() => {
- const { current, total } = progress.value;
- if (current === 0) {
- return "3rem";
- }
- if (current === total - 1) {
- return "calc(100% - 3rem)";
- }
-
- const offset = 0.5;
- const unit = 100 / total;
- const percent = Math.min((current + offset) * unit, 100);
- return `${percent}%`;
-});
-
-const hideQuickstart = (silent = false) => {
- uiStateStore
- .saveIntroStateByKey({
- key: "hidden",
- newState: true,
- })
- .then(() => {
- if (!silent) {
- pushNotification({
- module: "bytebase",
- style: "INFO",
- title: t("quick-start.notice.title"),
- description: t("quick-start.notice.desc"),
- manualHide: true,
- });
- }
- });
-};
-</script>
diff --git a/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue b/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue
deleted file mode 100644
index 04bad7bd76..0000000000
--- a/frontend/src/components/SchemaDiagram/SchemaDiagramIcon.vue
+++ /dev/null
@@ -1,17 +0,0 @@
-<template>
- <svg
- width="256"
- height="256"
- viewBox="0 0 256 256"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- class="w-4 h-4"
- >
- <path d="M22 33H94V105H22V33Z" fill="currentColor" />
- <path d="M43 152H127V236H43V152Z" fill="currentColor" />
- <path d="M145 21H241V117H145V21Z" fill="currentColor" />
- <rect x="94" y="57" width="51" height="24" fill="currentColor" />
- <rect x="127" y="182" width="78" height="24" fill="currentColor" />
- <rect x="181" y="117" width="24" height="65" fill="currentColor" />
- </svg>
-</template>
diff --git a/frontend/src/components/SchemaDiagram/index.ts b/frontend/src/components/SchemaDiagram/index.ts
deleted file mode 100644
index 918a1ec541..0000000000
--- a/frontend/src/components/SchemaDiagram/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-// The heavy SchemaDiagram surface (Canvas, Navigator, ER, FK lines,
-// auto-layout, ...) was migrated to React on 2026-04-29. The remaining
-// Vue surfaces here only consume the small `SchemaDiagramIcon` SVG;
-// every other consumer mounts the React diagram via `ReactPageMount`
-// (page="SchemaDiagramPage").
-import SchemaDiagramIcon from "./SchemaDiagramIcon.vue";
-
-export { SchemaDiagramIcon };
diff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vue
index 15951daec5..b60c46c1a6 100644
--- a/frontend/src/layouts/BodyLayout.vue
+++ b/frontend/src/layouts/BodyLayout.vue
@@ -37,7 +37,7 @@
</teleport>
<teleport v-if="quickstartTarget" :to="quickstartTarget">
- <Quickstart />
+ <ReactPageMount page="Quickstart" container-class="w-full" />
</teleport>
<AgentWindowMount />
@@ -53,7 +53,6 @@ import { useWindowSize } from "@vueuse/core";
import { computed, onMounted, onUnmounted, ref, shallowRef, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import AgentWindowMount from "@/components/AgentWindowMount.vue";
-import Quickstart from "@/components/Quickstart.vue";
import ReleaseRemindModal from "@/components/ReleaseRemindModal.vue";
import { t } from "@/plugins/i18n";
import type { DashboardShellTargets } from "@/react/dashboard-shell";
diff --git a/frontend/src/layouts/SQLEditorLayout.vue b/frontend/src/layouts/SQLEditorLayout.vue
deleted file mode 100644
index 5f8c2d9c47..0000000000
--- a/frontend/src/layouts/SQLEditorLayout.vue
+++ /dev/null
@@ -1,51 +0,0 @@
-<template>
- <div class="relative h-screen overflow-hidden flex flex-col">
- <ul
- id="sql-editor-debug"
- class="hidden text-xs font-mono max-h-[33vh] max-w-[40vw] overflow-auto fixed bottom-0 right-0 p-2 bg-white/50 border border-gray-400 z-999999"
- ></ul>
-
- <ReactPageMount page="BannersWrapper" container-class="w-full" />
- <template v-if="ready">
- <ProvideSQLEditorContext />
- </template>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { onMounted, ref } from "vue";
-import { useRouter } from "vue-router";
-import ProvideSQLEditorContext from "@/components/ProvideSQLEditorContext.vue";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { useEnvironmentV1Store, useSettingV1Store } from "@/store";
-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
-import { provideSQLEditorContext } from "@/views/sql-editor/context";
-import { provideSheetContext } from "@/views/sql-editor/Sheet";
-
-const router = useRouter();
-
-// provide context for SQL Editor
-provideSQLEditorContext();
-// provide context for sheets
-provideSheetContext();
-// TabList no longer uses Vue provide/inject — React consumers import
-// `tabListEvents` from `@/views/sql-editor/TabList/events` directly.
-
-const ready = ref(false);
-
-// We may tweak the resource loading here, and pre-load some frontend component
-// resources, and make a loading screen here in the future.
-const prepare = async () => {
- await router.isReady();
-
- await Promise.all([
- useSettingV1Store().getOrFetchSettingByName(
- Setting_SettingName.WORKSPACE_PROFILE
- ),
- useEnvironmentV1Store().fetchEnvironments(),
- ]);
- ready.value = true;
-};
-
-onMounted(prepare);
-</script>
diff --git a/frontend/src/layouts/layout-bridge.test.ts b/frontend/src/layouts/layout-bridge.test.ts
index 64aebd93f5..e45f6473ad 100644
--- a/frontend/src/layouts/layout-bridge.test.ts
+++ b/frontend/src/layouts/layout-bridge.test.ts
@@ -45,6 +45,9 @@ vi.mock("@/react/ReactPageMount.vue", async () => {
if (props.page === "DashboardFrameShell") {
return;
}
+ if (props.page === "Quickstart") {
+ return;
+ }
if (props.page === "RoutePermissionGuardShell") {
props.pageProps?.onReady?.(permissionTarget.value);
return;
@@ -65,6 +68,14 @@ vi.mock("@/react/ReactPageMount.vue", async () => {
});
});
+ if (props.page === "Quickstart") {
+ // Match the marker the legacy `<Quickstart />` Vue mock emitted
+ // — this lets the existing teleport assertions keep working
+ // unchanged after the React port replaced the Vue component
+ // with `<ReactPageMount page="Quickstart">` in BodyLayout.vue
+ // and ReactRouteShellBridge.vue.
+ return () => h("div", { "data-testid": "quickstart" }, "quickstart");
+ }
return () =>
props.page === "RoutePermissionGuardShell"
? h("div", {
@@ -104,18 +115,6 @@ vi.mock("@/react/ReactPageMount.vue", async () => {
};
});
-vi.mock("@/components/Quickstart.vue", async () => {
- const { defineComponent, h } = await import("vue");
- return {
- default: defineComponent({
- name: "MockQuickstart",
- setup() {
- return () => h("div", { "data-testid": "quickstart" }, "quickstart");
- },
- }),
- };
-});
-
vi.mock("@/components/AgentWindowMount.vue", async () => {
const { defineComponent, h } = await import("vue");
return {
diff --git a/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue b/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue
new file mode 100644
index 0000000000..abe046942b
--- /dev/null
+++ b/frontend/src/plugins/ai/components/AIChatToSQLBridgeHost.vue
@@ -0,0 +1,23 @@
+<template>
+ <ProvideAIContext>
+ <Suspense>
+ <AIChatToSQL />
+ </Suspense>
+ </ProvideAIContext>
+</template>
+
+<script lang="ts" setup>
+/**
+ * Self-contained AI chat panel host for use inside a `VueMount` bridge.
+ * The bridge spawns an isolated Vue 3 app whose component tree can't see
+ * the outer Vue's provide chain — so we re-establish `ProvideAIContext`
+ * at the bridge boundary. Pinia + the module-level `aiContextEvents`
+ * are singletons, so duplicating the provide doesn't fork state.
+ *
+ * Mounted from the post-Stage-21 React shells (`StandardPanel`,
+ * `Panels`) via `<VueMount component={AIChatToSQLBridgeHost} />`.
+ * Removed alongside Stage 22 if/when the AI plugin is ported to React.
+ */
+import AIChatToSQL from "./AIChatToSQL.vue";
+import ProvideAIContext from "./ProvideAIContext.vue";
+</script>
diff --git a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
index 2820b3e09c..73a5fb7ff1 100644
--- a/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
+++ b/frontend/src/plugins/ai/components/ChatView/Markdown/CodeBlock.vue
@@ -82,7 +82,7 @@ import { MonacoEditor } from "@/components/MonacoEditor";
import { CopyButton } from "@/components/v2";
import { useAIContext } from "@/plugins/ai/logic";
import { findAncestor } from "@/utils";
-import { useSQLEditorContext } from "@/views/sql-editor/context";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
import InsertAtCaretIcon from "./InsertAtCaretIcon.vue";
export type CodeBlockProps = {
@@ -96,7 +96,10 @@ const props = defineProps<
>();
const { events, showHistoryDialog } = useAIContext();
-const { events: editorEvents } = useSQLEditorContext();
+// `sqlEditorEvents` is a module-level singleton — the AI plugin runs
+// inside its own Vue app (via the React→Vue bridge), so a Vue inject
+// of `useSQLEditorContext` wouldn't reach the host's provide chain.
+const editorEvents = sqlEditorEvents;
const containerRef = ref<HTMLElement>();
const messageWrapperRef = computed(() =>
findAncestor(containerRef.value, ".message")
diff --git a/frontend/src/plugins/ai/index.ts b/frontend/src/plugins/ai/index.ts
index 6311ba7852..0b633790d3 100644
--- a/frontend/src/plugins/ai/index.ts
+++ b/frontend/src/plugins/ai/index.ts
@@ -1,6 +1,7 @@
import AIChatToSQL from "./components/AIChatToSQL.vue";
+import AIChatToSQLBridgeHost from "./components/AIChatToSQLBridgeHost.vue";
import ProvideAIContext from "./components/ProvideAIContext.vue";
export * from "./types";
export * from "./components/editor-actions";
-export { AIChatToSQL, ProvideAIContext };
+export { AIChatToSQL, AIChatToSQLBridgeHost, ProvideAIContext };
diff --git a/frontend/src/react/ReactRouteShellBridge.vue b/frontend/src/react/ReactRouteShellBridge.vue
index 21e33dfdc5..bef68d4a71 100644
--- a/frontend/src/react/ReactRouteShellBridge.vue
+++ b/frontend/src/react/ReactRouteShellBridge.vue
@@ -18,14 +18,13 @@
</teleport>
<teleport v-if="targets.quickstart" :to="targets.quickstart">
- <Quickstart />
+ <ReactPageMount page="Quickstart" container-class="w-full" />
</teleport>
</template>
<script lang="ts" setup>
import { computed, shallowRef } from "vue";
import { useRoute } from "vue-router";
-import Quickstart from "@/components/Quickstart.vue";
import { provideBodyLayoutContext } from "@/layouts/common";
import type { ReactRouteShellTargets } from "@/react/dashboard-shell";
import ReactPageMount from "@/react/ReactPageMount.vue";
diff --git a/frontend/src/react/components/ComponentPermissionGuard.tsx b/frontend/src/react/components/ComponentPermissionGuard.tsx
index 501795b1b4..3bdb3d26da 100644
--- a/frontend/src/react/components/ComponentPermissionGuard.tsx
+++ b/frontend/src/react/components/ComponentPermissionGuard.tsx
@@ -64,7 +64,6 @@ export function usePermissionDataReady(project?: Project) {
useEffect(() => {
let stale = false;
- setReadyKey("");
const requests: Promise<unknown>[] = [loadWorkspacePermissionState()];
if (project?.name) {
diff --git a/frontend/src/react/components/PermissionGuard.test.tsx b/frontend/src/react/components/PermissionGuard.test.tsx
index 62cbfb1c40..fe7c1ea0b6 100644
--- a/frontend/src/react/components/PermissionGuard.test.tsx
+++ b/frontend/src/react/components/PermissionGuard.test.tsx
@@ -88,7 +88,7 @@ afterEach(() => {
});
describe("PermissionGuard", () => {
- test("loads workspace permission state before enabling children", async () => {
+ test("renders children enabled when the user has the workspace permission", async () => {
mocks.workspacePermissions.add("bb.instances.create");
await act(async () => {
@@ -102,11 +102,10 @@ describe("PermissionGuard", () => {
await Promise.resolve();
});
- expect(mocks.loadWorkspacePermissionState).toHaveBeenCalledTimes(1);
expect(container.querySelector("button")?.disabled).toBe(false);
});
- test("loads project IAM policy for project permission checks", async () => {
+ test("renders children enabled when the user has the project permission", async () => {
const project = { name: "projects/demo" } as Project;
mocks.projectPermissions.add("bb.sql.select");
@@ -121,8 +120,21 @@ describe("PermissionGuard", () => {
await Promise.resolve();
});
- expect(mocks.loadWorkspacePermissionState).toHaveBeenCalledTimes(1);
- expect(mocks.loadProjectIamPolicy).toHaveBeenCalledWith(project.name);
expect(container.querySelector("button")?.disabled).toBe(false);
});
+
+ test("disables children when required permission is missing", async () => {
+ await act(async () => {
+ root.render(
+ <PermissionGuard permissions={["bb.instances.create"]}>
+ {({ disabled }) => <button disabled={disabled}>create</button>}
+ </PermissionGuard>
+ );
+ });
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ expect(container.querySelector("button")?.disabled).toBe(true);
+ });
});
diff --git a/frontend/src/react/components/PermissionGuard.tsx b/frontend/src/react/components/PermissionGuard.tsx
index 7856f748c4..7dc2cb36f2 100644
--- a/frontend/src/react/components/PermissionGuard.tsx
+++ b/frontend/src/react/components/PermissionGuard.tsx
@@ -1,9 +1,6 @@
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
-import {
- useComponentPermissionState,
- usePermissionDataReady,
-} from "@/react/components/ComponentPermissionGuard";
+import { useComponentPermissionState } from "@/react/components/ComponentPermissionGuard";
import type { Permission } from "@/types";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { BlockTooltip, Tooltip } from "./ui/tooltip";
@@ -17,13 +14,11 @@ export function usePermissionCheck(
project?: Project
): [boolean, string | undefined] {
const { t } = useTranslation();
- const ready = usePermissionDataReady(project);
const { missedPermissions } = useComponentPermissionState({
permissions,
project,
});
- const missed = ready ? missedPermissions : permissions;
- if (missed.length === 0) return [true, undefined];
+ if (missedPermissions.length === 0) return [true, undefined];
return [
false,
project
@@ -31,7 +26,7 @@ export function usePermissionCheck(
resource: project.name,
})
: t("common.missing-required-permission", {
- permissions: missed.join(", "),
+ permissions: missedPermissions.join(", "),
}),
];
}
@@ -79,30 +74,27 @@ export function PermissionGuard({
display = "inline",
}: PermissionGuardProps) {
const { t } = useTranslation();
- const ready = usePermissionDataReady(project);
const { missedPermissions } = useComponentPermissionState({
permissions,
project,
});
- const missed = ready ? missedPermissions : permissions;
- const disabled = missed.length > 0;
+ const disabled = missedPermissions.length > 0;
- const tooltip =
- ready && disabled ? (
- <div className="flex flex-col gap-1">
- {project
- ? t("common.missing-required-permission-for-resource", {
- resource: project.name,
- })
- : t("common.missing-required-permission", { permissions: "" })}
- <ul className="list-disc pl-4">
- {missed.map((p) => (
- <li key={p}>{p}</li>
- ))}
- </ul>
- </div>
- ) : undefined;
+ const tooltip = disabled ? (
+ <div className="flex flex-col gap-1">
+ {project
+ ? t("common.missing-required-permission-for-resource", {
+ resource: project.name,
+ })
+ : t("common.missing-required-permission", { permissions: "" })}
+ <ul className="list-disc pl-4">
+ {missedPermissions.map((p) => (
+ <li key={p}>{p}</li>
+ ))}
+ </ul>
+ </div>
+ ) : undefined;
const content =
typeof children === "function" ? children({ disabled }) : children;
diff --git a/frontend/src/react/components/Quickstart.tsx b/frontend/src/react/components/Quickstart.tsx
new file mode 100644
index 0000000000..d7028c890e
--- /dev/null
+++ b/frontend/src/react/components/Quickstart.tsx
@@ -0,0 +1,371 @@
+import { CheckCircle, X } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { RouteLocationRaw } from "vue-router";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { useNavigate } from "@/react/router";
+import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
+import {
+ DATABASE_ROUTE_DASHBOARD,
+ ENVIRONMENT_V1_ROUTE_DASHBOARD,
+ INSTANCE_ROUTE_DASHBOARD,
+ PROJECT_V1_ROUTE_DASHBOARD,
+ WORKSPACE_ROUTE_USERS,
+} from "@/router/dashboard/workspaceRoutes";
+import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";
+import {
+ pushNotification,
+ useActuatorV1Store,
+ useIssueV1Store,
+ useProjectIamPolicyStore,
+ useProjectV1Store,
+ useUIStateStore,
+ useWorkSheetStore,
+} from "@/store";
+import { projectNamePrefix } from "@/store/modules/v1/common";
+import type { Permission } from "@/types";
+import { isValidProjectName, UNKNOWN_PROJECT_NAME } from "@/types";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import {
+ extractProjectResourceName,
+ hasProjectPermissionV2,
+ hasWorkspacePermissionV2,
+} from "@/utils";
+
+const SAMPLE_PROJECT_NAME = "project-sample";
+const SAMPLE_ISSUE_ID = "101";
+const SAMPLE_SHEET_ID = "101";
+
+interface IntroItem {
+ name: string;
+ link: RouteLocationRaw;
+ done: boolean;
+ hide?: boolean;
+ requiredPermissions?: Permission[];
+ needsProject?: boolean;
+}
+
+/**
+ * React port of `frontend/src/components/Quickstart.vue`.
+ *
+ * Floating onboarding tracker pinned to the bottom of the workspace
+ * shell. Renders a progress bar over a list of intro tasks (view an
+ * issue, query data, visit project, visit environment / instance /
+ * database, visit member). Each task is permission-gated so users only
+ * see tasks they can perform; tasks that depend on the sample project
+ * are filtered out when no sample project exists for this workspace.
+ *
+ * State sources (all Pinia, read via `useVueState`):
+ * - `actuatorStore.quickStartEnabled` — disabled in self-hosted /
+ * enterprise builds via the actuator config.
+ * - `uiStateStore.getIntroStateByKey(...)` — per-task done flags and
+ * the global `hidden` flag (toggled when the user dismisses).
+ *
+ * Async fetches (project / sample issue / sample worksheet) run on
+ * mount and fall back to undefined when the sample data is missing
+ * (e.g. an upgraded workspace that never bootstrapped the sample).
+ */
+export function Quickstart() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const projectStore = useProjectV1Store();
+ const uiStateStore = useUIStateStore();
+ const actuatorStore = useActuatorV1Store();
+ const issueStore = useIssueV1Store();
+ const worksheetStore = useWorkSheetStore();
+ const projectIamPolicyStore = useProjectIamPolicyStore();
+
+ const quickStartEnabled = useVueState(() => actuatorStore.quickStartEnabled);
+ const hidden = useVueState(() => uiStateStore.getIntroStateByKey("hidden"));
+
+ // Subscribe to each task's done flag so the line-through + progress
+ // bar update live.
+ const issueVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("issue.visit")
+ );
+ const dataQueried = useVueState(() =>
+ uiStateStore.getIntroStateByKey("data.query")
+ );
+ const projectVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("project.visit")
+ );
+ const environmentVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("environment.visit")
+ );
+ const instanceVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("instance.visit")
+ );
+ const databaseVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("database.visit")
+ );
+ const memberVisited = useVueState(() =>
+ uiStateStore.getIntroStateByKey("member.visit")
+ );
+
+ // ---- async sample fetches --------------------------------------------
+
+ const [sampleProject, setSampleProject] = useState<Project | undefined>();
+ const [sampleIssueExists, setSampleIssueExists] = useState(false);
+ const [sampleSheetExists, setSampleSheetExists] = useState(false);
+
+ useEffect(() => {
+ if (!quickStartEnabled) {
+ setSampleProject(undefined);
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ const project = await projectStore.getOrFetchProjectByName(
+ `${projectNamePrefix}${SAMPLE_PROJECT_NAME}`,
+ true /* silent */
+ );
+ if (cancelled) return;
+ if (!isValidProjectName(project.name)) {
+ setSampleProject(undefined);
+ return;
+ }
+ await projectIamPolicyStore.getOrFetchProjectIamPolicy(project.name);
+ if (cancelled) return;
+ setSampleProject(project);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [quickStartEnabled, projectStore, projectIamPolicyStore]);
+
+ useEffect(() => {
+ if (!sampleProject) {
+ setSampleIssueExists(false);
+ setSampleSheetExists(false);
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ const issue = await issueStore.fetchIssueByName(
+ `${sampleProject.name}/issues/${SAMPLE_ISSUE_ID}`,
+ true /* silent */
+ );
+ if (!cancelled) setSampleIssueExists(!!issue);
+ })();
+ void (async () => {
+ const sheet = await worksheetStore.getOrFetchWorksheetByName(
+ `${sampleProject.name}/sheets/${SAMPLE_SHEET_ID}`,
+ true /* silent */
+ );
+ if (!cancelled) setSampleSheetExists(!!sheet);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [sampleProject, issueStore, worksheetStore]);
+
+ // ---- intro list (memoized + permission-filtered) ----------------------
+
+ const introList = useMemo<IntroItem[]>(() => {
+ const sampleProjectId = sampleProject
+ ? extractProjectResourceName(sampleProject.name)
+ : extractProjectResourceName(UNKNOWN_PROJECT_NAME);
+ const all: IntroItem[] = [
+ {
+ name: t("quick-start.view-an-issue"),
+ link: {
+ name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
+ params: { projectId: sampleProjectId, issueId: SAMPLE_ISSUE_ID },
+ },
+ done: issueVisited,
+ hide: !sampleIssueExists,
+ requiredPermissions: ["bb.issues.get", "bb.projects.get"],
+ needsProject: true,
+ },
+ {
+ name: t("quick-start.query-data"),
+ link: {
+ name: SQL_EDITOR_WORKSHEET_MODULE,
+ params: {
+ project: SAMPLE_PROJECT_NAME,
+ sheet: SAMPLE_SHEET_ID,
+ },
+ },
+ done: dataQueried,
+ hide: !sampleSheetExists,
+ requiredPermissions: [
+ "bb.sql.select",
+ "bb.projects.get",
+ "bb.worksheets.get",
+ ],
+ needsProject: true,
+ },
+ {
+ name: t("quick-start.visit-project"),
+ link: { name: PROJECT_V1_ROUTE_DASHBOARD },
+ done: projectVisited,
+ requiredPermissions: ["bb.projects.list"],
+ },
+ {
+ name: t("quick-start.visit-environment"),
+ link: { name: ENVIRONMENT_V1_ROUTE_DASHBOARD },
+ done: environmentVisited,
+ requiredPermissions: ["bb.settings.getEnvironment"],
+ },
+ {
+ name: t("quick-start.visit-instance"),
+ link: { name: INSTANCE_ROUTE_DASHBOARD },
+ done: instanceVisited,
+ requiredPermissions: ["bb.instances.list"],
+ },
+ {
+ name: t("quick-start.visit-database"),
+ link: { name: DATABASE_ROUTE_DASHBOARD },
+ done: databaseVisited,
+ requiredPermissions: ["bb.databases.list"],
+ },
+ {
+ name: t("quick-start.visit-member"),
+ link: { name: WORKSPACE_ROUTE_USERS },
+ done: memberVisited,
+ requiredPermissions: ["bb.workspaces.getIamPolicy", "bb.users.list"],
+ },
+ ];
+ return all.filter((item) => {
+ if (item.hide) return false;
+ const perms = item.requiredPermissions ?? [];
+ if (item.needsProject) {
+ if (!sampleProject) return false;
+ return perms.every((p) => hasProjectPermissionV2(sampleProject, p));
+ }
+ return perms.every(hasWorkspacePermissionV2);
+ });
+ }, [
+ t,
+ sampleProject,
+ sampleIssueExists,
+ sampleSheetExists,
+ issueVisited,
+ dataQueried,
+ projectVisited,
+ environmentVisited,
+ instanceVisited,
+ databaseVisited,
+ memberVisited,
+ ]);
+
+ const showQuickstart = quickStartEnabled && !hidden;
+ const currentStep = useMemo(() => {
+ let i = 0;
+ while (i < introList.length && introList[i].done) i++;
+ return i;
+ }, [introList]);
+
+ const isTaskActive = (index: number) => {
+ for (let i = index - 1; i >= 0; i--) {
+ if (!introList[i].done) return false;
+ }
+ return !introList[index].done;
+ };
+
+ const percent = useMemo(() => {
+ const total = introList.length;
+ if (total === 0) return "0%";
+ if (currentStep === 0) return "3rem";
+ if (currentStep === total - 1) return "calc(100% - 3rem)";
+ const offset = 0.5;
+ const unit = 100 / total;
+ return `${Math.min((currentStep + offset) * unit, 100)}%`;
+ }, [currentStep, introList.length]);
+
+ const handleHide = (silent = false) => {
+ void uiStateStore
+ .saveIntroStateByKey({ key: "hidden", newState: true })
+ .then(() => {
+ if (!silent) {
+ pushNotification({
+ module: "bytebase",
+ style: "INFO",
+ title: t("quick-start.notice.title"),
+ description: t("quick-start.notice.desc"),
+ manualHide: true,
+ });
+ }
+ });
+ };
+
+ if (!showQuickstart || introList.length === 0) {
+ return null;
+ }
+
+ return (
+ <div className="py-2 px-4 w-full shrink-0 border-t border-block-border hidden lg:block bg-yellow-50">
+ <p className="text-sm font-medium text-gray-900 flex items-center justify-between">
+ <span>
+ 🎈 {t("quick-start.self")} - {t("quick-start.guide")}
+ </span>
+ <button
+ type="button"
+ className="rounded-xs p-1 hover:bg-control-bg cursor-pointer"
+ aria-label={t("common.close")}
+ onClick={() => handleHide()}
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </p>
+ <div className="mt-2" aria-hidden="true">
+ <div className="overflow-hidden rounded-full bg-gray-200">
+ <div
+ className="h-2 rounded-full bg-indigo-600"
+ style={{ width: percent }}
+ />
+ </div>
+ <div
+ className="mt-2 hidden text-sm font-medium text-gray-600 sm:grid"
+ style={{
+ gridTemplateColumns: `repeat(${introList.length}, minmax(0, 1fr))`,
+ }}
+ >
+ {introList.map((intro, index) => {
+ const active = isTaskActive(index);
+ return (
+ <button
+ key={`${intro.name}-${index}`}
+ type="button"
+ className={cn(
+ "group cursor-pointer flex items-center gap-x-1 text-sm font-medium",
+ index === 0 && "justify-start",
+ index > 0 && index < introList.length - 1 && "justify-center",
+ index === introList.length - 1 && "justify-end",
+ active
+ ? "text-indigo-600"
+ : "text-control-light group-hover:text-control-light-hover",
+ intro.done && "line-through"
+ )}
+ onClick={() => {
+ void navigate.push(intro.link);
+ }}
+ >
+ <span className="relative h-5 w-5 inline-flex items-center justify-center">
+ {intro.done ? (
+ <CheckCircle className="w-4 h-auto text-success group-hover:text-success-hover" />
+ ) : active ? (
+ <span className="relative flex h-3 w-3">
+ <span
+ className="absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"
+ style={{
+ animation:
+ "ping 2s cubic-bezier(0, 0, 0.2, 1) infinite",
+ }}
+ />
+ <span className="relative inline-flex rounded-full h-3 w-3 bg-indigo-500" />
+ </span>
+ ) : (
+ <span className="h-2 w-2 bg-gray-300 rounded-full group-hover:bg-gray-400" />
+ )}
+ </span>
+ <span className="inline-flex">{intro.name}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/VueMount.test.tsx b/frontend/src/react/components/VueMount.test.tsx
new file mode 100644
index 0000000000..2026ce61e6
--- /dev/null
+++ b/frontend/src/react/components/VueMount.test.tsx
@@ -0,0 +1,97 @@
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { describe, expect, test, vi } from "vitest";
+import { defineComponent, h, nextTick } from "vue";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+vi.mock("@/store", () => ({
+ pinia: { install: vi.fn() },
+}));
+vi.mock("@/plugins/i18n", () => ({
+ default: { install: vi.fn() },
+}));
+vi.mock("@/plugins/naive-ui", () => ({
+ default: { install: vi.fn() },
+}));
+
+import { VueMount } from "./VueMount";
+
+const renderIntoContainer = (element: React.ReactElement) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ return {
+ container,
+ render: () =>
+ act(() => {
+ root.render(element);
+ }),
+ rerender: (next: React.ReactElement) =>
+ act(() => {
+ root.render(next);
+ }),
+ unmount: () => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ },
+ };
+};
+
+const Greet = defineComponent({
+ props: { name: { type: String, default: "world" } },
+ setup(props) {
+ return () => h("span", { class: "greet" }, `hello ${props.name}`);
+ },
+});
+
+describe("VueMount", () => {
+ test("mounts a Vue component into the React container", () => {
+ const { container, render, unmount } = renderIntoContainer(
+ <VueMount component={Greet} props={{ name: "Stage 21" }} />
+ );
+ render();
+ const span = container.querySelector("span.greet");
+ expect(span?.textContent).toBe("hello Stage 21");
+ unmount();
+ });
+
+ test("propagates prop changes without remounting", async () => {
+ const { container, render, rerender, unmount } = renderIntoContainer(
+ <VueMount component={Greet} props={{ name: "first" }} />
+ );
+ render();
+ const before = container.querySelector("span.greet");
+ expect(before?.textContent).toBe("hello first");
+
+ rerender(<VueMount component={Greet} props={{ name: "second" }} />);
+ await nextTick();
+ const after = container.querySelector("span.greet");
+ expect(after?.textContent).toBe("hello second");
+ expect(after).toBe(before); // same DOM node — Vue updated in place.
+ unmount();
+ });
+
+ test("unmounts the Vue app when React unmounts", () => {
+ const teardown = vi.fn();
+ const Probe = defineComponent({
+ setup() {
+ return () => h("span", { class: "probe" }, "alive");
+ },
+ beforeUnmount: teardown,
+ });
+
+ const { container, render, unmount } = renderIntoContainer(
+ <VueMount component={Probe} />
+ );
+ render();
+ expect(container.querySelector("span.probe")?.textContent).toBe("alive");
+
+ unmount();
+ expect(teardown).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/react/components/VueMount.tsx b/frontend/src/react/components/VueMount.tsx
new file mode 100644
index 0000000000..5a9a0dce50
--- /dev/null
+++ b/frontend/src/react/components/VueMount.tsx
@@ -0,0 +1,87 @@
+import { useEffect, useRef } from "react";
+import type { Component } from "vue";
+import { createApp, h, reactive } from "vue";
+import i18n from "@/plugins/i18n";
+import NaiveUI from "@/plugins/naive-ui";
+import { cn } from "@/react/lib/utils";
+import { pinia } from "@/store";
+
+interface VueMountProps<P extends Record<string, unknown>> {
+ /**
+ * Vue component to mount. Component identity must be stable across renders;
+ * passing a fresh inline definition will tear down and re-create the inner
+ * Vue app every render. Module-level imports satisfy this naturally.
+ */
+ component: Component;
+ /**
+ * Props forwarded to the Vue component. Treated reactively — assigning new
+ * keys/values updates the running Vue app in place via Vue's reactivity,
+ * no remount. The object reference itself doesn't need to be stable; only
+ * the keys/values are diffed.
+ */
+ props?: P;
+ className?: string;
+}
+
+/**
+ * Reverse mount bridge: hosts a Vue 3 component subtree inside a React tree.
+ * Mirrors `ReactPageMount.vue`'s lifecycle in reverse — used by the SQL
+ * Editor host shells (post-Stage-21) to keep the still-Vue AI plugin
+ * (`AIChatToSQL`, `ChatPanel`, etc.) running without porting it yet.
+ *
+ * The inner Vue app installs the same singleton plugins as the outer Vue
+ * app (Pinia, i18n, NaiveUI) so Pinia stores, translations, and Naive UI
+ * services are shared — no "two sources of truth" surprises.
+ */
+export function VueMount<P extends Record<string, unknown>>({
+ component,
+ props,
+ className,
+}: VueMountProps<P>) {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const reactivePropsRef = useRef<Record<string, unknown> | null>(null);
+
+ useEffect(() => {
+ const el = containerRef.current;
+ if (!el) return;
+
+ const reactiveProps = reactive<Record<string, unknown>>({
+ ...(props ?? {}),
+ });
+ reactivePropsRef.current = reactiveProps;
+
+ const app = createApp({
+ render: () => h(component, reactiveProps),
+ });
+ app.use(pinia);
+ app.use(i18n);
+ app.use(NaiveUI);
+ app.mount(el);
+
+ return () => {
+ reactivePropsRef.current = null;
+ app.unmount();
+ };
+ // Re-create the Vue app only when component identity changes; prop
+ // updates flow through the reactive proxy in the next effect.
+ }, [component]);
+
+ // Sync prop changes into the live Vue app without remounting.
+ useEffect(() => {
+ const target = reactivePropsRef.current;
+ if (!target) return;
+ const next = props ?? {};
+ // Add/overwrite keys.
+ for (const [k, v] of Object.entries(next)) {
+ target[k] = v;
+ }
+ // Drop keys removed from the new props snapshot.
+ for (const k of Object.keys(target)) {
+ if (!(k in next)) {
+ delete target[k];
+ }
+ }
+ }, [props]);
+
+ return <div ref={containerRef} className={cn(className)} />;
+}
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
index d1b3b0685c..1c212555b8 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx
@@ -1131,7 +1131,7 @@ function LoadMoreButton({
// ---- utilities ---------------------------------------------------------
-const ROW_HEIGHT = 24;
+const ROW_HEIGHT = 28;
function toTreeDataNode(
node: SQLEditorTreeNode
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts
index cd7d5bb51a..4e0f854356 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts
@@ -2,6 +2,7 @@ import {
createContext,
useCallback,
useContext,
+ useMemo,
useRef,
useState,
} from "react";
@@ -25,7 +26,7 @@ export type HoverStateContextValue = {
};
const DELAY_BEFORE = 1000;
-const DELAY_AFTER = 350;
+const DELAY_AFTER = 100;
const HoverStateContext = createContext<HoverStateContextValue | null>(null);
@@ -62,7 +63,17 @@ export function useProvideHoverState(): HoverStateContextValue {
[cancel]
);
- return { state, position, setPosition, update };
+ // Memoize the context value so an unrelated parent re-render (e.g.
+ // a Pinia tick triggering a `useVueState` update somewhere up the
+ // tree) doesn't churn the `<HoverStateProvider value={…}>` reference.
+ // Without this, every consumer of `useHoverState()` (every tree row
+ // in `ConnectionPane`) re-renders, which can show up as the hover
+ // panel rapidly toggling visibility / re-positioning while the user
+ // holds the cursor over a row.
+ return useMemo(
+ () => ({ state, position, setPosition, update }),
+ [state, position, setPosition, update]
+ );
}
export const HoverStateProvider = HoverStateContext.Provider;
diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
index 8f6ada1eda..46a8a33dde 100644
--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx
@@ -54,19 +54,29 @@ export function DatabaseNode({
const canQuery = isDatabaseV1Queryable(database);
const checkbox = supportBatchMode ? (
- <Tooltip content={checkTooltip ?? ""}>
- <Checkbox
- checked={!!checked}
- className="mr-2"
- disabled={checkDisabled}
- onClick={(e) => e.stopPropagation()}
- onCheckedChange={(checked) => onCheckedChange?.(checked)}
- />
- </Tooltip>
+ // The row activates on `mouseup` (Safari workaround). Stop the
+ // mouse events here so clicking the checkbox doesn't first connect
+ // to the database (which closes the panel and prevents the toggle
+ // click from registering) — the previous `onClick` stopPropagation
+ // alone wasn't enough because mouseup bubbles before click fires.
+ <div
+ onMouseDown={(e) => e.stopPropagation()}
+ onMouseUp={(e) => e.stopPropagation()}
+ >
+ <Tooltip content={checkTooltip ?? ""}>
+ <Checkbox
+ checked={!!checked}
+ className="mr-2"
+ disabled={checkDisabled}
+ onClick={(e) => e.stopPropagation()}
+ onCheckedChange={(checked) => onCheckedChange?.(checked)}
+ />
+ </Tooltip>
+ </div>
) : null;
return (
- <div className="flex items-center max-w-full overflow-hidden gap-x-1">
+ <div className="flex items-center w-full max-w-full overflow-hidden gap-x-1">
{checkbox}
<div
@@ -86,7 +96,15 @@ export function DatabaseNode({
</div>
{!canQuery && (
- <div className="ml-auto">
+ <div
+ className="ml-auto shrink-0"
+ // The row activates on `mouseup` (Safari workaround for click
+ // events split across inner elements). Stop propagation here so
+ // clicking the button doesn't connect to the database first
+ // and unmount the button before its `onClick` can open the drawer.
+ onMouseDown={(e) => e.stopPropagation()}
+ onMouseUp={(e) => e.stopPropagation()}
+ >
<RequestQueryButton
size="sm"
text
diff --git a/frontend/src/react/components/sql-editor/DatabaseQueryContextPage.tsx b/frontend/src/react/components/sql-editor/DatabaseQueryContextPage.tsx
new file mode 100644
index 0000000000..56dc131cba
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/DatabaseQueryContextPage.tsx
@@ -0,0 +1,12 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate the
+ * `<DatabaseQueryContext>` root via `mount.ts`'s `pageDirs` lookup
+ * (it scans for `<page>.tsx` files at the registered roots, not
+ * subdirectories).
+ *
+ * Vue caller mounts this with `<ReactPageMount page="DatabaseQueryContextPage"
+ * :page-props="{ database, context }">`. Stage 21 deletes both this shim
+ * and the Vue caller once `ResultPanel.vue` flips to React and imports
+ * `DatabaseQueryContext` directly.
+ */
+export { DatabaseQueryContext as DatabaseQueryContextPage } from "./ResultPanel/DatabaseQueryContext";
diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsx
index 622252fee2..996092fced 100644
--- a/frontend/src/react/components/sql-editor/EditorAction.tsx
+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx
@@ -51,19 +51,34 @@ export function EditorAction({ onExecute }: Props) {
const [shareOpen, setShareOpen] = useState(false);
+ // Track each tab field as a separate primitive reactive subscription
+ // — Pinia mutates the tab proxy in place via `Object.assign`, so a
+ // getter that just returns `tabStore.currentTab` would only fire on
+ // tab switches (the proxy reference changing), not on `statement` /
+ // `status` / `connection.*` field flips that happen within the same
+ // tab. Splitting into one `useVueState` per field gives Vue a clean
+ // primitive value to compare on each change, so each individual
+ // mutation fires its own re-render (Run button enables as soon as
+ // the user types, Save button enables on `status` → DIRTY, etc.).
const currentTab = useVueState(() => tabStore.currentTab);
+ const tabStatement = useVueState(() => tabStore.currentTab?.statement ?? "");
+ const tabStatus = useVueState(() => tabStore.currentTab?.status);
+ const tabMode = useVueState(() => tabStore.currentTab?.mode);
+ const tabWorksheet = useVueState(() => tabStore.currentTab?.worksheet ?? "");
+ const tabConnectionTable = useVueState(
+ () => tabStore.currentTab?.connection.table ?? ""
+ );
const isDisconnected = useVueState(() => tabStore.isDisconnected);
const instance = useVueState(() => instanceRef.value);
const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);
const currentWorksheet = useVueState(() => sheetAndTabStore.currentSheet);
- const mode = currentTab?.mode;
- const isAdminMode = mode === "ADMIN";
- const showSheetsFeature = mode === "WORKSHEET";
- const isEmptyStatement = !currentTab || currentTab.statement === "";
+ const isAdminMode = tabMode === "ADMIN";
+ const showSheetsFeature = tabMode === "WORKSHEET";
+ const isEmptyStatement = !currentTab || tabStatement === "";
const queryTip =
- instance.engine === Engine.COSMOSDB && !currentTab?.connection.table
+ instance.engine === Engine.COSMOSDB && !tabConnectionTable
? t("database.table.select-tip")
: "";
@@ -71,36 +86,36 @@ export function EditorAction({ onExecute }: Props) {
if (isDisconnected) return false;
if (isEmptyStatement) return false;
if (instance.engine === Engine.COSMOSDB) {
- return !!currentTab?.connection.table;
+ return !!tabConnectionTable;
}
return true;
})();
const canWriteSheet = (() => {
- if (!currentTab?.worksheet) return false;
- const sheet = worksheetStore.getWorksheetByName(currentTab.worksheet);
+ if (!tabWorksheet) return false;
+ const sheet = worksheetStore.getWorksheetByName(tabWorksheet);
return sheet ? isWorksheetWritableV1(sheet) : false;
})();
const allowSave = (() => {
if (!showSheetsFeature || !currentTab) return false;
- if (currentTab.worksheet) {
+ if (tabWorksheet) {
if (!canWriteSheet) return false;
- const sheet = worksheetStore.getWorksheetByName(currentTab.worksheet);
+ const sheet = worksheetStore.getWorksheetByName(tabWorksheet);
if (sheet && sheet.database !== currentTab.connection.database) {
return true;
}
}
// Only disable when status is CLEAN (nothing to save).
// SAVING is allowed — manual save will abort auto-save and proceed.
- return currentTab.status !== "CLEAN";
+ return tabStatus !== "CLEAN";
})();
const allowShare = (() => {
if (!currentTab) return false;
- if (currentTab.status !== "CLEAN") return false;
+ if (tabStatus !== "CLEAN") return false;
if (isEmptyStatement || isDisconnected) return false;
- if (currentTab.worksheet && !canWriteSheet) return false;
+ if (tabWorksheet && !canWriteSheet) return false;
return true;
})();
diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
new file mode 100644
index 0000000000..12f1442718
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx
@@ -0,0 +1,257 @@
+import { Loader2, ShieldAlert } from "lucide-react";
+import { Suspense, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ Panel,
+ Group as PanelGroup,
+ Separator as PanelResizeHandle,
+} from "react-resizable-panels";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { AIChatToSQLBridgeHost } from "@/plugins/ai";
+import { aiContextEvents } from "@/plugins/ai/logic";
+import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";
+import { DatabaseChooser } from "@/react/components/sql-editor/DatabaseChooser";
+import { DiagramPanel } from "@/react/components/sql-editor/DiagramPanel";
+import { ExternalTablesPanel } from "@/react/components/sql-editor/ExternalTablesPanel";
+import { FunctionsPanel } from "@/react/components/sql-editor/FunctionsPanel";
+import { InfoPanel } from "@/react/components/sql-editor/InfoPanel";
+import { PackagesPanel } from "@/react/components/sql-editor/PackagesPanel";
+import { ProceduresPanel } from "@/react/components/sql-editor/ProceduresPanel";
+import { SchemaSelectToolbar } from "@/react/components/sql-editor/SchemaSelectToolbar";
+import { SequencesPanel } from "@/react/components/sql-editor/SequencesPanel";
+import { StandardPanel } from "@/react/components/sql-editor/StandardPanel/StandardPanel";
+import { TablesPanel } from "@/react/components/sql-editor/TablesPanel";
+import { TerminalPanel } from "@/react/components/sql-editor/TerminalPanel/TerminalPanel";
+import { TriggersPanel } from "@/react/components/sql-editor/TriggersPanel";
+import { ViewsPanel } from "@/react/components/sql-editor/ViewsPanel";
+import { Alert } from "@/react/components/ui/alert";
+import { VueMount } from "@/react/components/VueMount";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useDatabaseV1Store,
+ useDBSchemaV1Store,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+} from "@/store";
+import { isValidDatabaseName } from "@/types";
+import {
+ extractDatabaseResourceName,
+ getInstanceResource,
+ nextAnimationFrame,
+} from "@/utils";
+import { useViewStateNav } from "./common/useViewStateNav";
+
+const AIPaneFallback = () => (
+ <div className="w-full h-full grow flex flex-col items-center justify-center">
+ <Loader2 className="size-6 animate-spin text-control-light" />
+ </div>
+);
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue`.
+ *
+ * The host shell beneath `<EditorPanel>`. Two render modes:
+ * - `viewState.view === "CODE"` (or no viewState) — shows the worksheet
+ * editor (`<StandardPanel>`) or terminal (`<TerminalPanel>`) based on
+ * the active tab's mode. The Vue version did this selection in
+ * `EditorPanel.vue` and passed the result into `<Panels>` via a named
+ * slot; React inlines it here since slots-as-children don't survive
+ * the cross-framework boundary cleanly.
+ * - any other `viewState.view` — shows a metadata browser surface
+ * (info / tables / views / functions / etc.) with the schema-select
+ * toolbar above. The AI pane mounts to the right via a horizontal
+ * resizable split when the user has both the AI panel and a
+ * "code-viewer" surface open (matches the Vue `isShowingCode`
+ * gate that previously hoisted the AI pane up from `CodeViewer.vue`).
+ *
+ * The Vue version's `availableActions` computation lives in
+ * `useAvailableActions` (already React-side); the schema-sync watchers
+ * move into React `useEffect`s here.
+ */
+export function Panels() {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const dbSchemaStore = useDBSchemaV1Store();
+ const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();
+
+ const tab = useVueState(() => tabStore.currentTab);
+ const databaseName = useVueState(() => databaseRef.value.name);
+ const view = useVueState(() => tabStore.currentTab?.viewState?.view);
+ const showAIPanel = useVueState(() => uiStore.showAIPanel);
+ const isShowingCode = useVueState(() => uiStore.isShowingCode);
+ const editorPanelSize = useVueState(() => uiStore.editorPanelSize);
+
+ const showAIPaneAlongsidePanel = showAIPanel && isShowingCode;
+ const { setSchema, updateViewState } = useViewStateNav();
+ const databaseV1Store = useDatabaseV1Store();
+ const { execute } = useExecuteSQL();
+
+ // AI plugin "run-statement" handler — mirrors Vue's
+ // `useEmitteryEventListener(AIEvents, "run-statement", ...)`. The
+ // event bus is a module-level singleton so we don't need to traverse
+ // a Vue provide chain to access it.
+ useEffect(() => {
+ const off = aiContextEvents.on("run-statement", async ({ statement }) => {
+ const t = tabStore.currentTab;
+ if (!t) return;
+ updateViewState({ view: "CODE" });
+ await nextAnimationFrame();
+ const connection = t.connection;
+ const database = await databaseV1Store.getOrFetchDatabaseByName(
+ connection.database
+ );
+ void execute({
+ connection,
+ statement,
+ engine: getInstanceResource(database).engine,
+ explain: false,
+ selection: t.editorState.selection,
+ });
+ });
+ return () => {
+ off();
+ };
+ }, [tabStore, updateViewState, databaseV1Store, execute]);
+
+ const [databaseMetadata, setDatabaseMetadata] = useState<
+ | Awaited<ReturnType<typeof dbSchemaStore.getOrFetchDatabaseMetadata>>
+ | undefined
+ >();
+ useEffect(() => {
+ if (!databaseName || !isValidDatabaseName(databaseName)) {
+ setDatabaseMetadata(undefined);
+ return;
+ }
+ let cancelled = false;
+ void dbSchemaStore
+ .getOrFetchDatabaseMetadata({ database: databaseName, silent: true })
+ .then((meta) => {
+ if (!cancelled) setDatabaseMetadata(meta);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [databaseName, dbSchemaStore]);
+
+ // Pin the active schema to a sensible default whenever the tab,
+ // database metadata, or current schema changes (mirrors the Vue
+ // immediate watcher).
+ const tabId = tab?.id;
+ const currentSchema = tab?.viewState?.schema;
+ useEffect(() => {
+ if (!tabId) return;
+ if (!databaseMetadata) return;
+ if (
+ !isValidDatabaseName(
+ extractDatabaseResourceName(databaseMetadata.name).database
+ )
+ ) {
+ return;
+ }
+ if (
+ !currentSchema ||
+ databaseMetadata.schemas.findIndex((s) => s.name === currentSchema) < 0
+ ) {
+ const next = databaseMetadata.schemas[0]?.name;
+ if (next !== undefined) setSchema(next);
+ }
+ }, [tabId, databaseMetadata, currentSchema, setSchema]);
+
+ const codePanel = useMemo(() => {
+ if (!tab || tab.mode === "WORKSHEET") {
+ return <StandardPanel key={`standard-${tab?.id ?? "default"}`} />;
+ }
+ if (tab.mode === "ADMIN") {
+ return <TerminalPanel key={`terminal-${tab.id}`} />;
+ }
+ return (
+ <Alert variant="error" className="m-2" key={`no-permission-${tab.id}`}>
+ <ShieldAlert className="size-5 shrink-0 mt-0.5" />
+ <div>{t("database.access-denied")}</div>
+ </Alert>
+ );
+ }, [tab, t]);
+
+ const subPanel = view ? renderSubPanel(view, tab?.id) : null;
+
+ const handleAiResize = (sizePct: number) => {
+ if (!Number.isFinite(sizePct)) return;
+ uiStore.handleEditorPanelResize(sizePct / 100);
+ };
+
+ return (
+ <div className="flex-1 flex items-stretch overflow-hidden">
+ <div className="flex-1 overflow-y-hidden overflow-x-auto">
+ {(!view || view === "CODE") && codePanel}
+ {view && view !== "CODE" && (
+ <div className="h-full flex flex-col">
+ <div className="py-2 px-2 w-full flex flex-row gap-x-2 justify-between items-center">
+ <div className="flex items-center justify-start gap-2">
+ <DatabaseChooser disabled />
+ <SchemaSelectToolbar />
+ </div>
+ </div>
+ {showAIPaneAlongsidePanel ? (
+ <PanelGroup orientation="horizontal" className="flex-1">
+ <Panel
+ defaultSize={`${editorPanelSize.size * 100}%`}
+ minSize={`${editorPanelSize.min * 100}%`}
+ maxSize={`${editorPanelSize.max * 100}%`}
+ onResize={(size) => handleAiResize(size.asPercentage)}
+ >
+ {subPanel}
+ </Panel>
+ <PanelResizeHandle className={resizeHandleClass("vertical")} />
+ <Panel
+ defaultSize={`${(1 - editorPanelSize.size) * 100}%`}
+ minSize="10%"
+ >
+ <div className="h-full overflow-hidden flex flex-col">
+ <Suspense fallback={<AIPaneFallback />}>
+ <VueMount
+ component={AIChatToSQLBridgeHost}
+ className="h-full"
+ />
+ </Suspense>
+ </div>
+ </Panel>
+ </PanelGroup>
+ ) : (
+ <div className="flex-1 min-h-0">{subPanel}</div>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function renderSubPanel(view: string, tabId: string | undefined) {
+ const k = (suffix: string) => `${suffix}-${tabId ?? "default"}`;
+ switch (view) {
+ case "INFO":
+ return <InfoPanel key={k("info")} />;
+ case "TABLES":
+ return <TablesPanel key={k("tables")} />;
+ case "VIEWS":
+ return <ViewsPanel key={k("views")} />;
+ case "FUNCTIONS":
+ return <FunctionsPanel key={k("functions")} />;
+ case "PROCEDURES":
+ return <ProceduresPanel key={k("procedures")} />;
+ case "SEQUENCES":
+ return <SequencesPanel key={k("sequences")} />;
+ case "PACKAGES":
+ return <PackagesPanel key={k("packages")} />;
+ case "TRIGGERS":
+ return <TriggersPanel key={k("triggers")} />;
+ case "EXTERNAL_TABLES":
+ return <ExternalTablesPanel key={k("external-tables")} />;
+ case "DIAGRAM":
+ return <DiagramPanel key={k("diagram")} />;
+ default:
+ return null;
+ }
+}
diff --git a/frontend/src/react/components/sql-editor/PanelsPage.tsx b/frontend/src/react/components/sql-editor/PanelsPage.tsx
new file mode 100644
index 0000000000..eeead4ed4e
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/PanelsPage.tsx
@@ -0,0 +1,10 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate `<Panels>` via
+ * `mount.ts`'s `pageDirs` lookup (it scans for `<page>.tsx` files at
+ * the registered roots, not subdirectories).
+ *
+ * Vue caller mounts this with `<ReactPageMount page="PanelsPage">`.
+ * Removed when `EditorPanel.vue` flips to React in the next slice of
+ * Stage 21 and imports `Panels` directly.
+ */
+export { Panels as PanelsPage } from "./Panels/Panels";
diff --git a/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx
new file mode 100644
index 0000000000..2004c18830
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/RequestDrawerHost.tsx
@@ -0,0 +1,82 @@
+import {
+ createContext,
+ type ReactNode,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";
+import type { DatabaseResource, Permission } from "@/types";
+import type { Project } from "@/types/proto-es/v1/project_service_pb";
+import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";
+
+type RequestRoleArgs = {
+ project: Project;
+ requiredPermissions: Permission[];
+ initialRole: string;
+ initialDatabaseResources: DatabaseResource[];
+};
+
+type AccessGrantArgs = {
+ query?: string;
+ targets: string[];
+ unmask?: boolean;
+};
+
+type ContextValue = {
+ openRequestRoleSheet: (args: RequestRoleArgs) => void;
+ openAccessGrantDrawer: (args: AccessGrantArgs) => void;
+};
+
+const RequestDrawerHostContext = createContext<ContextValue | null>(null);
+
+export function useRequestDrawerHost(): ContextValue | null {
+ return useContext(RequestDrawerHostContext);
+}
+
+/**
+ * Hosts the role-request and JIT-grant drawers at the SQL Editor layout
+ * level so they survive when descendant overlays (e.g. the connection
+ * panel Sheet) close, and so their own Sheet backdrop renders above the
+ * connection panel — giving the user the expected modal cover.
+ *
+ * `RequestQueryButton` calls `useRequestDrawerHost().openX(...)` instead
+ * of holding local drawer state, which previously caused the drawer to
+ * unmount whenever its host row/connection panel did.
+ */
+export function RequestDrawerHost({ children }: { children: ReactNode }) {
+ const [roleArgs, setRoleArgs] = useState<RequestRoleArgs | null>(null);
+ const [grantArgs, setGrantArgs] = useState<AccessGrantArgs | null>(null);
+
+ const value = useMemo<ContextValue>(
+ () => ({
+ openRequestRoleSheet: setRoleArgs,
+ openAccessGrantDrawer: setGrantArgs,
+ }),
+ []
+ );
+
+ return (
+ <RequestDrawerHostContext.Provider value={value}>
+ {children}
+ {roleArgs && (
+ <RequestRoleSheet
+ open
+ project={roleArgs.project}
+ requiredPermissions={roleArgs.requiredPermissions}
+ initialRole={roleArgs.initialRole}
+ initialDatabaseResources={roleArgs.initialDatabaseResources}
+ onClose={() => setRoleArgs(null)}
+ />
+ )}
+ {grantArgs && (
+ <AccessGrantRequestDrawer
+ query={grantArgs.query}
+ targets={grantArgs.targets}
+ unmask={grantArgs.unmask}
+ onClose={() => setGrantArgs(null)}
+ />
+ )}
+ </RequestDrawerHostContext.Provider>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
index 4b69a53eb1..8a29f714f5 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.test.tsx
@@ -87,20 +87,23 @@ vi.mock("@/react/components/ui/button", () => ({
),
}));
-vi.mock("./RoleGrantPanel", () => ({
- RoleGrantPanel: ({
+vi.mock("@/react/pages/settings/RequestRoleSheet", () => ({
+ RequestRoleSheet: ({
+ open,
onClose,
- role,
+ initialRole,
}: {
+ open: boolean;
onClose: () => void;
- role: string;
- }) => (
- <div data-testid="role-grant-panel" data-role={role}>
- <button data-close-btn onClick={onClose}>
- Close
- </button>
- </div>
- ),
+ initialRole: string;
+ }) =>
+ open ? (
+ <div data-testid="request-role-sheet" data-role={initialRole}>
+ <button data-close-btn onClick={onClose}>
+ Close
+ </button>
+ </div>
+ ) : null,
}));
vi.mock("./AccessGrantRequestDrawer", () => ({
@@ -240,7 +243,7 @@ describe("RequestQueryButton", () => {
unmount();
});
- test("click in non-JIT mode opens RoleGrantPanel", async () => {
+ test("click in non-JIT mode opens RequestRoleSheet", async () => {
setupDefaultMocks(false, true);
const { container, render, unmount } = renderIntoContainer(
<RequestQueryButton
@@ -253,7 +256,7 @@ describe("RequestQueryButton", () => {
render();
expect(
- container.querySelector("[data-testid='role-grant-panel']")
+ container.querySelector("[data-testid='request-role-sheet']")
).toBeNull();
const btn = container.querySelector("button") as HTMLButtonElement;
@@ -262,7 +265,7 @@ describe("RequestQueryButton", () => {
});
expect(
- container.querySelector("[data-testid='role-grant-panel']")
+ container.querySelector("[data-testid='request-role-sheet']")
).not.toBeNull();
unmount();
});
@@ -286,7 +289,7 @@ describe("RequestQueryButton", () => {
expect(
container
- .querySelector("[data-testid='role-grant-panel']")
+ .querySelector("[data-testid='request-role-sheet']")
?.getAttribute("data-role")
).toBe("roles/sqlEditorReadUser");
unmount();
@@ -311,7 +314,7 @@ describe("RequestQueryButton", () => {
expect(
container
- .querySelector("[data-testid='role-grant-panel']")
+ .querySelector("[data-testid='request-role-sheet']")
?.getAttribute("data-role")
).toBe("roles/sqlEditorUser");
unmount();
@@ -336,7 +339,7 @@ describe("RequestQueryButton", () => {
expect(
container
- .querySelector("[data-testid='role-grant-panel']")
+ .querySelector("[data-testid='request-role-sheet']")
?.getAttribute("data-role")
).toBe("roles/sqlEditorReadUser");
unmount();
@@ -364,7 +367,7 @@ describe("RequestQueryButton", () => {
expect(
container
- .querySelector("[data-testid='role-grant-panel']")
+ .querySelector("[data-testid='request-role-sheet']")
?.getAttribute("data-role")
).toBe("roles/queryOnly");
unmount();
@@ -399,7 +402,7 @@ describe("RequestQueryButton", () => {
expect(
container
- .querySelector("[data-testid='role-grant-panel']")
+ .querySelector("[data-testid='request-role-sheet']")
?.getAttribute("data-role")
).toBe("roles/sqlEditorReadUser");
unmount();
diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
index 8c0f50377e..7ff0d7adfb 100644
--- a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx
@@ -6,6 +6,8 @@ import { FeatureBadge } from "@/react/components/FeatureBadge";
import { PermissionGuard } from "@/react/components/PermissionGuard";
import { Button } from "@/react/components/ui/button";
import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";
import {
hasFeature,
useProjectV1Store,
@@ -19,7 +21,7 @@ import type { PermissionDeniedDetail } from "@/types/proto-es/v1/common_pb";
import type { Role } from "@/types/proto-es/v1/role_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
import { AccessGrantRequestDrawer } from "./AccessGrantRequestDrawer";
-import { RoleGrantPanel } from "./RoleGrantPanel";
+import { useRequestDrawerHost } from "./RequestDrawerHost";
const SQL_SELECT_PERMISSION = "bb.sql.select";
@@ -69,6 +71,12 @@ export function RequestQueryButton({
}: Props) {
const { t } = useTranslation();
+ // When the layout-level host is mounted (typical case inside the SQL
+ // Editor), opening the drawer dispatches up to the host so it survives
+ // ancestor unmounts (e.g. the connection panel Sheet closing). Local
+ // state stays as a fallback for standalone callers (tests, isolated
+ // pages without the host).
+ const drawerHost = useRequestDrawerHost();
const [showPanel, setShowPanel] = useState(false);
const [showJITDrawer, setShowJITDrawer] = useState(false);
@@ -125,9 +133,26 @@ export function RequestQueryButton({
const handleClick = (e: React.MouseEvent) => {
e.stopPropagation();
if (useJIT) {
- setShowJITDrawer(true);
- } else {
- setShowPanel(true);
+ if (drawerHost) {
+ drawerHost.openAccessGrantDrawer({
+ query: statement,
+ targets: missingResources.map((r) => r.databaseFullName),
+ });
+ } else {
+ setShowJITDrawer(true);
+ }
+ } else if (project) {
+ if (drawerHost) {
+ drawerHost.openRequestRoleSheet({
+ project,
+ requiredPermissions:
+ permissionDeniedDetail.requiredPermissions as Permission[],
+ initialRole: defaultQueryRole,
+ initialDatabaseResources: missingResources,
+ });
+ } else {
+ setShowPanel(true);
+ }
}
};
@@ -144,7 +169,10 @@ export function RequestQueryButton({
variant={text ? "ghost" : "default"}
disabled={disabled || !hasRequestFeature}
onClick={handleClick}
- className="gap-x-1"
+ className={cn(
+ "gap-x-1",
+ text && "text-accent hover:bg-transparent hover:text-accent-hover"
+ )}
>
{hasRequestFeature ? (
<ShieldUser className="size-4" />
@@ -158,12 +186,15 @@ export function RequestQueryButton({
)}
</PermissionGuard>
- {showPanel && (
- <RoleGrantPanel
- projectName={projectName}
- databaseResources={missingResources}
- role={defaultQueryRole}
- requiredPermissions={permissionDeniedDetail.requiredPermissions}
+ {showPanel && project && (
+ <RequestRoleSheet
+ open={showPanel}
+ project={project}
+ requiredPermissions={
+ permissionDeniedDetail.requiredPermissions as Permission[]
+ }
+ initialRole={defaultQueryRole}
+ initialDatabaseResources={missingResources}
onClose={() => setShowPanel(false)}
/>
)}
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
index 80c64ec2c2..4df181e88b 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx
@@ -32,11 +32,8 @@ import {
getInstanceResource,
hexToRgb,
} from "@/utils";
-import {
- type CloseTabAction,
- resultTabEvents,
-} from "@/views/sql-editor/EditorPanel/ResultPanel/resultTabContext";
import { TabContextMenu } from "./ContextMenu";
+import { type CloseTabAction, resultTabEvents } from "./resultTabContext";
const MAX_EXPORT = 20;
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx b/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx
index a1ee8421b5..1cee9ec077 100644
--- a/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx
+++ b/frontend/src/react/components/sql-editor/ResultPanel/ContextMenu.tsx
@@ -6,10 +6,7 @@ import {
ContextMenuItem,
ContextMenuTrigger,
} from "@/react/components/ui/context-menu";
-import {
- type CloseTabAction,
- resultTabEvents,
-} from "@/views/sql-editor/EditorPanel/ResultPanel/resultTabContext";
+import { type CloseTabAction, resultTabEvents } from "./resultTabContext";
interface TabContextMenuProps {
index: number;
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx
new file mode 100644
index 0000000000..c3dc65938f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx
@@ -0,0 +1,131 @@
+import { Loader2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { useExecuteSQL } from "@/composables/useExecuteSQL";
+import { ResultView } from "@/react/components/sql-editor/ResultView";
+import { Button } from "@/react/components/ui/button";
+import { useSQLEditorTabStore } from "@/store";
+import type {
+ SQLEditorDatabaseQueryContext,
+ SQLEditorQueryParams,
+} from "@/types";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+
+export interface DatabaseQueryContextProps {
+ database: Database;
+ context: SQLEditorDatabaseQueryContext;
+}
+
+/**
+ * React port of `DatabaseQueryContext.vue`. Three render paths:
+ * - EXECUTING — spinner + elapsed-time + cancel button
+ * - CANCELLED — re-execute button
+ * - default — `<ResultView>` with the executed result set
+ *
+ * Auto-runs the query when status flips to `PENDING`. Mirrors the Vue
+ * watcher behavior — same `useExecuteSQL().runQuery` entrypoint that
+ * `EditorMain.tsx` already uses from React.
+ */
+export function DatabaseQueryContext({
+ database,
+ context,
+}: DatabaseQueryContextProps) {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const { runQuery } = useExecuteSQL();
+ const isExecuting = context.status === "EXECUTING";
+
+ // Trigger run on status === PENDING. Pinia's reactivity already
+ // surfaces context.status changes through props; the effect dep array
+ // re-fires whenever the status flips back to PENDING (which the
+ // re-execute button below does).
+ const lastRanContextRef = useRef<string | null>(null);
+ useEffect(() => {
+ if (context.status !== "PENDING") return;
+ const key = `${database.name}:${context.id}`;
+ if (lastRanContextRef.current === key) return;
+ lastRanContextRef.current = key;
+ void runQuery(database, context);
+ }, [database, context, runQuery, context.status]);
+
+ const elapsed = useElapsed(isExecuting, context.beginTimestampMS);
+
+ const cancelQuery = () => {
+ context.abortController?.abort();
+ tabStore.updateDatabaseQueryContext({
+ database: database.name,
+ contextId: context.id,
+ context: { status: "CANCELLED" },
+ });
+ };
+
+ const execQuery = (params: SQLEditorQueryParams) => {
+ const next = tabStore.updateDatabaseQueryContext({
+ database: database.name,
+ contextId: context.id,
+ context: { params },
+ });
+ if (!next) return;
+ // Reset so the auto-run effect re-fires for this context.
+ lastRanContextRef.current = null;
+ void runQuery(database, next);
+ };
+
+ if (isExecuting) {
+ return (
+ <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80">
+ <div className="flex items-center gap-x-1">
+ <Loader2 className="size-5 animate-spin mr-1" />
+ <span>{t("sql-editor.executing-query")}</span>
+ <span>-</span>
+ <span className="font-mono">{elapsed}</span>
+ </div>
+ <div>
+ <Button size="sm" variant="outline" onClick={cancelQuery}>
+ {t("common.cancel")}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ if (context.status === "CANCELLED") {
+ return (
+ <div className="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => execQuery(context.params)}
+ >
+ {t("sql-editor.execute-query")}
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <ResultView
+ executeParams={context.params}
+ database={database}
+ resultSet={context.resultSet}
+ />
+ );
+}
+
+/**
+ * Returns a humanized elapsed-time string ("3.2s") that ticks once per
+ * second while `running` is true. Replaces the Vue `useCurrentTimestamp`
+ * + computed combo. Stops/clears the interval on unmount or when
+ * `running` flips to false.
+ */
+function useElapsed(running: boolean, beginMS: number | undefined): string {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!running) return;
+ setNow(Date.now());
+ const handle = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(handle);
+ }, [running]);
+ if (!running || !beginMS) return "";
+ return `${((now - beginMS) / 1000).toFixed(1)}s`;
+}
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx
new file mode 100644
index 0000000000..ef0340f84f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx
@@ -0,0 +1,317 @@
+import { CircleAlert, Loader2, X } from "lucide-react";
+import { useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { watch } from "vue";
+import { Alert } from "@/react/components/ui/alert";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from "@/react/components/ui/context-menu";
+import {
+ Tabs,
+ TabsList,
+ TabsPanel,
+ TabsTrigger,
+} from "@/react/components/ui/tabs";
+import { Tooltip } from "@/react/components/ui/tooltip";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { useSQLEditorTabStore } from "@/store";
+import type { SQLEditorDatabaseQueryContext } from "@/types";
+import { getDataSourceTypeI18n } from "@/types";
+import type { Database } from "@/types/proto-es/v1/database_service_pb";
+import { formatAbsoluteDateTime, getInstanceResource } from "@/utils";
+import { BatchQuerySelect } from "./BatchQuerySelect";
+import { DatabaseQueryContext } from "./DatabaseQueryContext";
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue`.
+ *
+ * Hosts the batch-query database selector at the top, then a card-style
+ * tab strip of query contexts for the currently selected database, with
+ * each tab rendering a `<DatabaseQueryContext>` (spinner / cancelled /
+ * `<ResultView>`). Right-click on a tab opens a "close / close others /
+ * close to the right / close all" menu.
+ *
+ * State the React component owns:
+ * - `selectedDatabase`: which database the inner tabs are showing.
+ * - `selectedTab`: which query-context id is the active inner tab.
+ *
+ * State read from Pinia via `useVueState`:
+ * - `tabStore.currentTab.databaseQueryContexts.get(selectedDatabase.name)` —
+ * the array of query contexts for the active database. `{ deep: true }`
+ * so per-context status / resultSet flips re-render this tree without
+ * the Map reference changing.
+ */
+export function ResultPanel() {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const [selectedDatabase, setSelectedDatabase] = useState<Database>();
+ const [selectedTab, setSelectedTab] = useState<string>();
+
+ // Force a React re-render whenever **anything** changes inside the
+ // current tab's `databaseQueryContexts` Map — Map mutations
+ // (`set` / `delete`), inner-array mutations (`unshift` / `splice`),
+ // and per-item field flips (status PENDING → EXECUTING → DONE,
+ // resultSet writes). Keying the watch on the Map itself (rather than
+ // `Map.get(selectedDatabase.name)`) is critical: when this component
+ // first mounts `selectedDatabase` is `undefined`, and a getter that
+ // bailed out early would register **no** Vue reactive deps — leaving
+ // the watch dead forever, since `selectedDatabase` becoming defined
+ // doesn't fire any watcher. Tracking the Map directly with `deep:
+ // true` keeps the watch live across all reactive transitions, so the
+ // newly-created PENDING context reaches `<DatabaseQueryContext>` and
+ // its auto-run effect can advance the status.
+ const [, forceRender] = useState(0);
+ const tabIdForWatch = useVueState(() => tabStore.currentTab?.id);
+ useEffect(() => {
+ const stop = watch(
+ () => tabStore.currentTab?.databaseQueryContexts,
+ () => forceRender((v) => v + 1),
+ { deep: true, flush: "sync" }
+ );
+ return () => {
+ stop();
+ };
+ // Re-arm the watch when the active tab changes — each tab has its
+ // own `databaseQueryContexts` Map and Vue's auto-re-tracking only
+ // fires when the previously-tracked deps change. Without this,
+ // switching tabs would lose live updates from the new tab's Map.
+ }, [tabStore, tabIdForWatch]);
+
+ // Re-spread on every render so the iteration sees the latest array
+ // (Pinia mutates in place; cached refs would hide additions). Items
+ // are still the same Vue reactive proxies so `context.status` reads
+ // the live value.
+ const queryContexts: SQLEditorDatabaseQueryContext[] | undefined = (() => {
+ const name = selectedDatabase?.name;
+ if (!name) return undefined;
+ const arr = tabStore.currentTab?.databaseQueryContexts?.get(name);
+ return arr ? [...arr] : undefined;
+ })();
+
+ const isBatchQuery = useVueState(() => {
+ const contexts = tabStore.currentTab?.databaseQueryContexts;
+ return contexts ? contexts.size > 1 : false;
+ });
+
+ const batchModeDataSourceType = useVueState(() => {
+ if (!tabStore.isInBatchMode) return null;
+ return tabStore.currentTab?.batchQueryContext.dataSourceType ?? null;
+ });
+
+ const hasMultipleContexts = (queryContexts?.length ?? 0) > 1;
+
+ // Mirror Vue's `watch(queryContexts.[0]?.id, ..., { immediate: true })`:
+ // when the head of the contexts list changes, switch the active tab to
+ // it (newest run becomes selected).
+ const headId = queryContexts?.[0]?.id;
+ useEffect(() => {
+ if (headId !== undefined) setSelectedTab(headId);
+ }, [headId]);
+
+ const tabName = (context: SQLEditorDatabaseQueryContext): string => {
+ switch (context.status) {
+ case "PENDING":
+ return t("sql-editor.pending-query");
+ case "EXECUTING":
+ return t("sql-editor.executing-query");
+ default:
+ return formatAbsoluteDateTime(context.beginTimestampMS ?? Date.now());
+ }
+ };
+
+ const dataSourcesById = useMemo(() => {
+ if (!selectedDatabase) return new Map();
+ const instance = getInstanceResource(selectedDatabase);
+ return new Map((instance.dataSources ?? []).map((ds) => [ds.id, ds]));
+ }, [selectedDatabase]);
+
+ const dataSourceInContext = (context: SQLEditorDatabaseQueryContext) =>
+ dataSourcesById.get(context.params.connection.dataSourceId);
+
+ const isMatchedDataSource = (context: SQLEditorDatabaseQueryContext) => {
+ const mode = batchModeDataSourceType;
+ if (!mode) return true;
+ const ds = dataSourceInContext(context);
+ if (!ds) return true;
+ return ds.type === mode;
+ };
+
+ const closeTab = (id: string) => {
+ const next = tabStore.removeDatabaseQueryContext({
+ database: selectedDatabase?.name ?? "",
+ contextId: id,
+ });
+ if (selectedTab === id && next) setSelectedTab(next.id);
+ };
+
+ const closeOthers = (id: string) => {
+ tabStore.batchRemoveDatabaseQueryContext({
+ database: selectedDatabase?.name ?? "",
+ contextIds:
+ queryContexts?.filter((c) => c.id !== id).map((c) => c.id) ?? [],
+ });
+ setSelectedTab(id);
+ };
+
+ const closeToTheRight = (id: string) => {
+ const idx = queryContexts?.findIndex((c) => c.id === id) ?? -1;
+ if (idx < 0) return;
+ tabStore.batchRemoveDatabaseQueryContext({
+ database: selectedDatabase?.name ?? "",
+ contextIds: queryContexts?.slice(idx + 1).map((c) => c.id) ?? [],
+ });
+ setSelectedTab(id);
+ };
+
+ const closeAll = () => {
+ tabStore.deleteDatabaseQueryContext(selectedDatabase?.name ?? "");
+ setSelectedTab(undefined);
+ };
+
+ return (
+ <div className="relative w-full h-full flex flex-col justify-start items-start z-10 overflow-x-hidden">
+ <div className="w-full shrink-0">
+ <BatchQuerySelect
+ selectedDatabase={selectedDatabase}
+ onSelectedDatabaseChange={setSelectedDatabase}
+ />
+ </div>
+ {selectedDatabase && queryContexts && queryContexts.length > 0 && (
+ <Tabs
+ value={selectedTab ?? ""}
+ onValueChange={(v) => setSelectedTab(v as string)}
+ className={cn(
+ "flex-1 flex flex-col overflow-hidden px-2 min-h-0",
+ isBatchQuery ? "pt-0" : "pt-2"
+ )}
+ >
+ <TabsList className="shrink-0 gap-x-1 border-b border-control-border">
+ {queryContexts.map((context) => (
+ <TabContextMenu
+ key={context.id}
+ onSelect={(action) => {
+ switch (action) {
+ case "CLOSE":
+ closeTab(context.id);
+ break;
+ case "CLOSE_OTHERS":
+ closeOthers(context.id);
+ break;
+ case "CLOSE_TO_THE_RIGHT":
+ closeToTheRight(context.id);
+ break;
+ case "CLOSE_ALL":
+ closeAll();
+ break;
+ }
+ }}
+ >
+ <Tooltip content={context.params.statement}>
+ <TabsTrigger
+ value={context.id}
+ className="flex items-center gap-x-2 px-3 py-1"
+ >
+ <span className="truncate">{tabName(context)}</span>
+ {context.resultSet?.error && (
+ <CircleAlert className="size-4 text-error shrink-0" />
+ )}
+ {context.status === "EXECUTING" && (
+ <Loader2 className="size-3 animate-spin shrink-0" />
+ )}
+ {hasMultipleContexts && (
+ <X
+ className="size-4 text-control-light hover:text-control shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ closeTab(context.id);
+ }}
+ />
+ )}
+ </TabsTrigger>
+ </Tooltip>
+ </TabContextMenu>
+ ))}
+ </TabsList>
+ {queryContexts.map((context, i) => (
+ <TabsPanel
+ key={context.id}
+ value={context.id}
+ className="flex-1 flex flex-col min-h-0 overflow-hidden mt-2"
+ >
+ {i === 0 &&
+ batchModeDataSourceType &&
+ !isMatchedDataSource(context) && (
+ <Alert variant="warning" className="mb-2">
+ {t("sql-editor.batch-query.select-data-source.not-match", {
+ expect: getDataSourceTypeI18n(
+ tabStore.currentTab?.batchQueryContext.dataSourceType
+ ),
+ actual: getDataSourceTypeI18n(
+ dataSourceInContext(context)?.type
+ ),
+ })}
+ </Alert>
+ )}
+ <DatabaseQueryContext
+ database={selectedDatabase}
+ context={context}
+ />
+ </TabsPanel>
+ ))}
+ </Tabs>
+ )}
+ </div>
+ );
+}
+
+type CloseAction =
+ | "CLOSE"
+ | "CLOSE_OTHERS"
+ | "CLOSE_TO_THE_RIGHT"
+ | "CLOSE_ALL";
+
+const CLOSE_ACTIONS: readonly CloseAction[] = [
+ "CLOSE",
+ "CLOSE_OTHERS",
+ "CLOSE_TO_THE_RIGHT",
+ "CLOSE_ALL",
+];
+
+const CLOSE_ACTION_KEYS: Record<CloseAction, string> = {
+ CLOSE: "sql-editor.tab.context-menu.actions.close",
+ CLOSE_OTHERS: "sql-editor.tab.context-menu.actions.close-others",
+ CLOSE_TO_THE_RIGHT: "sql-editor.tab.context-menu.actions.close-to-the-right",
+ CLOSE_ALL: "sql-editor.tab.context-menu.actions.close-all",
+};
+
+/**
+ * Right-click context menu wrapper for a single tab. Local to ResultPanel
+ * so the close-tab handler is delivered directly via prop, sidestepping
+ * the cross-component `resultTabEvents` channel that Stage 18's
+ * `BatchQuerySelect` already owns for its database-strip tabs.
+ */
+function TabContextMenu({
+ children,
+ onSelect,
+}: {
+ children: React.ReactElement;
+ onSelect: (action: CloseAction) => void;
+}) {
+ const { t } = useTranslation();
+ return (
+ <ContextMenu>
+ <ContextMenuTrigger render={children} />
+ <ContextMenuContent>
+ {CLOSE_ACTIONS.map((action) => (
+ <ContextMenuItem key={action} onClick={() => onSelect(action)}>
+ {t(CLOSE_ACTION_KEYS[action])}
+ </ContextMenuItem>
+ ))}
+ </ContextMenuContent>
+ </ContextMenu>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/ResultPanel/resultTabContext.ts b/frontend/src/react/components/sql-editor/ResultPanel/resultTabContext.ts
new file mode 100644
index 0000000000..69841744c3
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanel/resultTabContext.ts
@@ -0,0 +1,23 @@
+import Emittery from "emittery";
+
+export type CloseTabAction =
+ | "CLOSE"
+ | "CLOSE_OTHERS"
+ | "CLOSE_TO_THE_RIGHT"
+ | "CLOSE_ALL";
+
+/**
+ * Module-level singleton emittery used by `BatchQuerySelect`'s
+ * right-click context menu (mounted once per database tab) to broadcast
+ * close-tab actions back to the parent. Lives outside any component so
+ * the menu's child trigger and the parent's listener can communicate
+ * without a Vue/React provide chain.
+ *
+ * The emitter is *only* used by `BatchQuerySelect` for its database
+ * tabs. The inner per-query-context tabs in `ResultPanel.tsx` use a
+ * local `onSelect` prop instead — keeping the channel single-consumer
+ * avoids cross-listener fan-out when both strips are visible.
+ */
+export const resultTabEvents = new Emittery<{
+ "close-tab": { index: number; action: CloseTabAction };
+}>();
diff --git a/frontend/src/react/components/sql-editor/ResultPanelPage.tsx b/frontend/src/react/components/sql-editor/ResultPanelPage.tsx
new file mode 100644
index 0000000000..aef6220bdc
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/ResultPanelPage.tsx
@@ -0,0 +1,10 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate the React
+ * `<ResultPanel>` via `mount.ts`'s `pageDirs` lookup (it scans for
+ * `<page>.tsx` files at the registered roots, not subdirectories).
+ *
+ * Vue caller mounts this with `<ReactPageMount page="ResultPanelPage">`.
+ * The shim is removed when `StandardPanel.vue` flips to React in the
+ * next slice of Stage 21 and imports `ResultPanel` directly.
+ */
+export { ResultPanel as ResultPanelPage } from "./ResultPanel/ResultPanel";
diff --git a/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx
index e9fd094501..af5f4a6000 100644
--- a/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx
+++ b/frontend/src/react/components/sql-editor/ResultView/ErrorView.tsx
@@ -2,11 +2,11 @@ import { type IRange, Selection } from "monaco-editor";
import { type ReactNode, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { positionWithOffset } from "@/components/MonacoEditor/utils";
+import { activeSQLEditorRef } from "@/react/components/sql-editor/StandardPanel/state";
import { Alert } from "@/react/components/ui/alert";
import { Button } from "@/react/components/ui/button";
import { cn } from "@/react/lib/utils";
import type { SQLEditorQueryParams, SQLResultSetV1 } from "@/types";
-import { activeSQLEditorRef } from "@/views/sql-editor/EditorPanel/StandardPanel/state";
import { sqlEditorEvents } from "@/views/sql-editor/events";
import { PostgresError } from "./PostgresError";
diff --git a/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsx b/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsx
deleted file mode 100644
index f39f675f6f..0000000000
--- a/frontend/src/react/components/sql-editor/RoleGrantPanel.test.tsx
+++ /dev/null
@@ -1,483 +0,0 @@
-import type { ReactElement } from "react";
-import { act } from "react";
-import { createRoot } from "react-dom/client";
-import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
-
-(
- globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
-).IS_REACT_ACT_ENVIRONMENT = true;
-
-const mocks = vi.hoisted(() => ({
- useTranslation: vi.fn(() => ({ t: (key: string) => key })),
- useVueState: vi.fn<(getter: () => unknown) => unknown>(),
- useCurrentUserV1: vi.fn(),
- useProjectV1Store: vi.fn(),
- useRoleStore: vi.fn(),
- useSettingV1Store: vi.fn(() => ({
- workspaceProfile: { maximumRoleExpiration: undefined },
- })),
- pushNotification: vi.fn(),
- issueServiceClientConnect: {
- createIssue: vi.fn().mockResolvedValue({ name: "projects/proj1/issues/1" }),
- },
- roleHasDatabaseLimitation: vi.fn(() => true),
-}));
-
-vi.mock("react-i18next", () => ({
- useTranslation: mocks.useTranslation,
-}));
-
-vi.mock("@/react/hooks/useVueState", () => ({
- useVueState: mocks.useVueState,
-}));
-
-vi.mock("@/store", () => ({
- useCurrentUserV1: mocks.useCurrentUserV1,
- useProjectV1Store: mocks.useProjectV1Store,
- useRoleStore: mocks.useRoleStore,
- useSettingV1Store: mocks.useSettingV1Store,
- pushNotification: mocks.pushNotification,
-}));
-
-vi.mock("@/types", () => ({
- PresetRoleType: {
- PROJECT_OWNER: "roles/projectOwner",
- },
-}));
-
-vi.mock("@/connect", () => ({
- issueServiceClientConnect: mocks.issueServiceClientConnect,
-}));
-
-vi.mock("@/router", () => ({
- router: {
- resolve: vi.fn(() => ({ fullPath: "/projects/proj1/issues/1" })),
- },
-}));
-
-vi.mock("@/router/dashboard/projectV1", () => ({
- PROJECT_V1_ROUTE_ISSUE_DETAIL: "project.issue-detail",
-}));
-
-vi.mock("@/utils", () => ({
- displayRoleTitle: vi.fn((r: string) => r),
- extractIssueUID: vi.fn(() => "1"),
- extractProjectResourceName: vi.fn(() => "proj1"),
- formatIssueTitle: vi.fn((title: string) => title),
-}));
-
-vi.mock("@/utils/issue/cel", () => ({
- buildConditionExpr: vi.fn(() => ({ expression: "", description: "" })),
-}));
-
-vi.mock("@/components/ProjectMember/utils", () => ({
- roleHasDatabaseLimitation: mocks.roleHasDatabaseLimitation,
-}));
-
-vi.mock("@/react/components/ui/sheet", () => ({
- Sheet: ({ children, open }: { children: React.ReactNode; open?: boolean }) =>
- open !== false ? <div data-testid="sheet">{children}</div> : null,
- SheetContent: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="sheet-content">{children}</div>
- ),
- SheetHeader: ({ children }: { children: React.ReactNode }) => (
- <div>{children}</div>
- ),
- SheetTitle: ({ children }: { children: React.ReactNode }) => (
- <h2 data-testid="sheet-title">{children}</h2>
- ),
- SheetBody: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="sheet-body">{children}</div>
- ),
- SheetFooter: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="sheet-footer">{children}</div>
- ),
-}));
-
-vi.mock("@/react/components/ui/button", () => ({
- Button: ({
- children,
- onClick,
- disabled,
- }: {
- children: React.ReactNode;
- onClick?: () => void;
- disabled?: boolean;
- }) => (
- <button disabled={disabled} onClick={onClick}>
- {children}
- </button>
- ),
-}));
-
-vi.mock("@/react/components/ui/textarea", () => ({
- Textarea: ({
- value,
- onChange,
- placeholder,
- }: {
- value: string;
- onChange: (e: { target: { value: string } }) => void;
- placeholder?: string;
- }) => (
- <textarea
- data-testid="reason-textarea"
- value={value}
- placeholder={placeholder}
- onChange={onChange}
- />
- ),
-}));
-
-vi.mock("@/react/components/ui/expiration-picker", () => ({
- ExpirationPicker: () => <div data-testid="expiration-picker" />,
-}));
-
-vi.mock("@/react/components/IssueLabelSelect", () => ({
- IssueLabelSelect: () => <div data-testid="label-select" />,
-}));
-
-vi.mock("@/react/components/RoleSelect", () => ({
- RoleSelect: ({
- value,
- disabled,
- scope,
- }: {
- value: string[];
- onChange: (roles: string[]) => void;
- multiple?: boolean;
- disabled?: boolean;
- scope?: string;
- }) => (
- <div
- data-testid="role-select"
- data-value={value.join(",")}
- data-disabled={String(disabled ?? false)}
- data-scope={scope ?? ""}
- />
- ),
-}));
-
-vi.mock("@/react/components/DatabaseResourceSelector", () => ({
- DatabaseResourceSelector: ({
- value,
- onChange,
- }: {
- projectName: string;
- value: { databaseFullName: string }[];
- onChange: (resources: { databaseFullName: string }[]) => void;
- }) => (
- <div
- data-testid="database-resource-selector"
- data-count={value.length}
- onClick={() =>
- onChange([...value, { databaseFullName: "instances/i1/databases/db1" }])
- }
- />
- ),
-}));
-
-vi.mock("@/types/proto-es/v1/issue_service_pb", () => ({
- CreateIssueRequestSchema: {},
- Issue_Type: { ROLE_GRANT: 3 },
- IssueSchema: {},
- RoleGrantSchema: {},
-}));
-
-vi.mock("@bufbuild/protobuf", () => ({
- create: vi.fn((_, data) => data ?? {}),
-}));
-
-vi.mock("@bufbuild/protobuf/wkt", () => ({
- DurationSchema: {},
-}));
-
-// Stub ResizeObserver
-globalThis.ResizeObserver = class ResizeObserver {
- observe() {}
- unobserve() {}
- disconnect() {}
-};
-
-let RoleGrantPanel: typeof import("./RoleGrantPanel").RoleGrantPanel;
-
-const renderIntoContainer = (element: ReactElement) => {
- const container = document.createElement("div");
- const root = createRoot(container);
- document.body.appendChild(container);
- return {
- container,
- render: () => {
- act(() => {
- root.render(element);
- });
- },
- unmount: () => {
- act(() => {
- root.unmount();
- });
- container.remove();
- },
- };
-};
-
-const setupDefaultMocks = () => {
- mocks.useTranslation.mockReturnValue({ t: (key: string) => key });
- mocks.useCurrentUserV1.mockReturnValue({
- value: { email: "[email protected]" },
- });
- mocks.useProjectV1Store.mockReturnValue({
- getProjectByName: vi.fn(() => ({
- name: "projects/proj1",
- enforceIssueTitle: false,
- forceIssueLabels: false,
- issueLabels: [],
- })),
- });
- mocks.useRoleStore.mockReturnValue({
- getRoleByName: vi.fn(() => ({
- name: "roles/sqlEditorUser",
- permissions: ["bb.sql.select", "bb.sql.explain"],
- })),
- });
- mocks.roleHasDatabaseLimitation.mockReturnValue(true);
- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());
-};
-
-beforeEach(async () => {
- vi.clearAllMocks();
- setupDefaultMocks();
- ({ RoleGrantPanel } = await import("./RoleGrantPanel"));
-});
-
-afterEach(() => {
- document.body.innerHTML = "";
-});
-
-describe("RoleGrantPanel", () => {
- test("renders with sheet title", () => {
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- expect(
- container.querySelector("[data-testid='sheet-title']")?.textContent
- ).toBe("issue.title.request-role");
- unmount();
- });
-
- test("renders RoleSelect as disabled with the correct role value", () => {
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- const roleSelect = container.querySelector("[data-testid='role-select']");
- expect(roleSelect).not.toBeNull();
- expect(roleSelect?.getAttribute("data-value")).toBe("roles/sqlEditorUser");
- expect(roleSelect?.getAttribute("data-disabled")).toBe("true");
- expect(roleSelect?.getAttribute("data-scope")).toBe("project");
- unmount();
- });
-
- test("shows required permissions when provided", () => {
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={["bb.sql.select", "bb.sql.explain"]}
- onClose={onClose}
- />
- );
- render();
-
- expect(container.textContent).toContain("bb.sql.select");
- expect(container.textContent).toContain("bb.sql.explain");
- unmount();
- });
-
- test("renders database resource selector when role has database limitation", () => {
- mocks.roleHasDatabaseLimitation.mockReturnValue(true);
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- expect(
- container.querySelector("[data-testid='database-resource-selector']")
- ).not.toBeNull();
- unmount();
- });
-
- test("does not render database resource selector when role has no database limitation", () => {
- mocks.roleHasDatabaseLimitation.mockReturnValue(false);
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[]}
- role="roles/projectOwner"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- expect(
- container.querySelector("[data-testid='database-resource-selector']")
- ).toBeNull();
- unmount();
- });
-
- test("submit disabled when database resources empty and role has database limitation", () => {
- mocks.roleHasDatabaseLimitation.mockReturnValue(true);
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- const buttons = container.querySelectorAll("button");
- let submitBtn: HTMLButtonElement | null = null;
- for (const btn of Array.from(buttons)) {
- if (btn.textContent?.includes("common.submit")) {
- submitBtn = btn;
- break;
- }
- }
- expect(submitBtn).not.toBeNull();
- expect(submitBtn!.disabled).toBe(true);
- unmount();
- });
-
- test("cancel button calls onClose", () => {
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- const buttons = container.querySelectorAll("button");
- let cancelBtn: HTMLButtonElement | null = null;
- for (const btn of Array.from(buttons)) {
- if (btn.textContent?.includes("common.cancel")) {
- cancelBtn = btn;
- break;
- }
- }
- expect(cancelBtn).not.toBeNull();
- act(() => {
- cancelBtn!.click();
- });
- expect(onClose).toHaveBeenCalledOnce();
- unmount();
- });
-
- test("submit button disabled when reason required but empty", () => {
- mocks.useProjectV1Store.mockReturnValue({
- getProjectByName: vi.fn(() => ({
- name: "projects/proj1",
- enforceIssueTitle: true,
- forceIssueLabels: false,
- issueLabels: [],
- })),
- });
-
- const onClose = vi.fn();
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- const buttons = container.querySelectorAll("button");
- let submitBtn: HTMLButtonElement | null = null;
- for (const btn of Array.from(buttons)) {
- if (btn.textContent?.includes("common.submit")) {
- submitBtn = btn;
- break;
- }
- }
- expect(submitBtn).not.toBeNull();
- expect(submitBtn!.disabled).toBe(true);
- unmount();
- });
-
- test("submit calls createIssue when reason not required and db resources provided", async () => {
- mocks.roleHasDatabaseLimitation.mockReturnValue(true);
- const onClose = vi.fn();
- const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
-
- const { container, render, unmount } = renderIntoContainer(
- <RoleGrantPanel
- projectName="projects/proj1"
- databaseResources={[{ databaseFullName: "instances/i1/databases/db1" }]}
- role="roles/sqlEditorUser"
- requiredPermissions={[]}
- onClose={onClose}
- />
- );
- render();
-
- const buttons = container.querySelectorAll("button");
- let submitBtn: HTMLButtonElement | null = null;
- for (const btn of Array.from(buttons)) {
- if (btn.textContent?.includes("common.submit")) {
- submitBtn = btn;
- break;
- }
- }
- expect(submitBtn).not.toBeNull();
- expect(submitBtn!.disabled).toBe(false);
-
- await act(async () => {
- submitBtn!.click();
- });
- await vi.waitFor(() => {
- expect(mocks.issueServiceClientConnect.createIssue).toHaveBeenCalled();
- });
- openSpy.mockRestore();
- unmount();
- });
-});
diff --git a/frontend/src/react/components/sql-editor/RoleGrantPanel.tsx b/frontend/src/react/components/sql-editor/RoleGrantPanel.tsx
deleted file mode 100644
index d197d85f09..0000000000
--- a/frontend/src/react/components/sql-editor/RoleGrantPanel.tsx
+++ /dev/null
@@ -1,380 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { DurationSchema } from "@bufbuild/protobuf/wkt";
-import dayjs from "dayjs";
-import { useMemo, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { roleHasDatabaseLimitation } from "@/components/ProjectMember/utils";
-import { issueServiceClientConnect } from "@/connect";
-import { DatabaseResourceSelector } from "@/react/components/DatabaseResourceSelector";
-import { IssueLabelSelect } from "@/react/components/IssueLabelSelect";
-import { RoleSelect } from "@/react/components/RoleSelect";
-import { Button } from "@/react/components/ui/button";
-import { ExpirationPicker } from "@/react/components/ui/expiration-picker";
-import {
- Sheet,
- SheetBody,
- SheetContent,
- SheetFooter,
- SheetHeader,
- SheetTitle,
-} from "@/react/components/ui/sheet";
-import { Textarea } from "@/react/components/ui/textarea";
-import { useVueState } from "@/react/hooks/useVueState";
-import { router } from "@/router";
-import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";
-import {
- pushNotification,
- useCurrentUserV1,
- useProjectV1Store,
- useRoleStore,
- useSettingV1Store,
-} from "@/store";
-import { type DatabaseResource, PresetRoleType } from "@/types";
-import {
- CreateIssueRequestSchema,
- Issue_Type,
- IssueSchema,
- RoleGrantSchema,
-} from "@/types/proto-es/v1/issue_service_pb";
-import {
- displayRoleTitle,
- extractIssueUID,
- extractProjectResourceName,
- formatIssueTitle,
-} from "@/utils";
-import { buildConditionExpr } from "@/utils/issue/cel";
-
-interface Props {
- readonly projectName: string;
- readonly databaseResources: DatabaseResource[];
- readonly role: string;
- readonly requiredPermissions: string[];
- readonly onClose: () => void;
-}
-
-interface RoleGrantPanelInnerProps {
- readonly stableProjectName: string;
- readonly databaseResources: DatabaseResource[];
- readonly role: string;
- readonly requiredPermissions: string[];
- readonly onClose: () => void;
-}
-
-function RoleGrantPanelInner({
- stableProjectName,
- databaseResources,
- role,
- requiredPermissions,
- onClose,
-}: RoleGrantPanelInnerProps) {
- const { t } = useTranslation();
-
- const currentUserRef = useCurrentUserV1();
- const currentUser = useVueState(() => currentUserRef.value);
-
- const projectStore = useProjectV1Store();
- const project = useVueState(() =>
- projectStore.getProjectByName(stableProjectName)
- );
-
- const roleStore = useRoleStore();
- const selectedRole = useVueState(() => roleStore.getRoleByName(role));
-
- const settingStore = useSettingV1Store();
- const maximumRoleExpirationDays = useVueState(() => {
- if (role === PresetRoleType.PROJECT_OWNER) return undefined;
- const seconds =
- settingStore.workspaceProfile.maximumRoleExpiration?.seconds;
- if (!seconds) return undefined;
- return Math.floor(Number(seconds) / (60 * 60 * 24));
- });
-
- const showDatabaseSelector = roleHasDatabaseLimitation(role);
-
- const [dbResources, setDbResources] =
- useState<DatabaseResource[]>(databaseResources);
- const [reason, setReason] = useState("");
- const [expirationTimestamp, setExpirationTimestamp] = useState<
- string | undefined
- >(undefined);
- const [labels, setLabels] = useState<string[]>([]);
- const [submitting, setSubmitting] = useState(false);
-
- const minDatetime = dayjs().format("YYYY-MM-DDTHH:mm");
- const maxDatetime = maximumRoleExpirationDays
- ? dayjs().add(maximumRoleExpirationDays, "days").format("YYYY-MM-DDTHH:mm")
- : undefined;
-
- const reasonRequired = useMemo(
- () => project?.enforceIssueTitle ?? false,
- [project]
- );
-
- const labelsMisconfigured = useMemo(
- () => !!(project?.forceIssueLabels && project.issueLabels.length === 0),
- [project]
- );
-
- const expirationIsInPast =
- !!expirationTimestamp &&
- dayjs(expirationTimestamp).unix() <= dayjs().unix();
-
- const expirationExceedsMax =
- !!expirationTimestamp &&
- !!maximumRoleExpirationDays &&
- dayjs(expirationTimestamp).isAfter(
- dayjs().add(maximumRoleExpirationDays, "days")
- );
-
- // When the workspace has a maximumRoleExpiration policy, the user must
- // pick an expiration — otherwise the backend treats missing expiration as
- // effectively unbounded (math.MaxInt32 days) and bypasses the cap.
- const expirationRequired = maximumRoleExpirationDays !== undefined;
-
- const canSubmit = useMemo(() => {
- if (submitting) return false;
- if (reasonRequired && !reason.trim()) return false;
- if (showDatabaseSelector && dbResources.length === 0) return false;
- if (expirationRequired && !expirationTimestamp) return false;
- if (expirationIsInPast) return false;
- if (expirationExceedsMax) return false;
- if (project?.forceIssueLabels && labels.length === 0) return false;
- if (labelsMisconfigured) return false;
- return true;
- }, [
- submitting,
- reasonRequired,
- reason,
- showDatabaseSelector,
- dbResources,
- expirationRequired,
- expirationTimestamp,
- expirationIsInPast,
- expirationExceedsMax,
- project,
- labels,
- labelsMisconfigured,
- ]);
-
- const handleSubmit = async () => {
- if (!canSubmit) return;
- setSubmitting(true);
- try {
- const trimmedReason = reason.trim();
- const expirationTimestampInMS = expirationTimestamp
- ? dayjs(expirationTimestamp).valueOf()
- : undefined;
-
- const condition = buildConditionExpr({
- role,
- description: trimmedReason,
- expirationTimestampInMS,
- databaseResources: dbResources.length > 0 ? dbResources : undefined,
- });
-
- const expiration = expirationTimestamp
- ? create(DurationSchema, {
- seconds: BigInt(
- Math.max(0, dayjs(expirationTimestamp).unix() - dayjs().unix())
- ),
- })
- : undefined;
-
- const roleGrant = create(RoleGrantSchema, {
- role,
- user: `users/${currentUser.email}`,
- condition,
- expiration,
- });
-
- const titleDatabaseNames =
- dbResources.length > 0
- ? [...new Set(dbResources.map((r) => r.databaseFullName))]
- : undefined;
-
- const title = project?.enforceIssueTitle
- ? `[${t("issue.title.request-role")}] ${trimmedReason}`
- : formatIssueTitle(
- t("issue.title.request-specific-role", {
- role: displayRoleTitle(role),
- }),
- titleDatabaseNames
- );
-
- const newIssue = create(IssueSchema, {
- title,
- description: trimmedReason,
- type: Issue_Type.ROLE_GRANT,
- roleGrant,
- labels,
- });
-
- const response = await issueServiceClientConnect.createIssue(
- create(CreateIssueRequestSchema, {
- parent: stableProjectName,
- issue: newIssue,
- })
- );
-
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.created"),
- });
-
- const route = router.resolve({
- name: PROJECT_V1_ROUTE_ISSUE_DETAIL,
- params: {
- projectId: extractProjectResourceName(response.name),
- issueId: extractIssueUID(response.name),
- },
- });
- window.open(route.fullPath, "_blank", "noopener,noreferrer");
- onClose();
- } catch {
- // Error notification pushed by client middleware.
- } finally {
- setSubmitting(false);
- }
- };
-
- const issueLabels = project?.issueLabels ?? [];
- const forceIssueLabels = !!project?.forceIssueLabels;
- const showLabelSelect = issueLabels.length > 0 || forceIssueLabels;
-
- return (
- <>
- <SheetHeader>
- <SheetTitle>{t("issue.title.request-role")}</SheetTitle>
- </SheetHeader>
- <SheetBody>
- <div className="flex flex-col gap-y-4">
- {requiredPermissions.length > 0 && (
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.required-permission")}
- </label>
- <ul className="list-disc pl-4 text-sm text-control-light">
- {requiredPermissions.map((p) => (
- <li key={p}>{p}</li>
- ))}
- </ul>
- </div>
- )}
-
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.role.self")}
- </label>
- <RoleSelect
- value={[role]}
- onChange={() => {}}
- multiple={false}
- disabled={true}
- scope="project"
- />
- </div>
-
- {selectedRole && selectedRole.permissions.length > 0 && (
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.permissions")} ({selectedRole.permissions.length})
- </label>
- <div className="max-h-[10em] overflow-auto border border-control-border rounded-sm p-2">
- <ul className="list-none">
- {selectedRole.permissions.map((p) => (
- <li key={p} className="text-sm leading-5">
- {p}
- </li>
- ))}
- </ul>
- </div>
- </div>
- )}
-
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.reason")}
- {reasonRequired && <span className="text-error ml-0.5">*</span>}
- </label>
- <Textarea
- value={reason}
- onChange={(e) => setReason(e.target.value)}
- placeholder={t("common.reason")}
- rows={3}
- />
- </div>
-
- {showDatabaseSelector && (
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.databases")}
- <span className="text-error ml-0.5">*</span>
- </label>
- <DatabaseResourceSelector
- projectName={stableProjectName}
- value={dbResources}
- onChange={setDbResources}
- />
- </div>
- )}
-
- <div className="flex flex-col gap-y-1">
- <label className="text-sm font-medium text-control">
- {t("common.expiration")}
- {expirationRequired && (
- <span className="text-error ml-0.5">*</span>
- )}
- </label>
- <ExpirationPicker
- value={expirationTimestamp}
- onChange={setExpirationTimestamp}
- minDate={minDatetime}
- maxDate={maxDatetime}
- />
- </div>
-
- {showLabelSelect && (
- <IssueLabelSelect
- labels={issueLabels}
- selected={labels}
- required={forceIssueLabels}
- onChange={setLabels}
- />
- )}
- </div>
- </SheetBody>
- <SheetFooter>
- <Button variant="outline" onClick={onClose} disabled={submitting}>
- {t("common.cancel")}
- </Button>
- <Button disabled={!canSubmit} onClick={() => void handleSubmit()}>
- {t("common.submit")}
- </Button>
- </SheetFooter>
- </>
- );
-}
-
-export function RoleGrantPanel({
- projectName,
- databaseResources,
- role,
- requiredPermissions,
- onClose,
-}: Props) {
- return (
- <Sheet open={true} onOpenChange={(next) => !next && onClose()}>
- <SheetContent width="standard">
- <RoleGrantPanelInner
- key={projectName}
- stableProjectName={projectName}
- databaseResources={databaseResources}
- role={role}
- requiredPermissions={requiredPermissions}
- onClose={onClose}
- />
- </SheetContent>
- </Sheet>
- );
-}
diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
new file mode 100644
index 0000000000..47cd754a7b
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx
@@ -0,0 +1,284 @@
+import { ChevronLeft } from "lucide-react";
+import { useEffect, useState } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import {
+ Panel,
+ Group as PanelGroup,
+ Separator as PanelResizeHandle,
+} from "react-resizable-panels";
+import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
+import { IAMRemindDialog } from "@/react/components/IAMRemindDialog";
+import { Quickstart } from "@/react/components/Quickstart";
+import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";
+import { AsidePanel } from "@/react/components/sql-editor/AsidePanel";
+import { ConnectionPanel } from "@/react/components/sql-editor/ConnectionPanel";
+import { Panels } from "@/react/components/sql-editor/Panels/Panels";
+import { TabList } from "@/react/components/sql-editor/TabList";
+import {
+ getLayerRoot,
+ LAYER_BACKDROP_CLASS,
+ LAYER_SURFACE_CLASS,
+} from "@/react/components/ui/layer";
+import { useVueState } from "@/react/hooks/useVueState";
+import { cn } from "@/react/lib/utils";
+import { useNavigate } from "@/react/router";
+import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
+import {
+ useDatabaseV1Store,
+ useProjectV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+} from "@/store";
+import { unknownProject } from "@/types";
+import {
+ extractDatabaseResourceName,
+ extractProjectResourceName,
+} from "@/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
+
+/**
+ * React port of `frontend/src/views/sql-editor/SQLEditorHomePage.vue`.
+ *
+ * Top-level shell of the SQL Editor route:
+ * - desktop: a horizontal split between `<AsidePanel>` (workspace
+ * tree, etc.) and the main column (`<TabList>` + `<Panels>`).
+ * - mobile (window width < 800px): the aside collapses behind a
+ * floating chevron + drawer.
+ *
+ * Two emittery listeners survive from the Vue version:
+ * - `alter-schema` opens a new tab to the plan editor with a
+ * pre-filled `ALTER TABLE` statement.
+ * - `insert-at-caret` flips back to the CODE view and stages the
+ * content into `pendingInsertAtCaret`; the React `<SQLEditor>` reads
+ * that ref and inserts at the cursor.
+ *
+ * Vue stragglers (`Quickstart`, `IAMRemindModal`) mount via
+ * `<VueMount>` so the Stage 22 ports can stay deferred without
+ * blocking this stage. The Vue Router route entry lives in
+ * `router/sqlEditor.ts` as a tiny inline `defineComponent` whose
+ * sole job is to mount this React tree via `<ReactPageMount
+ * page="SQLEditorHomePage">` — no per-route `.vue` file remains.
+ */
+export function SQLEditorHomePage() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const databaseStore = useDatabaseV1Store();
+ const projectStore = useProjectV1Store();
+ const editorStore = useSQLEditorStore();
+
+ const projectContextReady = useVueState(
+ () => editorStore.projectContextReady
+ );
+ const project = useVueState(() => {
+ if (!editorStore.project) return undefined;
+ const proj = projectStore.getProjectByName(editorStore.project);
+ return proj.name === editorStore.project ? proj : undefined;
+ });
+ const tab = useVueState(() => tabStore.currentTab);
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+
+ const [windowWidth, setWindowWidth] = useState(() => window.innerWidth);
+ useEffect(() => {
+ const handler = () => setWindowWidth(window.innerWidth);
+ window.addEventListener("resize", handler);
+ return () => window.removeEventListener("resize", handler);
+ }, []);
+ const hideSidebar = windowWidth < 800;
+
+ const [sidebarSize, setSidebarSize] = useState(25);
+ const [sidebarExpanded, setSidebarExpanded] = useState(false);
+
+ // alter-schema: open a new tab to the plan editor with a pre-filled
+ // ALTER TABLE template (mirrors Vue's `useEmitteryEventListener`).
+ useEffect(() => {
+ const off = sqlEditorEvents.on(
+ "alter-schema",
+ async ({ databaseName, schema, table }) => {
+ const database =
+ await databaseStore.getOrFetchDatabaseByName(databaseName);
+ const project = await projectStore
+ .getOrFetchProjectByName(database.project)
+ .catch(() => unknownProject());
+ const exampleSQL = ["ALTER TABLE"];
+ if (table) {
+ if (schema) exampleSQL.push(`${schema}.${table}`);
+ else exampleSQL.push(`${table}`);
+ }
+ const { databaseName: dbName } = extractDatabaseResourceName(
+ database.name
+ );
+ const query: Record<string, string> = {
+ template: "bb.plan.change-database",
+ databaseList: database.name,
+ sql: exampleSQL.join(" "),
+ };
+ applyPlanTitleToQuery(
+ query,
+ project,
+ () => `[${dbName}] ${t("issue.title.edit-schema")}`
+ );
+ const route = navigate.resolve({
+ name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
+ params: {
+ projectId: extractProjectResourceName(database.project),
+ planId: "create",
+ specId: "placeholder",
+ },
+ query,
+ });
+ window.open(route.fullPath, "_blank");
+ }
+ );
+ return () => {
+ off();
+ };
+ }, [databaseStore, projectStore, navigate, t]);
+
+ // insert-at-caret: flip view to CODE, stage content into
+ // pendingInsertAtCaret. The React `<SQLEditor>` reads the same Pinia
+ // ref and inserts at the cursor.
+ useEffect(() => {
+ const off = sqlEditorEvents.on("insert-at-caret", ({ content }) => {
+ const t = tabStore.currentTab;
+ if (!t) return;
+ tabStore.updateTab(t.id, {
+ viewState: { ...(t.viewState ?? {}), view: "CODE" },
+ });
+ requestAnimationFrame(() => {
+ uiStore.pendingInsertAtCaret = content;
+ });
+ });
+ return () => {
+ off();
+ };
+ }, [tabStore, uiStore]);
+
+ const mobileToggle = hideSidebar
+ ? createPortal(
+ <button
+ type="button"
+ className={cn(
+ "fixed rounded-full border border-control-border shadow-lg w-10 h-10 bottom-16 flex items-center justify-center bg-white hover:bg-control-bg cursor-pointer transition-all",
+ LAYER_SURFACE_CLASS,
+ sidebarExpanded ? "left-[80%] -translate-x-5" : "left-4"
+ )}
+ style={{
+ transitionTimingFunction: "cubic-bezier(0.4, 0, 0.2, 1)",
+ transitionDuration: "300ms",
+ }}
+ onClick={() => setSidebarExpanded((prev) => !prev)}
+ aria-label={sidebarExpanded ? "Collapse sidebar" : "Expand sidebar"}
+ >
+ <ChevronLeft
+ className={cn(
+ "w-6 h-6 transition-transform",
+ !sidebarExpanded && "-scale-100"
+ )}
+ />
+ </button>,
+ getLayerRoot("overlay")
+ )
+ : null;
+
+ return (
+ <div className="sqleditor--wrapper w-full flex-1 overflow-hidden flex flex-col">
+ {mobileToggle}
+ {hideSidebar &&
+ sidebarExpanded &&
+ createPortal(
+ <>
+ <div
+ className={cn("fixed inset-0 bg-black/40", LAYER_BACKDROP_CLASS)}
+ onClick={() => setSidebarExpanded(false)}
+ />
+ <div
+ className={cn(
+ "fixed inset-y-0 left-0 h-full w-[80vw] bg-background shadow-lg",
+ LAYER_SURFACE_CLASS
+ )}
+ role="dialog"
+ aria-label="Sidebar"
+ >
+ <AsidePanel />
+ </div>
+ </>,
+ getLayerRoot("overlay")
+ )}
+ <PanelGroup orientation="horizontal" className="h-full">
+ {!hideSidebar && (
+ <>
+ <Panel
+ defaultSize={`${sidebarSize}%`}
+ minSize="10%"
+ maxSize="40%"
+ onResize={(size) => setSidebarSize(size.asPercentage)}
+ >
+ <div className="h-full">
+ <AsidePanel />
+ </div>
+ </Panel>
+ <PanelResizeHandle className={resizeHandleClass("vertical")} />
+ </>
+ )}
+ <Panel>
+ <div className="h-full relative flex flex-col">
+ <div className="w-full">
+ <TabList />
+ </div>
+ <div className="flex-1 min-h-0 flex">
+ <Panels />
+ </div>
+ </div>
+ </Panel>
+ </PanelGroup>
+
+ <Quickstart />
+ {projectContextReady && project && <IAMRemindDialog project={project} />}
+
+ <ConnectionPanel />
+
+ {/* Diagnostic teleport target — the Vue version reused
+ `#sql-editor-debug`. Skipped here; the legacy markers
+ (`isDisconnected`, `currentTab.id`, `currentTab.connection`)
+ are still inspectable via Vue devtools on the Pinia store. */}
+ <DebugProbe
+ isDisconnected={isDisconnected}
+ tabId={tab?.id}
+ connection={tab?.connection}
+ />
+ </div>
+ );
+}
+
+/**
+ * Renders the same `[Page]…` debug strings the Vue version teleported
+ * into `#sql-editor-debug`. The portal is no-op when that target isn't
+ * in the DOM (production builds), matching the legacy behavior.
+ */
+function DebugProbe({
+ isDisconnected,
+ tabId,
+ connection,
+}: {
+ isDisconnected: boolean;
+ tabId: string | undefined;
+ connection: unknown;
+}) {
+ const target =
+ typeof document !== "undefined"
+ ? document.querySelector("#sql-editor-debug")
+ : null;
+ if (!target) return null;
+ return createPortal(
+ <>
+ <li>[Page]isDisconnected: {String(isDisconnected)}</li>
+ <li>[Page]currentTab.id: {tabId ?? ""}</li>
+ <li>[Page]currentTab.connection: {JSON.stringify(connection ?? null)}</li>
+ </>,
+ target
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
new file mode 100644
index 0000000000..2f299c62e7
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SQLEditorLayout.tsx
@@ -0,0 +1,77 @@
+import { useEffect, useState } from "react";
+import { BannersWrapper } from "@/react/components/BannersWrapper";
+import { router } from "@/router";
+import {
+ useEnvironmentV1Store,
+ useSettingV1Store,
+ useSQLEditorWorksheetStore,
+} from "@/store";
+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";
+import { RequestDrawerHost } from "./RequestDrawerHost";
+import { SQLEditorRouteShell } from "./SQLEditorRouteShell";
+import { useSQLEditorAutoSave } from "./useSQLEditorAutoSave";
+
+/**
+ * React port of `frontend/src/layouts/SQLEditorLayout.vue`.
+ *
+ * Top-level shell of the SQL Editor route. Wires up:
+ * - the legacy `#sql-editor-debug` teleport target (kept hidden by
+ * default, used by debug `<li>` strings the inner shells emit).
+ * - the React `<BannersWrapper>` at the top.
+ * - workspace profile + environment fetch on mount, gated by Vue
+ * Router's `isReady()` so the SQL Editor doesn't bootstrap before
+ * initial route resolution.
+ * - `useSQLEditorAutoSave()` — the 2-second debounced worksheet
+ * auto-save extracted from the legacy `provideSQLEditorContext()`.
+ * - the `<SQLEditorRouteShell>` once `ready` flips true.
+ */
+export function SQLEditorLayout() {
+ const settingStore = useSettingV1Store();
+ const environmentStore = useEnvironmentV1Store();
+ // Mounting the worksheet store eagerly mirrors the legacy
+ // `provideSheetContext()` call — it boots the per-view watchers
+ // (selectedKeys ↔ active tab) the moment the layout appears.
+ useSQLEditorWorksheetStore();
+
+ const [ready, setReady] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ await router.isReady();
+ await Promise.all([
+ settingStore.getOrFetchSettingByName(
+ Setting_SettingName.WORKSPACE_PROFILE
+ ),
+ environmentStore.fetchEnvironments(),
+ ]);
+ if (!cancelled) setReady(true);
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [settingStore, environmentStore]);
+
+ useSQLEditorAutoSave();
+
+ return (
+ <div className="relative h-screen overflow-hidden flex flex-col">
+ {/* Hidden teleport target inherited from the Vue layout. The debug
+ probes (Pinia connection, current tab, etc.) write `<li>`
+ children into this list when manually unhidden via dev tools.
+ The fixed positioning is enough to stack above the editor body
+ on its own — the legacy `z-999999` was a layering escape hatch
+ that the React layering policy now forbids. */}
+ <ul
+ id="sql-editor-debug"
+ className="hidden text-xs font-mono max-h-[33vh] max-w-[40vw] overflow-auto fixed bottom-0 right-0 p-2 bg-white/50 border border-gray-400"
+ />
+ <BannersWrapper />
+ {ready && (
+ <RequestDrawerHost>
+ <SQLEditorRouteShell />
+ </RequestDrawerHost>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
new file mode 100644
index 0000000000..c79d6a757f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx
@@ -0,0 +1,528 @@
+import { debounce, head, omit } from "lodash-es";
+import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ PermissionDeniedFallback,
+ useComponentPermissionState,
+ usePermissionDataReady,
+} from "@/react/components/ComponentPermissionGuard";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useCurrentRoute, useNavigate } from "@/react/router";
+import { router } from "@/router";
+import {
+ SQL_EDITOR_DATABASE_MODULE,
+ SQL_EDITOR_HOME_MODULE,
+ SQL_EDITOR_INSTANCE_MODULE,
+ SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_WORKSHEET_MODULE,
+} from "@/router/sqlEditor";
+import {
+ type AsidePanelTab,
+ pushNotification,
+ useActuatorV1Store,
+ useDatabaseV1Store,
+ useProjectV1Store,
+ useSQLEditorStore,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+ useSQLEditorWorksheetStore,
+ useWorkSheetStore,
+} from "@/store";
+import { migrateLegacyCache } from "@/store/modules/sqlEditor/legacy/migration";
+import {
+ DEFAULT_SQL_EDITOR_TAB_MODE,
+ isValidDatabaseName,
+ isValidInstanceName,
+ isValidProjectName,
+} from "@/types";
+import {
+ emptySQLEditorConnection,
+ extractDatabaseResourceName,
+ extractInstanceResourceName,
+ extractProjectResourceName,
+ extractWorksheetConnection,
+ extractWorksheetID,
+ getDefaultPagination,
+ getSheetStatement,
+ isWorksheetReadableV1,
+ STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,
+ suggestedTabTitleForSQLEditorConnection,
+} from "@/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
+import { SQLEditorHomePage } from "./SQLEditorHomePage";
+
+// Route-name set for the unsaved-changes leave guard. Vue Router's
+// `beforeEach` is global, so this set scopes the prompt to navigations
+// that actually leave the SQL Editor — internal SQL Editor route sync
+// (`navigate.replace(...)` between worksheet/database/instance modules)
+// must not trigger it.
+const SQL_EDITOR_MODULES = new Set<string>([
+ SQL_EDITOR_HOME_MODULE,
+ SQL_EDITOR_PROJECT_MODULE,
+ SQL_EDITOR_INSTANCE_MODULE,
+ SQL_EDITOR_DATABASE_MODULE,
+ SQL_EDITOR_WORKSHEET_MODULE,
+]);
+
+const ASIDE_PANEL_TABS: readonly AsidePanelTab[] = [
+ "SCHEMA",
+ "WORKSHEET",
+ "HISTORY",
+ "ACCESS",
+];
+
+/**
+ * React port of `frontend/src/components/ProvideSQLEditorContext.vue`.
+ *
+ * Owns the SQL Editor route bootstrap chain:
+ * - on mount, resolves the active project from URL params/query and
+ * `editorStore.storedLastViewedProject`, falling back to the first
+ * accessible project, then sets up the per-project tab list.
+ * - hydrates the active tab from the URL: opens the worksheet for
+ * `/projects/:project/sheets/:sheet`, or opens an instance/database
+ * connection for the `instances/:instance/databases/:database` form.
+ * - keeps the URL synced with the active tab's connection (Pinia →
+ * `router.replace`), so reload restores the right surface.
+ * - restores the sidebar tab from localStorage (or the `?panel=`
+ * override) once `editorStore.projectContextReady` flips true.
+ * - mounts `<RoutePermissionGuardShell>` and portals the React
+ * `<SQLEditorHomePage>` into its target div once the user has
+ * permission for the matched route.
+ *
+ * The legacy Vue wrapper additionally rendered `<ProvideAIContext>`
+ * around `<router-view>`. That outer provide is unused after Stage 21
+ * — every consumer of `useAIContext()` lives inside the AI plugin tree,
+ * which mounts via the React→Vue bridge with its own
+ * `<AIChatToSQLBridgeHost>` re-establishing the provide locally. The
+ * `aiContextEvents` emitter is a module-level singleton accessible
+ * cross-framework.
+ */
+export function SQLEditorRouteShell() {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const route = useCurrentRoute();
+ const actuatorStore = useActuatorV1Store();
+ const projectStore = useProjectV1Store();
+ const databaseStore = useDatabaseV1Store();
+ const editorStore = useSQLEditorStore();
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const worksheetStore = useWorkSheetStore();
+ const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();
+
+ const projectContextReady = useVueState(
+ () => editorStore.projectContextReady
+ );
+ const project = useVueState(() => {
+ const proj = projectStore.getProjectByName(editorStore.project);
+ if (!isValidProjectName(proj.name)) return undefined;
+ return proj;
+ });
+
+ // ---- one-shot bootstrap on mount -------------------------------------
+
+ const bootstrappedRef = useRef(false);
+ // Gate the URL ⇄ connection sync until the bootstrap chain completes.
+ // The Vue version called `syncURLWithConnection()` *after* the chain;
+ // wiring it as a plain `useEffect` would otherwise fire on first
+ // render with empty Pinia values (no tab loaded yet), navigate the
+ // route to `SQL_EDITOR_HOME_MODULE`, and clobber the user's
+ // `/projects/.../databases/...` URL — which then remounts the whole
+ // React tree (route-shell `setTarget(null)` on `route.fullPath`
+ // change), blowing away the active tab and editor state. Result: Run
+ // button disabled because the current tab ends up empty/disconnected.
+ const [bootstrapDone, setBootstrapDone] = useState(false);
+ useEffect(() => {
+ if (bootstrappedRef.current) return;
+ bootstrappedRef.current = true;
+ void (async () => {
+ editorStore.projectContextReady = false;
+ const project = await initializeProject();
+ await migrateLegacyCache();
+ await tabStore.initProject(project);
+ await initializeConnectionFromQuery();
+ setBootstrapDone(true);
+ })();
+ }, []);
+
+ const fallbackToFirstProject = async () => {
+ const { projects } = await projectStore.fetchProjectList({
+ pageSize: getDefaultPagination(),
+ filter: { excludeDefault: true },
+ });
+ return (
+ head(projects)?.name ?? actuatorStore.serverInfo?.defaultProject ?? ""
+ );
+ };
+
+ const initializeProject = async () => {
+ const projectInQuery = route.query.project as string | undefined;
+ const projectInParams = route.params.project as string | undefined;
+ let project = "";
+
+ if (typeof projectInQuery === "string" && projectInQuery) {
+ project = `projects/${projectInQuery}`;
+ } else if (typeof projectInParams === "string" && projectInParams) {
+ project = `projects/${projectInParams}`;
+ } else {
+ project = editorStore.storedLastViewedProject;
+ }
+
+ let initializeSuccess =
+ !!(await sqlEditorWorksheetStore.maybeSwitchProject(project));
+ if (!initializeSuccess) {
+ project = await fallbackToFirstProject();
+ initializeSuccess =
+ !!(await sqlEditorWorksheetStore.maybeSwitchProject(project));
+ }
+ if (!initializeSuccess) {
+ editorStore.setProject("");
+ }
+ return editorStore.project;
+ };
+
+ const switchWorksheet = async (sheetName: string) => {
+ const openedSheetTab = tabStore.getTabByWorksheet(sheetName);
+ const sheet = await worksheetStore.getOrFetchWorksheetByName(sheetName);
+ if (!sheet) {
+ if (openedSheetTab) {
+ tabStore.updateTab(openedSheetTab.id, {
+ worksheet: "",
+ status: "DIRTY",
+ });
+ }
+ return false;
+ }
+ if (!isWorksheetReadableV1(sheet)) {
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: t("common.access-denied"),
+ });
+ return false;
+ }
+ const connection = await extractWorksheetConnection(sheet);
+ tabStore.addTab({
+ id: openedSheetTab?.id,
+ connection,
+ worksheet: sheet.name,
+ title: sheet.title,
+ statement: getSheetStatement(sheet),
+ status: "CLEAN",
+ });
+ return true;
+ };
+
+ const prepareSheet = async () => {
+ const projectId = route.params.project;
+ const sheetId = route.params.sheet;
+ if (typeof projectId !== "string" || !projectId) return false;
+ if (typeof sheetId !== "string" || !sheetId) return false;
+ await sqlEditorWorksheetStore.maybeSwitchProject(`projects/${projectId}`);
+ return await switchWorksheet(`projects/${projectId}/worksheets/${sheetId}`);
+ };
+
+ const prepareConnectionParams = async () => {
+ if (
+ ![SQL_EDITOR_INSTANCE_MODULE, SQL_EDITOR_DATABASE_MODULE].includes(
+ route.name as string
+ )
+ ) {
+ return false;
+ }
+ const databaseName = `instances/${route.params.instance}/databases/${route.params.database}`;
+ if (!isValidDatabaseName(databaseName)) return false;
+ const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
+ await sqlEditorWorksheetStore.maybeSwitchProject(database.project);
+ const { instance } = extractDatabaseResourceName(database.name);
+ const connection = { instance, database: database.name };
+ tabStore.addTab({
+ connection,
+ mode: DEFAULT_SQL_EDITOR_TAB_MODE,
+ title: suggestedTabTitleForSQLEditorConnection(connection),
+ });
+ return true;
+ };
+
+ const initializeConnectionFromQuery = async () => {
+ if (await prepareSheet()) return;
+ if (await prepareConnectionParams()) return;
+ };
+
+ // ---- URL ⇄ connection sync (reactive) --------------------------------
+
+ // Subscribe to each Pinia field; the effect below fires whenever any
+ // changes (mirrors Vue's `watch([...], ..., { immediate: true })`).
+ // The dependency array does the multi-source coalescing.
+ const projName = useVueState(() => editorStore.project);
+ const sheetName = useVueState(() => tabStore.currentTab?.worksheet);
+ const instanceName = useVueState(
+ () => tabStore.currentTab?.connection.instance
+ );
+ const dbName = useVueState(() => tabStore.currentTab?.connection.database);
+ const schema = useVueState(() => tabStore.currentTab?.connection.schema);
+ const table = useVueState(() => tabStore.currentTab?.connection.table);
+
+ useEffect(() => {
+ // Skip until bootstrap is done — see `bootstrapDone` declaration
+ // for why firing this on first render with empty Pinia values
+ // breaks the editor (rounds the URL to HOME, remounts the React
+ // tree, ends up with `currentTab` empty + Run button disabled).
+ if (!bootstrapDone) return;
+ void syncURL({
+ projName: projName ?? "",
+ sheetName: sheetName ?? undefined,
+ instanceName: instanceName ?? undefined,
+ dbName: dbName ?? undefined,
+ schema: schema ?? undefined,
+ table: table ?? undefined,
+ });
+ // The route navigation reads stores again at fire time, so capturing
+ // these as deps is sufficient — we don't need full closures over them.
+ }, [bootstrapDone, projName, sheetName, instanceName, dbName, schema, table]);
+
+ const syncURL = async (vals: {
+ projName: string;
+ sheetName: string | undefined;
+ instanceName: string | undefined;
+ dbName: string | undefined;
+ schema: string | undefined;
+ table: string | undefined;
+ }) => {
+ const currentRoute = router.currentRoute.value;
+ const query = omit(
+ currentRoute.query,
+ "filter",
+ "project",
+ "schema",
+ "database",
+ "panel"
+ ) as Record<string, string>;
+
+ // Touch the connection ref so the omit() above sees the live tab —
+ // identical to the Vue version's `connection.value` read at the top.
+ void (tabStore.currentTab?.connection ?? emptySQLEditorConnection());
+
+ if (vals.sheetName) {
+ const sheet = worksheetStore.getWorksheetByName(vals.sheetName);
+ if (sheet) {
+ await navigate.replace({
+ name: SQL_EDITOR_WORKSHEET_MODULE,
+ params: {
+ project: extractProjectResourceName(sheet.project),
+ sheet: extractWorksheetID(sheet.name),
+ },
+ query,
+ });
+ return;
+ } else {
+ const tab = tabStore.currentTab;
+ if (tab) {
+ tab.worksheet = "";
+ tab.status = "DIRTY";
+ }
+ }
+ }
+ if (vals.dbName && isValidDatabaseName(vals.dbName)) {
+ const database = await databaseStore.getOrFetchDatabaseByName(
+ vals.dbName
+ );
+ if (vals.schema) query.schema = vals.schema;
+ if (vals.table) {
+ query.table = vals.table;
+ query.schema = vals.schema ?? "";
+ }
+ const dbResource = extractDatabaseResourceName(database.name);
+ await navigate.replace({
+ name: SQL_EDITOR_DATABASE_MODULE,
+ params: {
+ project: extractProjectResourceName(database.project),
+ instance: extractInstanceResourceName(dbResource.instance),
+ database: dbResource.databaseName,
+ },
+ query,
+ });
+ return;
+ }
+ if (vals.instanceName && isValidInstanceName(vals.instanceName)) {
+ if (vals.table) {
+ query.table = vals.table;
+ query.schema = vals.schema ?? "";
+ }
+ await navigate.replace({
+ name: SQL_EDITOR_INSTANCE_MODULE,
+ params: {
+ project: extractProjectResourceName(editorStore.project),
+ instance: extractInstanceResourceName(vals.instanceName),
+ },
+ query,
+ });
+ return;
+ }
+ if (vals.projName && isValidProjectName(vals.projName)) {
+ await navigate.replace({
+ name: SQL_EDITOR_PROJECT_MODULE,
+ params: {
+ project: extractProjectResourceName(vals.projName),
+ },
+ query,
+ });
+ return;
+ }
+ await navigate.replace({ name: SQL_EDITOR_HOME_MODULE });
+ };
+
+ // ---- sidebar tab restore (after project context ready) ----------------
+
+ useEffect(() => {
+ const off = sqlEditorEvents.on("project-context-ready", ({ project }) => {
+ if (!project) return;
+ requestAnimationFrame(() => restoreLastVisitedSidebarTab());
+ });
+ return () => {
+ off();
+ };
+ }, []);
+
+ const sidebarRestoredRef = useRef(false);
+ const restoreLastVisitedSidebarTab = () => {
+ let stored: AsidePanelTab = "WORKSHEET";
+ try {
+ const raw = window.localStorage.getItem(
+ STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB
+ );
+ if (raw) {
+ const parsed = JSON.parse(raw);
+ if (
+ typeof parsed === "string" &&
+ ASIDE_PANEL_TABS.includes(parsed as AsidePanelTab)
+ ) {
+ stored = parsed as AsidePanelTab;
+ }
+ }
+ } catch {
+ // ignore — fall back to default
+ }
+
+ const panelQuery = router.currentRoute.value.query.panel;
+ if (typeof panelQuery === "string" && panelQuery) {
+ const tab = panelQuery.toUpperCase() as AsidePanelTab;
+ uiStore.asidePanelTab = ASIDE_PANEL_TABS.includes(tab) ? tab : stored;
+ } else {
+ uiStore.asidePanelTab = stored;
+ }
+ sidebarRestoredRef.current = true;
+ };
+
+ // Persist sidebar tab changes back to localStorage (debounced).
+ const asidePanelTab = useVueState(() => uiStore.asidePanelTab);
+ const persistSidebarRef = useRef(
+ debounce((tab: AsidePanelTab) => {
+ try {
+ window.localStorage.setItem(
+ STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,
+ JSON.stringify(tab)
+ );
+ } catch {
+ // ignore
+ }
+ }, 100)
+ );
+ useEffect(() => {
+ if (!sidebarRestoredRef.current) return;
+ persistSidebarRef.current(asidePanelTab);
+ }, [asidePanelTab]);
+
+ // ---- unsaved-tabs guard -----------------------------------------------
+
+ useEffect(() => {
+ const dirtyMsg = () =>
+ `${t("sql-editor.tab.unsaved-worksheet")} ${t("common.leave-without-saving")}`;
+ const handler = (e: BeforeUnloadEvent) => {
+ const dirty = tabStore.openTabList.find((tab) => tab.status !== "CLEAN");
+ if (!dirty) return;
+ e.returnValue = dirtyMsg();
+ return e.returnValue;
+ };
+ window.addEventListener("beforeunload", handler);
+ // `router.beforeEach` is a global hook — it fires on every Vue Router
+ // navigation while the SQL Editor shell is mounted, including the
+ // internal `navigate.replace(...)` calls used to sync the URL with
+ // the current connection. Without scoping, every internal route
+ // sync prompts the user when any tab is dirty, which is both an
+ // annoying loop and a regression vs. the prior component-level leave
+ // guard. Only prompt when the destination route is OUTSIDE the SQL
+ // Editor module.
+ const removeGuard = router.beforeEach((to, _from, next) => {
+ const stayingInSqlEditor = SQL_EDITOR_MODULES.has(to.name as string);
+ if (stayingInSqlEditor) {
+ next();
+ return;
+ }
+ const dirty = tabStore.openTabList.find((tab) => tab.status !== "CLEAN");
+ if (dirty && !window.confirm(dirtyMsg())) {
+ next(false);
+ return;
+ }
+ next();
+ });
+ return () => {
+ window.removeEventListener("beforeunload", handler);
+ removeGuard();
+ };
+ }, [tabStore, t]);
+
+ // ---- permission gate (children-style) --------------------------------
+
+ // Use the underlying permission hooks directly instead of the
+ // `RoutePermissionGuardShell` + `createPortal(target)` pattern. The
+ // shell-with-portal flow toggled `target` between `null` and the real
+ // DOM ref on every `route.fullPath` change (its internal `useEffect`
+ // chain calls `onReady(null)` then `onReady(targetRef.current)`),
+ // which **unmounted and remounted `<SQLEditorHomePage />` on every
+ // tab switch / connection change** — wiping React state in
+ // ResultPanel, Monaco editor, and the auto-run effect chain. That
+ // showed up as: tab switches blanking the whole page, the Run button
+ // staying disabled (re-mounted tab had empty `currentTab.statement`),
+ // and PENDING contexts never advancing because `<DatabaseQueryContext>`
+ // was unmounted before its auto-run `useEffect` fired.
+ //
+ // Rendering `<SQLEditorHomePage />` as a stable child of this branch
+ // keeps the React tree mounted across SQL Editor sub-route changes;
+ // only `useCurrentRoute()` refreshes inside it.
+ const permissions = route.requiredPermissions;
+ const permissionReady = usePermissionDataReady(project);
+ const { missedBasicPermissions, missedPermissions, permitted } =
+ useComponentPermissionState({
+ permissions,
+ project,
+ checkBasicWorkspacePermissions: true,
+ });
+
+ if (!projectContextReady || !permissionReady) {
+ return (
+ <div className="flex items-center justify-center h-screen">
+ <span className="text-control-light">…</span>
+ </div>
+ );
+ }
+
+ if (!permitted) {
+ return (
+ <PermissionDeniedFallback
+ missedBasicPermissions={missedBasicPermissions}
+ missedPermissions={missedPermissions}
+ project={project}
+ className="m-6"
+ path={route.fullPath}
+ enableRequestRole
+ />
+ );
+ }
+
+ return (
+ <div className="h-full min-h-0 flex flex-col">
+ <SQLEditorHomePage />
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx b/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx
index b20c41f1fd..79b8662bd1 100644
--- a/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx
+++ b/frontend/src/react/components/sql-editor/SchemaPane/hover-state.tsx
@@ -37,7 +37,7 @@ export type HoverStateContextValue = {
};
const DELAY_BEFORE = 1000;
-const DELAY_AFTER = 350;
+const DELAY_AFTER = 100;
const HoverStateContext = createContext<HoverStateContextValue | null>(null);
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
index eacb50f14f..dde0c480ee 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx
@@ -10,13 +10,13 @@ import {
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";
+import { activeStatementRef } from "./state";
interface EditorMainProps {
/** Open the connection drawer (hosted by SQLEditorHomePage). */
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
index ad628dddec..1d09b26817 100644
--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx
@@ -31,12 +31,9 @@ import {
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 { activeSQLEditorRef, activeStatementRef } from "./state";
import { UploadFileButton } from "./UploadFileButton";
const AI_ACTIONS: readonly ChatAction[] = [
diff --git a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
new file mode 100644
index 0000000000..03f4232939
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx
@@ -0,0 +1,135 @@
+import { Loader2 } from "lucide-react";
+import { Suspense } from "react";
+import {
+ Panel,
+ Group as PanelGroup,
+ Separator as PanelResizeHandle,
+} from "react-resizable-panels";
+import { AIChatToSQLBridgeHost } from "@/plugins/ai";
+import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";
+import { ResultPanel } from "@/react/components/sql-editor/ResultPanel/ResultPanel";
+import { VueMount } from "@/react/components/VueMount";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useConnectionOfCurrentSQLEditorTab,
+ useSQLEditorTabStore,
+ useSQLEditorUIStore,
+} from "@/store";
+import { instanceV1HasReadonlyMode } from "@/utils";
+import { EditorMain } from "./EditorMain";
+
+// Lazy-load EditorMain ↔ Pane callback to keep parity with Vue's
+// async-imported `AIChatToSQL`. The original `<Suspense>` fallback is
+// the matrix-style spinner; we mirror that with `<Loader2 />`.
+const AIPaneFallback = () => (
+ <div className="w-full h-full grow flex flex-col items-center justify-center">
+ <Loader2 className="size-6 animate-spin text-control-light" />
+ </div>
+);
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue`.
+ *
+ * Worksheet-mode editor host. Layout, ordered top-to-bottom:
+ * 1. Optional outer vertical split — editor / `<ResultPanel>`.
+ * Only rendered when the underlying instance supports read-only
+ * queries (mirrors the Vue `showResultPanel` gate that prevents
+ * the editor from being squeezed into an arbitrary top pane when
+ * the result pane wouldn't render anyway).
+ * 2. Inner horizontal split — `<EditorMain>` / `<AIChatToSQL>`.
+ * The AI side pane mounts via `<VueMount>` so the Stage 22
+ * AI-plugin port can stay deferred without blocking this stage.
+ *
+ * State source: `useSQLEditorTabStore` for tab + disconnect state,
+ * `useConnectionOfCurrentSQLEditorTab` for the current instance,
+ * `useSQLEditorUIStore` for AI-panel visibility / sizing. The Vue
+ * version reads the same Pinia stores via the `useSQLEditorContext`
+ * adapter, but the underlying state lives here.
+ */
+export function StandardPanel() {
+ const tabStore = useSQLEditorTabStore();
+ const uiStore = useSQLEditorUIStore();
+ const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();
+
+ const tab = useVueState(() => tabStore.currentTab);
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+ const showAIPanel = useVueState(() => uiStore.showAIPanel);
+ const editorPanelSize = useVueState(() => uiStore.editorPanelSize);
+ const instanceHasReadonly = useVueState(() =>
+ instanceV1HasReadonlyMode(instanceRef.value)
+ );
+
+ if (tab && tab.mode !== "WORKSHEET") {
+ return null;
+ }
+
+ const showResultPanel = !isDisconnected && instanceHasReadonly;
+
+ const handleAiPanelResize = (sizePct: number) => {
+ // react-resizable-panels reports a `PanelSize` struct
+ // ({ asPercentage, inPixels }) on resize. Pinia stores a 0-1
+ // fraction (`{size: 0.7, ...}`); convert and forward — the store's
+ // setter writes `1 - size` to localStorage.
+ if (!Number.isFinite(sizePct)) return;
+ uiStore.handleEditorPanelResize(sizePct / 100);
+ };
+
+ const handleChangeConnection = () => {
+ uiStore.asidePanelTab = "SCHEMA";
+ uiStore.showConnectionPanel = true;
+ };
+
+ const editorWithAi = (
+ <PanelGroup orientation="horizontal" className="h-full">
+ <Panel
+ defaultSize={`${editorPanelSize.size * 100}%`}
+ minSize={`${editorPanelSize.min * 100}%`}
+ maxSize={`${editorPanelSize.max * 100}%`}
+ onResize={(size) => {
+ // Only live-sync when the AI pane is visible. Without this
+ // guard, the resize fires on initial layout when AI is hidden
+ // and the editor occupies 100%, clobbering the persisted size.
+ if (showAIPanel) handleAiPanelResize(size.asPercentage);
+ }}
+ >
+ <EditorMain onChangeConnection={handleChangeConnection} />
+ </Panel>
+ {showAIPanel && tab && (
+ <>
+ <PanelResizeHandle className={resizeHandleClass("vertical")} />
+ <Panel
+ defaultSize={`${(1 - editorPanelSize.size) * 100}%`}
+ minSize="10%"
+ >
+ <div className="h-full overflow-hidden flex flex-col">
+ <Suspense fallback={<AIPaneFallback />}>
+ <VueMount
+ component={AIChatToSQLBridgeHost}
+ className="h-full"
+ />
+ </Suspense>
+ </div>
+ </Panel>
+ </>
+ )}
+ </PanelGroup>
+ );
+
+ if (!showResultPanel) {
+ return <div className="h-full">{editorWithAi}</div>;
+ }
+
+ return (
+ <PanelGroup orientation="vertical" className="h-full">
+ <Panel defaultSize="60%" minSize="20%" maxSize="80%">
+ {editorWithAi}
+ </Panel>
+ <PanelResizeHandle className={resizeHandleClass("horizontal")} />
+ <Panel defaultSize="40%" minSize="20%">
+ <div className="relative h-full">
+ <ResultPanel />
+ </div>
+ </Panel>
+ </PanelGroup>
+ );
+}
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts b/frontend/src/react/components/sql-editor/StandardPanel/state.ts
similarity index 59%
rename from frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts
rename to frontend/src/react/components/sql-editor/StandardPanel/state.ts
index 145eaf3759..687fd57c49 100644
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/state.ts
+++ b/frontend/src/react/components/sql-editor/StandardPanel/state.ts
@@ -6,8 +6,9 @@ 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).
+ * `SQLEditor` writes here via `onActiveContentChange`; the React
+ * `EditorMain` reads it when the toolbar's "Run" button is pressed
+ * (and Stage 22's still-Vue AI plugin can read it via the same Vue
+ * `shallowRef` since the bridge shares Vue's reactivity system).
*/
export const activeStatementRef = shallowRef<string>("");
diff --git a/frontend/src/react/components/sql-editor/StandardPanelPage.tsx b/frontend/src/react/components/sql-editor/StandardPanelPage.tsx
new file mode 100644
index 0000000000..bf4e1ce97f
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/StandardPanelPage.tsx
@@ -0,0 +1,10 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate `<StandardPanel>`
+ * via `mount.ts`'s `pageDirs` lookup (it scans for `<page>.tsx` files
+ * at the registered roots, not subdirectories).
+ *
+ * Vue caller mounts this with `<ReactPageMount page="StandardPanelPage">`.
+ * Removed when `EditorPanel.vue` flips to React in a later slice of
+ * Stage 21 and imports `StandardPanel` directly.
+ */
+export { StandardPanel as StandardPanelPage } from "./StandardPanel/StandardPanel";
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
index 82c7484faa..35d6367b55 100644
--- a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx
@@ -18,13 +18,13 @@ import { dialectOfEngineV1 } from "@/types";
import { Engine } from "@/types/proto-es/v1/common_pb";
import { languageOfEngineV1 } from "@/types/sqlEditor/editor";
import { instanceV1AllowsExplain } from "@/utils";
+import { sqlEditorEvents } from "@/views/sql-editor/events";
import {
checkCursorAtFirstLine,
checkCursorAtLast,
checkCursorAtLastLine,
checkIsEnterEndsStatement,
-} from "@/views/sql-editor/EditorPanel/TerminalPanel/utils";
-import { sqlEditorEvents } from "@/views/sql-editor/events";
+} from "./utils";
const MIN_EDITOR_HEIGHT = 40;
const MAX_EDITOR_HEIGHT = 360;
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx
new file mode 100644
index 0000000000..0a9f418ab8
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx
@@ -0,0 +1,257 @@
+import { Loader2 } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { watch } from "vue";
+import type { IStandaloneCodeEditor } from "@/components/MonacoEditor";
+import { ConnectionHolder } from "@/react/components/sql-editor/ConnectionHolder";
+import { EditorAction } from "@/react/components/sql-editor/EditorAction";
+import { ResultView } from "@/react/components/sql-editor/ResultView";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useDatabaseV1Store,
+ useSQLEditorTabStore,
+ useWebTerminalStore,
+} from "@/store";
+import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";
+import { CompactSQLEditor } from "./CompactSQLEditor";
+import { useHistory } from "./useHistory";
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue`.
+ *
+ * Hosts the admin-mode terminal: a top action bar, then a vertically
+ * scrolling stack of `<CompactSQLEditor>` + `<ResultView>` rows (one per
+ * historical query). Tail row is editable; older rows are read-only.
+ * When the underlying Pinia tab is disconnected we render
+ * `<ConnectionHolder>` instead (mirrors the Vue `v-if`).
+ *
+ * State source:
+ * - `webTerminalStore.getQueryStateByTab(currentTab).queryItemList` — the
+ * per-tab list of query items (statements + their result sets).
+ * - `useHistory()` — the up/down arrow command-history Pinia composable.
+ *
+ * Auto-scroll: a ResizeObserver on the inner stack scrolls the outer
+ * container to the bottom whenever the stack grows (replacing Vue's
+ * `useElementSize` + watch).
+ */
+export function TerminalPanel() {
+ const { t } = useTranslation();
+ const tabStore = useSQLEditorTabStore();
+ const webTerminalStore = useWebTerminalStore();
+ const databaseStore = useDatabaseV1Store();
+
+ const isDisconnected = useVueState(() => tabStore.isDisconnected);
+ const currentTabId = useVueState(() => tabStore.currentTab?.id);
+
+ // Force a React re-render on every mutation of the active tab's
+ // `queryItemList` (push, shift, per-item field flips). Watching the
+ // ref's `.value` keeps the watch alive even when no tab is loaded
+ // initially — re-arming on `currentTabId` change picks up the new
+ // tab's query list. A plain `useVueState` getter wouldn't work here
+ // because the store mutates the array in place, so the getter would
+ // keep returning the same reference and `useSyncExternalStore` would
+ // skip the re-render.
+ const [, forceRender] = useState(0);
+ useEffect(() => {
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ const qs = webTerminalStore.getQueryStateByTab(tab);
+ const stop = watch(
+ () => qs.queryItemList.value,
+ () => forceRender((v) => v + 1),
+ { deep: true, flush: "sync" }
+ );
+ return () => {
+ stop();
+ };
+ }, [tabStore, webTerminalStore, currentTabId]);
+
+ // Re-spread on every render so the JSX iteration sees the latest
+ // array. Items are still the same Vue reactive proxies; mutating
+ // `item.statement` etc. flows back to the store via Pinia. Operations
+ // that need to mutate the **list shape** (e.g. clear-screen
+ // `.shift()`) must reach the live `queryItemList.value` directly.
+ const queryList: WebTerminalQueryItemV1[] = (() => {
+ const tab = tabStore.currentTab;
+ if (!tab) return [];
+ const qs = webTerminalStore.getQueryStateByTab(tab);
+ return [...qs.queryItemList.value];
+ })();
+
+ const expired = useVueState(() => {
+ const tab = tabStore.currentTab;
+ if (!tab) return false;
+ const qs = webTerminalStore.getQueryStateByTab(tab);
+ return qs.timer.expired.value;
+ });
+
+ // Pre-fetch any database referenced by an existing query item so the
+ // ResultView can render `database.environment` etc. synchronously.
+ useEffect(() => {
+ void databaseStore.batchGetOrFetchDatabases(
+ queryList.map((q) => q?.params?.connection.database ?? "")
+ );
+ }, [queryList, databaseStore]);
+
+ const currentQuery = queryList[queryList.length - 1];
+ const isEditableQueryItem = (item: WebTerminalQueryItemV1) =>
+ item === currentQuery && item.status === "IDLE";
+
+ const { move: moveHistory } = useHistory();
+
+ const handleExecute = useCallback(
+ (params: SQLEditorQueryParams) => {
+ if (currentQuery?.status !== "IDLE") return;
+ if (!params.statement) {
+ console.warn("Empty query");
+ return;
+ }
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ const qs = webTerminalStore.getQueryStateByTab(tab);
+ void qs.controller.events.emit("query", params);
+ },
+ [currentQuery, tabStore, webTerminalStore]
+ );
+
+ const handleClearScreen = useCallback(() => {
+ // Mutate the live Vue array, not our shallow copy — the store's
+ // reactivity is tracked on the source and React re-renders via the
+ // tick-bumped `queryList` snapshot.
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ const list = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
+ while (list.length > 1) {
+ list.shift();
+ }
+ }, [tabStore, webTerminalStore]);
+
+ const handleHistory = useCallback(
+ (direction: "up" | "down", editor: IStandaloneCodeEditor) => {
+ if (currentQuery?.status !== "IDLE") return;
+ moveHistory(direction);
+ requestAnimationFrame(() => {
+ const model = editor.getModel();
+ if (!model) return;
+ const lineNumber = model.getLineCount();
+ const column = model.getLineMaxColumn(lineNumber);
+ editor.setPosition({ lineNumber, column });
+ });
+ },
+ [currentQuery, moveHistory]
+ );
+
+ const handleCancelQuery = () => {
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ webTerminalStore.getQueryStateByTab(tab).controller.abort();
+ };
+
+ // Auto-scroll the outer container to the bottom whenever the inner
+ // stack resizes. ResizeObserver replaces `@vueuse/core`'s
+ // `useElementSize` + `watch(queryListHeight, ...)`.
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const stackRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const stack = stackRef.current;
+ if (!stack) return;
+ const observer = new ResizeObserver(() => {
+ const container = containerRef.current;
+ if (container) {
+ requestAnimationFrame(() => {
+ container.scrollTo(0, container.scrollHeight);
+ });
+ }
+ });
+ observer.observe(stack);
+ return () => observer.disconnect();
+ // Re-bind when the active tab changes — the stack element may remount.
+ }, [currentTabId]);
+
+ // Build a stable handler list per-query for the editor onChange callback,
+ // since the editor inside `<CompactSQLEditor>` re-registers actions on
+ // identity change of these props.
+ const handleChangeFor = useMemo(
+ () =>
+ new Map(
+ queryList.map((q) => [
+ q.id,
+ (value: string) => {
+ q.statement = value;
+ },
+ ])
+ ),
+ [queryList]
+ );
+
+ return (
+ <div className="flex h-full w-full flex-col justify-start items-stretch overflow-hidden bg-dark-bg">
+ <EditorAction />
+ {!isDisconnected ? (
+ <div
+ ref={containerRef}
+ className="w-full flex-1 overflow-y-auto bg-dark-bg"
+ >
+ <div ref={stackRef} className="w-full flex flex-col">
+ {queryList.map((query) => {
+ const editable = isEditableQueryItem(query);
+ const database = query.params?.connection.database
+ ? databaseStore.getDatabaseByName(
+ query.params.connection.database
+ )
+ : undefined;
+ return (
+ <div key={query.id} className="relative">
+ <CompactSQLEditor
+ content={query.statement}
+ readonly={!editable}
+ onChange={handleChangeFor.get(query.id) ?? noop}
+ onExecute={handleExecute}
+ onHistory={handleHistory}
+ onClearScreen={handleClearScreen}
+ />
+ {query.params && query.resultSet && database && (
+ <div className="p-2 w-full flex-1 min-h-0">
+ <ResultView
+ executeParams={query.params}
+ resultSet={query.resultSet}
+ database={database}
+ loading={query.status === "RUNNING"}
+ dark
+ />
+ </div>
+ )}
+ {query.resultSet?.error && (
+ <div className="p-2 pb-1 text-md font-normal text-matrix-green-hover">
+ {t("sql-editor.connection-lost")}
+ </div>
+ )}
+ {query.status === "RUNNING" && (
+ <div className="absolute inset-0 bg-black/20 flex justify-center items-center gap-2">
+ <Loader2 className="size-5 animate-spin text-control-light" />
+ {query === currentQuery && expired && (
+ <button
+ type="button"
+ className="text-gray-400 cursor-pointer hover:underline text-sm select-none"
+ onClick={handleCancelQuery}
+ >
+ {t("common.cancel")}
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ ) : (
+ <div className="flex-1 flex flex-col min-h-0">
+ <ConnectionHolder />
+ </div>
+ )}
+ </div>
+ );
+}
+
+const noop = () => {};
diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
new file mode 100644
index 0000000000..3e4c1166c9
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts
@@ -0,0 +1,88 @@
+import { useEffect, useRef } from "react";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useSQLEditorTabStore, useWebTerminalStore } from "@/store";
+import type { WebTerminalQueryItemV1 } from "@/types";
+import { minmax } from "@/utils";
+
+const MAX_HISTORY_ITEM_COUNT = 1000;
+
+interface HistoryState {
+ index: number;
+ list: WebTerminalQueryItemV1[];
+}
+
+/**
+ * React port of `frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useHistory.ts`.
+ * Tracks an in-memory command history per ADMIN-mode tab so the up/down
+ * arrow keys cycle through previously executed statements (replacing the
+ * editor's current statement). Mirrors the Vue composable exactly:
+ * push on every new query item, move respecting bounds, clear current
+ * statement when stepping past the tail.
+ */
+export function useHistory() {
+ const tabStore = useSQLEditorTabStore();
+ const webTerminalStore = useWebTerminalStore();
+ const historyByTabIdRef = useRef(new Map<string, HistoryState>());
+
+ const currentQuery = useVueState((): WebTerminalQueryItemV1 | undefined => {
+ const tab = tabStore.currentTab;
+ if (!tab) return undefined;
+ const list = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
+ return list[list.length - 1];
+ });
+
+ const currentStack = (): HistoryState | undefined => {
+ const tab = tabStore.currentTab;
+ if (!tab) return undefined;
+ if (tab.mode !== "ADMIN") return undefined;
+ const map = historyByTabIdRef.current;
+ const existed = map.get(tab.id);
+ if (existed) return existed;
+ const initial: HistoryState = { index: -1, list: [] };
+ map.set(tab.id, initial);
+ return initial;
+ };
+
+ const push = (query: WebTerminalQueryItemV1) => {
+ const stack = currentStack();
+ if (!stack) return;
+ stack.list.push(query);
+ if (stack.list.length > MAX_HISTORY_ITEM_COUNT) {
+ stack.list.shift();
+ }
+ stack.index = stack.list.length - 1;
+ };
+
+ // Push the new query item onto the per-tab history whenever the tail
+ // changes. Mirrors Vue's `watch(currentQuery, push, { immediate: true })`.
+ // `push` reads through refs and store getters, so it doesn't need to be
+ // a dependency.
+ useEffect(() => {
+ if (currentQuery) push(currentQuery);
+ }, [currentQuery]);
+
+ const move = (direction: "up" | "down") => {
+ const stack = currentStack();
+ if (!stack) return;
+ const { index, list } = stack;
+ const delta = direction === "up" ? -1 : 1;
+ const nextIndex = minmax(index + delta, 0, list.length - 1);
+ if (nextIndex === index) return;
+
+ const tab = tabStore.currentTab;
+ if (!tab) return;
+ const head = webTerminalStore.getQueryStateByTab(tab).queryItemList.value;
+ const tail = head[head.length - 1];
+ if (!tail) return;
+
+ if (nextIndex === list.length - 1) {
+ tail.statement = "";
+ } else {
+ const historyQuery = list[nextIndex];
+ if (historyQuery) tail.statement = historyQuery.statement;
+ }
+ stack.index = nextIndex;
+ };
+
+ return { push, move };
+}
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/utils.ts b/frontend/src/react/components/sql-editor/TerminalPanel/utils.ts
similarity index 100%
rename from frontend/src/views/sql-editor/EditorPanel/TerminalPanel/utils.ts
rename to frontend/src/react/components/sql-editor/TerminalPanel/utils.ts
diff --git a/frontend/src/react/components/sql-editor/TerminalPanelPage.tsx b/frontend/src/react/components/sql-editor/TerminalPanelPage.tsx
new file mode 100644
index 0000000000..2ab47031d6
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/TerminalPanelPage.tsx
@@ -0,0 +1,10 @@
+/**
+ * Top-level page shim so `ReactPageMount` can locate `<TerminalPanel>`
+ * via `mount.ts`'s `pageDirs` lookup (it scans for `<page>.tsx` files at
+ * the registered roots, not subdirectories).
+ *
+ * Vue caller mounts this with `<ReactPageMount page="TerminalPanelPage">`.
+ * Removed when `EditorPanel.vue` flips to React in a later slice of
+ * Stage 21 and imports `TerminalPanel` directly.
+ */
+export { TerminalPanel as TerminalPanelPage } from "./TerminalPanel/TerminalPanel";
diff --git a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
new file mode 100644
index 0000000000..d227c8fdef
--- /dev/null
+++ b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts
@@ -0,0 +1,101 @@
+import { useEffect, useRef } from "react";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ pushNotification,
+ useSQLEditorTabStore,
+ useSQLEditorWorksheetStore,
+ useWorkSheetStore,
+} from "@/store";
+import { isWorksheetWritableV1 } from "@/utils";
+
+const AUTO_SAVE_DEBOUNCE_MS = 2000;
+
+/**
+ * React port of the auto-save block previously embedded in
+ * `views/sql-editor/context.ts`'s `provideSQLEditorContext()`.
+ *
+ * Watches the active tab's `statement` and after a 2s debounce calls
+ * `maybeUpdateWorksheet` if the tab is dirty + writable. Mirrors the
+ * Vue `watchDebounced` behavior: aborts any in-flight auto-save when a
+ * newer one starts, reverts the tab to DIRTY on error (unless aborted),
+ * and re-flags DIRTY when the statement keeps changing during the save.
+ *
+ * Mounted once at the SQL Editor layout level; safe to call from any
+ * component but should only be active while the SQL Editor route is.
+ */
+export function useSQLEditorAutoSave() {
+ const tabStore = useSQLEditorTabStore();
+ const worksheetStore = useWorkSheetStore();
+ const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();
+
+ const statement = useVueState(() => tabStore.currentTab?.statement);
+ const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(() => {
+ if (debounceTimerRef.current !== null) {
+ clearTimeout(debounceTimerRef.current);
+ }
+ debounceTimerRef.current = setTimeout(() => {
+ void runAutoSave();
+ }, AUTO_SAVE_DEBOUNCE_MS);
+ return () => {
+ if (debounceTimerRef.current !== null) {
+ clearTimeout(debounceTimerRef.current);
+ debounceTimerRef.current = null;
+ }
+ };
+ // We re-arm the debounce on every statement change. The save itself
+ // reads tab.statement from Pinia at fire time, so capturing only the
+ // change-trigger here is sufficient.
+ }, [statement]);
+
+ const runAutoSave = async () => {
+ const tab = tabStore.currentTab;
+ if (!tab || !tab.worksheet || tab.status === "CLEAN") return;
+
+ const worksheet = worksheetStore.getWorksheetByName(tab.worksheet);
+ if (!worksheet || !isWorksheetWritableV1(worksheet)) return;
+
+ sqlEditorWorksheetStore.abortAutoSave();
+
+ const statementToSave = tab.statement;
+ const tabId = tab.id;
+
+ const controller = new AbortController();
+ sqlEditorWorksheetStore.autoSaveController = controller;
+ tabStore.updateTab(tabId, { status: "SAVING" });
+
+ let wasAborted = false;
+ try {
+ await sqlEditorWorksheetStore.maybeUpdateWorksheet({
+ tabId,
+ worksheet: tab.worksheet,
+ database: tab.connection.database,
+ statement: statementToSave,
+ signal: controller.signal,
+ });
+ } catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ wasAborted = true;
+ return;
+ }
+ if (tabStore.getTabById(tabId)?.status === "SAVING") {
+ tabStore.updateTab(tabId, { status: "DIRTY" });
+ }
+ pushNotification({
+ module: "bytebase",
+ style: "CRITICAL",
+ title: "Auto-save failed",
+ description: error instanceof Error ? error.message : "Unknown error",
+ });
+ } finally {
+ sqlEditorWorksheetStore.autoSaveController = null;
+ if (!wasAborted) {
+ const currentStatement = tabStore.getTabById(tabId)?.statement;
+ if (currentStatement !== statementToSave) {
+ tabStore.updateTab(tabId, { status: "DIRTY" });
+ }
+ }
+ }
+ };
+}
diff --git a/frontend/src/react/hooks/useVueState.ts b/frontend/src/react/hooks/useVueState.ts
index 709c8a5ffe..4f5baabf66 100644
--- a/frontend/src/react/hooks/useVueState.ts
+++ b/frontend/src/react/hooks/useVueState.ts
@@ -1,75 +1,96 @@
-import { useCallback, useRef, useSyncExternalStore } from "react";
+import { useEffect, useRef, useState } from "react";
import { watch } from "vue";
export interface UseVueStateOptions {
/**
- * Track deep mutations of returned reactive objects.
+ * Force the watch to traverse nested reactive properties when
+ * registering deps. Default `false`.
*
- * Default `false` (shallow) — Vue's `watch` only fires when properties
- * read by the getter change reference. Pinia stores typically mutate
- * fields in place via `Object.assign(tab, payload)`, so a getter like
- * `() => [...tabStore.openTabList]` tracks the array + each item
- * reference but NOT each item's nested fields. Set `deep: true` for
- * collection getters where consumers care about field-level changes
- * (e.g. tab connection / status updates that don't reseat the tab
- * reference).
+ * Set this to `true` when the getter returns a reactive object/Map/
+ * Set whose **nested fields** mutate in place (e.g. a collection
+ * getter where consumers also read item fields). Without it, Vue's
+ * watch only tracks the top-level reactive accesses the getter made
+ * during evaluation.
+ *
+ * Note: this hook ALREADY surfaces in-place mutations of fields read
+ * by the getter — those reads register Vue deps individually, and a
+ * mutation to any of them triggers a re-render via the version
+ * counter even when the getter's *return reference* is unchanged.
+ * `deep: true` is only needed for collections whose contents the
+ * getter doesn't read directly.
*/
readonly deep?: boolean;
}
/**
* Subscribe a React component to a Vue reactive getter.
- * Re-renders whenever the getter's tracked dependencies change,
- * AND whenever the getter's closure variables (e.g. props) change.
*
- * @param getter — A function that reads Vue reactive state (Pinia store, ref, computed, etc.)
- * @param options — Optional `{ deep }` flag, see `UseVueStateOptions`.
- * @returns The current value of the getter, kept in sync with Vue reactivity.
+ * Re-renders whenever:
+ * 1. Vue's `watch` fires (any reactive dep accessed by the getter
+ * changed — including in-place field mutations of objects the
+ * getter reads), OR
+ * 2. The getter's closure variables (props, local state, etc.)
+ * change in a way that produces a different return value.
+ *
+ * Why a version counter rather than `useSyncExternalStore`'s snapshot
+ * compare: Pinia stores typically mutate proxy objects in place via
+ * `Object.assign(tab, payload)` or per-field writes. A getter that
+ * returns the proxy itself (e.g. `() => tabStore.currentTab`) keeps
+ * returning the same reference across mutations, and a snapshot
+ * comparison via `Object.is` would skip the re-render even though Vue
+ * detected a change. The version counter forces React to commit a new
+ * render whenever Vue's watch callback fires, regardless of the
+ * snapshot reference.
+ *
+ * @example
+ * // Reads a primitive — version bump and value change agree.
+ * const url = useVueState(() => actuatorStore.serverInfo?.externalUrl ?? "");
+ *
+ * @example
+ * // Reads a proxy object that mutates in place — the version bump
+ * // is what makes consumers see the new field values.
+ * const tab = useVueState(() => tabStore.currentTab);
+ * const isEmpty = !tab || tab.statement === "";
*
* @example
- * const externalUrl = useVueState(() => useActuatorV1Store().serverInfo?.externalUrl ?? "");
+ * // Deep-tracks nested collections the getter doesn't read directly.
+ * const queryList = useVueState(
+ * () => webTerminalStore.getQueryStateByTab(tab).queryItemList.value,
+ * { deep: true }
+ * );
*/
export function useVueState<T>(
getter: () => T,
options?: UseVueStateOptions
): T {
- // Cache the latest snapshot so getSnapshot returns a stable reference
- // between renders when the value hasn't changed.
- const snapshotRef = useRef<T>(getter());
-
- // Always point to the latest getter so the Vue watch evaluates
- // up-to-date closure variables (props, local state, etc.).
+ // Always read the latest getter from the closure (props, local state,
+ // etc. may have updated since mount).
const getterRef = useRef(getter);
getterRef.current = getter;
- // Capture `deep` once per mount; flipping it post-mount would require
- // tearing down + re-subscribing the watch and isn't a real use case.
+ // Pulling the deep flag through a ref keeps the watch wiring stable
+ // across re-renders. Flipping it post-mount isn't supported — that
+ // would require resubscribing.
const deepRef = useRef(!!options?.deep);
- const subscribe = useCallback((onStoreChange: () => void) => {
+ // Version bumps from the watch callback; React's `useState` setter
+ // triggers a re-render even when the underlying Pinia object's
+ // reference is unchanged (in-place mutation case).
+ const [, setVersion] = useState(0);
+
+ useEffect(() => {
const stop = watch(
() => getterRef.current(),
- (newVal) => {
- snapshotRef.current = newVal;
- onStoreChange();
- },
+ () => setVersion((v) => v + 1),
{ flush: "sync", deep: deepRef.current }
);
- // Initialize with current value
- snapshotRef.current = getterRef.current();
- return stop;
+ return () => {
+ stop();
+ };
}, []);
- // Re-evaluate getter on every render to catch closure-driven changes
- // (e.g. a prop like environmentName changing from "prod" to "test").
- // The Vue watch only fires for Vue reactive dep changes — it cannot
- // detect plain JS closure variable changes, so we sync here.
- const currentValue = getter();
- if (!Object.is(snapshotRef.current, currentValue)) {
- snapshotRef.current = currentValue;
- }
-
- const getSnapshot = useCallback(() => snapshotRef.current, []);
-
- return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ // Read the live value at render time. The watch above guarantees a
+ // re-render fires after every Vue mutation, so this read sees the
+ // freshly-mutated state on the next render.
+ return getter();
}
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 5459bc2a88..72ce1c1a3a 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -199,6 +199,7 @@
},
"common": {
"Default": "Default",
+ "access-denied": "Access denied",
"action-required": "Action Required",
"actions": "Actions",
"activated": "Activated",
@@ -723,6 +724,7 @@
"data-source.ssl.verify-certificate": "Verify TLS certificate",
"data-source.ssl.verify-certificate-tooltip": "Enable TLS certificate verification for secure connections. Disable only for development or when certificates cannot be properly validated (e.g., self-signed certs, VPN environments). Warning: Disabling verification is insecure",
"database": {
+ "access-denied": "You don't have the permission to access this database.",
"all": "All databases",
"change-database": "Change Database",
"checks": "Checks",
@@ -1471,6 +1473,7 @@
"title": {
"change-database": "Change database",
"change-from-sql-editor": "Change from SQL Editor",
+ "edit-schema": "Edit schema",
"request-role": "Request role",
"request-specific-role": "Request \"{{role}}\" role"
},
@@ -1862,7 +1865,19 @@
"quick-action.create-project": "Create project",
"quick-action.new-project": "New Project",
"quick-start": {
- "self": "Quick Start"
+ "guide": "click on the step to try it out",
+ "notice": {
+ "desc": "You can still bring it back later from the top right menu",
+ "title": "Quickstart guide dismissed"
+ },
+ "query-data": "Query data",
+ "self": "Quick Start",
+ "view-an-issue": "View an issue",
+ "visit-database": "Visit Databases",
+ "visit-environment": "Visit Environments",
+ "visit-instance": "Visit Instances",
+ "visit-member": "Visit Member | Members",
+ "visit-project": "Visit Projects"
},
"quick-start.self": "Quick Start",
"release": {
@@ -2646,6 +2661,7 @@
"description": "Batch query {{database}} additional databases and {{group}} database groups under {{project}}.",
"select-data-source": {
"admin": "Admin",
+ "not-match": "Data source mismatch, expect {{expect}} but got {{actual}}.",
"readonly": "Read-only",
"self": "Select data source for batch",
"tooltip": "Will find available data sources with restriction policy, then apply the selection."
@@ -2662,6 +2678,7 @@
"column-display-format": "Column Display Format",
"connect-in-admin-mode": "Connect in admin mode",
"connect-to-a-database": "Connect to database",
+ "connection-lost": "Connection lost. Will try to reconnect when executing next query.",
"copy-all-column-names": "Copy all column names",
"copy-name": "Copy name",
"copy-selected-results": "Copy selected data by <action></action> or <button></button>",
@@ -2671,6 +2688,8 @@
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
+ "execute-query": "Execute query",
+ "executing-query": "Executing query",
"expire-at": "Expire at {{time}}",
"expire-in": "Expire in {{time}}",
"expired": "Expired",
@@ -2705,6 +2724,7 @@
"no-queriable-database": "No queriable database",
"only-select-allowed": "Only read-only statements are allowed to execute.",
"open-in-new-tab": "Open in new tab",
+ "pending-query": "Pending query",
"preview-table-data": "Preview table data",
"previous-row": "Previous Row",
"private": "Private",
@@ -2765,7 +2785,8 @@
"multi-select": "Multi-select",
"rename": "Rename"
}
- }
+ },
+ "unsaved-worksheet": "You have unsaved worksheet."
},
"table-empty-placeholder": "Click Run to execute the query.",
"table-view": "Table view",
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index 5cdf29adc6..fc22edf5a9 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -198,6 +198,7 @@
},
"common": {
"Default": "Predeterminado",
+ "access-denied": "Acceso denegado",
"action-required": "Acción requerida",
"actions": "Acciones",
"activated": "Activado",
@@ -716,6 +717,7 @@
"data-source.ssl.verify-certificate": "Verificar certificado TLS",
"data-source.ssl.verify-certificate-tooltip": "Habilitar la verificación del certificado TLS para conexiones seguras. Deshabilitar solo para desarrollo o cuando los certificados no se pueden validar correctamente (por ejemplo, certificados autofirmados, entornos VPN). Advertencia: Deshabilitar la verificación es inseguro",
"database": {
+ "access-denied": "No tiene permiso para acceder a esta base de datos.",
"all": "Todas las bases de datos",
"change-database": "Modificar base de datos",
"checks": "Verificaciones",
@@ -1463,6 +1465,7 @@
"title": {
"change-database": "Modificar base de datos",
"change-from-sql-editor": "Modificar desde el editor SQL",
+ "edit-schema": "Editar esquema",
"request-role": "Solicitar rol",
"request-specific-role": "Solicitar rol \"{{role}}\""
},
@@ -1851,6 +1854,20 @@
},
"quick-action.create-project": "Create project",
"quick-action.new-project": "Nuevo Proyecto",
+ "quick-start": {
+ "guide": "haga clic en el paso para probarlo",
+ "notice": {
+ "desc": "Todavía puede volver a abrirla más tarde desde el menú en la parte superior derecha",
+ "title": "Guía de inicio rápido omitida"
+ },
+ "query-data": "Consultar datos",
+ "view-an-issue": "Ver una incidencia",
+ "visit-database": "Visitar Bases de datos",
+ "visit-environment": "Visitar Entornos",
+ "visit-instance": "Visitar Instancias",
+ "visit-member": "Visitar Miembro | Miembros",
+ "visit-project": "Visitar Proyectos"
+ },
"quick-start.self": "Quick Start",
"release": {
"and-n-more-files": "and {{count}} more files",
@@ -2632,6 +2649,7 @@
"description": "Consulta por lotes {{database}} bases de datos adicionales y {{group}} grupos de bases de datos bajo {{project}}.",
"select-data-source": {
"admin": "Administración",
+ "not-match": "La fuente de datos no coincide, se esperaba {{expect}} pero se obtuvo {{actual}}.",
"readonly": "Sólo lectura",
"self": "Seleccionar la fuente de datos para el lote",
"tooltip": "Encontrará fuentes de datos disponibles con política de restricción y luego aplicará la selección."
@@ -2648,6 +2666,7 @@
"column-display-format": "Formato de visualización de columna",
"connect-in-admin-mode": "Conectar en modo administrador",
"connect-to-a-database": "Conectar a base de datos",
+ "connection-lost": "Conexión perdida. \nIntentará volver a conectarse al ejecutar la siguiente consulta.",
"copy-all-column-names": "Copiar todos los nombres de las columnas",
"copy-name": "Copiar nombre",
"copy-selected-results": "Copiar datos seleccionados por <action></action> o <button></button>",
@@ -2657,6 +2676,8 @@
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
+ "execute-query": "Ejecutar consulta",
+ "executing-query": "Ejecutando consulta",
"expire-at": "Expire at {{time}}",
"expire-in": "Expire in {{time}}",
"expired": "Expired",
@@ -2691,6 +2712,7 @@
"no-queriable-database": "No hay base de datos consultable",
"only-select-allowed": "Solo se permiten ejecutar declaraciones de solo lectura.",
"open-in-new-tab": "Abrir en nueva pestaña",
+ "pending-query": "Consulta pendiente",
"preview-table-data": "Vista previa de datos de la tabla",
"previous-row": "Fila anterior",
"private": "Privado",
@@ -2751,7 +2773,8 @@
"multi-select": "Selección múltiple",
"rename": "Renombrar"
}
- }
+ },
+ "unsaved-worksheet": "Tiene una hoja de trabajo sin guardar."
},
"table-empty-placeholder": "Haga clic en Ejecutar para ejecutar la consulta.",
"table-view": "Vista de tabla",
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 57c19faa22..ebde265d18 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -198,6 +198,7 @@
},
"common": {
"Default": "デフォルト",
+ "access-denied": "アクセスが拒否されました",
"action-required": "対応が必要",
"actions": "アクション",
"activated": "有効化しました",
@@ -716,6 +717,7 @@
"data-source.ssl.verify-certificate": "TLS証明書を検証",
"data-source.ssl.verify-certificate-tooltip": "安全な接続のためにTLS証明書の検証を有効にします。開発環境や証明書が適切に検証できない場合(自己署名証明書、VPN環境など)にのみ無効にしてください。警告:検証を無効にすることは安全ではありません",
"database": {
+ "access-denied": "データベースにアクセスする権限がありません",
"all": "すべてのデータベース",
"change-database": "データベースの変更",
"checks": "チェック",
@@ -1463,6 +1465,7 @@
"title": {
"change-database": "データベースの変更",
"change-from-sql-editor": "SQL エディタからの変更",
+ "edit-schema": "スキーマを編集",
"request-role": "ロールをリクエスト",
"request-specific-role": "「{{role}}」ロールをリクエスト"
},
@@ -1851,6 +1854,20 @@
},
"quick-action.create-project": "Create project",
"quick-action.new-project": "作成するプロジェクト",
+ "quick-start": {
+ "guide": "クリックしてステップを試してみましょう",
+ "notice": {
+ "desc": "後から右上のメニューから元に戻すことができます",
+ "title": "クイックスタートガイドを終了しました"
+ },
+ "query-data": "クエリデータ",
+ "view-an-issue": "イシューを表示する",
+ "visit-database": "データベースにアクセスする",
+ "visit-environment": "環境にアクセスする",
+ "visit-instance": "インスタンスにアクセスする",
+ "visit-member": "メンバー | メンバーにアクセスする",
+ "visit-project": "プロジェクトにアクセスする"
+ },
"quick-start.self": "Quick Start",
"release": {
"and-n-more-files": "and {{count}} more files",
@@ -2632,6 +2649,7 @@
"description": "{{project}} の下の {{database}} 個の追加データベースと {{group}} 個のデータベース グループに対してバッチ クエリを実行します。",
"select-data-source": {
"admin": "管理者",
+ "not-match": "データ ソースが一致しません。{{expect}} を期待しましたが、{{actual}} を取得しました。",
"readonly": "読み取り専用",
"self": "バッチのデータソースを選択",
"tooltip": "制限ポリシーが設定された利用可能なデータ ソースを見つけて、選択を適用します。"
@@ -2648,6 +2666,7 @@
"column-display-format": "列の表示形式",
"connect-in-admin-mode": "管理者モードで接続する",
"connect-to-a-database": "データベースに接続",
+ "connection-lost": "接続切断。次回クエリが実行されるときに再接続が試行されます。",
"copy-all-column-names": "すべての列名をコピーします",
"copy-name": "名前をコピーする",
"copy-selected-results": "選択したデータを<action></action>または<button></button>でコピーします",
@@ -2657,6 +2676,8 @@
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
+ "execute-query": "クエリを実行する",
+ "executing-query": "クエリの実行",
"expire-at": "Expire at {{time}}",
"expire-in": "Expire in {{time}}",
"expired": "Expired",
@@ -2691,6 +2712,7 @@
"no-queriable-database": "クエリ可能なデータベースがありません",
"only-select-allowed": "読み取り専用ステートメントのみが実行を許可されます",
"open-in-new-tab": "新しいタブで開く",
+ "pending-query": "保留中のクエリ",
"preview-table-data": "テーブルデータのプレビュー",
"previous-row": "前の行",
"private": "プライベート",
@@ -2751,7 +2773,8 @@
"multi-select": "複数選択",
"rename": "名前の変更"
}
- }
+ },
+ "unsaved-worksheet": "保存されていないワークシートがあります。"
},
"table-empty-placeholder": "「実行」をクリックしてクエリを実行します。",
"table-view": "テーブルビュー",
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 33f3535461..eeccbe8947 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -198,6 +198,7 @@
},
"common": {
"Default": "Mặc định",
+ "access-denied": "Truy cập bị từ chối",
"action-required": "Cần thực hiện hành động",
"actions": "Hành động",
"activated": "Đã kích hoạt",
@@ -716,6 +717,7 @@
"data-source.ssl.verify-certificate": "Xác minh chứng chỉ TLS",
"data-source.ssl.verify-certificate-tooltip": "Bật xác minh chứng chỉ TLS để kết nối an toàn. Chỉ tắt cho môi trường phát triển hoặc khi không thể xác thực chứng chỉ đúng cách (ví dụ: chứng chỉ tự ký, môi trường VPN). Cảnh báo: Tắt xác minh là không an toàn",
"database": {
+ "access-denied": "Bạn không có quyền truy cập cơ sở dữ liệu này.",
"all": "Tất cả cơ sở dữ liệu",
"change-database": "Thay đổi cơ sở dữ liệu",
"checks": "Kiểm tra",
@@ -1463,6 +1465,7 @@
"title": {
"change-database": "Thay đổi cơ sở dữ liệu",
"change-from-sql-editor": "Thay đổi từ SQL Editor",
+ "edit-schema": "Chỉnh sửa schema",
"request-role": "Yêu cầu vai trò",
"request-specific-role": "Yêu cầu vai trò \"{{role}}\""
},
@@ -1851,6 +1854,20 @@
},
"quick-action.create-project": "Create project",
"quick-action.new-project": "Mới Dự án",
+ "quick-start": {
+ "guide": "nhấp vào bước để thử",
+ "notice": {
+ "desc": "Bạn vẫn có thể mang nó trở lại sau từ menu trên cùng bên phải",
+ "title": "Đã bỏ qua hướng dẫn bắt đầu nhanh"
+ },
+ "query-data": "Truy vấn dữ liệu",
+ "view-an-issue": "Xem một vấn đề",
+ "visit-database": "Truy cập Cơ sở dữ liệu",
+ "visit-environment": "Truy cập Môi trường",
+ "visit-instance": "Truy cập Phiên bản",
+ "visit-member": "Truy cập Thành viên | Thành viên",
+ "visit-project": "Truy cập Dự án"
+ },
"quick-start.self": "Quick Start",
"release": {
"and-n-more-files": "and {{count}} more files",
@@ -2632,6 +2649,7 @@
"description": "Truy vấn hàng loạt {{database}} cơ sở dữ liệu bổ sung và {{group}} nhóm cơ sở dữ liệu trong {{project}}.",
"select-data-source": {
"admin": "Quản trị viên",
+ "not-match": "Nguồn dữ liệu không khớp, mong đợi {{expect}} nhưng lại nhận được {{actual}}.",
"readonly": "Chỉ đọc",
"self": "Chọn nguồn dữ liệu cho lô",
"tooltip": "Sẽ tìm các nguồn dữ liệu có sẵn với chính sách hạn chế, sau đó áp dụng lựa chọn."
@@ -2648,6 +2666,7 @@
"column-display-format": "Định dạng hiển thị cột",
"connect-in-admin-mode": "Kết nối ở chế độ quản trị",
"connect-to-a-database": "Kết nối cơ sở dữ liệu",
+ "connection-lost": "Mất kết nối. Sẽ thử kết nối lại khi thực hiện truy vấn tiếp theo.",
"copy-all-column-names": "Sao chép tất cả tên cột",
"copy-name": "Sao chép tên",
"copy-selected-results": "Sao chép dữ liệu đã chọn bằng <action></action> hoặc <button></button>",
@@ -2657,6 +2676,8 @@
"duration-day": "{{days}} day",
"duration-days": "{{days}} days",
"duration-hours": "{{hours}} hour | {{hours}} hours",
+ "execute-query": "Thực hiện truy vấn",
+ "executing-query": "Đang thực hiện truy vấn",
"expire-at": "Expire at {{time}}",
"expire-in": "Expire in {{time}}",
"expired": "Expired",
@@ -2691,6 +2712,7 @@
"no-queriable-database": "Không có cơ sở dữ liệu có thể truy vấn",
"only-select-allowed": "Chỉ cho phép thực thi câu lệnh chỉ đọc.",
"open-in-new-tab": "Mở trong tab mới",
+ "pending-query": "Đang chờ truy vấn",
"preview-table-data": "Xem trước dữ liệu bảng",
"previous-row": "Dòng trước",
"private": "Riêng tư",
@@ -2751,7 +2773,8 @@
"multi-select": "Chọn nhiều",
"rename": "Đổi tên"
}
- }
+ },
+ "unsaved-worksheet": "Bạn có bảng tính chưa lưu."
},
"table-empty-placeholder": "Nhấp vào Chạy để thực hiện truy vấn.",
"table-view": "Chế độ xem bảng",
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 9f3ff7b4fa..2d0b33920c 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -198,6 +198,7 @@
},
"common": {
"Default": "默认",
+ "access-denied": "拒绝访问",
"action-required": "需要操作",
"actions": "操作",
"activated": "已激活",
@@ -716,6 +717,7 @@
"data-source.ssl.verify-certificate": "验证 TLS 证书",
"data-source.ssl.verify-certificate-tooltip": "启用 TLS 证书验证以确保安全连接。仅在开发环境或证书无法正确验证的情况下禁用(例如自签名证书、VPN 环境)。警告:禁用验证是不安全的",
"database": {
+ "access-denied": "您无权访问该数据库",
"all": "所有数据库",
"change-database": "变更数据库",
"checks": "Check 约束",
@@ -1463,6 +1465,7 @@
"title": {
"change-database": "变更数据库",
"change-from-sql-editor": "从 SQL 编辑器变更",
+ "edit-schema": "编辑 Schema",
"request-role": "申请角色",
"request-specific-role": "申请 \"{{role}}\" 角色"
},
@@ -1851,6 +1854,20 @@
},
"quick-action.create-project": "Create project",
"quick-action.new-project": "创建项目",
+ "quick-start": {
+ "guide": "可点击步骤进行尝试",
+ "notice": {
+ "desc": "您稍后仍可以从右上角的菜单中再次打开新手任务",
+ "title": "新手任务已关闭"
+ },
+ "query-data": "查询数据",
+ "view-an-issue": "查看工单",
+ "visit-database": "访问数据库",
+ "visit-environment": "访问环境",
+ "visit-instance": "访问实例",
+ "visit-member": "访问成员 | 成员",
+ "visit-project": "访问项目"
+ },
"quick-start.self": "Quick Start",
"release": {
"and-n-more-files": "以及另外 {{count}} 个文件",
@@ -2632,6 +2649,7 @@
"description": "批量查询 {{project}} 下的 {{database}} 个数据库和 {{group}} 个数据库组。",
"select-data-source": {
"admin": "主数据源",
+ "not-match": "数据源不匹配,预期为 {{expect}},但实际使用 {{actual}}。",
"readonly": "只读数据源",
"self": "选择批量查询使用的数据源",
"tooltip": "将先根据限制策略寻找数据源,然后应用该选择。"
@@ -2648,6 +2666,7 @@
"column-display-format": "列显示格式",
"connect-in-admin-mode": "以管理员模式连接",
"connect-to-a-database": "连接数据库",
+ "connection-lost": "连接丢失。下一次执行查询时将尝试重新连接。",
"copy-all-column-names": "复制所有列名",
"copy-name": "复制名称",
"copy-selected-results": "通过 <action></action> 或 <button></button> 来快速复制选定的数据",
@@ -2657,6 +2676,8 @@
"duration-day": "{{days}} 天",
"duration-days": "{{days}} 天",
"duration-hours": "{{hours}} 小时",
+ "execute-query": "执行查询",
+ "executing-query": "执行查询",
"expire-at": "{{time}} 过期",
"expire-in": "{{time}} 后过期",
"expired": "已过期",
@@ -2691,6 +2712,7 @@
"no-queriable-database": "没有可查询的数据库",
"only-select-allowed": "只允许执行只读语句",
"open-in-new-tab": "在新选项卡中打开",
+ "pending-query": "待处理查询",
"preview-table-data": "预览表数据",
"previous-row": "上一行",
"private": "私有",
@@ -2751,7 +2773,8 @@
"multi-select": "多选",
"rename": "重命名"
}
- }
+ },
+ "unsaved-worksheet": "您有未保存的工作表。"
},
"table-empty-placeholder": "点击 \"运行\" 执行查询",
"table-view": "表格视图",
diff --git a/frontend/src/react/pages/settings/RequestRoleSheet.tsx b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
index 21406196de..3814ae54ce 100644
--- a/frontend/src/react/pages/settings/RequestRoleSheet.tsx
+++ b/frontend/src/react/pages/settings/RequestRoleSheet.tsx
@@ -78,10 +78,27 @@ export interface RequestRoleSheetProps {
open: boolean;
project: Project;
requiredPermissions?: Permission[];
+ /**
+ * Pre-fill the role select. Useful when the sheet is opened from a
+ * surface that already knows which role the user needs (e.g. the SQL
+ * Editor's "Request query" button hard-codes
+ * `PresetRoleType.SQL_EDITOR_USER`). The user can still change the
+ * role from the picker — pass `requiredPermissions` to constrain the
+ * available roles instead of hard-locking the selection.
+ */
+ initialRole?: string;
+ /**
+ * Pre-fill the SELECT-mode database scope. When provided AND the
+ * pre-selected role requires a database scope, the sheet opens in
+ * SELECT mode with these resources already chosen. The user can
+ * switch to ALL or EXPRESSION mode if they want to broaden the scope.
+ */
+ initialDatabaseResources?: DatabaseResource[];
onClose: () => void;
}
const EMPTY_REQUIRED_PERMISSIONS: Permission[] = [];
+const EMPTY_DATABASE_RESOURCES: DatabaseResource[] = [];
// i18n key lookup for the three DatabaseMode radio labels. Kept as a flat
// function to avoid nested ternaries in the render tree.
@@ -114,6 +131,8 @@ export function RequestRoleSheet(props: Readonly<RequestRoleSheetProps>) {
function RequestRoleForm({
project,
requiredPermissions = EMPTY_REQUIRED_PERMISSIONS,
+ initialRole = "",
+ initialDatabaseResources = EMPTY_DATABASE_RESOURCES,
onClose,
}: Readonly<Omit<RequestRoleSheetProps, "open">>) {
const { t } = useTranslation();
@@ -124,18 +143,23 @@ function RequestRoleForm({
// getter produces identical reactive semantics.
const currentUserRef = useCurrentUserV1();
const currentUser = useVueState(() => currentUserRef.value);
- const [role, setRole] = useState("");
+ const [role, setRole] = useState(initialRole);
const [reason, setReason] = useState("");
const [expirationTimestamp, setExpirationTimestamp] = useState<
string | undefined
>(undefined);
const [labels, setLabels] = useState<string[]>([]);
// Role-scope fields — only rendered for roles that require them, but kept
- // in state so switching roles back and forth preserves user input.
- const [databaseMode, setDatabaseMode] = useState<DatabaseMode>("ALL");
+ // in state so switching roles back and forth preserves user input. When
+ // the caller pre-fills database resources we open in SELECT mode so the
+ // pre-filled scope is visible (otherwise the radio would default to ALL
+ // and the resources would be ignored).
+ const [databaseMode, setDatabaseMode] = useState<DatabaseMode>(
+ initialDatabaseResources.length > 0 ? "SELECT" : "ALL"
+ );
const [databaseResources, setDatabaseResources] = useState<
DatabaseResource[]
- >([]);
+ >(initialDatabaseResources);
// CEL expression for EXPRESSION mode is held as a structured group so it
// can render in ExprEditor (matching the old Vue DatabaseResourceForm).
const [exprGroup, setExprGroup] = useState<ConditionGroupExpr>(() =>
diff --git a/frontend/src/router/sqlEditor.ts b/frontend/src/router/sqlEditor.ts
index fda91d1e2a..108fa323b2 100644
--- a/frontend/src/router/sqlEditor.ts
+++ b/frontend/src/router/sqlEditor.ts
@@ -1,6 +1,7 @@
+import { defineComponent, h } from "vue";
import type { RouteRecordRaw } from "vue-router";
-import SQLEditorLayout from "@/layouts/SQLEditorLayout.vue";
import { t } from "@/plugins/i18n";
+import ReactPageMount from "@/react/ReactPageMount.vue";
export const SQL_EDITOR_HOME_MODULE = "sql-editor.home";
export const SQL_EDITOR_PROJECT_MODULE = "sql-editor.project";
@@ -8,11 +9,36 @@ export const SQL_EDITOR_INSTANCE_MODULE = "sql-editor.instance";
export const SQL_EDITOR_DATABASE_MODULE = "sql-editor.database";
export const SQL_EDITOR_WORKSHEET_MODULE = "sql-editor.worksheet";
+// Parent route component: a one-line Vue render-only shell that mounts
+// the React `SQLEditorLayout` tree. The full layout (debug teleport
+// target, banners wrapper, route shell, home page, AI bridge, etc.)
+// lives React-side; this shim exists only because Vue Router still
+// owns the route entry. Migrating the route itself to React Router is
+// out of scope per Stage 21 design § 4.8 option A.
+const SQLEditorLayoutComponent = defineComponent({
+ name: "SQLEditorLayoutRoute",
+ render: () =>
+ h(ReactPageMount, {
+ page: "SQLEditorLayout",
+ containerClass: "w-full h-full flex flex-col",
+ }),
+});
+
+// Child routes don't render anything of their own — the React layout
+// inspects `useCurrentRoute()` and decides what to show. We only need
+// each child to exist so `router.push({ name: SQL_EDITOR_*_MODULE })`
+// resolves to a valid path. Vue Router requires a `component` field;
+// rendering nothing is the closest match to "no body".
+const NoopRouteComponent = defineComponent({
+ name: "SQLEditorChildRoute",
+ render: () => null,
+});
+
const sqlEditorRoutes: RouteRecordRaw[] = [
{
path: "/sql-editor",
name: "sql-editor",
- component: SQLEditorLayout,
+ component: SQLEditorLayoutComponent,
meta: {
requiredPermissionList: () => [
"bb.projects.get",
@@ -25,31 +51,31 @@ const sqlEditorRoutes: RouteRecordRaw[] = [
path: "",
name: SQL_EDITOR_HOME_MODULE,
meta: { title: () => t("sql-editor.self") },
- component: () => import("../views/sql-editor/SQLEditorPage.vue"),
+ component: NoopRouteComponent,
},
{
path: "projects/:project",
name: SQL_EDITOR_PROJECT_MODULE,
meta: { title: () => t("sql-editor.self") },
- component: () => import("../views/sql-editor/SQLEditorPage.vue"),
+ component: NoopRouteComponent,
},
{
path: "projects/:project/instances/:instance/databases/:database",
name: SQL_EDITOR_DATABASE_MODULE,
meta: { title: () => t("sql-editor.self") },
- component: () => import("../views/sql-editor/SQLEditorPage.vue"),
+ component: NoopRouteComponent,
},
{
path: "projects/:project/instances/:instance",
name: SQL_EDITOR_INSTANCE_MODULE,
meta: { title: () => t("sql-editor.self") },
- component: () => import("../views/sql-editor/SQLEditorPage.vue"),
+ component: NoopRouteComponent,
},
{
path: "projects/:project/sheets/:sheet",
name: SQL_EDITOR_WORKSHEET_MODULE,
meta: { title: () => t("sql-editor.self") },
- component: () => import("../views/sql-editor/SQLEditorPage.vue"),
+ component: NoopRouteComponent,
},
],
},
diff --git a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue b/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
deleted file mode 100644
index 1b611d5385..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/EditorPanel.vue
+++ /dev/null
@@ -1,35 +0,0 @@
-<template>
- <div class="w-full flex-1 flex flex-row items-stretch overflow-hidden">
- <Panels>
- <template #code-panel>
- <StandardPanel
- v-if="!currentTab || currentTab.mode === 'WORKSHEET'"
- :key="`standard-${currentTab?.id || 'default'}`"
- />
-
- <TerminalPanel
- v-else-if="currentTab.mode === 'ADMIN'"
- :key="`terminal-${currentTab?.id || 'default'}`"
- />
-
- <NoPermissionPlaceholder
- v-else
- :key="`no-permission-${currentTab?.id || 'default'}`"
- :description="$t('database.access-denied')"
- />
- </template>
- </Panels>
- </div>
-</template>
-
-<script setup lang="ts">
-import { storeToRefs } from "pinia";
-import NoPermissionPlaceholder from "@/components/Permission/NoPermissionPlaceholder.vue";
-import { useSQLEditorTabStore } from "@/store";
-import Panels from "./Panels";
-import StandardPanel from "./StandardPanel";
-import TerminalPanel from "./TerminalPanel";
-
-const tabStore = useSQLEditorTabStore();
-const { currentTab } = storeToRefs(tabStore);
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
deleted file mode 100644
index 73d2388a6d..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/Panels.vue
+++ /dev/null
@@ -1,205 +0,0 @@
-<template>
- <div class="flex-1 flex items-stretch overflow-hidden">
- <div class="flex-1 overflow-y-hidden overflow-x-auto" :class="contentClass">
- <slot v-if="!viewState || viewState.view === 'CODE'" name="code-panel" />
-
- <template v-if="viewState && viewState.view !== 'CODE'">
- <div class="h-full flex flex-col">
- <div
- class="py-2 px-2 w-full flex flex-row gap-x-2 justify-between items-center"
- >
- <div class="flex items-center justify-start gap-2">
- <ReactPageMount page="DatabaseChooser" :disabled="true" />
- <ReactPageMount
- page="SchemaSelectToolbar"
- container-class="w-fit"
- />
- </div>
- </div>
- <NSplit
- class="flex-1"
- :disabled="!showAIPaneAlongsidePanel"
- :size="
- showAIPaneAlongsidePanel ? editorPanelSize.size : 1
- "
- :min="showAIPaneAlongsidePanel ? editorPanelSize.min : 1"
- :max="showAIPaneAlongsidePanel ? editorPanelSize.max : 1"
- :resize-trigger-size="3"
- @update:size="handleEditorPanelResize"
- >
- <template #1>
- <ReactPageMount
- v-if="viewState.view === 'INFO'"
- :key="`info-${tab?.id}`"
- page="InfoPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'TABLES'"
- :key="`tables-${tab?.id}`"
- page="TablesPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'VIEWS'"
- :key="`views-${tab?.id}`"
- page="ViewsPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'FUNCTIONS'"
- :key="`functions-${tab?.id}`"
- page="FunctionsPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'PROCEDURES'"
- :key="`procedures-${tab?.id}`"
- page="ProceduresPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'SEQUENCES'"
- :key="`sequences-${tab?.id}`"
- page="SequencesPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'PACKAGES'"
- :key="`packages-${tab?.id}`"
- page="PackagesPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'TRIGGERS'"
- :key="`triggers-${tab?.id}`"
- page="TriggersPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'EXTERNAL_TABLES'"
- :key="`external-tables-${tab?.id}`"
- page="ExternalTablesPanel"
- />
- <ReactPageMount
- v-if="viewState.view === 'DIAGRAM'"
- :key="`diagram-${tab?.id}`"
- page="DiagramPanel"
- />
- </template>
- <template v-if="showAIPaneAlongsidePanel" #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>
- </div>
- </template>
- </div>
- </div>
-</template>
-
-<script setup lang="ts">
-import { computedAsync } from "@vueuse/core";
-import { first } from "lodash-es";
-import { NSplit } from "naive-ui";
-import { storeToRefs } from "pinia";
-import { computed, watch } from "vue";
-import { BBSpin } from "@/bbkit";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import { AIChatToSQL } from "@/plugins/ai";
-import { useAIContext } from "@/plugins/ai/logic";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useDatabaseV1Store,
- useDBSchemaV1Store,
- useSQLEditorTabStore,
- useSQLEditorUIStore,
-} from "@/store";
-import { isValidDatabaseName } from "@/types";
-import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";
-import {
- extractDatabaseResourceName,
- getInstanceResource,
- nextAnimationFrame,
- type VueClass,
-} from "@/utils";
-import { useCurrentTabViewStateContext } from "../context/viewState.tsx";
-
-defineProps<{
- contentClass?: VueClass;
-}>();
-
-const { currentTab: tab } = storeToRefs(useSQLEditorTabStore());
-const { viewState, selectedSchemaName, updateViewState } =
- useCurrentTabViewStateContext();
-const { database } = useConnectionOfCurrentSQLEditorTab();
-const { execute } = useExecuteSQL();
-const { events: AIEvents } = useAIContext();
-
-// AI pane host: when a CodeViewer-style React surface is mounted under
-// this panel (`isShowingCode`), and the user has toggled the AI panel
-// open (`showAIPanel`), render `AIChatToSQL` to the right via NSplit.
-// This mirrors the Vue `CodeViewer`'s NSplit but hoists the host one
-// level up so React panels don't need to embed the Vue chat panel.
-const uiStore = useSQLEditorUIStore();
-const { showAIPanel, isShowingCode, editorPanelSize } = storeToRefs(uiStore);
-const handleEditorPanelResize = uiStore.handleEditorPanelResize;
-const showAIPaneAlongsidePanel = computed(
- () => showAIPanel.value && isShowingCode.value
-);
-const databaseMetadata = computedAsync(() => {
- if (!isValidDatabaseName(database.value.name)) {
- return undefined;
- }
- return useDBSchemaV1Store().getOrFetchDatabaseMetadata({
- database: database.value.name,
- silent: true,
- });
-});
-
-watch(
- [() => tab.value?.id, databaseMetadata, selectedSchemaName],
- ([id, database, schema]: [
- string | undefined,
- DatabaseMetadata | undefined,
- string | undefined,
- ]) => {
- if (!id) return;
- if (!database) return;
- if (
- !isValidDatabaseName(extractDatabaseResourceName(database.name).database)
- ) {
- return;
- }
- if (!schema || database.schemas.findIndex((s) => s.name === schema) < 0) {
- selectedSchemaName.value = first(database.schemas)?.name;
- }
- },
- { immediate: true, flush: "post" }
-);
-
-useEmitteryEventListener(AIEvents, "run-statement", async ({ statement }) => {
- if (!tab.value) {
- return;
- }
- updateViewState({
- view: "CODE",
- });
- await nextAnimationFrame();
- const connection = tab.value.connection;
- const database = await useDatabaseV1Store().getOrFetchDatabaseByName(
- connection.database
- );
- execute({
- connection,
- statement,
- engine: getInstanceResource(database).engine,
- explain: false,
- selection: tab.value.editorState.selection,
- });
-});
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/index.ts b/frontend/src/views/sql-editor/EditorPanel/Panels/index.ts
deleted file mode 100644
index 00c2ad4552..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/Panels/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import Panels from "./Panels.vue";
-
-export default Panels;
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue
deleted file mode 100644
index 35d6657327..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/DatabaseQueryContext.vue
+++ /dev/null
@@ -1,127 +0,0 @@
-<template>
- <template v-if="context.status === 'EXECUTING'">
- <div
- class="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80"
- >
- <div class="flex items-center gap-x-1">
- <BBSpin :size="20" class="mr-1" />
- <span>{{ $t("sql-editor.executing-query") }}</span>
- <span>-</span>
- <!-- use mono font to prevent the UI jitters frequently -->
- <span class="font-mono">{{ queryElapsedTime }}</span>
- </div>
- <div>
- <NButton size="small" @click="cancelQuery">
- {{ $t("common.cancel") }}
- </NButton>
- </div>
- </div>
- </template>
- <template v-else-if="context.status === 'CANCELLED'">
- <div
- class="w-full h-full flex flex-col justify-center items-center text-sm gap-y-1 bg-white/80 dark:bg-black/80"
- >
- <NButton size="small" @click="() => execQuery(context.params)">
- {{ $t("sql-editor.execute-query") }}
- </NButton>
- </div>
- </template>
- <ReactPageMount
- v-else
- page="ResultViewPage"
- container-class="w-full flex-1 min-h-0"
- :page-props="{
- executeParams: context.params,
- database,
- resultSet: context.resultSet,
- }"
- />
-</template>
-
-<script lang="tsx" setup>
-import { NButton } from "naive-ui";
-import { computed, watch } from "vue";
-import { BBSpin } from "@/bbkit";
-import { useCurrentTimestamp } from "@/composables/useCurrentTimestamp";
-import { useExecuteSQL } from "@/composables/useExecuteSQL";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { useSQLEditorTabStore } from "@/store";
-import type {
- SQLEditorDatabaseQueryContext,
- SQLEditorQueryParams,
-} from "@/types";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-
-const props = defineProps<{
- database: Database;
- context: SQLEditorDatabaseQueryContext;
-}>();
-
-const executeSQL = useExecuteSQL();
-const tabStore = useSQLEditorTabStore();
-
-const loading = computed(() => props.context.status === "EXECUTING");
-
-const { currentTsInMS, pause, resume } = useCurrentTimestamp();
-
-// Start/stop the timer based on loading state
-watch(
- loading,
- (isLoading) => {
- if (isLoading) {
- currentTsInMS.value = Date.now();
- resume();
- } else {
- pause();
- }
- },
- { immediate: true }
-);
-
-const queryElapsedTime = computed(() => {
- if (!loading.value) {
- return "";
- }
- const beginMS = props.context.beginTimestampMS;
- if (!beginMS) {
- return "";
- }
- const elapsedMS = currentTsInMS.value - beginMS;
- return `${(elapsedMS / 1000).toFixed(1)}s`;
-});
-
-const cancelQuery = () => {
- props.context.abortController?.abort();
- tabStore.updateDatabaseQueryContext({
- database: props.database.name,
- contextId: props.context.id,
- context: {
- status: "CANCELLED",
- },
- });
-};
-
-watch(
- [() => props.database, () => props.context.status],
- async ([database, status]) => {
- if (status === "PENDING") {
- await executeSQL.runQuery(database, props.context);
- }
- },
- { immediate: true, deep: true }
-);
-
-const execQuery = async (params: SQLEditorQueryParams) => {
- const context = tabStore.updateDatabaseQueryContext({
- database: props.database.name,
- contextId: props.context.id,
- context: {
- params,
- },
- });
- if (!context) {
- return;
- }
- await executeSQL.runQuery(props.database, context);
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
deleted file mode 100644
index d3ccf29041..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/ResultPanel.vue
+++ /dev/null
@@ -1,308 +0,0 @@
-<template>
- <div
- class="relative w-full h-full flex flex-col justify-start items-start z-10 overflow-x-hidden"
- >
- <ReactPageMount
- page="BatchQuerySelect"
- container-class="w-full shrink-0"
- :page-props="{
- selectedDatabase,
- onSelectedDatabaseChange: handleSelectedDatabaseChange,
- }"
- />
- <NTabs
- v-if="selectedDatabase && queryContexts"
- type="card"
- size="small"
- class="flex-1 flex flex-col overflow-hidden px-2"
- :class="isBatchQuery ? 'pt-0' : 'pt-2'"
- style="--n-tab-padding: 4px 12px"
- v-model:value="selectedTab"
- >
- <NTabPane
- v-for="(context, i) in queryContexts"
- :key="context.id"
- :name="context.id"
- class="flex-1 flex flex-col overflow-hidden"
- >
- <template #tab>
- <NTooltip>
- <template #trigger>
- <div
- class="flex items-center gap-x-2"
- @contextmenu.stop.prevent="
- handleContextMenuShow(context.id, $event)
- "
- >
- <span>{{ tabName(context) }}</span>
- <CircleAlertIcon
- v-if="context.resultSet?.error"
- class="text-red-600 w-4 h-auto"
- />
- <BBSpin v-if="context.status === 'EXECUTING'" :size="10" />
- <XIcon
- v-if="hasMultipleContexts"
- class="text-gray-400 w-4 h-auto hover:text-gray-600"
- @click.stop="handleCloseTab(context.id)"
- />
- </div>
- </template>
- {{ context.params.statement }}
- </NTooltip>
- </template>
- <BBAttention
- v-if="
- i === 0 && batchModeDataSourceType && !isMatchedDataSource(context)
- "
- type="warning"
- class="mb-2"
- >
- {{
- $t("sql-editor.batch-query.select-data-source.not-match", {
- expect: getDataSourceTypeI18n(
- tabStore.currentTab?.batchQueryContext.dataSourceType
- ),
- actual: getDataSourceTypeI18n(dataSourceInContext(context)?.type),
- })
- }}
- </BBAttention>
- <DatabaseQueryContext
- class="w-full h-auto grow"
- :database="selectedDatabase"
- :context="context"
- />
- </NTabPane>
- </NTabs>
- <NDropdown
- v-if="contextMenuState"
- trigger="manual"
- placement="bottom-start"
- :show="true"
- :x="contextMenuState?.x"
- :y="contextMenuState?.y"
- :options="contextMenuOptions"
- @clickoutside="handleContextMenuClose"
- @update:show="
- (show: boolean) => {
- if (!show) {
- handleContextMenuClose();
- }
- }
- "
- @select="handleContextMenuSelect"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { CircleAlertIcon, XIcon } from "lucide-vue-next";
-import type { DropdownOption } from "naive-ui";
-import { NDropdown, NTabPane, NTabs, NTooltip } from "naive-ui";
-import { computed, nextTick, ref, watch } from "vue";
-import { useI18n } from "vue-i18n";
-import { BBAttention, BBSpin } from "@/bbkit";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { useSQLEditorTabStore } from "@/store";
-import type { SQLEditorDatabaseQueryContext } from "@/types";
-import { getDataSourceTypeI18n } from "@/types";
-import type { Database } from "@/types/proto-es/v1/database_service_pb";
-import { formatAbsoluteDateTime, getInstanceResource } from "@/utils";
-import DatabaseQueryContext from "./DatabaseQueryContext.vue";
-
-const selectedDatabase = ref<Database>();
-const handleSelectedDatabaseChange = (db: Database | undefined) => {
- selectedDatabase.value = db;
-};
-const tabStore = useSQLEditorTabStore();
-const selectedTab = ref<string>();
-const { t } = useI18n();
-const contextMenuState = ref<
- | {
- x: number;
- y: number;
- tabId: string;
- }
- | undefined
->();
-
-const contextMenuOptions = computed((): DropdownOption[] => {
- return [
- {
- key: "CLOSE",
- label: t("sql-editor.tab.context-menu.actions.close"),
- },
- {
- key: "CLOSE_OTHERS",
- label: t("sql-editor.tab.context-menu.actions.close-others"),
- },
- {
- key: "CLOSE_TO_THE_RIGHT",
- label: t("sql-editor.tab.context-menu.actions.close-to-the-right"),
- },
- {
- key: "CLOSE_ALL",
- label: t("sql-editor.tab.context-menu.actions.close-all"),
- },
- ];
-});
-
-const handleContextMenuSelect = (action: string) => {
- if (!contextMenuState.value) {
- return;
- }
- switch (action) {
- case "CLOSE":
- handleCloseTab(contextMenuState.value.tabId);
- break;
- case "CLOSE_OTHERS":
- tabStore.batchRemoveDatabaseQueryContext({
- database: selectedDatabase.value?.name ?? "",
- contextIds:
- queryContexts.value
- ?.filter((ctx) => ctx.id !== contextMenuState.value?.tabId)
- .map((ctx) => ctx.id) ?? [],
- });
- selectedTab.value = contextMenuState.value?.tabId;
- break;
- case "CLOSE_TO_THE_RIGHT":
- const index =
- queryContexts.value?.findIndex(
- (ctx) => ctx.id === contextMenuState.value?.tabId
- ) ?? -1;
- if (index < 0) {
- return;
- }
- tabStore.batchRemoveDatabaseQueryContext({
- database: selectedDatabase.value?.name ?? "",
- contextIds:
- queryContexts.value?.slice(index + 1).map((ctx) => ctx.id) ?? [],
- });
- selectedTab.value = contextMenuState.value?.tabId;
- break;
- case "CLOSE_ALL":
- tabStore.deleteDatabaseQueryContext(selectedDatabase.value?.name ?? "");
- selectedTab.value = undefined;
- break;
- }
-
- handleContextMenuClose();
-};
-
-const handleContextMenuShow = (tabId: string, e: MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
- handleContextMenuClose();
- nextTick(() => {
- const { pageX, pageY } = e;
- contextMenuState.value = {
- x: pageX,
- y: pageY,
- tabId,
- };
- });
-};
-
-const handleContextMenuClose = () => {
- contextMenuState.value = undefined;
-};
-
-// Cache the batch query state to avoid recreating arrays
-const isBatchQuery = computed(() => {
- const contexts = tabStore.currentTab?.databaseQueryContexts;
- if (!contexts) return false;
- return contexts.size > 1;
-});
-
-// Memoize query contexts to avoid multiple accesses
-const queryContexts = computed(() => {
- if (!selectedDatabase.value?.name) return undefined;
- return tabStore.currentTab?.databaseQueryContexts?.get(
- selectedDatabase.value.name
- );
-});
-
-// Cache whether we have multiple contexts for close button visibility
-const hasMultipleContexts = computed(() => {
- return (queryContexts.value?.length ?? 0) > 1;
-});
-
-// Memoize tab names to avoid recalculation
-const tabNamesMap = computed(() => {
- const map = new Map<string, string>();
- if (!queryContexts.value) return map;
-
- for (const context of queryContexts.value) {
- let name: string;
- switch (context.status) {
- case "PENDING":
- name = t("sql-editor.pending-query");
- break;
- case "EXECUTING":
- name = t("sql-editor.executing-query");
- break;
- default:
- name = formatAbsoluteDateTime(context.beginTimestampMS ?? Date.now());
- }
- map.set(context.id, name);
- }
- return map;
-});
-
-const tabName = (context: SQLEditorDatabaseQueryContext) => {
- return tabNamesMap.value.get(context.id) ?? "";
-};
-
-// Cache data sources for better performance
-const dataSourcesMap = computed(() => {
- if (!selectedDatabase.value) {
- return new Map();
- }
- const instance = getInstanceResource(selectedDatabase.value);
- if (!instance.dataSources) {
- return new Map();
- }
- return new Map(instance.dataSources.map((ds) => [ds.id, ds]));
-});
-
-const dataSourceInContext = (context: SQLEditorDatabaseQueryContext) => {
- const dataSourceId = context.params.connection.dataSourceId;
- return dataSourcesMap.value.get(dataSourceId);
-};
-
-// Memoize batch mode check
-const batchModeDataSourceType = computed(() => {
- if (!tabStore.isInBatchMode) return null;
- return tabStore.currentTab?.batchQueryContext.dataSourceType ?? null;
-});
-
-const isMatchedDataSource = (context: SQLEditorDatabaseQueryContext) => {
- const mode = batchModeDataSourceType.value;
- if (!mode) {
- return true;
- }
- const dataSource = dataSourceInContext(context);
- if (!dataSource) {
- return true;
- }
- return dataSource.type === mode;
-};
-
-// Only watch the first item's ID to minimize reactive dependencies
-watch(
- () => queryContexts.value?.[0]?.id,
- (id) => {
- selectedTab.value = id;
- },
- { immediate: true }
-);
-
-const handleCloseTab = (id: string) => {
- const nextContext = tabStore.removeDatabaseQueryContext({
- database: selectedDatabase.value?.name ?? "",
- contextId: id,
- });
- if (selectedTab.value === id && nextContext) {
- selectedTab.value = nextContext.id;
- }
-};
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/index.ts b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/index.ts
deleted file mode 100644
index 4dbff35866..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import ResultPanel from "./ResultPanel.vue";
-
-export default ResultPanel;
diff --git a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts b/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts
deleted file mode 100644
index 7b788b73a1..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/ResultPanel/resultTabContext.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import Emittery from "emittery";
-
-export type CloseTabAction =
- | "CLOSE"
- | "CLOSE_OTHERS"
- | "CLOSE_TO_THE_RIGHT"
- | "CLOSE_ALL";
-
-/**
- * Module-level singleton replacing the per-instance Vue provide/inject in
- * `./context.ts`. The React `ContextMenu` (mounted per-tab inside
- * `BatchQuerySelect`) emits on this channel; `BatchQuerySelect` subscribes
- * to it to handle close-tab actions.
- *
- * Base UI's `ContextMenuTrigger` handles right-click positioning natively, so
- * the previous `{ x, y, index }` state from the Vue context is no longer
- * needed — only the close-tab event bus survives.
- */
-export const resultTabEvents = new Emittery<{
- "close-tab": { index: number; action: CloseTabAction };
-}>();
diff --git a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
deleted file mode 100644
index cc09cdc6a7..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/StandardPanel.vue
+++ /dev/null
@@ -1,120 +0,0 @@
-<template>
- <template v-if="!tab || tab.mode === 'WORKSHEET'">
- <NSplit
- v-if="showResultPanel"
- direction="vertical"
- :max="0.8"
- :resize-trigger-size="3"
- >
- <template #1>
- <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">
- <ResultPanel />
- </div>
- </template>
- </NSplit>
- <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>
-
-<script lang="ts" setup>
-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";
-
-const { currentTab: tab, isDisconnected } = storeToRefs(useSQLEditorTabStore());
-const { instance } = useConnectionOfCurrentSQLEditorTab();
-
-// ResultPanel only renders when connected to a read-only-capable instance;
-// when it won't render we skip the outer NSplit so the editor body (incl.
-// the Welcome screen) can occupy the full height instead of being squeezed
-// into an arbitrary top pane.
-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/index.ts b/frontend/src/views/sql-editor/EditorPanel/StandardPanel/index.ts
deleted file mode 100644
index dee995dc37..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/StandardPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import StandardPanel from "./StandardPanel.vue";
-
-export default StandardPanel;
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue
deleted file mode 100644
index af5a28f916..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/TerminalPanel.vue
+++ /dev/null
@@ -1,186 +0,0 @@
-<template>
- <div
- class="flex h-full w-full flex-col justify-start items-stretch overflow-hidden bg-dark-bg"
- >
- <ReactPageMount page="EditorAction" container-class="w-full" />
-
- <div
- v-if="!tabStore.isDisconnected"
- ref="queryListContainerRef"
- class="w-full flex-1 overflow-y-auto bg-dark-bg"
- >
- <div
- ref="queryListRef"
- class="w-full flex flex-col"
- :data-height="queryListHeight"
- >
- <div v-for="query in queryList" :key="query.id" class="relative">
- <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,
- }"
- />
- <ReactPageMount
- v-if="query.params && query.resultSet"
- page="ResultViewPage"
- container-class="p-2 w-full flex-1 min-h-0"
- :page-props="{
- executeParams: query.params,
- resultSet: query.resultSet,
- database: databaseStore.getDatabaseByName(
- query.params.connection.database
- ),
- loading: query.status === 'RUNNING',
- dark: true,
- }"
- />
-
- <div
- v-if="query.resultSet?.error"
- class="p-2 pb-1 text-md font-normal text-matrix-green-hover"
- >
- {{ $t("sql-editor.connection-lost") }}
- </div>
-
- <div
- v-if="query.status === 'RUNNING'"
- class="absolute inset-0 bg-black/20 flex justify-center items-center gap-2"
- >
- <BBSpin />
- <div
- v-if="query === currentQuery && expired"
- class="text-gray-400 cursor-pointer hover:underline text-sm select-none"
- @click="handleCancelQuery"
- >
- {{ $t("common.cancel") }}
- </div>
- </div>
- </div>
- </div>
- </div>
- <div v-else class="flex-1 flex flex-col min-h-0">
- <ReactPageMount page="ConnectionHolder" />
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-import { useElementSize } from "@vueuse/core";
-import { computed, ref, unref, watch, watchEffect } from "vue";
-import { BBSpin } from "@/bbkit";
-import type { IStandaloneCodeEditor } from "@/components/MonacoEditor";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import {
- useDatabaseV1Store,
- useSQLEditorTabStore,
- useWebTerminalStore,
-} from "@/store";
-import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";
-import { useHistory } from "./useHistory";
-
-const tabStore = useSQLEditorTabStore();
-const webTerminalStore = useWebTerminalStore();
-const databaseStore = useDatabaseV1Store();
-
-const queryState = computed(() => {
- return webTerminalStore.getQueryStateByTab(tabStore.currentTab!);
-});
-
-const queryList = computed(() => {
- return unref(queryState.value.queryItemList);
-});
-
-watchEffect(async () => {
- await databaseStore.batchGetOrFetchDatabases(
- queryList.value.map((query) => query?.params?.connection.database ?? "")
- );
-});
-
-const queryListContainerRef = ref<HTMLDivElement>();
-const queryListRef = ref<HTMLDivElement>();
-
-const currentQuery = computed(
- () => queryList.value[queryList.value.length - 1]
-);
-
-const { move: moveHistory } = useHistory();
-
-const timer = computed(() => {
- return unref(queryState.value.timer);
-});
-const expired = computed(() => {
- return unref(timer.value.expired);
-});
-
-const isEditableQueryItem = (item: WebTerminalQueryItemV1): boolean => {
- return item === currentQuery.value && item.status === "IDLE";
-};
-
-const handleExecute = async (params: SQLEditorQueryParams) => {
- if (currentQuery.value.status !== "IDLE") {
- return;
- }
-
- // Prevent executing empty query;
- if (!params.statement) {
- console.warn("Empty query");
- return;
- }
-
- queryState.value.controller.events.emit("query", params);
-};
-
-const handleClearScreen = () => {
- const list = queryList.value;
- while (list.length > 1) {
- list.shift();
- }
-};
-
-const handleHistory = (
- direction: "up" | "down",
- editor: IStandaloneCodeEditor
-) => {
- if (currentQuery.value.status !== "IDLE") {
- return;
- }
- moveHistory(direction);
-
- requestAnimationFrame(() => {
- const model = editor.getModel();
- if (!model) return;
- const lineNumber = model.getLineCount();
- const column = model.getLineMaxColumn(lineNumber);
- editor.setPosition({
- lineNumber,
- column,
- });
- });
-};
-
-const handleCancelQuery = async () => {
- queryState.value.controller.abort();
-};
-
-const { height: queryListHeight } = useElementSize(queryListRef);
-
-watch(queryListHeight, () => {
- // Always scroll to the bottom as if we are in a real terminal.
- requestAnimationFrame(() => {
- const container = queryListContainerRef.value;
- if (container) {
- container.scrollTo(0, container.scrollHeight);
- }
- });
-});
-</script>
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/index.ts b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/index.ts
deleted file mode 100644
index e24262cef5..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import TerminalPanel from "./TerminalPanel.vue";
-
-export default TerminalPanel;
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useAttractFocus.ts b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useAttractFocus.ts
deleted file mode 100644
index b74b6d37f0..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useAttractFocus.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useEventListener } from "@vueuse/core";
-import { unref } from "vue";
-import type { MaybeRef } from "@/types";
-import { isDescendantOf } from "@/utils";
-
-const FOCUS_ATTRACTIVE_KEYS: (RegExp | string)[] = [
- /^[A-Za-z0-9\s.`~!@#$%^&*()-=[\]\\;',./_+{}|:"<>?]$/,
- "ArrowUp",
- "ArrowDown",
- "ArrowLeft",
- "ArrowRight",
- "Backspace",
- "Delete",
- "Home",
- "End",
-];
-
-const shouldAttractFocus = (e: KeyboardEvent) => {
- if (e.metaKey || e.ctrlKey) {
- // A downgrade for safety since key strokes with cmd or ctrl might
- // probably be a system-wide keyboard shortcut.
- return false;
- }
- return FOCUS_ATTRACTIVE_KEYS.some((rule) => {
- if (typeof rule === "string") {
- return e.key === rule;
- }
- return e.key.match(rule);
- });
-};
-
-export type AttractFocusOptions = {
- excluded?: { tag: string; selector: string }[];
- targetSelector: string;
-};
-
-export const useAttractFocus = (options: MaybeRef<AttractFocusOptions>) => {
- useEventListener("keydown", (e: KeyboardEvent) => {
- const sourceElement = e.target as Element;
- const tag = sourceElement.tagName.toLowerCase();
- if (tag === "input") {
- // Don't rob the focus in other text boxes
- return;
- }
- const { excluded = [], targetSelector } = unref(options);
- for (let i = 0; i < excluded.length; i++) {
- const rule = excluded[i];
- if (tag === rule.tag && isDescendantOf(sourceElement, rule.selector)) {
- return;
- }
- }
- if (!shouldAttractFocus(e)) {
- return;
- }
-
- const target = document.querySelector<HTMLTextAreaElement>(targetSelector);
- // monaco-editor will consume the focus event with key stroke11
- target?.focus();
- });
-};
diff --git a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useHistory.ts b/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useHistory.ts
deleted file mode 100644
index bebfc1a7c0..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/TerminalPanel/useHistory.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { computed, unref, watch } from "vue";
-import { useSQLEditorTabStore, useWebTerminalStore } from "@/store";
-import type { WebTerminalQueryItemV1 } from "@/types";
-import { minmax } from "@/utils";
-
-const MAX_HISTORY_ITEM_COUNT = 1000;
-
-type HistoryState = {
- index: number;
- list: WebTerminalQueryItemV1[];
-};
-
-export const useHistory = () => {
- const tabStore = useSQLEditorTabStore();
- const webTerminalStore = useWebTerminalStore();
- const historyByTabId = new Map<string, HistoryState>();
- const queryState = computed(() => {
- return webTerminalStore.getQueryStateByTab(tabStore.currentTab!);
- });
-
- const currentQuery = computed(() => {
- const queryList = unref(queryState.value.queryItemList);
- return queryList[queryList.length - 1];
- });
-
- const currentStack = () => {
- const tab = tabStore.currentTab!;
- if (tab.mode !== "ADMIN") return undefined;
-
- const existed = historyByTabId.get(tab.id);
- if (existed) {
- return existed;
- }
- const initial: HistoryState = {
- index: -1,
- list: [],
- };
- historyByTabId.set(tab.id, initial);
- return initial;
- };
-
- const push = (query: WebTerminalQueryItemV1) => {
- const stack = currentStack();
- if (!stack) return;
- const { list } = stack;
- list.push(query);
- if (list.length > MAX_HISTORY_ITEM_COUNT) {
- list.shift();
- }
- stack.index = list.length - 1;
- };
-
- const move = (direction: "up" | "down") => {
- const stack = currentStack();
- if (!stack) return;
- const { index, list } = stack;
- const delta = direction === "up" ? -1 : 1;
- const nextIndex = minmax(index + delta, 0, list.length - 1);
- if (nextIndex === index) {
- return;
- }
- if (nextIndex === list.length - 1) {
- currentQuery.value.statement = "";
- } else {
- const historyQuery = list[nextIndex];
- if (historyQuery) {
- currentQuery.value.statement = historyQuery.statement;
- }
- }
-
- stack.index = nextIndex;
- };
-
- watch(
- () => currentQuery.value,
- (query) => {
- push(query);
- },
- {
- immediate: true,
- }
- );
-
- return { push, move };
-};
diff --git a/frontend/src/views/sql-editor/EditorPanel/context/viewState.tsx b/frontend/src/views/sql-editor/EditorPanel/context/viewState.tsx
deleted file mode 100644
index 8385853cae..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/context/viewState.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-import { InfoIcon } from "lucide-vue-next";
-import { storeToRefs } from "pinia";
-import type { VNodeChild } from "vue";
-import { computed, type InjectionKey, inject, provide, watch } from "vue";
-import {
- ExternalTableIcon,
- FunctionIcon,
- PackageIcon,
- ProcedureIcon,
- SequenceIcon,
- TableIcon,
- ViewIcon,
-} from "@/components/Icon";
-import { SchemaDiagramIcon } from "@/components/SchemaDiagram";
-import { t } from "@/plugins/i18n";
-import {
- useConnectionOfCurrentSQLEditorTab,
- useSQLEditorTabStore,
-} from "@/store";
-import {
- defaultViewState,
- type EditorPanelView,
- type EditorPanelViewState as ViewState,
-} from "@/types";
-import {
- instanceV1SupportsExternalTable,
- instanceV1SupportsPackage,
- instanceV1SupportsSequence,
-} from "@/utils";
-
-const KEY = Symbol(
- "bb.sql-editor.editor-panel"
-) as InjectionKey<EditorPanelContext>;
-
-export const provideCurrentTabViewStateContext = () => {
- const tabStore = useSQLEditorTabStore();
- const { currentTab: tab } = storeToRefs(tabStore);
-
- const { instance } = useConnectionOfCurrentSQLEditorTab();
-
- const viewState = computed(() => {
- return tab.value?.viewState;
- });
-
- const availableActions = computed(() => {
- const actions: {
- view: EditorPanelView;
- title: string;
- icon: () => VNodeChild;
- }[] = [
- {
- view: "INFO",
- title: t("common.info"),
- icon: () => <InfoIcon class="w-4 h-4" />,
- },
- {
- view: "TABLES",
- title: t("db.tables"),
- icon: () => <TableIcon class="w-4 h-4" />,
- },
- {
- view: "VIEWS",
- title: t("db.views"),
- icon: () => <ViewIcon class="w-4 h-4" />,
- },
- {
- view: "FUNCTIONS",
- title: t("db.functions"),
- icon: () => <FunctionIcon class="w-4 h-4" />,
- },
- {
- view: "PROCEDURES",
- title: t("db.procedures"),
- icon: () => <ProcedureIcon class="w-4 h-4" />,
- },
- ];
- if (instanceV1SupportsSequence(instance.value)) {
- actions.push({
- view: "SEQUENCES",
- title: t("db.sequences"),
- icon: () => <SequenceIcon class="w-4 h-4" />,
- });
- }
- if (instanceV1SupportsExternalTable(instance.value)) {
- actions.push({
- view: "EXTERNAL_TABLES",
- title: t("db.external-tables"),
- icon: () => <ExternalTableIcon class="w-4 h-4" />,
- });
- }
- if (instanceV1SupportsPackage(instance.value)) {
- actions.push({
- view: "PACKAGES",
- title: t("db.packages"),
- icon: () => <PackageIcon class="w-4 h-4" />,
- });
- }
- actions.push({
- view: "DIAGRAM",
- title: t("schema-diagram.self"),
- icon: () => <SchemaDiagramIcon class="w-4 h-4" />,
- });
- return actions;
- });
-
- const selectedSchemaName = computed({
- get() {
- return viewState.value?.schema;
- },
- set(schema) {
- if (schema === undefined) return;
- updateViewState({
- schema,
- });
- },
- });
-
- const updateViewState = (patch: Partial<ViewState>) => {
- if (!tab.value) return;
- tabStore.updateTab(tab.value.id, {
- viewState: {
- ...defaultViewState(),
- ...tab.value.viewState,
- ...patch,
- },
- });
- };
-
- watch(
- () => tab.value?.connection.schema,
- (schema) => {
- if (schema === undefined) return;
- if (!viewState.value) return;
- if (viewState.value.schema === schema) return;
- viewState.value.schema = schema;
- },
- { immediate: true }
- );
-
- watch(
- () => viewState.value?.schema,
- (schema) => {
- if (!schema) return;
- if (!tab.value) return;
- if (tab.value.connection.schema === undefined) return; // if schema chooser is "ALL", don't sync
- if (tab.value.connection.schema === schema) return;
- tab.value.connection.schema = schema;
- },
- { immediate: true }
- );
-
- const context = {
- viewState,
- selectedSchemaName,
- availableActions,
- updateViewState,
- };
-
- provide(KEY, context);
-
- return context;
-};
-
-export const useCurrentTabViewStateContext = () => {
- return inject(KEY)!;
-};
-
-export type EditorPanelContext = ReturnType<
- typeof provideCurrentTabViewStateContext
->;
diff --git a/frontend/src/views/sql-editor/EditorPanel/index.ts b/frontend/src/views/sql-editor/EditorPanel/index.ts
deleted file mode 100644
index aadd6e3525..0000000000
--- a/frontend/src/views/sql-editor/EditorPanel/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import EditorPanel from "./EditorPanel.vue";
-
-export * from "./context/viewState.tsx";
-
-export default EditorPanel;
diff --git a/frontend/src/views/sql-editor/SQLEditorHomePage.vue b/frontend/src/views/sql-editor/SQLEditorHomePage.vue
deleted file mode 100644
index 7c7b74c9c2..0000000000
--- a/frontend/src/views/sql-editor/SQLEditorHomePage.vue
+++ /dev/null
@@ -1,196 +0,0 @@
-<template>
- <div class="sqleditor--wrapper">
- <teleport v-if="hideSidebar" to="body">
- <div
- id="fff"
- class="fixed rounded-full border border-control-border shadow-lg w-10 h-10 bottom-16 flex items-center justify-center bg-white hover:bg-control-bg cursor-pointer z-99999999 transition-all"
- :class="[
- state.sidebarExpanded ? 'left-[80%] -translate-x-5' : 'left-4',
- ]"
- style="
- transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
- transition-duration: 300ms;
- "
- @click="state.sidebarExpanded = !state.sidebarExpanded"
- >
- <ChevronLeft
- class="w-6 h-6 transition-transform"
- :class="[state.sidebarExpanded ? '' : '-scale-100']"
- />
- </div>
- <Drawer
- v-model:show="state.sidebarExpanded"
- width="80vw"
- placement="left"
- >
- <ReactPageMount page="AsidePanel" container-class="h-full" />
- </Drawer>
- </teleport>
- <NSplit
- direction="horizontal"
- :disabled="hideSidebar"
- :size="hideSidebar ? 0 : state.sizebarSize"
- :min="0.1"
- :max="0.4"
- :resize-trigger-size="3"
- @update:size="size => state.sizebarSize = size"
- >
- <template #1>
- <ReactPageMount page="AsidePanel" container-class="h-full" />
- </template>
- <template #2>
- <div class="h-full relative flex flex-col">
- <ReactPageMount page="TabList" container-class="w-full" />
- <EditorPanel />
- </div>
- </template>
- </NSplit>
-
- <Quickstart />
-
- <teleport to="#sql-editor-debug">
- <li>[Page]isDisconnected: {{ isDisconnected }}</li>
- <li>[Page]currentTab.id: {{ currentTab?.id }}</li>
- <li>[Page]currentTab.connection: {{ currentTab?.connection }}</li>
- </teleport>
-
- <!-- ConnectionPanel reads its open state directly from uiStore via
- useVueState, so no prop wiring is needed here. The Sheet portals
- out of the SQL Editor layout into the overlay layer. -->
- <ReactPageMount page="ConnectionPanel" container-class="" />
- </div>
-
- <IAMRemindModal v-if="projectContextReady" :project-name="projectName" />
-</template>
-
-<script lang="ts" setup>
-import { useWindowSize } from "@vueuse/core";
-import { ChevronLeft } from "lucide-vue-next";
-import { NSplit } from "naive-ui";
-import { storeToRefs } from "pinia";
-import { computed, reactive } from "vue";
-// useI18n imported under a non-`use*` alias so SonarCloud's React-hook-
-// rule (typescript:S6440) doesn't misfire on this Vue composable called
-// at <script setup> top level. Consistent with the projectV1Store alias
-// workaround already in this file. See fd2aca60bf for the pattern.
-import { useI18n as vueI18n } from "vue-i18n";
-import { useRouter } from "vue-router";
-import IAMRemindModal from "@/components/IAMRemindModal.vue";
-import { applyPlanTitleToQuery } from "@/components/Plan/logic/title";
-import Quickstart from "@/components/Quickstart.vue";
-import { Drawer } from "@/components/v2";
-import { useEmitteryEventListener } from "@/composables/useEmitteryEventListener";
-import ReactPageMount from "@/react/ReactPageMount.vue";
-import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";
-import {
- useProjectV1Store as projectV1Store,
- useDatabaseV1Store,
- useSQLEditorStore,
- useSQLEditorTabStore,
-} from "@/store";
-import { unknownProject } from "@/types";
-import {
- extractDatabaseResourceName,
- extractProjectResourceName,
-} from "@/utils";
-import { useSQLEditorContext } from "./context";
-import EditorPanel from "./EditorPanel";
-import { provideCurrentTabViewStateContext } from "./EditorPanel/context/viewState";
-
-type LocalState = {
- sizebarSize: number;
- sidebarExpanded: boolean;
-};
-
-const state = reactive<LocalState>({
- sizebarSize: 0.25,
- sidebarExpanded: false,
-});
-
-const router = useRouter();
-const { t } = vueI18n();
-const databaseStore = useDatabaseV1Store();
-// projectStore accessor imported under a non-`use*` alias so SonarCloud's
-// React-hook-rule (typescript:S6440) doesn't misfire on this new Pinia
-// call in a Vue SFC. Consistent with the same workaround in
-// ExecuteHint.vue. Pinia stores are module-level singletons.
-const projectStore = projectV1Store();
-const tabStore = useSQLEditorTabStore();
-const editorStore = useSQLEditorStore();
-
-const { events: editorEvents, pendingInsertAtCaret } = useSQLEditorContext();
-
-const { project: projectName, projectContextReady } = storeToRefs(editorStore);
-
-const { currentTab, isDisconnected } = storeToRefs(tabStore);
-
-const { width: windowWidth } = useWindowSize();
-const hideSidebar = computed(() => windowWidth.value < 800);
-
-useEmitteryEventListener(
- editorEvents,
- "alter-schema",
- async ({ databaseName, schema, table }) => {
- const database = await databaseStore.getOrFetchDatabaseByName(databaseName);
- // Project-fetch-failed cell: if the project lookup rejects, still
- // launch the plan page using the known `database.project`. Fall back
- // to `unknownProject()` (enforceIssueTitle=true) — the launcher
- // drops `query.name` so the user types a deliberate title before
- // submitting. Backend remains the source of truth on submit.
- const project = await projectStore
- .getOrFetchProjectByName(database.project)
- .catch(() => unknownProject());
- const exampleSQL = ["ALTER TABLE"];
- if (table) {
- if (schema) {
- exampleSQL.push(`${schema}.${table}`);
- } else {
- exampleSQL.push(`${table}`);
- }
- }
- const { databaseName: dbName } = extractDatabaseResourceName(database.name);
- const query: Record<string, string> = {
- template: "bb.plan.change-database",
- databaseList: database.name,
- sql: exampleSQL.join(" "),
- };
- applyPlanTitleToQuery(
- query,
- project,
- () => `[${dbName}] ${t("issue.title.edit-schema")}`
- );
- const route = router.resolve({
- name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
- params: {
- projectId: extractProjectResourceName(database.project),
- planId: "create",
- specId: "placeholder",
- },
- query,
- });
- window.open(route.fullPath, "_blank");
- }
-);
-
-const editorPanelContext = provideCurrentTabViewStateContext();
-
-useEmitteryEventListener(editorEvents, "insert-at-caret", ({ content }) => {
- if (!tabStore.currentTab) return;
- editorPanelContext.updateViewState({
- view: "CODE",
- });
- requestAnimationFrame(() => {
- pendingInsertAtCaret.value = content;
- });
-});
-</script>
-
-<style scoped lang="postcss">
-.sqleditor--wrapper {
- width: 100%;
- flex: 1 1 0%;
- overflow: hidden;
- display: flex;
- flex-direction: column;
-}
-</style>
diff --git a/frontend/src/views/sql-editor/SQLEditorPage.vue b/frontend/src/views/sql-editor/SQLEditorPage.vue
deleted file mode 100644
index cceba50d32..0000000000
--- a/frontend/src/views/sql-editor/SQLEditorPage.vue
+++ /dev/null
@@ -1,34 +0,0 @@
-<template>
- <Suspense>
- <template #default>
- <SQLEditorHomePage />
- </template>
- <template #fallback>
- <div class="flex items-center justify-center h-screen">
- <BBSpin />
- </div>
- </template>
- </Suspense>
-</template>
-
-<script setup lang="ts">
-import { defineAsyncComponent } from "vue";
-import { BBSpin } from "@/bbkit";
-
-// Lazy load the SQL Editor to reduce initial bundle size.
-const SQLEditorHomePage = defineAsyncComponent({
- loader: () => import("./SQLEditorHomePage.vue"),
- delay: 200,
- timeout: 30000,
- errorComponent: {
- template: `
- <div class="flex items-center justify-center h-screen">
- <div class="text-red-500">Failed to load SQL Editor</div>
- </div>
- `,
- },
- onError(error) {
- console.error("Failed to load SQL Editor:", error);
- },
-});
-</script>
diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.ts
deleted file mode 100644
index 61ab6469d1..0000000000
--- a/frontend/src/views/sql-editor/context.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-import { watchDebounced } from "@vueuse/core";
-import Emittery from "emittery";
-import { storeToRefs } from "pinia";
-import type { ComputedRef, InjectionKey, Ref } from "vue";
-import { inject, provide } from "vue";
-import {
- pushNotification,
- useSQLEditorTabStore,
- useSQLEditorUIStore,
- useSQLEditorWorksheetStore,
- useWorkSheetStore,
-} from "@/store";
-import type { SQLEditorTab } from "@/types";
-import { isWorksheetWritableV1 } from "@/utils";
-import type { SQLEditorEvents as SQLEditorEventsMap } from "./events";
-import { sqlEditorEvents } from "./events";
-
-// Backward-compat alias: consumers typed the events field as Emittery<{...}>.
-// Re-export Emittery<SQLEditorEventsMap> under the old name so that no callers need changing.
-export type SQLEditorEvents = Emittery<SQLEditorEventsMap>;
-
-export const ASIDE_PANEL_TABS = [
- "SCHEMA",
- "WORKSHEET",
- "HISTORY",
- "ACCESS",
-] as const;
-export type AsidePanelTab = (typeof ASIDE_PANEL_TABS)[number];
-
-export type SQLEditorContext = {
- asidePanelTab: Ref<AsidePanelTab>;
- showConnectionPanel: Ref<boolean>;
- showAIPanel: Ref<boolean>;
- editorPanelSize: ComputedRef<{
- size: number;
- min: number;
- max: number;
- }>;
-
- pendingInsertAtCaret: Ref<string | undefined>;
-
- // The resource name of a newly created access grant to highlight in the list.
- highlightAccessGrantName: Ref<string | undefined>;
-
- events: SQLEditorEvents;
-
- maybeSwitchProject: (project: string) => Promise<string | undefined>;
- handleEditorPanelResize: (size: number) => void;
- createWorksheet: (options: {
- tabId?: string;
- title?: string;
- folders?: string[];
- statement?: string;
- database?: string;
- }) => Promise<SQLEditorTab | undefined>;
- maybeUpdateWorksheet: (options: {
- tabId: string;
- worksheet: string;
- title?: string;
- database: string;
- statement: string;
- folders?: string[];
- signal?: AbortSignal;
- }) => Promise<SQLEditorTab | undefined>;
- // Abort any in-progress auto-save (used when manual save takes priority)
- abortAutoSave: () => void;
-};
-
-export const KEY = Symbol(
- "bb.sql-editor.context"
-) as InjectionKey<SQLEditorContext>;
-
-export const useSQLEditorContext = () => {
- return inject(KEY)!;
-};
-
-export const provideSQLEditorContext = () => {
- const tabStore = useSQLEditorTabStore();
- const worksheetStore = useWorkSheetStore();
- const uiStore = useSQLEditorUIStore();
- const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();
- const {
- asidePanelTab,
- showConnectionPanel,
- showAIPanel,
- pendingInsertAtCaret,
- highlightAccessGrantName,
- editorPanelSize,
- } = storeToRefs(uiStore);
-
- const context: SQLEditorContext = {
- asidePanelTab,
- showConnectionPanel,
- showAIPanel,
- editorPanelSize,
- pendingInsertAtCaret,
- highlightAccessGrantName,
- events: sqlEditorEvents,
-
- maybeSwitchProject: sqlEditorWorksheetStore.maybeSwitchProject,
- handleEditorPanelResize: uiStore.handleEditorPanelResize,
- createWorksheet: sqlEditorWorksheetStore.createWorksheet,
- maybeUpdateWorksheet: sqlEditorWorksheetStore.maybeUpdateWorksheet,
- abortAutoSave: sqlEditorWorksheetStore.abortAutoSave,
- };
-
- // Auto-saving for current tab.
- // This handles several complex scenarios:
- //
- // Scenario 1: Normal auto-save
- // 1. User types "statement1", status → DIRTY
- // 2. After 2s debounce, auto-save starts, status → SAVING
- // 3. Auto-save completes, status → CLEAN
- //
- // Scenario 2: User types during auto-save
- // 1. User types "statement1", status → DIRTY
- // 2. Auto-save #1 starts for "statement1", status → SAVING
- // 3. User types more → "statement1 statement2", status → DIRTY
- // 4. Auto-save #1 completes, status → CLEAN
- // 5. Finally block: statement changed, status → DIRTY
- // 6. After 2s debounce, auto-save #2 starts for "statement1 statement2"
- //
- // Scenario 3: Manual save during auto-save
- // 1. User types "statement1", status → DIRTY
- // 2. Auto-save #1 starts, status → SAVING
- // 3. User clicks save → abortAutoSave() called
- // 4. Auto-save #1 aborted (throws AbortError), wasAborted = true
- // 5. Manual save runs and completes, status → CLEAN
- // 6. Auto-save #1's finally: wasAborted = true, skips logic
- //
- // Scenario 4: Rapid typing (newer auto-save aborts older)
- // 1. User types "statement1", status → DIRTY
- // 2. Auto-save #1 starts (slow network), status → SAVING
- // 3. User types "statement1 statement2", status → DIRTY
- // 4. After 2s debounce, abortAutoSave() aborts #1, auto-save #2 starts
- // 5. Auto-save #1's finally: wasAborted = true, skips logic
- // 6. Auto-save #2 completes with correct content
- //
- // Scenario 5: Auto-save fails (network/server error)
- // 1. User types "statement1", status → DIRTY
- // 2. Auto-save starts, status → SAVING
- // 3. Network error occurs
- // 4. Catch block: status → DIRTY, error notification shown
- // 5. User can manually save or wait for next auto-save attempt
- //
- // Scenario 6: Tab closed during auto-save
- // 1. User types "statement1", status → DIRTY
- // 2. Auto-save starts, status → SAVING
- // 3. User closes tab (warning shown since status !== CLEAN)
- // 4. User confirms, tab removed from store
- // 5. Auto-save completes, finally block runs
- // 6. getTabById returns undefined, updateTab is no-op (safe)
- //
- // Guard conditions (auto-save skipped):
- // - No worksheet (draft tab): user must manually save to create worksheet
- // - Read-only worksheet: user doesn't have write permission
- // - Status is CLEAN: nothing to save
- //
- const { currentTab } = storeToRefs(tabStore);
-
- watchDebounced(
- () => currentTab.value?.statement,
- async () => {
- const tab = currentTab.value;
- if (!tab || !tab.worksheet || tab.status === "CLEAN") {
- return;
- }
-
- // Check write permission
- const worksheet = worksheetStore.getWorksheetByName(tab.worksheet);
- if (!worksheet || !isWorksheetWritableV1(worksheet)) {
- return;
- }
-
- // Abort any in-progress auto-save before starting a new one
- sqlEditorWorksheetStore.abortAutoSave();
-
- // Capture the statement and tab id before async operation
- const statementToSave = tab.statement;
- const tabId = tab.id;
-
- // Create new abort controller for this auto-save
- const controller = new AbortController();
- sqlEditorWorksheetStore.autoSaveController = controller;
- // Set status to SAVING
- tabStore.updateTab(tabId, { status: "SAVING" });
-
- // Track if this auto-save was aborted
- let wasAborted = false;
-
- try {
- // the maybeUpdateWorksheet will set status to CLEAN
- await sqlEditorWorksheetStore.maybeUpdateWorksheet({
- tabId,
- worksheet: tab.worksheet,
- database: tab.connection.database,
- statement: statementToSave,
- signal: controller.signal,
- });
- } catch (error) {
- // Don't handle aborted requests - a newer save or manual save took priority
- if (error instanceof Error && error.name === "AbortError") {
- wasAborted = true;
- return;
- }
- // Only revert to DIRTY if still in SAVING state
- // (user might have manually saved successfully during this time)
- if (tabStore.getTabById(tabId)?.status === "SAVING") {
- tabStore.updateTab(tabId, { status: "DIRTY" });
- }
- pushNotification({
- module: "bytebase",
- style: "CRITICAL",
- title: "Auto-save failed",
- description: error instanceof Error ? error.message : "Unknown error",
- });
- } finally {
- sqlEditorWorksheetStore.autoSaveController = null;
-
- // Skip for aborted requests - manual save or newer auto-save took priority
- if (wasAborted) {
- return;
- }
-
- // After save, check if the statement changed while we were saving
- // If it did, the user typed more content, so keep status as DIRTY
- const currentStatement = tabStore.getTabById(tabId)?.statement;
- if (currentStatement !== statementToSave) {
- tabStore.updateTab(tabId, { status: "DIRTY" });
- }
- }
- },
- { debounce: 2000 /* 2 seconds */ }
- );
-
- provide(KEY, context);
-
- return context;
-};