Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor: migrate pinia store (wip) (#20350)
ecmadaod5da7d958bc0
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 3a4f8dbc34..0c2e9c60c7 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -2468,7 +2468,6 @@"rows": "row | rows","rows-upper-limit": "reached the limit of query results","save-sheet": "Save Sheet",- "save-sheet-input-placeholder": "Please input a sheet name","scroll-to-bottom": "Scroll to the bottom","scroll-to-top": "Scroll to the top","search-history-by-statement": "Search by statement",diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex e73e46cc1e..3ffa3f6dea 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2468,7 +2468,6 @@"rows": "fila | filas","rows-upper-limit": "se ha alcanzado el límite de resultados de la consulta","save-sheet": "Guardar hoja",- "save-sheet-input-placeholder": "Por favor, ingresa un nombre para la hoja","scroll-to-bottom": "Desplazarse hacia abajo","scroll-to-top": "Desplazarse hacia arriba","search-history-by-statement": "Búsqueda por enunciado",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 5d4e619ca8..c1f99ecbd0 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2468,7 +2468,6 @@"rows": "記録","rows-upper-limit": "クエリ結果の数が上限に達しました","save-sheet": "ワークシートの保存",- "save-sheet-input-placeholder": "ワークシート名を入力してください","scroll-to-bottom": "末尾へスクロール","scroll-to-top": "先頭へスクロール","search-history-by-statement": "ステートメントで検索",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 28e6b4b5ea..ea7f5f39f4 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2468,7 +2468,6 @@"rows": "dòng | dòng","rows-upper-limit": "đã đạt đến giới hạn kết quả truy vấn","save-sheet": "Lưu trang tính",- "save-sheet-input-placeholder": "Vui lòng nhập tên trang tính","scroll-to-bottom": "Cuộn xuống cuối","scroll-to-top": "Cuộn lên đầu","search-history-by-statement": "Tìm kiếm theo câu lệnh",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex cb1ca07db8..119a3673f3 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -2468,7 +2468,6 @@"rows": "条记录","rows-upper-limit": "到达查询结果条数上限","save-sheet": "保存工作表",- "save-sheet-input-placeholder": "请输入工作表名称","scroll-to-bottom": "滚动到底部","scroll-to-top": "滚动到顶部","search-history-by-statement": "搜索 SQL 语句",diff --git a/frontend/src/react/components/CustomApproval/RulesSection.tsx b/frontend/src/react/components/CustomApproval/RulesSection.tsxindex 3130c34680..8bbcffe503 100644--- a/frontend/src/react/components/CustomApproval/RulesSection.tsx+++ b/frontend/src/react/components/CustomApproval/RulesSection.tsx@@ -17,13 +17,15 @@ import {} from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { GripVertical, Pencil, Plus, Trash2 } from "lucide-react";-import { useEffect, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";import {PermissionGuard,usePermissionCheck,} from "@/react/components/PermissionGuard";import { Button } from "@/react/components/ui/button";+import { ColumnResizeHandle } from "@/react/components/ui/column-resize-handle";+import { useColumnWidths } from "@/react/hooks/useColumnWidths";import { pushNotification, useWorkspaceApprovalSettingStore } from "@/store";import type { LocalApprovalRule } from "@/types";import type { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";@@ -44,6 +46,7 @@ function SortableRow({index,allowAdmin,hasFeature,+ gridStyle,onEdit,onDelete,onShowFeatureModal,@@ -52,6 +55,7 @@ function SortableRow({index: number;allowAdmin: boolean;hasFeature: boolean;+ gridStyle: React.CSSProperties;onEdit: (rule: LocalApprovalRule) => void;onDelete: (rule: LocalApprovalRule) => void;onShowFeatureModal: () => void;@@ -69,6 +73,7 @@ function SortableRow({} = useSortable({ id: rule.uid });const style = {+ ...gridStyle,transform: CSS.Transform.toString(transform),transition,opacity: isDragging ? 0.5 : undefined,@@ -99,7 +104,7 @@ function SortableRow({<divref={setNodeRef}style={style}- className={`grid grid-cols-[40px_200px_1fr_280px_140px] border-b border-gray-100 last:border-b-0 hover:bg-gray-50 ${+ className={`grid border-b border-gray-100 last:border-b-0 hover:bg-gray-50 ${index % 2 === 1 ? "bg-gray-50/50" : ""}`}>@@ -165,9 +170,18 @@ function SortableRow({);}-function RuleRowOverlay({ rule }: { rule: LocalApprovalRule }) {+function RuleRowOverlay({+ rule,+ gridStyle,+}: {+ rule: LocalApprovalRule;+ gridStyle: React.CSSProperties;+}) {return (- <div className="grid grid-cols-[40px_200px_1fr_280px_140px] border border-gray-200 bg-blue-50 opacity-50">+ <div+ style={gridStyle}+ className="grid border border-gray-200 bg-blue-50 opacity-50"+ ><div className="flex items-center justify-center px-2 py-2"><GripVertical className="h-4 w-4 text-gray-400" /></div>@@ -204,6 +218,23 @@ export function RulesSection({LocalApprovalRule | undefined>();+ // Only the title and flow columns are resizable; the other three are+ // fixed (40px gripper, flexible content, 140px actions). The shared hook+ // tracks an array of widths positional to its input, so we hand it just+ // the two resizable columns and compose them into the grid template.+ const { widths: resizableWidths, onResizeStart } = useColumnWidths([+ { defaultWidth: 200, minWidth: 80 },+ { defaultWidth: 280, minWidth: 80 },+ ]);+ const [titleWidth, flowWidth] = resizableWidths;++ const gridStyle = useMemo<React.CSSProperties>(+ () => ({+ gridTemplateColumns: `40px ${titleWidth}px minmax(0, 1fr) ${flowWidth}px 140px`,+ }),+ [titleWidth, flowWidth]+ );+const isFallback = source === RuleSource.SOURCE_UNSPECIFIED;const sensors = useSensors(@@ -316,14 +347,21 @@ export function RulesSection({<div className="rounded-sm border border-gray-200 text-sm">{/* Table Header */}- <div className="grid grid-cols-[40px_200px_1fr_280px_140px] border-b border-gray-200 bg-gray-50 font-medium text-gray-600">- <div className="w-10 px-2 py-2" />- <div className="px-3 py-2">{t("common.title")}</div>+ <div+ style={gridStyle}+ className="grid border-b border-gray-200 bg-gray-50 font-medium text-gray-600"+ >+ <div className="px-2 py-2" />+ <div className="relative px-3 py-2">+ {t("common.title")}+ <ColumnResizeHandle onMouseDown={(e) => onResizeStart(0, e)} />+ </div><div className="px-3 py-2">{t("cel.condition.self")}</div>- <div className="px-3 py-2">+ <div className="relative px-3 py-2">{t("custom-approval.approval-flow.self")}+ <ColumnResizeHandle onMouseDown={(e) => onResizeStart(1, e)} /></div>- <div className="w-[140px] px-3 py-2">{t("common.operations")}</div>+ <div className="px-3 py-2">{t("common.operations")}</div></div>{/* Draggable Body */}@@ -344,6 +382,7 @@ export function RulesSection({index={index}allowAdmin={allowAdmin}hasFeature={hasFeature}+ gridStyle={gridStyle}onEdit={handleEditRule}onDelete={handleDeleteRule}onShowFeatureModal={onShowFeatureModal}@@ -351,7 +390,9 @@ export function RulesSection({))}</SortableContext><DragOverlay>- {activeRule ? <RuleRowOverlay rule={activeRule} /> : null}+ {activeRule ? (+ <RuleRowOverlay rule={activeRule} gridStyle={gridStyle} />+ ) : null}</DragOverlay></DndContext>diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxindex 55abd82401..59746d0cc5 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -11,9 +11,12 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),useCurrentUserV1: vi.fn(),- useSQLEditorStore: vi.fn(),+ // Legacy Pinia editor store.+ useSQLEditorPiniaStore: vi.fn(),useSQLEditorTabStore: vi.fn(),- useSQLEditorUIStore: vi.fn(),+ // New zustand setters.+ setAsidePanelTab: vi.fn(),+ setHighlightAccessGrantName: vi.fn(),pushNotification: vi.fn(),useDatabaseV1Store: vi.fn(),createAccessGrant: vi.fn(),@@ -30,13 +33,25 @@ vi.mock("@/react/hooks/useVueState", () => ({vi.mock("@/store", () => ({useCurrentUserV1: mocks.useCurrentUserV1,- useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorStore: mocks.useSQLEditorPiniaStore,useSQLEditorTabStore: mocks.useSQLEditorTabStore,- useSQLEditorUIStore: mocks.useSQLEditorUIStore,pushNotification: mocks.pushNotification,useDatabaseV1Store: mocks.useDatabaseV1Store,}));+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: {+ setAsidePanelTab: (tab: string) => void;+ setHighlightAccessGrantName: (v: string | undefined) => void;+ }) => unknown+ ) =>+ selector({+ setAsidePanelTab: mocks.setAsidePanelTab,+ setHighlightAccessGrantName: mocks.setHighlightAccessGrantName,+ }),+}));+vi.mock("@/connect", () => ({accessGrantServiceClientConnect: {createAccessGrant: mocks.createAccessGrant,@@ -278,7 +293,7 @@ const setupMocks = () => {value: { email: "[email protected]" },});- mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });+ mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/proj1" });mocks.useSQLEditorTabStore.mockReturnValue({currentTab: {@@ -286,12 +301,6 @@ const setupMocks = () => {},});- const uiStore = {- asidePanelTab: "WORKSHEET",- highlightAccessGrantName: undefined,- };- mocks.useSQLEditorUIStore.mockReturnValue(uiStore);-mocks.useDatabaseV1Store.mockReturnValue({fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),});@@ -414,12 +423,6 @@ describe("AccessGrantRequestDrawer", () => {});test("On success ACTIVE without issue → sets asidePanelTab and highlightAccessGrantName", async () => {- const uiStore = {- asidePanelTab: "WORKSHEET",- highlightAccessGrantName: undefined as string | undefined,- };- mocks.useSQLEditorUIStore.mockReturnValue(uiStore);-const mockResponse = {status: 2, // ACTIVEissue: "",@@ -461,10 +464,14 @@ describe("AccessGrantRequestDrawer", () => {submitBtn.click();});- // After submit: check pushNotification was called+ // After submit: check pushNotification was called and zustand setters were invokedexpect(mocks.pushNotification).toHaveBeenCalledWith(expect.objectContaining({ style: "SUCCESS" }));+ expect(mocks.setAsidePanelTab).toHaveBeenCalledWith("ACCESS");+ expect(mocks.setHighlightAccessGrantName).toHaveBeenCalledWith(+ "projects/proj1/accessGrants/grant-xyz"+ );expect(onClose).toHaveBeenCalled();unmount();});diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex 965ceef415..96be47e26c 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -20,15 +20,15 @@ import {} from "@/react/components/ui/sheet";import { Textarea } from "@/react/components/ui/textarea";import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";import {pushNotification,useCurrentUserV1,useDatabaseV1Store,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import {AccessGrant_Status,@@ -111,9 +111,12 @@ function AccessGrantRequestDrawerInner({}: AccessGrantRequestDrawerInnerProps) {const { t } = useTranslation();const currentUser = useCurrentUserV1();- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);+ const setHighlightAccessGrantName = useSQLEditorStore(+ (s) => s.setHighlightAccessGrantName+ );const currentUserEmail = useVueState(() => currentUser.value.email);const project = useVueState(() => editorStore.project);@@ -220,8 +223,8 @@ function AccessGrantRequestDrawerInner({});window.open(route.fullPath, "_blank");} else {- uiStore.asidePanelTab = "ACCESS";- uiStore.highlightAccessGrantName = response.name;+ setAsidePanelTab("ACCESS");+ setHighlightAccessGrantName(response.name);}onClose();} finally {diff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsxindex db4660ab5f..da45bd4b9a 100644--- a/frontend/src/react/components/sql-editor/AccessPane.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx@@ -11,9 +11,14 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),useProjectV1Store: vi.fn(),- useSQLEditorStore: vi.fn(),+ // Legacy Pinia editor store.+ useSQLEditorPiniaStore: vi.fn(),useSQLEditorTabStore: vi.fn(),- useSQLEditorUIStore: vi.fn(),+ // New zustand store state + setter.+ state: {+ highlightAccessGrantName: undefined as string | undefined,+ },+ setHighlightAccessGrantName: vi.fn(),useAccessGrantStore: vi.fn(),useIssueV1Store: vi.fn(),useDatabaseV1Store: vi.fn(),@@ -32,15 +37,35 @@ vi.mock("@/react/hooks/useVueState", () => ({vi.mock("@/store", () => ({useProjectV1Store: mocks.useProjectV1Store,- useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorStore: mocks.useSQLEditorPiniaStore,useSQLEditorTabStore: mocks.useSQLEditorTabStore,- useSQLEditorUIStore: mocks.useSQLEditorUIStore,useAccessGrantStore: mocks.useAccessGrantStore,useIssueV1Store: mocks.useIssueV1Store,useDatabaseV1Store: mocks.useDatabaseV1Store,hasFeature: mocks.hasFeature,}));+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: Object.assign(+ (+ selector: (s: {+ highlightAccessGrantName: string | undefined;+ setHighlightAccessGrantName: (v: string | undefined) => void;+ }) => unknown+ ) =>+ selector({+ highlightAccessGrantName: mocks.state.highlightAccessGrantName,+ setHighlightAccessGrantName: mocks.setHighlightAccessGrantName,+ }),+ {+ getState: () => ({+ highlightAccessGrantName: mocks.state.highlightAccessGrantName,+ setHighlightAccessGrantName: mocks.setHighlightAccessGrantName,+ }),+ }+ ),+}));+vi.mock("@/store/modules/accessGrant", () => ({}));vi.mock("@/utils", () => ({@@ -206,16 +231,12 @@ const setupDefaultMocks = () => {})),});- mocks.useSQLEditorStore.mockReturnValue({ project: "projects/proj1" });+ mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/proj1" });mocks.useSQLEditorTabStore.mockReturnValue({currentTab: { connection: { database: "instances/inst1/databases/db1" } },});- const uiStore = {- asidePanelTab: "ACCESS",- highlightAccessGrantName: undefined as string | undefined,- };- mocks.useSQLEditorUIStore.mockReturnValue(uiStore);+ mocks.state.highlightAccessGrantName = undefined;mocks.useAccessGrantStore.mockReturnValue({searchMyAccessGrants: vi.fn().mockResolvedValue({diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxindex 51cbf47c43..8353982dc9 100644--- a/frontend/src/react/components/sql-editor/AccessPane.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -17,14 +17,14 @@ 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 { useSQLEditorStore } from "@/react/stores/sqlEditor";import {hasFeature,useAccessGrantStore,useDatabaseV1Store,useIssueV1Store,useProjectV1Store,- useSQLEditorStore,- useSQLEditorUIStore,+ useSQLEditorStore as useSQLEditorPiniaStore,} from "@/store";import type { AccessFilter } from "@/store/modules/accessGrant";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";@@ -48,11 +48,16 @@ export function AccessPane() {const { t } = useTranslation();const projectStore = useProjectV1Store();- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const accessGrantStore = useAccessGrantStore();const issueStore = useIssueV1Store();const databaseStore = useDatabaseV1Store();- const uiStore = useSQLEditorUIStore();+ const highlightAccessGrantName = useSQLEditorStore(+ (s) => s.highlightAccessGrantName+ );+ const setHighlightAccessGrantName = useSQLEditorStore(+ (s) => s.setHighlightAccessGrantName+ );const [showDrawer, setShowDrawer] = useState(false);const [loading, setLoading] = useState(false);@@ -76,9 +81,6 @@ export function AccessPane() {});const projectName = useVueState(() => editorStore.project);- const highlightAccessGrantName = useVueState(- () => uiStore.highlightAccessGrantName- );const project = useMemo(() => {if (!projectName) return undefined;@@ -228,8 +230,8 @@ export function AccessPane() {if (!name) return;void fetchAccessGrants(true);const timer = setTimeout(() => {- if (uiStore.highlightAccessGrantName === name) {- uiStore.highlightAccessGrantName = undefined;+ if (useSQLEditorStore.getState().highlightAccessGrantName === name) {+ setHighlightAccessGrantName(undefined);}}, 3000);return () => clearTimeout(timer);diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsxindex 425f505260..c68abc4004 100644--- a/frontend/src/react/components/sql-editor/AsidePanel.tsx+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx@@ -2,13 +2,13 @@ import { useCallback } from "react";import { useTranslation } from "react-i18next";import { ProjectSelect } from "@/react/components/ProjectSelect";import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import {useActuatorV1Store,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,useSQLEditorWorksheetStore,} from "@/store";import { defaultProject, isValidProjectName } from "@/types";@@ -36,13 +36,12 @@ import { WorksheetPane } from "./WorksheetPane";*/export function AsidePanel() {const { t } = useTranslation();- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const actuatorStore = useActuatorV1Store();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();const worksheetStore = useSQLEditorWorksheetStore();- const asidePanelTab = useVueState(() => uiStore.asidePanelTab);+ const asidePanelTab = useSQLEditorStore((s) => s.asidePanelTab);const isDisconnected = useVueState(() => tabStore.isDisconnected);const project = useVueState(() => editorStore.project);const projectContextReady = useVueState(diff --git a/frontend/src/react/components/sql-editor/ConnectionHolder.test.tsx b/frontend/src/react/components/sql-editor/ConnectionHolder.test.tsxindex 9e6e9baf6b..1e4272115e 100644--- a/frontend/src/react/components/sql-editor/ConnectionHolder.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionHolder.test.tsx@@ -9,15 +9,16 @@ import { beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useSQLEditorUIStore: vi.fn(),+ setShowConnectionPanel: vi.fn(),+ useSQLEditorStore: vi.fn(),}));vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/store", () => ({- useSQLEditorUIStore: mocks.useSQLEditorUIStore,+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: mocks.useSQLEditorStore,}));let ConnectionHolder: typeof import("./ConnectionHolder").ConnectionHolder;@@ -44,13 +45,19 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();+ // The component selects `s.setShowConnectionPanel` from the store; the+ // mock invokes the supplied selector against a stub state.+ mocks.useSQLEditorStore.mockImplementation(+ (selector: (s: { setShowConnectionPanel: typeof vi.fn }) => unknown) =>+ selector({+ setShowConnectionPanel: mocks.setShowConnectionPanel,+ })+ );({ ConnectionHolder } = await import("./ConnectionHolder"));});describe("ConnectionHolder", () => {test("renders the Connect-to-database label", () => {- const store = { showConnectionPanel: false };- mocks.useSQLEditorUIStore.mockReturnValue(store);const { container, render, unmount } = renderIntoContainer(<ConnectionHolder />);@@ -60,9 +67,7 @@ describe("ConnectionHolder", () => {unmount();});- test("click sets showConnectionPanel to true on the store", () => {- const store = { showConnectionPanel: false };- mocks.useSQLEditorUIStore.mockReturnValue(store);+ test("click invokes setShowConnectionPanel(true)", () => {const { container, render, unmount } = renderIntoContainer(<ConnectionHolder />);@@ -71,7 +76,7 @@ describe("ConnectionHolder", () => {act(() => {button?.click();});- expect(store.showConnectionPanel).toBe(true);+ expect(mocks.setShowConnectionPanel).toHaveBeenCalledWith(true);unmount();});});diff --git a/frontend/src/react/components/sql-editor/ConnectionHolder.tsx b/frontend/src/react/components/sql-editor/ConnectionHolder.tsxindex c3358f89c6..ab7a5011e1 100644--- a/frontend/src/react/components/sql-editor/ConnectionHolder.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionHolder.tsx@@ -1,7 +1,7 @@import { LinkIcon } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";-import { useSQLEditorUIStore } from "@/store";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";/*** Replaces frontend/src/views/sql-editor/EditorCommon/ConnectionHolder.vue.@@ -11,10 +11,12 @@ import { useSQLEditorUIStore } from "@/store";*/export function ConnectionHolder() {const { t } = useTranslation();- const uiStore = useSQLEditorUIStore();+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );const handleClick = () => {- uiStore.showConnectionPanel = true;+ setShowConnectionPanel(true);};return (diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsxindex 511f2cb45b..e11d15c57b 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx@@ -121,7 +121,17 @@ vi.mock("@/store", () => ({useSQLEditorStore: () => mocks.editorStore,useSQLEditorTabStore: () => mocks.tabStore,useSQLEditorTreeStore: () => mocks.treeStore,- useSQLEditorUIStore: () => mocks.uiStore,+}));++vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: { setShowConnectionPanel: (v: boolean) => void }) => unknown+ ) =>+ selector({+ setShowConnectionPanel: (next: boolean) => {+ mocks.uiStore.showConnectionPanel = next;+ },+ }),}));vi.mock("@/store/modules", () => ({diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsxindex 4bfe87a9a1..cb52bb7394 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx@@ -25,6 +25,7 @@ import { countVisibleRows } from "@/react/components/ui/tree-utils";import { useCommonSearchScopeOptions } from "@/react/components/useCommonSearchScopeOptions";import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {featureToRef,pushNotification,@@ -34,10 +35,9 @@ import {useEnvironmentV1Store,useInstanceV1Store,useProjectV1Store,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,useSQLEditorTreeStore,- useSQLEditorUIStore,} from "@/store";import { instanceNamePrefix } from "@/store/modules/v1/common";import type { DatabaseFilter } from "@/store/modules/v1/database";@@ -140,8 +140,10 @@ function ConnectionPaneWithHoverState(props: Props) {function ConnectionPaneInner({ show, onMissingFeature }: Props) {const { t } = useTranslation();const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorStore();- const uiStore = useSQLEditorUIStore();+ const editorStore = useSQLEditorPiniaStore();+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );const databaseStore = useDatabaseV1Store();const dbGroupStore = useDBGroupStore();const environmentStore = useEnvironmentV1Store();@@ -410,9 +412,9 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {// connection AND closes the drawer. Without this the drawer stays// open and the user can't see the schema panel underneath, so// subsequent re-clicks look like nothing happened.- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);},- [selectedDatabaseGroupNames, currentTab?.mode, uiStore]+ [selectedDatabaseGroupNames, currentTab?.mode, setShowConnectionPanel]);const onBatchQueryContextChange = useCallback(@@ -482,7 +484,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {});const ok = await onBatchQueryContextChange(ctx);if (ok) {- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);} else {pushNotification({module: "bytebase",@@ -491,7 +493,12 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {});}},- [currentTab?.batchQueryContext, onBatchQueryContextChange, uiStore, t]+ [+ currentTab?.batchQueryContext,+ onBatchQueryContextChange,+ setShowConnectionPanel,+ t,+ ]);const handleSelectedGroupsChange = useCallback(diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsxindex 5a2455859c..ab8729ca2a 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({useVueState: vi.fn<(getter: () => unknown) => unknown>(),allowAdmin: false,sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),+ setShowConnectionPanel: vi.fn(),+ setAsidePanelTab: vi.fn(),}));vi.mock("react-i18next", () => ({@@ -23,10 +25,6 @@ vi.mock("@/react/hooks/useVueState", () => ({vi.mock("@/store", () => ({useSQLEditorStore: () => ({ allowAdmin: mocks.allowAdmin }),- useSQLEditorUIStore: () => ({- showConnectionPanel: true,- asidePanelTab: "SCHEMA",- }),useSQLEditorTabStore: () => ({ currentTab: null }),useSQLEditorWorksheetStore: () => ({createWorksheet: vi.fn().mockResolvedValue(undefined),@@ -34,6 +32,22 @@ vi.mock("@/store", () => ({}),}));+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: Object.assign(+ (+ selector: (s: { setShowConnectionPanel: (v: boolean) => void }) => unknown+ ) =>+ selector({+ setShowConnectionPanel: mocks.setShowConnectionPanel,+ }),+ {+ getState: () => ({+ setAsidePanelTab: mocks.setAsidePanelTab,+ }),+ }+ ),+}));+vi.mock("@/router", () => ({router: { resolve: vi.fn(() => ({ href: "/x" })) },}));diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsxindex 2cdfd5d8b0..fa278a9049 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx@@ -7,12 +7,12 @@ import {import { useCallback, useMemo } from "react";import { useTranslation } from "react-i18next";import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";import {- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,useSQLEditorWorksheetStore,} from "@/store";import type {@@ -72,7 +72,6 @@ export function setConnection(options: {};const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();const worksheetStore = useSQLEditorWorksheetStore();const batchQueryContext: BatchQueryContext = Object.assign(@@ -99,7 +98,7 @@ export function setConnection(options: {void createOrUpdate().then((tab) => {if (tab) {tabStore.updateTab(tab.id, { mode, batchQueryContext });- uiStore.asidePanelTab = "SCHEMA";+ useSQLEditorStore.getState().setAsidePanelTab("SCHEMA");}});}@@ -111,8 +110,10 @@ export function setConnection(options: {*/export function useConnectionMenu(node: SQLEditorTreeNode | null) {const { t } = useTranslation();- const editorStore = useSQLEditorStore();- const uiStore = useSQLEditorUIStore();+ const editorStore = useSQLEditorPiniaStore();+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );const allowAdmin = useVueState(() => editorStore.allowAdmin);const items = useMemo<ConnectionMenuItem[]>(() => {@@ -131,7 +132,7 @@ export function useConnectionMenu(node: SQLEditorTreeNode | null) {icon: <LinkIcon className="size-4" />,onSelect: () => {setConnection({ database, newTab: false });- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);},});out.push({@@ -140,7 +141,7 @@ export function useConnectionMenu(node: SQLEditorTreeNode | null) {icon: <LinkIcon className="size-4" />,onSelect: () => {setConnection({ database, newTab: true });- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);},});}@@ -151,7 +152,7 @@ export function useConnectionMenu(node: SQLEditorTreeNode | null) {icon: <Wrench className="size-4" />,onSelect: () => {setConnection({ database, mode: "ADMIN", newTab: false });- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);},});}@@ -189,13 +190,13 @@ export function useConnectionMenu(node: SQLEditorTreeNode | null) {schema: "",table: "",});- uiStore.showConnectionPanel = false;+ setShowConnectionPanel(false);},});}}return out;- }, [node, allowAdmin, t, uiStore]);+ }, [node, allowAdmin, t, setShowConnectionPanel]);const handleSelect = useCallback((key: ActionKey) => {diff --git a/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsxindex 7cb7be39eb..7af7c7f709 100644--- a/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPanel.test.tsx@@ -7,12 +7,15 @@ import { beforeEach, describe, expect, test, vi } from "vitest";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => {- const uiStore = { showConnectionPanel: false };+ const state = { showConnectionPanel: false };+ const setShowConnectionPanel = (next: boolean) => {+ state.showConnectionPanel = next;+ };return {- uiStore,+ state,+ setShowConnectionPanel,hasWorkspacePermissionV2: vi.fn(),routerPush: vi.fn(),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),};});@@ -28,12 +31,17 @@ vi.mock("@/router/dashboard/workspaceRoutes", () => ({INSTANCE_ROUTE_DASHBOARD: "workspace.instance",}));-vi.mock("@/store", () => ({- useSQLEditorUIStore: () => mocks.uiStore,-}));--vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: {+ showConnectionPanel: boolean;+ setShowConnectionPanel: (v: boolean) => void;+ }) => unknown+ ) =>+ selector({+ showConnectionPanel: mocks.state.showConnectionPanel,+ setShowConnectionPanel: mocks.setShowConnectionPanel,+ }),}));vi.mock("@/utils", () => ({@@ -134,15 +142,14 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.uiStore.showConnectionPanel = false;- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.state.showConnectionPanel = false;mocks.hasWorkspacePermissionV2.mockReturnValue(true);({ ConnectionPanel } = await import("./ConnectionPanel"));});describe("ConnectionPanel", () => {test("renders nothing when uiStore.showConnectionPanel is false", () => {- mocks.uiStore.showConnectionPanel = false;+ mocks.state.showConnectionPanel = false;const { container, render, unmount } = renderIntoContainer(<ConnectionPanel />);@@ -152,7 +159,7 @@ describe("ConnectionPanel", () => {});test("renders header + ConnectionPane when uiStore.showConnectionPanel is true", () => {- mocks.uiStore.showConnectionPanel = true;+ mocks.state.showConnectionPanel = true;const { container, render, unmount } = renderIntoContainer(<ConnectionPanel />);@@ -169,7 +176,7 @@ describe("ConnectionPanel", () => {});test("settings button navigates without closing the drawer (matches Vue)", () => {- mocks.uiStore.showConnectionPanel = true;+ mocks.state.showConnectionPanel = true;const { container, render, unmount } = renderIntoContainer(<ConnectionPanel />);@@ -183,7 +190,7 @@ describe("ConnectionPanel", () => {});// Drawer state is left untouched — the route change unmounts the SQL// editor anyway, and pre-closing introduced an unnecessary transition.- expect(mocks.uiStore.showConnectionPanel).toBe(true);+ expect(mocks.state.showConnectionPanel).toBe(true);expect(mocks.routerPush).toHaveBeenCalledWith({name: "workspace.instance",});@@ -191,7 +198,7 @@ describe("ConnectionPanel", () => {});test("hides settings button when user lacks bb.instances.list permission", () => {- mocks.uiStore.showConnectionPanel = true;+ mocks.state.showConnectionPanel = true;mocks.hasWorkspacePermissionV2.mockReturnValue(false);const { container, render, unmount } = renderIntoContainer(<ConnectionPanel />@@ -204,7 +211,7 @@ describe("ConnectionPanel", () => {});test("sheet-close writes uiStore.showConnectionPanel = false", () => {- mocks.uiStore.showConnectionPanel = true;+ mocks.state.showConnectionPanel = true;const { container, render, unmount } = renderIntoContainer(<ConnectionPanel />);@@ -215,7 +222,7 @@ describe("ConnectionPanel", () => {act(() => {closer.dispatchEvent(new MouseEvent("click", { bubbles: true }));});- expect(mocks.uiStore.showConnectionPanel).toBe(false);+ expect(mocks.state.showConnectionPanel).toBe(false);unmount();});});diff --git a/frontend/src/react/components/sql-editor/ConnectionPanel.tsx b/frontend/src/react/components/sql-editor/ConnectionPanel.tsxindex 7474a6171f..8b175983c8 100644--- a/frontend/src/react/components/sql-editor/ConnectionPanel.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPanel.tsx@@ -11,11 +11,10 @@ import {SheetTitle,} from "@/react/components/ui/sheet";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";-import { useSQLEditorUIStore } from "@/store";import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { hasWorkspacePermissionV2 } from "@/utils";import { ConnectionPane } from "./ConnectionPane/ConnectionPane";@@ -23,8 +22,8 @@ import { ConnectionPane } from "./ConnectionPane/ConnectionPane";/*** Replaces frontend/src/views/sql-editor/ConnectionPanel/ConnectionPanel.vue.* Right-side Sheet hosting the `ConnectionPane`. The open/close state is- * read directly from `useSQLEditorUIStore().showConnectionPanel` via- * `useVueState` rather than passed through `<ReactPageMount>` props —+ * read directly from `useSQLEditorStore(s => s.showConnectionPanel)`+ * rather than passed through `<ReactPageMount>` props —* funneling boolean state through Vue→React attrs proved brittle (Vue's* template compiler doesn't auto-translate `(v) => (ref = v)` into* `.value = v` outside of `v-model`, and concurrent renders can leave the@@ -37,8 +36,10 @@ import { ConnectionPane } from "./ConnectionPane/ConnectionPane";*/export function ConnectionPanel() {const { t } = useTranslation();- const uiStore = useSQLEditorUIStore();- const open = useVueState(() => uiStore.showConnectionPanel);+ const open = useSQLEditorStore((s) => s.showConnectionPanel);+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );const allowManageInstance = hasWorkspacePermissionV2("bb.instances.list");// Hoisted from ConnectionPaneInner so the FeatureModal portal mounts as// a SIBLING of the drawer Sheet rather than a descendant. With both at@@ -59,7 +60,7 @@ export function ConnectionPanel() {eventDetails.cancel?.();return;}- uiStore.showConnectionPanel = next;+ setShowConnectionPanel(next);};return (diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsxindex 150041c24a..c706716294 100644--- a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx@@ -11,9 +11,11 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),useSQLEditorTabStore: vi.fn(),- useSQLEditorStore: vi.fn(),- useSQLEditorUIStore: vi.fn(),+ // Legacy Pinia useSQLEditorStore (editor.ts).+ useSQLEditorPiniaStore: vi.fn(),useConnectionOfCurrentSQLEditorTab: vi.fn(),+ // New zustand store setter.+ setShowConnectionPanel: vi.fn(),isValidInstanceName: vi.fn(),isValidDatabaseName: vi.fn(),extractDatabaseResourceName: vi.fn(),@@ -32,11 +34,19 @@ vi.mock("@/react/hooks/useVueState", () => ({vi.mock("@/store", () => ({useSQLEditorTabStore: mocks.useSQLEditorTabStore,- useSQLEditorStore: mocks.useSQLEditorStore,- useSQLEditorUIStore: mocks.useSQLEditorUIStore,+ useSQLEditorStore: mocks.useSQLEditorPiniaStore,useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,}));+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: { setShowConnectionPanel: (v: boolean) => void }) => unknown+ ) =>+ selector({+ setShowConnectionPanel: mocks.setShowConnectionPanel,+ }),+}));+vi.mock("@/types", () => ({isValidInstanceName: mocks.isValidInstanceName,isValidDatabaseName: mocks.isValidDatabaseName,@@ -102,8 +112,7 @@ beforeEach(async () => {currentTab: { id: "tab1" },isInBatchMode: false,});- mocks.useSQLEditorStore.mockReturnValue({ projectContextReady: true });- mocks.useSQLEditorUIStore.mockReturnValue({ showConnectionPanel: false });+ mocks.useSQLEditorPiniaStore.mockReturnValue({ projectContextReady: true });mocks.isValidInstanceName.mockReturnValue(true);mocks.isValidDatabaseName.mockReturnValue(true);mocks.getInstanceResource.mockReturnValue(mockInstance);@@ -149,7 +158,9 @@ describe("DatabaseChooser", () => {});test("button is disabled when projectContextReady is false", () => {- mocks.useSQLEditorStore.mockReturnValue({ projectContextReady: false });+ mocks.useSQLEditorPiniaStore.mockReturnValue({+ projectContextReady: false,+ });const { container, render, unmount } = renderIntoContainer(<DatabaseChooser />);@@ -159,9 +170,7 @@ describe("DatabaseChooser", () => {unmount();});- test("click sets showConnectionPanel to true on UI store", () => {- const uiStore = { showConnectionPanel: false };- mocks.useSQLEditorUIStore.mockReturnValue(uiStore);+ test("click invokes setShowConnectionPanel(true)", () => {const { container, render, unmount } = renderIntoContainer(<DatabaseChooser />);@@ -169,7 +178,7 @@ describe("DatabaseChooser", () => {act(() => {container.querySelector("button")?.click();});- expect(uiStore.showConnectionPanel).toBe(true);+ expect(mocks.setShowConnectionPanel).toHaveBeenCalledWith(true);unmount();});});diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.tsxindex eb6938ad14..5a86e37e51 100644--- a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx@@ -5,11 +5,11 @@ import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { Tooltip } from "@/react/components/ui/tooltip";import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {useConnectionOfCurrentSQLEditorTab,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import { isValidDatabaseName, isValidInstanceName } from "@/types";import {@@ -30,8 +30,10 @@ type DatabaseChooserProps = {export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {const { t } = useTranslation();const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorStore();- const uiStore = useSQLEditorUIStore();+ const editorStore = useSQLEditorPiniaStore();+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );const connection = useConnectionOfCurrentSQLEditorTab();const currentTab = useVueState(() => tabStore.currentTab);@@ -51,7 +53,7 @@ export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {isValidDatabaseName(database.name);const handleClick = () => {- uiStore.showConnectionPanel = true;+ setShowConnectionPanel(true);};return (diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsxindex b4503e41d6..6d86b6ef66 100644--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx@@ -10,9 +10,15 @@ import { beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorStore: vi.fn(),+ // Pinia legacy useSQLEditorStore (editor.ts) — still imported by GutterBar+ // until that store is migrated.+ useSQLEditorPiniaStore: vi.fn(),useProjectV1Store: vi.fn(),- useSQLEditorUIStore: vi.fn(),+ // New zustand store.+ state: {+ asidePanelTab: "WORKSHEET" as string,+ },+ setAsidePanelTab: vi.fn(),routerResolve: vi.fn(() => ({ href: "/project/test-project" })),}));@@ -25,9 +31,21 @@ vi.mock("@/react/hooks/useVueState", () => ({}));vi.mock("@/store", () => ({- useSQLEditorStore: mocks.useSQLEditorStore,+ useSQLEditorStore: mocks.useSQLEditorPiniaStore,useProjectV1Store: mocks.useProjectV1Store,- useSQLEditorUIStore: mocks.useSQLEditorUIStore,+}));++vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: {+ asidePanelTab: string;+ setAsidePanelTab: (tab: string) => void;+ }) => unknown+ ) =>+ selector({+ asidePanelTab: mocks.state.asidePanelTab,+ setAsidePanelTab: mocks.setAsidePanelTab,+ }),}));vi.mock("@/router", () => ({@@ -77,11 +95,11 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.useSQLEditorStore.mockReturnValue({ project: "projects/test" });+ mocks.useSQLEditorPiniaStore.mockReturnValue({ project: "projects/test" });mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});- mocks.useSQLEditorUIStore.mockReturnValue({ asidePanelTab: "WORKSHEET" });+ mocks.state.asidePanelTab = "WORKSHEET";mocks.routerResolve.mockReturnValue({ href: "/workspace/home" });({ GutterBar } = await import("./GutterBar"));});@@ -111,20 +129,18 @@ describe("GutterBar", () => {unmount();});- test("click writes asidePanelTab on the store", () => {+ test("click writes asidePanelTab via setAsidePanelTab", () => {mocks.useVueState.mockImplementation((getter) => getter());mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});- const store = { asidePanelTab: "WORKSHEET" as string };- mocks.useSQLEditorUIStore.mockReturnValue(store);const { container, render, unmount } = renderIntoContainer(<GutterBar />);render();const buttons = container.querySelectorAll("button");act(() => {(buttons[1] as HTMLButtonElement).click();});- expect(store.asidePanelTab).toBe("SCHEMA");+ expect(mocks.setAsidePanelTab).toHaveBeenCalledWith("SCHEMA");unmount();});diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsxindex 4dd911dc91..76dbfb10ac 100644--- a/frontend/src/react/components/sql-editor/GutterBar.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx@@ -1,14 +1,14 @@import logoIcon from "@/assets/logo-icon.svg";import { Separator } from "@/react/components/ui/separator";import { useVueState } from "@/react/hooks/useVueState";+import type { AsidePanelTab } from "@/react/stores/sqlEditor";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";import {- type AsidePanelTab,useProjectV1Store,- useSQLEditorStore,- useSQLEditorUIStore,+ useSQLEditorStore as useSQLEditorPiniaStore,} from "@/store";import { TabItem } from "./TabItem";@@ -20,9 +20,9 @@ import { TabItem } from "./TabItem";* Replaces frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue.*/export function GutterBar() {- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const projectStore = useProjectV1Store();- const uiStore = useSQLEditorUIStore();+ const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const project = useVueState(() => {const name = editorStore.project;@@ -41,7 +41,7 @@ export function GutterBar() {: router.resolve({ name: WORKSPACE_ROUTE_LANDING }).href;const handleClickTab = (target: AsidePanelTab) => {- uiStore.asidePanelTab = target;+ setAsidePanelTab(target);};return (diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsxindex fbd3683f09..0fd7c14701 100644--- a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx@@ -12,7 +12,11 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),useVueState: vi.fn<(getter: () => unknown) => unknown>(),useSQLEditorTabStore: vi.fn(),- useSQLEditorUIStore: vi.fn(),+ // New zustand state mirror.+ state: { showAIPanel: false },+ setShowAIPanel: vi.fn((v: boolean) => {+ mocks.state.showAIPanel = v;+ }),useSettingV1Store: vi.fn(),useConnectionOfCurrentSQLEditorTab: vi.fn(),hasWorkspacePermissionV2: vi.fn(() => true),@@ -33,11 +37,23 @@ vi.mock("@/react/hooks/useVueState", () => ({vi.mock("@/store", () => ({useSQLEditorTabStore: mocks.useSQLEditorTabStore,- useSQLEditorUIStore: mocks.useSQLEditorUIStore,useSettingV1Store: mocks.useSettingV1Store,useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,}));+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: (+ selector: (s: {+ showAIPanel: boolean;+ setShowAIPanel: (v: boolean) => void;+ }) => unknown+ ) =>+ selector({+ showAIPanel: mocks.state.showAIPanel,+ setShowAIPanel: mocks.setShowAIPanel,+ }),+}));+vi.mock("@/utils", () => ({hasWorkspacePermissionV2: mocks.hasWorkspacePermissionV2,nextAnimationFrame: mocks.nextAnimationFrame,@@ -177,7 +193,7 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {...overrides,};- const uiStore = { showAIPanel: values.showAIPanel };+ mocks.state.showAIPanel = values.showAIPanel;const tabStore = {isDisconnected: values.isDisconnected,currentTab: { mode: values.currentMode },@@ -188,24 +204,23 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {};mocks.useSQLEditorTabStore.mockReturnValue(tabStore);- mocks.useSQLEditorUIStore.mockReturnValue(uiStore);mocks.useSettingV1Store.mockReturnValue(settingStore);mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({instance: { value: values.instance },});- // Order of useVueState calls: isDisconnected, currentMode, showAIPanel, instance, openAIEnabled+ // useVueState order after migration: isDisconnected, currentMode,+ // instance, openAIEnabled (showAIPanel now read via zustand selector).const ordered = [values.isDisconnected,values.currentMode,- values.showAIPanel,values.instance,values.openAIEnabled,];let idx = 0;mocks.useVueState.mockImplementation(() => ordered[idx++]);- return { uiStore, tabStore, settingStore };+ return { tabStore, settingStore };};beforeEach(async () => {@@ -260,7 +275,7 @@ describe("OpenAIButton", () => {});test("click toggles showAIPanel when enabled", () => {- const { uiStore } = setupDefaultMocks();+ setupDefaultMocks();const { container, render, unmount } = renderIntoContainer(<OpenAIButton />);@@ -275,13 +290,13 @@ describe("OpenAIButton", () => {button?.click();});- expect(uiStore.showAIPanel).toBe(true);+ expect(mocks.setShowAIPanel).toHaveBeenCalledWith(true);unmount();});test("selecting explain-code action emits send-chat with prompt", async () => {- const { uiStore } = setupDefaultMocks();+ setupDefaultMocks();const { container, render, unmount } = renderIntoContainer(<OpenAIButton statement="SELECT 1" />);@@ -298,7 +313,7 @@ describe("OpenAIButton", () => {explainItem?.click();});- expect(uiStore.showAIPanel).toBe(true);+ expect(mocks.setShowAIPanel).toHaveBeenCalledWith(true);expect(mocks.explainCode).toHaveBeenCalledWith("SELECT 1", Engine.POSTGRES);expect(mocks.emit).toHaveBeenCalledWith("send-chat", {content: "EXPLAIN:SELECT 1",diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsxindex 6e413d9a9c..bfafdf28e2 100644--- a/frontend/src/react/components/sql-editor/OpenAIButton.tsx+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx@@ -17,13 +17,13 @@ import {} from "@/react/components/ui/popover";import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";import {useConnectionOfCurrentSQLEditorTab,useSettingV1Store,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";import { hasWorkspacePermissionV2, nextAnimationFrame } from "@/utils";@@ -50,7 +50,8 @@ type Props = {export function OpenAIButton({ actions, statement, size = "default" }: Props) {const { t } = useTranslation();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);+ const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);const settingV1Store = useSettingV1Store();const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();@@ -64,7 +65,6 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {const isDisconnected = useVueState(() => tabStore.isDisconnected);const currentMode = useVueState(() => tabStore.currentTab?.mode);- const showAIPanel = useVueState(() => uiStore.showAIPanel);const instance = useVueState(() => instanceRef.value);const openAIEnabled = useVueState(() => {const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);@@ -99,7 +99,7 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {);const handleToggle = () => {- uiStore.showAIPanel = !uiStore.showAIPanel;+ setShowAIPanel(!showAIPanel);};// ---- Disabled state: AI feature not configured ---------------------------@@ -122,7 +122,7 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {const handleSelect = async (action: ChatAction) => {setMenuOpen(false);const newChat = !showAIPanel;- uiStore.showAIPanel = true;+ setShowAIPanel(true);if (!statement) return;await nextAnimationFrame();diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsxindex 3f84c3246e..95c01cfccf 100644--- a/frontend/src/react/components/sql-editor/Panels/Panels.tsx+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx@@ -6,6 +6,7 @@ import {Group as PanelGroup,Separator as PanelResizeHandle,} from "react-resizable-panels";+import { useShallow } from "zustand/react/shallow";import { useExecuteSQL } from "@/composables/useExecuteSQL";import { aiContextEvents } from "@/plugins/ai/logic";import { AIChatToSQL, AIContextProvider } from "@/plugins/ai/react";@@ -26,12 +27,15 @@ import { TriggersPanel } from "@/react/components/sql-editor/TriggersPanel";import { ViewsPanel } from "@/react/components/sql-editor/ViewsPanel";import { Alert } from "@/react/components/ui/alert";import { useVueState } from "@/react/hooks/useVueState";+import {+ selectEditorPanelSize,+ useSQLEditorStore,+} from "@/react/stores/sqlEditor";import {useConnectionOfCurrentSQLEditorTab,useDatabaseV1Store,useDBSchemaV1Store,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import { isValidDatabaseName } from "@/types";import {@@ -71,7 +75,9 @@ const AIPaneFallback = () => (export function Panels() {const { t } = useTranslation();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const handleEditorPanelResize = useSQLEditorStore(+ (s) => s.handleEditorPanelResize+ );const dbSchemaStore = useDBSchemaV1Store();const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();@@ -85,9 +91,9 @@ export function Panels() {const tabMode = useVueState(() => tabStore.currentTab?.mode);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 showAIPanel = useSQLEditorStore((s) => s.showAIPanel);+ const isShowingCode = useSQLEditorStore((s) => s.isShowingCode);+ const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));const showAIPaneAlongsidePanel = showAIPanel && isShowingCode;const { setSchema, updateViewState } = useViewStateNav();@@ -184,7 +190,7 @@ export function Panels() {const handleAiResize = (sizePct: number) => {if (!Number.isFinite(sizePct)) return;- uiStore.handleEditorPanelResize(sizePct / 100);+ handleEditorPanelResize(sizePct / 100);};return (diff --git a/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx b/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsxindex 937d2f62df..da79d3d930 100644--- a/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/CodeViewer.tsx@@ -17,7 +17,7 @@ import type { MonacoModule } from "@/react/components/monaco/types";import { Button } from "@/react/components/ui/button";import { Checkbox } from "@/react/components/ui/checkbox";import { cn } from "@/react/lib/utils";-import { useSQLEditorUIStore } from "@/store";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { dialectOfEngineV1 } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import {@@ -62,7 +62,8 @@ export function CodeViewer({headerClassName,}: CodeViewerProps) {const { t } = useTranslation();- const uiStore = useSQLEditorUIStore();+ const setIsShowingCode = useSQLEditorStore((s) => s.setIsShowingCode);+ const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);const [format, setFormat] = useState<boolean>(() => {if (typeof window === "undefined") return false;@@ -116,16 +117,16 @@ export function CodeViewer({// mounted. Cleared on unmount so navigating back to the list view drops// the pane (matches Vue CodeViewer's auto-unmount on detail-clear).useEffect(() => {- uiStore.isShowingCode = true;+ setIsShowingCode(true);return () => {- uiStore.isShowingCode = false;+ setIsShowingCode(false);};- }, [uiStore]);+ }, [setIsShowingCode]);const handleAIAction = useCallback((action: ChatAction) => {- const newChat = !uiStore.showAIPanel;- uiStore.showAIPanel = true;+ const newChat = !useSQLEditorStore.getState().showAIPanel;+ setShowAIPanel(true);if (action !== "explain-code") return;const statement = selectedStatement || content;void nextAnimationFrame().then(() => {@@ -135,7 +136,7 @@ export function CodeViewer({});});},- [uiStore, selectedStatement, content, engine]+ [setShowAIPanel, selectedStatement, content, engine]);useAIActions({diff --git a/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx b/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsxindex e8335a3b90..87f609184f 100644--- a/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/DefinitionViewer.tsx@@ -6,7 +6,7 @@ import type { ChatAction } from "@/plugins/ai/types";import { ReadonlyMonaco } from "@/react/components/monaco/ReadonlyMonaco";import { formatSQL } from "@/react/components/monaco/sqlFormatter";import type { MonacoModule } from "@/react/components/monaco/types";-import { useSQLEditorUIStore } from "@/store";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { dialectOfEngineV1 } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { getInstanceResource, nextAnimationFrame } from "@/utils";@@ -33,7 +33,8 @@ export function DefinitionViewer({format,onSelectContent,}: DefinitionViewerProps) {- const uiStore = useSQLEditorUIStore();+ const setIsShowingCode = useSQLEditorStore((s) => s.setIsShowingCode);+ const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);const engine = useMemo(() => getInstanceResource(db).engine, [db]);const [formatted, setFormatted] = useState<{@@ -68,16 +69,16 @@ export function DefinitionViewer({);useEffect(() => {- uiStore.isShowingCode = true;+ setIsShowingCode(true);return () => {- uiStore.isShowingCode = false;+ setIsShowingCode(false);};- }, [uiStore]);+ }, [setIsShowingCode]);const handleAIAction = useCallback((action: ChatAction) => {- const newChat = !uiStore.showAIPanel;- uiStore.showAIPanel = true;+ const newChat = !useSQLEditorStore.getState().showAIPanel;+ setShowAIPanel(true);if (action !== "explain-code") return;const statement = selectedStatement || content;void nextAnimationFrame().then(() => {@@ -87,7 +88,7 @@ export function DefinitionViewer({});});},- [uiStore, selectedStatement, content, engine]+ [setShowAIPanel, selectedStatement, content, engine]);useAIActions({diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsxindex a41cebbaad..683bd7d754 100644--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx@@ -23,13 +23,13 @@ import { useVueState } from "@/react/hooks/useVueState";import { applyPlanTitleToQuery } from "@/react/lib/plan/title";import { cn } from "@/react/lib/utils";import { useNavigate } from "@/react/router";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";import {useDatabaseV1Store,useProjectV1Store,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import { unknownProject } from "@/types";import {@@ -63,10 +63,12 @@ export function SQLEditorHomePage() {const { t } = useTranslation();const navigate = useNavigate();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const setPendingInsertAtCaret = useSQLEditorStore(+ (s) => s.setPendingInsertAtCaret+ );const databaseStore = useDatabaseV1Store();const projectStore = useProjectV1Store();- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const projectContextReady = useVueState(() => editorStore.projectContextReady@@ -147,13 +149,13 @@ export function SQLEditorHomePage() {viewState: { ...(t.viewState ?? {}), view: "CODE" },});requestAnimationFrame(() => {- uiStore.pendingInsertAtCaret = content;+ setPendingInsertAtCaret(content);});});return () => {off();};- }, [tabStore, uiStore]);+ }, [tabStore, setPendingInsertAtCaret]);const mobileToggle = hideSidebar? createPortal(diff --git a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsxindex c79d6a757f..b187cc6803 100644--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx@@ -8,6 +8,8 @@ import {} from "@/react/components/ComponentPermissionGuard";import { useVueState } from "@/react/hooks/useVueState";import { useCurrentRoute, useNavigate } from "@/react/router";+import type { AsidePanelTab } from "@/react/stores/sqlEditor";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import { router } from "@/router";import {SQL_EDITOR_DATABASE_MODULE,@@ -17,14 +19,12 @@ import {SQL_EDITOR_WORKSHEET_MODULE,} from "@/router/sqlEditor";import {- type AsidePanelTab,pushNotification,useActuatorV1Store,useDatabaseV1Store,useProjectV1Store,- useSQLEditorStore,+ useSQLEditorStore as useSQLEditorPiniaStore,useSQLEditorTabStore,- useSQLEditorUIStore,useSQLEditorWorksheetStore,useWorkSheetStore,} from "@/store";@@ -46,7 +46,6 @@ import {getSheetStatement,isWorksheetReadableV1,STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,- suggestedTabTitleForSQLEditorConnection,} from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";import { SQLEditorHomePage } from "./SQLEditorHomePage";@@ -104,9 +103,9 @@ export function SQLEditorRouteShell() {const actuatorStore = useActuatorV1Store();const projectStore = useProjectV1Store();const databaseStore = useDatabaseV1Store();- const editorStore = useSQLEditorStore();+ const editorStore = useSQLEditorPiniaStore();const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const worksheetStore = useWorkSheetStore();const sqlEditorWorksheetStore = useSQLEditorWorksheetStore();@@ -239,7 +238,6 @@ export function SQLEditorRouteShell() {tabStore.addTab({connection,mode: DEFAULT_SQL_EDITOR_TAB_MODE,- title: suggestedTabTitleForSQLEditorConnection(connection),});return true;};@@ -407,15 +405,15 @@ export function SQLEditorRouteShell() {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;+ setAsidePanelTab(ASIDE_PANEL_TABS.includes(tab) ? tab : stored);} else {- uiStore.asidePanelTab = stored;+ setAsidePanelTab(stored);}sidebarRestoredRef.current = true;};// Persist sidebar tab changes back to localStorage (debounced).- const asidePanelTab = useVueState(() => uiStore.asidePanelTab);+ const asidePanelTab = useSQLEditorStore((s) => s.asidePanelTab);const persistSidebarRef = useRef(debounce((tab: AsidePanelTab) => {try {diff --git a/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx b/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsxindex 4e9c3c96e4..48be7bbf05 100644--- a/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx+++ b/frontend/src/react/components/sql-editor/SaveSheetModal.test.tsx@@ -272,25 +272,37 @@ describe("SaveSheetModal", () => {unmount();});- test("4. Save button is disabled when title is empty", () => {+ test("4. Save button stays enabled with an empty title (worksheet becomes Untitled)", async () => {const { container, render, unmount } = renderIntoContainer(<SaveSheetModal />);render();- // Open modal with a tab that has an empty title — Save must be disabled+ // Open modal with a tab that has an empty title — Save is allowed; the+ // worksheet is created with an empty title and the UI renders "Untitled"+ // placeholders for it elsewhere.const tabWithEmptyTitle = {...tabWithoutWorksheet,title: "",};emitSaveSheet({ tab: tabWithEmptyTitle });- const buttons = container.querySelectorAll("button");- const saveButton = Array.from(buttons).find(+ const saveButton = Array.from(container.querySelectorAll("button")).find((b) => b.textContent === "common.save") as HTMLButtonElement;expect(saveButton).not.toBeNull();- expect(saveButton.disabled).toBe(true);+ expect(saveButton.disabled).toBe(false);++ await act(async () => {+ saveButton.click();+ });++ expect(mocks.editorWorksheetStore.createWorksheet).toHaveBeenCalledWith(+ expect.objectContaining({+ tabId: tabWithEmptyTitle.id,+ title: "",+ })+ );unmount();});diff --git a/frontend/src/react/components/sql-editor/SaveSheetModal.tsx b/frontend/src/react/components/sql-editor/SaveSheetModal.tsxindex 191e62ee13..2327a01d4c 100644--- a/frontend/src/react/components/sql-editor/SaveSheetModal.tsx+++ b/frontend/src/react/components/sql-editor/SaveSheetModal.tsx@@ -40,10 +40,8 @@ export function SaveSheetModal() {}// Silent path passes title + folder explicitly because React state setters// are async — reading state here would observe the prior modal's values.+ // Empty titles are allowed; surfaces render an "Untitled" placeholder.const effectiveTitle = tabTitle ?? title;- if (effectiveTitle === "") {- return;- }const effectiveFolder = tabFolder ?? folder;editorWorksheetStore.abortAutoSave();@@ -106,14 +104,11 @@ export function SaveSheetModal() {<DialogTitle>{t("sql-editor.save-sheet")}</DialogTitle><div className="flex flex-col gap-y-3"><div className="flex flex-col gap-y-1">- <p>- {t("common.title")}- <span className="text-error ml-0.5">*</span>- </p>+ <p>{t("common.title")}</p><Inputvalue={title}onChange={(e) => setTitle(e.target.value)}- placeholder={t("sql-editor.save-sheet-input-placeholder")}+ placeholder={t("common.untitled")}maxLength={200}/></div>@@ -122,7 +117,7 @@ export function SaveSheetModal() {<Button variant="outline" onClick={close}>{t("common.close")}</Button>- <Button disabled={!title} onClick={() => void doSaveSheet()}>+ <Button onClick={() => void doSaveSheet()}>{t("common.save")}</Button></div>diff --git a/frontend/src/react/components/sql-editor/SheetTree.tsx b/frontend/src/react/components/sql-editor/SheetTree.tsxindex 53598067cf..74c2cf4751 100644--- a/frontend/src/react/components/sql-editor/SheetTree.tsx+++ b/frontend/src/react/components/sql-editor/SheetTree.tsx@@ -482,7 +482,10 @@ export function SheetTree({};const newTitle = editing.node.label.trim();- if (!newTitle) {+ // Folders can't be renamed to empty (the label IS the folder name and the+ // key segment). Worksheets can — they fall back to the "Untitled"+ // placeholder in the UI.+ if (!newTitle && !editing.node.worksheet) {editing.node.label = editing.rawLabel;cleanup();return;@@ -1032,6 +1035,13 @@ export function SheetTree({}}onClick={(e) => e.stopPropagation()}/>+ ) : folderNode.worksheet && !folderNode.label ? (+ // Untitled worksheet — render a placeholder. We don't pipe this+ // through HighlightLabelText since there's nothing to highlight+ // and the muted italic styling signals "empty title".+ <span className="truncate block text-control-placeholder italic">+ {t("common.untitled")}+ </span>) : (<HighlightLabelTexttext={folderNode.label}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsxindex 4c4c6880e9..4ea9c7d22a 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx@@ -16,10 +16,10 @@ import {formatEditorContent,} from "@/react/components/monaco/utils";import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {useConnectionOfCurrentSQLEditorTab,useSQLEditorTabStore,- useSQLEditorUIStore,useUIStateStore,useWorkSheetAndTabStore,} from "@/store";@@ -68,7 +68,10 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {const tabStore = useSQLEditorTabStore();const sheetAndTabStore = useWorkSheetAndTabStore();const uiStateStore = useUIStateStore();- const sqlEditorUIStore = useSQLEditorUIStore();+ const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);+ const setPendingInsertAtCaret = useSQLEditorStore(+ (s) => s.setPendingInsertAtCaret+ );const { instance, database } = useConnectionOfCurrentSQLEditorTab();const tabId = useVueState(() => tabStore.currentTab?.id);@@ -242,8 +245,8 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {// ----- AI Monaco actions (explain-code / find-problems / new-chat) -----const handleAIAction = useCallback((action: ChatAction) => {- const newChat = !sqlEditorUIStore.showAIPanel;- sqlEditorUIStore.showAIPanel = true;+ const newChat = !useSQLEditorStore.getState().showAIPanel;+ setShowAIPanel(true);const statement = getActiveStatement();if (!statement) return;const tab = tabStore.currentTab;@@ -268,7 +271,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {}});},- [sqlEditorUIStore, getActiveStatement, tabStore]+ [setShowAIPanel, getActiveStatement, tabStore]);useAIActions({@@ -302,15 +305,13 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {}, [engine, runQueryAction, editorState, monacoState]);// ----- pendingInsertAtCaret ------ const pendingInsertAtCaret = useVueState(- () => sqlEditorUIStore.pendingInsertAtCaret- );+ const pendingInsertAtCaret = useSQLEditorStore((s) => s.pendingInsertAtCaret);useEffect(() => {const editor = activeSQLEditorRef.value;if (!editor) return;const text = pendingInsertAtCaret;if (!text) return;- sqlEditorUIStore.pendingInsertAtCaret = undefined;+ setPendingInsertAtCaret(undefined);requestAnimationFrame(() => {const selection = editor.getSelection();@@ -324,7 +325,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {editor.focus();editor.revealLine(range.startLineNumber);});- }, [pendingInsertAtCaret, sqlEditorUIStore]);+ }, [pendingInsertAtCaret, setPendingInsertAtCaret]);// ----- file upload (triggered by UploadFileButton in cornerPrefix) -----const handleUploadFile = useCallback(diff --git a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsxindex f13bcea561..fd1a4ab33e 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx@@ -5,14 +5,18 @@ import {Group as PanelGroup,Separator as PanelResizeHandle,} from "react-resizable-panels";+import { useShallow } from "zustand/react/shallow";import { AIChatToSQL, AIContextProvider } from "@/plugins/ai/react";import { resizeHandleClass } from "@/react/components/SchemaEditorLite/resize";import { ResultPanel } from "@/react/components/sql-editor/ResultPanel/ResultPanel";import { useVueState } from "@/react/hooks/useVueState";+import {+ selectEditorPanelSize,+ useSQLEditorStore,+} from "@/react/stores/sqlEditor";import {useConnectionOfCurrentSQLEditorTab,useSQLEditorTabStore,- useSQLEditorUIStore,} from "@/store";import { instanceV1HasReadonlyMode } from "@/utils";import { EditorMain } from "./EditorMain";@@ -43,19 +47,23 @@ const AIPaneFallback = () => (** 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.+ * `useSQLEditorStore` (zustand) for AI-panel visibility / sizing.*/export function StandardPanel() {const tabStore = useSQLEditorTabStore();- const uiStore = useSQLEditorUIStore();+ const handleEditorPanelResize = useSQLEditorStore(+ (s) => s.handleEditorPanelResize+ );+ const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);+ const setShowConnectionPanel = useSQLEditorStore(+ (s) => s.setShowConnectionPanel+ );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 showAIPanel = useSQLEditorStore((s) => s.showAIPanel);+ const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));const instanceHasReadonly = useVueState(() =>instanceV1HasReadonlyMode(instanceRef.value));@@ -72,12 +80,12 @@ export function StandardPanel() {// 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);+ handleEditorPanelResize(sizePct / 100);};const handleChangeConnection = () => {- uiStore.asidePanelTab = "SCHEMA";- uiStore.showConnectionPanel = true;+ setAsidePanelTab("SCHEMA");+ setShowConnectionPanel(true);};const editorWithAi = (diff --git a/frontend/src/react/components/sql-editor/TabItem.test.tsx b/frontend/src/react/components/sql-editor/TabItem.test.tsxindex 6800ac79af..78c5dba87a 100644--- a/frontend/src/react/components/sql-editor/TabItem.test.tsx+++ b/frontend/src/react/components/sql-editor/TabItem.test.tsx@@ -9,20 +9,16 @@ import { beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorUIStore: vi.fn(),+ useSQLEditorStore: vi.fn(),+ currentAsidePanelTab: "WORKSHEET" as string,}));vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));--vi.mock("@/store", () => ({- useSQLEditorUIStore: mocks.useSQLEditorUIStore,+vi.mock("@/react/stores/sqlEditor", () => ({+ useSQLEditorStore: mocks.useSQLEditorStore,}));vi.mock("@/react/components/ui/tooltip", () => ({@@ -53,8 +49,11 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.useVueState.mockReturnValue(false);- mocks.useSQLEditorUIStore.mockReturnValue({ asidePanelTab: "WORKSHEET" });+ mocks.currentAsidePanelTab = "WORKSHEET";+ mocks.useSQLEditorStore.mockImplementation(+ (selector: (s: { asidePanelTab: string }) => unknown) =>+ selector({ asidePanelTab: mocks.currentAsidePanelTab })+ );({ TabItem } = await import("./TabItem"));});@@ -97,7 +96,7 @@ describe("TabItem", () => {});test("applies active class when asidePanelTab matches", () => {- mocks.useVueState.mockReturnValue(true);+ mocks.currentAsidePanelTab = "SCHEMA";const { container, render, unmount } = renderIntoContainer(<TabItem tab="SCHEMA" onClick={() => {}} />);@@ -109,7 +108,7 @@ describe("TabItem", () => {});test("does NOT apply active class when asidePanelTab differs", () => {- mocks.useVueState.mockReturnValue(false);+ mocks.currentAsidePanelTab = "WORKSHEET";const { container, render, unmount } = renderIntoContainer(<TabItem tab="SCHEMA" onClick={() => {}} />);diff --git a/frontend/src/react/components/sql-editor/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem.tsxindex 6bde71012a..8cc7c647b8 100644--- a/frontend/src/react/components/sql-editor/TabItem.tsx+++ b/frontend/src/react/components/sql-editor/TabItem.tsx@@ -2,10 +2,9 @@ import { Database, FileCode, History, ShieldCheck } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import type { AsidePanelTab } from "@/store";-import { useSQLEditorUIStore } from "@/store";+import type { AsidePanelTab } from "@/react/stores/sqlEditor";+import { useSQLEditorStore } from "@/react/stores/sqlEditor";type TabItemProps = {readonly tab: AsidePanelTab;@@ -22,13 +21,12 @@ const iconByTab = {/*** Single tab button in the SQL Editor aside panel's left gutter.* Replaces frontend/src/views/sql-editor/AsidePanel/GutterBar/TabItem.vue.- * Active state reflects useSQLEditorUIStore().asidePanelTab; click handler+ * Active state reflects `useSQLEditorStore().asidePanelTab`; click handler* is supplied by the GutterBar parent (which writes the store).*/export function TabItem({ tab, onClick }: TabItemProps) {const { t } = useTranslation();- const uiStore = useSQLEditorUIStore();- const isActive = useVueState(() => uiStore.asidePanelTab === tab);+ const isActive = useSQLEditorStore((s) => s.asidePanelTab === tab);const Icon = iconByTab[tab];const labelByTab = {diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsxindex 18875d3f43..d116454eae 100644--- a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx@@ -79,7 +79,11 @@ const makeTab = (overrides: Partial<SQLEditorTab> = {}): SQLEditorTab =>beforeEach(async () => {vi.clearAllMocks();+ // `currentTabId` matches the `id` makeTab returns ("t1") so the rendered+ // tab is treated as the active tab — required for the click-to-rename+ // behavior since clicks on non-current tabs only activate (no rename).mocks.useSQLEditorTabStore.mockReturnValue({+ currentTabId: "t1",updateTab: mocks.updateTab,setCurrentTabId: mocks.setCurrentTabId,});@@ -103,17 +107,21 @@ describe("Label", () => {unmount();});- test("double-click enters edit mode", () => {+ test("clicking the current tab enters edit mode", () => {const { container, render, unmount } = renderIntoContainer(<Label tab={makeTab()} />);render();- const dblLayer = container.querySelector(".cursor-text") as HTMLElement;- expect(dblLayer).not.toBeNull();+ const clickLayer = container.querySelector(".cursor-text") as HTMLElement;+ expect(clickLayer).not.toBeNull();act(() => {- dblLayer.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ // The Label gates rename on a mousedown-time snapshot of whether the+ // tab was already current. Tests must dispatch mousedown first so the+ // ref is populated before the click handler reads it.+ clickLayer.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ clickLayer.dispatchEvent(new MouseEvent("click", { bubbles: true }));});expect(container.querySelector("input")).not.toBeNull();@@ -121,6 +129,34 @@ describe("Label", () => {unmount();});+ test("clicking a non-current tab does NOT enter edit mode", () => {+ mocks.useSQLEditorTabStore.mockReturnValue({+ // Simulate a different tab being active so this Label sees itself as+ // non-current. Activation is handled by the parent TabItem's+ // onMouseDown; the Label's click handler should be a no-op here.+ currentTabId: "other-tab",+ updateTab: mocks.updateTab,+ setCurrentTabId: mocks.setCurrentTabId,+ });++ const { container, render, unmount } = renderIntoContainer(+ <Label tab={makeTab()} />+ );+ render();++ act(() => {+ const layer = container.querySelector(".cursor-text");+ // mousedown captures `wasCurrentAtMouseDownRef = false` since this tab+ // isn't the current one. The subsequent click is a no-op.+ layer?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ layer?.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ });++ expect(container.querySelector("input")).toBeNull();++ unmount();+ });+test("blur with the initial title still calls store.updateTab (preserving title)", () => {const { container, render, unmount } = renderIntoContainer(<Label tab={makeTab({ title: "Old" })} />@@ -128,9 +164,9 @@ describe("Label", () => {render();act(() => {- container- .querySelector(".cursor-text")- ?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ const layer = container.querySelector(".cursor-text");+ layer?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ layer?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});const input = container.querySelector("input") as HTMLInputElement;@@ -147,17 +183,16 @@ describe("Label", () => {unmount();});- test("blur with empty draft cancels edit and does not call store.updateTab", () => {- // Re-mount after each test clears mocks.+ test("blur with empty draft persists empty title (no longer cancels)", () => {const { container, render, unmount } = renderIntoContainer(<Label tab={makeTab({ title: "Old" })} />);render();act(() => {- container- .querySelector(".cursor-text")- ?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ const layer = container.querySelector(".cursor-text");+ layer?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ layer?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});const input = container.querySelector("input") as HTMLInputElement;@@ -165,8 +200,6 @@ describe("Label", () => {HTMLInputElement.prototype,"value")?.set;- // Try to set empty string via the prototype setter (may or may not- // propagate to React's state in jsdom — behavior is what matters).act(() => {setter?.call(input, "");input.dispatchEvent(new Event("input", { bubbles: true }));@@ -175,10 +208,9 @@ describe("Label", () => {input.dispatchEvent(new Event("blur", { bubbles: true }));});- // Either path: if React saw the empty draft → cancel (no updateTab),- // or React didn't see it → updateTab("Old") called. Both are valid- // behaviors given jsdom limitations. This test just documents that- // the component never crashes on blur.+ // Empty title is now valid (renders as a localized "Untitled"+ // placeholder elsewhere). Either way the component should not crash;+ // assert it didn't.expect(true).toBe(true);unmount();diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.tsxindex dfb6b54831..b6f1b47422 100644--- a/frontend/src/react/components/sql-editor/TabItem/Label.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/Label.tsx@@ -1,5 +1,6 @@import { create } from "@bufbuild/protobuf";import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";import { EllipsisText } from "@/react/components/ui/ellipsis-text";import { cn } from "@/react/lib/utils";import { useSQLEditorTabStore, useWorkSheetStore } from "@/store";@@ -20,6 +21,7 @@ type Props = {* - Ellipsis + native tooltip via EllipsisText.*/export function Label({ tab }: Props) {+ const { t } = useTranslation();const tabStore = useSQLEditorTabStore();const worksheetStore = useWorkSheetStore();@@ -28,6 +30,15 @@ export function Label({ tab }: Props) {const inputRef = useRef<HTMLInputElement>(null);const readonly = tab.viewState.view !== "CODE";+ const displayTitle = tab.title || t("common.untitled");+ // Captures whether the tab was already current at mousedown time, before+ // the parent TabItem's onMouseDown handler runs and switches activation.+ // We can't use a render-captured value: React commits the re-render+ // between mousedown and click, so by the time onClick fires the new render+ // already shows this tab as current. Inner mousedown handlers fire before+ // the parent's (bubble order), giving us a moment to read the *previous*+ // value from the store.+ const wasCurrentAtMouseDownRef = useRef(false);const beginEdit = () => {if (readonly) return;@@ -42,10 +53,6 @@ export function Label({ tab }: Props) {const confirmEdit = () => {const title = draft.trim();- if (title === "") {- cancelEdit();- return;- }tabStore.updateTab(tab.id, { title });if (tab.worksheet) {void worksheetStore.patchWorksheet(@@ -109,14 +116,31 @@ export function Label({ tab }: Props) {the relative container and the `absolute inset-0` input shrinks tozero height → the cursor is visible but the text field is not. */}<EllipsisText- text={tab.title}- className={cn("text-sm leading-5 block", editing && "invisible")}+ text={displayTitle}+ className={cn(+ "text-sm leading-5 block",+ !tab.title && "text-control-placeholder italic",+ editing && "invisible"+ )}/>- {/* Invisible "expand" dbl-click layer — EllipsisText strips onDblClick */}+ {/* Invisible click layer — EllipsisText strips its own handlers.+ Click-to-rename behaviour:+ - Click on the *current* tab's label → enter rename mode.+ - Click on a non-current tab → just activates the tab (handled by+ the parent TabItem's onMouseDown). No rename on the first click.+ We snapshot `wasCurrentAtMouseDownRef` at this layer's mousedown+ (which fires before the parent's via bubble order). The parent's+ mousedown then mutates the store; by the time onClick fires, the+ ref still holds the pre-activation value. */}{!editing && !readonly && (<divclassName="absolute inset-0 cursor-text"- onDoubleClick={beginEdit}+ onMouseDown={() => {+ wasCurrentAtMouseDownRef.current = tabStore.currentTabId === tab.id;+ }}+ onClick={() => {+ if (wasCurrentAtMouseDownRef.current) beginEdit();+ }}/>)}{editing && (@@ -125,6 +149,7 @@ export function Label({ tab }: Props) {type="text"className="absolute inset-0 border-0 border-b p-0 text-sm leading-5 bg-background"value={draft}+ placeholder={t("common.untitled")}onChange={(e) => setDraft(e.target.value)}onBlur={confirmEdit}onKeyDown={(e) => {diff --git a/frontend/src/react/hooks/useColumnWidths.ts b/frontend/src/react/hooks/useColumnWidths.tsindex eef2e70925..061f66f8b4 100644--- a/frontend/src/react/hooks/useColumnWidths.ts+++ b/frontend/src/react/hooks/useColumnWidths.ts@@ -1,4 +1,4 @@-import { useCallback, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";export interface ColumnWithWidth {defaultWidth: number;@@ -21,6 +21,10 @@ export function useColumnWidths<T extends ColumnWithWidth>(columns: T[]) {startX: number;startWidth: number;} | null>(null);+ // Holds the teardown function for an active drag so an unmount-mid-drag+ // (route change, modal close, etc.) tears down document-level listeners+ // and resets the body cursor/userSelect overrides.+ const dragCleanupRef = useRef<() => void>(() => {});const onResizeStart = useCallback((colIndex: number, e: React.MouseEvent) => {@@ -43,21 +47,32 @@ export function useColumnWidths<T extends ColumnWithWidth>(columns: T[]) {return next;});};- const onMouseUp = () => {+ const teardown = () => {dragRef.current = null;document.removeEventListener("mousemove", onMouseMove);- document.removeEventListener("mouseup", onMouseUp);+ document.removeEventListener("mouseup", teardown);document.body.style.cursor = "";document.body.style.userSelect = "";+ // Reset so the unmount-cleanup is a no-op if the drag ended cleanly.+ dragCleanupRef.current = () => {};};document.addEventListener("mousemove", onMouseMove);- document.addEventListener("mouseup", onMouseUp);+ document.addEventListener("mouseup", teardown);document.body.style.cursor = "col-resize";document.body.style.userSelect = "none";+ dragCleanupRef.current = teardown;},[widths, columns]);+ useEffect(() => {+ return () => {+ // If unmount happens mid-drag, tear down before any stale listener+ // can fire against the unmounted tree.+ dragCleanupRef.current();+ };+ }, []);+const totalWidth = widths.reduce((sum, w) => sum + w, 0);return { widths, totalWidth, onResizeStart };diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex bd26be98e4..34caf5199a 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -2808,7 +2808,6 @@"rows-affected": "rows affected","rows-upper-limit": "reached the limit of query results","save-sheet": "Save Sheet",- "save-sheet-input-placeholder": "Please input a sheet name","scroll-to-bottom": "Scroll to the bottom","scroll-to-top": "Scroll to the top","search-history-by-statement": "Search by statement",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 057b0f15e7..0d9b157129 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -2796,7 +2796,6 @@"rows-affected": "filas afectadas","rows-upper-limit": "se ha alcanzado el límite de resultados de la consulta","save-sheet": "Guardar hoja",- "save-sheet-input-placeholder": "Por favor, ingresa un nombre para la hoja","scroll-to-bottom": "Desplazarse hacia abajo","scroll-to-top": "Desplazarse hacia arriba","search-history-by-statement": "Búsqueda por enunciado",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex bab73f5ecf..a33e1243ff 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -2796,7 +2796,6 @@"rows-affected": "行に影響","rows-upper-limit": "クエリ結果の数が上限に達しました","save-sheet": "ワークシートの保存",- "save-sheet-input-placeholder": "ワークシート名を入力してください","scroll-to-bottom": "末尾へスクロール","scroll-to-top": "先頭へスクロール","search-history-by-statement": "ステートメントで検索",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 90cc0fc16f..584067f1a9 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -2796,7 +2796,6 @@"rows-affected": "dòng bị ảnh hưởng","rows-upper-limit": "đã đạt đến giới hạn kết quả truy vấn","save-sheet": "Lưu trang tính",- "save-sheet-input-placeholder": "Vui lòng nhập tên trang tính","scroll-to-bottom": "Cuộn xuống cuối","scroll-to-top": "Cuộn lên đầu","search-history-by-statement": "Tìm kiếm theo câu lệnh",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 53123c82fc..a0987c8359 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -2796,7 +2796,6 @@"rows-affected": "行受影响","rows-upper-limit": "到达查询结果条数上限","save-sheet": "保存工作表",- "save-sheet-input-placeholder": "请输入工作表名称","scroll-to-bottom": "滚动到底部","scroll-to-top": "滚动到顶部","search-history-by-statement": "搜索 SQL 语句",diff --git a/frontend/src/react/stores/sqlEditor/index.ts b/frontend/src/react/stores/sqlEditor/index.tsnew file mode 100644index 0000000000..2a23ef59e1--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/index.ts@@ -0,0 +1,10 @@+import { create } from "zustand";+import type { SQLEditorStoreState } from "./types";+import { createUIStateSlice } from "./uiState";++export type { AsidePanelTab, SQLEditorStoreState } from "./types";+export { selectEditorPanelSize } from "./uiState";++export const useSQLEditorStore = create<SQLEditorStoreState>()((...args) => ({+ ...createUIStateSlice(...args),+}));diff --git a/frontend/src/react/stores/sqlEditor/types.ts b/frontend/src/react/stores/sqlEditor/types.tsnew file mode 100644index 0000000000..0c8e78de5c--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/types.ts@@ -0,0 +1,35 @@+import type { StateCreator } from "zustand";++export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY" | "ACCESS";++export interface UIStateSlice {+ asidePanelTab: AsidePanelTab;+ showConnectionPanel: boolean;+ showAIPanel: boolean;+ pendingInsertAtCaret: string | undefined;+ highlightAccessGrantName: string | undefined;+ // True while a CodeViewer-style surface is mounted (procedure / function /+ // package body, view definition, trigger body). Used by panels to decide+ // whether to render the AIChatToSQL side pane.+ isShowingCode: boolean;+ // Persisted fraction of the editor width given to the AI side pane when it+ // is shown. Stored in localStorage and re-read on store creation.+ aiPanelSize: number;++ setAsidePanelTab: (tab: AsidePanelTab) => void;+ setShowConnectionPanel: (value: boolean) => void;+ setShowAIPanel: (value: boolean) => void;+ setPendingInsertAtCaret: (value: string | undefined) => void;+ setHighlightAccessGrantName: (value: string | undefined) => void;+ setIsShowingCode: (value: boolean) => void;+ handleEditorPanelResize: (size: number) => void;+}++export type SQLEditorStoreState = UIStateSlice;++export type SQLEditorSliceCreator<Slice> = StateCreator<+ SQLEditorStoreState,+ [],+ [],+ Slice+>;diff --git a/frontend/src/react/stores/sqlEditor/uiState.test.ts b/frontend/src/react/stores/sqlEditor/uiState.test.tsnew file mode 100644index 0000000000..fe4d3d8217--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/uiState.test.ts@@ -0,0 +1,114 @@+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import { create, type StoreApi } from "zustand";+import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";+import type { SQLEditorStoreState } from "./types";++const originalLocalStorage = globalThis.localStorage;+const storage = new Map<string, string>();+const localStorageMock = {+ getItem: (key: string) => storage.get(key) ?? null,+ setItem: (key: string, value: string) => {+ storage.set(key, value);+ },+ removeItem: (key: string) => {+ storage.delete(key);+ },+ clear: () => {+ storage.clear();+ },+ key: (index: number) => Array.from(storage.keys())[index] ?? null,+ get length() {+ return storage.size;+ },+};++// Build a fresh store for each test so the slice's `aiPanelSize`+// initialiser re-reads the (mocked) localStorage and we don't leak state+// between tests. The slice module is dynamically imported with a query+// string so Vitest doesn't cache the module-level read of localStorage.+const makeStore = async (): Promise<StoreApi<SQLEditorStoreState>> => {+ const mod = (await import(+ `./uiState?t=${Date.now()}`+ )) as typeof import("./uiState");+ return create<SQLEditorStoreState>()((...args) => ({+ ...mod.createUIStateSlice(...args),+ }));+};++let selectEditorPanelSize: typeof import("./uiState").selectEditorPanelSize;++beforeEach(async () => {+ storage.clear();+ Object.defineProperty(globalThis, "localStorage", {+ value: localStorageMock,+ configurable: true,+ });+ ({ selectEditorPanelSize } = await import(`./uiState?t=${Date.now()}`));+});++afterEach(() => {+ Object.defineProperty(globalThis, "localStorage", {+ value: originalLocalStorage,+ configurable: true,+ });+});++describe("sqlEditor uiState slice", () => {+ test("initial state has documented defaults", async () => {+ const useStore = await makeStore();+ const s = useStore.getState();+ expect(s.asidePanelTab).toBe("WORKSHEET");+ expect(s.showConnectionPanel).toBe(false);+ expect(s.showAIPanel).toBe(false);+ expect(s.pendingInsertAtCaret).toBeUndefined();+ expect(s.highlightAccessGrantName).toBeUndefined();+ expect(s.isShowingCode).toBe(false);+ expect(s.aiPanelSize).toBe(0.3);+ });++ test("selectEditorPanelSize returns full-width when AI panel is hidden", async () => {+ const useStore = await makeStore();+ expect(selectEditorPanelSize(useStore.getState())).toEqual({+ size: 1,+ max: 1,+ min: 1,+ });+ });++ test("selectEditorPanelSize returns clamped split when AI panel is shown", async () => {+ const useStore = await makeStore();+ useStore.getState().setShowAIPanel(true);+ expect(selectEditorPanelSize(useStore.getState())).toEqual({+ size: 0.7,+ max: 0.9,+ min: 0.5,+ });+ });++ test("selectEditorPanelSize clamps to minimum 0.5 when AI panel is huge", async () => {+ localStorage.setItem(+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,+ JSON.stringify(0.8)+ );+ const useStore = await makeStore();+ useStore.getState().setShowAIPanel(true);+ expect(selectEditorPanelSize(useStore.getState()).size).toBe(0.5);+ });++ test("handleEditorPanelResize writes complement to aiPanelSize and persists it", async () => {+ const useStore = await makeStore();+ useStore.getState().setShowAIPanel(true);+ useStore.getState().handleEditorPanelResize(0.6);+ expect(selectEditorPanelSize(useStore.getState()).size).toBe(0.6);+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE)).toBe(+ JSON.stringify(0.4)+ );+ });++ test("handleEditorPanelResize no-ops when size is >= 1", async () => {+ const useStore = await makeStore();+ useStore.getState().setShowAIPanel(true);+ useStore.getState().handleEditorPanelResize(1);+ expect(selectEditorPanelSize(useStore.getState()).size).toBe(0.7);+ });+});diff --git a/frontend/src/react/stores/sqlEditor/uiState.ts b/frontend/src/react/stores/sqlEditor/uiState.tsnew file mode 100644index 0000000000..6d3dfbe20b--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/uiState.ts@@ -0,0 +1,71 @@+import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";+import type {+ SQLEditorSliceCreator,+ SQLEditorStoreState,+ UIStateSlice,+} from "./types";++const MINIMUM_EDITOR_PANEL_SIZE = 0.5;+const DEFAULT_AI_PANEL_SIZE = 0.3;++const readAIPanelSize = (): number => {+ try {+ const raw = localStorage.getItem(STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE);+ if (raw !== null) {+ const parsed = JSON.parse(raw);+ if (typeof parsed === "number") return parsed;+ }+ } catch {+ // ignore — fall back to default+ }+ return DEFAULT_AI_PANEL_SIZE;+};++const writeAIPanelSize = (size: number) => {+ try {+ localStorage.setItem(+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,+ JSON.stringify(size)+ );+ } catch {+ // ignore+ }+};++export const createUIStateSlice: SQLEditorSliceCreator<UIStateSlice> = (+ set+) => ({+ asidePanelTab: "WORKSHEET",+ showConnectionPanel: false,+ showAIPanel: false,+ pendingInsertAtCaret: undefined,+ highlightAccessGrantName: undefined,+ isShowingCode: false,+ aiPanelSize: readAIPanelSize(),++ setAsidePanelTab: (tab) => set({ asidePanelTab: tab }),+ setShowConnectionPanel: (v) => set({ showConnectionPanel: v }),+ setShowAIPanel: (v) => set({ showAIPanel: v }),+ setPendingInsertAtCaret: (v) => set({ pendingInsertAtCaret: v }),+ setHighlightAccessGrantName: (v) => set({ highlightAccessGrantName: v }),+ setIsShowingCode: (v) => set({ isShowingCode: v }),+ handleEditorPanelResize: (size) => {+ if (size >= 1) return;+ const next = 1 - size;+ writeAIPanelSize(next);+ set({ aiPanelSize: next });+ },+});++export const selectEditorPanelSize = (+ state: SQLEditorStoreState+): { size: number; max: number; min: number } => {+ if (!state.showAIPanel) {+ return { size: 1, max: 1, min: 1 };+ }+ return {+ size: Math.max(1 - state.aiPanelSize, MINIMUM_EDITOR_PANEL_SIZE),+ max: 0.9,+ min: MINIMUM_EDITOR_PANEL_SIZE,+ };+};diff --git a/frontend/src/store/modules/sqlEditor/index.ts b/frontend/src/store/modules/sqlEditor/index.tsindex 1e3738e5fc..790c0ad1b5 100644--- a/frontend/src/store/modules/sqlEditor/index.ts+++ b/frontend/src/store/modules/sqlEditor/index.ts@@ -2,7 +2,6 @@ export * from "./editor";export * from "./tab";export * from "./tree";export * from "./queryHistory";-export * from "./uiState";export * from "./webTerminal";export * from "./folder";export * from "./worksheet";diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex d7da1a772c..bbc2ca1fc3 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -20,7 +20,6 @@ import {isConnectedSQLEditorTab,storageKeySqlEditorCurrentTab,storageKeySqlEditorTabs,- suggestedTabTitleForSQLEditorConnection,useDynamicLocalStorage,} from "@/utils";import {@@ -212,9 +211,8 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {treeState: cloneDeep(targetTab?.treeState),editorState: cloneDeep(targetTab?.editorState),batchQueryContext: cloneDeep(targetTab?.batchQueryContext),- title: suggestedTabTitleForSQLEditorConnection(- targetTab?.connection ?? emptySQLEditorConnection()- ),+ // Cloned tabs start untitled; the UI renders an "Untitled" placeholder.+ title: "",...payload,};diff --git a/frontend/src/store/modules/sqlEditor/uiState.test.ts b/frontend/src/store/modules/sqlEditor/uiState.test.tsdeleted file mode 100644index 0b7fb5ebf5..0000000000--- a/frontend/src/store/modules/sqlEditor/uiState.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { createPinia, setActivePinia } from "pinia";-import { afterEach, beforeEach, describe, expect, test } from "vitest";-import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";--let useSQLEditorUIStore: typeof import("./uiState").useSQLEditorUIStore;-const originalLocalStorage = globalThis.localStorage;-const storage = new Map<string, string>();-const localStorageMock = {- getItem: (key: string) => storage.get(key) ?? null,- setItem: (key: string, value: string) => {- storage.set(key, value);- },- removeItem: (key: string) => {- storage.delete(key);- },- clear: () => {- storage.clear();- },- key: (index: number) => Array.from(storage.keys())[index] ?? null,- get length() {- return storage.size;- },-};--beforeEach(async () => {- storage.clear();- Object.defineProperty(globalThis, "localStorage", {- value: localStorageMock,- configurable: true,- });- setActivePinia(createPinia());- ({ useSQLEditorUIStore } = await import("./uiState"));-});--afterEach(() => {- Object.defineProperty(globalThis, "localStorage", {- value: originalLocalStorage,- configurable: true,- });-});--describe("useSQLEditorUIStore", () => {- test("initial state has documented defaults", () => {- const store = useSQLEditorUIStore();- expect(store.asidePanelTab).toBe("WORKSHEET");- expect(store.showConnectionPanel).toBe(false);- expect(store.showAIPanel).toBe(false);- expect(store.pendingInsertAtCaret).toBeUndefined();- expect(store.highlightAccessGrantName).toBeUndefined();- });-- test("editorPanelSize returns full-width when AI panel is hidden", () => {- const store = useSQLEditorUIStore();- expect(store.showAIPanel).toBe(false);- expect(store.editorPanelSize).toEqual({ size: 1, max: 1, min: 1 });- });-- test("editorPanelSize returns clamped split when AI panel is shown", () => {- const store = useSQLEditorUIStore();- store.showAIPanel = true;- expect(store.editorPanelSize).toEqual({ size: 0.7, max: 0.9, min: 0.5 });- });-- test("editorPanelSize clamps to minimum 0.5 when AI panel is huge", () => {- localStorage.setItem(- STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,- JSON.stringify(0.8)- );- const store = useSQLEditorUIStore();- store.showAIPanel = true;- expect(store.editorPanelSize.size).toBe(0.5);- });-- test("handleEditorPanelResize writes complement to aiPanelSize LocalStorage", () => {- const store = useSQLEditorUIStore();- store.showAIPanel = true;- store.handleEditorPanelResize(0.6);- expect(store.editorPanelSize.size).toBe(0.6);- });-- test("handleEditorPanelResize no-ops when size is >= 1", () => {- const store = useSQLEditorUIStore();- store.showAIPanel = true;- store.handleEditorPanelResize(1);- expect(store.editorPanelSize.size).toBe(0.7);- });-});diff --git a/frontend/src/store/modules/sqlEditor/uiState.ts b/frontend/src/store/modules/sqlEditor/uiState.tsdeleted file mode 100644index c038d2a6e9..0000000000--- a/frontend/src/store/modules/sqlEditor/uiState.ts+++ /dev/null@@ -1,62 +0,0 @@-import { useLocalStorage } from "@vueuse/core";-import { defineStore } from "pinia";-import { computed, ref } from "vue";-import { STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE } from "@/utils/storage-keys";--export type AsidePanelTab = "SCHEMA" | "WORKSHEET" | "HISTORY" | "ACCESS";--const minimumEditorPanelSize = 0.5;--/**- * UI state for the SQL Editor shell.- *- * Extracted from `useSQLEditorContext` so React leaves can access the same- * reactive state that Vue consumers read via inject. Vue's- * `useSQLEditorContext()` wraps this store via `storeToRefs` and preserves- * its existing API shape.- */-export const useSQLEditorUIStore = defineStore("sqlEditorUI", () => {- const asidePanelTab = ref<AsidePanelTab>("WORKSHEET");- const showConnectionPanel = ref(false);- const showAIPanel = ref(false);- const pendingInsertAtCaret = ref<string | undefined>();- const highlightAccessGrantName = ref<string | undefined>();- // True while a CodeViewer-style surface is mounted (procedure/function/- // package body, view definition, trigger body). Panels.vue uses this to- // decide whether to render the AIChatToSQL side pane — matches the Vue- // CodeViewer's behavior of unmounting AIChatToSQL when the user navigates- // back to the list view.- const isShowingCode = ref(false);-- const aiPanelSize = useLocalStorage(- STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,- 0.3- );-- const editorPanelSize = computed(() => {- if (!showAIPanel.value) {- return { size: 1, max: 1, min: 1 };- }- return {- size: Math.max(1 - aiPanelSize.value, minimumEditorPanelSize),- max: 0.9,- min: minimumEditorPanelSize,- };- });-- const handleEditorPanelResize = (size: number) => {- if (size >= 1) return;- aiPanelSize.value = 1 - size;- };-- return {- asidePanelTab,- showConnectionPanel,- showAIPanel,- pendingInsertAtCaret,- highlightAccessGrantName,- isShowingCode,- editorPanelSize,- handleEditorPanelResize,- };-});diff --git a/frontend/src/store/modules/sqlEditor/worksheet.test.ts b/frontend/src/store/modules/sqlEditor/worksheet.test.tsindex a29d1503d7..c5b683c902 100644--- a/frontend/src/store/modules/sqlEditor/worksheet.test.ts+++ b/frontend/src/store/modules/sqlEditor/worksheet.test.ts@@ -52,11 +52,7 @@ vi.mock("@/utils", async () => {instance: "",})),- isSimilarDefaultSQLEditorTabTitle: vi.fn(() => false),isWorksheetWritableV1: vi.fn(() => true),- NEW_WORKSHEET_TITLE: "Untitled",- suggestedTabTitleForSQLEditorConnection: vi.fn(() => "Untitled"),- isValidDatabaseName: vi.fn(() => false),isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),storageKeySqlEditorWorksheetFilter: vi.fn(() => "filter-key"),storageKeySqlEditorWorksheetTree: vi.fn(() => "tree-key"),@@ -69,7 +65,6 @@ vi.mock("@/utils", async () => {// Mock @/types to avoid importing native modules transitivelyvi.mock("@/types", () => ({- isValidDatabaseName: vi.fn(() => false),isValidProjectName: vi.fn((name: string) => name.startsWith("projects/")),DEBOUNCE_SEARCH_DELAY: 300,}));diff --git a/frontend/src/store/modules/sqlEditor/worksheet.ts b/frontend/src/store/modules/sqlEditor/worksheet.tsindex 33a64a084c..af3aac2e3e 100644--- a/frontend/src/store/modules/sqlEditor/worksheet.ts+++ b/frontend/src/store/modules/sqlEditor/worksheet.ts@@ -7,21 +7,17 @@ import scrollIntoView from "scroll-into-view-if-needed";import type { Ref } from "vue";import { computed, nextTick, ref, watch } from "vue";import { t } from "@/plugins/i18n";+import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";import {useCurrentUserV1,useProjectIamPolicyStore,useProjectV1Store,useSQLEditorStore,useSQLEditorTabStore,- useSQLEditorUIStore,useWorkSheetStore,} from "@/store";import type { SQLEditorTab } from "@/types";-import {- DEBOUNCE_SEARCH_DELAY,- isValidDatabaseName,- isValidProjectName,-} from "@/types";+import { DEBOUNCE_SEARCH_DELAY, isValidProjectName } from "@/types";import {type Worksheet,Worksheet_Visibility,@@ -29,11 +25,8 @@ import {} from "@/types/proto-es/v1/worksheet_service_pb";import {extractWorksheetConnection,- isSimilarDefaultSQLEditorTabTitle,- NEW_WORKSHEET_TITLE,storageKeySqlEditorWorksheetFilter,storageKeySqlEditorWorksheetTree,- suggestedTabTitleForSQLEditorConnection,useDynamicLocalStorage,} from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";@@ -346,7 +339,6 @@ export const useSQLEditorWorksheetStore = defineStore(const projectStore = useProjectV1Store();const projectIamPolicyStore = useProjectIamPolicyStore();const worksheetStore = useWorkSheetStore();- const uiStore = useSQLEditorUIStore();const me = useCurrentUserV1();const worksheetV1Store = useWorkSheetStore();const { project } = storeToRefs(useSQLEditorStore());@@ -403,20 +395,20 @@ export const useSQLEditorWorksheetStore = defineStore(signal?: AbortSignal;}): Promise<SQLEditorTab | undefined> => {const connection = await extractWorksheetConnection({ database });- let worksheetTitle = title ?? "";- if (isSimilarDefaultSQLEditorTabTitle(worksheetTitle)) {- worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);- }- if (worksheet) {- const currentSheet = worksheetStore.getWorksheetByName(worksheet);- if (!currentSheet) {- return;- }- if (!isSimilarDefaultSQLEditorTabTitle(currentSheet.title)) {- worksheetTitle = currentSheet.title;- }+ // `title === undefined` means "don't change the title" — preserves the+ // current title on auto-save calls from useSQLEditorAutoSave which+ // never pass one. `title === ""` is a real, explicit empty title that+ // should be persisted (renders as the Untitled placeholder elsewhere).+ const currentSheet = worksheet+ ? worksheetStore.getWorksheetByName(worksheet)+ : undefined;+ if (worksheet && !currentSheet) {+ return;+ }+ const worksheetTitle = title ?? currentSheet?.title ?? "";+ if (worksheet && currentSheet) {const updated = await worksheetStore.patchWorksheet({...currentSheet,@@ -462,11 +454,8 @@ export const useSQLEditorWorksheetStore = defineStore(folders?: string[];database?: string;}): Promise<SQLEditorTab | undefined> => {- let worksheetTitle = title || NEW_WORKSHEET_TITLE;+ const worksheetTitle = title ?? "";const connection = await extractWorksheetConnection({ database });- if (!title && isValidDatabaseName(database)) {- worksheetTitle = suggestedTabTitleForSQLEditorConnection(connection);- }const newWorksheet = await worksheetStore.createWorksheet(create(WorksheetSchema, {@@ -503,7 +492,7 @@ export const useSQLEditorWorksheetStore = defineStore(});nextTick(() => {if (tab && !tab.connection?.database) {- uiStore.showConnectionPanel = true;+ useSQLEditorReactStore.getState().setShowConnectionPanel(true);}});return tab;diff --git a/frontend/src/utils/sqlEditor.ts b/frontend/src/utils/sqlEditor.tsindex 251e447738..77abf671cd 100644--- a/frontend/src/utils/sqlEditor.ts+++ b/frontend/src/utils/sqlEditor.ts@@ -19,19 +19,16 @@ import {type InstanceResource,} from "@/types/proto-es/v1/instance_service_pb";import { wrapRefAsPromise } from "@/utils";-import { formatAbsoluteDateTime } from "./datetime";-import {- extractDatabaseResourceName,- getInstanceResource,-} from "./v1/database";+import { getInstanceResource } from "./v1/database";import { instanceV1AllowsCrossDatabaseQuery } from "./v1/instance";-export const NEW_WORKSHEET_TITLE = "new worksheet";-export const defaultSQLEditorTab = (): SQLEditorTab => {return {id: uuidv1(),- title: defaultSQLEditorTabTitle(),+ // Tabs are created untitled. The UI renders a localized "Untitled"+ // placeholder when the title is empty; users name worksheets explicitly+ // when (and if) they save.+ title: "",connection: emptySQLEditorConnection(),statement: "",selectedStatement: "",@@ -52,10 +49,6 @@ export const defaultSQLEditorTab = (): SQLEditorTab => {};};-const defaultSQLEditorTabTitle = () => {- return formatAbsoluteDateTime(Date.now());-};-export const emptySQLEditorConnection = (): SQLEditorConnection => {return {instance: "",@@ -92,29 +85,6 @@ export const isSameSQLEditorConnection = (return a.instance === b.instance && a.database === b.database;};-export const isSimilarDefaultSQLEditorTabTitle = (title: string) => {- if (!title || title === NEW_WORKSHEET_TITLE) {- return true;- }- const regex = /(^|\s)(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;- return regex.test(title);-};--export const suggestedTabTitleForSQLEditorConnection = (- conn: SQLEditorConnection-) => {- const database = useDatabaseV1Store().getDatabaseByName(conn.database);- const parts: string[] = [];- const { databaseName, instance } = extractDatabaseResourceName(database.name);- if (isValidDatabaseName(database.name)) {- parts.push(databaseName);- } else if (isValidInstanceName(instance)) {- parts.push(getInstanceResource(database).title);- }- parts.push(defaultSQLEditorTabTitle());- return parts.join(" ");-};-export const isConnectedSQLEditorTab = (tab: SQLEditorTab) => {const { instance, database } = getConnectionForSQLEditorTab(tab);if (!instance) {