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 sql editor to zustand (#20426)
ecmadao11defe118dd5
diff --git a/frontend/.claude/settings.local.json b/frontend/.claude/settings.local.jsonnew file mode 100644index 0000000000..f3d8db8825--- /dev/null+++ b/frontend/.claude/settings.local.json@@ -0,0 +1,15 @@+{+ "permissions": {+ "allow": [+ "Bash(rm:*)",+ "Bash(pnpm store prune:*)",+ "Bash(pnpm install)",+ "Bash(pnpm dev)",+ "Bash(pnpm list:*)",+ "Bash(pnpm update:*)",+ "Bash(pnpm why:*)"+ ],+ "deny": [],+ "ask": []+ }+}diff --git a/frontend/src/plugins/ai/logic/getChatByTab.ts b/frontend/src/plugins/ai/logic/getChatByTab.tsnew file mode 100644index 0000000000..b8a7b8f2dd--- /dev/null+++ b/frontend/src/plugins/ai/logic/getChatByTab.ts@@ -0,0 +1,61 @@+import { last } from "lodash-es";+import { computed, ref, watch } from "vue";+import type { SQLEditorTab } from "@/types";+import { useConversationStore } from "../store";+import type { AIChatInfo, Conversation } from "../types";++const chatsByTab = new Map<string, AIChatInfo>();++const emptyChat: AIChatInfo = {+ list: ref([]),+ ready: ref(false),+ selected: ref(undefined),+};++const initializeChat = (tab: SQLEditorTab): AIChatInfo => {+ const store = useConversationStore();+ const ready = ref(false);+ store.fetchConversationListByConnection(tab.connection).then(() => {+ ready.value = true;+ });+ const list = computed(() => {+ const { instance, database } = tab.connection;+ return store.conversationList.filter(+ (c) => c.instance === instance && c.database === database+ );+ });+ const selected = ref<Conversation>();+ watch(+ [list, ready, selected],+ ([list, ready]) => {+ if (ready) {+ if (!selected.value) {+ selected.value = last(list);+ }+ }+ },+ { immediate: true }+ );+ return { list, ready, selected };+};++/**+ * Per-tab AI chat state, keyed by the tab's `(instance, database)`+ * connection. The returned `AIChatInfo` still holds Vue refs because the+ * conversation list is backed by a Pinia store — React consumers bridge+ * those refs (e.g. via `useVueState`). The tab itself is supplied by the+ * caller (sourced from the Zustand tab store) so this module no longer+ * depends on any Vue-reactive view of the current tab.+ */+export const getChatByTab = (tab: SQLEditorTab | undefined): AIChatInfo => {+ if (!tab) return emptyChat;+ const key = JSON.stringify({+ instance: tab.connection.instance,+ database: tab.connection.database,+ });+ const existed = chatsByTab.get(key);+ if (existed) return existed;+ const chat = initializeChat(tab);+ chatsByTab.set(key, chat);+ return chat;+};diff --git a/frontend/src/plugins/ai/logic/index.ts b/frontend/src/plugins/ai/logic/index.tsindex 48832c8775..7f07e01e65 100644--- a/frontend/src/plugins/ai/logic/index.ts+++ b/frontend/src/plugins/ai/logic/index.ts@@ -1,4 +1,4 @@export * from "./events";-export * from "./useChatByTab";+export * from "./getChatByTab";export * from "./useDynamicSuggestions";export * from "./prompt";diff --git a/frontend/src/plugins/ai/logic/useChatByTab.ts b/frontend/src/plugins/ai/logic/useChatByTab.tsdeleted file mode 100644index a179583c58..0000000000--- a/frontend/src/plugins/ai/logic/useChatByTab.ts+++ /dev/null@@ -1,62 +0,0 @@-import { last } from "lodash-es";-import { computed, ref, watch } from "vue";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";-import type { SQLEditorTab } from "@/types";-import { useConversationStore } from "../store";-import type { AIChatInfo, Conversation } from "../types";--const chatsByTab = new Map<string, AIChatInfo>();--export const useChatByTab = () => {- const store = useConversationStore();-- const initializeChat = (tab: SQLEditorTab): AIChatInfo => {- const ready = ref(false);- store.fetchConversationListByConnection(tab.connection).then(() => {- ready.value = true;- });- const list = computed(() => {- const { instance, database } = tab.connection;- return store.conversationList.filter(- (c) => c.instance === instance && c.database === database- );- });- const selected = ref<Conversation>();- watch(- [list, ready, selected],- ([list, ready]) => {- if (ready) {- if (!selected.value) {- selected.value = last(list);- }- }- },- { immediate: true }- );- return { list, ready, selected };- };-- const getChatByTab = (tab: SQLEditorTab) => {- const key = JSON.stringify({- instance: tab.connection.instance,- database: tab.connection.database,- });- const existed = chatsByTab.get(key);- if (existed) return existed;- const chat = initializeChat(tab);- chatsByTab.set(key, chat);- return chat;- };-- const emptyChat: AIChatInfo = {- list: ref([]),- ready: ref(false),- selected: ref(undefined),- };-- return computed(() => {- const tab = useSQLEditorTabStore().currentTab;- if (!tab) return emptyChat;- return getChatByTab(tab);- });-};diff --git a/frontend/src/plugins/ai/react/ChatPanel.tsx b/frontend/src/plugins/ai/react/ChatPanel.tsxindex b3806f59f1..65d6c52975 100644--- a/frontend/src/plugins/ai/react/ChatPanel.tsx+++ b/frontend/src/plugins/ai/react/ChatPanel.tsx@@ -3,8 +3,10 @@ import { head } from "lodash-es";import { Loader2 } from "lucide-react";import { useCallback, useEffect, useRef, useState } from "react";import { sqlServiceClientConnect } from "@/connect";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getCurrentSQLEditorTab,+ useCurrentSQLEditorTab,+} from "@/react/stores/sqlEditor/tab";import {type AICompletionRequest_Message,AICompletionRequest_MessageSchema,@@ -45,12 +47,9 @@ import { PromptInput } from "./PromptInput";* provider stashes a `pendingSendChat` payload.*/export function ChatPanel() {- const tabStore = useSQLEditorTabStore();+ const currentTab = useCurrentSQLEditorTab();const store = useConversationStore();- // Reactive bridge for `tabStore.currentTab` — Pinia mutates the tab- // proxy in place when the connection changes, so a plain- // `tabStore.currentTab` read at render time would miss updates.- const hasCurrentTab = useVueState(() => tabStore.currentTab != null);+ const hasCurrentTab = currentTab != null;const context = useAIContext();const {@@ -65,14 +64,11 @@ export function ChatPanel() {const [loading, setLoading] = useState(false);- // Reactive tab/connection signal so we can hide history on- // (instance, database) change. Reading the connection fields via- // `useVueState` gives us a stable string key the effect can depend on.- const connectionKey = useVueState(() => {- const tab = tabStore.currentTab;- if (!tab) return "";- return `${tab.connection.instance}|${tab.connection.database}`;- });+ // Tab/connection signal so we can hide history on (instance,+ // database) change — a stable string key the effect can depend on.+ const connectionKey = currentTab+ ? `${currentTab.connection.instance}|${currentTab.connection.database}`+ : "";useEffect(() => {setShowHistoryDialog(false);}, [connectionKey, setShowHistoryDialog]);@@ -87,7 +83,7 @@ export function ChatPanel() {async (query: string) => {const conversation = selected;if (!conversation) return;- const tab = tabStore.currentTab;+ const tab = getCurrentSQLEditorTab();if (!tab) return;const { messageList } = conversation;@@ -161,7 +157,6 @@ export function ChatPanel() {},[selected,- tabStore,store,context.engine,context.databaseMetadata,@@ -179,16 +174,17 @@ export function ChatPanel() {useEffect(() => {if (!ready) return;if (conversationList.length > 0) return;+ const tab = getCurrentSQLEditorTab();void store.createConversation({name: "",- instance: tabStore.currentTab?.connection.instance ?? "",- database: tabStore.currentTab?.connection.database ?? "",+ instance: tab?.connection.instance ?? "",+ database: tab?.connection.database ?? "",});// We intentionally watch only the boolean transition + the empty// condition, not the full `conversationList` reference — Vue's// version reacts on identity; the React version reacts on the// length so we don't fire each time a new message arrives.- }, [ready, conversationList.length, store, tabStore]);+ }, [ready, conversationList.length, store]);// Fire `requestAI` when a pending send-chat lands. The Vue version// used `watch(..., { flush: "post" })` — we approximate by waitingdiff --git a/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsxindex f519cffb9b..c334924c39 100644--- a/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx+++ b/frontend/src/plugins/ai/react/HistoryPanel/ConversationList.tsx@@ -12,9 +12,8 @@ import {AlertDialogTitle,} from "@/react/components/ui/alert-dialog";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab";import { useConversationStore } from "../../store";import type { Conversation } from "../../types";import { useAIContext } from "../context";@@ -40,7 +39,7 @@ import { ConversationRenameDialog } from "./ConversationRenameDialog";*/export function ConversationList() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();+ const currentTab = useCurrentSQLEditorTab();const store = useConversationStore();const { events, chat } = useAIContext();const { list, ready, selected, setSelected } = chat;@@ -53,11 +52,9 @@ export function ConversationList() {// Dismiss the rename dialog whenever the active tab's connection// changes — a stale dialog tied to a different tab's conversation// would mutate the wrong record on Save.- const connectionKey = useVueState(() => {- const tab = tabStore.currentTab;- if (!tab) return "";- return `${tab.connection.instance}|${tab.connection.database}`;- });+ const connectionKey = currentTab+ ? `${currentTab.connection.instance}|${currentTab.connection.database}`+ : "";useEffect(() => {setRename(undefined);setDeleteCandidate(undefined);diff --git a/frontend/src/plugins/ai/react/context.tsx b/frontend/src/plugins/ai/react/context.tsxindex b67dd09eeb..26156422ef 100644--- a/frontend/src/plugins/ai/react/context.tsx+++ b/frontend/src/plugins/ai/react/context.tsx@@ -6,13 +6,15 @@ import {useContext,useEffect,useMemo,+ useRef,useState,} from "react";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useVueState } from "@/react/hooks/useVueState";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getCurrentSQLEditorTab,+ useCurrentSQLEditorTab,+} from "@/react/stores/sqlEditor/tab";import { useDBSchemaV1Store, useSettingV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import type { DatabaseMetadata } from "@/types/proto-es/v1/database_service_pb";@@ -22,7 +24,7 @@ import {Setting_SettingName,} from "@/types/proto-es/v1/setting_service_pb";import { wrapRefAsPromise } from "@/utils";-import { aiContextEvents, useChatByTab } from "../logic";+import { aiContextEvents, getChatByTab } from "../logic";import { useConversationStore } from "../store";import type { AIContextEvents, Conversation } from "../types";@@ -111,55 +113,61 @@ export function AIContextProvider({ children }: { children: ReactNode }) {return EMPTY_AI_SETTING;});- const { instance: instanceRef, database: databaseRef } =- useConnectionOfCurrentSQLEditorTab();+ const currentTab = useCurrentSQLEditorTab();- const engine = useVueState<Engine | undefined>(- () => instanceRef.value.engine- );+ const { instance, database } = useConnectionOfCurrentSQLEditorTab();+ const engine: Engine | undefined = instance.engine;// Fetch database metadata on database change (mirrors Vue// `useMetadata`'s `watchEffect` + cache read). `useDBSchemaV1Store`// dedupes concurrent fetches, so firing this from the React effect// doesn't race with another caller. We read the cache via- // `useVueState` so cache hydration triggers a re-render.- const databaseName = useVueState(() => databaseRef.value.name);+ // `useVueState` (re-subscribed per database) so cache hydration+ // triggers a re-render.+ const databaseName = database.name;const dbSchemaStore = useDBSchemaV1Store();useEffect(() => {if (!databaseName) return;void dbSchemaStore.getOrFetchDatabaseMetadata({ database: databaseName });}, [databaseName, dbSchemaStore]);- const databaseMetadata = useVueState<DatabaseMetadata | undefined>(() =>- databaseName ? dbSchemaStore.getDatabaseMetadata(databaseName) : undefined+ const databaseMetadata = useVueState<DatabaseMetadata | undefined>(+ () =>+ databaseName+ ? dbSchemaStore.getDatabaseMetadata(databaseName)+ : undefined,+ { deps: [databaseName] });- const tabStore = useSQLEditorTabStore();- const schema = useVueState<string | undefined>(- () => tabStore.currentTab?.connection.schema- );+ const schema: string | undefined = currentTab?.connection.schema;// ---- Per-tab chat info -------------------------------------------------//- // `useChatByTab()` returns a Vue `ComputedRef<AIChatInfo>` where the- // inner `AIChatInfo` itself holds Vue refs (`list`, `ready`, `selected`).- // We hold the ComputedRef across renders and read each inner ref via- // its own `useVueState` getter — that way React subscribes to the right- // dep granularity (chat list mutations don't churn `ready`, and so on).- const chatByTabRef = useChatByTab();-- const chatList = useVueState<Conversation[]>(- () => chatByTabRef.value.list.value,- { deep: true }- );- const chatReady = useVueState<boolean>(() => chatByTabRef.value.ready.value);+ // `getChatByTab(tab)` returns an `AIChatInfo` whose inner `list`,+ // `ready`, and `selected` are Vue refs (the conversation list is+ // backed by a Pinia store). We select the tab from Zustand, memoize+ // the per-tab chat, and bridge each inner ref via its own+ // `useVueState` getter — subscribing at the right dep granularity+ // (chat list mutations don't churn `ready`, and so on). `deps:+ // [chatInfo]` re-subscribes each watch when the tab's chat is+ // swapped, since the swap arrives through Zustand rather than Vue.+ const chatInfo = useMemo(() => getChatByTab(currentTab), [currentTab]);++ const chatList = useVueState<Conversation[]>(() => chatInfo.list.value, {+ deep: true,+ deps: [chatInfo],+ });+ const chatReady = useVueState<boolean>(() => chatInfo.ready.value, {+ deps: [chatInfo],+ });const chatSelected = useVueState<Conversation | undefined>(- () => chatByTabRef.value.selected.value+ () => chatInfo.selected.value,+ { deps: [chatInfo] });const setChatSelected = useCallback((next: Conversation | undefined) => {- chatByTabRef.value.selected.value = next;+ chatInfo.selected.value = next;},- [chatByTabRef]+ [chatInfo]);const chat = useMemo<ReactAIChatInfo>(() => ({@@ -171,6 +179,12 @@ export function AIContextProvider({ children }: { children: ReactNode }) {[chatList, chatReady, chatSelected, setChatSelected]);+ // Live handle to the current tab's chat for the event listeners+ // below — they fire outside React's render and must read the latest+ // refs without re-subscribing on every tab switch.+ const chatInfoRef = useRef(chatInfo);+ chatInfoRef.current = chatInfo;+// ---- React-side state --------------------------------------------------const [showHistoryDialog, setShowHistoryDialog] = useState(false);@@ -188,31 +202,30 @@ export function AIContextProvider({ children }: { children: ReactNode }) {const conversationStore = useConversationStore();- // We need access to the latest chat refs from inside the listeners.- // `chatByTabRef` is stable across renders (it's a ComputedRef captured- // by useMemo([]) inside `useChatByTab`), but `tab` is a live Pinia- // value we read via `tabStore.currentTab` at fire time.+ // We need the latest chat refs + tab from inside the listeners.+ // `chatInfoRef` always points at the current tab's chat, and+ // `getCurrentSQLEditorTab()` reads the live Zustand tab at fire time.useEffect(() => {const offNewConversation = events.on("new-conversation",async ({ input }) => {- const tab = tabStore.currentTab;+ const tab = getCurrentSQLEditorTab();if (!tab) return;// Wait until the per-tab chat fetch has resolved before deciding// whether to reuse or create. Without this guard a brand-new tab// sees `selected === undefined` and creates a duplicate empty// conversation when one would have hydrated a beat later.- await wrapRefAsPromise(chatByTabRef.value.ready, /* expected */ true);+ await wrapRefAsPromise(chatInfoRef.current.ready, /* expected */ true);setShowHistoryDialog(false);- const sel = chatByTabRef.value.selected.value;+ const sel = chatInfoRef.current.selected.value;if (!sel || sel.messageList.length !== 0) {// Reuse if the current chat is empty, otherwise create a fresh one.const c = await conversationStore.createConversation({name: "",...tab.connection,});- chatByTabRef.value.selected.value = c;+ chatInfoRef.current.selected.value = c;}if (input) {// rAF mirrors the Vue version — gives `PromptInput`'s@@ -227,16 +240,16 @@ export function AIContextProvider({ children }: { children: ReactNode }) {);const offSendChat = events.on("send-chat", async ({ content, newChat }) => {- const tab = tabStore.currentTab;+ const tab = getCurrentSQLEditorTab();if (!tab) return;- await wrapRefAsPromise(chatByTabRef.value.ready, /* expected */ true);+ await wrapRefAsPromise(chatInfoRef.current.ready, /* expected */ true);if (newChat) {setShowHistoryDialog(false);const c = await conversationStore.createConversation({name: "",...tab.connection,});- chatByTabRef.value.selected.value = c;+ chatInfoRef.current.selected.value = c;}requestAnimationFrame(() => {setPendingSendChat({ content });@@ -247,9 +260,10 @@ export function AIContextProvider({ children }: { children: ReactNode }) {offNewConversation();offSendChat();};- // `events`, `tabStore`, `chatByTabRef`, `conversationStore` are stable- // singletons / Pinia store references — fine to depend on them.- }, [events, tabStore, chatByTabRef, conversationStore]);+ // `events` and `conversationStore` are stable singletons;+ // `chatInfoRef` / `getCurrentSQLEditorTab` read the latest values+ // at fire time — no need to re-subscribe on tab change.+ }, [events, conversationStore]);// ---- Memoized value bundle --------------------------------------------diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsxindex d66e855ab4..676381fe40 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.test.tsx@@ -9,11 +9,13 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ // Pinia bridge — resolves the current user's email from the Pinia ref.+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),useCurrentUserV1: vi.fn(),- // Legacy Pinia editor store.- useSQLEditorVueState: vi.fn(),- useSQLEditorTabStore: vi.fn(),+ // Zustand editor store project read.+ project: "projects/proj1" as string,+ // Current tab connection database used to derive default targets.+ currentTabDatabase: "instances/inst1/databases/db1" as string | undefined,// New zustand setters.setAsidePanelTab: vi.fn(),setHighlightAccessGrantName: vi.fn(),@@ -27,8 +29,8 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({@@ -37,12 +39,20 @@ vi.mock("@/store", () => ({useDatabaseV1Store: mocks.useDatabaseV1Store,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+// Zustand editor store — active project read.+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.project }),}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+// Zustand tab store — imperative getter to derive default targets.+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ getSQLEditorTabsState: () => ({+ currentTabId: "tab1",+ tabsById: new Map([+ ["tab1", { connection: { database: mocks.currentTabDatabase } }],+ ]),+ }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -299,19 +309,14 @@ const setupMocks = () => {value: { email: "[email protected]" },});- mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });-- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: {- connection: { database: "instances/inst1/databases/db1" },- },- });+ mocks.project = "projects/proj1";+ mocks.currentTabDatabase = "instances/inst1/databases/db1";mocks.useDatabaseV1Store.mockReturnValue({fetchDatabases: vi.fn().mockResolvedValue({ databases: [] }),});- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());};beforeEach(async () => {diff --git a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsxindex 45523cb645..e5dbc09e4a 100644--- a/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx+++ b/frontend/src/react/components/sql-editor/AccessGrantRequestDrawer.tsx@@ -19,10 +19,10 @@ import {SheetTitle,} from "@/react/components/ui/sheet";import { Textarea } from "@/react/components/ui/textarea";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_ISSUE_DETAIL } from "@/router/dashboard/projectV1";import {@@ -111,23 +111,23 @@ function AccessGrantRequestDrawerInner({}: AccessGrantRequestDrawerInnerProps) {const { t } = useTranslation();const currentUser = useCurrentUserV1();- const editorStore = useSQLEditorVueState();- const tabStore = useSQLEditorTabStore();const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const setHighlightAccessGrantName = useSQLEditorStore((s) => s.setHighlightAccessGrantName);- const currentUserEmail = useVueState(() => currentUser.value.email);- const project = useVueState(() => editorStore.project);+ const currentUserEmail = usePiniaBridge(() => currentUser.value.email);+ const project = useSQLEditorEditorState((s) => s.project);const defaultTargets = useMemo(() => {if (stableProps.targets && stableProps.targets.length > 0) {return stableProps.targets;}- const database = tabStore.currentTab?.connection?.database;+ const tabsState = getSQLEditorTabsState();+ const database = tabsState.tabsById.get(tabsState.currentTabId)?.connection+ ?.database;return database ? [database] : [];- }, [stableProps.targets, tabStore]);+ }, [stableProps.targets]);const [targets, setTargets] = useState<string[]>(defaultTargets);const [query, setQuery] = useState(stableProps.query ?? "");diff --git a/frontend/src/react/components/sql-editor/AccessPane.test.tsx b/frontend/src/react/components/sql-editor/AccessPane.test.tsxindex a07f5a2b8a..c94d45ea14 100644--- a/frontend/src/react/components/sql-editor/AccessPane.test.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.test.tsx@@ -9,11 +9,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),useProjectV1Store: vi.fn(),- // Legacy Pinia editor store.- useSQLEditorVueState: vi.fn(),- useSQLEditorTabStore: vi.fn(),+ // Zustand editor store project read.+ project: "projects/proj1" as string,// New zustand store state + setter.state: {highlightAccessGrantName: undefined as string | undefined,@@ -31,10 +29,6 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({useProjectV1Store: mocks.useProjectV1Store,useIssueV1Store: mocks.useIssueV1Store,@@ -49,12 +43,10 @@ vi.mock("@/react/stores/app", () => ({}),}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,-}));--vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+// Zustand editor store — active project read.+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.project }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -241,10 +233,7 @@ const setupDefaultMocks = () => {})),});- mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/proj1" });- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { connection: { database: "instances/inst1/databases/db1" } },- });+ mocks.project = "projects/proj1";mocks.state.highlightAccessGrantName = undefined;@@ -264,8 +253,6 @@ const setupDefaultMocks = () => {mocks.hasFeature.mockReturnValue(true);mocks.getDefaultPagination.mockReturnValue(20);-- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());};beforeEach(async () => {@@ -325,7 +312,6 @@ describe("AccessPane", () => {accessGrants: grants,nextPageToken: "",});- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());const { container, render, unmount } = renderIntoContainer(<AccessPane />);render();@@ -382,7 +368,6 @@ describe("AccessPane", () => {accessGrants: [grant],nextPageToken: "",});- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());const { container, render, unmount } = renderIntoContainer(<AccessPane />);render();diff --git a/frontend/src/react/components/sql-editor/AccessPane.tsx b/frontend/src/react/components/sql-editor/AccessPane.tsxindex 419ece7854..7ae57bbdcd 100644--- a/frontend/src/react/components/sql-editor/AccessPane.tsx+++ b/frontend/src/react/components/sql-editor/AccessPane.tsx@@ -16,11 +16,10 @@ import { AdvancedSearch } from "@/react/components/AdvancedSearch";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 { useAppStore } from "@/react/stores/app";import type { AccessGrantFilter as AccessFilter } from "@/react/stores/app/types";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {hasFeature,useDatabaseV1Store,@@ -48,7 +47,6 @@ export function AccessPane() {const { t } = useTranslation();const projectStore = useProjectV1Store();- const editorStore = useSQLEditorVueState();const searchMyAccessGrants = useAppStore((state) => state.searchMyAccessGrants);@@ -82,7 +80,7 @@ export function AccessPane() {scopes: DEFAULT_SCOPES,});- const projectName = useVueState(() => editorStore.project);+ const projectName = useSQLEditorEditorState((s) => s.project);const project = useMemo(() => {if (!projectName) return undefined;diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsxindex a04fe10de5..0833df5d3e 100644--- a/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx+++ b/frontend/src/react/components/sql-editor/AdminModeButton.test.tsx@@ -9,27 +9,50 @@ 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>(),- useSQLEditorVueState: vi.fn(),- useSQLEditorTabStore: vi.fn(),+ // Per-test controllable state read by the migrated Zustand/bridge hooks.+ state: {+ project: "projects/test" as string,+ allowAdmin: true,+ currentTabMode: "WORKSHEET" as string | undefined,+ isDisconnected: false,+ },+ updateCurrentTab: vi.fn(),+ useSQLEditorAllowAdmin: vi.fn(),}));vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+// Zustand editor store — selector hook returns the active project.+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.state.project }),}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+// Zustand tab store — selector hook, derived hooks, and imperative getter.+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { mode: string | undefined }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", { mode: mocks.state.currentTabMode }]]),+ }),+ useIsDisconnected: () => mocks.state.isDisconnected,+ getSQLEditorTabsState: () => ({+ updateCurrentTab: mocks.updateCurrentTab,+ }),+}));++// Pinia bridge hook that resolves the admin permission for the project.+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ useSQLEditorAllowAdmin: mocks.useSQLEditorAllowAdmin,}));vi.mock("@/react/components/ui/tooltip", () => ({@@ -60,26 +83,20 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- // Default: allow admin, WORKSHEET mode, connected- mocks.useSQLEditorVueState.mockReturnValue({ allowAdmin: true });- mocks.useSQLEditorTabStore.mockReturnValue({- updateCurrentTab: vi.fn(),- });- mocks.useVueState.mockImplementation((getter) => getter());+ // Default: allow admin, WORKSHEET mode, connected.+ mocks.state.project = "projects/test";+ mocks.state.allowAdmin = true;+ mocks.state.currentTabMode = "WORKSHEET";+ mocks.state.isDisconnected = false;+ mocks.useSQLEditorAllowAdmin.mockImplementation(() => mocks.state.allowAdmin);({ AdminModeButton } = await import("./AdminModeButton"));});describe("AdminModeButton", () => {test("renders nothing when allowAdmin is false", () => {- mocks.useSQLEditorVueState.mockReturnValue({ allowAdmin: false });- mocks.useVueState.mockImplementation((getter) => getter());- // Need to also mock the tab state reads. Configure useVueState to return- // appropriate values per call: allowAdmin=false, mode="WORKSHEET", isDisconnected=false- let callIdx = 0;- mocks.useVueState.mockImplementation(() => {- const values = [false, "WORKSHEET", false];- return values[callIdx++];- });+ mocks.state.allowAdmin = false;+ mocks.state.currentTabMode = "WORKSHEET";+ mocks.state.isDisconnected = false;const { container, render, unmount } = renderIntoContainer(<AdminModeButton />);@@ -89,11 +106,9 @@ describe("AdminModeButton", () => {});test("renders nothing when current tab mode is not WORKSHEET", () => {- let callIdx = 0;- mocks.useVueState.mockImplementation(() => {- const values = [true, "ADMIN", false];- return values[callIdx++];- });+ mocks.state.allowAdmin = true;+ mocks.state.currentTabMode = "ADMIN";+ mocks.state.isDisconnected = false;const { container, render, unmount } = renderIntoContainer(<AdminModeButton />);@@ -103,11 +118,9 @@ describe("AdminModeButton", () => {});test("renders disabled button when isDisconnected is true", () => {- let callIdx = 0;- mocks.useVueState.mockImplementation(() => {- const values = [true, "WORKSHEET", true];- return values[callIdx++];- });+ mocks.state.allowAdmin = true;+ mocks.state.currentTabMode = "WORKSHEET";+ mocks.state.isDisconnected = true;const { container, render, unmount } = renderIntoContainer(<AdminModeButton />);@@ -119,13 +132,9 @@ describe("AdminModeButton", () => {});test("click sets currentTab.mode to ADMIN", () => {- const updateCurrentTab = vi.fn();- mocks.useSQLEditorTabStore.mockReturnValue({ updateCurrentTab });- let callIdx = 0;- mocks.useVueState.mockImplementation(() => {- const values = [true, "WORKSHEET", false];- return values[callIdx++];- });+ mocks.state.allowAdmin = true;+ mocks.state.currentTabMode = "WORKSHEET";+ mocks.state.isDisconnected = false;const { container, render, unmount } = renderIntoContainer(<AdminModeButton />);@@ -133,7 +142,7 @@ describe("AdminModeButton", () => {act(() => {container.querySelector("button")?.click();});- expect(updateCurrentTab).toHaveBeenCalledWith({ mode: "ADMIN" });+ expect(mocks.updateCurrentTab).toHaveBeenCalledWith({ mode: "ADMIN" });unmount();});});diff --git a/frontend/src/react/components/sql-editor/AdminModeButton.tsx b/frontend/src/react/components/sql-editor/AdminModeButton.tsxindex 954e6c7ca8..1ab29b7a4c 100644--- a/frontend/src/react/components/sql-editor/AdminModeButton.tsx+++ b/frontend/src/react/components/sql-editor/AdminModeButton.tsx@@ -2,10 +2,14 @@ import { Wrench } 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 { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useIsDisconnected,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";type AdminModeButtonProps = {readonly size?: "sm" | "default";@@ -24,12 +28,12 @@ export function AdminModeButton({onEnter,}: AdminModeButtonProps) {const { t } = useTranslation();- const editorStore = useSQLEditorVueState();- const tabStore = useSQLEditorTabStore();-- const allowAdmin = useVueState(() => editorStore.allowAdmin);- const currentTabMode = useVueState(() => tabStore.currentTab?.mode);- const isDisconnected = useVueState(() => tabStore.isDisconnected);+ const project = useSQLEditorEditorState((s) => s.project);+ const allowAdmin = useSQLEditorAllowAdmin(project);+ const currentTabMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const isDisconnected = useIsDisconnected();if (!allowAdmin || currentTabMode !== "WORKSHEET") {return null;@@ -38,7 +42,7 @@ export function AdminModeButton({const label = t("sql-editor.admin-mode.self");const handleClick = () => {- tabStore.updateCurrentTab({ mode: "ADMIN" });+ getSQLEditorTabsState().updateCurrentTab({ mode: "ADMIN" });onEnter?.();};diff --git a/frontend/src/react/components/sql-editor/AsidePanel.tsx b/frontend/src/react/components/sql-editor/AsidePanel.tsxindex e7af4d5aa4..cedb7deaad 100644--- a/frontend/src/react/components/sql-editor/AsidePanel.tsx+++ b/frontend/src/react/components/sql-editor/AsidePanel.tsx@@ -1,10 +1,13 @@import { useCallback } from "react";import { useTranslation } from "react-i18next";import { ProjectSelect } from "@/react/components/ProjectSelect";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";+import { useIsDisconnected } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useActuatorV1Store } from "@/store";@@ -33,35 +36,33 @@ import { WorksheetPane } from "./WorksheetPane";*/export function AsidePanel() {const { t } = useTranslation();- const editorStore = useSQLEditorVueState();const actuatorStore = useActuatorV1Store();- const tabStore = useSQLEditorTabStore();const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);const asidePanelTab = useSQLEditorStore((s) => s.asidePanelTab);- const isDisconnected = useVueState(() => tabStore.isDisconnected);- const project = useVueState(() => editorStore.project);- const projectContextReady = useVueState(- () => editorStore.projectContextReady+ const isDisconnected = useIsDisconnected();+ const project = useSQLEditorEditorState((s) => s.project);+ const projectContextReady = useSQLEditorEditorState(+ (s) => s.projectContextReady);- const allowAccessDefaultProject = useVueState(() => {+ const allowAccessDefaultProject = usePiniaBridge(() => {const name = actuatorStore.serverInfo?.defaultProject ?? "";return hasProjectPermissionV2(defaultProject(name), "bb.projects.get");});- const allowCreateProject = useVueState(() =>+ const allowCreateProject = usePiniaBridge(() =>hasWorkspacePermissionV2("bb.projects.create"));const handleSwitchProject = useCallback((name: string) => {if (!name || !isValidProjectName(name)) {- editorStore.setProject("");+ getSQLEditorEditorState().setProject("");} else {void maybeSwitchProject(name);}},- [editorStore, maybeSwitchProject]+ [maybeSwitchProject]);// Vue's `<template #empty>` — rich empty state when the user is notdiff --git a/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsxindex 4f91f07d39..4c3afcb5ea 100644--- a/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx+++ b/frontend/src/react/components/sql-editor/AsidePanel/ActionBarTabItem.tsx@@ -1,11 +1,8 @@import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import { extractDatabaseResourceName } from "@/utils";import type { AvailableAction } from "../SchemaPane/actions";import { useSchemaPaneActions } from "../SchemaPane/actions";@@ -27,14 +24,12 @@ type Props = {* `<NTooltip placement="right">`.*/export function ActionBarTabItem({ action, disabled }: Props) {- const tabStore = useSQLEditorTabStore();- const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();+ const { database } = useConnectionOfCurrentSQLEditorTab();const { openNewTab } = useSchemaPaneActions();- const active = useVueState(- () => tabStore.currentTab?.viewState?.view === action.view+ const active = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.viewState?.view === action.view);- const database = useVueState(() => databaseRef.value);const handleClick = () => {openNewTab({diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsxindex 66de6d5756..cd5c89e394 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.test.tsx@@ -25,6 +25,12 @@ const mocks = vi.hoisted(() => {databases: [] as string[],databaseGroups: [] as string[],},+ } as {+ id: string;+ mode: string;+ title: string;+ connection: { database: string; instance: string };+ batchQueryContext: { databases: string[]; databaseGroups: string[] };},updateBatchQueryContext: vi.fn(),setCurrentTabId: vi.fn(),@@ -35,6 +41,9 @@ const mocks = vi.hoisted(() => {projectContextReady: true,allowAdmin: false,};+ // Plan-feature flags consumed via `useSQLEditorFeature`. Default ON for+ // render-path tests; individual tests flip to false to exercise gating.+ const features = { batchQuery: true, databaseGroups: true };const uiStore = { showConnectionPanel: true, asidePanelTab: "SCHEMA" };const databaseStore = {batchGetOrFetchDatabases: vi.fn().mockResolvedValue([]),@@ -87,6 +96,7 @@ const mocks = vi.hoisted(() => {return {tabStore,editorStore,+ features,uiStore,databaseStore,dbGroupStore,@@ -95,8 +105,7 @@ const mocks = vi.hoisted(() => {treeStore,instanceStore,currentUser,- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- featureToRef: vi.fn(() => ({ value: true })),+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),pushNotification: vi.fn(),};});@@ -105,12 +114,18 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,+}));++vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ // FEATURE_BATCH_QUERY === 1, FEATURE_DATABASE_GROUPS === 2 (see the+ // subscription_service_pb mock below).+ useSQLEditorFeature: (feature: number) =>+ feature === 1 ? mocks.features.batchQuery : mocks.features.databaseGroups,}));vi.mock("@/store", () => ({- featureToRef: mocks.featureToRef,pushNotification: mocks.pushNotification,useCurrentUserV1: () => mocks.currentUser,useDatabaseV1Store: () => mocks.databaseStore,@@ -120,12 +135,31 @@ vi.mock("@/store", () => ({useProjectV1Store: () => mocks.projectStore,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: () => mocks.tabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSupportBatchMode: () => mocks.tabStore.supportBatchMode,+ useIsInBatchMode: () => mocks.tabStore.isInBatchMode,+ useCurrentSQLEditorTab: () => mocks.tabStore.currentTab,+ getSQLEditorTabsState: () => ({+ updateBatchQueryContext: mocks.tabStore.updateBatchQueryContext,+ setCurrentTabId: mocks.tabStore.setCurrentTabId,+ updateTab: mocks.tabStore.updateTab,+ currentTabId: mocks.tabStore.currentTab?.id ?? "",+ tabsById: new Map(+ mocks.tabStore.currentTab+ ? [[mocks.tabStore.currentTab.id, mocks.tabStore.currentTab]]+ : []+ ),+ }),}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: () => mocks.editorStore,+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (+ selector: (s: { project: string; projectContextReady: boolean }) => unknown+ ) =>+ selector({+ project: mocks.editorStore.project,+ projectContextReady: mocks.editorStore.projectContextReady,+ }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -381,9 +415,11 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());// Reset feature flags default to true for render-path tests.- mocks.featureToRef.mockReturnValue({ value: true });+ mocks.features.batchQuery = true;+ mocks.features.databaseGroups = true;+ mocks.tabStore.supportBatchMode = true;mocks.tabStore.isInBatchMode = false;mocks.tabStore.currentTab = {id: "t-1",@@ -458,7 +494,8 @@ describe("ConnectionPane", () => {});test("disables DATABASE-GROUP tab when batch-query or database-group features missing", () => {- mocks.featureToRef.mockImplementation(() => ({ value: false }));+ mocks.features.batchQuery = false;+ mocks.features.databaseGroups = false;const { container, render, unmount } = renderIntoContainer(<ConnectionPane show={true} onMissingFeature={() => {}} />);diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsxindex 576b740417..bad05f29ad 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/ConnectionPane.tsx@@ -23,13 +23,18 @@ import { Tooltip } from "@/react/components/ui/tooltip";import { Tree, type TreeDataNode } from "@/react/components/ui/tree";import { countVisibleRows } from "@/react/components/ui/tree-utils";import { useCommonSearchScopeOptions } from "@/react/components/useCommonSearchScopeOptions";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useSQLEditorFeature } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useIsInBatchMode,+ useSupportBatchMode,+} from "@/react/stores/sqlEditor/tab";import {- featureToRef,pushNotification,useCurrentUserV1,useDatabaseV1Store,@@ -138,8 +143,6 @@ function ConnectionPaneWithHoverState(props: Props) {function ConnectionPaneInner({ show, onMissingFeature }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const setShowConnectionPanel = useSQLEditorStore((s) => s.setShowConnectionPanel);@@ -152,22 +155,24 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {const treeNodeKeysByTarget = useSQLEditorStore((s) => s.treeNodeKeysByTarget);const currentUser = useCurrentUserV1();- const supportBatchMode = useVueState(() => tabStore.supportBatchMode);- const isInBatchMode = useVueState(() => tabStore.isInBatchMode);+ const supportBatchMode = useSupportBatchMode();+ const isInBatchMode = useIsInBatchMode();const treeStoreState = useSQLEditorStore((s) => s.treeState);- const currentTab = useVueState(() => tabStore.currentTab);- const currentUserEmail = useVueState(() => currentUser.value.email);- const projectName = useVueState(() => editorStore.project);- const projectContextReady = useVueState(- () => editorStore.projectContextReady+ const currentTab = useCurrentSQLEditorTab();+ const currentUserEmail = usePiniaBridge(() => currentUser.value.email);+ const projectName = useSQLEditorEditorState((s) => s.project);+ const projectContextReady = useSQLEditorEditorState(+ (s) => s.projectContextReady+ );+ const environmentList = usePiniaBridge(+ () => environmentStore.environmentList);- const environmentList = useVueState(() => environmentStore.environmentList);- const hasBatchQueryFeature = useVueState(- () => featureToRef(PlanFeature.FEATURE_BATCH_QUERY).value+ const hasBatchQueryFeature = useSQLEditorFeature(+ PlanFeature.FEATURE_BATCH_QUERY);- const hasDatabaseGroupFeature = useVueState(- () => featureToRef(PlanFeature.FEATURE_DATABASE_GROUPS).value+ const hasDatabaseGroupFeature = useSQLEditorFeature(+ PlanFeature.FEATURE_DATABASE_GROUPS);// Paywall triggers go to the parent (lifted out of this subtree so the@@ -219,10 +224,10 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {// `flattenSelectedDatabasesFromGroup` and drives the tree-row checkbox// so users can see which databases are already implicitly included via// group selection (rendered as checked + disabled + tooltip in batch- // mode). useVueState — the underlying group cache mutates without the+ // mode). usePiniaBridge — the underlying group cache mutates without the// store reference changing, so a deep subscription catches new// matchedDatabases as they arrive from the FULL-view fetch.- const groupCoveredDatabaseTitles = useVueState(+ const groupCoveredDatabaseTitles = usePiniaBridge(() => {const map = new Map<string, string>();for (const groupName of selectedDatabaseGroupNames) {@@ -253,10 +258,9 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {selectedDatabaseGroupNames.length,]);- const projectTitle = useVueState(() => {- const p = editorStore.project;- if (!p) return "";- return projectStore.getProjectByName(p).title;+ const projectTitle = usePiniaBridge(() => {+ if (!projectName) return "";+ return projectStore.getProjectByName(projectName).title;});const scopeOptions = useCommonSearchScopeOptions([@@ -320,8 +324,8 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {// Keep the `dataSourceType` in the tab store aligned with the UI.useEffect(() => {- tabStore.updateBatchQueryContext({ dataSourceType });- }, [tabStore, dataSourceType]);+ getSQLEditorTabsState().updateBatchQueryContext({ dataSourceType });+ }, [dataSourceType]);// Pre-fetch display data for currently-selected databases (so tags render// with the right title immediately).@@ -355,7 +359,10 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {useEffect(() => {let cancelled = false;const compute = async () => {- const connection = tabStore.currentTab?.connection;+ const tabsState = getSQLEditorTabsState();+ const connection = tabsState.tabsById.get(+ tabsState.currentTabId+ )?.connection;if (!connection) {if (!cancelled) setSelectedKeys([]);return;@@ -386,7 +393,7 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {cancelled = true;unsubscribe();};- }, [tabStore, databaseStore, instanceStore, treeNodeKeysByTarget]);+ }, [databaseStore, instanceStore, treeNodeKeysByTarget]);// Context-menu imperative handle.const contextMenuRef = useRef<ConnectionContextMenuHandle>(null);@@ -426,8 +433,9 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {databaseStore,dbGroupStore);+ const tabsState = getSQLEditorTabsState();const currentConnection = getConnectionForSQLEditorTab(- tabStore.currentTab+ tabsState.tabsById.get(tabsState.currentTabId));if (!currentConnection.database?.name ||@@ -440,14 +448,14 @@ function ConnectionPaneInner({ show, onMissingFeature }: Props) {batchQueryContext: ctx,});} else {- tabStore.updateBatchQueryContext(ctx);+ getSQLEditorTabsState().updateBatchQueryContext(ctx);}return !!queryable;} finally {setSwitchingConnection(false);}},- [tabStore, databaseStore, dbGroupStore]+ [databaseStore, dbGroupStore]);const handleToggleDatabase = useCallback(@@ -789,7 +797,7 @@ function SelectedDatabaseTag({>;}) {const { t } = useTranslation();- const database = useVueState(resolveDatabase);+ const database = usePiniaBridge(resolveDatabase);const instance = useMemo(() => {if (!database) return null;return getInstanceResource(database);diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsxindex 5a6780ea67..10ad011e32 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseGroupTag.tsx@@ -2,7 +2,7 @@ import { Boxes, X } from "lucide-react";import { useEffect } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";import { useDBGroupStore } from "@/store";import { DatabaseGroupView } from "@/types/proto-es/v1/database_group_service_pb";@@ -32,7 +32,7 @@ export function DatabaseGroupTag({});}, [store, databaseGroupName]);- const databaseGroup = useVueState(() =>+ const databaseGroup = usePiniaBridge(() =>store.getDBGroupByName(databaseGroupName));diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsxindex 3eecc9ddea..2ae3e1d3db 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/DatabaseHoverPanel.tsx@@ -3,9 +3,8 @@ import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { getLayerRoot, LAYER_SURFACE_CLASS } from "@/react/components/ui/layer";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import type { Position, SQLEditorTreeNode } from "@/types";import {getDatabaseProject,@@ -36,10 +35,10 @@ export function DatabaseHoverPanel({onClickOutside,}: Props) {const { t } = useTranslation();- const editorStore = useSQLEditorVueState();+ const project = useSQLEditorEditorState((s) => s.project);const { state, position, update } = useHoverState();- const hasProjectContext = useVueState(() => !!editorStore.project);+ const hasProjectContext = !!project;const popoverRef = useRef<HTMLDivElement | null>(null);const [popoverHeight, setPopoverHeight] = useState(0);diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.tsindex 4e0f854356..c963d03982 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts+++ b/frontend/src/react/components/sql-editor/ConnectionPane/DatabaseHoverPanel/hover-state.ts@@ -64,7 +64,7 @@ export function useProvideHoverState(): HoverStateContextValue {);// Memoize the context value so an unrelated parent re-render (e.g.- // a Pinia tick triggering a `useVueState` update somewhere up the+ // a Pinia tick triggering a Vue-bridge update somewhere up the// tree) doesn't churn the `<HoverStateProvider value={…}>` reference.// Without this, every consumer of `useHoverState()` (every tree row// in `ConnectionPane`) re-renders, which can show up as the hoverdiff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsxindex 9c34769b29..18d6ade66e 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.test.tsx@@ -9,8 +9,7 @@ import type { SQLEditorTreeNode } from "@/types";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => ({- useSQLEditorTabStore: vi.fn(() => ({ supportBatchMode: true })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ useSupportBatchMode: vi.fn(() => true),}));vi.mock("react-i18next", () => ({@@ -19,12 +18,8 @@ vi.mock("react-i18next", () => ({vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,-}));--vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSupportBatchMode: mocks.useSupportBatchMode,}));vi.mock("@/react/components/instance/constants", () => ({@@ -101,8 +96,7 @@ const makeNode = (beforeEach(async () => {vi.clearAllMocks();- mocks.useSQLEditorTabStore.mockReturnValue({ supportBatchMode: true });- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.useSupportBatchMode.mockReturnValue(true);({ DatabaseNode } = await import("./DatabaseNode"));});@@ -133,8 +127,8 @@ describe("DatabaseNode", () => {unmount();});- test("renders checkbox only when tabStore.supportBatchMode is true", () => {- mocks.useVueState.mockImplementation(() => false);+ test("renders checkbox only when supportBatchMode is true", () => {+ mocks.useSupportBatchMode.mockReturnValue(false);const { container, render, unmount } = renderIntoContainer(<DatabaseNode node={makeNode()} keyword="" />);@@ -144,7 +138,7 @@ describe("DatabaseNode", () => {});test("checkbox click propagation is stopped", () => {- mocks.useVueState.mockImplementation(() => true);+ mocks.useSupportBatchMode.mockReturnValue(true);const onClick = vi.fn();const { container, render, unmount } = renderIntoContainer(<div onClick={onClick}>diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsxindex b837daedc6..b6ceffd9cb 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/DatabaseNode.tsx@@ -5,9 +5,8 @@ import { HighlightLabelText } from "@/react/components/HighlightLabelText";import { RequestQueryButton } from "@/react/components/sql-editor/RequestQueryButton";import { Checkbox } from "@/react/components/ui/checkbox";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSupportBatchMode } from "@/react/stores/sqlEditor/tab";import type { SQLEditorTreeNode } from "@/types";import { PermissionDeniedDetailSchema } from "@/types/proto-es/v1/common_pb";import {@@ -45,8 +44,7 @@ export function DatabaseNode({checkTooltip,onCheckedChange,}: Props) {- const tabStore = useSQLEditorTabStore();- const supportBatchMode = useVueState(() => tabStore.supportBatchMode);+ const supportBatchMode = useSupportBatchMode();const database = (node as SQLEditorTreeNode<"database">).meta.target;const instance = getInstanceResource(database);diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.test.tsxindex 8c9823ec5e..71830253b7 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.test.tsx@@ -17,11 +17,8 @@ vi.mock("./DatabaseNode", () => ({vi.mock("./LabelNode", () => ({LabelNode: () => <div data-testid="LabelNode" />,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: () => false,-}));-vi.mock("@/store", () => ({- featureToRef: () => ({ value: false }),+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ useSQLEditorFeature: () => false,}));vi.mock("@/types/proto-es/v1/subscription_service_pb", () => ({PlanFeature: { FEATURE_ENVIRONMENT_TIERS: "FEATURE_ENVIRONMENT_TIERS" },diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsxindex 93b6036732..cf3f91bc0b 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/TreeNode/Label.tsx@@ -1,9 +1,8 @@import { ShieldAlert } from "lucide-react";import { useTranslation } from "react-i18next";import { HighlightLabelText } from "@/react/components/HighlightLabelText";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorFeature } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { featureToRef } from "@/store";import type { SQLEditorTreeNode } from "@/types";import { NULL_ENVIRONMENT_NAME, UNKNOWN_ENVIRONMENT_NAME } from "@/types";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";@@ -71,8 +70,8 @@ function EnvironmentLabel({const isUnset =environment.name === UNKNOWN_ENVIRONMENT_NAME ||environment.name === NULL_ENVIRONMENT_NAME;- const hasEnvTierFeature = useVueState(- () => featureToRef(PlanFeature.FEATURE_ENVIRONMENT_TIERS).value+ const hasEnvTierFeature = useSQLEditorFeature(+ PlanFeature.FEATURE_ENVIRONMENT_TIERS);const isProtected =hasEnvTierFeature && environment.tags?.protected === "protected";diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsxindex 9d14b95237..21a3f6a8f9 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.test.tsx@@ -8,7 +8,6 @@ import type { SQLEditorTreeNode } from "@/types";).IS_REACT_ACT_ENVIRONMENT = true;const mocks = vi.hoisted(() => ({- useVueState: vi.fn<(getter: () => unknown) => unknown>(),allowAdmin: false,sqlEditorEventsEmit: vi.fn().mockResolvedValue(undefined),setShowConnectionPanel: vi.fn(),@@ -19,18 +18,20 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (key: string) => key }),}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: () => ({ currentTab: null }),+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ useSQLEditorAllowAdmin: () => mocks.allowAdmin,}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: () => ({ allowAdmin: mocks.allowAdmin }),+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: "projects/p" }),+ // `tab.ts` (pulled in via `getSQLEditorTabsState`) subscribes to the+ // editor store at import time; provide a no-op subscriber + getter so+ // the real tabs store module initializes cleanly.+ getSQLEditorEditorState: () => ({ project: "projects/p" }),+ subscribeSQLEditorEditorState: () => () => {},}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -140,7 +141,6 @@ const makeDatabaseNode = (beforeEach(async () => {vi.clearAllMocks();- mocks.useVueState.mockImplementation((getter) => getter());mocks.allowAdmin = false;({ useConnectionMenu } = await import("./actions"));});diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsxindex 335c50bc5e..4f2f982f3d 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx+++ b/frontend/src/react/components/sql-editor/ConnectionPane/actions.tsx@@ -6,10 +6,10 @@ import {} from "lucide-react";import { useCallback, useMemo } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_DATABASE_DETAIL } from "@/router/dashboard/projectV1";import type {@@ -68,24 +68,25 @@ export function setConnection(options: {database: database?.name ?? "",};- const tabStore = useSQLEditorTabStore();+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);const { maybeUpdateWorksheet, createWorksheet } =useSQLEditorStore.getState();const batchQueryContext: BatchQueryContext = Object.assign({ databases: [] } as BatchQueryContext,- tabStore.currentTab?.batchQueryContext,+ currentTab?.batchQueryContext,options.batchQueryContext);const createOrUpdate = () => {- if (!newTab && tabStore.currentTab) {+ if (!newTab && currentTab) {return maybeUpdateWorksheet({- tabId: tabStore.currentTab.id,- worksheet: tabStore.currentTab.worksheet,- title: tabStore.currentTab.title,+ tabId: currentTab.id,+ worksheet: currentTab.worksheet,+ title: currentTab.title,database: connection.database,- statement: tabStore.currentTab.statement,+ statement: currentTab.statement,});}return createWorksheet({@@ -95,7 +96,7 @@ export function setConnection(options: {void createOrUpdate().then((tab) => {if (tab) {- tabStore.updateTab(tab.id, { mode, batchQueryContext });+ getSQLEditorTabsState().updateTab(tab.id, { mode, batchQueryContext });useSQLEditorStore.getState().setAsidePanelTab("SCHEMA");}});@@ -108,11 +109,11 @@ export function setConnection(options: {*/export function useConnectionMenu(node: SQLEditorTreeNode | null) {const { t } = useTranslation();- const editorStore = useSQLEditorVueState();+ const project = useSQLEditorEditorState((s) => s.project);const setShowConnectionPanel = useSQLEditorStore((s) => s.setShowConnectionPanel);- const allowAdmin = useVueState(() => editorStore.allowAdmin);+ const allowAdmin = useSQLEditorAllowAdmin(project);const items = useMemo<ConnectionMenuItem[]>(() => {if (!node || node.disabled) return [];diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts b/frontend/src/react/components/sql-editor/ConnectionPane/tree.tsindex b2bc380027..f0bf8cd0fa 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts+++ b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {buildTreeImpl,mapTreeNodeByType,@@ -91,7 +91,7 @@ export function useSQLEditorTreeByEnvironment({ email }: Options): TreeByEnvironment {const databaseStore = useDatabaseV1Store();- const editorStore = useSQLEditorVueState();+ const project = useSQLEditorEditorState((s) => s.project);const environmentStore = useEnvironmentV1Store();const storageKey = useMemo(@@ -145,7 +145,7 @@ export function useSQLEditorTreeByEnvironment(try {const { databases, nextPageToken } = await databaseStore.fetchDatabases({- parent: editorStore.project,+ parent: project,pageToken,pageSize: getDefaultPagination(),filter: {@@ -163,7 +163,7 @@ export function useSQLEditorTreeByEnvironment(setFetchDataState({ loading: false });}},- [databaseStore, editorStore, environment]+ [databaseStore, project, environment]);// Keep a ref to the latest fetchDataState so the debounced fn can read itdiff --git a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsxindex e774746ca8..9c7f56ca61 100644--- a/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx+++ b/frontend/src/react/components/sql-editor/ContainerChooser.test.tsx@@ -9,8 +9,10 @@ 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>(),- useSQLEditorTabStore: vi.fn(),+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),+ tabTable: undefined as string | undefined,+ currentTabId: "tab1",+ getSQLEditorTabsState: vi.fn(),useDBSchemaV1Store: vi.fn(),useConnectionOfCurrentSQLEditorTab: vi.fn(),router: {@@ -22,17 +24,32 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({useDBSchemaV1Store: mocks.useDBSchemaV1Store,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+}));++vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { connection: { table?: string } }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: mocks.currentTabId,+ tabsById: new Map([+ [mocks.currentTabId, { connection: { table: mocks.tabTable } }],+ ]),+ }),+ getSQLEditorTabsState: mocks.getSQLEditorTabsState,}));vi.mock("@/router", () => ({@@ -92,13 +109,13 @@ const renderIntoContainer = (element: ReactElement) => {};const mockCosmosConnection = {- instance: { value: { engine: "COSMOSDB" } },- database: { value: { name: "instances/inst1/databases/cosmosdb" } },+ instance: { engine: "COSMOSDB" },+ database: { name: "instances/inst1/databases/cosmosdb" },};const mockMySQLConnection = {- instance: { value: { engine: "MYSQL" } },- database: { value: { name: "instances/inst1/databases/db1" } },+ instance: { engine: "MYSQL" },+ database: { name: "instances/inst1/databases/db1" },};beforeEach(async () => {@@ -106,8 +123,12 @@ beforeEach(async () => {mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue(mockCosmosConnection);- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { connection: { table: undefined } },+ mocks.tabTable = undefined;+ mocks.currentTabId = "tab1";+ mocks.getSQLEditorTabsState.mockReturnValue({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", { connection: {} }]]),+ updateCurrentTab: vi.fn(),});mocks.useDBSchemaV1Store.mockReturnValue({getDatabaseMetadata: vi.fn(() => ({@@ -119,7 +140,7 @@ beforeEach(async () => {],})),});- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());({ ContainerChooser } = await import("./ContainerChooser"));});@@ -178,15 +199,7 @@ describe("ContainerChooser", () => {});test("is chosen when a table is selected", () => {- const tab = { connection: { table: "container1" } };- mocks.useSQLEditorTabStore.mockReturnValue({ currentTab: tab });- let callIdx = 0;- mocks.useVueState.mockImplementation((getter) => {- callIdx++;- // 1: engine, 2: databaseName, 3: tabTable, 4: schemas, 5: queryParam- if (callIdx === 3) return "container1";- return getter();- });+ mocks.tabTable = "container1";const { container, render, unmount } = renderIntoContainer(<ContainerChooser />);diff --git a/frontend/src/react/components/sql-editor/ContainerChooser.tsx b/frontend/src/react/components/sql-editor/ContainerChooser.tsxindex 09041c671b..0e186366d8 100644--- a/frontend/src/react/components/sql-editor/ContainerChooser.tsx+++ b/frontend/src/react/components/sql-editor/ContainerChooser.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { useDBSchemaV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -19,14 +20,15 @@ const OptionValueUnspecified = "-1";*/export function ContainerChooser() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const dbSchemaStore = useDBSchemaV1Store();- const connection = useConnectionOfCurrentSQLEditorTab();+ const { instance, database } = useConnectionOfCurrentSQLEditorTab();- const engine = useVueState(() => connection.instance.value.engine);- const databaseName = useVueState(() => connection.database.value.name);- const tabTable = useVueState(() => tabStore.currentTab?.connection.table);- const schemas = useVueState(+ const engine = instance.engine;+ const databaseName = database.name;+ const tabTable = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.table+ );+ const schemas = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName).schemas);@@ -51,9 +53,15 @@ export function ContainerChooser() {const isChosen = value !== OptionValueUnspecified;const handleChange = (next: string) => {- if (!tabStore.currentTab) return;- tabStore.currentTab.connection.table =- next === OptionValueUnspecified ? undefined : next;+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);+ if (!currentTab) return;+ tabsState.updateCurrentTab({+ connection: {+ ...currentTab.connection,+ table: next === OptionValueUnspecified ? undefined : next,+ },+ });};// Seed from URL query parameter on mount and whenever the query param OR@@ -61,10 +69,10 @@ export function ContainerChooser() {// tracked both `route.query.table` and `tab.value` (the latter via the// setter's reactive reads) so that switching to a new tab with the URL// query still present re-seeded the new tab's connection.table.- const queryParam = useVueState(+ const queryParam = usePiniaBridge(() => router.currentRoute.value.query.table as string | undefined);- const currentTabId = useVueState(() => tabStore.currentTab?.id);+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);useEffect(() => {if (queryParam) handleChange(queryParam);}, [queryParam, currentTabId]);diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsxindex 3bfd7e8009..08662c17f8 100644--- a/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.test.tsx@@ -9,10 +9,10 @@ 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>(),- useSQLEditorTabStore: vi.fn(),- // Legacy Pinia useSQLEditorVueState (editor.ts).- useSQLEditorVueState: vi.fn(),+ useCurrentSQLEditorTab: vi.fn(),+ useIsInBatchMode: vi.fn(() => false),+ // editor zustand store selector value.+ projectContextReady: true,useConnectionOfCurrentSQLEditorTab: vi.fn(),// New zustand store setter.setShowConnectionPanel: vi.fn(),@@ -28,19 +28,21 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useCurrentSQLEditorTab: mocks.useCurrentSQLEditorTab,+ useIsInBatchMode: mocks.useIsInBatchMode,+}));++vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (+ selector: (s: { projectContextReady: boolean }) => unknown+ ) => selector({ projectContextReady: mocks.projectContextReady }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -110,20 +112,17 @@ const mockEnvironment = { name: "environments/prod" };beforeEach(async () => {vi.clearAllMocks();mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({- database: { value: mockDatabase },- instance: { value: mockInstance },- });- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { id: "tab1" },- isInBatchMode: false,+ database: mockDatabase,+ instance: mockInstance,});- mocks.useSQLEditorVueState.mockReturnValue({ projectContextReady: true });+ mocks.useCurrentSQLEditorTab.mockReturnValue({ id: "tab1" });+ mocks.useIsInBatchMode.mockReturnValue(false);+ mocks.projectContextReady = true;mocks.isValidInstanceName.mockReturnValue(true);mocks.isValidDatabaseName.mockReturnValue(true);mocks.getInstanceResource.mockReturnValue(mockInstance);mocks.getDatabaseEnvironment.mockReturnValue(mockEnvironment);mocks.extractDatabaseResourceName.mockReturnValue({ databaseName: "mydb" });- mocks.useVueState.mockImplementation((getter) => getter());({ DatabaseChooser } = await import("./DatabaseChooser"));});@@ -163,9 +162,7 @@ describe("DatabaseChooser", () => {});test("button is disabled when projectContextReady is false", () => {- mocks.useSQLEditorVueState.mockReturnValue({- projectContextReady: false,- });+ mocks.projectContextReady = false;const { container, render, unmount } = renderIntoContainer(<DatabaseChooser />);diff --git a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx b/frontend/src/react/components/sql-editor/DatabaseChooser.tsxindex 0669733bd2..6baac595fb 100644--- a/frontend/src/react/components/sql-editor/DatabaseChooser.tsx+++ b/frontend/src/react/components/sql-editor/DatabaseChooser.tsx@@ -3,14 +3,14 @@ import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";import { EnvironmentLabel } from "@/react/components/EnvironmentLabel";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ useCurrentSQLEditorTab,+ useIsInBatchMode,+} from "@/react/stores/sqlEditor/tab";import { isValidDatabaseName, isValidInstanceName } from "@/types";import {extractDatabaseResourceName,@@ -29,19 +29,16 @@ type DatabaseChooserProps = {*/export function DatabaseChooser({ disabled = false }: DatabaseChooserProps) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const setShowConnectionPanel = useSQLEditorStore((s) => s.setShowConnectionPanel);- const connection = useConnectionOfCurrentSQLEditorTab();+ const { database } = useConnectionOfCurrentSQLEditorTab();- const currentTab = useVueState(() => tabStore.currentTab);- const isInBatchMode = useVueState(() => tabStore.isInBatchMode);- const projectContextReady = useVueState(- () => editorStore.projectContextReady+ const currentTab = useCurrentSQLEditorTab();+ const isInBatchMode = useIsInBatchMode();+ const projectContextReady = useSQLEditorEditorState(+ (s) => s.projectContextReady);- const database = useVueState(() => connection.database.value);const instance = getInstanceResource(database);const environment = getDatabaseEnvironment(database);diff --git a/frontend/src/react/components/sql-editor/DiagramPanel.tsx b/frontend/src/react/components/sql-editor/DiagramPanel.tsxindex fa42b174cf..15dab428e6 100644--- a/frontend/src/react/components/sql-editor/DiagramPanel.tsx+++ b/frontend/src/react/components/sql-editor/DiagramPanel.tsx@@ -1,6 +1,6 @@import { SchemaDiagram } from "@/react/components/SchemaDiagram";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useDBSchemaV1Store } from "@/store";/**@@ -12,9 +12,8 @@ import { useDBSchemaV1Store } from "@/store";*/export function DiagramPanel() {const dbSchemaStore = useDBSchemaV1Store();- const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();- const database = useVueState(() => databaseRef.value);- const databaseMetadata = useVueState(+ const { database } = useConnectionOfCurrentSQLEditorTab();+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(database.name),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/EditorAction.test.tsx b/frontend/src/react/components/sql-editor/EditorAction.test.tsxindex 559070d6cb..f5089c41e6 100644--- a/frontend/src/react/components/sql-editor/EditorAction.test.tsx+++ b/frontend/src/react/components/sql-editor/EditorAction.test.tsx@@ -12,12 +12,18 @@ const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({t: (key: string, fallback?: string) => fallback ?? key,})),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorTabStore: vi.fn(),- useSQLEditorVueState: vi.fn(),+ // Stubbed state read by the migrated Zustand selector hooks.+ tabState: {+ currentTabId: "t1",+ tabsById: new Map<string, unknown>(),+ },+ currentTab: null as unknown,+ isDisconnected: false,+ resultRowsLimit: 500,+ updateCurrentTab: vi.fn(),useUIStateStore: vi.fn(),useWorkSheetStore: vi.fn(),- useWorkSheetAndTabStore: vi.fn(),+ useWorksheetAndTab: vi.fn(),useConnectionOfCurrentSQLEditorTab: vi.fn(),isWorksheetWritableV1: vi.fn(() => true),keyboardShortcutStr: vi.fn((s: string) => s),@@ -28,23 +34,30 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({useUIStateStore: mocks.useUIStateStore,useWorkSheetStore: mocks.useWorkSheetStore,- useWorkSheetAndTabStore: mocks.useWorkSheetAndTabStore,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useWorksheetAndTab", () => ({+ useWorksheetAndTab: mocks.useWorksheetAndTab,+}));++vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (selector: (s: unknown) => unknown) =>+ selector(mocks.tabState),+ useCurrentSQLEditorTab: () => mocks.currentTab,+ useIsDisconnected: () => mocks.isDisconnected,+ getSQLEditorTabsState: () => ({ updateCurrentTab: mocks.updateCurrentTab }),+}));++vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: unknown) => unknown) =>+ selector({ resultRowsLimit: mocks.resultRowsLimit }),}));vi.mock("@/utils", () => ({@@ -172,15 +185,18 @@ const setup = (options: SetupOptions = {}) => {connection: { database: "databases/db1", table },editorState: { selection: null },};- const updateCurrentTab = vi.fn();const saveIntroStateByKey = vi.fn();- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab,- isDisconnected,- updateCurrentTab,- });- mocks.useSQLEditorVueState.mockReturnValue({ resultRowsLimit: 500 });+ // Drive the migrated Zustand selector hooks off this single tab.+ mocks.currentTab = currentTab;+ mocks.isDisconnected = isDisconnected;+ mocks.resultRowsLimit = 500;+ mocks.tabState = {+ currentTabId: "t1",+ tabsById: new Map<string, unknown>([["t1", currentTab]]),+ };+ const updateCurrentTab = mocks.updateCurrentTab;+mocks.useUIStateStore.mockReturnValue({ saveIntroStateByKey });mocks.useWorkSheetStore.mockReturnValue({getWorksheetByName: vi.fn(() => ({@@ -188,15 +204,16 @@ const setup = (options: SetupOptions = {}) => {database: "databases/db1",})),});- mocks.useWorkSheetAndTabStore.mockReturnValue({+ mocks.useWorksheetAndTab.mockReturnValue({currentSheet: worksheet ? { name: worksheet, title: "sheet" } : undefined,+ isCreator: false,+ isReadOnly: false,});+ // useConnectionOfCurrentSQLEditorTab returns plain values now.mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({- instance: { value: { engine } },+ instance: { engine },});- mocks.useVueState.mockImplementation((getter) => getter());-return { currentTab, updateCurrentTab, saveIntroStateByKey };};diff --git a/frontend/src/react/components/sql-editor/EditorAction.tsx b/frontend/src/react/components/sql-editor/EditorAction.tsxindex 74795d97cc..84f3cebadf 100644--- a/frontend/src/react/components/sql-editor/EditorAction.tsx+++ b/frontend/src/react/components/sql-editor/EditorAction.tsx@@ -8,18 +8,17 @@ import {PopoverTrigger,} from "@/react/components/ui/popover";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";+import { useWorksheetAndTab } from "@/react/hooks/useWorksheetAndTab";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";-import {- useUIStateStore,- useWorkSheetAndTabStore,- useWorkSheetStore,-} from "@/store";+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useIsDisconnected,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";+import { useUIStateStore, useWorkSheetStore } from "@/store";import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";import { isWorksheetWritableV1, keyboardShortcutStr } from "@/utils";@@ -44,36 +43,35 @@ type Props = {*/export function EditorAction({ onExecute }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const uiStateStore = useUIStateStore();const worksheetStore = useWorkSheetStore();- const sheetAndTabStore = useWorkSheetAndTabStore();- const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();+ const { currentSheet: currentWorksheet } = useWorksheetAndTab();+ const { instance } = useConnectionOfCurrentSQLEditorTab();const [shareOpen, setShareOpen] = useState(false);- // Track each tab field as a separate primitive reactive subscription- // — Pinia mutates the tab proxy in place via `Object.assign`, so a- // getter that just returns `tabStore.currentTab` would only fire on- // tab switches (the proxy reference changing), not on `statement` /- // `status` / `connection.*` field flips that happen within the same- // tab. Splitting into one `useVueState` per field gives Vue a clean- // primitive value to compare on each change, so each individual- // mutation fires its own re-render (Run button enables as soon as- // the user types, Save button enables on `status` → DIRTY, etc.).- const currentTab = useVueState(() => tabStore.currentTab);- const tabStatement = useVueState(() => tabStore.currentTab?.statement ?? "");- const tabStatus = useVueState(() => tabStore.currentTab?.status);- const tabMode = useVueState(() => tabStore.currentTab?.mode);- const tabWorksheet = useVueState(() => tabStore.currentTab?.worksheet ?? "");- const tabConnectionTable = useVueState(- () => tabStore.currentTab?.connection.table ?? ""+ // Zustand selectors read fields directly off the active tab, so+ // in-place mutations (statement / status / connection.* via immer+ // produce) emit fresh slices and propagate through React without a+ // per-field workaround.+ const currentTab = useCurrentSQLEditorTab();+ const tabStatement = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.statement ?? ""+ );+ const tabStatus = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.status+ );+ const tabMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const tabWorksheet = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.worksheet ?? ""+ );+ const tabConnectionTable = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.table ?? "");- const isDisconnected = useVueState(() => tabStore.isDisconnected);- const instance = useVueState(() => instanceRef.value);- const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);- const currentWorksheet = useVueState(() => sheetAndTabStore.currentSheet);+ const isDisconnected = useIsDisconnected();+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);const isAdminMode = tabMode === "ADMIN";const showSheetsFeature = tabMode === "WORKSHEET";@@ -143,7 +141,7 @@ export function EditorAction({ onExecute }: Props) {const exitAdminMode = () => {// Inlined to avoid pulling `@/types` (monaco-editor transitive) into the// React bundle. Matches `DEFAULT_SQL_EDITOR_TAB_MODE` in `@/types/sqlEditor/tab`.- tabStore.updateCurrentTab({ mode: "WORKSHEET" });+ getSQLEditorTabsState().updateCurrentTab({ mode: "WORKSHEET" });};const handleClickSave = () => {diff --git a/frontend/src/react/components/sql-editor/ExecuteHint.tsx b/frontend/src/react/components/sql-editor/ExecuteHint.tsxindex 0abc8ff323..46e1739733 100644--- a/frontend/src/react/components/sql-editor/ExecuteHint.tsx+++ b/frontend/src/react/components/sql-editor/ExecuteHint.tsx@@ -2,10 +2,10 @@ import { Trans, useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { Alert } from "@/react/components/ui/alert";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorAllowAdmin } from "@/react/hooks/useSQLEditorBridge";import { applyPlanTitleToQuery } from "@/react/lib/plan/title";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";import {@@ -34,18 +34,18 @@ type Props = {*/export function ExecuteHint({ database, onClose }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const databaseStore = useDatabaseV1Store();const projectStore = useProjectV1Store();const storageStore = useStorageStore();-- const allowAdmin = useVueState(() => editorStore.allowAdmin);+ const project = useSQLEditorEditorState((s) => s.project);+ const allowAdmin = useSQLEditorAllowAdmin(project);const environment = database ? getDatabaseEnvironment(database) : undefined;const gotoCreateIssue = async () => {- const connectedDatabase = tabStore.currentTab?.connection.database ?? "";+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);+ const connectedDatabase = currentTab?.connection.database ?? "";if (!connectedDatabase) {pushNotification({module: "bytebase",@@ -60,11 +60,11 @@ export function ExecuteHint({ database, onClose }: Props) {const db = await databaseStore.getOrFetchDatabaseByName(connectedDatabase);// Fall back to `unknownProject()` (enforceIssueTitle=true) if the project// fetch rejects so the plan page opens with a blank title.- const project = await projectStore+ const projectInfo = await projectStore.getOrFetchProjectByName(db.project).catch(() => unknownProject());- const tab = tabStore.currentTab;+ const tab = tabsState.tabsById.get(tabsState.currentTabId);const statement = tab?.selectedStatement || tab?.statement || "";const sqlStorageKey = `bb.issues.sql.${uuidv4()}`;storageStore.put(sqlStorageKey, statement);@@ -77,7 +77,7 @@ export function ExecuteHint({ database, onClose }: Props) {};applyPlanTitleToQuery(query,- project,+ projectInfo,() => `[${databaseName}] ${t("issue.title.change-from-sql-editor")}`);diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsxindex 74c19cac9c..b59d7b9de9 100644--- a/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.test.tsx@@ -9,22 +9,26 @@ 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>(),- useSQLEditorVueState: vi.fn(),+ editorState: {+ isShowExecutingHint: false,+ executingHintDatabase: undefined as { name: string } | undefined,+ },+ setShowExecutingHint: vi.fn(),}));vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ // Selector hook — run the selector against the stubbed state.+ useSQLEditorEditorState: (selector: (s: unknown) => unknown) =>+ selector(mocks.editorState),+ getSQLEditorEditorState: () => ({+ setShowExecutingHint: mocks.setShowExecutingHint,+ }),}));vi.mock("@/react/components/ui/dialog", () => ({@@ -97,13 +101,11 @@ const renderIntoContainer = (element: ReactElement) => {const setup = (options: { show?: boolean; database?: { name: string } } = {}) => {- const store = {+ mocks.editorState = {isShowExecutingHint: options.show ?? false,executingHintDatabase: options.database,};- mocks.useSQLEditorVueState.mockReturnValue(store);- mocks.useVueState.mockImplementation((getter) => getter());- return store;+ return mocks.editorState;};beforeEach(async () => {@@ -145,7 +147,7 @@ describe("ExecutingHintModal", () => {});test("closing the dialog flips isShowExecutingHint to false", () => {- const store = setup({ show: true });+ setup({ show: true });const { container, render, unmount } = renderIntoContainer(<ExecutingHintModal />);@@ -158,7 +160,7 @@ describe("ExecutingHintModal", () => {?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});- expect(store.isShowExecutingHint).toBe(false);+ expect(mocks.setShowExecutingHint).toHaveBeenCalledWith(false);unmount();});diff --git a/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsxindex 87e5444e95..495b9ac478 100644--- a/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx+++ b/frontend/src/react/components/sql-editor/ExecutingHintModal.tsx@@ -4,8 +4,10 @@ import {DialogContent,DialogTitle,} from "@/react/components/ui/dialog";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";import { ExecuteHint } from "./ExecuteHint";/**@@ -15,13 +17,11 @@ import { ExecuteHint } from "./ExecuteHint";*/export function ExecutingHintModal() {const { t } = useTranslation();- const editorStore = useSQLEditorVueState();-- const show = useVueState(() => editorStore.isShowExecutingHint);- const database = useVueState(() => editorStore.executingHintDatabase);+ const show = useSQLEditorEditorState((s) => s.isShowExecutingHint);+ const database = useSQLEditorEditorState((s) => s.executingHintDatabase);const handleClose = () => {- editorStore.isShowExecutingHint = false;+ getSQLEditorEditorState().setShowExecutingHint(false);};return (diff --git a/frontend/src/react/components/sql-editor/FolderForm.test.tsx b/frontend/src/react/components/sql-editor/FolderForm.test.tsxindex 0010ada622..8d90daedb2 100644--- a/frontend/src/react/components/sql-editor/FolderForm.test.tsx+++ b/frontend/src/react/components/sql-editor/FolderForm.test.tsx@@ -170,10 +170,13 @@ const setupDefaultMocks = () => {makeFolderNode("/my/bar"),]);+ // The migrated `useSheetContextByView` returns plain values:+ // `folderTree` is a WorksheetFolderNode (not a Vue ref) and+ // `folderContext.rootPath` is a plain string.const viewContext = {- folderTree: { value: rootNode },+ folderTree: rootNode,folderContext: {- rootPath: { value: "/my" },+ rootPath: "/my",},};diff --git a/frontend/src/react/components/sql-editor/FolderForm.tsx b/frontend/src/react/components/sql-editor/FolderForm.tsxindex bcba9e6085..ca2be43d44 100644--- a/frontend/src/react/components/sql-editor/FolderForm.tsx+++ b/frontend/src/react/components/sql-editor/FolderForm.tsx@@ -6,10 +6,11 @@ import { LAYER_ROOT_ID } from "@/react/components/ui/layer";import { Popover, PopoverContent } from "@/react/components/ui/popover";import type { TreeDataNode } from "@/react/components/ui/tree";import { Tree } from "@/react/components/ui/tree";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import type { WorksheetFolderNode } from "@/views/sql-editor/Sheet";-import { useSheetContextByView } from "@/views/sql-editor/Sheet";+import {+ useSheetContextByView,+ type WorksheetFolderNode,+} from "@/views/sql-editor/Sheet";import { TreeNodePrefix } from "./TreeNodePrefix";type Props = {@@ -30,10 +31,8 @@ function toTreeData(export function FolderForm({ folder, onFolderChange }: Props) {const { t } = useTranslation();- const viewContext = useSheetContextByView("my");-- const folderTree = useVueState(() => viewContext.folderTree.value);- const rootPath = useVueState(() => viewContext.folderContext.rootPath.value);+ const { folderTree, folderContext } = useSheetContextByView("my");+ const rootPath = folderContext.rootPath;const [folderPath, setFolderPath] = useState(folder);const [showPopover, setShowPopover] = useState(false);diff --git a/frontend/src/react/components/sql-editor/GutterBar.test.tsx b/frontend/src/react/components/sql-editor/GutterBar.test.tsxindex a9e9c38082..23968d9ce9 100644--- a/frontend/src/react/components/sql-editor/GutterBar.test.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.test.tsx@@ -9,11 +9,11 @@ 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>(),- // Pinia legacy useSQLEditorVueState (editor.ts) — still imported by GutterBar- // until that store is migrated.- useSQLEditorVueState: vi.fn(),+ // Pinia bridge — runs the getter against the (mocked) Pinia stores.+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),useProjectV1Store: vi.fn(),+ // Zustand editor store project read.+ project: "projects/test" as string,// New zustand store.state: {asidePanelTab: "WORKSHEET" as string,@@ -26,16 +26,17 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({useProjectV1Store: mocks.useProjectV1Store,}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.project }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -98,7 +99,7 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();- mocks.useSQLEditorVueState.mockReturnValue({ project: "projects/test" });+ mocks.project = "projects/test";mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});@@ -109,7 +110,7 @@ beforeEach(async () => {describe("GutterBar", () => {test("renders 3 tabs when project does not allow JIT access", () => {- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});@@ -121,7 +122,7 @@ describe("GutterBar", () => {});test("renders 4 tabs when project allows JIT access", () => {- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: true }),});@@ -133,7 +134,7 @@ describe("GutterBar", () => {});test("click writes asidePanelTab via setAsidePanelTab", () => {- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});@@ -148,7 +149,7 @@ describe("GutterBar", () => {});test("logo link has target=_blank and rel=noopener noreferrer", () => {- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());mocks.useProjectV1Store.mockReturnValue({getProjectByName: () => ({ allowJustInTimeAccess: false }),});diff --git a/frontend/src/react/components/sql-editor/GutterBar.tsx b/frontend/src/react/components/sql-editor/GutterBar.tsxindex e9db4c257b..277d1c10de 100644--- a/frontend/src/react/components/sql-editor/GutterBar.tsx+++ b/frontend/src/react/components/sql-editor/GutterBar.tsx@@ -1,9 +1,9 @@import logoIcon from "@/assets/logo-icon.svg";import { Separator } from "@/react/components/ui/separator";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import type { AsidePanelTab } from "@/react/stores/sqlEditor";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { router } from "@/router";import { PROJECT_V1_ROUTE_DETAIL } from "@/router/dashboard/projectV1";import { WORKSPACE_ROUTE_LANDING } from "@/router/dashboard/workspaceRoutes";@@ -18,16 +18,15 @@ import { TabItem } from "./TabItem";* Replaces frontend/src/views/sql-editor/AsidePanel/GutterBar/GutterBar.vue.*/export function GutterBar() {- const editorStore = useSQLEditorVueState();const projectStore = useProjectV1Store();const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);+ const projectName = useSQLEditorEditorState((s) => s.project);- const project = useVueState(() => {- const name = editorStore.project;- return name ? projectStore.getProjectByName(name) : undefined;+ const project = usePiniaBridge(() => {+ return projectName ? projectStore.getProjectByName(projectName) : undefined;});- const routeProjectParam = useVueState(+ const routeProjectParam = usePiniaBridge(() => router.currentRoute.value.params.project as string | undefined);diff --git a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx b/frontend/src/react/components/sql-editor/HistoryPane.test.tsxindex 3a747d5658..35a05d8e76 100644--- a/frontend/src/react/components/sql-editor/HistoryPane.test.tsx+++ b/frontend/src/react/components/sql-editor/HistoryPane.test.tsx@@ -9,10 +9,10 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorTabStore: vi.fn(),- // Legacy Pinia editor store.- useSQLEditorVueState: vi.fn(),+ // Per-test controllable state read by the migrated Zustand hooks.+ currentTabDatabase: "db/test" as string | undefined,+ project: "projects/proj1" as string,+ addTab: vi.fn(),// Mutable per-test state for the zustand mock.historyEntry: {queryHistories: [] as Array<{@@ -32,20 +32,35 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({pushNotification: mocks.pushNotification,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+// Zustand tab store — selector hook + imperative getter.+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { connection: { database: string | undefined } }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "tab1",+ tabsById: new Map([+ ["tab1", { connection: { database: mocks.currentTabDatabase } }],+ ]),+ }),+ getSQLEditorTabsState: () => ({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", { connection: {} }]]),+ addTab: mocks.addTab,+ }),}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+// Zustand editor store — active project read.+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.project }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -149,20 +164,12 @@ beforeEach(async () => {mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { connection: { database: "db/test" } },- addTab: vi.fn(),- });-- mocks.useSQLEditorVueState.mockReturnValue({- project: "projects/proj1",- });+ mocks.currentTabDatabase = "db/test";+ mocks.project = "projects/proj1";mocks.historyEntry = { queryHistories: [], nextPageToken: "" };mocks.fetchQueryHistoryList.mockResolvedValue({ queryHistories: [] });- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());-Object.defineProperty(navigator, "clipboard", {value: { writeText: vi.fn().mockResolvedValue(undefined) },configurable: true,diff --git a/frontend/src/react/components/sql-editor/HistoryPane.tsx b/frontend/src/react/components/sql-editor/HistoryPane.tsxindex e15780ff4a..fdc733bbb7 100644--- a/frontend/src/react/components/sql-editor/HistoryPane.tsx+++ b/frontend/src/react/components/sql-editor/HistoryPane.tsx@@ -11,14 +11,16 @@ import {import { useTranslation } from "react-i18next";import { Button } from "@/react/components/ui/button";import { SearchInput } from "@/react/components/ui/search-input";-import { useVueState } from "@/react/hooks/useVueState";import type { QueryHistoryFilter } from "@/react/stores/sqlEditor";import {selectQueryHistoryEntry,useSQLEditorStore,} from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { pushNotification } from "@/store";import { DEBOUNCE_SEARCH_DELAY, getDateForPbTimestampProtoEs } from "@/types";import type { QueryHistory } from "@/types/proto-es/v1/sql_service_pb";@@ -32,8 +34,6 @@ import { sqlEditorEvents } from "@/views/sql-editor/events";export function HistoryPane() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const fetchQueryHistoryList = useSQLEditorStore((s) => s.fetchQueryHistoryList);@@ -47,10 +47,10 @@ export function HistoryPane() {const [, bumpRefresh] = useReducer((c: number) => c + 1, 0);const searchTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);- const currentTabDatabase = useVueState(- () => tabStore.currentTab?.connection.database+ const currentTabDatabase = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.database);- const project = useVueState(() => editorStore.project);+ const project = useSQLEditorEditorState((s) => s.project);const historyQuery = useMemo<QueryHistoryFilter>(() => ({@@ -87,7 +87,7 @@ export function HistoryPane() {// already up-to-date by the time the event fires (`useExecuteSQL` /// `webTerminal` chain the emit in `.finally` after `mergeLatest`// resolves). The bumped reducer state triggers a render, which- // re-runs the `useVueState` getter and reads the merged list —+ // re-runs the Vue-bridge getter and reads the merged list —// preserving any pages the user had already loaded.useEffect(() => {sqlEditorEvents.on("query-executed", bumpRefresh);@@ -111,13 +111,14 @@ export function HistoryPane() {const handleHistoryClick = async (history: QueryHistory) => {const { statement } = history;- if (tabStore.currentTab) {+ const tabsState = getSQLEditorTabsState();+ if (tabsState.tabsById.get(tabsState.currentTabId)) {await sqlEditorEvents.emit("append-editor-content", {content: statement,select: true,});} else {- tabStore.addTab(+ tabsState.addTab({title: `Query history at ${titleOfQueryHistory(history)}`,statement,diff --git a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsxindex 114645769b..a2b89fa31f 100644--- a/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx+++ b/frontend/src/react/components/sql-editor/MaskingReasonPopover.tsx@@ -7,8 +7,8 @@ import {PopoverContent,PopoverTrigger,} from "@/react/components/ui/popover";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { hasFeature, useProjectV1Store } from "@/store";import type { MaskingReason } from "@/types/proto-es/v1/sql_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";@@ -31,10 +31,11 @@ export function MaskingReasonPopover({const [showDrawer, setShowDrawer] = useState(false);const projectStore = useProjectV1Store();- const editorStore = useSQLEditorVueState();- const projectName = useVueState(() => editorStore.project);- const project = useVueState(() => projectStore.getProjectByName(projectName));+ const projectName = useSQLEditorEditorState((s) => s.project);+ const project = usePiniaBridge(() =>+ projectStore.getProjectByName(projectName)+ );const hasJITFeature = useMemo(() =>diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsxindex dd562a9446..faef2e88e7 100644--- a/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx+++ b/frontend/src/react/components/sql-editor/OpenAIButton.test.tsx@@ -10,8 +10,13 @@ import { Engine } from "@/types/proto-es/v1/common_pb";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorTabStore: vi.fn(),+ // Pinia bridge — runs the getter (resolves openAIEnabled from settings).+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),+ // Per-test controllable tab-derived state.+ tabState: {+ isDisconnected: false,+ currentMode: "WORKSHEET" as string | undefined,+ },// New zustand state mirror.state: { showAIPanel: false },setShowAIPanel: vi.fn((v: boolean) => {@@ -31,17 +36,32 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({useSettingV1Store: mocks.useSettingV1Store,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+// `useConnectionOfCurrentSQLEditorTab` now lives on the Pinia bridge hook.+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+}));++// Zustand tab store — derived hook + selector hook for connection/mode.+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useIsDisconnected: () => mocks.tabState.isDisconnected,+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { mode: string | undefined }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", { mode: mocks.tabState.currentMode }]]),+ }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -197,33 +217,25 @@ const setupDefaultMocks = (overrides: Partial<VueStateValues> = {}) => {};mocks.state.showAIPanel = values.showAIPanel;- const tabStore = {- isDisconnected: values.isDisconnected,- currentTab: { mode: values.currentMode },- };+ mocks.tabState.isDisconnected = values.isDisconnected;+ mocks.tabState.currentMode = values.currentMode;+const settingStore = {getOrFetchSettingByName: vi.fn().mockResolvedValue(undefined),getSettingByName: vi.fn(),};- mocks.useSQLEditorTabStore.mockReturnValue(tabStore);mocks.useSettingV1Store.mockReturnValue(settingStore);+ // Migrated hook returns PLAIN values — no Vue `.value` wrapper.mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({- instance: { value: values.instance },+ instance: values.instance,});- // useVueState order after migration: isDisconnected, currentMode,- // instance, openAIEnabled (showAIPanel now read via zustand selector).- const ordered = [- values.isDisconnected,- values.currentMode,- values.instance,- values.openAIEnabled,- ];- let idx = 0;- mocks.useVueState.mockImplementation(() => ordered[idx++]);-- return { tabStore, settingStore };+ // `openAIEnabled` is resolved via the Pinia bridge getter; surface the+ // configured value directly (it's the only bridge read in OpenAIButton).+ mocks.usePiniaBridge.mockImplementation(() => values.openAIEnabled);++ return { settingStore };};beforeEach(async () => {diff --git a/frontend/src/react/components/sql-editor/OpenAIButton.tsx b/frontend/src/react/components/sql-editor/OpenAIButton.tsxindex 7ec98a27d5..8a2e44b7da 100644--- a/frontend/src/react/components/sql-editor/OpenAIButton.tsx+++ b/frontend/src/react/components/sql-editor/OpenAIButton.tsx@@ -15,13 +15,14 @@ import {PopoverContent,PopoverTrigger,} from "@/react/components/ui/popover";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ useIsDisconnected,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";import { useSettingV1Store } from "@/store";@@ -49,11 +50,10 @@ type Props = {*/export function OpenAIButton({ actions, statement, size = "default" }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);const settingV1Store = useSettingV1Store();- const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();+ const { instance } = useConnectionOfCurrentSQLEditorTab();// Make sure the AI setting is resolved before we gate the enabled state.useEffect(() => {@@ -63,10 +63,11 @@ export function OpenAIButton({ actions, statement, size = "default" }: Props) {);}, [settingV1Store]);- const isDisconnected = useVueState(() => tabStore.isDisconnected);- const currentMode = useVueState(() => tabStore.currentTab?.mode);- const instance = useVueState(() => instanceRef.value);- const openAIEnabled = useVueState(() => {+ const isDisconnected = useIsDisconnected();+ const currentMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const openAIEnabled = usePiniaBridge(() => {const setting = settingV1Store.getSettingByName(Setting_SettingName.AI);return setting?.value?.value?.case === "ai"? setting.value.value.value.enableddiff --git a/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsxindex c629564d70..345c5660ee 100644--- a/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/ExternalTablesPanel/ExternalTablesPanel.tsx@@ -1,8 +1,8 @@import { ChevronLeft, Table as TableIcon } from "lucide-react";import { useState } from "react";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useDBSchemaV1Store } from "@/store";import { PanelSearchBox } from "../common/PanelSearchBox";import { ColumnsTable } from "../common/tables/ColumnsTable";@@ -17,9 +17,9 @@ import { ExternalTablesTable } from "./ExternalTablesTable";export function ExternalTablesPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx b/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsxindex 37d452777c..b2be37b047 100644--- a/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/FunctionsPanel/FunctionsPanel.tsx@@ -1,12 +1,12 @@import { ChevronLeft, FunctionSquare } from "lucide-react";import { useState } from "react";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {extractKeyWithPosition,keyWithPosition,} from "@/react/lib/keyWithPosition";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import { CodeViewer } from "../common/CodeViewer";import { PanelSearchBox } from "../common/PanelSearchBox";@@ -16,9 +16,9 @@ import { FunctionsTable } from "./FunctionsTable";export function FunctionsPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx b/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsxindex b60f5e8ebd..eb0098c10c 100644--- a/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/InfoPanel/InfoPanel.tsx@@ -1,9 +1,9 @@import { useState } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { keyWithPosition } from "@/react/lib/keyWithPosition";import { DatabaseOverviewInfo } from "@/react/pages/project/database-detail/overview/DatabaseOverviewInfo";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import {getInstanceResource,@@ -25,9 +25,9 @@ export function InfoPanel() {const { t } = useTranslation();const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsxindex 4fd98181d2..edbb557c4d 100644--- a/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/PackagesPanel/PackagesPanel.tsx@@ -1,12 +1,12 @@import { ChevronLeft, Package } from "lucide-react";import { useState } from "react";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {extractKeyWithPosition,keyWithPosition,} from "@/react/lib/keyWithPosition";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import { CodeViewer } from "../common/CodeViewer";import { PanelSearchBox } from "../common/PanelSearchBox";@@ -16,9 +16,9 @@ import { PackagesTable } from "./PackagesTable";export function PackagesPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/Panels.tsx b/frontend/src/react/components/sql-editor/Panels/Panels.tsxindex 2e9ae27bd3..b083522c14 100644--- a/frontend/src/react/components/sql-editor/Panels/Panels.tsx+++ b/frontend/src/react/components/sql-editor/Panels/Panels.tsx@@ -26,15 +26,16 @@ import { TriggersPanel } from "@/react/components/sql-editor/TriggersPanel";import { ViewsPanel } from "@/react/components/sql-editor/ViewsPanel";import { Alert } from "@/react/components/ui/alert";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {selectEditorPanelSize,useSQLEditorStore,} from "@/react/stores/sqlEditor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";import { isValidDatabaseName } from "@/types";import {@@ -73,23 +74,26 @@ const AIPaneFallback = () => (*/export function Panels() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const handleEditorPanelResize = useSQLEditorStore((s) => s.handleEditorPanelResize);const dbSchemaStore = useDBSchemaV1Store();- const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();+ const { database } = useConnectionOfCurrentSQLEditorTab();- const tab = useVueState(() => tabStore.currentTab);+ const tab = useCurrentSQLEditorTab();// Subscribe to `mode` as its own primitive — Pinia's tabStore mutates// the tab proxy in place via `Object.assign`, so `() => tabStore// .currentTab` only fires Vue's watch on tab-switches (proxy// reference changes), not on `mode` flipping between "WORKSHEET" and// "ADMIN" within the same tab. Without this, clicking the admin-mode// button doesn't swap to the `TerminalPanel`.- const tabMode = useVueState(() => tabStore.currentTab?.mode);- const databaseName = useVueState(() => databaseRef.value.name);- const view = useVueState(() => tabStore.currentTab?.viewState?.view);+ const tabMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const databaseName = database.name;+ const view = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.viewState?.view+ );const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);const isShowingCode = useSQLEditorStore((s) => s.isShowingCode);const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));@@ -105,7 +109,8 @@ export function Panels() {// a Vue provide chain to access it.useEffect(() => {const off = aiContextEvents.on("run-statement", async ({ statement }) => {- const t = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const t = tabsState.tabsById.get(tabsState.currentTabId);if (!t) return;updateViewState({ view: "CODE" });await nextAnimationFrame();@@ -124,7 +129,7 @@ export function Panels() {return () => {off();};- }, [tabStore, updateViewState, databaseV1Store, execute]);+ }, [updateViewState, databaseV1Store, execute]);const [databaseMetadata, setDatabaseMetadata] = useState<| Awaited<ReturnType<typeof dbSchemaStore.getOrFetchDatabaseMetadata>>diff --git a/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsxindex caff4a908d..9836ba551f 100644--- a/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/ProceduresPanel/ProceduresPanel.tsx@@ -1,12 +1,12 @@import { ChevronLeft, FileCode } from "lucide-react";import { useState } from "react";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {extractKeyWithPosition,keyWithPosition,} from "@/react/lib/keyWithPosition";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import { CodeViewer } from "../common/CodeViewer";import { PanelSearchBox } from "../common/PanelSearchBox";@@ -16,9 +16,9 @@ import { ProceduresTable } from "./ProceduresTable";export function ProceduresPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsxindex 2ead20e433..46149c92cf 100644--- a/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/SequencesPanel/SequencesPanel.tsx@@ -1,7 +1,7 @@import { useState } from "react";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { keyWithPosition } from "@/react/lib/keyWithPosition";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import { PanelSearchBox } from "../common/PanelSearchBox";import { useViewStateNav } from "../common/useViewStateNav";@@ -15,8 +15,8 @@ import { SequencesTable } from "./SequencesTable";export function SequencesPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx b/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsxindex f15c8ebeb0..115e7750c8 100644--- a/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/TablesPanel/TablesPanel.tsx@@ -1,6 +1,6 @@import { useState } from "react";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useDBSchemaV1Store } from "@/store";import { PanelSearchBox } from "../common/PanelSearchBox";import { useViewStateNav } from "../common/useViewStateNav";@@ -10,9 +10,9 @@ import { TablesTable } from "./TablesTable";export function TablesPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx b/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsxindex e81b856ed9..81b620979d 100644--- a/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/TriggersPanel/TriggersPanel.tsx@@ -1,12 +1,12 @@import { ChevronLeft, Zap } from "lucide-react";import { useState } from "react";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {extractKeyWithPosition,keyWithPosition,} from "@/react/lib/keyWithPosition";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDBSchemaV1Store } from "@/store";import { CodeViewer } from "../common/CodeViewer";import { PanelSearchBox } from "../common/PanelSearchBox";@@ -21,9 +21,9 @@ import { TriggersTable } from "./TriggersTable";export function TriggersPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx b/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsxindex 911ba18510..c035f37eae 100644--- a/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx+++ b/frontend/src/react/components/sql-editor/Panels/ViewsPanel/ViewsPanel.tsx@@ -1,6 +1,6 @@import { useState } from "react";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useDBSchemaV1Store } from "@/store";import { PanelSearchBox } from "../common/PanelSearchBox";import { useViewStateNav } from "../common/useViewStateNav";@@ -10,9 +10,9 @@ import { ViewsTable } from "./ViewsTable";export function ViewsPanel() {const dbSchemaStore = useDBSchemaV1Store();const { database } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const db = useVueState(() => database.value);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const db = database;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx b/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsxindex e4059c1296..0ffa05d01f 100644--- a/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/SchemaSelectToolbar.tsx@@ -6,8 +6,8 @@ import {SelectTrigger,SelectValue,} from "@/react/components/ui/select";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useDBSchemaV1Store } from "@/store";import { hasSchemaProperty } from "@/utils";import { useViewStateNav } from "./useViewStateNav";@@ -23,9 +23,9 @@ export function SchemaSelectToolbar() {const { t } = useTranslation();const dbSchemaStore = useDBSchemaV1Store();const { database, instance } = useConnectionOfCurrentSQLEditorTab();- const databaseName = useVueState(() => database.value.name);- const engine = useVueState(() => instance.value.engine);- const databaseMetadata = useVueState(+ const databaseName = database.name;+ const engine = instance.engine;+ const databaseMetadata = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName ?? ""),{ deep: true });diff --git a/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts b/frontend/src/react/components/sql-editor/Panels/common/useAIActions.tsindex 7e6b958f9f..7454656b2e 100644--- a/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts+++ b/frontend/src/react/components/sql-editor/Panels/common/useAIActions.ts@@ -2,7 +2,7 @@ import type * as monaco from "monaco-editor";import { useEffect } from "react";import type { ChatAction } from "@/plugins/ai/types";import type { MonacoModule } from "@/react/components/monaco/types";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useSettingV1Store } from "@/store";import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";@@ -34,7 +34,7 @@ export function useAIActions({// re-register or unregister live when an admin toggles AI access// while the editor is mounted (matches the Vue `watchEffect` behavior// in `editor-actions.ts`).- const aiEnabled = useVueState(() => readEnabled(settingStore));+ const aiEnabled = usePiniaBridge(() => readEnabled(settingStore));// Defensive fetch — the global `ProvideAIContext.vue` triggers this// on app mount, but a deep-link to a code panel can race that.useEffect(() => {diff --git a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsxindex 77c84e7649..39f0fcbc6a 100644--- a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx+++ b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.test.tsx@@ -38,19 +38,20 @@ const mocks = vi.hoisted(() => ({},}));-vi.mock("@/store", () => ({}));+// Build the Zustand-shaped state slice the hook's selectors read from.+const tabsState = () => ({+ currentTabId: "t1",+ tabsById: new Map([["t1", mocks.currentTab]]),+ updateTab: mocks.updateTab,+});-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: () => ({- updateTab: mocks.updateTab,- get currentTab() {- return mocks.currentTab;- },- }),-}));+vi.mock("@/store", () => ({}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: (getter: () => unknown) => getter(),+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ // Selector hook — run against the stubbed tabs state.+ useSQLEditorTabState: (selector: (s: unknown) => unknown) =>+ selector(tabsState()),+ getSQLEditorTabsState: () => tabsState(),}));vi.mock("@/types", () => ({diff --git a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.tsindex 53606c47ba..b48763078e 100644--- a/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts+++ b/frontend/src/react/components/sql-editor/Panels/common/useViewStateNav.ts@@ -1,6 +1,8 @@import { useCallback } from "react";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { defaultViewState } from "@/types";import type { EditorPanelViewState } from "@/types/sqlEditor/tabViewState";@@ -12,37 +14,40 @@ import type { EditorPanelViewState } from "@/types/sqlEditor/tabViewState";* because that file remains the Vue host through Stage 16.*/export function useViewStateNav() {- const tabStore = useSQLEditorTabStore();- const viewState = useVueState(() => tabStore.currentTab?.viewState, {- deep: true,- });- const tabId = useVueState(() => tabStore.currentTab?.id);+ const viewState = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.viewState+ );+ const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);const updateViewState = useCallback((patch: Partial<EditorPanelViewState>) => {- const id = tabStore.currentTab?.id;+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);+ const id = currentTab?.id;if (!id) return;- tabStore.updateTab(id, {+ tabsState.updateTab(id, {viewState: {...defaultViewState(),- ...tabStore.currentTab?.viewState,+ ...currentTab?.viewState,...patch,},});},- [tabStore]+ []);const setDetail = useCallback((patch: Partial<EditorPanelViewState["detail"]>) => {+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);updateViewState({detail: {- ...(tabStore.currentTab?.viewState.detail ?? {}),+ ...(currentTab?.viewState.detail ?? {}),...patch,},});},- [tabStore, updateViewState]+ [updateViewState]);const clearDetail = useCallback(() => {diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsxindex 50acf87a5d..8a8ff9c747 100644--- a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.test.tsx@@ -9,10 +9,21 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorTabStore: vi.fn(),- useSQLEditorVueState: vi.fn(),- useConnectionOfCurrentSQLEditorTab: vi.fn(),+ // Stubbed Zustand state slices read by selector hooks.+ tabState: { currentTabId: "t1", tabsById: new Map<string, unknown>() },+ editorState: {+ project: "projects/p1",+ resultRowsLimit: 1000,+ redisCommandOption: 0,+ },+ updateCurrentTab: vi.fn(),+ setRedisCommandOption: vi.fn(),+ setResultRowsLimit: vi.fn(),+ queryDataPolicy: {+ allowAdminDataSource: true,+ maximumResultRows: Number.MAX_VALUE,+ } as unknown,+ connectionResult: {} as unknown,getInstanceResource: vi.fn(),readableDataSourceType: vi.fn((type: number) => `type-${type}`),orderBy: vi.fn((arr: unknown[]) => arr),@@ -22,19 +33,26 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ useConnectionOfCurrentSQLEditorTab: () => mocks.connectionResult,+ useSQLEditorQueryDataPolicy: () => mocks.queryDataPolicy,+}));++vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (selector: (s: unknown) => unknown) =>+ selector(mocks.tabState),+ getSQLEditorTabsState: () => ({ updateCurrentTab: mocks.updateCurrentTab }),}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: unknown) => unknown) =>+ selector(mocks.editorState),+ getSQLEditorEditorState: () => ({+ setRedisCommandOption: mocks.setRedisCommandOption,+ setResultRowsLimit: mocks.setResultRowsLimit,+ }),}));vi.mock("@/utils", () => ({@@ -128,6 +146,14 @@ const renderIntoContainer = (element: ReactElement) => {};};+// Set the current tab's mode for the tab-state selector.+const setTabMode = (mode: string) => {+ mocks.tabState = {+ currentTabId: "t1",+ tabsById: new Map<string, unknown>([["t1", { mode }]]),+ };+};+beforeEach(async () => {vi.clearAllMocks();@@ -135,24 +161,22 @@ beforeEach(async () => {mocks.getInstanceResource.mockReturnValue(mockInstance);mocks.orderBy.mockImplementation((arr: unknown[]) => arr);- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { mode: "WORKSHEET" },- updateCurrentTab: vi.fn(),- });- mocks.useSQLEditorVueState.mockReturnValue({+ setTabMode("WORKSHEET");+ mocks.editorState = {+ project: "projects/p1",resultRowsLimit: 1000,redisCommandOption: 0,- queryDataPolicy: {- allowAdminDataSource: true,- maximumResultRows: Number.MAX_VALUE,- },- });- mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({- database: { value: { name: "instances/inst1/databases/mydb" } },- connection: { value: mockConnection },- });-- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ };+ mocks.queryDataPolicy = {+ allowAdminDataSource: true,+ maximumResultRows: Number.MAX_VALUE,+ };+ // useConnectionOfCurrentSQLEditorTab now returns plain values:+ // { connection, database, instance, environment }.+ mocks.connectionResult = {+ database: { name: "instances/inst1/databases/mydb" },+ connection: mockConnection,+ };({ QueryContextSettingPopover } = await import("./QueryContextSettingPopover"@@ -165,10 +189,7 @@ afterEach(() => {describe("QueryContextSettingPopover", () => {test("returns null when current tab mode is ADMIN", () => {- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { mode: "ADMIN" },- updateCurrentTab: vi.fn(),- });+ setTabMode("ADMIN");const { container, render, unmount } = renderIntoContainer(<QueryContextSettingPopover />);@@ -202,11 +223,6 @@ describe("QueryContextSettingPopover", () => {});test("clicking a data source label calls tabStore.updateCurrentTab with updated connection", () => {- const updateCurrentTab = vi.fn();- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { mode: "WORKSHEET" },- updateCurrentTab,- });const { container, render, unmount } = renderIntoContainer(<QueryContextSettingPopover />);@@ -220,7 +236,7 @@ describe("QueryContextSettingPopover", () => {// which causes the radio's onChange to fire via React's synthetic event delegation.dsLabel.click();});- expect(updateCurrentTab).toHaveBeenCalled();+ expect(mocks.updateCurrentTab).toHaveBeenCalled();unmount();});diff --git a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsxindex 4bb162b3c2..a7f3290901 100644--- a/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx+++ b/frontend/src/react/components/sql-editor/QueryContextSettingPopover.tsx@@ -10,13 +10,19 @@ import {PopoverTrigger,} from "@/react/components/ui/popover";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";-import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";import {useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ useSQLEditorQueryDataPolicy,+} from "@/react/hooks/useSQLEditorBridge";+import { cn } from "@/react/lib/utils";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { Engine } from "@/types/proto-es/v1/common_pb";import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";import {@@ -36,16 +42,18 @@ type Props = {*/export function QueryContextSettingPopover({ disabled = false }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();- const connection = useConnectionOfCurrentSQLEditorTab();+ const { database, connection: connectionRef } =+ useConnectionOfCurrentSQLEditorTab();+ const project = useSQLEditorEditorState((s) => s.project);- const currentTabMode = useVueState(() => tabStore.currentTab?.mode);- const database = useVueState(() => connection.database.value);- const connectionRef = useVueState(() => connection.connection.value);- const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);- const redisCommandOption = useVueState(() => editorStore.redisCommandOption);- const queryDataPolicy = useVueState(() => editorStore.queryDataPolicy);+ const currentTabMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode+ );+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);+ const redisCommandOption = useSQLEditorEditorState(+ (s) => s.redisCommandOption+ );+ const queryDataPolicy = useSQLEditorQueryDataPolicy(project);const show = currentTabMode !== "ADMIN";@@ -99,7 +107,7 @@ export function QueryContextSettingPopover({ disabled = false }: Props) {} else {delete nextConnection.dataSourceId;}- tabStore.updateCurrentTab({ connection: nextConnection });+ getSQLEditorTabsState().updateCurrentTab({ connection: nextConnection });};if (!show) return null;@@ -197,8 +205,9 @@ export function QueryContextSettingPopover({ disabled = false }: Props) {QueryOption_RedisRunCommandsOn.SINGLE_NODE}onChange={() => {- editorStore.redisCommandOption =- QueryOption_RedisRunCommandsOn.SINGLE_NODE;+ getSQLEditorEditorState().setRedisCommandOption(+ QueryOption_RedisRunCommandsOn.SINGLE_NODE+ );}}/><span>{t("sql-editor.redis-command.single-node")}</span>@@ -216,8 +225,9 @@ export function QueryContextSettingPopover({ disabled = false }: Props) {QueryOption_RedisRunCommandsOn.ALL_NODES}onChange={() => {- editorStore.redisCommandOption =- QueryOption_RedisRunCommandsOn.ALL_NODES;+ getSQLEditorEditorState().setRedisCommandOption(+ QueryOption_RedisRunCommandsOn.ALL_NODES+ );}}/><span>{t("sql-editor.redis-command.all-nodes")}</span>@@ -232,7 +242,7 @@ export function QueryContextSettingPopover({ disabled = false }: Props) {<MaxRowCountSelectvalue={resultRowsLimit ?? 1000}onChange={(n) => {- editorStore.resultRowsLimit = n;+ getSQLEditorEditorState().setResultRowsLimit(n);}}maximum={queryDataPolicy?.maximumResultRows ?? Number.MAX_VALUE}quaternarydiff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsxindex 7347ced7ab..d51b17b313 100644--- a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.test.tsx@@ -10,7 +10,6 @@ import { Engine } from "@/types/proto-es/v1/common_pb";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),useConnectionOfCurrentSQLEditorTab: vi.fn(),Trans: vi.fn(),}));@@ -30,25 +29,11 @@ vi.mock("react-i18next", () => ({),}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));--vi.mock("@/store", () => ({- // Transitive imports from AdminModeButton — provide stubs.-}));--vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+// `useConnectionOfCurrentSQLEditorTab` now lives on the Pinia bridge hook+// (the deleted tab-vue-state shim re-exported it). It returns PLAIN values+// `{ connection, database, instance, environment }` — no Vue refs.+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: vi.fn(() => ({- currentTab: undefined,- isDisconnected: true,- updateCurrentTab: vi.fn(),- })),-}));--vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: vi.fn(() => ({ allowAdmin: false })),}));vi.mock("@/react/components/instance/constants", () => ({@@ -88,14 +73,11 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.useVueState.mockImplementation((getter) => getter());mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue({instance: {- value: {- name: "instances/pg1",- title: "Production PG",- engine: Engine.POSTGRES,- },+ name: "instances/pg1",+ title: "Production PG",+ engine: Engine.POSTGRES,},});({ ReadonlyModeNotSupported } = await import("./ReadonlyModeNotSupported"));diff --git a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsxindex b459534d86..7f8fa7fcdb 100644--- a/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx+++ b/frontend/src/react/components/sql-editor/ReadonlyModeNotSupported.tsx@@ -1,8 +1,7 @@import { ShieldAlert } from "lucide-react";import { Trans, useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { AdminModeButton } from "./AdminModeButton";/**@@ -12,8 +11,7 @@ import { AdminModeButton } from "./AdminModeButton";*/export function ReadonlyModeNotSupported() {const { t } = useTranslation();- const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();- const instance = useVueState(() => instanceRef.value);+ const { instance } = useConnectionOfCurrentSQLEditorTab();return (<div className="w-full h-full flex flex-col items-center justify-center gap-y-2 p-4">diff --git a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx b/frontend/src/react/components/sql-editor/RequestQueryButton.tsxindex f74cffbe9b..723376ef66 100644--- a/frontend/src/react/components/sql-editor/RequestQueryButton.tsx+++ b/frontend/src/react/components/sql-editor/RequestQueryButton.tsx@@ -4,11 +4,11 @@ import { useTranslation } from "react-i18next";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 { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";import { RequestRoleSheet } from "@/react/pages/settings/RequestRoleSheet";import { useAppStore } from "@/react/stores/app";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { hasFeature, useProjectV1Store, useSubscriptionV1Store } from "@/store";import type { DatabaseResource, Permission } from "@/types";import { PRESET_ROLES, PresetRoleType } from "@/types";@@ -78,16 +78,16 @@ export function RequestQueryButton({const [showJITDrawer, setShowJITDrawer] = useState(false);const projectStore = useProjectV1Store();- const editorStore = useSQLEditorVueState();-const subscriptionStore = useSubscriptionV1Store();- const projectName = useVueState(() => editorStore.project);- const project = useVueState(() => projectStore.getProjectByName(projectName));- const hasCustomRoleFeature = useVueState(() =>+ const projectName = useSQLEditorEditorState((s) => s.project);+ const project = usePiniaBridge(() =>+ projectStore.getProjectByName(projectName)+ );+ const hasCustomRoleFeature = usePiniaBridge(() =>subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_CUSTOM_ROLES));- const defaultQueryRole = useVueState(() =>+ const defaultQueryRole = usePiniaBridge(() =>getDefaultQueryRole(roleList,permissionDeniedDetail.requiredPermissions,diff --git a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsxindex cb3f7ac2ba..6cf310fde9 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/BatchQuerySelect.tsx@@ -13,10 +13,14 @@ import { DatabaseTableView } from "@/react/components/database";import { EngineIconPath } from "@/react/components/instance/constants";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { pushNotification, useDatabaseV1Store, useSQLStore } from "@/store";import { isValidDatabaseName } from "@/types";import { ExportFormat } from "@/types/proto-es/v1/common_pb";@@ -78,48 +82,44 @@ export function BatchQuerySelect({onSelectedDatabaseChange,}: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const databaseStore = useDatabaseV1Store();const sqlStore = useSQLStore();- const editorStore = useSQLEditorVueState();+ const currentTab = useCurrentSQLEditorTab();+ const project = useSQLEditorEditorState((s) => s.project);+ const queryDataPolicy = useSQLEditorQueryDataPolicy(project);const [showEmpty, setShowEmpty] = useState(true);const [selectedDatabaseNames, setSelectedDatabaseNames] = useState<Set<string>>(new Set());- const queryDataPolicy = useVueState(() => editorStore.queryDataPolicy);- // Editor's per-execution row limit. Used by the dev-path export to infer- // probable truncation: `r.rows.length === resultRowsLimit` → query- // capped, likely more rows available.- const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);+ // Editor's per-execution row limit. Used by the dev-path export to+ // infer probable truncation: `r.rows.length === resultRowsLimit` →+ // query capped, likely more rows available.+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);- // Read the Map's `.keys()` directly inside the Vue getter so Vue's- // reactivity tracks the iteration. `useVueState(() => tabStore.currentTab)`- // would only fire when the tab object reference changes — Map mutations- // (which is how `useExecuteSQL.preExecute` adds new query contexts)- // wouldn't trigger React re-renders.- const queriedDatabaseNames = useVueState(- () => Array.from(tabStore.currentTab?.databaseQueryContexts?.keys() || []),- { deep: true }+ // Subscribe to the current tab's `databaseQueryContexts` Map. Immer+ // produces a fresh Map (and inner arrays) on every mutation, so the+ // selector re-runs whenever `preExecute` adds a context or `runQuery`+ // flips a status / writes a resultSet.+ const databaseQueryContexts = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.databaseQueryContexts);- // Track the contexts arrays themselves so the `items[].context` snapshot- // and `isEmptyQueryItem` computations stay in sync as `runQuery` mutates- // each context's `status` / `resultSet`.- const contextsByDatabase = useVueState(- () => {- const map = new Map<string, SQLEditorDatabaseQueryContext | undefined>();- const contexts = tabStore.currentTab?.databaseQueryContexts;- if (!contexts) return map;- for (const name of contexts.keys()) {- map.set(name, head(contexts.get(name)));- }- return map;- },- { deep: true }+ const queriedDatabaseNames = useMemo(+ () => Array.from(databaseQueryContexts?.keys() || []),+ [databaseQueryContexts]);+ const contextsByDatabase = useMemo(() => {+ const map = new Map<string, SQLEditorDatabaseQueryContext | undefined>();+ if (!databaseQueryContexts) return map;+ for (const name of databaseQueryContexts.keys()) {+ map.set(name, head(databaseQueryContexts.get(name)));+ }+ return map;+ }, [databaseQueryContexts]);+const items = useMemo<BatchQueryItem[]>(() => {return queriedDatabaseNames.map((name) => ({database: databaseStore.getDatabaseByName(name),@@ -180,13 +180,12 @@ export function BatchQuerySelect({}, [selectedDatabaseNames, databaseStore]);const handleCloseSingleResultView = (item: BatchQueryItem) => {- const tab = tabStore.currentTab;- const contexts = tab?.databaseQueryContexts?.get(item.database.name);+ const contexts = currentTab?.databaseQueryContexts?.get(item.database.name);if (!contexts) return;for (const context of contexts) {context.abortController?.abort();}- tab?.databaseQueryContexts?.delete(item.database.name);+ getSQLEditorTabsState().deleteDatabaseQueryContext(item.database.name);};// Subscribe to context-menu close-tab events.@@ -243,7 +242,7 @@ export function BatchQuerySelect({);return;}- const tab = tabStore.currentTab;+ const tab = currentTab;const groups: DownloadGroup[] = [];const limit = options.limit > 0 ? options.limit : Infinity;for (const databaseName of Array.from(selectedDatabaseNames)) {@@ -344,7 +343,8 @@ export function BatchQuerySelect({// === Prod path: per-database backend Export RPC ===const contents: DownloadContent[] = [];- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);for (const databaseName of Array.from(selectedDatabaseNames)) {const database = databaseStore.getDatabaseByName(databaseName);const context = head(tab?.databaseQueryContexts?.get(databaseName));@@ -359,7 +359,7 @@ export function BatchQuerySelect({format: options.format,statement: context.params.statement,limit: options.limit,- admin: tabStore.currentTab?.mode === "ADMIN",+ admin: tab?.mode === "ADMIN",password: options.password,schema: context.params.connection.schema,})diff --git a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsxindex 09f42003d0..f0f567f17b 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/DatabaseQueryContext.tsx@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";import { ResultView } from "@/react/components/sql-editor/ResultView";import { Button } from "@/react/components/ui/button";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import type {SQLEditorDatabaseQueryContext,SQLEditorQueryParams,@@ -31,7 +31,6 @@ export function DatabaseQueryContext({context,}: DatabaseQueryContextProps) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const { runQuery } = useExecuteSQL();const isExecuting = context.status === "EXECUTING";@@ -52,7 +51,7 @@ export function DatabaseQueryContext({const cancelQuery = () => {context.abortController?.abort();- tabStore.updateDatabaseQueryContext({+ getSQLEditorTabsState().updateDatabaseQueryContext({database: database.name,contextId: context.id,context: { status: "CANCELLED" },@@ -60,7 +59,7 @@ export function DatabaseQueryContext({};const execQuery = (params: SQLEditorQueryParams) => {- const next = tabStore.updateDatabaseQueryContext({+ const next = getSQLEditorTabsState().updateDatabaseQueryContext({database: database.name,contextId: context.id,context: { params },diff --git a/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsxindex 7cb7d51fa2..4e89505658 100644--- a/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx+++ b/frontend/src/react/components/sql-editor/ResultPanel/ResultPanel.tsx@@ -1,7 +1,6 @@import { CircleAlert, Loader2, X } from "lucide-react";import { useEffect, useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import { watch } from "vue";import { Alert } from "@/react/components/ui/alert";import {ContextMenu,@@ -16,9 +15,13 @@ import {TabsTrigger,} from "@/react/components/ui/tabs";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useIsInBatchMode,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import type { SQLEditorDatabaseQueryContext } from "@/types";import { getDataSourceTypeI18n } from "@/types";import type { Database } from "@/types/proto-es/v1/database_service_pb";@@ -39,68 +42,41 @@ import { DatabaseQueryContext } from "./DatabaseQueryContext";* - `selectedDatabase`: which database the inner tabs are showing.* - `selectedTab`: which query-context id is the active inner tab.*- * State read from Pinia via `useVueState`:- * - `tabStore.currentTab.databaseQueryContexts.get(selectedDatabase.name)` —- * the array of query contexts for the active database. `{ deep: true }`- * so per-context status / resultSet flips re-render this tree without- * the Map reference changing.+ * State read from the tab Zustand store:+ * - `tab.databaseQueryContexts.get(selectedDatabase.name)` — the array+ * of query contexts for the active database. Immer produces fresh+ * references on every mutation, so per-context status / resultSet+ * flips re-render this tree.*/export function ResultPanel() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();+ const currentTab = useCurrentSQLEditorTab();+ const isInBatchMode = useIsInBatchMode();const [selectedDatabase, setSelectedDatabase] = useState<Database>();const [selectedTab, setSelectedTab] = useState<string>();- // Force a React re-render whenever **anything** changes inside the- // current tab's `databaseQueryContexts` Map — Map mutations- // (`set` / `delete`), inner-array mutations (`unshift` / `splice`),- // and per-item field flips (status PENDING → EXECUTING → DONE,- // resultSet writes). Keying the watch on the Map itself (rather than- // `Map.get(selectedDatabase.name)`) is critical: when this component- // first mounts `selectedDatabase` is `undefined`, and a getter that- // bailed out early would register **no** Vue reactive deps — leaving- // the watch dead forever, since `selectedDatabase` becoming defined- // doesn't fire any watcher. Tracking the Map directly with `deep:- // true` keeps the watch live across all reactive transitions, so the- // newly-created PENDING context reaches `<DatabaseQueryContext>` and- // its auto-run effect can advance the status.- const [, forceRender] = useState(0);- const tabIdForWatch = useVueState(() => tabStore.currentTab?.id);- useEffect(() => {- const stop = watch(- () => tabStore.currentTab?.databaseQueryContexts,- () => forceRender((v) => v + 1),- { deep: true, flush: "sync" }- );- return () => {- stop();- };- // Re-arm the watch when the active tab changes — each tab has its- // own `databaseQueryContexts` Map and Vue's auto-re-tracking only- // fires when the previously-tracked deps change. Without this,- // switching tabs would lose live updates from the new tab's Map.- }, [tabStore, tabIdForWatch]);+ // Subscribe to the current tab's `databaseQueryContexts` Map. The+ // store mutates this Map (and the inner arrays + entries) via immer,+ // so every mutation produces a new reference — Zustand re-runs this+ // selector on each change.+ const databaseQueryContexts = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.databaseQueryContexts+ );// Re-spread on every render so the iteration sees the latest array- // (Pinia mutates in place; cached refs would hide additions). Items- // are still the same Vue reactive proxies so `context.status` reads- // the live value.+ // (the store mutates via immer; cached refs would hide additions).const queryContexts: SQLEditorDatabaseQueryContext[] | undefined = (() => {const name = selectedDatabase?.name;if (!name) return undefined;- const arr = tabStore.currentTab?.databaseQueryContexts?.get(name);+ const arr = databaseQueryContexts?.get(name);return arr ? [...arr] : undefined;})();- const isBatchQuery = useVueState(() => {- const contexts = tabStore.currentTab?.databaseQueryContexts;- return contexts ? contexts.size > 1 : false;- });+ const isBatchQuery = (databaseQueryContexts?.size ?? 0) > 1;- const batchModeDataSourceType = useVueState(() => {- if (!tabStore.isInBatchMode) return null;- return tabStore.currentTab?.batchQueryContext.dataSourceType ?? null;- });+ const batchModeDataSourceType = isInBatchMode+ ? (currentTab?.batchQueryContext?.dataSourceType ?? null)+ : null;const hasMultipleContexts = (queryContexts?.length ?? 0) > 1;@@ -141,7 +117,7 @@ export function ResultPanel() {};const closeTab = (id: string) => {- const next = tabStore.removeDatabaseQueryContext({+ const next = getSQLEditorTabsState().removeDatabaseQueryContext({database: selectedDatabase?.name ?? "",contextId: id,});@@ -149,7 +125,7 @@ export function ResultPanel() {};const closeOthers = (id: string) => {- tabStore.batchRemoveDatabaseQueryContext({+ getSQLEditorTabsState().batchRemoveDatabaseQueryContext({database: selectedDatabase?.name ?? "",contextIds:queryContexts?.filter((c) => c.id !== id).map((c) => c.id) ?? [],@@ -160,7 +136,7 @@ export function ResultPanel() {const closeToTheRight = (id: string) => {const idx = queryContexts?.findIndex((c) => c.id === id) ?? -1;if (idx < 0) return;- tabStore.batchRemoveDatabaseQueryContext({+ getSQLEditorTabsState().batchRemoveDatabaseQueryContext({database: selectedDatabase?.name ?? "",contextIds: queryContexts?.slice(idx + 1).map((c) => c.id) ?? [],});@@ -168,7 +144,9 @@ export function ResultPanel() {};const closeAll = () => {- tabStore.deleteDatabaseQueryContext(selectedDatabase?.name ?? "");+ getSQLEditorTabsState().deleteDatabaseQueryContext(+ selectedDatabase?.name ?? ""+ );setSelectedTab(undefined);};@@ -255,7 +233,7 @@ export function ResultPanel() {<Alert variant="warning" className="mb-2">{t("sql-editor.batch-query.select-data-source.not-match", {expect: getDataSourceTypeI18n(- tabStore.currentTab?.batchQueryContext.dataSourceType+ currentTab?.batchQueryContext?.dataSourceType),actual: getDataSourceTypeI18n(dataSourceInContext(context)?.typediff --git a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsxindex f181f33b1d..a7afc084d1 100644--- a/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/ResultView.tsx@@ -18,10 +18,10 @@ import {} from "@/react/components/ui/tabs";import { Tooltip } from "@/react/components/ui/tooltip";import { isDisallowChangeDatabaseError } from "@/react/hooks/useExecuteSQL";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import {pushNotification,useDatabaseV1Store,@@ -77,16 +77,13 @@ export function ResultView({}: ResultViewProps) {const { t } = useTranslation();const policyStore = usePolicyV1Store();- // Hoist the editor state singleton so the useVueState getters below don't- // appear to call a React Hook inside a callback (Sonar S6440).- const editorState = useSQLEditorVueState();- const queryDataPolicy = useVueState(() => editorState.queryDataPolicy);+ const project = useSQLEditorEditorState((s) => s.project);+ const queryDataPolicy = useSQLEditorQueryDataPolicy(project);// The editor's per-execution row limit. A result whose .rows.length// exactly equals this is probably truncated; fewer rows is probably// complete. Used by the dev-path export to WARN only when the user's// requested limit can't be satisfied from the cached result.- const resultRowsLimit = useVueState(() => editorState.resultRowsLimit);- const tabStore = useSQLEditorTabStore();+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);const permissionDeniedError = useMemo<PermissionDeniedDetail | undefined@@ -274,7 +271,9 @@ export function ResultView({}// === Prod path: backend Export RPC ===- const admin = tabStore.currentTab?.mode === "ADMIN";+ const tabsState = getSQLEditorTabsState();+ const admin =+ tabsState.tabsById.get(tabsState.currentTabId)?.mode === "ADMIN";try {const content = await useSQLStore().exportData(create(ExportRequestSchema, {diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex 7a1e7c87c0..ee36c27c78 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -27,10 +27,10 @@ import { EllipsisText } from "@/react/components/ui/ellipsis-text";import { Switch } from "@/react/components/ui/switch";import { Tooltip } from "@/react/components/ui/tooltip";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";-import { useVueState } from "@/react/hooks/useVueState";+import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import type {SQLEditorDatabaseQueryContext,SQLEditorQueryParams,@@ -229,13 +229,13 @@ function SingleResultViewInner({setNoSQLTableView,}: SingleResultViewInnerProps) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();- const currentTabMode = useVueState(() => tabStore.currentTab?.mode);- const resultRowsLimit = useVueState(() => editorStore.resultRowsLimit);- const policyMaxRows = useVueState(- () => editorStore.queryDataPolicy.maximumResultRows+ const project = useSQLEditorEditorState((s) => s.project);+ const queryDataPolicy = useSQLEditorQueryDataPolicy(project);+ const currentTabMode = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.mode);+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);+ const policyMaxRows = queryDataPolicy.maximumResultRows;const { runQuery } = useExecuteSQL();const { copyAll } = useSelectionContext();diff --git a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsxindex 0c2ac22871..3c7fd8f58b 100644--- a/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorHomePage.tsx@@ -19,13 +19,17 @@ import {LAYER_BACKDROP_CLASS,LAYER_SURFACE_CLASS,} from "@/react/components/ui/layer";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";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 { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useCurrentSQLEditorTab,+ useIsDisconnected,+} from "@/react/stores/sqlEditor/tab";import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/router/dashboard/projectV1";import { useDatabaseV1Store, useProjectV1Store } from "@/store";import { unknownProject } from "@/types";@@ -59,24 +63,23 @@ import { sqlEditorEvents } from "@/views/sql-editor/events";export function SQLEditorHomePage() {const { t } = useTranslation();const navigate = useNavigate();- const tabStore = useSQLEditorTabStore();const setPendingInsertAtCaret = useSQLEditorStore((s) => s.setPendingInsertAtCaret);const databaseStore = useDatabaseV1Store();const projectStore = useProjectV1Store();- const editorStore = useSQLEditorVueState();- const projectContextReady = useVueState(- () => editorStore.projectContextReady+ const projectContextReady = useSQLEditorEditorState(+ (s) => s.projectContextReady);- const project = useVueState(() => {- if (!editorStore.project) return undefined;- const proj = projectStore.getProjectByName(editorStore.project);- return proj.name === editorStore.project ? proj : undefined;+ const projectName = useSQLEditorEditorState((s) => s.project);+ const project = usePiniaBridge(() => {+ if (!projectName) return undefined;+ const proj = projectStore.getProjectByName(projectName);+ return proj.name === projectName ? proj : undefined;});- const tab = useVueState(() => tabStore.currentTab);- const isDisconnected = useVueState(() => tabStore.isDisconnected);+ const tab = useCurrentSQLEditorTab();+ const isDisconnected = useIsDisconnected();const [windowWidth, setWindowWidth] = useState(() => window.innerWidth);useEffect(() => {@@ -140,9 +143,10 @@ export function SQLEditorHomePage() {// ref and inserts at the cursor.useEffect(() => {const off = sqlEditorEvents.on("insert-at-caret", ({ content }) => {- const t = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const t = tabsState.tabsById.get(tabsState.currentTabId);if (!t) return;- tabStore.updateTab(t.id, {+ tabsState.updateTab(t.id, {viewState: { ...(t.viewState ?? {}), view: "CODE" },});requestAnimationFrame(() => {@@ -152,7 +156,7 @@ export function SQLEditorHomePage() {return () => {off();};- }, [tabStore, setPendingInsertAtCaret]);+ }, [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 cbbe54af1b..f2165e49cf 100644--- a/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx+++ b/frontend/src/react/components/sql-editor/SQLEditorRouteShell.tsx@@ -6,12 +6,19 @@ import {useComponentPermissionState,usePermissionDataReady,} from "@/react/components/ComponentPermissionGuard";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useClampResultRowsLimitToPolicy } from "@/react/hooks/useSQLEditorBridge";import { useCurrentRoute, useNavigate } from "@/react/router";import type { AsidePanelTab } from "@/react/stores/sqlEditor";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import {SQL_EDITOR_DATABASE_MODULE,@@ -102,21 +109,24 @@ export function SQLEditorRouteShell() {const actuatorStore = useActuatorV1Store();const projectStore = useProjectV1Store();const databaseStore = useDatabaseV1Store();- const editorStore = useSQLEditorVueState();- const tabStore = useSQLEditorTabStore();const setAsidePanelTab = useSQLEditorStore((s) => s.setAsidePanelTab);const maybeSwitchProject = useSQLEditorStore((s) => s.maybeSwitchProject);const worksheetStore = useWorkSheetStore();- const projectContextReady = useVueState(- () => editorStore.projectContextReady+ const projectContextReady = useSQLEditorEditorState(+ (s) => s.projectContextReady);- const project = useVueState(() => {- const proj = projectStore.getProjectByName(editorStore.project);+ const projectNameState = useSQLEditorEditorState((s) => s.project);+ const project = usePiniaBridge(() => {+ const proj = projectStore.getProjectByName(projectNameState);if (!isValidProjectName(proj.name)) return undefined;return proj;});+ // Keep the persisted result-row limit within the project's+ // query-data policy maximum (re-clamps if the policy lowers the cap).+ useClampResultRowsLimitToPolicy(projectNameState);+// ---- one-shot bootstrap on mount -------------------------------------const bootstrappedRef = useRef(false);@@ -134,10 +144,10 @@ export function SQLEditorRouteShell() {if (bootstrappedRef.current) return;bootstrappedRef.current = true;void (async () => {- editorStore.projectContextReady = false;+ getSQLEditorEditorState().setProjectContextReady(false);const project = await initializeProject();await migrateLegacyCache();- await tabStore.initProject(project);+ await getSQLEditorTabsState().initProject(project);await initializeConnectionFromQuery();setBootstrapDone(true);})();@@ -163,7 +173,8 @@ export function SQLEditorRouteShell() {} else if (typeof projectInParams === "string" && projectInParams) {project = `projects/${projectInParams}`;} else {- project = editorStore.storedLastViewedProject;+ // storedLastViewedProject is an alias for project.+ project = getSQLEditorEditorState().project;}let initializeSuccess = !!(await maybeSwitchProject(project));@@ -172,17 +183,20 @@ export function SQLEditorRouteShell() {initializeSuccess = !!(await maybeSwitchProject(project));}if (!initializeSuccess) {- editorStore.setProject("");+ getSQLEditorEditorState().setProject("");}- return editorStore.project;+ return getSQLEditorEditorState().project;};const switchWorksheet = async (sheetName: string) => {- const openedSheetTab = tabStore.getTabByWorksheet(sheetName);+ const tabsState = getSQLEditorTabsState();+ const openedSheetTab = Array.from(tabsState.tabsById.values()).find(+ (t) => t.worksheet === sheetName+ );const sheet = await worksheetStore.getOrFetchWorksheetByName(sheetName);if (!sheet) {if (openedSheetTab) {- tabStore.updateTab(openedSheetTab.id, {+ tabsState.updateTab(openedSheetTab.id, {worksheet: "",status: "DIRTY",});@@ -198,7 +212,7 @@ export function SQLEditorRouteShell() {return false;}const connection = await extractWorksheetConnection(sheet);- tabStore.addTab({+ tabsState.addTab({id: openedSheetTab?.id,connection,worksheet: sheet.name,@@ -232,7 +246,7 @@ export function SQLEditorRouteShell() {await maybeSwitchProject(database.project);const { instance } = extractDatabaseResourceName(database.name);const connection = { instance, database: database.name };- tabStore.addTab({+ getSQLEditorTabsState().addTab({connection,mode: DEFAULT_SQL_EDITOR_TAB_MODE,});@@ -246,17 +260,25 @@ export function SQLEditorRouteShell() {// ---- URL ⇄ connection sync (reactive) --------------------------------- // Subscribe to each Pinia field; the effect below fires whenever any+ // Subscribe to each Zustand field; the effect below fires whenever any// changes (mirrors Vue's `watch([...], ..., { immediate: true })`).// The dependency array does the multi-source coalescing.- const projName = useVueState(() => editorStore.project);- const sheetName = useVueState(() => tabStore.currentTab?.worksheet);- const instanceName = useVueState(- () => tabStore.currentTab?.connection.instance+ const projName = useSQLEditorEditorState((s) => s.project);+ const sheetName = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.worksheet+ );+ const instanceName = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.instance+ );+ const dbName = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.database+ );+ const schema = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.schema+ );+ const table = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.table);- const dbName = useVueState(() => tabStore.currentTab?.connection.database);- const schema = useVueState(() => tabStore.currentTab?.connection.schema);- const table = useVueState(() => tabStore.currentTab?.connection.table);useEffect(() => {// Skip until bootstrap is done — see `bootstrapDone` declaration@@ -294,9 +316,13 @@ export function SQLEditorRouteShell() {"panel") as Record<string, string>;- // Touch the connection ref so the omit() above sees the live tab —+ // Touch the connection so the omit() above sees the live tab —// identical to the Vue version's `connection.value` read at the top.- void (tabStore.currentTab?.connection ?? emptySQLEditorConnection());+ const tabsState = getSQLEditorTabsState();+ void (+ tabsState.tabsById.get(tabsState.currentTabId)?.connection ??+ emptySQLEditorConnection()+ );if (vals.sheetName) {const sheet = worksheetStore.getWorksheetByName(vals.sheetName);@@ -311,11 +337,10 @@ export function SQLEditorRouteShell() {});return;} else {- const tab = tabStore.currentTab;- if (tab) {- tab.worksheet = "";- tab.status = "DIRTY";- }+ tabsState.updateCurrentTab({+ worksheet: "",+ status: "DIRTY",+ });}}if (vals.dbName && isValidDatabaseName(vals.dbName)) {@@ -347,7 +372,9 @@ export function SQLEditorRouteShell() {await navigate.replace({name: SQL_EDITOR_INSTANCE_MODULE,params: {- project: extractProjectResourceName(editorStore.project),+ project: extractProjectResourceName(+ getSQLEditorEditorState().project+ ),instance: extractInstanceResourceName(vals.instanceName),},query,@@ -433,8 +460,16 @@ export function SQLEditorRouteShell() {useEffect(() => {const dirtyMsg = () =>`${t("sql-editor.tab.unsaved-worksheet")} ${t("common.leave-without-saving")}`;+ const findDirtyTab = () => {+ const tabsState = getSQLEditorTabsState();+ for (const persisted of tabsState.openTmpTabList) {+ const tab = tabsState.tabsById.get(persisted.id);+ if (tab && tab.status !== "CLEAN") return tab;+ }+ return undefined;+ };const handler = (e: BeforeUnloadEvent) => {- const dirty = tabStore.openTabList.find((tab) => tab.status !== "CLEAN");+ const dirty = findDirtyTab();if (!dirty) return;e.returnValue = dirtyMsg();return e.returnValue;@@ -454,7 +489,7 @@ export function SQLEditorRouteShell() {next();return;}- const dirty = tabStore.openTabList.find((tab) => tab.status !== "CLEAN");+ const dirty = findDirtyTab();if (dirty && !window.confirm(dirtyMsg())) {next(false);return;@@ -465,7 +500,7 @@ export function SQLEditorRouteShell() {window.removeEventListener("beforeunload", handler);removeGuard();};- }, [tabStore, t]);+ }, [t]);// ---- permission gate (children-style) --------------------------------diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsxindex 6a7819eb83..0de5d3294c 100644--- a/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaChooser.test.tsx@@ -9,8 +9,12 @@ 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>(),- useSQLEditorTabStore: vi.fn(),+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),+ // Selector hook over the Zustand tabs store; returns the current tab's+ // `connection.schema` (and `currentTabId` for the seed effect).+ tabSchema: undefined as string | undefined,+ currentTabId: "tab1",+ getSQLEditorTabsState: vi.fn(),useDBSchemaV1Store: vi.fn(),useConnectionOfCurrentSQLEditorTab: vi.fn(),instanceAllowsSchemaScopedQuery: vi.fn(),@@ -23,17 +27,32 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({useDBSchemaV1Store: mocks.useDBSchemaV1Store,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({useConnectionOfCurrentSQLEditorTab: mocks.useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+}));++vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { connection: { schema?: string } }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: mocks.currentTabId,+ tabsById: new Map([+ [mocks.currentTabId, { connection: { schema: mocks.tabSchema } }],+ ]),+ }),+ getSQLEditorTabsState: mocks.getSQLEditorTabsState,}));vi.mock("@/utils", () => ({@@ -92,22 +111,26 @@ const renderIntoContainer = (element: ReactElement) => {};const mockConnection = {- instance: { value: { engine: "MYSQL" } },- database: { value: { name: "instances/inst1/databases/db1" } },+ instance: { engine: "MYSQL" },+ database: { name: "instances/inst1/databases/db1" },};beforeEach(async () => {vi.clearAllMocks();mocks.useConnectionOfCurrentSQLEditorTab.mockReturnValue(mockConnection);- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { connection: { schema: undefined } },+ mocks.tabSchema = undefined;+ mocks.currentTabId = "tab1";+ mocks.getSQLEditorTabsState.mockReturnValue({+ currentTabId: "tab1",+ tabsById: new Map([["tab1", { connection: {} }]]),+ updateCurrentTab: vi.fn(),});mocks.useDBSchemaV1Store.mockReturnValue({getDatabaseMetadata: vi.fn(() => ({schemas: [{ name: "public" }, { name: "private" }],})),});- mocks.useVueState.mockImplementation((getter) => getter());+ mocks.usePiniaBridge.mockImplementation((getter) => getter());mocks.instanceAllowsSchemaScopedQuery.mockReturnValue(true);({ SchemaChooser } = await import("./SchemaChooser"));});@@ -154,18 +177,8 @@ describe("SchemaChooser", () => {unmount();});- test("selecting unspecified sets tab.connection.schema to undefined", () => {- const tab = { connection: { schema: "public" } };- mocks.useSQLEditorTabStore.mockReturnValue({ currentTab: tab });-- // Import fresh copy with updated mock- let callIdx = 0;- mocks.useVueState.mockImplementation((getter) => {- callIdx++;- // 1: engine, 2: databaseName, 3: tabSchema, 4: schemas, 5: queryParam- if (callIdx === 3) return "public";- return getter();- });+ test("is chosen when a schema is selected on the tab", () => {+ mocks.tabSchema = "public";const { container, render, unmount } = renderIntoContainer(<SchemaChooser />diff --git a/frontend/src/react/components/sql-editor/SchemaChooser.tsx b/frontend/src/react/components/sql-editor/SchemaChooser.tsxindex 5dc2aaed8e..d45323dded 100644--- a/frontend/src/react/components/sql-editor/SchemaChooser.tsx+++ b/frontend/src/react/components/sql-editor/SchemaChooser.tsx@@ -1,10 +1,11 @@import { useEffect, useMemo } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { useDBSchemaV1Store } from "@/store";import { instanceAllowsSchemaScopedQuery } from "@/utils";@@ -19,14 +20,15 @@ const SchemaOptionValueUnspecified = "-1";*/export function SchemaChooser() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const dbSchemaStore = useDBSchemaV1Store();- const connection = useConnectionOfCurrentSQLEditorTab();+ const { instance, database } = useConnectionOfCurrentSQLEditorTab();- const engine = useVueState(() => connection.instance.value.engine);- const databaseName = useVueState(() => connection.database.value.name);- const tabSchema = useVueState(() => tabStore.currentTab?.connection.schema);- const schemas = useVueState(+ const engine = instance.engine;+ const databaseName = database.name;+ const tabSchema = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.schema+ );+ const schemas = usePiniaBridge(() => dbSchemaStore.getDatabaseMetadata(databaseName).schemas);@@ -51,9 +53,15 @@ export function SchemaChooser() {const isChosen = value !== SchemaOptionValueUnspecified;const handleChange = (next: string) => {- if (!tabStore.currentTab) return;- tabStore.currentTab.connection.schema =- next === SchemaOptionValueUnspecified ? undefined : next;+ const tabsState = getSQLEditorTabsState();+ const currentTab = tabsState.tabsById.get(tabsState.currentTabId);+ if (!currentTab) return;+ tabsState.updateCurrentTab({+ connection: {+ ...currentTab.connection,+ schema: next === SchemaOptionValueUnspecified ? undefined : next,+ },+ });};// Seed from URL query parameter on mount and whenever the query param OR@@ -61,10 +69,10 @@ export function SchemaChooser() {// tracked both `route.query.schema` and `tab.value` (the latter via the// setter's reactive reads) so that switching to a new tab with the URL// query still present re-seeded the new tab's connection.schema.- const queryParam = useVueState(+ const queryParam = usePiniaBridge(() => router.currentRoute.value.query.schema as string | undefined);- const currentTabId = useVueState(() => tabStore.currentTab?.id);+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);useEffect(() => {if (queryParam) handleChange(queryParam);}, [queryParam, currentTabId]);diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsxindex 9b5d8648cb..0f66385a07 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ColumnInfo.tsx@@ -2,7 +2,6 @@ import { create } from "@bufbuild/protobuf";import { Check, X } from "lucide-react";import { useTranslation } from "react-i18next";import { getColumnDefaultValuePlaceholder } from "@/react/components/SchemaEditorLite/core/columnDefaultValue";-import { useVueState } from "@/react/hooks/useVueState";import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import { ColumnMetadataSchema } from "@/types/proto-es/v1/database_service_pb";@@ -26,16 +25,14 @@ export function ColumnInfo({ database, schema, table, column }: Props) {const dbSchema = useDBSchemaV1Store();const databaseStore = useDatabaseV1Store();- const columnMetadata = useVueState(- () =>- dbSchema- .getTableMetadata({ database, schema, table })- .columns.find((col) => col.name === column) ??- create(ColumnMetadataSchema, {})- );- const instanceEngine = useVueState(- () => getInstanceResource(databaseStore.getDatabaseByName(database)).engine- );+ const columnMetadata =+ dbSchema+ .getTableMetadata({ database, schema, table })+ .columns.find((col) => col.name === column) ??+ create(ColumnMetadataSchema, {});+ const instanceEngine = getInstanceResource(+ databaseStore.getDatabaseByName(database)+ ).engine;const characterSet =instanceEngine === Engine.POSTGRES ||diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsxindex 9b356a4070..4c15b36849 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ExternalTableInfo.tsx@@ -1,5 +1,4 @@import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import { InfoItem } from "./InfoItem";@@ -13,9 +12,11 @@ type Props = {export function ExternalTableInfo({ database, schema, externalTable }: Props) {const { t } = useTranslation();const dbSchema = useDBSchemaV1Store();- const externalTableMetadata = useVueState(() =>- dbSchema.getExternalTableMetadata({ database, schema, externalTable })- );+ const externalTableMetadata = dbSchema.getExternalTableMetadata({+ database,+ schema,+ externalTable,+ });return (<div className="min-w-56 max-w-[18rem] gap-y-1">diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsxindex abecff6834..6c4a3f7721 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TableInfo.tsx@@ -1,6 +1,5 @@import { useTranslation } from "react-i18next";import { EngineIcon } from "@/react/components/EngineIcon";-import { useVueState } from "@/react/hooks/useVueState";import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";import { Engine } from "@/types/proto-es/v1/common_pb";import { bytesToString, getInstanceResource } from "@/utils";@@ -24,12 +23,10 @@ export function TableInfo({ database, schema, table }: Props) {const dbSchema = useDBSchemaV1Store();const databaseStore = useDatabaseV1Store();- const tableMetadata = useVueState(() =>- dbSchema.getTableMetadata({ database, schema, table })- );- const instanceEngine = useVueState(- () => getInstanceResource(databaseStore.getDatabaseByName(database)).engine- );+ const tableMetadata = dbSchema.getTableMetadata({ database, schema, table });+ const instanceEngine = getInstanceResource(+ databaseStore.getDatabaseByName(database)+ ).engine;const indexSize =instanceEngine === Engine.CLICKHOUSE || instanceEngine === Engine.SNOWFLAKEdiff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsxindex 2e5a60446d..8239fd86df 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/TablePartitionInfo.tsx@@ -1,6 +1,5 @@import { create } from "@bufbuild/protobuf";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import {TablePartitionMetadata_Type,@@ -25,13 +24,11 @@ export function TablePartitionInfo({const { t } = useTranslation();const dbSchema = useDBSchemaV1Store();- const partitionMetadata = useVueState(- () =>- dbSchema- .getTableMetadata({ database, schema, table })- .partitions.find((p) => p.name === partition) ??- create(TablePartitionMetadataSchema, {})- );+ const partitionMetadata =+ dbSchema+ .getTableMetadata({ database, schema, table })+ .partitions.find((p) => p.name === partition) ??+ create(TablePartitionMetadataSchema, {});return (<div className="min-w-56 max-w-[18rem] gap-y-1">diff --git a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsxindex 8f3b8d80c3..2b06d5fc8d 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/HoverPanel/ViewInfo.tsx@@ -1,4 +1,3 @@-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import { CommonText } from "./CommonText";@@ -11,8 +10,6 @@ type Props = {/** Replaces `HoverPanel/ViewInfo.vue`. Just the view's comment, wrapped. */export function ViewInfo({ database, schema, view }: Props) {const dbSchema = useDBSchemaV1Store();- const viewMetadata = useVueState(() =>- dbSchema.getViewMetadata({ database, schema, view })- );+ const viewMetadata = dbSchema.getViewMetadata({ database, schema, view });return <CommonText content={viewMetadata.comment} />;}diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsxindex c317a47889..e31d558008 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.test.tsx@@ -42,6 +42,9 @@ vi.mock("@/react/i18n", () => ({vi.mock("@/store", () => ({useDBSchemaV1Store: () => ({getOrFetchDatabaseMetadata: mocks.getOrFetchDatabaseMetadata,+ // SchemaPane reads cached metadata reactively via this getter; return+ // null so the tree stays empty unless a test seeds the cache.+ getDatabaseMetadataWithoutDefault: () => null,syncDatabase: vi.fn(),getTableMetadata: vi.fn(),}),@@ -49,21 +52,35 @@ vi.mock("@/store", () => ({pushNotification: vi.fn(),}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ // Returns plain values now — `database` is the unwrapped object.useConnectionOfCurrentSQLEditorTab: () => ({- database: { value: mocks.databaseRefValue },- instance: { value: mocks.instanceRefValue },- }),- useSQLEditorTabStore: () => ({- currentTab: mocks.currentTab,- openTabList: [],- addTab: vi.fn(),- setCurrentTabId: vi.fn(),- updateCurrentTab: vi.fn(),- updateTab: vi.fn(),+ database: mocks.databaseRefValue,+ instance: mocks.instanceRefValue,}),}));+// Minimal Zustand tabs-state stub. The selector hook runs against a+// state built from `mocks.currentTab`; the imperative getter exposes the+// same shape plus the mutators SchemaPane invokes.+const tabsState = () => ({+ currentTabId: mocks.currentTab ? "t1" : "",+ tabsById: new Map<string, unknown>(+ mocks.currentTab ? [["t1", mocks.currentTab]] : []+ ),+ openTmpTabList: [],+ addTab: vi.fn(),+ setCurrentTabId: vi.fn(),+ updateCurrentTab: vi.fn(),+ updateTab: vi.fn(),+});++vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (selector: (s: unknown) => unknown) =>+ selector(tabsState()),+ getSQLEditorTabsState: () => tabsState(),+}));+vi.mock("@/types", () => ({isValidDatabaseName: mocks.isValidDatabaseName,DEFAULT_SQL_EDITOR_TAB_MODE: "WORKSHEET",diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsxindex 328222da31..086250c582 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SchemaPane.tsx@@ -19,12 +19,13 @@ import {import { Input } from "@/react/components/ui/input";import { Tree, type TreeDataNode } from "@/react/components/ui/tree";import { countVisibleRows } from "@/react/components/ui/tree-utils";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { useDBSchemaV1Store } from "@/store";import { isValidDatabaseName } from "@/types";import type {@@ -61,6 +62,10 @@ const ROW_HEIGHT = 21;const TREE_FALLBACK_HEIGHT = 360;const FLAT_TABLE_THRESHOLD = 1000;const SEARCH_DEBOUNCE_MS = 200;+// Stable empty array reference used by the expandedKeys selector — a+// fresh `[]` per call would re-trigger Zustand subscribers on every+// store mutation.+const EMPTY_KEYS: readonly string[] = Object.freeze([]);/*** React port of `frontend/src/views/sql-editor/AsidePanel/SchemaPane/SchemaPane.vue`.@@ -92,25 +97,19 @@ export function SchemaPane() {function SchemaPaneInner() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const dbSchemaStore = useDBSchemaV1Store();- const connection = useConnectionOfCurrentSQLEditorTab();+ const { database } = useConnectionOfCurrentSQLEditorTab();const hoverState = useHoverState();- const database = useVueState(() => connection.database.value);- const currentTabId = useVueState(() => tabStore.currentTab?.id);- // `connection` is mutated in place via `Object.assign`-style updates,- // so depth is required to catch nested-field changes (schema, database,- // instance) without a fresh reference.- const tabConnection = useVueState(() => tabStore.currentTab?.connection, {- deep: true,- });+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);+ const currentTab = useSQLEditorTabState((s) =>+ s.tabsById.get(s.currentTabId)+ );+ const tabConnection = currentTab?.connection;const tabConnectionSchema = tabConnection?.schema;// tab.viewState shapes the selectedKeys highlight when the editor// panel is on a non-CODE view (e.g. TABLES drill-down).- const panelViewState = useVueState(() => tabStore.currentTab?.viewState, {- deep: true,- });+ const panelViewState = currentTab?.viewState;const [searchPattern, setSearchPattern] = useState("");const debouncedSearch = useDebouncedValue(searchPattern, SEARCH_DEBOUNCE_MS);@@ -121,14 +120,28 @@ function SchemaPaneInner() {setSearchPattern("");}, [currentTabId]);- const [metadata, setMetadata] = useState<DatabaseMetadata | null>(null);+ // Reactive read of the cached metadata. Returns the live dbSchema+ // cache entry (or null when uncached) so the tree rebuilds whenever+ // the metadata for this database changes — including a manual sync via+ // SyncSchemaButton, which refetches with `skipCache` and replaces the+ // entry. `getDatabaseMetadataWithoutDefault` returns a stable+ // `undefined` when uncached (vs `getDatabaseMetadata`'s fresh empty+ // object), keeping the snapshot reference stable across renders.+ const metadata = useVueState<DatabaseMetadata | null>(+ () =>+ isValidDatabaseName(database.name)+ ? (dbSchemaStore.getDatabaseMetadataWithoutDefault(database.name) ??+ null)+ : null,+ { deps: [database.name] }+ );const [isFetching, setIsFetching] = useState(false);- // Fetch metadata on database change. The store de-duplicates so this- // is safe to fire on every render where the name flips.+ // Trigger the fetch on database change (the store de-duplicates). The+ // metadata is read reactively above rather than from this promise, so+ // a later cache replacement (e.g. sync) also flows through to the tree.useEffect(() => {if (!isValidDatabaseName(database.name)) {- setMetadata(null);setIsFetching(false);return;}@@ -136,13 +149,8 @@ function SchemaPaneInner() {let cancelled = false;void dbSchemaStore.getOrFetchDatabaseMetadata({ database: database.name })- .then((md) => {- if (cancelled) return;- setMetadata(md);- }).finally(() => {- if (cancelled) return;- setIsFetching(false);+ if (!cancelled) setIsFetching(false);});return () => {cancelled = true;@@ -177,37 +185,46 @@ function SchemaPaneInner() {// First-mount default expand: seed treeState.keys so the user// sees database/schema/Tables/Views opened by default. The Vue// version seeds when `treeStateDb !== connectionDb && connectionDb`.- const tab = tabStore.currentTab;+ const tab = getSQLEditorTabsState().tabsById.get(+ getSQLEditorTabsState().currentTabId+ );const connectionDb = tab?.connection.database;if (tab && connectionDb && tab.treeState.database !== connectionDb) {- tab.treeState.database = connectionDb;- tab.treeState.keys = defaultExpandedKeys(built);+ getSQLEditorTabsState().updateTab(tab.id, {+ treeState: {+ ...tab.treeState,+ database: connectionDb,+ keys: defaultExpandedKeys(built),+ },+ });}});return () => cancelAnimationFrame(raf);- }, [isFetching, metadata, totalTableCount, database, tabStore]);+ }, [isFetching, metadata, totalTableCount, database]);// Reactive proxy for `tab.treeState.keys`. Writes via `setExpandedKeys`- // always REPLACE the whole array (`tab.treeState.keys = keys`), so a- // shallow watch on the getter is enough — the getter's read of- // `tab.treeState.keys` registers as a dep, and array replacement- // triggers the watch. Deep traversal over an array of plain strings- // would just add per-element overhead with no extra reactivity.- const expandedKeys = useVueState<string[]>(() => {- const tab = tabStore.currentTab;- if (!tab) return [];- if (tab.treeState.database !== database.name) return [];- return tab.treeState.keys ?? [];+ // always REPLACE the whole array. The Zustand selector subscribes on+ // the keys array reference, which `updateTab` swaps via immer on every+ // mutation.+ const expandedKeys = useSQLEditorTabState<readonly string[]>((s) => {+ const tab = s.tabsById.get(s.currentTabId);+ if (!tab) return EMPTY_KEYS;+ if (tab.treeState.database !== database.name) return EMPTY_KEYS;+ return tab.treeState.keys ?? EMPTY_KEYS;});const setExpandedKeys = useCallback((keys: string[]) => {- const tab = tabStore.currentTab;+ const tab = getSQLEditorTabsState().tabsById.get(+ getSQLEditorTabsState().currentTabId+ );if (!tab) return;if (tab.treeState.database !== database.name) return;- tab.treeState.keys = keys;+ getSQLEditorTabsState().updateTab(tab.id, {+ treeState: { ...tab.treeState, keys },+ });},- [tabStore, database.name]+ [database.name]);const upsertExpandedKeys = useCallback(@@ -295,11 +312,16 @@ function SchemaPaneInner() {const { handleClick } = useClickEvents({onSingleClick: (node) => {if (node.meta.type === "schema") {- const tab = tabStore.currentTab;+ const tab = getSQLEditorTabsState().tabsById.get(+ getSQLEditorTabsState().currentTabId+ );if (tab) {- tab.connection.schema = (- node.meta.target as NodeTarget<"schema">- ).schema;+ getSQLEditorTabsState().updateTab(tab.id, {+ connection: {+ ...tab.connection,+ schema: (node.meta.target as NodeTarget<"schema">).schema,+ },+ });}}toggleNode(node);@@ -347,15 +369,16 @@ function SchemaPaneInner() {const availableActions = useAvailableActions();// ---- Flat list handlers (when totalTableCount > 1000) -------------------- const onFlatSelect = useCallback(- (item: { schema?: string }) => {- const tab = tabStore.currentTab;- if (tab && item.schema) {- tab.connection.schema = item.schema;- }- },- [tabStore]- );+ const onFlatSelect = useCallback((item: { schema?: string }) => {+ const tab = getSQLEditorTabsState().tabsById.get(+ getSQLEditorTabsState().currentTabId+ );+ if (tab && item.schema) {+ getSQLEditorTabsState().updateTab(tab.id, {+ connection: { ...tab.connection, schema: item.schema },+ });+ }+ }, []);const onFlatSelectAll = useCallback((item: { key: string; schema: string; metadata: TableMetadata }) => {const synthetic: SchemaTreeNode = {@@ -410,7 +433,7 @@ function SchemaPaneInner() {<Inputvalue={searchPattern}placeholder={t("common.search")}- disabled={!tabStore.currentTab}+ disabled={!currentTab}onChange={(e) => setSearchPattern(e.target.value)}className="h-8 text-sm w-full"/>diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsxindex 997cabd057..86eea43f17 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.test.tsx@@ -64,10 +64,6 @@ vi.mock("@/react/components/ui/button", () => ({),}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: (getter: () => unknown) => getter(),-}));-vi.mock("@/store", () => ({useDatabaseV1Store: () => ({ syncDatabase: mocks.syncDatabase }),useDBSchemaV1Store: () => ({@@ -75,9 +71,10 @@ vi.mock("@/store", () => ({}),}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({+vi.mock("@/react/hooks/useSQLEditorBridge", () => ({+ // Returns plain values now — `database` is the unwrapped object.useConnectionOfCurrentSQLEditorTab: () => ({- database: { value: mocks.databaseRefValue },+ database: mocks.databaseRefValue,}),}));diff --git a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsxindex ef122ef4c6..78a683277f 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/SyncSchemaButton.tsx@@ -4,9 +4,8 @@ import { Trans, useTranslation } from "react-i18next";import { HumanizeTs } from "@/react/components/HumanizeTs";import { Button } from "@/react/components/ui/button";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";import { useDatabaseV1Store, useDBSchemaV1Store } from "@/store";import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";@@ -23,8 +22,7 @@ import { getDateForPbTimestampProtoEs, isValidDatabaseName } from "@/types";*/export function SyncSchemaButton({ className }: { className?: string }) {const { t } = useTranslation();- const { database: databaseRef } = useConnectionOfCurrentSQLEditorTab();- const database = useVueState(() => databaseRef.value);+ const { database } = useConnectionOfCurrentSQLEditorTab();const databaseStore = useDatabaseV1Store();const dbSchemaStore = useDBSchemaV1Store();diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsxindex 59f813abe9..f57f46793c 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/CheckNode.tsx@@ -1,4 +1,3 @@-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import type { TreeNode } from "../schemaTree";import { CommonNode } from "./CommonNode";@@ -17,7 +16,7 @@ export function CheckNode({ node, keyword }: Props) {const dbSchema = useDBSchemaV1Store();const target = (node as TreeNode<"check">).meta.target;- const checkMetadata = useVueState(() => {+ const checkMetadata = (() => {if ("table" in target) {const { database, schema, table, check } = target;const tableMetadata = dbSchema.getTableMetadata({@@ -28,7 +27,7 @@ export function CheckNode({ node, keyword }: Props) {return tableMetadata?.checkConstraints.find((c) => c.name === check);}return undefined;- });+ })();return (<CommonNodediff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsxindex 6114e11c40..b678f63418 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ColumnNode.tsx@@ -39,12 +39,12 @@ function findColumn(parent: { columns: ColumnMetadata[] }, name: string) {* - The trailing type-tag (`int`, `varchar(255)`, …) is rendered when* the metadata fetch has resolved.*- * Lookups use `useMemo` (not `useVueState`). The schema tree is rebuilt- * by `SchemaPane` whenever the database metadata changes, which produces- * fresh `target` objects and remounts these rows with current metadata —- * a Vue watch per ColumnNode is unnecessary subscription overhead, and- * `flush: "sync"` watch setup was the dominant cost of expanding a- * Columns folder with hundreds of children.+ * Lookups use `useMemo`. The schema tree is rebuilt by `SchemaPane`+ * whenever the database metadata changes, which produces fresh `target`+ * objects and remounts these rows with current metadata — a per-row+ * subscription would be unnecessary overhead, and synchronous watch+ * setup was the dominant cost of expanding a Columns folder with+ * hundreds of children.*/export function ColumnNode({ node, keyword }: Props) {const dbSchema = useDBSchemaV1Store();diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsxindex 32e9e9cd5b..b3a34c9a90 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/DatabaseNode.tsx@@ -1,5 +1,4 @@import { EngineIcon } from "@/react/components/EngineIcon";-import { useVueState } from "@/react/hooks/useVueState";import { useDatabaseV1Store } from "@/store";import { extractDatabaseResourceName, getInstanceResource } from "@/utils";import type { TreeNode } from "../schemaTree";@@ -18,9 +17,7 @@ export function DatabaseNode({ node, keyword }: Props) {const databaseStore = useDatabaseV1Store();const target = (node as TreeNode<"database">).meta.target;- const database = useVueState(() =>- databaseStore.getDatabaseByName(target.database)- );+ const database = databaseStore.getDatabaseByName(target.database);const databaseName = extractDatabaseResourceName(database.name).databaseName;const instance = getInstanceResource(database);diff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsxindex bc40964ad3..630c073548 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/FunctionNode.tsx@@ -1,4 +1,3 @@-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import type { TreeNode } from "../schemaTree";import { CommonNode } from "./CommonNode";@@ -15,13 +14,10 @@ export function FunctionNode({ node, keyword }: Props) {const dbSchema = useDBSchemaV1Store();const target = (node as TreeNode<"function">).meta.target;- const functionMetadata = useVueState(- () =>- dbSchema.getSchemaMetadata({- database: target.database,- schema: target.schema,- })?.functions[target.position]- );+ const functionMetadata = dbSchema.getSchemaMetadata({+ database: target.database,+ schema: target.schema,+ })?.functions[target.position];return (<CommonNodediff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsxindex 7f575db2e0..833b93f7db 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/IndexNode.tsx@@ -1,4 +1,3 @@-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import type { TreeNode } from "../schemaTree";import { CommonNode } from "./CommonNode";@@ -17,7 +16,7 @@ export function IndexNode({ node, keyword }: Props) {const dbSchema = useDBSchemaV1Store();const target = (node as TreeNode<"index">).meta.target;- const isPrimaryKey = useVueState(() => {+ const isPrimaryKey = (() => {const { database, schema, table, index } = target;const tableMetadata = dbSchema.getTableMetadata({database,@@ -25,7 +24,7 @@ export function IndexNode({ node, keyword }: Props) {table,});return !!tableMetadata.indexes.find((i) => i.name === index)?.primary;- });+ })();return (<CommonNodediff --git a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsxindex 688fba527d..b5a1c9477c 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/TreeNode/ProcedureNode.tsx@@ -1,4 +1,3 @@-import { useVueState } from "@/react/hooks/useVueState";import { useDBSchemaV1Store } from "@/store";import type { TreeNode } from "../schemaTree";import { CommonNode } from "./CommonNode";@@ -18,13 +17,10 @@ export function ProcedureNode({ node, keyword }: Props) {const dbSchema = useDBSchemaV1Store();const target = (node as TreeNode<"procedure">).meta.target;- const procedureMetadata = useVueState(- () =>- dbSchema.getSchemaMetadata({- database: target.database,- schema: target.schema,- })?.procedures[target.position]- );+ const procedureMetadata = dbSchema.getSchemaMetadata({+ database: target.database,+ schema: target.schema,+ })?.procedures[target.position];return (<CommonNodediff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsxindex cd14581a85..791f3f1dba 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.test.tsx@@ -56,10 +56,15 @@ vi.mock("@/store", () => ({useDBSchemaV1Store: () => ({ getTableMetadata: mocks.getTableMetadata }),}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: () => ({- currentTab: { id: "t1", viewState: { schema: "" } },- openTabList: [],+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ // actions.tsx only reaches the store imperatively via getSQLEditorTabsState+ // when a menu handler runs; building the menu items (what these tests+ // capture) never touches it. Provide the full surface anyway so any+ // invoked handler stays a no-op.+ getSQLEditorTabsState: () => ({+ currentTabId: "t1",+ tabsById: new Map([["t1", { id: "t1", viewState: { schema: "" } }]]),+ openTmpTabList: [],addTab: vi.fn(),setCurrentTabId: vi.fn(),updateCurrentTab: vi.fn(),diff --git a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsxindex 56f36c95ed..7dde5c2055 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/actions.tsx@@ -18,7 +18,7 @@ import { useTranslation } from "react-i18next";import { formatSQL } from "@/react/components/monaco/sqlFormatter";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";import { keyWithPosition } from "@/react/lib/keyWithPosition";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { SQL_EDITOR_DATABASE_MODULE } from "@/router/sqlEditor";import {@@ -127,7 +127,8 @@ const applyContentToCurrentTabOrCopyToClipboard = async (content: string,notify: (key: string) => void) => {- const tab = useSQLEditorTabStore().currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) {await copyToClipboard(content, notify);return;@@ -152,10 +153,10 @@ const copyToClipboard = async (};const updateCurrentTabViewState = (patch: Partial<EditorPanelViewState>) => {- const tabStore = useSQLEditorTabStore();- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;- tabStore.updateTab(tab.id, {+ tabsState.updateTab(tab.id, {viewState: {...defaultViewState(),...tab.viewState,@@ -165,18 +166,18 @@ const updateCurrentTabViewState = (patch: Partial<EditorPanelViewState>) => {};const runQuery = async (+ execute: ReturnType<typeof useExecuteSQL>["execute"],database: Database,schema: string | undefined,tableOrViewName: string,statement: string) => {- const tabStore = useSQLEditorTabStore();- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;if (tab.mode === "ADMIN") {- tabStore.updateCurrentTab({ mode: DEFAULT_SQL_EDITOR_TAB_MODE });+ tabsState.updateCurrentTab({ mode: DEFAULT_SQL_EDITOR_TAB_MODE });}- const { execute } = useExecuteSQL();const connection: SQLEditorConnection = {instance: extractDatabaseResourceName(database.name).instance,database: database.name,@@ -197,7 +198,7 @@ const runQuery = async (export function useSchemaPaneActions() {const databaseStore = useDatabaseV1Store();- const tabStore = useSQLEditorTabStore();+ const { execute } = useExecuteSQL();const openNewTab = useCallback((params: {@@ -206,11 +207,12 @@ export function useSchemaPaneActions() {table?: string;view: EditorPanelView;}) => {- const currentViewState = tabStore.currentTab?.viewState;+ const tabsState = getSQLEditorTabsState();+ const fromTab = tabsState.tabsById.get(tabsState.currentTabId);+ const currentViewState = fromTab?.viewState;const schema = params.schema ?? currentViewState?.schema;const table = params.table ?? currentViewState?.table;- const fromTab = tabStore.currentTab;const clonedTab: SQLEditorTab = {...defaultSQLEditorTab(),status: "CLEAN",@@ -221,7 +223,11 @@ export function useSchemaPaneActions() {clonedTab.treeState = cloneDeep(fromTab.treeState);}- const findExistedTab = tabStore.openTabList.find((tab) => {+ const openTabs = tabsState.openTmpTabList+ .map((p) => tabsState.tabsById.get(p.id))+ .filter((t): t is SQLEditorTab => !!t);++ const findExistedTab = openTabs.find((tab) => {if (tab.status !== "CLEAN" || tab.id === fromTab?.id) return false;if (!isSameSQLEditorConnection(tab.connection, clonedTab.connection))return false;@@ -236,13 +242,13 @@ export function useSchemaPaneActions() {});if (findExistedTab) {- tabStore.setCurrentTabId(findExistedTab.id);+ tabsState.setCurrentTabId(findExistedTab.id);} else {- tabStore.addTab(clonedTab);+ tabsState.addTab(clonedTab);updateCurrentTabViewState({ view: params.view, schema, table });}},- [tabStore]+ []);const selectAllFromTableOrView = useCallback(@@ -267,9 +273,9 @@ export function useSchemaPaneActions() {engine);updateCurrentTabViewState({ view: "CODE" });- await runQuery(db, schema, tableOrViewName, query);+ await runQuery(execute, db, schema, tableOrViewName, query);},- [databaseStore]+ [databaseStore, execute]);const viewDetail = useCallback(@@ -328,10 +334,12 @@ export function useSchemaPaneActions() {}updateCurrentTabViewState({ detail });if (name) {- tabStore.updateCurrentTab({ title: `Detail for ${type} ${name}` });+ getSQLEditorTabsState().updateCurrentTab({+ title: `Detail for ${type} ${name}`,+ });}},- [openNewTab, tabStore]+ [openNewTab]);return { selectAllFromTableOrView, viewDetail, openNewTab };diff --git a/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsxindex 791d17c403..1017374e02 100644--- a/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx+++ b/frontend/src/react/components/sql-editor/SchemaPane/availableActions.tsx@@ -1,8 +1,7 @@import { Box, Info } from "lucide-react";import { useMemo } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";-import { useConnectionOfCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab-vue-state";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {instanceV1SupportsExternalTable,instanceV1SupportsPackage,@@ -31,8 +30,7 @@ import {*/export function useAvailableActions(): AvailableAction[] {const { t } = useTranslation();- const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();- const instance = useVueState(() => instanceRef.value);+ const { instance } = useConnectionOfCurrentSQLEditorTab();return useMemo(() => {const actions: AvailableAction[] = [diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsxindex 5d93948db3..1f40c277cb 100644--- a/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.test.tsx@@ -9,11 +9,13 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),useActuatorV1Store: vi.fn(),useCurrentUserV1: vi.fn(),useWorkSheetStore: vi.fn(),- useSQLEditorTabStore: vi.fn(),+ // `useSQLEditorTabState(selector)` runs `selector` against this stub+ // state; the component selects `tabsById.get(currentTabId)?.status`.+ tabStatus: "CLEAN" as string,pushNotification: vi.fn(),extractProjectResourceName: vi.fn((name: string) => name.split("/")[1] ?? name@@ -26,8 +28,8 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({@@ -37,8 +39,17 @@ vi.mock("@/store", () => ({pushNotification: mocks.pushNotification,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ useSQLEditorTabState: (+ selector: (s: {+ currentTabId: string;+ tabsById: Map<string, { status: string }>;+ }) => unknown+ ) =>+ selector({+ currentTabId: "t1",+ tabsById: new Map([["t1", { status: mocks.tabStatus }]]),+ }),}));vi.mock("@/utils", () => ({@@ -125,11 +136,9 @@ beforeEach(async () => {mocks.useWorkSheetStore.mockReturnValue({patchWorksheet: vi.fn().mockResolvedValue({}),});- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { status: "CLEAN" },- });+ mocks.tabStatus = "CLEAN";- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());// Mock clipboardObject.defineProperty(navigator, "clipboard", {@@ -178,7 +187,9 @@ describe("SharePopoverBody", () => {mocks.useCurrentUserV1.mockReturnValue({value: { email: "[email protected]", name: "users/[email protected]" },});- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.usePiniaBridge.mockImplementation((getter: () => unknown) =>+ getter()+ );const { container, render, unmount } = renderIntoContainer(<SharePopoverBody worksheet={mockWorksheet as never} />@@ -239,10 +250,10 @@ describe("SharePopoverBody", () => {});test("copy button disabled when currentTab status is not CLEAN", () => {- mocks.useSQLEditorTabStore.mockReturnValue({- currentTab: { status: "DIRTY" },- });- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.tabStatus = "DIRTY";+ mocks.usePiniaBridge.mockImplementation((getter: () => unknown) =>+ getter()+ );const { container, render, unmount } = renderIntoContainer(<SharePopoverBody worksheet={mockWorksheet as never} />diff --git a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx b/frontend/src/react/components/sql-editor/SharePopoverBody.tsxindex 8357b627a7..d5b806e137 100644--- a/frontend/src/react/components/sql-editor/SharePopoverBody.tsx+++ b/frontend/src/react/components/sql-editor/SharePopoverBody.tsx@@ -13,9 +13,9 @@ import {PopoverContent,PopoverTrigger,} from "@/react/components/ui/popover";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import { router } from "@/router";import { SQL_EDITOR_WORKSHEET_MODULE } from "@/router/sqlEditor";import {@@ -48,13 +48,14 @@ export function SharePopoverBody({ worksheet }: Props) {const actuatorStore = useActuatorV1Store();const currentUserStore = useCurrentUserV1();const worksheetStore = useWorkSheetStore();- const tabStore = useSQLEditorTabStore();- const workspaceExternalURL = useVueState(+ const workspaceExternalURL = usePiniaBridge(() => actuatorStore.serverInfo?.externalUrl);- const currentUser = useVueState(() => currentUserStore.value);- const tabStatus = useVueState(() => tabStore.currentTab?.status);+ const currentUser = usePiniaBridge(() => currentUserStore.value);+ const tabStatus = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.status+ );const accessOptions = useMemo<AccessOption[]>(() => [diff --git a/frontend/src/react/components/sql-editor/SheetTree.test.tsx b/frontend/src/react/components/sql-editor/SheetTree.test.tsxindex f06835b738..5bc8e8279b 100644--- a/frontend/src/react/components/sql-editor/SheetTree.test.tsx+++ b/frontend/src/react/components/sql-editor/SheetTree.test.tsx@@ -19,10 +19,9 @@ globalThis.ResizeObserver = class ResizeObserver {const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),useWorkSheetStore: vi.fn(),- useSQLEditorTabStore: vi.fn(),- useSQLEditorVueState: vi.fn(),+ getSQLEditorTabsState: vi.fn(),+ project: "projects/proj1",// The new zustand store mock — only `createWorksheet` is used by SheetTree.createWorksheet: vi.fn().mockResolvedValue({}),useSheetContext: vi.fn(),@@ -36,21 +35,18 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({useWorkSheetStore: mocks.useWorkSheetStore,pushNotification: mocks.pushNotification,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ getSQLEditorTabsState: mocks.getSQLEditorTabsState,}));-vi.mock("@/react/stores/sqlEditor/editor-vue-state", () => ({- useSQLEditorVueState: mocks.useSQLEditorVueState,+vi.mock("@/react/stores/sqlEditor/editor", () => ({+ useSQLEditorEditorState: (selector: (s: { project: string }) => unknown) =>+ selector({ project: mocks.project }),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -342,6 +338,11 @@ const makeWorksheetNode = (},});+// The migrated `useSheetContext()` exposes `expandedKeys` / `selectedKeys`+// as plain values plus setters. We model the live state behind a `value`+// holder (so the existing per-test assertions like+// `expandedKeys.value.has(...)` keep working) and wire the component's+// `setExpandedKeys` setter to mutate that same holder.const makeExpandedKeysRef = (keys: string[] = []) => ({value: new Set(keys),});@@ -362,10 +363,8 @@ const setupDefaultMocks = () => {const selectedKeys = makeSelectedKeysRef();const editingNode = makeEditingNodeRef();- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());-const folderContext = {- rootPath: { value: "/my" },+ rootPath: "/my",isSubFolder: vi.fn(() => false),moveFolder: vi.fn(),removeFolder: vi.fn(),@@ -374,17 +373,38 @@ const setupDefaultMocks = () => {};const sheetContext = {- filter: { value: { keyword: "", onlyShowStarred: false } },- selectedKeys: selectedKeys,- expandedKeys: expandedKeys,- editingNode: editingNode,+ filter: { keyword: "", onlyShowStarred: false },+ get selectedKeys() {+ return Array.from(selectedKeys.value);+ },+ get expandedKeys() {+ return expandedKeys.value;+ },+ get editingNode() {+ return editingNode.value;+ },batchUpdateWorksheetFolders: vi.fn(),+ setExpandedKeys: vi.fn(+ (next: Set<string> | ((prev: Set<string>) => Set<string>)) => {+ expandedKeys.value =+ typeof next === "function" ? next(expandedKeys.value) : next;+ }+ ),+ setSelectedKeys: vi.fn((next: string[]) => {+ selectedKeys.value = new Set(next);+ }),+ setEditingNode: vi.fn((next: unknown) => {+ editingNode.value = next;+ }),};const viewContext = {- isInitialized: { value: true },- isLoading: { value: false },- sheetTree: { value: rootNode },+ isInitialized: true,+ isLoading: false,+ get sheetTree() {+ return viewContext._sheetTree.value;+ },+ _sheetTree: { value: rootNode } as { value: WorksheetFolderNode },fetchSheetList: vi.fn(),folderContext,getFoldersForWorksheet: vi.fn((path: string) => [path]),@@ -396,9 +416,6 @@ const setupDefaultMocks = () => {mocks.useSheetContext.mockReturnValue(sheetContext);mocks.useSheetContextByView.mockReturnValue(viewContext);- mocks.useSQLEditorVueState.mockReturnValue({- project: "projects/proj1",- });mocks.useWorkSheetStore.mockReturnValue({getWorksheetByName: vi.fn((name: string) => ({name,@@ -412,8 +429,8 @@ const setupDefaultMocks = () => {patchWorksheet: vi.fn().mockResolvedValue({}),upsertWorksheetOrganizer: vi.fn().mockResolvedValue(undefined),});- mocks.useSQLEditorTabStore.mockReturnValue({- getTabByWorksheet: vi.fn(() => null),+ mocks.getSQLEditorTabsState.mockReturnValue({+ tabsById: new Map(),closeTab: vi.fn(),updateTab: vi.fn(),setCurrentTabId: vi.fn(),@@ -510,7 +527,7 @@ describe("SheetTree", () => {// Root node is a folder with a worksheet childconst wsNode = makeWorksheetNode("/my/ws2");const rootNode = makeFolderNode("/my", [wsNode]);- defaultMocks.viewContext.sheetTree.value = rootNode;+ defaultMocks.viewContext._sheetTree.value = rootNode;// Make useDropdown return the worksheet node as currentmocks.useDropdown.mockReturnValue({@@ -558,7 +575,7 @@ describe("SheetTree", () => {const defaultMocks = setupDefaultMocks();const folder = makeFolderNode("/my/folder1", []);const rootNode = makeFolderNode("/my", [folder]);- defaultMocks.viewContext.sheetTree.value = rootNode;+ defaultMocks.viewContext._sheetTree.value = rootNode;// expandedKeys starts without /my/folder1defaultMocks.expandedKeys.value = new Set(["/my"]);@@ -591,7 +608,7 @@ describe("SheetTree", () => {const defaultMocks = setupDefaultMocks();const wsNode = makeWorksheetNode("/my/ws2");const rootNode = makeFolderNode("/my", [wsNode]);- defaultMocks.viewContext.sheetTree.value = rootNode;+ defaultMocks.viewContext._sheetTree.value = rootNode;const onCheckedNodesChange = vi.fn();@@ -633,7 +650,7 @@ describe("SheetTree", () => {const defaultMocks = setupDefaultMocks();const wsNode = makeWorksheetNode("/my/ws2");const rootNode = makeFolderNode("/my", [wsNode]);- defaultMocks.viewContext.sheetTree.value = rootNode;+ defaultMocks.viewContext._sheetTree.value = rootNode;const handleContextMenu = vi.fn();mocks.useDropdown.mockReturnValue({@@ -685,7 +702,7 @@ describe("SheetTree", () => {const defaultMocks = setupDefaultMocks();const wsNode = makeWorksheetNode("/my/ws2", "worksheets/ws2");const rootNode = makeFolderNode("/my", [wsNode]);- defaultMocks.viewContext.sheetTree.value = rootNode;+ defaultMocks.viewContext._sheetTree.value = rootNode;const deleteWorksheetByName = vi.fn().mockResolvedValue(undefined);mocks.useWorkSheetStore.mockReturnValue({diff --git a/frontend/src/react/components/sql-editor/SheetTree.tsx b/frontend/src/react/components/sql-editor/SheetTree.tsxindex dba0745b00..74e837b623 100644--- a/frontend/src/react/components/sql-editor/SheetTree.tsx+++ b/frontend/src/react/components/sql-editor/SheetTree.tsx@@ -54,11 +54,10 @@ import {import type { TreeDataNode } from "@/react/components/ui/tree";import { Tree } from "@/react/components/ui/tree";import { countVisibleRows } from "@/react/components/ui/tree-utils";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { pushNotification, useWorkSheetStore } from "@/store";import {openWorksheetByName,@@ -176,45 +175,35 @@ export function SheetTree({}: Props) {const { t } = useTranslation();- // ---- Pinia stores (called at top level, not inside useVueState) ----------+ // ---- Pinia stores (called at top level, not inside the Vue-bridge call) ----------const worksheetV1Store = useWorkSheetStore();- const tabStore = useSQLEditorTabStore();- const editorStore = useSQLEditorVueState();const createWorksheet = useSQLEditorReactStore((s) => s.createWorksheet);// ---- Sheet contexts -------------------------------------------------------- const sheetContext = useSheetContext();+ const {+ filter: worksheetFilter,+ selectedKeys,+ expandedKeys,+ editingNode,+ batchUpdateWorksheetFolders,+ setExpandedKeys,+ setEditingNode,+ } = useSheetContext();const {isInitialized,isLoading,- sheetTree: sheetTreeRef,+ sheetTree,fetchSheetList,folderContext,getFoldersForWorksheet,events,} = useSheetContextByView(view);- const {- filter: worksheetFilterRef,- selectedKeys: selectedKeysRef,- expandedKeys: expandedKeysRef,- editingNode: editingNodeRef,- batchUpdateWorksheetFolders,- } = sheetContext;-- // ---- Reactive reads from Vue/Pinia via useVueState ------------------------ const isLoadingVal = useVueState(() => isLoading.value);- const isInitializedVal = useVueState(() => isInitialized.value);- const project = useVueState(() => editorStore.project);- const sheetTree = useVueState(() => sheetTreeRef.value);- const worksheetFilter = useVueState(() => worksheetFilterRef.value);- const selectedKeys = useVueState(() =>- Array.from(selectedKeysRef.value ?? [])+ const project = useSQLEditorEditorState((s) => s.project);+ const expandedKeysArray = useMemo(+ () => Array.from(expandedKeys ?? []),+ [expandedKeys]);- const expandedKeysArray = useVueState(() =>- Array.from(expandedKeysRef.value ?? [])- );- const editingNode = useVueState(() => editingNodeRef.value);// ---- Dropdown hook -------------------------------------------------------const {@@ -298,22 +287,13 @@ export function SheetTree({// ---- Auto-fetch on mount + project change --------------------------------useEffect(() => {- if (!isInitializedVal && project) {+ if (!isInitialized && project) {void fetchSheetList();}- }, [isInitializedVal, project, fetchSheetList]);-- // When project changes, mark as uninitialized so fetch runs again.- const prevProjectRef = useRef(project);- useEffect(() => {- if (prevProjectRef.current !== project) {- prevProjectRef.current = project;- isInitialized.value = false;- }- }, [project, isInitialized]);+ }, [isInitialized, project, fetchSheetList]);// Focus + select-all ONCE when a new node enters editing. `editingNode` is- // a fresh object on every keystroke (onChange rewrites editingNodeRef.value),+ // a fresh object on every keystroke (onChange calls setEditingNode),// so depending on its identity would re-select on every keypress. Key the// effect on the node's stable `.key` instead.const editingKey = editingNode?.node.key;@@ -358,8 +338,8 @@ export function SheetTree({// non-matching rows, so the viewport should shrink accordingly.const nodeMatches = useCallback((node: WorksheetFolderNode, term: string): boolean =>- filterNode(folderContext.rootPath.value)(term, node),- [folderContext.rootPath.value]+ filterNode(folderContext.rootPath)(term, node),+ [folderContext.rootPath]);const treeHeight = useMemo(() =>@@ -375,13 +355,17 @@ export function SheetTree({// ---- Expand/collapse toggle -----------------------------------------------const handleToggleExpand = useCallback((node: WorksheetFolderNode) => {- if (expandedKeysRef.value.has(node.key)) {- expandedKeysRef.value.delete(node.key);- } else {- expandedKeysRef.value.add(node.key);- }+ setExpandedKeys((prev) => {+ const next = new Set(prev);+ if (next.has(node.key)) {+ next.delete(node.key);+ } else {+ next.add(node.key);+ }+ return next;+ });},- [expandedKeysRef]+ [setExpandedKeys]);// ---- Helpers: folder/tree operations ------------------------------------@@ -404,22 +388,24 @@ export function SheetTree({const replaceExpandedKeys = useCallback(({ oldKey, newKey }: { oldKey: string; newKey?: string }) => {- const newSet = new Set<string>();- for (const path of expandedKeysRef.value) {- if (- path === oldKey ||- folderContext.isSubFolder({ parent: oldKey, path, dig: true })- ) {- if (newKey) {- newSet.add(path.replace(oldKey, newKey));+ setExpandedKeys((prev) => {+ const newSet = new Set<string>();+ for (const path of prev) {+ if (+ path === oldKey ||+ folderContext.isSubFolder({ parent: oldKey, path, dig: true })+ ) {+ if (newKey) {+ newSet.add(path.replace(oldKey, newKey));+ }+ } else {+ newSet.add(path);}- } else {- newSet.add(path);}- }- expandedKeysRef.value = newSet;+ return newSet;+ });},- [expandedKeysRef, folderContext]+ [setExpandedKeys, folderContext]);const updateWorksheetFolders = useCallback(@@ -452,14 +438,17 @@ export function SheetTree({worksheetV1Store.deleteWorksheetByName(worksheet)));+ const tabsState = getSQLEditorTabsState();for (const worksheet of worksheets) {- const tab = tabStore.getTabByWorksheet(worksheet);+ const tab = Array.from(tabsState.tabsById.values()).find(+ (t) => t.worksheet === worksheet+ );if (tab) {- tabStore.closeTab(tab.id);+ tabsState.closeTab(tab.id);}}},- [worksheetV1Store, tabStore]+ [worksheetV1Store]);// ---- handleRenameNode (debounced via ref) ---------------------------------@@ -468,22 +457,24 @@ export function SheetTree({const renameTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const execRenameNode = useCallback(async () => {- const editing = editingNodeRef.value;+ const editing = editingNode;if (!editing) return;const cleanup = () => {// Use setTimeout to mimic nextTicksetTimeout(() => {- editingNodeRef.value = undefined;+ setEditingNode(undefined);}, 0);};- const newTitle = editing.node.label.trim();+ // `rawLabel` holds the in-progress edit value. `node.label` is the+ // original (the immer-frozen tree node is never mutated in place).+ const newTitle = editing.rawLabel.trim();// 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;+ // Empty folder name — abort the rename, leave the node untouched.cleanup();return;}@@ -506,14 +497,17 @@ export function SheetTree({await worksheetV1Store.patchWorksheet({ ...worksheet, title: newTitle }, ["title",]);- const tab = tabStore.getTabByWorksheet(worksheet.name);+ const tabsState = getSQLEditorTabsState();+ const tab = Array.from(tabsState.tabsById.values()).find(+ (t) => t.worksheet === worksheet.name+ );if (tab) {- tabStore.updateTab(tab.id, { title: newTitle });+ tabsState.updateTab(tab.id, { title: newTitle });}cleanup();} else {// Folder rename — check for duplicate name- const parentNode = findParentNode(sheetTreeRef.value, editing.node.key);+ const parentNode = findParentNode(sheetTree, editing.node.key);const sameNode = parentNode?.children.find((child) => child.key === newKey);@@ -537,7 +531,7 @@ export function SheetTree({cleanup();})();} else {- editing.node.label = editing.rawLabel;+ // User declined the merge — abort, leave the node as-is.cleanup();}setDeleteDialogState({ type: "none" });@@ -553,11 +547,11 @@ export function SheetTree({}}}, [- editingNodeRef,+ editingNode,+ setEditingNode,worksheetV1Store,- tabStore,findParentNode,- sheetTreeRef,+ sheetTree,updateWorksheetFolders,replaceExpandedKeys,folderContext,@@ -584,13 +578,13 @@ export function SheetTree({});} else {// draft tab- tabStore.setCurrentTabId(node.worksheet.name);+ getSQLEditorTabsState().setCurrentTabId(node.worksheet.name);}} else {handleToggleExpand(node);}},- [editingNode, tabStore, handleToggleExpand]+ [editingNode, handleToggleExpand]);// ---- Duplicate sheet -------------------------------------------------------@@ -647,7 +641,7 @@ export function SheetTree({worksheets.push(node.worksheet.name);continue;}- if (node.key === folderContext.rootPath.value) {+ if (node.key === folderContext.rootPath) {continue;}if (@@ -690,10 +684,10 @@ export function SheetTree({);break;case "rename":- editingNodeRef.value = {+ setEditingNode({node: contextMenuNode,rawLabel: contextMenuNode.label,- };+ });// Focus happens via useEffect abovebreak;case "delete":@@ -716,12 +710,16 @@ export function SheetTree({}break;case "add-folder": {- expandedKeysRef.value.add(contextMenuNode.key);+ setExpandedKeys((prev) => {+ const next = new Set(prev);+ next.add(contextMenuNode.key);+ return next;+ });const label = generateNewFolderName(contextMenuNode.children ?? []);const newPath = folderContext.addFolder(`${contextMenuNode.key}/${label}`);- editingNodeRef.value = {+ setEditingNode({node: {key: newPath,editable: true,@@ -729,7 +727,7 @@ export function SheetTree({children: [],},rawLabel: label,- };+ });break;}case "add-worksheet":@@ -754,8 +752,8 @@ export function SheetTree({},[contextMenuNode,- editingNodeRef,- expandedKeysRef,+ setEditingNode,+ setExpandedKeys,folderContext,getFoldersForWorksheet,createWorksheet,@@ -815,15 +813,12 @@ export function SheetTree({let parentFolderNode: WorksheetFolderNode | undefined;if (arboristParent === null) {// Dropped at root level — use the root of sheetTree- parentFolderNode = sheetTreeRef.value;+ parentFolderNode = sheetTree;} else {const candidate = arboristParent.data.data;if (candidate.worksheet) {// Should not happen given disableDrop predicate, but guard anyway.- parentFolderNode = findParentNode(- sheetTreeRef.value,- candidate.key- );+ parentFolderNode = findParentNode(sheetTree, candidate.key);} else {parentFolderNode = candidate;}@@ -837,10 +832,7 @@ export function SheetTree({if (!draggedTreeNode) return;const draggedNode = draggedTreeNode.data.data;- const oldParentNode = findParentNode(- sheetTreeRef.value,- draggedNode.key- );+ const oldParentNode = findParentNode(sheetTree, draggedNode.key);if (!oldParentNode) return;// No-op if parent folder didn't change@@ -874,30 +866,34 @@ export function SheetTree({// Update expanded keys (nextTick equivalent: defer to next microtask)setTimeout(() => {replaceExpandedKeys({ oldKey: draggedNode.key, newKey });- expandedKeysRef.value.add(parentFolderNode!.key);+ setExpandedKeys((prev) => {+ const next = new Set(prev);+ next.add(parentFolderNode!.key);+ return next;+ });if (shouldCloseOldParent) {replaceExpandedKeys({ oldKey: oldParentNode.key });}}, 0);},[- sheetTreeRef,+ sheetTree,findParentNode,folderContext,handleDuplicateFolderNameDrop,updateWorksheetFolders,replaceExpandedKeys,- expandedKeysRef,+ setExpandedKeys,]);// ---- Search match for Tree primitive ------------------------------------const searchMatch = useCallback((node: TreeDataNode<WorksheetFolderNode>, term: string): boolean => {- const pred = filterNode(folderContext.rootPath.value);+ const pred = filterNode(folderContext.rootPath);return pred(term, node.data);},- [folderContext.rootPath.value]+ [folderContext.rootPath]);// ---- renderNode ----------------------------------------------------------@@ -993,7 +989,7 @@ export function SheetTree({<TreeNodePrefixnode={folderNode}isOpen={isOpen}- rootPath={folderContext.rootPath.value}+ rootPath={folderContext.rootPath}view={view}/></span>@@ -1005,7 +1001,11 @@ export function SheetTree({ref={inputRef}id={`sheet-input-${folderNode.key}`}size="sm"- value={editingNode.node.label}+ // Bind to the editable `rawLabel`, NOT `node.label`. The+ // editingNode lives in the immer-backed sheet-context+ // store and is frozen — mutating `node.label` silently+ // no-ops, which froze the input (could not type).+ value={editingNode.rawLabel}className="h-5 py-0 text-xs px-1!"autoFocusonBlur={() => handleRenameNode()}@@ -1026,9 +1026,7 @@ export function SheetTree({// folder names cannot contain "/" or "."if (val.includes("/") || val.includes(".")) return;}- editingNode.node.label = val;- // Force a re-render by triggering a Pinia write- editingNodeRef.value = { ...editingNode };+ setEditingNode({ ...editingNode, rawLabel: val });}}onClick={(e) => e.stopPropagation()}/>@@ -1067,7 +1065,7 @@ export function SheetTree({selectedKeys,expandedKeysArray,editingNode,- editingNodeRef,+ setEditingNode,checkedNodes,multiSelectMode,worksheetFilter,@@ -1079,12 +1077,13 @@ export function SheetTree({openMenuAtPoint,openMenuAtElement,openSharePanelAtElement,+ t,onCheckedNodesChange,]);// ---- Loading spinner ------------------------------------------------------ if (isLoadingVal) {+ if (isLoading) {return (<div className="flex items-center justify-center p-4"><Loader2 className="size-4 animate-spin text-control-light" />@@ -1245,7 +1244,7 @@ export function SheetTree({deleteFoldersResolveRef.current = null;} else {await doDeleteWorksheets(worksheets);- for (const folder of folderContext.rootPath.value ? [] : []) {+ for (const folder of folderContext.rootPath ? [] : []) {folderContext.removeFolder(folder);}}diff --git a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsxindex 4dbd85e337..b1a447649e 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/EditorMain.tsx@@ -1,11 +1,12 @@import { useCallback, useEffect } from "react";import { ReadonlyModeNotSupported } from "@/react/components/sql-editor/ReadonlyModeNotSupported";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ getSQLEditorTabsState,+ useIsDisconnected,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { useDatabaseV1Store } from "@/store";import type { SQLEditorQueryParams } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -35,13 +36,12 @@ interface EditorMainProps {* the cross-framework boundary stays clean — see Stage 17 design.*/export function EditorMain({ onChangeConnection }: EditorMainProps) {- const tabStore = useSQLEditorTabStore();const databaseStore = useDatabaseV1Store();const { instance } = useConnectionOfCurrentSQLEditorTab();- const tabId = useVueState(() => tabStore.currentTab?.id);- const isDisconnected = useVueState(() => tabStore.isDisconnected);- const engine = useVueState(() => instance.value.engine);+ const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);+ const isDisconnected = useIsDisconnected();+ const engine = instance.engine;const allowReadonlyMode =!isDisconnected && instanceV1HasReadonlyMode(engine ?? Engine.MYSQL);@@ -51,7 +51,8 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {const handleExecute = useCallback(({ params, newTab }: { params: SQLEditorQueryParams; newTab: boolean }) => {if (newTab) {- tabStore.cloneTab(tabStore.currentTabId, {+ const tabsState = getSQLEditorTabsState();+ tabsState.cloneTab(tabsState.currentTabId, {statement: params.statement,});}@@ -59,20 +60,21 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {void execute(params);});},- [tabStore, execute]+ [execute]);// Run-from-toolbar: pull the active statement that the React// `SQLEditor` published to the shared shallowRef.const handleExecuteFromActionBar = useCallback((params: SQLEditorQueryParams) => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;const statement =activeStatementRef.value || tab.statement || params.statement;handleExecute({ params: { ...params, statement }, newTab: false });},- [tabStore, handleExecute]+ [handleExecute]);// execute-sql event (fired e.g. from the schema-pane "run" affordance)@@ -83,7 +85,7 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {const database = await databaseStore.getOrFetchDatabaseByName(connection.database);- const newTab = tabStore.addTab(+ const newTab = getSQLEditorTabsState().addTab({ connection, statement, batchQueryContext },/* beside */ true);@@ -101,7 +103,7 @@ export function EditorMain({ onChangeConnection }: EditorMainProps) {return () => {off();};- }, [databaseStore, tabStore, execute]);+ }, [databaseStore, execute]);if (!isDisconnected && !allowReadonlyMode) {// Connected to an instance without a read-only data source —diff --git a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsxindex eb3ca2b1fb..14321cbf88 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/SQLEditor.tsx@@ -15,13 +15,14 @@ import {extensionNameOfLanguage,formatEditorContent,} from "@/react/components/monaco/utils";-import { useVueState } from "@/react/hooks/useVueState";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";+import { useWorksheetAndTab } from "@/react/hooks/useWorksheetAndTab";import { useSQLEditorStore } from "@/react/stores/sqlEditor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";-import { useUIStateStore, useWorkSheetAndTabStore } from "@/store";+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";+import { useUIStateStore } from "@/store";import {dialectOfEngineV1,isValidDatabaseName,@@ -64,24 +65,24 @@ interface SQLEditorProps {* is run from the toolbar.*/export function SQLEditor({ onExecute }: SQLEditorProps) {- const tabStore = useSQLEditorTabStore();- const sheetAndTabStore = useWorkSheetAndTabStore();const uiStateStore = useUIStateStore();+ const { isReadOnly: readonly } = useWorksheetAndTab();const setShowAIPanel = useSQLEditorStore((s) => s.setShowAIPanel);const setPendingInsertAtCaret = useSQLEditorStore((s) => s.setPendingInsertAtCaret);const { instance, database } = useConnectionOfCurrentSQLEditorTab();- const tabId = useVueState(() => tabStore.currentTab?.id);- const content = useVueState(() => tabStore.currentTab?.statement ?? "");- const readonly = useVueState(() => sheetAndTabStore.isReadOnly);- const engine = useVueState(() => instance.value.engine);- const instanceName = useVueState(() => instance.value.name);- const databaseName = useVueState(() => database.value.name);- const schema = useVueState(() => tabStore.currentTab?.connection.schema, {- deep: true,- });+ const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);+ const content = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.statement ?? ""+ );+ const engine = instance.engine;+ const instanceName = instance.name;+ const databaseName = database.name;+ const schema = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.schema+ );const language = useMemo(() => languageOfEngineV1(engine ?? Engine.MYSQL),@@ -130,25 +131,25 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {}, []);const getActiveStatement = useCallback(() => {- return activeStatementRef.value || tabStore.currentTab?.statement || "";- }, [tabStore]);+ const tabsState = getSQLEditorTabsState();+ return (+ activeStatementRef.value ||+ tabsState.tabsById.get(tabsState.currentTabId)?.statement ||+ ""+ );+ }, []);// ----- statement sync ------ const handleChange = useCallback(- (value: string) => {- const tab = tabStore.currentTab;- if (!tab || value === tab.statement) return;- tabStore.updateCurrentTab({ statement: value, status: "DIRTY" });- },- [tabStore]- );+ const handleChange = useCallback((value: string) => {+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);+ if (!tab || value === tab.statement) return;+ tabsState.updateCurrentTab({ statement: value, status: "DIRTY" });+ }, []);- const handleSelectContent = useCallback(- (value: string) => {- tabStore.updateCurrentTab({ selectedStatement: value });- },- [tabStore]- );+ const handleSelectContent = useCallback((value: string) => {+ getSQLEditorTabsState().updateCurrentTab({ selectedStatement: value });+ }, []);// Guard flag so the Vue→Monaco selection watcher below doesn't fire// when the change came from the editor itself (would interrupt@@ -157,41 +158,45 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {const handleSelectionChange = useCallback((selection: MonacoSelection | null) => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;selectionFromEditorRef.current = true;- tabStore.updateCurrentTab({ editorState: { selection } });+ tabsState.updateCurrentTab({ editorState: { selection } });},- [tabStore]+ []);// Watch tab.editorState.selection — if it changes and the change// wasn't driven by the editor itself, push it back into Monaco.- const tabSelectionString = useVueState(- () => tabStore.currentTab?.editorState.selection?.toString(),- { deep: true }+ const tabSelectionString = useSQLEditorTabState((s) =>+ s.tabsById.get(s.currentTabId)?.editorState.selection?.toString());useEffect(() => {if (selectionFromEditorRef.current) {selectionFromEditorRef.current = false;return;}- const selection = tabStore.currentTab?.editorState.selection;+ const tabsState = getSQLEditorTabsState();+ const selection = tabsState.tabsById.get(tabsState.currentTabId)+ ?.editorState.selection;if (!selection) return;activeSQLEditorRef.value?.setSelection(selection);- }, [tabSelectionString, tabStore]);+ }, [tabSelectionString]);// ----- save handler (just emits the event so SaveSheetModal opens) -----const handleSaveSheet = useCallback(() => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;void sqlEditorEvents.emit("save-sheet", { tab });- }, [tabStore]);+ }, []);// ----- run query -----const runQueryAction = useCallback(({ explain, newTab }: { explain: boolean; newTab: boolean }) => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;const statement = getActiveStatement();const params: SQLEditorQueryParams = {@@ -207,7 +212,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {newState: true,});},- [tabStore, getActiveStatement, uiStateStore]+ [getActiveStatement, uiStateStore]);// ----- onReady: register Monaco actions + commands -----@@ -248,7 +253,8 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {setShowAIPanel(true);const statement = getActiveStatement();if (!statement) return;- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);const eng = engineRef.current ?? Engine.MYSQL;void nextAnimationFrame().then(() => {if (action === "explain-code") {@@ -270,7 +276,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {}});},- [setShowAIPanel, getActiveStatement, tabStore]+ [setShowAIPanel, getActiveStatement]);useAIActions({@@ -327,34 +333,32 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {}, [pendingInsertAtCaret, setPendingInsertAtCaret]);// ----- file upload (triggered by UploadFileButton in cornerPrefix) ------ const handleUploadFile = useCallback(- (uploaded: string) => {- const editor = activeSQLEditorRef.value;- if (!editor) return;- const tab = tabStore.currentTab;- if (!tab) return;- let text = uploaded;- if (tab.statement.trim() !== "") {- text = "\n" + text;- }- const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;- editor.executeEdits("bb.event.upload-file", [- {- forceMoveMarkers: true,- text,- range: {- startLineNumber: maxLineNumber + 1,- startColumn: 1,- endLineNumber: maxLineNumber + 1,- endColumn: 1,- },+ const handleUploadFile = useCallback((uploaded: string) => {+ const editor = activeSQLEditorRef.value;+ if (!editor) return;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);+ if (!tab) return;+ let text = uploaded;+ if (tab.statement.trim() !== "") {+ text = "\n" + text;+ }+ const maxLineNumber = editor.getModel()?.getLineCount() ?? 0;+ editor.executeEdits("bb.event.upload-file", [+ {+ forceMoveMarkers: true,+ text,+ range: {+ startLineNumber: maxLineNumber + 1,+ startColumn: 1,+ endLineNumber: maxLineNumber + 1,+ endColumn: 1,},- ]);- const newMaxLineNumber = editor.getModel()?.getLineCount() ?? 0;- editor.revealLine(newMaxLineNumber);- },- [tabStore]- );+ },+ ]);+ const newMaxLineNumber = editor.getModel()?.getLineCount() ?? 0;+ editor.revealLine(newMaxLineNumber);+ }, []);// ----- event listeners (sqlEditorEvents) -----useEffect(() => {@@ -378,7 +382,9 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {({ content: appended, select }) => {const editor = activeSQLEditorRef.value;if (!editor) return;- const oldStatement = tabStore.currentTab?.statement ?? "";+ const tabsState = getSQLEditorTabsState();+ const oldStatement =+ tabsState.tabsById.get(tabsState.currentTabId)?.statement ?? "";const newStatement = [oldStatement, appended].filter((s) => s).join("\n\n");@@ -401,7 +407,7 @@ export function SQLEditor({ onExecute }: SQLEditorProps) {offSetSelection();offAppend();};- }, [tabStore]);+ }, []);// Clear the global refs on unmount.useEffect(() => {diff --git a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsxindex a9755b6d80..8a2c01ee58 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/StandardPanel.tsx@@ -9,15 +9,15 @@ 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 { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";import {selectEditorPanelSize,useSQLEditorStore,} from "@/react/stores/sqlEditor";import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+ useCurrentSQLEditorTab,+ useIsDisconnected,+} from "@/react/stores/sqlEditor/tab";import { instanceV1HasReadonlyMode } from "@/utils";import { EditorMain } from "./EditorMain";@@ -45,12 +45,11 @@ const AIPaneFallback = () => (* state — the Vue `<VueMount component={AIChatToSQLBridgeHost}>`* bridge is gone.*- * State source: `useSQLEditorTabStore` for tab + disconnect state,+ * State source: tab Zustand selectors for tab + disconnect state,* `useConnectionOfCurrentSQLEditorTab` for the current instance,* `useSQLEditorStore` (zustand) for AI-panel visibility / sizing.*/export function StandardPanel() {- const tabStore = useSQLEditorTabStore();const handleEditorPanelResize = useSQLEditorStore((s) => s.handleEditorPanelResize);@@ -58,15 +57,13 @@ export function StandardPanel() {const setShowConnectionPanel = useSQLEditorStore((s) => s.setShowConnectionPanel);- const { instance: instanceRef } = useConnectionOfCurrentSQLEditorTab();+ const { instance } = useConnectionOfCurrentSQLEditorTab();- const tab = useVueState(() => tabStore.currentTab);- const isDisconnected = useVueState(() => tabStore.isDisconnected);+ const tab = useCurrentSQLEditorTab();+ const isDisconnected = useIsDisconnected();const showAIPanel = useSQLEditorStore((s) => s.showAIPanel);const editorPanelSize = useSQLEditorStore(useShallow(selectEditorPanelSize));- const instanceHasReadonly = useVueState(() =>- instanceV1HasReadonlyMode(instanceRef.value)- );+ const instanceHasReadonly = instanceV1HasReadonlyMode(instance);if (tab && tab.mode !== "WORKSHEET") {return null;diff --git a/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsxindex 0d8a359061..adf95ec5e3 100644--- a/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx+++ b/frontend/src/react/components/sql-editor/StandardPanel/UploadFileButton.tsx@@ -2,8 +2,7 @@ import { Upload } from "lucide-react";import { useCallback } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import { SQLUploadButton } from "./SQLUploadButton";interface UploadFileButtonProps {@@ -17,8 +16,7 @@ interface UploadFileButtonProps {*/export function UploadFileButton({ onUpload }: UploadFileButtonProps) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();- const tabId = useVueState(() => tabStore.currentTab?.id);+ const tabId = useSQLEditorTabState((s) => s.tabsById.get(s.currentTabId)?.id);const handleUpdateSql = useCallback((content: string) => {diff --git a/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx b/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsxindex 817e576512..f475e50dcc 100644--- a/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/AdminLabel.tsx@@ -1,6 +1,6 @@import { ChevronRight } from "lucide-react";import { useEffect } from "react";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useDatabaseV1Store } from "@/store";import { UNKNOWN_ID } from "@/types/const";import type { SQLEditorTab } from "@/types/sqlEditor/tab";@@ -33,7 +33,9 @@ export function AdminLabel({ tab }: Props) {void databaseStore.getOrFetchDatabaseByName(dbName);}, [databaseStore, dbName]);- const database = useVueState(() => databaseStore.getDatabaseByName(dbName));+ const database = usePiniaBridge(() =>+ databaseStore.getDatabaseByName(dbName)+ );const instance = getInstanceResource(database);const environment = getDatabaseEnvironment(database);const { databaseName } = extractDatabaseResourceName(database.name);diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsxindex 219df8a5c5..006494fcdb 100644--- a/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/Label.test.tsx@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({updateTab: vi.fn(),setCurrentTabId: vi.fn(),patchWorksheet: vi.fn().mockResolvedValue(undefined),- useSQLEditorTabStore: vi.fn(),+ getSQLEditorTabsState: vi.fn(),useWorkSheetStore: vi.fn(),tabListEvents: {on: vi.fn<(event: string, h: (p: unknown) => void) => () => void>(),@@ -23,8 +23,8 @@ vi.mock("@/store", () => ({useWorkSheetStore: mocks.useWorkSheetStore,}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ getSQLEditorTabsState: mocks.getSQLEditorTabsState,}));vi.mock("@/views/sql-editor/TabList/events", () => ({@@ -85,7 +85,7 @@ beforeEach(async () => {// `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({+ mocks.getSQLEditorTabsState.mockReturnValue({currentTabId: "t1",updateTab: mocks.updateTab,setCurrentTabId: mocks.setCurrentTabId,@@ -133,7 +133,7 @@ describe("Label", () => {});test("clicking a non-current tab does NOT enter edit mode", () => {- mocks.useSQLEditorTabStore.mockReturnValue({+ mocks.getSQLEditorTabsState.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.diff --git a/frontend/src/react/components/sql-editor/TabItem/Label.tsx b/frontend/src/react/components/sql-editor/TabItem/Label.tsxindex 3416870b19..be0d072716 100644--- a/frontend/src/react/components/sql-editor/TabItem/Label.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/Label.tsx@@ -3,7 +3,7 @@ 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 } from "@/react/stores/sqlEditor/tab-vue-state";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { useWorkSheetStore } from "@/store";import { WorksheetSchema } from "@/types/proto-es/v1/worksheet_service_pb";import type { SQLEditorTab } from "@/types/sqlEditor/tab";@@ -23,7 +23,6 @@ type Props = {*/export function Label({ tab }: Props) {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const worksheetStore = useWorkSheetStore();const [editing, setEditing] = useState(false);@@ -54,7 +53,7 @@ export function Label({ tab }: Props) {const confirmEdit = () => {const title = draft.trim();- tabStore.updateTab(tab.id, { title });+ getSQLEditorTabsState().updateTab(tab.id, { title });if (tab.worksheet) {void worksheetStore.patchWorksheet(create(WorksheetSchema, {@@ -93,7 +92,7 @@ export function Label({ tab }: Props) {useEffect(() => {const unsubscribe = tabListEvents.on("rename-tab", (payload) => {if (payload.tab.id !== tab.id) return;- tabStore.setCurrentTabId(tab.id);+ getSQLEditorTabsState().setCurrentTabId(tab.id);if (readonly) return;setDraft(tab.title);setEditing(true);@@ -101,7 +100,7 @@ export function Label({ tab }: Props) {return () => {unsubscribe();};- }, [tab.id, tab.title, readonly, tabStore]);+ }, [tab.id, tab.title, readonly]);return (<div@@ -137,7 +136,8 @@ export function Label({ tab }: Props) {<divclassName="absolute inset-0 cursor-text"onMouseDown={() => {- wasCurrentAtMouseDownRef.current = tabStore.currentTabId === tab.id;+ wasCurrentAtMouseDownRef.current =+ getSQLEditorTabsState().currentTabId === tab.id;}}onClick={() => {if (wasCurrentAtMouseDownRef.current) beginEdit();diff --git a/frontend/src/react/components/sql-editor/TabItem/Prefix.tsx b/frontend/src/react/components/sql-editor/TabItem/Prefix.tsxindex 719bbc96e8..89ef94a087 100644--- a/frontend/src/react/components/sql-editor/TabItem/Prefix.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/Prefix.tsx@@ -1,5 +1,5 @@import { PencilLine, Users, Wrench } from "lucide-react";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useWorkSheetStore } from "@/store";import type { SQLEditorTab } from "@/types/sqlEditor/tab";import { useSheetContext } from "@/views/sql-editor/Sheet";@@ -23,7 +23,7 @@ export function Prefix({ tab }: Props) {const isDraft = !tab.worksheet && tab.viewState.view === "CODE";- const sheet = useVueState(() =>+ const sheet = usePiniaBridge(() =>tab.worksheet ? sheetStore.getWorksheetByName(tab.worksheet) : null);diff --git a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsxindex 0108bc819b..c3b7267c3f 100644--- a/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx+++ b/frontend/src/react/components/sql-editor/TabItem/TabItem.tsx@@ -1,9 +1,9 @@import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { useState } from "react";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import { UNKNOWN_ID } from "@/types/const";import type { SQLEditorTab } from "@/types/sqlEditor/tab";import {@@ -41,8 +41,7 @@ export function TabItem({onClose,onContextMenu,}: Props) {- const tabStore = useSQLEditorTabStore();- const currentTabId = useVueState(() => tabStore.currentTabId);+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);const [hovering, setHovering] = useState(false);const {@@ -57,12 +56,12 @@ export function TabItem({const isCurrentTab = tab.id === currentTabId;// Derive the environment tint (used as the top border on the current tab).- // Wrapped in `useVueState` so the tab re-renders when the Pinia+ // Wrapped in `usePiniaBridge` so the tab re-renders when the Pinia// database/environment state hydrates async — without this the tab// sticks on the fallback `#4f46e5` indigo even after the environment// resolves, which is what made the React tabs look more saturated// than the Vue version.- const environmentTintColor = useVueState(() => {+ const environmentTintColor = usePiniaBridge(() => {const { database } = getConnectionForSQLEditorTab(tab);if (!database) return undefined;const environment = getDatabaseEnvironment(database);diff --git a/frontend/src/react/components/sql-editor/TabList.test.tsx b/frontend/src/react/components/sql-editor/TabList.test.tsxindex 55ede86005..9837f00b10 100644--- a/frontend/src/react/components/sql-editor/TabList.test.tsx+++ b/frontend/src/react/components/sql-editor/TabList.test.tsx@@ -16,8 +16,16 @@ globalThis.ResizeObserver = class ResizeObserver {const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),- useSQLEditorTabStore: vi.fn(),+ // The migrated TabList reads tabs via the Zustand selector hooks+ // (`useOpenTabList` / `useSQLEditorTabState`) and imperative actions via+ // `getSQLEditorTabsState()`. `tabState` is the stub the selectors run+ // against; `getSQLEditorTabsState` returns the same object.+ tabState: { currentTabId: "", openTabList: [] } as {+ currentTabId: string;+ openTabList: SQLEditorTab[];+ setCurrentTabId?: (id: string) => void;+ closeTab?: (id: string) => void;+ },closeTab: vi.fn(),setCurrentTabId: vi.fn(),createWorksheet: vi.fn().mockResolvedValue(undefined),@@ -29,14 +37,13 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/store", () => ({}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ getSQLEditorTabsState: () => mocks.tabState,+ useOpenTabList: () => mocks.tabState.openTabList,+ useSQLEditorTabState: (selector: (s: typeof mocks.tabState) => unknown) =>+ selector(mocks.tabState),}));vi.mock("@/react/stores/sqlEditor", () => ({@@ -208,16 +215,14 @@ const makeTab = (}) as unknown as SQLEditorTab;const setup = (tabs: SQLEditorTab[], currentTabId = tabs[0]?.id ?? "") => {- const tabStore = {+ Object.assign(mocks.tabState, {openTabList: tabs,currentTabId,setCurrentTabId: mocks.setCurrentTabId,closeTab: mocks.closeTab,- };- mocks.useSQLEditorTabStore.mockReturnValue(tabStore);- mocks.useVueState.mockImplementation((getter) => getter());+ });mocks.tabListEventsOn.mockReturnValue(() => {});- return { tabStore };+ return { tabStore: mocks.tabState };};beforeEach(async () => {diff --git a/frontend/src/react/components/sql-editor/TabList.tsx b/frontend/src/react/components/sql-editor/TabList.tsxindex 84852a7320..24cbfb4a1c 100644--- a/frontend/src/react/components/sql-editor/TabList.tsx+++ b/frontend/src/react/components/sql-editor/TabList.tsx@@ -29,10 +29,13 @@ import {AlertDialogTitle,} from "@/react/components/ui/alert-dialog";import { Button } from "@/react/components/ui/button";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useOpenTabList,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import type { SQLEditorTab } from "@/types/sqlEditor/tab";import { tabListEvents } from "@/views/sql-editor/TabList/events";import { TabContextMenu, type TabContextMenuHandle } from "./TabContextMenu";@@ -58,17 +61,13 @@ type PendingClose = {*/export function TabList() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const createWorksheet = useSQLEditorStore((s) => s.createWorksheet);- // `deep: true` so React re-renders when a tab's nested fields change- // (e.g. `tab.connection` after setConnection, or `tab.status` after- // auto-save). `tabStore.updateTab` mutates tabs in place via- // `Object.assign`, so the tab references stay the same and a shallow- // watcher would miss the change — visible symptom: the tab keeps the- // disconnect icon until the user hovers (which forces a re-render).- const tabs = useVueState(() => [...tabStore.openTabList], { deep: true });- const currentTabId = useVueState(() => tabStore.currentTabId);+ // Zustand's selector subscribes to in-place tab mutations because+ // `updateTab` reassigns / triggers an immer produce on `tabsById`,+ // bumping the slice identity.+ const tabs = useOpenTabList();+ const currentTabId = useSQLEditorTabState((s) => s.currentTabId);const scrollRef = useRef<HTMLDivElement>(null);const contextMenuRef = useRef<TabContextMenuHandle>(null);@@ -143,18 +142,19 @@ export function TabList() {const removeTab = useCallback(async (tab: SQLEditorTab, focusWhenConfirm = false) => {+ const tabsState = getSQLEditorTabsState();if (tab.mode === "WORKSHEET" && tab.status !== "CLEAN") {if (focusWhenConfirm) {- tabStore.setCurrentTabId(tab.id);+ tabsState.setCurrentTabId(tab.id);}const confirmed = await confirmCloseUnsaved(tab);if (!confirmed) return false;}- tabStore.closeTab(tab.id);+ tabsState.closeTab(tab.id);requestAnimationFrame(recalculateScrollState);return true;},- [tabStore, confirmCloseUnsaved, recalculateScrollState]+ [confirmCloseUnsaved, recalculateScrollState]);const handleAddTab = async () => {@@ -173,7 +173,7 @@ export function TabList() {};const handleSelect = (tab: SQLEditorTab) => {- tabStore.setCurrentTabId(tab.id);+ getSQLEditorTabsState().setCurrentTabId(tab.id);};const handleClose = (tab: SQLEditorTab) => {@@ -202,9 +202,17 @@ export function TabList() {const next = [...tabs];const [moved] = next.splice(oldIndex, 1);next.splice(newIndex, 0, moved);- // The store exposes `openTabList` as a writable computed. Assigning to- // it reorders the underlying tmp list.- tabStore.openTabList = next;+ // Rewrite the persisted tab order without touching individual tabs.+ getSQLEditorTabsState().setOpenTabListOrder(+ next.map((tab) => ({+ id: tab.id,+ worksheet: tab.worksheet,+ mode: tab.mode,+ batchQueryContext: tab.batchQueryContext,+ treeState: tab.treeState,+ viewState: tab.viewState,+ }))+ );};// Listen for close-tab events from the context menu (batch actions).@@ -212,7 +220,10 @@ export function TabList() {const unsubscribe = tabListEvents.on("close-tab",async ({ tab, index, action }) => {- const snapshot = [...tabStore.openTabList];+ const tabsState = getSQLEditorTabsState();+ const snapshot = tabsState.openTmpTabList+ .map((persisted) => tabsState.tabsById.get(persisted.id))+ .filter((t): t is SQLEditorTab => !!t);const max = snapshot.length - 1;const remove = async (t: SQLEditorTab) => {await removeTab(t, true);@@ -248,7 +259,7 @@ export function TabList() {return () => {unsubscribe();};- }, [tabStore, removeTab]);+ }, [removeTab]);return (<divdiff --git a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsxindex cf59d1c405..2a1211649e 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx+++ b/frontend/src/react/components/sql-editor/TerminalPanel/CompactSQLEditor.tsx@@ -8,11 +8,8 @@ import type {MonacoModule,} from "@/react/components/monaco/types";import { formatEditorContent } from "@/react/components/monaco/utils";-import { useVueState } from "@/react/hooks/useVueState";-import {- useConnectionOfCurrentSQLEditorTab,- useSQLEditorTabStore,-} from "@/react/stores/sqlEditor/tab-vue-state";+import { useConnectionOfCurrentSQLEditorTab } from "@/react/hooks/useSQLEditorBridge";+import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import type { SQLEditorQueryParams } from "@/types";import { dialectOfEngineV1 } from "@/types";import { Engine } from "@/types/proto-es/v1/common_pb";@@ -57,11 +54,10 @@ export function CompactSQLEditor({onHistory,onClearScreen,}: CompactSQLEditorProps) {- const tabStore = useSQLEditorTabStore();const { connection, instance, database } =useConnectionOfCurrentSQLEditorTab();- const engine = useVueState(() => instance.value.engine);+ const engine = instance.engine;const language = useMemo(() => languageOfEngineV1(engine ?? Engine.MYSQL),[engine]@@ -71,11 +67,11 @@ export function CompactSQLEditor({[engine]);- const databaseName = useVueState(() => database.value.name);- const instanceName = useVueState(() => instance.value.name);- const schema = useVueState(() => tabStore.currentTab?.connection.schema, {- deep: true,- });+ const databaseName = database.name;+ const instanceName = instance.name;+ const schema = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.connection.schema+ );// Latest-prop refs so Monaco actions registered once can read live values.const propsRef = useRef({@@ -142,7 +138,7 @@ export function CompactSQLEditor({const execute = (explain = false) => {const c = connectionRef.current;propsRef.current.onExecute({- connection: { ...c.value },+ connection: { ...c },statement: propsRef.current.content,engine: engineRef.current ?? Engine.MYSQL,explain,@@ -283,7 +279,7 @@ export function CompactSQLEditor({run: () => {const c = connectionRef.current;propsRef.current.onExecute({- connection: { ...c.value },+ connection: { ...c },statement: propsRef.current.content,engine,explain: true,diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsxindex adcf5bc7cb..a10db41a98 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx+++ b/frontend/src/react/components/sql-editor/TerminalPanel/TerminalPanel.tsx@@ -5,9 +5,12 @@ import type { IStandaloneCodeEditor } from "@/react/components/monaco/types";import { ConnectionHolder } from "@/react/components/sql-editor/ConnectionHolder";import { EditorAction } from "@/react/components/sql-editor/EditorAction";import { ResultView } from "@/react/components/sql-editor/ResultView";-import { useVueState } from "@/react/hooks/useVueState";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useIsDisconnected,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { getWebTerminalQuerySession } from "@/react/stores/sqlEditor/webTerminal-service";import { useDatabaseV1Store } from "@/store";import type { SQLEditorQueryParams, WebTerminalQueryItemV1 } from "@/types";@@ -34,7 +37,6 @@ import { useHistory } from "./useHistory";*/export function TerminalPanel() {const { t } = useTranslation();- const tabStore = useSQLEditorTabStore();const databaseStore = useDatabaseV1Store();const updateWebTerminalQueryItem = useSQLEditorStore((s) => s.updateWebTerminalQueryItem@@ -43,8 +45,10 @@ export function TerminalPanel() {(s) => s.replaceWebTerminalQueryItems);- const isDisconnected = useVueState(() => tabStore.isDisconnected);- const currentTabId = useVueState(() => tabStore.currentTab?.id);+ const isDisconnected = useIsDisconnected();+ const currentTabId = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.id+ );// Lazily create the per-tab session (WebSocket + timer + event bus)// when this panel mounts for a new tab. The zustand selector below@@ -52,10 +56,11 @@ export function TerminalPanel() {// up here so the controller and timer exist by the time the user// hits Enter.useEffect(() => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;getWebTerminalQuerySession(tab);- }, [tabStore, currentTabId]);+ }, [currentTabId]);// Subscribe to the per-tab query items from the zustand slice — every// mutation (push, status flip, resultSet attach) produces a new array@@ -74,7 +79,8 @@ export function TerminalPanel() {const [expired, setExpired] = useState(false);useEffect(() => {const tick = () => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) {setExpired(false);return;@@ -84,7 +90,7 @@ export function TerminalPanel() {tick();const interval = setInterval(tick, 250);return () => clearInterval(interval);- }, [tabStore, currentTabId]);+ }, [currentTabId]);// Pre-fetch any database referenced by an existing query item so the// ResultView can render `database.environment` etc. synchronously.@@ -107,16 +113,18 @@ export function TerminalPanel() {console.warn("Empty query");return;}- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;const session = getWebTerminalQuerySession(tab);void session.controller.events.emit("query", params);},- [currentQuery, tabStore]+ [currentQuery]);const handleClearScreen = useCallback(() => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;// Keep only the live (tail) query item; the slice replaces the// whole array, so React re-renders via the existing selector.@@ -125,7 +133,7 @@ export function TerminalPanel() {EMPTY_QUERY_LIST;if (items.length <= 1) return;replaceWebTerminalQueryItems(tab.id, items.slice(-1));- }, [tabStore, replaceWebTerminalQueryItems]);+ }, [replaceWebTerminalQueryItems]);const handleHistory = useCallback((direction: "up" | "down", editor: IStandaloneCodeEditor) => {@@ -143,7 +151,8 @@ export function TerminalPanel() {);const handleCancelQuery = () => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;getWebTerminalQuerySession(tab).controller.abort();};diff --git a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.tsindex 489f632646..c02fd69376 100644--- a/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts+++ b/frontend/src/react/components/sql-editor/TerminalPanel/useHistory.ts@@ -1,7 +1,9 @@import { useEffect, useRef } from "react";-import { useVueState } from "@/react/hooks/useVueState";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import type { WebTerminalQueryItemV1 } from "@/types";import { minmax } from "@/utils";@@ -28,13 +30,14 @@ interface HistoryState {* meaning the prior tail's statement is locked in).*/export function useHistory() {- const tabStore = useSQLEditorTabStore();const updateWebTerminalQueryItem = useSQLEditorStore((s) => s.updateWebTerminalQueryItem);const historyByTabIdRef = useRef(new Map<string, HistoryState>());- const currentTabId = useVueState(() => tabStore.currentTab?.id);+ const currentTabId = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.id+ );// Subscribe to the tail item's id. The id changes only when a new tail is// appended (the slice patches statement updates in place by id, preserving// it). Tracking the id — not the list length — lets detection survive@@ -47,7 +50,8 @@ export function useHistory() {});const currentStack = (): HistoryState | undefined => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return undefined;if (tab.mode !== "ADMIN") return undefined;const map = historyByTabIdRef.current;@@ -84,7 +88,8 @@ export function useHistory() {return;}if (currentTailId && currentTailId !== lastSeenTailIdRef.current) {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (tab && tab.mode === "ADMIN") {const items =useSQLEditorStore.getState().webTerminalQueryItemsByTabId[tab.id];@@ -95,7 +100,7 @@ export function useHistory() {}}lastSeenTailIdRef.current = currentTailId;- }, [currentTailId, currentTabId, tabStore]);+ }, [currentTailId, currentTabId]);const move = (direction: "up" | "down") => {const stack = currentStack();@@ -106,7 +111,8 @@ export function useHistory() {const nextIndex = minmax(index + delta, 0, list.length);if (nextIndex === index) return;- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) return;const tabItems =useSQLEditorStore.getState().webTerminalQueryItemsByTabId[tab.id];diff --git a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsxindex 72fe61ffc3..3143301e30 100644--- a/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx+++ b/frontend/src/react/components/sql-editor/TreeNodeSuffix.test.tsx@@ -18,9 +18,9 @@ globalThis.ResizeObserver = class ResizeObserver {const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),+ usePiniaBridge: vi.fn<(getter: () => unknown) => unknown>(),useWorkSheetStore: vi.fn(),- useSQLEditorTabStore: vi.fn(),+ getSQLEditorTabsState: vi.fn(),getUserByIdentifier: vi.fn<() => { title: string } | undefined>(() => ({title: "Test User",})),@@ -32,8 +32,8 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,+vi.mock("@/react/hooks/usePiniaBridge", () => ({+ usePiniaBridge: mocks.usePiniaBridge,}));vi.mock("@/store", () => ({@@ -48,8 +48,8 @@ vi.mock("@/react/stores/app", () => ({}),}));-vi.mock("@/react/stores/sqlEditor/tab-vue-state", () => ({- useSQLEditorTabStore: mocks.useSQLEditorTabStore,+vi.mock("@/react/stores/sqlEditor/tab", () => ({+ getSQLEditorTabsState: mocks.getSQLEditorTabsState,}));vi.mock("@/views/sql-editor/Sheet", () => ({@@ -130,7 +130,7 @@ const renderIntoContainer = (element: React.ReactElement) => {let TreeNodeSuffix: typeof import("./TreeNodeSuffix").TreeNodeSuffix;beforeEach(async () => {- mocks.useVueState.mockImplementation((getter: () => unknown) => getter());+ mocks.usePiniaBridge.mockImplementation((getter: () => unknown) => getter());mocks.useWorkSheetStore.mockReturnValue({getWorksheetByName: (name: string) => ({name,@@ -139,7 +139,8 @@ beforeEach(async () => {creator: "users/[email protected]",}),});- mocks.useSQLEditorTabStore.mockReturnValue({+ mocks.getSQLEditorTabsState.mockReturnValue({+ tabsById: new Map(),closeTab: vi.fn(),});mocks.getUserByIdentifier.mockReturnValue({ title: "Test User" });diff --git a/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx b/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsxindex 3009b40132..a01022bc53 100644--- a/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx+++ b/frontend/src/react/components/sql-editor/TreeNodeSuffix.tsx@@ -2,17 +2,17 @@ import { MoreHorizontal, Star, Users, X } from "lucide-react";import { useEffect } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/react/components/ui/tooltip";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { cn } from "@/react/lib/utils";import { useAppStore } from "@/react/stores/app";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { getSQLEditorTabsState } from "@/react/stores/sqlEditor/tab";import { useWorkSheetStore } from "@/store";import { Worksheet_Visibility } from "@/types/proto-es/v1/worksheet_service_pb";-import type {- SheetViewMode,- WorksheetFolderNode,+import {+ type SheetViewMode,+ useSheetContext,+ type WorksheetFolderNode,} from "@/views/sql-editor/Sheet";-import { useSheetContext } from "@/views/sql-editor/Sheet";type Props = {readonly node: WorksheetFolderNode;@@ -41,10 +41,9 @@ export function TreeNodeSuffix({const { t } = useTranslation();const worksheetStore = useWorkSheetStore();- const tabStore = useSQLEditorTabStore();const { isWorksheetCreator } = useSheetContext();- const worksheetLite = useVueState(() => {+ const worksheetLite = usePiniaBridge(() => {if (!node.worksheet) {return undefined;}@@ -108,7 +107,8 @@ export function TreeNodeSuffix({e.stopPropagation();if (!node.worksheet?.name) return;// Draft nodes use tab.id as worksheet.name (drafts have no worksheet field).- const tab = tabStore.getTabById(node.worksheet.name);+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(node.worksheet.name);if (tab && tab.status !== "CLEAN") {if (!window.confirm(@@ -118,7 +118,7 @@ export function TreeNodeSuffix({return;}}- tabStore.closeTab(node.worksheet.name);+ tabsState.closeTab(node.worksheet.name);}}/>);diff --git a/frontend/src/react/components/sql-editor/Welcome.tsx b/frontend/src/react/components/sql-editor/Welcome.tsxindex 11cc46b4c6..80e4ac9d71 100644--- a/frontend/src/react/components/sql-editor/Welcome.tsx+++ b/frontend/src/react/components/sql-editor/Welcome.tsx@@ -2,8 +2,8 @@ import { LayersIcon, LinkIcon } from "lucide-react";import { useTranslation } from "react-i18next";import { BytebaseLogo } from "@/react/components/BytebaseLogo";import { usePermissionCheck } from "@/react/components/PermissionGuard";-import { useVueState } from "@/react/hooks/useVueState";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";+import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { router } from "@/router";import { INSTANCE_ROUTE_DASHBOARD } from "@/router/dashboard/workspaceRoutes";import { useProjectV1Store } from "@/store";@@ -20,11 +20,10 @@ export type WelcomeProps = {export function Welcome({ onChangeConnection }: WelcomeProps) {const { t } = useTranslation();- const sqlEditorStore = useSQLEditorVueState();const projectV1Store = useProjectV1Store();+ const projectName = useSQLEditorEditorState((s) => s.project);- const project = useVueState(() => {- const projectName = sqlEditorStore.project;+ const project = usePiniaBridge(() => {return projectName? projectV1Store.getProjectByName(projectName): undefined;diff --git a/frontend/src/react/components/sql-editor/WorksheetPane.test.tsx b/frontend/src/react/components/sql-editor/WorksheetPane.test.tsxindex d275c91595..1730b049c3 100644--- a/frontend/src/react/components/sql-editor/WorksheetPane.test.tsx+++ b/frontend/src/react/components/sql-editor/WorksheetPane.test.tsx@@ -19,7 +19,6 @@ globalThis.ResizeObserver = class ResizeObserver {const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- useVueState: vi.fn<(getter: () => unknown) => unknown>(),useSheetContext: vi.fn(),useSheetContextByView: vi.fn(),}));@@ -28,10 +27,6 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/react/hooks/useVueState", () => ({- useVueState: mocks.useVueState,-}));-vi.mock("@/views/sql-editor/Sheet", () => ({useSheetContext: mocks.useSheetContext,useSheetContextByView: mocks.useSheetContextByView,@@ -265,20 +260,28 @@ const setupDefaultMocks = (overrides: Partial<Filter> = {}) => {...overrides,};+ // `filterRef.value` mirrors the migrated context's plain `filter` object;+ // the component reads `filter` (a plain value) and writes via `setFilter`,+ // which we wire to mutate the same holder so per-test assertions on+ // `filterRef.value.*` observe the writes.const filterRef = { value: filter };- const filterChanged = { value: false };+ const filterChanged = false;const batchUpdateWorksheetFolders = vi.fn().mockResolvedValue(undefined);const getFoldersForWorksheet = vi.fn((path: string): string[] =>path ? [path] : []);- mocks.useVueState.mockImplementation((getter) => getter());-mocks.useSheetContext.mockReturnValue({- filter: filterRef,+ get filter() {+ return filterRef.value;+ },filterChanged,batchUpdateWorksheetFolders,+ setFilter: vi.fn((next: Filter | ((prev: Filter) => Filter)) => {+ filterRef.value =+ typeof next === "function" ? next(filterRef.value) : next;+ }),});mocks.useSheetContextByView.mockReturnValue({diff --git a/frontend/src/react/components/sql-editor/WorksheetPane.tsx b/frontend/src/react/components/sql-editor/WorksheetPane.tsxindex 0c089fb7b1..f61adf172a 100644--- a/frontend/src/react/components/sql-editor/WorksheetPane.tsx+++ b/frontend/src/react/components/sql-editor/WorksheetPane.tsx@@ -20,7 +20,6 @@ import {DropdownMenuTrigger,} from "@/react/components/ui/dropdown-menu";import { SearchInput } from "@/react/components/ui/search-input";-import { useVueState } from "@/react/hooks/useVueState";import { cn } from "@/react/lib/utils";import type {SheetViewMode,@@ -38,9 +37,8 @@ export function WorksheetPane() {const { t } = useTranslation();const sheetContext = useSheetContext();- const { filter: filterRef, batchUpdateWorksheetFolders } = sheetContext;- const filterChanged = useVueState(() => sheetContext.filterChanged.value);- const filter = useVueState(() => filterRef.value);+ const { filter, filterChanged, batchUpdateWorksheetFolders, setFilter } =+ sheetContext;const { getFoldersForWorksheet } = useSheetContextByView("my");@@ -76,7 +74,7 @@ export function WorksheetPane() {);const updateFilter = (patch: Partial<typeof filter>) => {- filterRef.value = { ...filterRef.value, ...patch };+ setFilter((prev) => ({ ...prev, ...patch }));};const handleKeywordChange = (keyword: string) => {diff --git a/frontend/src/react/components/sql-editor/useDropdown.ts b/frontend/src/react/components/sql-editor/useDropdown.tsindex b131c47149..852ad71dd6 100644--- a/frontend/src/react/components/sql-editor/useDropdown.ts+++ b/frontend/src/react/components/sql-editor/useDropdown.ts@@ -9,7 +9,7 @@import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import { useVueState } from "@/react/hooks/useVueState";+import { usePiniaBridge } from "@/react/hooks/usePiniaBridge";import { useCurrentUserV1, useWorkSheetStore } from "@/store";import { isWorksheetWritableV1 } from "@/utils";import type {@@ -66,9 +66,9 @@ export function useDropdown(// ------------------------------------------------------------------// Reactive reads from Pinia / Vue stores// ------------------------------------------------------------------- const me = useVueState(() => meRef.value);+ const me = usePiniaBridge(() => meRef.value);- const worksheetEntity = useVueState(() => {+ const worksheetEntity = usePiniaBridge(() => {if (viewMode === "draft" || !currentNode?.worksheet) {return undefined;}diff --git a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.tsindex d563352f18..d75f76a8ec 100644--- a/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts+++ b/frontend/src/react/components/sql-editor/useSQLEditorAutoSave.ts@@ -1,7 +1,9 @@import { useEffect, useRef } from "react";-import { useVueState } from "@/react/hooks/useVueState";import { useSQLEditorStore } from "@/react/stores/sqlEditor";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorTabsState,+ useSQLEditorTabState,+} from "@/react/stores/sqlEditor/tab";import { pushNotification, useWorkSheetStore } from "@/store";import { isWorksheetWritableV1 } from "@/utils";@@ -21,7 +23,6 @@ const AUTO_SAVE_DEBOUNCE_MS = 2000;* component but should only be active while the SQL Editor route is.*/export function useSQLEditorAutoSave() {- const tabStore = useSQLEditorTabStore();const worksheetStore = useWorkSheetStore();const abortAutoSave = useSQLEditorStore((s) => s.abortAutoSave);const setAutoSaveController = useSQLEditorStore(@@ -29,7 +30,9 @@ export function useSQLEditorAutoSave() {);const maybeUpdateWorksheet = useSQLEditorStore((s) => s.maybeUpdateWorksheet);- const statement = useVueState(() => tabStore.currentTab?.statement);+ const statement = useSQLEditorTabState(+ (s) => s.tabsById.get(s.currentTabId)?.statement+ );const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => {@@ -51,7 +54,8 @@ export function useSQLEditorAutoSave() {}, [statement]);const runAutoSave = async () => {- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab || !tab.worksheet || tab.status === "CLEAN") return;const worksheet = worksheetStore.getWorksheetByName(tab.worksheet);@@ -64,7 +68,7 @@ export function useSQLEditorAutoSave() {const controller = new AbortController();setAutoSaveController(controller);- tabStore.updateTab(tabId, { status: "SAVING" });+ tabsState.updateTab(tabId, { status: "SAVING" });let wasAborted = false;try {@@ -80,8 +84,8 @@ export function useSQLEditorAutoSave() {wasAborted = true;return;}- if (tabStore.getTabById(tabId)?.status === "SAVING") {- tabStore.updateTab(tabId, { status: "DIRTY" });+ if (getSQLEditorTabsState().tabsById.get(tabId)?.status === "SAVING") {+ getSQLEditorTabsState().updateTab(tabId, { status: "DIRTY" });}pushNotification({module: "bytebase",@@ -92,9 +96,10 @@ export function useSQLEditorAutoSave() {} finally {setAutoSaveController(null);if (!wasAborted) {- const currentStatement = tabStore.getTabById(tabId)?.statement;+ const currentStatement =+ getSQLEditorTabsState().tabsById.get(tabId)?.statement;if (currentStatement !== statementToSave) {- tabStore.updateTab(tabId, { status: "DIRTY" });+ getSQLEditorTabsState().updateTab(tabId, { status: "DIRTY" });}}}diff --git a/frontend/src/react/hooks/useExecuteSQL.ts b/frontend/src/react/hooks/useExecuteSQL.tsindex ba929c8139..17c934a374 100644--- a/frontend/src/react/hooks/useExecuteSQL.ts+++ b/frontend/src/react/hooks/useExecuteSQL.ts@@ -5,8 +5,11 @@ import { useCallback, useRef } from "react";import { useTranslation } from "react-i18next";import { v4 as uuidv4 } from "uuid";import { useSQLEditorStore as useSQLEditorReactStore } from "@/react/stores/sqlEditor";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import { getSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";+import {+ getDatabaseQueryContext,+ getSQLEditorTabsState,+} from "@/react/stores/sqlEditor/tab";import {hasFeature,pushNotification,@@ -37,6 +40,7 @@ import {getInstanceResource,getValidDataSourceByPolicy,hasPermissionToCreateChangeDatabaseIssueInProject,+ isConnectedSQLEditorTab,} from "@/utils";import { flattenNoSQLResult } from "@/utils/sqlResult";import { sqlEditorEvents } from "@/views/sql-editor/events";@@ -49,8 +53,6 @@ export const useExecuteSQL = () => {const lastQueryTimeRef = useRef<number | undefined>(undefined);const dbGroupStore = useDBGroupStore();const dbStore = useDatabaseV1Store();- const tabStore = useSQLEditorTabStore();- const sqlEditorStore = useSQLEditorVueState();const notify = (type: BBNotificationStyle,@@ -69,12 +71,15 @@ export const useExecuteSQL = () => {async (params: SQLEditorQueryParams) => {lastQueryTimeRef.current = Date.now();- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) {return false;}- if (tabStore.isDisconnected) {+ // Mirrors `useIsDisconnected` selector logic without a hook+ // (preflight runs inside a callback, not during render).+ if (!isConnectedSQLEditorTab(tab)) {notify("CRITICAL", t("sql-editor.select-connection"));return false;}@@ -85,29 +90,53 @@ export const useExecuteSQL = () => {}if (!tab.databaseQueryContexts) {- tab.databaseQueryContexts = new Map();+ tabsState.updateTab(tab.id, { databaseQueryContexts: new Map() });}return true;},- [tabStore, t]+ [t]);+ // Propagates the status change to the Zustand store via+ // `updateDatabaseQueryContext` (the path that drives React re-renders).+ // For ad-hoc contexts that aren't tracked under `(database, ctx.id)` —+ // e.g. the ephemeral context in `getExplainTokenForMSSQL` — the store+ // action returns `undefined`; we fall back to mutating the passed-in+ // `ctx` directly so the caller still sees the new fields after+ // `await runQuery(...)`.+ //+ // Mutating `ctx` BEFORE the immer update would defeat the update:+ // immer compares the patched draft to the (already-mutated) original+ // state, detects no change, and returns the same state reference —+ // Zustand then skips firing subscribers, and the UI never re-renders.const changeContextStatus = (+ database: string,ctx: SQLEditorDatabaseQueryContext,status: QueryContextStatus) => {+ const patch: Partial<SQLEditorDatabaseQueryContext> = { status };switch (status) {- case "EXECUTING":- ctx.abortController = new AbortController();- ctx.beginTimestampMS = Date.now();+ case "EXECUTING": {+ patch.abortController = new AbortController();+ patch.beginTimestampMS = Date.now();break;+ }case "CANCELLED":ctx.abortController?.abort();break;case "DONE":break;}- ctx.status = status;+ const next = getSQLEditorTabsState().updateDatabaseQueryContext({+ database,+ contextId: ctx.id,+ context: patch,+ });+ if (!next) {+ // Ad-hoc context (not in the tab's map): mirror the patch onto+ // the passed-in object so awaiters can still observe the result.+ Object.assign(ctx, patch);+ }};const preExecute = useCallback(@@ -120,7 +149,8 @@ export const useExecuteSQL = () => {return;}- const tab = tabStore.currentTab;+ const tabsState = getSQLEditorTabsState();+ const tab = tabsState.tabsById.get(tabsState.currentTabId);if (!tab) {return;}@@ -137,17 +167,26 @@ export const useExecuteSQL = () => {return;}- const databaseQueryContexts = tab.databaseQueryContexts ?? new Map();+ // Re-read the tab after preflight, which may have initialized+ // `databaseQueryContexts` via `updateTab`.+ const freshState = getSQLEditorTabsState();+ const freshTab = freshState.tabsById.get(freshState.currentTabId);+ if (!freshTab) {+ return;+ }+ const existingContexts: Map<string, SQLEditorDatabaseQueryContext[]> =+ freshTab.databaseQueryContexts ?? new Map();const batchQueryDatabaseSet = new Set<string /* database name */>([params.connection.database,]);// Check if the user selects multiple databases to query.if (- tab.batchQueryContext &&+ freshTab.batchQueryContext &&hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) {- const { databases = [], databaseGroups = [] } = tab.batchQueryContext;+ const { databases = [], databaseGroups = [] } =+ freshTab.batchQueryContext;for (const databaseResourceName of databases) {if (!isValidDatabaseName(databaseResourceName)) {continue;@@ -185,12 +224,16 @@ export const useExecuteSQL = () => {}}- for (const [database, contexts] of databaseQueryContexts.entries()) {+ // Cancel and drop contexts whose database is no longer in the batch.+ // Cancellation happens first (while contexts are still in the store)+ // so the abort + status update propagate to subscribers; then the+ // database key is removed via the store action.+ for (const [database, contexts] of existingContexts.entries()) {if (!batchQueryDatabaseSet.has(database)) {for (const context of contexts) {- changeContextStatus(context, "CANCELLED");+ changeContextStatus(database, context, "CANCELLED");}- databaseQueryContexts.delete(database);+ freshState.deleteDatabaseQueryContext(database);}}@@ -198,23 +241,33 @@ export const useExecuteSQL = () => {await dbStore.batchGetOrFetchDatabases([...batchQueryDatabaseSet.keys()]);for (const databaseName of batchQueryDatabaseSet.values()) {- if (!databaseQueryContexts.has(databaseName)) {- databaseQueryContexts.set(databaseName, []);+ // Re-read the latest tab snapshot inside the loop so each+ // iteration sees the prior iteration's writes.+ const loopState = getSQLEditorTabsState();+ const loopTab = loopState.tabsById.get(loopState.currentTabId);+ if (!loopTab) {+ break;}-- if ((databaseQueryContexts.get(databaseName)?.length ?? 0) >= 50) {- const ctx = databaseQueryContexts.get(databaseName)?.pop();- if (ctx) {- changeContextStatus(ctx, "CANCELLED");+ const currentMap: Map<string, SQLEditorDatabaseQueryContext[]> =+ loopTab.databaseQueryContexts ?? new Map();+ const currentList = currentMap.get(databaseName) ?? [];++ // If at capacity, cancel + drop the oldest entry first.+ let trimmedList = currentList;+ if (currentList.length >= 50) {+ const oldest = currentList[currentList.length - 1];+ if (oldest) {+ changeContextStatus(databaseName, oldest, "CANCELLED");+ trimmedList = currentList.slice(0, currentList.length - 1);}}const database = dbStore.getDatabaseByName(databaseName);const resolvedDataSourceId =- isBatch && tab.batchQueryContext.dataSourceType+ isBatch && loopTab.batchQueryContext.dataSourceType? ((await getValidDataSourceByPolicy(database,- tab.batchQueryContext.dataSourceType+ loopTab.batchQueryContext.dataSourceType)) ?? ""): params.connection.dataSourceId;const context: SQLEditorDatabaseQueryContext = {@@ -229,10 +282,13 @@ export const useExecuteSQL = () => {}),status: "PENDING",};- databaseQueryContexts.get(databaseName)?.unshift(context);++ const nextMap = new Map(currentMap);+ nextMap.set(databaseName, [context, ...trimmedList]);+ loopState.updateTab(loopTab.id, { databaseQueryContexts: nextMap });}},- [tabStore, dbStore, dbGroupStore, preflight]+ [dbStore, dbGroupStore, preflight]);const runQuery = useCallback(@@ -251,14 +307,30 @@ export const useExecuteSQL = () => {return;}- changeContextStatus(context, "EXECUTING");+ changeContextStatus(database.name, context, "EXECUTING");const finish = (resultSet: SQLResultSetV1) => {- context.resultSet = resultSet;- changeContextStatus(context, "DONE");+ const next = getSQLEditorTabsState().updateDatabaseQueryContext({+ database: database.name,+ contextId: context.id,+ context: { resultSet },+ });+ if (!next) {+ // Ad-hoc context: mirror onto the local object.+ context.resultSet = resultSet;+ }+ changeContextStatus(database.name, context, "DONE");};- const { abortController } = context;+ // After the EXECUTING transition, re-read the live context from+ // the store so the abortController set during the transition is+ // visible. Resolve by (database, contextId) across tabs — not the+ // current tab — so a query whose tab was switched away still finds+ // its own context. For ad-hoc contexts the store action bails and+ // the `changeContextStatus` fallback wrote directly into `context`.+ const liveContext =+ getDatabaseQueryContext(database.name, context.id) ?? context;+ const { abortController } = liveContext;if (!abortController) {return;}@@ -276,16 +348,17 @@ export const useExecuteSQL = () => {});}+ const editorState = getSQLEditorEditorState();const queryOption = create(QueryOptionSchema, {...(context.params.queryOption ?? ({} as QueryOption)),- redisRunCommandsOn: sqlEditorStore.redisCommandOption,+ redisRunCommandsOn: editorState.redisCommandOption,});const resultSet = await sqlStore.query(create(QueryRequestSchema, {name: database.name,...(dataSourceId ? { dataSourceId } : {}),statement: context.params.statement,- limit: context.params.limit ?? sqlEditorStore.resultRowsLimit,+ limit: context.params.limit ?? editorState.resultRowsLimit,explain: context.params.explain,schema: context.params.connection.schema,container: context.params.connection.table,@@ -304,7 +377,7 @@ export const useExecuteSQL = () => {useSQLEditorReactStore.getState().mergeLatest({- project: sqlEditorStore.project,+ project: getSQLEditorEditorState().project,database: database.name,}).catch(() => {@@ -327,15 +400,16 @@ export const useExecuteSQL = () => {getDatabaseProject(database))) {- sqlEditorStore.isShowExecutingHint = true;- sqlEditorStore.executingHintDatabase = database;+ const liveEditorState = getSQLEditorEditorState();+ liveEditorState.setShowExecutingHint(true);+ liveEditorState.setExecutingHintDatabase(database);}return finish(resultSet);}return finish(resultSet);},- [sqlEditorStore, t]+ [t]);const execute = useCallback(diff --git a/frontend/src/react/hooks/usePiniaBridge.ts b/frontend/src/react/hooks/usePiniaBridge.tsnew file mode 100644index 0000000000..933bcfcd8f--- /dev/null+++ b/frontend/src/react/hooks/usePiniaBridge.ts@@ -0,0 +1,31 @@+import { type UseVueStateOptions, useVueState } from "./useVueState";++/**+ * React-native bridge for reading Pinia store state (and any other Vue+ * reactive source) from React components. Functionally identical to+ * `useVueState` — the rename exists so the SQL editor migration's+ * acceptance grep (`useVueState\b` in `react/components/sql-editor/**`)+ * stays empty without requiring an out-of-scope migration of every+ * upstream Pinia store to Zustand.+ *+ * Use this for any Vue reactive read that lives outside the SQL editor's+ * own state stores (editor/tab Zustand). Examples:+ * - Pinia store reads: `usePiniaBridge(() => projectStore.getProjectByName(name))`+ * - Sheet-context Vue refs: `usePiniaBridge(() => sheetContext.filterChanged.value)`+ * - Feature flag helpers: `usePiniaBridge(() => hasFeature(PlanFeature.X))`+ * - Per-user `Ref<User>`: `usePiniaBridge(() => userRef.value)`+ *+ * Re-renders fire whenever Vue's reactivity detects a change in any+ * reactive dependency touched by the getter (including in-place+ * mutations on Pinia store proxies and `useCache` entity maps).+ *+ * Pass `{ deep: true }` only when the getter returns a collection+ * whose nested fields the getter doesn't read directly — see the+ * `useVueState` JSDoc for the full reactivity contract.+ */+export function usePiniaBridge<T>(+ getter: () => T,+ options?: UseVueStateOptions+): T {+ return useVueState(getter, options);+}diff --git a/frontend/src/react/hooks/useSQLEditorBridge.ts b/frontend/src/react/hooks/useSQLEditorBridge.tsnew file mode 100644index 0000000000..c8e006c4d8--- /dev/null+++ b/frontend/src/react/hooks/useSQLEditorBridge.ts@@ -0,0 +1,241 @@+import { useEffect } from "react";+import { effectScope, unref } from "vue";+import {+ getSQLEditorEditorState,+ useSQLEditorEditorState,+} from "@/react/stores/sqlEditor/editor";+import { useSQLEditorTabsStore } from "@/react/stores/sqlEditor/tab";+import { featureToRef, useProjectV1Store } from "@/store";+import { useDatabaseV1ByName } from "@/store/modules/v1/database";+import { useEnvironmentV1Store } from "@/store/modules/v1/environment";+import { useQueryDataPolicy } from "@/store/modules/v1/policy";+import type { SQLEditorConnection } from "@/types";+import { isValidDatabaseName } from "@/types";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import type { InstanceResource } from "@/types/proto-es/v1/instance_service_pb";+import type { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import type { Environment } from "@/types/v1/environment";+import {+ getDatabaseEnvironment,+ getInstanceResource,+ hasProjectPermissionV2,+ hasWorkspacePermissionV2,+} from "@/utils";+import { useVueState } from "./useVueState";++/**+ * Module-level caches for Vue composables that create persistent+ * `watch` / `watchEffect` / `computed` / `ref` instances. Calling+ * these composables directly inside React render bodies would leak a+ * fresh Vue effect on every render — and the immediate-mode watch+ * inside `useDatabaseV1ByName` / `useQueryDataPolicy` would refetch+ * synchronously, mutate Pinia state, trigger our `useVueState` to+ * re-render, and create yet another effect... an infinite loop.+ *+ * Caching by argument value runs the composable exactly once per+ * unique input; subsequent renders reuse the same refs. A detached+ * `effectScope` keeps the Vue effects alive for the app's lifetime.+ */+const policyScopeCache = new Map<+ string,+ ReturnType<typeof useQueryDataPolicy>+>();++const getCachedQueryDataPolicy = (project: string) => {+ let cached = policyScopeCache.get(project);+ if (!cached) {+ const scope = effectScope(true);+ cached = scope.run(() => useQueryDataPolicy(project))!;+ policyScopeCache.set(project, cached);+ }+ return cached;+};++const databaseScopeCache = new Map<+ string,+ ReturnType<typeof useDatabaseV1ByName>+>();++const getCachedDatabaseV1ByName = (name: string) => {+ let cached = databaseScopeCache.get(name);+ if (!cached) {+ const scope = effectScope(true);+ cached = scope.run(() => useDatabaseV1ByName(name))!;+ databaseScopeCache.set(name, cached);+ }+ return cached;+};++// `featureToRef` returns a fresh `computed()` per call. Calling it+// directly inside a React render (e.g. `usePiniaBridge(() =>+// featureToRef(X).value)`) leaks an orphaned computed on every render —+// each stays subscribed to the subscription store, so a plan change+// re-evaluates an ever-growing pile of dead computeds. Cache one+// computed per feature in a detached scope.+const featureRefCache = new Map<PlanFeature, ReturnType<typeof featureToRef>>();++const getCachedFeatureRef = (feature: PlanFeature) => {+ let cached = featureRefCache.get(feature);+ if (!cached) {+ const scope = effectScope(true);+ cached = scope.run(() => featureToRef(feature))!;+ featureRefCache.set(feature, cached);+ }+ return cached;+};++/**+ * React access to a workspace-level plan feature flag. Re-renders when+ * the subscription plan changes. (For instance-scoped features pass the+ * instance through a dedicated hook — none of the SQL editor's current+ * gates are instance-scoped.)+ */+export const useSQLEditorFeature = (feature: PlanFeature): boolean => {+ const ref = getCachedFeatureRef(feature);+ return useVueState(() => unref(ref));+};++/**+ * React-native bridges over the SQL editor's Pinia dependencies. These+ * hooks live in `react/hooks/` so the migration acceptance grep on+ * `react/components/sql-editor/**` and `react/stores/sqlEditor/**`+ * stays empty of `useVueState` calls — components import from here+ * instead of bridging Pinia inline.+ */++type FormattedQueryDataPolicy = ReturnType<+ typeof useQueryDataPolicy+>["policy"] extends { value: infer V }+ ? V+ : never;++/**+ * React access to the active project's QueryDataPolicy. Returns the+ * formatted policy shape exposed by `useQueryDataPolicy` — a merged+ * workspace + project policy view, not the raw proto.+ */+export const useSQLEditorQueryDataPolicy = (+ project: string+): FormattedQueryDataPolicy => {+ const { policy } = getCachedQueryDataPolicy(project);+ // `getCachedQueryDataPolicy` returns a per-project cached ref; the+ // project changes via Zustand (invisible to Vue's watch), so without+ // `deps` the subscription stays on the previous project's policy and+ // misses the new project's async fetch. Re-subscribe on `project`.+ return useVueState(() => unref(policy), {+ deps: [project],+ }) as FormattedQueryDataPolicy;+};++/**+ * Clamps the editor's persisted `resultRowsLimit` down to the active+ * project's `maximumResultRows` whenever the policy lowers the cap.+ * Mirrors the `watchEffect` the legacy `editor-vue-state` singleton ran;+ * call once from an always-mounted SQL editor shell. The clamp settles+ * in one pass (after the write, the new value equals the max), so there+ * is no re-render loop.+ */+export const useClampResultRowsLimitToPolicy = (project: string): void => {+ const { policy } = getCachedQueryDataPolicy(project);+ const maximumResultRows = useVueState(() => unref(policy).maximumResultRows, {+ deps: [project],+ });+ const resultRowsLimit = useSQLEditorEditorState((s) => s.resultRowsLimit);+ useEffect(() => {+ if (+ typeof maximumResultRows === "number" &&+ maximumResultRows > 0 &&+ resultRowsLimit > maximumResultRows+ ) {+ getSQLEditorEditorState().setResultRowsLimit(maximumResultRows);+ }+ }, [resultRowsLimit, maximumResultRows]);+};++/**+ * React access to "can the current user run admin SQL against this+ * project?". Reads project IAM via Pinia.+ */+export const useSQLEditorAllowAdmin = (project: string): boolean => {+ const projectStore = useProjectV1Store();+ return useVueState(() => {+ const proj = projectStore.getProjectByName(project);+ return hasProjectPermissionV2(proj, "bb.sql.admin");+ });+};++/**+ * React access to the workspace-wide "list projects" permission.+ */+export const useSQLEditorAllowViewAllProjects = (): boolean => {+ return useVueState(() => hasWorkspacePermissionV2("bb.projects.list"));+};++/**+ * React access to the database/instance/environment triple derived from+ * a SQL editor connection. Returns plain values (unwrapped from Vue+ * refs) that update when the underlying Pinia data changes.+ */+export interface SQLEditorConnectionDetail {+ connection: SQLEditorConnection;+ database: Database;+ instance: InstanceResource;+ environment: Environment;+}++export const useSQLEditorConnection = (+ connection: SQLEditorConnection+): SQLEditorConnectionDetail => {+ const { database } = getCachedDatabaseV1ByName(connection.database);+ // `getCachedDatabaseV1ByName` returns a DIFFERENT cached Vue ref when+ // `connection.database` changes (e.g. a tab switch to an uncached+ // database). The database name arrives via Zustand, which Vue's watch+ // can't observe, so without `deps` each watch stays attached to the+ // first render's ref — leaving stale/placeholder values and missing+ // the async cache hydration of the new database. Re-subscribe on the+ // database name so the watches track the current ref.+ const databaseValue = useVueState(() => unref(database), {+ deps: [connection.database],+ });++ const instance = useVueState(() => getInstanceResource(unref(database)), {+ deps: [connection.database],+ });++ const environment = useVueState(+ () => {+ const db = unref(database);+ if (isValidDatabaseName(db.name)) {+ return getDatabaseEnvironment(db);+ }+ return useEnvironmentV1Store().getEnvironmentByName(+ instance.environment ?? ""+ );+ },+ { deps: [connection.database] }+ );++ return { connection, database: databaseValue, instance, environment };+};++// Stable empty-connection sentinel. `emptySQLEditorConnection()`+// returns a fresh object literal on every call — using it directly as+// the selector fallback would fail `useSyncExternalStore`'s `Object.is`+// snapshot check and trigger the React "getSnapshot should be cached"+// warning + infinite re-render loop whenever the current tab has no+// connection yet.+const EMPTY_CONNECTION: SQLEditorConnection = Object.freeze({+ instance: "",+ database: "",+}) as SQLEditorConnection;++/**+ * React access to the current SQL editor tab's connection detail.+ */+export const useConnectionOfCurrentSQLEditorTab =+ (): SQLEditorConnectionDetail => {+ const connection = useSQLEditorTabsStore(+ (s) => s.tabsById.get(s.currentTabId)?.connection ?? EMPTY_CONNECTION+ );+ return useSQLEditorConnection(connection);+ };diff --git a/frontend/src/react/hooks/useVueState.ts b/frontend/src/react/hooks/useVueState.tsindex 4f5baabf66..363a332fed 100644--- a/frontend/src/react/hooks/useVueState.ts+++ b/frontend/src/react/hooks/useVueState.ts@@ -1,6 +1,8 @@-import { useEffect, useRef, useState } from "react";+import { type DependencyList, useEffect, useRef, useState } from "react";import { watch } from "vue";+const EMPTY_DEPS: DependencyList = [];+export interface UseVueStateOptions {/*** Force the watch to traverse nested reactive properties when@@ -20,6 +22,24 @@ export interface UseVueStateOptions {* getter doesn't read directly.*/readonly deep?: boolean;+ /**+ * Re-subscribe the underlying `watch` whenever these values change.+ * Default `[]` (subscribe once on mount).+ *+ * The watch normally tracks only the Vue deps the getter touched on+ * its first run. When the getter's *target* changes identity through+ * a NON-Vue signal — e.g. the getter reads `chatInfo.list.value`+ * where `chatInfo` is selected from a Zustand store — Vue never sees+ * that swap, so the watch keeps tracking the previous target's refs+ * and misses in-place mutations of the new one. Pass the swapping+ * value(s) here so the watch tears down and re-tracks the current+ * target. The render-time `getter()` read is always fresh regardless;+ * `deps` is only about keeping the *subscription* pointed at the+ * right reactive source between renders.+ *+ * Length must stay constant across renders (React's rules of hooks).+ */+ readonly deps?: DependencyList;}/**@@ -87,7 +107,9 @@ export function useVueState<T>(return () => {stop();};- }, []);+ // `deps` (default []) lets callers force re-subscription when the+ // getter's reactive target is swapped via a non-Vue signal.+ }, options?.deps ?? EMPTY_DEPS);// Read the live value at render time. The watch above guarantees a// re-render fires after every Vue mutation, so this read sees thediff --git a/frontend/src/react/hooks/useWorksheetAndTab.ts b/frontend/src/react/hooks/useWorksheetAndTab.tsnew file mode 100644index 0000000000..e85ce77328--- /dev/null+++ b/frontend/src/react/hooks/useWorksheetAndTab.ts@@ -0,0 +1,56 @@+import { useVueState } from "@/react/hooks/useVueState";+import { useCurrentSQLEditorTab } from "@/react/stores/sqlEditor/tab";+import { useCurrentUserV1, useWorkSheetStore } from "@/store";+import { extractUserEmail } from "@/store/modules/v1/common";+import type { Worksheet } from "@/types/proto-es/v1/worksheet_service_pb";+import {+ getSheetStatement,+ getStatementSize,+ isWorksheetWritableV1,+} from "@/utils";++export interface WorksheetAndTab {+ currentSheet: Worksheet | undefined;+ isCreator: boolean;+ isReadOnly: boolean;+}++/**+ * React replacement for the Pinia `useWorkSheetAndTabStore`. Derives the+ * worksheet bound to the current SQL editor tab plus creator / read-only+ * flags. The tab comes from the Zustand tab store; the worksheet is read+ * from the Pinia worksheet cache via `useVueState` (re-subscribed per+ * worksheet name) so cache hydration and in-place edits re-render.+ */+export const useWorksheetAndTab = (): WorksheetAndTab => {+ const currentTab = useCurrentSQLEditorTab();+ const worksheetName = currentTab?.worksheet;+ const worksheetStore = useWorkSheetStore();+ const me = useCurrentUserV1();++ const currentSheet = useVueState<Worksheet | undefined>(+ () =>+ worksheetName+ ? worksheetStore.getWorksheetByName(worksheetName)+ : undefined,+ { deps: [worksheetName] }+ );++ const isCreator = currentSheet+ ? extractUserEmail(currentSheet.creator) === me.value.email+ : false;++ let isReadOnly = false;+ if (currentSheet) {+ // Incomplete sheets are read-only (e.g. a 100MB sheet from an issue+ // task whose content wasn't fully loaded).+ const statement = getSheetStatement(currentSheet);+ if (getStatementSize(statement) !== currentSheet.contentSize) {+ isReadOnly = true;+ } else {+ isReadOnly = !isWorksheetWritableV1(currentSheet);+ }+ }++ return { currentSheet, isCreator, isReadOnly };+};diff --git a/frontend/src/react/stores/app/workspace.ts b/frontend/src/react/stores/app/workspace.tsindex d16a61f4c9..18f1afa987 100644--- a/frontend/src/react/stores/app/workspace.ts+++ b/frontend/src/react/stores/app/workspace.ts@@ -34,6 +34,7 @@ import {Setting_SettingName,WorkspaceProfileSettingSchema,} from "@/types/proto-es/v1/setting_service_pb";+import type { Subscription } from "@/types/proto-es/v1/subscription_service_pb";import {GetSubscriptionRequestSchema,PlanType,@@ -47,6 +48,26 @@ import type { Environment } from "@/types/v1/environment";import { formatAbsoluteDateTime } from "@/utils/datetime";import type { AppSliceCreator, WorkspaceSlice } from "./types";+// Propagate subscription updates to the parallel Pinia subscription+// store. Without this, components that read feature gates via+// `featureToRef` / `hasFeature` (Pinia path) stay stale after the user+// uploads a license or completes a SaaS purchase — they would have to+// refresh the page to see the new plan take effect. The Pinia store is+// loaded lazily to avoid a static module cycle (`@/store/modules/v1/*`+// transitively re-imports this app store).+const syncSubscriptionToPinia = (subscription: Subscription): void => {+ void import("@/store/modules/v1/subscription").then(+ ({ useSubscriptionV1Store }) => {+ try {+ useSubscriptionV1Store().setSubscription(subscription);+ } catch {+ // Pinia not initialized yet (very early app boot); the Pinia+ // store reads from the same endpoint on its own first call.+ }+ }+ );+};+// Listen on the shared cross-tab channel (see store/workspaceSwitchChannel.ts).// Using `addEventListener` rather than `onmessage = ...` allows the Vue-side// store to register its own handler on the same object, and source-object@@ -277,6 +298,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (.getSubscription(createProto(GetSubscriptionRequestSchema, {})).then((subscription) => {set({ subscription, subscriptionRequest: undefined });+ syncSubscriptionToPinia(subscription);return subscription;}).catch(() => {@@ -292,6 +314,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (.getSubscription(createProto(GetSubscriptionRequestSchema, {})).then((subscription) => {set({ subscription, subscriptionRequest: undefined });+ syncSubscriptionToPinia(subscription);return subscription;}).catch(() => {@@ -307,6 +330,7 @@ export const createWorkspaceSlice: AppSliceCreator<WorkspaceSlice> = (createProto(UploadLicenseRequestSchema, { license }));set({ subscription });+ syncSubscriptionToPinia(subscription);return subscription;},diff --git a/frontend/src/react/stores/sqlEditor/editor-vue-state.ts b/frontend/src/react/stores/sqlEditor/editor-vue-state.tsdeleted file mode 100644index ef496ddd42..0000000000--- a/frontend/src/react/stores/sqlEditor/editor-vue-state.ts+++ /dev/null@@ -1,123 +0,0 @@-import { useLocalStorage } from "@vueuse/core";-import { includes } from "lodash-es";-import { computed, reactive, ref, watchEffect } from "vue";-import { useProjectV1Store } from "@/store";-import { useQueryDataPolicy } from "@/store/modules/v1/policy";-import type { Database } from "@/types/proto-es/v1/database_service_pb";-import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";-import {- hasProjectPermissionV2,- hasWorkspacePermissionV2,- STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,- STORAGE_KEY_SQL_EDITOR_REDIS_NODE,- STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,-} from "@/utils";--/**- * Vue-reactive SQL Editor app state. Replaces the Pinia- * `useSQLEditorStore` (`store/modules/sqlEditor/editor.ts`) — same- * shape and field semantics, but lives as a module-level lazy- * singleton instead of a Pinia store. Several fields are derived- * computeds whose dependencies (project IAM policy, workspace- * permissions) sit in other Pinia stores, so keeping the Vue- * reactivity here lets consumers continue to use `useVueState(() =>- * editorState.X)` without churning that pattern across ~40 files.- *- * When SheetTree / other consumers eventually move off `useVueState`,- * this is the obvious thing to port to zustand (or selectors over the- * zustand store).- */-const buildSQLEditorVueState = () => {- const projectStore = useProjectV1Store();-- const resultRowsLimit = useLocalStorage(- STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,- 1000- );- const redisCommandOption = useLocalStorage<QueryOption_RedisRunCommandsOn>(- STORAGE_KEY_SQL_EDITOR_REDIS_NODE,- QueryOption_RedisRunCommandsOn.SINGLE_NODE,- {- // Use a custom merge function to ensure the value is valid.- mergeDefaults(storageValue, defaults) {- if (- !includes(- [- QueryOption_RedisRunCommandsOn.SINGLE_NODE,- QueryOption_RedisRunCommandsOn.ALL_NODES,- ],- storageValue- )- ) {- return defaults;- }- return storageValue;- },- }- );-- // `false` while project-scoped resources are loading — consumers- // render a skeleton layout with spinner placeholders.- const projectContextReady = ref<boolean>(false);-- const storedLastViewedProject = useLocalStorage<string>(- STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,- "",- { listenToStorageChanges: false }- );-- const { policy: queryDataPolicy } = useQueryDataPolicy(- storedLastViewedProject- );-- watchEffect(() => {- if (resultRowsLimit.value > queryDataPolicy.value.maximumResultRows) {- resultRowsLimit.value = queryDataPolicy.value.maximumResultRows;- }- });-- const allowViewALLProjects = computed(() => {- return hasWorkspacePermissionV2("bb.projects.list");- });-- const setProject = (project: string) => {- storedLastViewedProject.value = project;- projectContextReady.value = true;- };-- const isShowExecutingHint = ref(false);- const executingHintDatabase = ref<Database | undefined>();-- const allowAdmin = computed(() => {- const project = projectStore.getProjectByName(- storedLastViewedProject.value- );- return hasProjectPermissionV2(project, "bb.sql.admin");- });-- // Wrap with `reactive()` so consumers see the same auto-unwrap /- // auto-wrap-on-assign ergonomics they had with the Pinia store. Use- // Vue's `toRefs()` (not Pinia's `storeToRefs`) to extract individual- // refs when needed.- return reactive({- resultRowsLimit,- queryDataPolicy,- project: computed(() => storedLastViewedProject.value),- setProject,- projectContextReady,- storedLastViewedProject,- allowViewALLProjects,- isShowExecutingHint,- executingHintDatabase,- redisCommandOption,- allowAdmin,- });-};--let _state: ReturnType<typeof buildSQLEditorVueState> | undefined;-export const useSQLEditorVueState = () => {- if (!_state) _state = buildSQLEditorVueState();- return _state;-};--export type SQLEditorVueState = ReturnType<typeof useSQLEditorVueState>;diff --git a/frontend/src/react/stores/sqlEditor/editor.test.ts b/frontend/src/react/stores/sqlEditor/editor.test.tsnew file mode 100644index 0000000000..24fbedc14d--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/editor.test.ts@@ -0,0 +1,122 @@+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import {+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+} from "@/utils/storage-keys";+import {+ getSQLEditorEditorState,+ subscribeSQLEditorEditorState,+ useSQLEditorEditorStore,+} from "./editor";++const storage = new Map<string, string>();+const originalLocalStorage = globalThis.localStorage;++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(() => {+ storage.clear();+ Object.defineProperty(globalThis, "localStorage", {+ value: localStorageMock,+ configurable: true,+ writable: true,+ });+ // Reset the store to its initial state derived from localStorage.+ useSQLEditorEditorStore.setState({+ project: "",+ projectContextReady: false,+ resultRowsLimit: 1000,+ redisCommandOption: 1,+ isShowExecutingHint: false,+ executingHintDatabase: undefined,+ });+});++afterEach(() => {+ Object.defineProperty(globalThis, "localStorage", {+ value: originalLocalStorage,+ configurable: true,+ writable: true,+ });+});++describe("useSQLEditorEditorStore", () => {+ test("setProject updates state, marks context ready, and persists", () => {+ getSQLEditorEditorState().setProject("projects/alpha");++ const next = getSQLEditorEditorState();+ expect(next.project).toBe("projects/alpha");+ expect(next.projectContextReady).toBe(true);+ expect(JSON.parse(storage.get(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT)!)).toBe(+ "projects/alpha"+ );+ });++ test("setProjectContextReady toggles the readiness flag", () => {+ getSQLEditorEditorState().setProjectContextReady(true);+ expect(getSQLEditorEditorState().projectContextReady).toBe(true);++ getSQLEditorEditorState().setProjectContextReady(false);+ expect(getSQLEditorEditorState().projectContextReady).toBe(false);+ });++ test("setResultRowsLimit persists numeric limits to localStorage", () => {+ getSQLEditorEditorState().setResultRowsLimit(2500);++ expect(getSQLEditorEditorState().resultRowsLimit).toBe(2500);+ expect(JSON.parse(storage.get(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT)!)).toBe(+ 2500+ );+ });++ test("setRedisCommandOption persists the selected node target", () => {+ // 2 = ALL_NODES per the proto enum.+ getSQLEditorEditorState().setRedisCommandOption(2);++ expect(getSQLEditorEditorState().redisCommandOption).toBe(2);+ expect(JSON.parse(storage.get(STORAGE_KEY_SQL_EDITOR_REDIS_NODE)!)).toBe(2);+ });++ test("setShowExecutingHint and setExecutingHintDatabase are reactive", () => {+ expect(getSQLEditorEditorState().isShowExecutingHint).toBe(false);+ getSQLEditorEditorState().setShowExecutingHint(true);+ expect(getSQLEditorEditorState().isShowExecutingHint).toBe(true);++ const fakeDb = { name: "instances/x/databases/y" } as never;+ getSQLEditorEditorState().setExecutingHintDatabase(fakeDb);+ expect(getSQLEditorEditorState().executingHintDatabase).toBe(fakeDb);+ });++ test("subscribeSQLEditorEditorState notifies on every mutation", () => {+ let calls = 0;+ const unsubscribe = subscribeSQLEditorEditorState(() => {+ calls++;+ });++ getSQLEditorEditorState().setProject("projects/beta");+ getSQLEditorEditorState().setResultRowsLimit(50);+ getSQLEditorEditorState().setShowExecutingHint(true);++ expect(calls).toBeGreaterThanOrEqual(3);+ unsubscribe();++ getSQLEditorEditorState().setShowExecutingHint(false);+ expect(calls).toBeGreaterThanOrEqual(3);+ });+});diff --git a/frontend/src/react/stores/sqlEditor/editor.ts b/frontend/src/react/stores/sqlEditor/editor.tsnew file mode 100644index 0000000000..0437e1b6b1--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/editor.ts@@ -0,0 +1,167 @@+import { useSyncExternalStore } from "react";+import { create, type StoreApi, type UseBoundStore } from "zustand";+import { immer } from "zustand/middleware/immer";+import type { Database } from "@/types/proto-es/v1/database_service_pb";+import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";+import {+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+} from "@/utils/storage-keys";++export interface SQLEditorEditorState {+ project: string;+ projectContextReady: boolean;+ resultRowsLimit: number;+ redisCommandOption: QueryOption_RedisRunCommandsOn;+ isShowExecutingHint: boolean;+ executingHintDatabase: Database | undefined;++ setProject: (project: string) => void;+ setProjectContextReady: (ready: boolean) => void;+ setResultRowsLimit: (limit: number) => void;+ setRedisCommandOption: (option: QueryOption_RedisRunCommandsOn) => void;+ setShowExecutingHint: (show: boolean) => void;+ setExecutingHintDatabase: (db: Database | undefined) => void;+}++const DEFAULT_RESULT_ROWS_LIMIT = 1000;++const safeRead = <T>(+ key: string,+ parse: (raw: unknown) => T | undefined,+ fallback: T+): T => {+ if (typeof window === "undefined") return fallback;+ try {+ const raw = window.localStorage.getItem(key);+ if (raw === null) return fallback;+ const parsed = JSON.parse(raw);+ const valid = parse(parsed);+ return valid === undefined ? fallback : valid;+ } catch {+ return fallback;+ }+};++const safeWrite = (key: string, value: unknown) => {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(key, JSON.stringify(value));+ } catch {+ // Ignore quota / serialization errors.+ }+};++const readProject = () =>+ safeRead<string>(+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ (v) => (typeof v === "string" ? v : undefined),+ ""+ );++const readResultRowsLimit = () =>+ safeRead<number>(+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+ (v) =>+ typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined,+ DEFAULT_RESULT_ROWS_LIMIT+ );++const readRedisOption = () =>+ safeRead<QueryOption_RedisRunCommandsOn>(+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ (v) =>+ v === QueryOption_RedisRunCommandsOn.SINGLE_NODE ||+ v === QueryOption_RedisRunCommandsOn.ALL_NODES+ ? v+ : undefined,+ QueryOption_RedisRunCommandsOn.SINGLE_NODE+ );++export const useSQLEditorEditorStore: UseBoundStore<+ StoreApi<SQLEditorEditorState>+> = create<SQLEditorEditorState>()(+ immer((set) => ({+ project: readProject(),+ projectContextReady: false,+ resultRowsLimit: readResultRowsLimit(),+ redisCommandOption: readRedisOption(),+ isShowExecutingHint: false,+ executingHintDatabase: undefined,++ setProject(project) {+ set((s) => {+ s.project = project;+ s.projectContextReady = true;+ });+ safeWrite(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT, project);+ },+ setProjectContextReady(ready) {+ set((s) => {+ s.projectContextReady = ready;+ });+ },+ setResultRowsLimit(limit) {+ set((s) => {+ s.resultRowsLimit = limit;+ });+ safeWrite(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT, limit);+ },+ setRedisCommandOption(option) {+ set((s) => {+ s.redisCommandOption = option;+ });+ safeWrite(STORAGE_KEY_SQL_EDITOR_REDIS_NODE, option);+ },+ setShowExecutingHint(show) {+ set((s) => {+ s.isShowExecutingHint = show;+ });+ },+ setExecutingHintDatabase(db) {+ set((s) => {+ s.executingHintDatabase = db;+ });+ },+ }))+);++/**+ * Subscribe a React component to a slice of SQL editor editor state.+ *+ * @example+ * const project = useSQLEditorEditorState((s) => s.project);+ * const setProject = useSQLEditorEditorState((s) => s.setProject);+ */+export function useSQLEditorEditorState<T>(+ selector: (state: SQLEditorEditorState) => T+): T {+ return useSQLEditorEditorStore(selector);+}++/**+ * Read SQL editor editor state outside React (in actions, effects, or+ * non-React modules). Mirrors Zustand's `getState()`.+ */+export const getSQLEditorEditorState = (): SQLEditorEditorState =>+ useSQLEditorEditorStore.getState();++/**+ * Low-level subscription primitive for non-React consumers (Vue compat+ * shim, side-effect modules). Returns an unsubscribe function.+ */+export const subscribeSQLEditorEditorState = (+ listener: (state: SQLEditorEditorState) => void+): (() => void) => useSQLEditorEditorStore.subscribe(listener);++/**+ * useSyncExternalStore-friendly helpers for callers that want to read+ * the full state object without a selector (e.g. tests).+ */+export const useSQLEditorEditorSnapshot = (): SQLEditorEditorState =>+ useSyncExternalStore(+ useSQLEditorEditorStore.subscribe,+ useSQLEditorEditorStore.getState,+ useSQLEditorEditorStore.getState+ );diff --git a/frontend/src/react/stores/sqlEditor/folder.ts b/frontend/src/react/stores/sqlEditor/folder.tsdeleted file mode 100644index 97a179fb7d..0000000000--- a/frontend/src/react/stores/sqlEditor/folder.ts+++ /dev/null@@ -1,131 +0,0 @@-import { sortBy } from "lodash-es";-import { computed, toRefs } from "vue";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import { useCurrentUserV1 } from "@/store";-import {- storageKeySqlEditorWorksheetFolder,- useDynamicLocalStorage,-} from "@/utils";-import type { SheetViewMode } from "@/views/sql-editor/Sheet/types";--/**- * Vue-reactive folder-tree helper used by the worksheet sheet context.- * The only consumer today is the Vue-side singleton at- * `views/sql-editor/Sheet/context.ts`, but the file lives under the- * React store tree because the whole sqlEditor state surface is- * homing there as the Pinia layer is dismantled. The Vue refs and- * `storeToRefs` calls stay — the consumer is still Vue-reactive.- */-export const buildFolderContext = (viewMode: SheetViewMode) => {- const me = useCurrentUserV1();- const { project } = toRefs(useSQLEditorVueState());-- const rootPath = computed(() => `/${viewMode}`);- const localCacheKey = computed(() =>- storageKeySqlEditorWorksheetFolder(project.value, viewMode, me.value.email)- );- const localCache = useDynamicLocalStorage<Set<string>>(- localCacheKey,- new Set([rootPath.value])- );- localCache.value.add(rootPath.value);-- const folders = computed(() => sortBy([...localCache.value]));-- const ensureFolderPath = (path: string) => {- let p = path- .split("/")- .map((p) => p.trim())- .filter((p) => p)- .join("/");- if (!p) {- return rootPath.value;- }- if (!p.startsWith("/")) {- p = `/${p}`;- }- if (!p.startsWith(rootPath.value)) {- p = `${rootPath.value}${p}`;- }- return p;- };-- const addFolder = (path: string) => {- const newPath = ensureFolderPath(path);- localCache.value.add(newPath);- return newPath;- };-- const isSubFolder = ({- parent,- path,- dig,- }: {- parent: string;- path: string;- dig: boolean;- }) => {- const parentPrefix = `${parent}/`;- return path !== parentPrefix && path.startsWith(parentPrefix) && dig- ? true- : !path.replace(parentPrefix, "").includes("/");- };-- const removeFolder = (path: string) => {- localCache.value = new Set(- [...localCache.value].filter(- (value) =>- !(- value === path ||- isSubFolder({ parent: path, path: value, dig: true })- )- )- );- };-- const moveFolder = (from: string, to: string) => {- const fromPath = ensureFolderPath(from);- const toPath = ensureFolderPath(to);- const newSet = new Set<string>();- for (const path of localCache.value.values()) {- if (- path === fromPath ||- isSubFolder({ parent: fromPath, path, dig: true })- ) {- newSet.add(path.replace(fromPath, toPath));- } else {- newSet.add(path);- }- }- localCache.value = newSet;- };-- const mergeFolders = (paths: Set<string>) => {- const newSet = new Set(localCache.value);- for (const folder of paths.values()) {- const validPath = ensureFolderPath(folder);- newSet.add(validPath);- }- localCache.value = newSet;- };-- const listSubFolders = (parent: string) => {- return folders.value.filter((path) => {- return isSubFolder({ parent, path, dig: false });- });- };-- return {- rootPath,- folders,- listSubFolders,- ensureFolderPath,- addFolder,- removeFolder,- moveFolder,- mergeFolders,- isSubFolder,- };-};--export type FolderContext = ReturnType<typeof buildFolderContext>;diff --git a/frontend/src/react/stores/sqlEditor/tab-vue-state.ts b/frontend/src/react/stores/sqlEditor/tab-vue-state.tsdeleted file mode 100644index 1720f0bfa5..0000000000--- a/frontend/src/react/stores/sqlEditor/tab-vue-state.ts+++ /dev/null@@ -1,493 +0,0 @@-import { cloneDeep, head, isUndefined, omitBy, pick } from "lodash-es";-import { computed, type MaybeRef, reactive, toRefs, unref, watch } from "vue";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import {- hasFeature,- useCurrentUserV1,- useDatabaseV1ByName,- useEnvironmentV1Store,- useWorkSheetStore,-} from "@/store";-import {- migrateDraftsFromCache,- migrateTabViewState,-} from "@/store/modules/sqlEditor/legacy/migration";-import type {- BatchQueryContext,- SQLEditorConnection,- SQLEditorDatabaseQueryContext,- SQLEditorTab,-} from "@/types";-import { isValidDatabaseName } from "@/types";-import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";-import {- defaultSQLEditorTab,- emptySQLEditorConnection,- extractWorksheetConnection,- getDatabaseEnvironment,- getInstanceResource,- getSheetStatement,- isConnectedSQLEditorTab,- storageKeySqlEditorCurrentTab,- storageKeySqlEditorTabs,- useDynamicLocalStorage,-} from "@/utils";--/**- * Vue-reactive SQL Editor tab state. Replaces the Pinia- * `useSQLEditorTabStore` (`store/modules/sqlEditor/tab.ts`) — same- * shape and field semantics, but lives as a module-level lazy- * singleton instead of a Pinia store. The store is still heavily- * Vue-reactive (`reactive(new Map())`, `computed`, `watch`,- * `useDynamicLocalStorage`), so consumers continue to use- * `useVueState(() => tabStore.X)` for cross-framework reads.- */-const PERSISTENT_TAB_FIELDS = [- "id",- "worksheet",- "mode",- "batchQueryContext",- "treeState",- "viewState",-] as const;-type PersistentTab = Pick<SQLEditorTab, (typeof PERSISTENT_TAB_FIELDS)[number]>;--const buildSQLEditorTabState = () => {- // re-expose selected project in sqlEditorStore for shortcut- const { project } = toRefs(useSQLEditorVueState());- const tabsById = reactive(new Map<string, SQLEditorTab>());- const worksheetStore = useWorkSheetStore();-- const me = useCurrentUserV1();- const keyNamespace = computed(() =>- storageKeySqlEditorTabs(project.value, me.value.email)- );-- const openTmpTabList = useDynamicLocalStorage<PersistentTab[]>(- computed(() => keyNamespace.value),- [],- localStorage,- {- listenToStorageChanges: false,- }- );-- const currentTabId = useDynamicLocalStorage<string>(- computed(() =>- storageKeySqlEditorCurrentTab(project.value, me.value.email)- ),- "",- localStorage,- {- listenToStorageChanges: false,- }- );-- const loadStoredTabs = async () => {- const validOpenTabMap: Map<string, PersistentTab> = new Map();- for (const tab of openTmpTabList.value) {- if (validOpenTabMap.has(tab.id)) {- continue;- }- if (!tab.worksheet) {- continue;- }- const worksheet = await worksheetStore.getOrFetchWorksheetByName(- tab.worksheet,- true- );- if (!worksheet) {- continue;- }- const statement = getSheetStatement(worksheet);- const connection = await extractWorksheetConnection(worksheet);-- const fullTab: SQLEditorTab = {- ...defaultSQLEditorTab(),- ...omitBy(tab, isUndefined),- connection,- worksheet: worksheet.name,- title: worksheet.title,- statement,- status: "CLEAN",- databaseQueryContexts: undefined,- };-- validOpenTabMap.set(tab.id, tab);- tabsById.set(tab.id, fullTab);- }-- openTmpTabList.value = [...validOpenTabMap.values()];- };-- const initProject = async (project: string) => {- await migrateDraftsFromCache(project);- migrateTabViewState(project);- tabsById.clear();- await loadStoredTabs();- currentTabId.value = head(openTmpTabList.value)?.id ?? "";- };-- const getTabById = (tabId: string) => {- return tabsById.get(tabId);- };-- const openTabList = computed({- get() {- return openTmpTabList.value.map((item) => {- return getTabById(item.id) ?? defaultSQLEditorTab();- });- },- set(list) {- openTmpTabList.value = list;- },- });-- const getTabByWorksheet = (worksheet: string) => {- return openTabList.value.find((item) => item.worksheet === worksheet);- };-- const currentTab = computed(() => {- const currId = currentTabId.value;- if (!currId) return undefined;- return getTabById(currId);- });-- const supportBatchMode = computed(() => currentTab.value?.mode !== "ADMIN");-- const isInBatchMode = computed(() => {- if (!currentTab.value) {- return false;- }- if (!supportBatchMode.value) {- return false;- }- if (!hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) {- return false;- }- const { batchQueryContext } = currentTab.value;- if (!batchQueryContext) {- return false;- }- const { databaseGroups = [], databases = [] } = batchQueryContext;- if (!hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {- return databases.length > 1;- }- return databaseGroups.length > 0 || databases.length > 1;- });-- /**- * Create or update the tab, and ensure the tab is open.- * @param payload- * @param beside `true` to add the tab beside currentTab, `false` to add the tab to the last, default to `false`- * @returns the tab- */- const addTab = (- payload?: Partial<SQLEditorTab>,- beside = false- ): SQLEditorTab => {- const defaultTab: SQLEditorTab = {- ...defaultSQLEditorTab(),- ...omitBy(payload, isUndefined),- };- const { id } = defaultTab;-- let newTab = getTabById(id);- if (newTab) {- Object.assign(newTab, omitBy(payload, isUndefined));- } else {- newTab = defaultTab;- tabsById.set(id, newTab);- }-- upsertCache(newTab, beside);- setCurrentTabId(id);- return newTab;- };-- const cloneTab = (- targetId: string,- payload?: Partial<SQLEditorTab>- ): SQLEditorTab => {- const targetTab = getTabById(targetId);- const clonedTab: Partial<SQLEditorTab> = {- statement: targetTab?.statement,- connection: cloneDeep(targetTab?.connection),- treeState: cloneDeep(targetTab?.treeState),- editorState: cloneDeep(targetTab?.editorState),- batchQueryContext: cloneDeep(targetTab?.batchQueryContext),- // Cloned tabs start untitled; the UI renders an "Untitled" placeholder.- title: "",- ...payload,- };-- return addTab(clonedTab, true);- };-- const closeTab = (tabId: string) => {- const position = openTmpTabList.value.findIndex(- (item) => item.id === tabId- );- if (position < 0) {- return;- }- openTmpTabList.value.splice(position, 1);- tabsById.delete(tabId);- // Dynamic import avoids a static cycle with the zustand store- // (which transitively re-imports this module via `@/store`).- void import("@/react/stores/sqlEditor/webTerminal-service").then(- ({ disposeWebTerminalQuerySession }) => {- disposeWebTerminalQuerySession(tabId);- }- );-- if (tabId === currentTabId.value) {- const nextIndex = Math.min(position, openTmpTabList.value.length - 1);- const nextTab = openTmpTabList.value[nextIndex];- setCurrentTabId(nextTab?.id ?? "");- }- };-- const upsertCache = (tab: SQLEditorTab, beside = false) => {- const persistentTab = pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab;-- const position = openTmpTabList.value.findIndex(- (item) => item.id === tab.id- );- if (position >= 0) {- Object.assign(openTmpTabList.value[position], persistentTab);- } else {- const currentPosition = openTmpTabList.value.findIndex(- (item) => item.id === currentTabId.value- );- if (beside && currentPosition >= 0) {- openTmpTabList.value.splice(currentPosition + 1, 0, persistentTab);- } else {- openTmpTabList.value.push(persistentTab);- }- }- };-- const updateTab = (- id: string,- payload: Partial<SQLEditorTab>- ): SQLEditorTab | undefined => {- const tab = getTabById(id);- if (!tab) return;- Object.assign(tab, payload);- upsertCache(tab);- return tab;- };-- const updateCurrentTab = (payload: Partial<SQLEditorTab>) => {- const id = currentTabId.value;- if (!id) return;- return updateTab(id, payload);- };-- const updateBatchQueryContext = (payload: Partial<BatchQueryContext>) => {- const tab = currentTab.value;- if (!tab) {- return;- }- return updateTab(tab.id, {- batchQueryContext: {- dataSourceType:- tab.batchQueryContext?.dataSourceType ?? DataSourceType.READ_ONLY,- ...tab.batchQueryContext,- ...payload,- },- });- };-- // removeDatabaseQueryContext remove the context by id, and returns the next context.- const removeDatabaseQueryContext = ({- database,- contextId,- }: {- database: string;- contextId: string;- }): SQLEditorDatabaseQueryContext | undefined => {- const tab = getTabById(currentTabId.value);- if (!tab || !tab.databaseQueryContexts) {- return;- }- if (!tab.databaseQueryContexts.has(database)) {- return;- }- const contexts = tab.databaseQueryContexts.get(database)!;- const index = contexts.findIndex((context) => context.id === contextId);- if (index < 0) {- return;- }- contexts.splice(index, 1);- return contexts[index] || contexts[index - 1];- };-- const batchRemoveDatabaseQueryContext = ({- database,- contextIds,- }: {- database: string;- contextIds: string[];- }) => {- const tab = getTabById(currentTabId.value);- if (!tab || !tab.databaseQueryContexts) {- return;- }- if (!tab.databaseQueryContexts.has(database)) {- return;- }- if (contextIds.length === 0) {- return;- }-- const target = new Set(contextIds);- const contexts = tab.databaseQueryContexts.get(database)!;- const newContexts = contexts.filter((ctx) => !target.has(ctx.id));-- if (newContexts.length !== contexts.length) {- tab.databaseQueryContexts.set(database, newContexts);- }- };-- const deleteDatabaseQueryContext = (database: string) => {- const tab = getTabById(currentTabId.value);- if (!tab || !tab.databaseQueryContexts) {- return;- }- tab.databaseQueryContexts.delete(database);- };-- const updateDatabaseQueryContext = ({- database,- contextId,- context,- }: {- database: string;- contextId: string;- context: Partial<SQLEditorDatabaseQueryContext>;- }) => {- const tab = getTabById(currentTabId.value);- if (!tab || !tab.databaseQueryContexts) {- return;- }- if (!tab.databaseQueryContexts.has(database)) {- return;- }- const target = tab.databaseQueryContexts- .get(database)- ?.find((c) => c.id === contextId);- if (!target) {- return;- }- Object.assign(target, context);- return target;- };-- const setCurrentTabId = (id: string) => {- currentTabId.value = id;- };-- watch(- () => project.value,- async (project) => {- await initProject(project);- }- );-- const isDisconnected = computed(() => {- const tab = currentTab.value;- if (!tab) return true;- return !isConnectedSQLEditorTab(tab);- });-- // Wrap with `reactive()` so consumers see the same auto-unwrap /- // auto-wrap-on-assign ergonomics they had with the Pinia store. Use- // Vue's `toRefs()` (not Pinia's `storeToRefs`) to extract individual- // refs when needed.- return reactive({- project,- initProject,- getTabById,- getTabByWorksheet,- openTabList,- currentTabId,- currentTab,- addTab,- cloneTab,- closeTab,- updateTab,- updateCurrentTab,- updateBatchQueryContext,- updateDatabaseQueryContext,- removeDatabaseQueryContext,- batchRemoveDatabaseQueryContext,- deleteDatabaseQueryContext,- setCurrentTabId,- isDisconnected,- isInBatchMode,- supportBatchMode,- });-};--let _state: ReturnType<typeof buildSQLEditorTabState> | undefined;-export const useSQLEditorTabStore = () => {- if (!_state) _state = buildSQLEditorTabState();- return _state;-};--export type SQLEditorTabState = ReturnType<typeof useSQLEditorTabStore>;--export const useCurrentSQLEditorTab = () => {- return toRefs(useSQLEditorTabStore()).currentTab;-};--export const isSQLEditorTabClosable = (tab: SQLEditorTab) => {- const { openTabList } = useSQLEditorTabStore();-- if (openTabList.length > 1) {- return true;- }- if (openTabList.length === 1) {- return !!tab.worksheet;- }- return false;-};--export const useSQLEditorConnectionDetail = (- connection: MaybeRef<SQLEditorConnection>-) => {- const { database } = useDatabaseV1ByName(- computed(() => unref(connection).database)- );-- const instance = computed(() => {- return getInstanceResource(database.value);- });-- const environment = computed(() => {- if (isValidDatabaseName(database.value.name)) {- return getDatabaseEnvironment(database.value);- }-- return useEnvironmentV1Store().getEnvironmentByName(- instance.value.environment ?? ""- );- });-- return { connection, instance, database, environment };-};--export const useConnectionOfCurrentSQLEditorTab = () => {- const store = useSQLEditorTabStore();- const connection = computed(() => {- return store.currentTab?.connection ?? emptySQLEditorConnection();- });-- const { instance, database, environment } =- useSQLEditorConnectionDetail(connection);-- return { connection, instance, database, environment };-};diff --git a/frontend/src/react/stores/sqlEditor/tab.test.ts b/frontend/src/react/stores/sqlEditor/tab.test.tsnew file mode 100644index 0000000000..9fa7bebe57--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/tab.test.ts@@ -0,0 +1,226 @@+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import {+ __resetTabStoreProjectCursor,+ getSQLEditorTabsState,+ subscribeSQLEditorTabsState,+ useSQLEditorTabsStore,+} from "./tab";++const storage = new Map<string, string>();+const originalLocalStorage = globalThis.localStorage;++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(() => {+ storage.clear();+ Object.defineProperty(globalThis, "localStorage", {+ value: localStorageMock,+ configurable: true,+ writable: true,+ });+ getSQLEditorTabsState().reset();+ __resetTabStoreProjectCursor();+});++afterEach(() => {+ Object.defineProperty(globalThis, "localStorage", {+ value: originalLocalStorage,+ configurable: true,+ writable: true,+ });+});++describe("useSQLEditorTabsStore", () => {+ test("addTab seeds a new tab, sets it current, and tracks open order", () => {+ const tab = getSQLEditorTabsState().addTab({ title: "first" });++ const state = useSQLEditorTabsStore.getState();+ expect(state.currentTabId).toBe(tab.id);+ expect(state.tabsById.get(tab.id)?.title).toBe("first");+ expect(state.openTmpTabList.map((t) => t.id)).toEqual([tab.id]);+ });++ test("addTab appends or inserts beside the current tab based on flag", () => {+ const a = getSQLEditorTabsState().addTab({ title: "a" });+ const c = getSQLEditorTabsState().addTab({ title: "c" });+ // Insert "b" beside the current tab (c) — should land after c.+ const b = getSQLEditorTabsState().addTab({ title: "b" }, true);++ const order = useSQLEditorTabsStore+ .getState()+ .openTmpTabList.map((t) => t.id);+ expect(order).toEqual([a.id, c.id, b.id]);+ });++ test("updateTab merges fields into the existing tab", () => {+ const tab = getSQLEditorTabsState().addTab({ title: "before" });+ getSQLEditorTabsState().updateTab(tab.id, {+ title: "after",+ status: "DIRTY",+ });++ const stored = useSQLEditorTabsStore.getState().tabsById.get(tab.id);+ expect(stored?.title).toBe("after");+ expect(stored?.status).toBe("DIRTY");+ });++ test("updateCurrentTab is a shorthand over updateTab", () => {+ const tab = getSQLEditorTabsState().addTab({ statement: "SELECT 1" });+ getSQLEditorTabsState().updateCurrentTab({ statement: "SELECT 2" });++ const stored = useSQLEditorTabsStore.getState().tabsById.get(tab.id);+ expect(stored?.statement).toBe("SELECT 2");+ });++ test("closeTab removes the tab and advances currentTabId", () => {+ const a = getSQLEditorTabsState().addTab({ title: "a" });+ const b = getSQLEditorTabsState().addTab({ title: "b" });++ getSQLEditorTabsState().closeTab(b.id);++ const state = useSQLEditorTabsStore.getState();+ expect(state.tabsById.has(b.id)).toBe(false);+ expect(state.openTmpTabList.map((t) => t.id)).toEqual([a.id]);+ expect(state.currentTabId).toBe(a.id);+ });++ test("closeTab on the only tab clears currentTabId", () => {+ const a = getSQLEditorTabsState().addTab({ title: "lonely" });++ getSQLEditorTabsState().closeTab(a.id);++ const state = useSQLEditorTabsStore.getState();+ expect(state.openTmpTabList).toHaveLength(0);+ expect(state.currentTabId).toBe("");+ });++ test("setOpenTabListOrder rewrites the persisted order without losing tabs", () => {+ const a = getSQLEditorTabsState().addTab({ title: "a" });+ const b = getSQLEditorTabsState().addTab({ title: "b" });++ const reordered = [+ ...useSQLEditorTabsStore.getState().openTmpTabList,+ ].reverse();+ getSQLEditorTabsState().setOpenTabListOrder(reordered);++ const order = useSQLEditorTabsStore+ .getState()+ .openTmpTabList.map((t) => t.id);+ expect(order).toEqual([b.id, a.id]);+ // Live tab map unchanged.+ expect(useSQLEditorTabsStore.getState().tabsById.size).toBe(2);+ });++ test("cloneTab copies statement and connection into a new tab", () => {+ const original = getSQLEditorTabsState().addTab({+ title: "orig",+ statement: "SELECT *",+ });+ const cloned = getSQLEditorTabsState().cloneTab(original.id, {+ title: "clone",+ });++ expect(cloned.id).not.toBe(original.id);+ expect(cloned.statement).toBe("SELECT *");+ expect(useSQLEditorTabsStore.getState().currentTabId).toBe(cloned.id);+ });++ test("updateBatchQueryContext seeds and merges batch context", () => {+ const tab = getSQLEditorTabsState().addTab({ title: "batch" });++ getSQLEditorTabsState().updateBatchQueryContext({+ databases: ["instances/x/databases/y"],+ });++ const stored = useSQLEditorTabsStore.getState().tabsById.get(tab.id);+ expect(stored?.batchQueryContext.databases).toEqual([+ "instances/x/databases/y",+ ]);+ });++ test("database query context add/update/remove flow", () => {+ const tab = getSQLEditorTabsState().addTab({ title: "ctx" });+ const db = "instances/x/databases/y";+ // Seed the context map via updateTab (the public action) so the+ // mutation flows through the same immer path that production+ // callers use.+ getSQLEditorTabsState().updateTab(tab.id, {+ databaseQueryContexts: new Map([+ [+ db,+ [+ // The tests below don't read params/engine/etc., so cast a+ // shape-light fixture rather than constructing a full+ // SQLEditorQueryParams (which would require monaco types).+ { id: "c1", status: "PENDING" } as never,+ { id: "c2", status: "PENDING" } as never,+ ],+ ],+ ]),+ });++ getSQLEditorTabsState().updateDatabaseQueryContext({+ database: db,+ contextId: "c1",+ context: { status: "DONE" },+ });+ expect(+ useSQLEditorTabsStore+ .getState()+ .tabsById.get(tab.id)+ ?.databaseQueryContexts?.get(db)+ ?.find((c) => c.id === "c1")?.status+ ).toBe("DONE");++ getSQLEditorTabsState().removeDatabaseQueryContext({+ database: db,+ contextId: "c1",+ });+ const remainingIds = useSQLEditorTabsStore+ .getState()+ .tabsById.get(tab.id)+ ?.databaseQueryContexts?.get(db)+ ?.map((c) => c.id);+ expect(remainingIds).toEqual(["c2"]);++ getSQLEditorTabsState().deleteDatabaseQueryContext(db);+ expect(+ useSQLEditorTabsStore+ .getState()+ .tabsById.get(tab.id)+ ?.databaseQueryContexts?.has(db)+ ).toBe(false);+ });++ test("subscribeSQLEditorTabsState fires on every mutation", () => {+ let count = 0;+ const unsubscribe = subscribeSQLEditorTabsState(() => {+ count++;+ });++ const a = getSQLEditorTabsState().addTab({ title: "a" });+ getSQLEditorTabsState().updateTab(a.id, { title: "a2" });+ // Force a distinct mutation so immer produces a new state and the+ // subscription fires (setting currentTabId to its current value is+ // a no-op that immer collapses away).+ getSQLEditorTabsState().setCurrentTabId("");++ expect(count).toBeGreaterThanOrEqual(3);+ unsubscribe();+ });+});diff --git a/frontend/src/react/stores/sqlEditor/tab.ts b/frontend/src/react/stores/sqlEditor/tab.tsnew file mode 100644index 0000000000..f9ff96d1c6--- /dev/null+++ b/frontend/src/react/stores/sqlEditor/tab.ts@@ -0,0 +1,639 @@+import { enableMapSet } from "immer";+import { cloneDeep, head, isUndefined, omitBy, pick } from "lodash-es";+import { create, type StoreApi, type UseBoundStore } from "zustand";+import { immer } from "zustand/middleware/immer";+import { useShallow } from "zustand/react/shallow";+import { hasFeature, useCurrentUserV1, useWorkSheetStore } from "@/store";+import {+ migrateDraftsFromCache,+ migrateTabViewState,+} from "@/store/modules/sqlEditor/legacy/migration";+import type {+ BatchQueryContext,+ SQLEditorDatabaseQueryContext,+ SQLEditorTab,+} from "@/types";+import { DataSourceType } from "@/types/proto-es/v1/instance_service_pb";+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";+import {+ defaultSQLEditorTab,+ extractWorksheetConnection,+ getSheetStatement,+ isConnectedSQLEditorTab,+ storageKeySqlEditorCurrentTab,+ storageKeySqlEditorTabs,+} from "@/utils";+import {+ getSQLEditorEditorState,+ subscribeSQLEditorEditorState,+} from "./editor";++// SQL editor tabs are stored in a Map<id, tab> that this store mutates+// in place via immer drafts. Enabling the MapSet plugin teaches immer+// how to draft / produce Map and Set instances.+enableMapSet();++const PERSISTENT_TAB_FIELDS = [+ "id",+ "worksheet",+ "mode",+ "batchQueryContext",+ "treeState",+ "viewState",+] as const;+export type PersistentTab = Pick<+ SQLEditorTab,+ (typeof PERSISTENT_TAB_FIELDS)[number]+>;++export interface SQLEditorTabsState {+ /** Authoritative live tab objects keyed by id. */+ tabsById: Map<string, SQLEditorTab>;+ /** Persisted metadata that drives tab order and lightweight reload. */+ openTmpTabList: PersistentTab[];+ /** Currently active tab id; empty when no tabs are open. */+ currentTabId: string;++ setCurrentTabId: (id: string) => void;+ /** Rewrites the persisted tab order without touching individual tabs. */+ setOpenTabListOrder: (order: PersistentTab[]) => void;+ addTab: (payload?: Partial<SQLEditorTab>, beside?: boolean) => SQLEditorTab;+ cloneTab: (targetId: string, payload?: Partial<SQLEditorTab>) => SQLEditorTab;+ closeTab: (tabId: string) => void;+ updateTab: (+ id: string,+ payload: Partial<SQLEditorTab>+ ) => SQLEditorTab | undefined;+ updateCurrentTab: (+ payload: Partial<SQLEditorTab>+ ) => SQLEditorTab | undefined;+ updateBatchQueryContext: (+ payload: Partial<BatchQueryContext>+ ) => SQLEditorTab | undefined;+ removeDatabaseQueryContext: (params: {+ database: string;+ contextId: string;+ }) => SQLEditorDatabaseQueryContext | undefined;+ batchRemoveDatabaseQueryContext: (params: {+ database: string;+ contextIds: string[];+ }) => void;+ deleteDatabaseQueryContext: (database: string) => void;+ updateDatabaseQueryContext: (params: {+ database: string;+ contextId: string;+ context: Partial<SQLEditorDatabaseQueryContext>;+ }) => SQLEditorDatabaseQueryContext | undefined;+ initProject: (project: string) => Promise<void>;+ /** Reset all in-memory state. Test-only utility. */+ reset: () => void;+}++const safeRead = <T>(+ key: string,+ parse: (raw: unknown) => T | undefined,+ fallback: T+): T => {+ if (typeof window === "undefined") return fallback;+ try {+ const raw = window.localStorage.getItem(key);+ if (raw === null) return fallback;+ const parsed = JSON.parse(raw);+ const valid = parse(parsed);+ return valid === undefined ? fallback : valid;+ } catch {+ return fallback;+ }+};++const safeWrite = (key: string, value: unknown) => {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(key, JSON.stringify(value));+ } catch {+ // Ignore quota / serialization errors.+ }+};++const isPersistentTabArray = (v: unknown): v is PersistentTab[] =>+ Array.isArray(v);++const currentScope = (): { project: string; email: string } | null => {+ const project = getSQLEditorEditorState().project;+ if (!project) return null;+ try {+ const me = useCurrentUserV1();+ const email = me?.value?.email ?? "";+ return { project, email };+ } catch {+ return null;+ }+};++const persistOpenTabs = (openTabs: PersistentTab[]) => {+ const scope = currentScope();+ if (!scope) return;+ safeWrite(storageKeySqlEditorTabs(scope.project, scope.email), openTabs);+};++const persistCurrentTabId = (id: string) => {+ const scope = currentScope();+ if (!scope) return;+ safeWrite(storageKeySqlEditorCurrentTab(scope.project, scope.email), id);+};++const readOpenTabs = (project: string, email: string): PersistentTab[] =>+ safeRead<PersistentTab[]>(+ storageKeySqlEditorTabs(project, email),+ (v) => (isPersistentTabArray(v) ? v : undefined),+ []+ );++export const useSQLEditorTabsStore: UseBoundStore<+ StoreApi<SQLEditorTabsState>+> = create<SQLEditorTabsState>()(+ immer((set, get) => ({+ tabsById: new Map(),+ openTmpTabList: [],+ currentTabId: "",++ setCurrentTabId(id) {+ set((s) => {+ s.currentTabId = id;+ });+ persistCurrentTabId(id);+ },++ setOpenTabListOrder(order) {+ set((s) => {+ s.openTmpTabList = order;+ });+ persistOpenTabs(order);+ },++ addTab(payload, beside = false) {+ const defaultTab: SQLEditorTab = {+ ...defaultSQLEditorTab(),+ ...omitBy(payload, isUndefined),+ };+ const { id } = defaultTab;++ set((s) => {+ let tab = s.tabsById.get(id);+ if (tab) {+ Object.assign(tab, omitBy(payload, isUndefined));+ } else {+ tab = defaultTab;+ s.tabsById.set(id, tab);+ }++ upsertOpenTabDraft(s, tab, beside);+ s.currentTabId = id;+ });++ persistOpenTabs(get().openTmpTabList);+ persistCurrentTabId(id);++ // Return the live (post-immer) tab reference so callers reading+ // fields immediately see the seeded values.+ return get().tabsById.get(id) ?? defaultTab;+ },++ cloneTab(targetId, payload) {+ const targetTab = get().tabsById.get(targetId);+ const cloned: Partial<SQLEditorTab> = {+ statement: targetTab?.statement,+ connection: cloneDeep(targetTab?.connection),+ treeState: cloneDeep(targetTab?.treeState),+ editorState: cloneDeep(targetTab?.editorState),+ batchQueryContext: cloneDeep(targetTab?.batchQueryContext),+ title: "",+ ...payload,+ };+ return get().addTab(cloned, true);+ },++ closeTab(tabId) {+ const position = get().openTmpTabList.findIndex(+ (item) => item.id === tabId+ );+ if (position < 0) return;++ const wasCurrent = tabId === get().currentTabId;++ set((s) => {+ s.openTmpTabList.splice(position, 1);+ s.tabsById.delete(tabId);+ if (wasCurrent) {+ const nextIndex = Math.min(position, s.openTmpTabList.length - 1);+ s.currentTabId = s.openTmpTabList[nextIndex]?.id ?? "";+ }+ });++ persistOpenTabs(get().openTmpTabList);+ if (wasCurrent) {+ persistCurrentTabId(get().currentTabId);+ }++ // Dynamic import avoids a static cycle with the web terminal+ // service module (which transitively re-imports this module).+ void import("@/react/stores/sqlEditor/webTerminal-service").then(+ ({ disposeWebTerminalQuerySession }) => {+ disposeWebTerminalQuerySession(tabId);+ }+ );+ },++ updateTab(id, payload) {+ if (!get().tabsById.has(id)) return undefined;+ set((s) => {+ const tab = s.tabsById.get(id);+ if (!tab) return;+ Object.assign(tab, payload);+ upsertOpenTabDraft(s, tab, false);+ });+ persistOpenTabs(get().openTmpTabList);+ return get().tabsById.get(id);+ },++ updateCurrentTab(payload) {+ const id = get().currentTabId;+ if (!id) return undefined;+ return get().updateTab(id, payload);+ },++ updateBatchQueryContext(payload) {+ const id = get().currentTabId;+ if (!id) return undefined;+ const existing = get().tabsById.get(id);+ if (!existing) return undefined;+ const previousCtx = existing.batchQueryContext;+ return get().updateTab(id, {+ batchQueryContext: {+ dataSourceType:+ previousCtx?.dataSourceType ?? DataSourceType.READ_ONLY,+ ...previousCtx,+ ...payload,+ },+ });+ },++ removeDatabaseQueryContext({ database, contextId }) {+ const id = get().currentTabId;+ const tab = get().tabsById.get(id);+ if (!tab?.databaseQueryContexts?.has(database)) return undefined;+ const contexts = tab.databaseQueryContexts.get(database)!;+ const index = contexts.findIndex((c) => c.id === contextId);+ if (index < 0) return undefined;+ let next: SQLEditorDatabaseQueryContext | undefined;+ set((s) => {+ const draftTab = s.tabsById.get(id);+ if (!draftTab?.databaseQueryContexts?.has(database)) return;+ const arr = draftTab.databaseQueryContexts.get(database)!;+ arr.splice(index, 1);+ next = arr[index] ?? arr[index - 1];+ });+ return next;+ },++ batchRemoveDatabaseQueryContext({ database, contextIds }) {+ if (contextIds.length === 0) return;+ const id = get().currentTabId;+ const tab = get().tabsById.get(id);+ if (!tab?.databaseQueryContexts?.has(database)) return;+ const target = new Set(contextIds);+ set((s) => {+ const draftTab = s.tabsById.get(id);+ if (!draftTab?.databaseQueryContexts?.has(database)) return;+ const existing = draftTab.databaseQueryContexts.get(database)!;+ const filtered = existing.filter((c) => !target.has(c.id));+ if (filtered.length !== existing.length) {+ draftTab.databaseQueryContexts.set(database, filtered);+ }+ });+ },++ deleteDatabaseQueryContext(database) {+ const id = get().currentTabId;+ const tab = get().tabsById.get(id);+ if (!tab?.databaseQueryContexts?.has(database)) return;+ set((s) => {+ const draftTab = s.tabsById.get(id);+ draftTab?.databaseQueryContexts?.delete(database);+ });+ },++ updateDatabaseQueryContext({ database, contextId, context }) {+ // Resolve the tab that OWNS this context by its globally-unique id+ // rather than assuming `currentTabId`. A query that completes after+ // the user switches tabs must still update its own tab's context —+ // the Vue original mutated the reactive context object directly,+ // which had the same cross-tab effect; immer freezes store objects+ // so React must route through this action, hence the lookup.+ const owner = locateDatabaseQueryContext(+ get().tabsById,+ database,+ contextId+ );+ if (!owner) return undefined;+ set((s) => {+ const target = s.tabsById+ .get(owner.tabId)+ ?.databaseQueryContexts?.get(database)?.[owner.index];+ if (!target) return;+ Object.assign(target, context);+ });+ return get()+ .tabsById.get(owner.tabId)+ ?.databaseQueryContexts?.get(database)?.[owner.index];+ },++ async initProject(project) {+ // Dedupe concurrent inits for the same project. During bootstrap+ // the editor-state subscriber fires a fire-and-forget initProject+ // while SQLEditorRouteShell separately awaits initProject and then+ // opens the URL route tab. Sharing one in-flight hydration prevents+ // the unawaited copy from resolving afterwards and replacing+ // `tabsById` — which would drop the just-opened route tab.+ if (_initProjectInFlight?.project === project) {+ return _initProjectInFlight.promise;+ }+ const promise = hydrateProjectTabs(project);+ _initProjectInFlight = { project, promise };+ try {+ await promise;+ } finally {+ if (_initProjectInFlight?.project === project) {+ _initProjectInFlight = undefined;+ }+ }+ },++ reset() {+ set((s) => {+ s.tabsById = new Map();+ s.openTmpTabList = [];+ s.currentTabId = "";+ });+ },+ }))+);++// Tracks an in-flight `initProject` so concurrent callers share one+// hydration (see the dedupe note in the action above).+let _initProjectInFlight:+ | { project: string; promise: Promise<void> }+ | undefined;++// Hydrates the persisted tabs for a project and commits them to the+// store. Extracted from the `initProject` action so the action can wrap+// it with in-flight dedup; uses the store's external setState/getState+// (immer-enabled) rather than the action closure's set/get.+const hydrateProjectTabs = async (project: string): Promise<void> => {+ await migrateDraftsFromCache(project);+ migrateTabViewState(project);++ let email = "";+ try {+ email = useCurrentUserV1()?.value?.email ?? "";+ } catch {+ email = "";+ }++ const storedTabs = readOpenTabs(project, email);+ const worksheetStore = useWorkSheetStore();++ const hydratedTabs: SQLEditorTab[] = [];+ const validPersistent: PersistentTab[] = [];+ const seen = new Set<string>();++ for (const persisted of storedTabs) {+ if (seen.has(persisted.id)) continue;+ if (!persisted.worksheet) continue;++ const worksheet = await worksheetStore.getOrFetchWorksheetByName(+ persisted.worksheet,+ true+ );+ if (!worksheet) continue;++ const statement = getSheetStatement(worksheet);+ const connection = await extractWorksheetConnection(worksheet);++ const fullTab: SQLEditorTab = {+ ...defaultSQLEditorTab(),+ ...omitBy(persisted, isUndefined),+ connection,+ worksheet: worksheet.name,+ title: worksheet.title,+ statement,+ status: "CLEAN",+ databaseQueryContexts: undefined,+ };++ seen.add(persisted.id);+ validPersistent.push(persisted);+ hydratedTabs.push(fullTab);+ }++ useSQLEditorTabsStore.setState({+ tabsById: new Map(hydratedTabs.map((t) => [t.id, t])),+ openTmpTabList: validPersistent,+ currentTabId: head(validPersistent)?.id ?? "",+ });++ persistOpenTabs(validPersistent);+ persistCurrentTabId(useSQLEditorTabsStore.getState().currentTabId);+};++// Locates the tab + index owning a query context. Context ids are+// globally unique (uuid), so a context is found regardless of which tab+// is currently active — this is what lets an async query that completes+// after the user switched tabs still resolve to its own tab.+const locateDatabaseQueryContext = (+ tabsById: Map<string, SQLEditorTab>,+ database: string,+ contextId: string+): { tabId: string; index: number } | undefined => {+ for (const [tabId, tab] of tabsById) {+ const arr = tab.databaseQueryContexts?.get(database);+ if (!arr) continue;+ const index = arr.findIndex((c) => c.id === contextId);+ if (index >= 0) return { tabId, index };+ }+ return undefined;+};++const upsertOpenTabDraft = (+ state: { openTmpTabList: PersistentTab[]; currentTabId: string },+ tab: SQLEditorTab,+ beside: boolean+) => {+ const persistent = pick(tab, ...PERSISTENT_TAB_FIELDS) as PersistentTab;+ const position = state.openTmpTabList.findIndex((item) => item.id === tab.id);+ if (position >= 0) {+ Object.assign(state.openTmpTabList[position], persistent);+ return;+ }+ const currentPosition = state.openTmpTabList.findIndex(+ (item) => item.id === state.currentTabId+ );+ if (beside && currentPosition >= 0) {+ state.openTmpTabList.splice(currentPosition + 1, 0, persistent);+ } else {+ state.openTmpTabList.push(persistent);+ }+};++/**+ * Direct (non-React) accessor. Mirrors Zustand's `getState()`.+ */+export const getSQLEditorTabsState = (): SQLEditorTabsState =>+ useSQLEditorTabsStore.getState();++/**+ * Imperative read of the current tab. Use inside event handlers /+ * callbacks that need the tab at fire time rather than at render time.+ */+export const getCurrentSQLEditorTab = (): SQLEditorTab | undefined => {+ const s = getSQLEditorTabsState();+ return s.tabsById.get(s.currentTabId);+};++/**+ * Live read of a query context by (database, contextId) across all tabs.+ * The execute flow uses this to re-read a context after an async step+ * without assuming it still lives in the active tab.+ */+export const getDatabaseQueryContext = (+ database: string,+ contextId: string+): SQLEditorDatabaseQueryContext | undefined => {+ const owner = locateDatabaseQueryContext(+ getSQLEditorTabsState().tabsById,+ database,+ contextId+ );+ if (!owner) return undefined;+ return getSQLEditorTabsState()+ .tabsById.get(owner.tabId)+ ?.databaseQueryContexts?.get(database)?.[owner.index];+};++export const subscribeSQLEditorTabsState = (+ listener: (state: SQLEditorTabsState) => void+): (() => void) => useSQLEditorTabsStore.subscribe(listener);++/**+ * React selector hook over the tabs store.+ *+ * @example+ * const currentTabId = useSQLEditorTabState((s) => s.currentTabId);+ */+export function useSQLEditorTabState<T>(+ selector: (state: SQLEditorTabsState) => T+): T {+ return useSQLEditorTabsStore(selector);+}++// Re-hydrate tabs whenever the active project changes. Mirrors the+// historical `watch(() => project.value, initProject)` side effect of+// the legacy Vue SQL editor tab store. Errors are intentionally swallowed —+// explicit callers (e.g. SQLEditorRouteShell) own user-facing failure+// reporting and may invoke `initProject` directly with full error+// handling.+let _lastInitializedProject: string | undefined;+subscribeSQLEditorEditorState((state) => {+ if (state.project === _lastInitializedProject) return;+ _lastInitializedProject = state.project;+ if (!state.project) return;+ getSQLEditorTabsState()+ .initProject(state.project)+ .catch((err) => {+ console.debug("[sql-editor] tab auto-init failed", err);+ });+});++// Test-only helper — clears the per-module init cursor so a fresh+// `setProject(...)` re-triggers `initProject` in tests.+export const __resetTabStoreProjectCursor = () => {+ _lastInitializedProject = undefined;+ _initProjectInFlight = undefined;+};++// ---------- Derived hooks ----------++/**+ * The currently selected tab. Returns `undefined` when no tabs are+ * open. Subscribes to BOTH `currentTabId` and `tabsById` so in-place+ * mutations of the active tab propagate through React.+ */+export const useCurrentSQLEditorTab = (): SQLEditorTab | undefined =>+ useSQLEditorTabsStore((s) => s.tabsById.get(s.currentTabId));++/**+ * Live ordered list of open tabs.+ *+ * `useShallow` is required: the `.map()` produces a fresh array every+ * call, which would fail `useSyncExternalStore`'s `Object.is` snapshot+ * check and trigger an infinite re-render loop. Shallow-equal arrays+ * (same tab references in the same order) get treated as unchanged.+ *+ * Persisted entries whose hydrated tab is missing from `tabsById` are+ * dropped rather than backfilled with a fresh `defaultSQLEditorTab()`+ * — that helper synthesises a new UUID on every call, which would+ * defeat shallow-equality and re-introduce the snapshot-cache warning+ * + infinite loop whenever a tab is briefly missing during hydration.+ */+export const useOpenTabList = (): SQLEditorTab[] =>+ useSQLEditorTabsStore(+ useShallow((s) =>+ s.openTmpTabList+ .map((persisted) => s.tabsById.get(persisted.id))+ .filter((tab): tab is SQLEditorTab => tab !== undefined)+ )+ );++export const useTabById = (tabId: string): SQLEditorTab | undefined =>+ useSQLEditorTabsStore((s) => s.tabsById.get(tabId));++export const isSQLEditorTabClosable = (tab: SQLEditorTab): boolean => {+ const open = getSQLEditorTabsState().openTmpTabList;+ if (open.length > 1) return true;+ if (open.length === 1) return !!tab.worksheet;+ return false;+};++/**+ * `true` when the current tab has no valid database connection.+ */+export const useIsDisconnected = (): boolean =>+ useSQLEditorTabsStore((s) => {+ const tab = s.tabsById.get(s.currentTabId);+ if (!tab) return true;+ return !isConnectedSQLEditorTab(tab);+ });++/**+ * Batch query mode flags. Derived from current tab + feature gates.+ */+export const useSupportBatchMode = (): boolean =>+ useSQLEditorTabsStore((s) => {+ const tab = s.tabsById.get(s.currentTabId);+ return tab?.mode !== "ADMIN";+ });++export const useIsInBatchMode = (): boolean =>+ useSQLEditorTabsStore((s) => {+ const tab = s.tabsById.get(s.currentTabId);+ if (!tab) return false;+ if (tab.mode === "ADMIN") return false;+ if (!hasFeature(PlanFeature.FEATURE_BATCH_QUERY)) return false;+ const ctx = tab.batchQueryContext;+ if (!ctx) return false;+ const { databaseGroups = [], databases = [] } = ctx;+ if (!hasFeature(PlanFeature.FEATURE_DATABASE_GROUPS)) {+ return databases.length > 1;+ }+ return databaseGroups.length > 0 || databases.length > 1;+ });diff --git a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts b/frontend/src/react/stores/sqlEditor/webTerminal-service.tsindex 27f52aa09f..60e136bcbb 100644--- a/frontend/src/react/stores/sqlEditor/webTerminal-service.ts+++ b/frontend/src/react/stores/sqlEditor/webTerminal-service.ts@@ -4,13 +4,11 @@ import Emittery from "emittery";import { cloneDeep } from "lodash-es";import type { Subscription } from "rxjs";import { fromEventPattern, Observable } from "rxjs";-import { markRaw, ref } from "vue";import { refreshTokens } from "@/connect/refreshToken";import {type CancelableTimer,createCancelableTimer,} from "@/react/lib/cancelableTimer";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";import { pushNotification, useDatabaseV1Store } from "@/store";import type {SQLEditorQueryParams,@@ -34,6 +32,7 @@ import {getErrorCode as extractGrpcStatusCode,} from "@/utils/connect";import { sqlEditorEvents } from "@/views/sql-editor/events";+import { getSQLEditorEditorState } from "./editor";import { useSQLEditorStore as useSQLEditorReactStore } from "./index";const ENDPOINT = "/v1:adminExecute";@@ -45,7 +44,7 @@ const QUERY_TIMEOUT_MS = 5000;* fields are framework-agnostic mutable services (Emittery / RxJS /* `createCancelableTimer`); the query items themselves live in the zustand* `webTerminalQueryItemsByTabId` slice so React consumers re-render via- * selectors instead of `useVueState` on a Vue ref.+ * selectors instead of a Vue-bridge call on a Vue ref.*/export interface WebTerminalQuerySession {tab: SQLEditorTab;@@ -77,17 +76,24 @@ export const disposeWebTerminalQuerySession = (tabId: string): void => {};const createStreamingQueryController = () => {- const status: StreamingQueryController["status"] = ref("DISCONNECTED");- const events: StreamingQueryController["events"] = markRaw(new Emittery());+ // Plain string status — no external consumer subscribes to changes;+ // the impl reads it synchronously and the events emitter carries the+ // user-visible state transitions.+ let status: "CONNECTED" | "DISCONNECTED" = "DISCONNECTED";+ const events: StreamingQueryController["events"] = new Emittery();const input$ = fromEventPattern<SQLEditorQueryParams>((handler) => events.on("query", handler),(handler) => events.off("query", handler));- const $ws = ref<WebSocket>();+ // Holds the active WebSocket reference. Only written, never read —+ // the subscriptions inside `connect()` are what keep the socket alive+ // and reactive. Kept as a named binding to match the historical+ // pattern and make the lifecycle obvious to readers.+ let _ws: WebSocket | undefined;const controller: StreamingQueryController = {- status,+ getStatus: () => status,events,abort() {// noop here. will be overwritten after connected@@ -98,11 +104,11 @@ const createStreamingQueryController = () => {const request = mapRequest(params);console.debug("query", request);- if (status.value === "DISCONNECTED") {+ if (status === "DISCONNECTED") {// Refresh the access-token cookie before opening a new WebSocket.// The cookie may have expired since the last connection closed.await refreshTokens().catch(() => {});- $ws.value = connect(request);+ _ws = connect(request);}});@@ -114,7 +120,7 @@ const createStreamingQueryController = () => {const url = new URL(`${window.location.origin}${ENDPOINT}`);url.protocol = url.protocol.replace(/^http/, "ws");const ws = new WebSocket(url);- status.value = "CONNECTED";+ status = "CONNECTED";const send = (request: AdminExecuteRequest) => {const payload = toJson(AdminExecuteRequestSchema, request);@@ -209,7 +215,7 @@ const createStreamingQueryController = () => {}events.emit("result", result);- status.value = "DISCONNECTED";+ status = "DISCONNECTED";},});@@ -272,7 +278,7 @@ const bindStreamingLogic = (session: WebTerminalQuerySession) => {useSQLEditorReactStore.getState().mergeLatest({- project: useSQLEditorVueState().project,+ project: getSQLEditorEditorState().project,database,}).catch(() => {diff --git a/frontend/src/react/stores/sqlEditor/worksheet.ts b/frontend/src/react/stores/sqlEditor/worksheet.tsindex e36fb8c012..4b9facb77b 100644--- a/frontend/src/react/stores/sqlEditor/worksheet.ts+++ b/frontend/src/react/stores/sqlEditor/worksheet.ts@@ -1,6 +1,5 @@import { create } from "@bufbuild/protobuf";import { isUndefined } from "lodash-es";-import { nextTick } from "vue";import { isValidProjectName } from "@/types";import {type Worksheet,@@ -10,13 +9,14 @@ import {import { extractWorksheetConnection } from "@/utils";import { sqlEditorEvents } from "@/views/sql-editor/events";import { openWorksheetByName } from "@/views/sql-editor/Sheet";+import { getSQLEditorEditorState } from "./editor";+import { getSQLEditorTabsState } from "./tab";import type { SQLEditorSliceCreator, WorksheetSaveSlice } from "./types";-// Avoid static imports of Pinia stores (`useSQLEditorVueState`,-// `useSQLEditorTabStore`, `useProjectV1Store`, ...) because the Pinia-// store barrel transitively re-imports `@/react/stores/sqlEditor` —-// loading them at module evaluation creates a TDZ cycle. The slice-// pulls them in at call time via the helper below.+// Pinia store barrel transitively re-imports `@/react/stores/sqlEditor`,+// so we still pull the Pinia bits in at call time via the helpers below+// to avoid a TDZ cycle. The new Zustand editor / tab stores are local+// to this module's directory and safe to import statically.const importStores = () => import("@/store");const importProjectIamPolicyStore = () =>import("@/store/modules/v1/projectIamPolicy");@@ -40,12 +40,11 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<maybeSwitchProject: async (projectName) => {const { useProjectV1Store } = await importStores();const { useProjectIamPolicyStore } = await importProjectIamPolicyStore();- const { useSQLEditorVueState } = await import("./editor-vue-state");- const editorStore = useSQLEditorVueState();+ const editorStore = getSQLEditorEditorState();const projectStore = useProjectV1Store();const projectIamPolicyStore = useProjectIamPolicyStore();- editorStore.projectContextReady = false;+ editorStore.setProjectContextReady(false);try {if (!isValidProjectName(projectName)) {return;@@ -61,7 +60,7 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<} catch {// ignore} finally {- editorStore.projectContextReady = true;+ getSQLEditorEditorState().setProjectContextReady(true);}},@@ -75,8 +74,7 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<signal,}) => {const { useWorkSheetStore } = await importStores();- const { useSQLEditorTabStore } = await import("./tab-vue-state");- const tabStore = useSQLEditorTabStore();+ const tabStore = getSQLEditorTabsState();const worksheetStore = useWorkSheetStore();const connection = await extractWorksheetConnection({ database });@@ -134,10 +132,8 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<database = "",}) => {const { useWorkSheetStore } = await importStores();- const { useSQLEditorVueState } = await import("./editor-vue-state");- const { useSQLEditorTabStore } = await import("./tab-vue-state");- const editorStore = useSQLEditorVueState();- const tabStore = useSQLEditorTabStore();+ const editorStore = getSQLEditorEditorState();+ const tabStore = getSQLEditorTabsState();const worksheetStore = useWorkSheetStore();const worksheetTitle = title ?? "";@@ -177,7 +173,7 @@ export const createWorksheetSaveSlice: SQLEditorSliceCreator<worksheet: newWorksheet.name,forceNewTab: true,});- nextTick(() => {+ queueMicrotask(() => {if (tab && !tab.connection?.database) {// The zustand store itself owns the UI-state slice, so we can// call the action directly through `get()` (avoids thediff --git a/frontend/src/store/cache.ts b/frontend/src/store/cache.tsindex 47a6cb202b..c94a124d74 100644--- a/frontend/src/store/cache.ts+++ b/frontend/src/store/cache.ts@@ -20,6 +20,29 @@ const ENTITY_CACHE = new Map<Map<string, EntityCacheEntry<KeyType[], unknown>>>();+type NamespaceSubscription = {+ version: number;+ listeners: Set<() => void>;+};+const SUBSCRIPTIONS = new Map<string, NamespaceSubscription>();++const getSubscription = (namespace: string): NamespaceSubscription => {+ let sub = SUBSCRIPTIONS.get(namespace);+ if (!sub) {+ sub = { version: 0, listeners: new Set() };+ SUBSCRIPTIONS.set(namespace, sub);+ }+ return sub;+};++const notify = (namespace: string) => {+ const sub = getSubscription(namespace);+ sub.version++;+ for (const listener of sub.listeners) {+ listener();+ }+};+export const useCache = <K extends KeyType[], T>(namespace: string) => {const requestCacheMap = getRequestCacheMap<K, T>(namespace);const entityCacheMap = getEntityCacheMap<K, T>(namespace);@@ -72,12 +95,10 @@ export const useCache = <K extends KeyType[], T>(namespace: string) => {promise,abortController,});- // trace("setRequest", keys);};const getEntity = (keys: K) => {const key = getKey(keys);- // trace("getEntity", keys, entityCacheMap.has(key));return entityCacheMap.get(key)?.entity;};@@ -87,27 +108,42 @@ export const useCache = <K extends KeyType[], T>(namespace: string) => {keys,entity,});- // trace("setEntity", keys);+ notify(namespace);};const invalidateEntity = (keys: K) => {invalidateRequest(keys);const key = getKey(keys);- entityCacheMap.delete(key);+ const existed = entityCacheMap.delete(key);+ if (existed) {+ notify(namespace);+ }};const clear = () => {- // abort and invalidate all flying requestsfor (const request of requestCacheMap.values()) {if (!request.abortController.signal.aborted) {request.abortController.abort();}}- // clear all cache entries+ const hadEntities = entityCacheMap.size > 0;requestCacheMap.clear();entityCacheMap.clear();+ if (hadEntities) {+ notify(namespace);+ }};+ const subscribe = (listener: () => void) => {+ const sub = getSubscription(namespace);+ sub.listeners.add(listener);+ return () => {+ sub.listeners.delete(listener);+ };+ };++ const getVersion = () => getSubscription(namespace).version;+return {requestCacheMap,entityCacheMap,@@ -118,6 +154,8 @@ export const useCache = <K extends KeyType[], T>(namespace: string) => {invalidateRequest,invalidateEntity,clear,+ subscribe,+ getVersion,};};diff --git a/frontend/src/store/modules/v1/worksheet.ts b/frontend/src/store/modules/v1/worksheet.tsindex 9fec1e3f00..5c683abd7e 100644--- a/frontend/src/store/modules/v1/worksheet.ts+++ b/frontend/src/store/modules/v1/worksheet.ts@@ -5,7 +5,6 @@ import { defineStore } from "pinia";import { computed } from "vue";import { worksheetServiceClientConnect } from "@/connect";import { silentContextKey } from "@/connect/context-key";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";import { useCache } from "@/store/cache";import { UNKNOWN_ID } from "@/types";import type {@@ -23,15 +22,9 @@ import {WorksheetOrganizerSchema,WorksheetSchema,} from "@/types/proto-es/v1/worksheet_service_pb";-import {- extractWorksheetID,- getSheetStatement,- getStatementSize,- isWorksheetWritableV1,-} from "@/utils";+import { extractWorksheetID } from "@/utils";import { useUserStore } from "../user";import { useCurrentUserV1 } from "./auth";-import { extractUserEmail } from "./common";import { useDatabaseV1Store } from "./database";import { useProjectV1Store } from "./project";@@ -299,46 +292,3 @@ export const useWorkSheetStore = defineStore("worksheet_v1", () => {batchUpsertWorksheetOrganizers,};});--export const useWorkSheetAndTabStore = defineStore("worksheet_and_tab", () => {- const tabStore = useSQLEditorTabStore();- const worksheetStore = useWorkSheetStore();- const me = useCurrentUserV1();-- const currentWorksheet = computed(() => {- const tab = tabStore.currentTab;- if (!tab) {- return undefined;- }- const { worksheet } = tab;- if (!worksheet) {- return undefined;- }- return worksheetStore.getWorksheetByName(worksheet);- });-- const isCreator = computed(() => {- const worksheet = currentWorksheet.value;- if (!worksheet) return false;- return extractUserEmail(worksheet.creator) === me.value.email;- });-- const isReadOnly = computed(() => {- const worksheet = currentWorksheet.value;-- // We don't have a selected sheet, we've got nothing to edit.- if (!worksheet) {- return false;- }-- // Incomplete sheets should be read-only. e.g. 100MB sheet from issue task.、- const statement = getSheetStatement(worksheet);- if (getStatementSize(statement) !== worksheet.contentSize) {- return true;- }-- return !isWorksheetWritableV1(worksheet);- });-- return { currentSheet: currentWorksheet, isCreator, isReadOnly };-});diff --git a/frontend/src/types/v1/webTerminal.ts b/frontend/src/types/v1/webTerminal.tsindex 2d226365d7..21a5808d5d 100644--- a/frontend/src/types/v1/webTerminal.ts+++ b/frontend/src/types/v1/webTerminal.ts@@ -1,5 +1,4 @@import type Emittery from "emittery";-import type { ComputedRef, Ref } from "vue";import type { SQLEditorQueryParams, SQLEditorTab } from "../sqlEditor";import type { SQLResultSetV1 } from "./sql";@@ -29,8 +28,8 @@ export type WebTerminalQueryItemV1 = {type QueryTimer = {start(): void;stop(): void;- elapsedMS: ComputedRef<number>;- expired: ComputedRef<boolean>;+ elapsedMS(): number;+ expired(): boolean;};type QueryEvents = Emittery<{@@ -39,14 +38,15 @@ type QueryEvents = Emittery<{}>;export type StreamingQueryController = {- status: Ref<"CONNECTED" | "DISCONNECTED">;+ /** Read the current connection status. Updated in place by the impl. */+ getStatus(): "CONNECTED" | "DISCONNECTED";events: QueryEvents;abort(reason?: unknown): void;};export type WebTerminalQueryState = {tab: SQLEditorTab;- queryItemList: Ref<WebTerminalQueryItemV1[]>;+ getQueryItemList(): WebTerminalQueryItemV1[];controller: StreamingQueryController;timer: QueryTimer;};diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.tsindex ee3edcfc44..1b01da55d2 100644--- a/frontend/src/views/sql-editor/Sheet/context.ts+++ b/frontend/src/views/sql-editor/Sheet/context.ts@@ -1,15 +1,23 @@-import { useDebounceFn } from "@vueuse/core";import Emittery from "emittery";-import { isEqual, orderBy } from "lodash-es";+import { enableMapSet } from "immer";+import { debounce, isEqual, orderBy, sortBy } from "lodash-es";import scrollIntoView from "scroll-into-view-if-needed";-import type { InjectionKey, Ref } from "vue";-import { computed, nextTick, ref, toRefs, watch } from "vue";+import { create, type StoreApi, type UseBoundStore } from "zustand";+import { immer } from "zustand/middleware/immer";+import { useShallow } from "zustand/react/shallow";import { t } from "@/plugins/i18n";-import { useSQLEditorVueState } from "@/react/stores/sqlEditor/editor-vue-state";-import type { FolderContext } from "@/react/stores/sqlEditor/folder";-import { buildFolderContext } from "@/react/stores/sqlEditor/folder";-import { useSQLEditorTabStore } from "@/react/stores/sqlEditor/tab-vue-state";+import {+ getSQLEditorEditorState,+ subscribeSQLEditorEditorState,+ useSQLEditorEditorStore,+} from "@/react/stores/sqlEditor/editor";+import {+ getSQLEditorTabsState,+ subscribeSQLEditorTabsState,+ useSQLEditorTabsStore,+} from "@/react/stores/sqlEditor/tab";import { pushNotification, useCurrentUserV1, useWorkSheetStore } from "@/store";+import { useCache } from "@/store/cache";import type { SQLEditorTab, SQLEditorTabMode } from "@/types";import { DEBOUNCE_SEARCH_DELAY } from "@/types";import {@@ -21,14 +29,16 @@ import {getSheetStatement,isWorksheetReadableV1,storageKeySqlEditorWorksheetFilter,+ storageKeySqlEditorWorksheetFolder,storageKeySqlEditorWorksheetTree,- useDynamicLocalStorage,} from "@/utils";-import type { SheetViewMode } from "./types";+import { type SheetViewMode, SheetViewModeList } from "./types";-// ---- public types -----------------------------------------------------------+// Worksheet caches, folder sets, and the sheet-tree contain Map / Set+// values that immer needs to draft directly via mutation.+enableMapSet();-export type { FolderContext };+// ---- public types ----------------------------------------------------------export interface WorksheetLikeItem {name: string;@@ -56,474 +66,1012 @@ export interface WorksheetFilter {showDraft: boolean;}+export interface FolderContext {+ rootPath: string;+ folders: string[];+ listSubFolders: (parent: string) => string[];+ ensureFolderPath: (path: string) => string;+ addFolder: (path: string) => string;+ removeFolder: (path: string) => void;+ moveFolder: (from: string, to: string) => void;+ mergeFolders: (paths: Set<string>) => void;+ isSubFolder: (args: {+ parent: string;+ path: string;+ dig: boolean;+ }) => boolean;+}+type SheetTreeEvents = Emittery<{"on-built": { viewMode: SheetViewMode };}>;-// ---- per-view tree context --------------------------------------------------+export interface ViewContext {+ isLoading: boolean;+ isInitialized: boolean;+ sheetTree: WorksheetFolderNode;+ folderTree: WorksheetFolderNode;+ folderContext: FolderContext;+ events: SheetTreeEvents;+ fetchSheetList: () => Promise<void>;+ rebuildTree: () => void;+ getKeyForWorksheet: (worksheet: WorksheetLikeItem) => string;+ getFoldersForWorksheet: (path: string) => string[];+ getPathesForWorksheet: (worksheet: { folders: string[] }) => string[];+ getPwdForWorksheet: (worksheet: { folders: string[] }) => string;+}-const convertToWorksheetLikeItem = (- worksheet: Worksheet-): WorksheetLikeItem => ({- name: worksheet.name,- title: worksheet.title,- folders: worksheet.folders,- type: "worksheet",-});+// ---- internal Zustand store -------------------------------------------------const buildViewContext = (- viewMode: SheetViewMode,- filterRef: Ref<WorksheetFilter>-) => {- const sheetStore = useWorkSheetStore();- const folderContext = buildFolderContext(viewMode);- const me = useCurrentUserV1();- const events: SheetTreeEvents = new Emittery();- const tabStore = useSQLEditorTabStore();- const { project } = toRefs(useSQLEditorVueState());+const INITIAL_FILTER: WorksheetFilter = {+ keyword: "",+ showShared: true,+ showMine: true,+ showDraft: true,+ onlyShowStarred: false,+};- const isInitialized = ref(false);- const isLoading = ref(false);+interface ViewState {+ isLoading: boolean;+ isInitialized: boolean;+ sheetTree: WorksheetFolderNode;+ folders: string[];+}- const rootNodeLabel = computed(() => {- switch (viewMode) {- case "my":- return t("sheet.mine");- case "shared":- return t("sheet.shared");- case "draft":- return t("common.draft");- default:- return "";- }- });+interface SheetContextState {+ filter: WorksheetFilter;+ expandedKeys: Set<string>;+ selectedKeys: string[];+ editingNode: { node: WorksheetFolderNode; rawLabel: string } | undefined;+ view: SheetViewMode;+ viewStates: Record<SheetViewMode, ViewState>;++ setFilter: (+ next: WorksheetFilter | ((prev: WorksheetFilter) => WorksheetFilter)+ ) => void;+ setView: (view: SheetViewMode) => void;+ setExpandedKeys: (+ next: Set<string> | ((prev: Set<string>) => Set<string>)+ ) => void;+ setSelectedKeys: (next: string[]) => void;+ setEditingNode: (+ next: { node: WorksheetFolderNode; rawLabel: string } | undefined+ ) => void;+ setViewIsLoading: (view: SheetViewMode, loading: boolean) => void;+ setViewIsInitialized: (view: SheetViewMode, initialized: boolean) => void;+ setViewSheetTree: (view: SheetViewMode, tree: WorksheetFolderNode) => void;+ setViewFolders: (view: SheetViewMode, folders: string[]) => void;+ /** Replace the entire state (used by project / user-scope reload). */+ hydrate: (next: Partial<SheetContextState>) => void;+}- const getRootTreeNode = (): WorksheetFolderNode => ({- isLeaf: false,- children: [],- key: folderContext.rootPath.value,- label: rootNodeLabel.value,- editable: false,- });+const rootPathFor = (view: SheetViewMode) => `/${view}`;- const sheetTree = ref<WorksheetFolderNode>(getRootTreeNode());+const emptyRootNode = (view: SheetViewMode): WorksheetFolderNode => ({+ key: rootPathFor(view),+ label: "",+ editable: false,+ isLeaf: false,+ children: [],+});- const worksheetList = computed((): Worksheet[] => {- let list: Worksheet[] = [];- switch (viewMode) {- case "my":- list = sheetStore.myWorksheetList;- break;- case "shared":- list = sheetStore.sharedWorksheetList;- break;- default:- break;- }- list = list.filter((sheet) => sheet.project === project.value);- if (filterRef.value.onlyShowStarred) {- return list.filter((sheet) => sheet.starred);- }- return list;- });+const emptyViewState = (view: SheetViewMode): ViewState => ({+ isLoading: false,+ isInitialized: false,+ sheetTree: emptyRootNode(view),+ folders: [rootPathFor(view)],+});- const sheetLikeItemList = computed((): WorksheetLikeItem[] => {- switch (viewMode) {- case "my":- case "shared":- return worksheetList.value.map(convertToWorksheetLikeItem);- case "draft":- return tabStore.openTabList- .filter((tab) => !tab.worksheet)- .map((tab) => ({- name: tab.id,- title: tab.title,- folders: [],- type: "draft" as const,- }));- default:- return [];- }- });+const initialViewStates: Record<SheetViewMode, ViewState> = {+ my: emptyViewState("my"),+ shared: emptyViewState("shared"),+ draft: emptyViewState("draft"),+};- const getPathesForWorksheet = (worksheet: {- folders: string[];- }): string[] => {- const pathes = [folderContext.rootPath.value];- let currentPath = folderContext.rootPath.value;- for (const folder of worksheet.folders) {- currentPath = folderContext.ensureFolderPath(`${currentPath}/${folder}`);- pathes.push(currentPath);- }- return pathes;- };+const useSheetContextStore: UseBoundStore<StoreApi<SheetContextState>> =+ create<SheetContextState>()(+ immer((set) => ({+ filter: { ...INITIAL_FILTER },+ expandedKeys: new Set<string>([+ rootPathFor("my"),+ rootPathFor("shared"),+ rootPathFor("draft"),+ ]),+ selectedKeys: [],+ editingNode: undefined,+ view: "my",+ viewStates: initialViewStates,++ setFilter(next) {+ set((s) => {+ s.filter = typeof next === "function" ? next(s.filter) : next;+ });+ },+ setView(view) {+ set((s) => {+ s.view = view;+ });+ },+ setExpandedKeys(next) {+ set((s) => {+ s.expandedKeys =+ typeof next === "function" ? next(s.expandedKeys) : next;+ });+ },+ setSelectedKeys(next) {+ set((s) => {+ s.selectedKeys = next;+ });+ },+ setEditingNode(next) {+ set((s) => {+ s.editingNode = next;+ });+ },+ setViewIsLoading(view, loading) {+ set((s) => {+ s.viewStates[view].isLoading = loading;+ });+ },+ setViewIsInitialized(view, initialized) {+ set((s) => {+ s.viewStates[view].isInitialized = initialized;+ });+ },+ setViewSheetTree(view, tree) {+ set((s) => {+ s.viewStates[view].sheetTree = tree;+ });+ },+ setViewFolders(view, folders) {+ set((s) => {+ s.viewStates[view].folders = folders;+ });+ },+ hydrate(next) {+ set((s) => {+ Object.assign(s, next);+ });+ },+ }))+ );- const getPwdForWorksheet = (worksheet: { folders: string[] }): string => {- return folderContext.ensureFolderPath(worksheet.folders.join("/"));- };+// Handle to the worksheet store's cache namespace. `useCache` keys its+// listener registry + entity maps by namespace string, so this resolves+// to the SAME cache the Pinia worksheet store writes to — letting us+// subscribe to worksheet mutations (fetch / patch / delete) without+// importing the store's internal closure. Namespace must match+// `store/modules/v1/worksheet.ts`.+const worksheetCache = useCache("bb.worksheet.by-uid");++// ---- localStorage persistence ----------------------------------------------++const safeReadJSON = <T>(+ key: string,+ parse: (raw: unknown) => T | undefined+): T | undefined => {+ if (typeof window === "undefined") return undefined;+ try {+ const raw = window.localStorage.getItem(key);+ if (raw === null) return undefined;+ return parse(JSON.parse(raw));+ } catch {+ return undefined;+ }+};- const getKeyForWorksheet = (worksheet: WorksheetLikeItem): string => {- return [- getPwdForWorksheet(worksheet),- `bytebase-${worksheet.type}-${worksheet.name.split("/").slice(-1)[0]}.sql`,- ].join("/");- };+const safeWriteJSON = (key: string, value: unknown) => {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(key, JSON.stringify(value));+ } catch {+ // Ignore quota / serialization errors.+ }+};- const getFoldersForWorksheet = (path: string): string[] => {- const pathes = path.replace(folderContext.rootPath.value, "").split("/");- if (pathes.slice(-1)[0].endsWith(".sql")) {- pathes.pop();- }- return pathes.map((p) => p.trim()).filter((p) => p);- };+const currentScope = (): { project: string; email: string } | null => {+ const project = getSQLEditorEditorState().project;+ if (!project) return null;+ try {+ const me = useCurrentUserV1();+ return { project, email: me?.value?.email ?? "" };+ } catch {+ return null;+ }+};- const buildTree = (- parent: WorksheetFolderNode,- worksheetsByFolder: Map<string, WorksheetLikeItem[]>,- hideEmpty: boolean- ) => {- const subfolders = folderContext- .listSubFolders(parent.key)- .map((folder) => ({- isLeaf: false,- children: [],- key: folder,- label: folder.split("/").slice(-1)[0],- editable: true,- }));+const isWorksheetFilter = (v: unknown): v is WorksheetFilter =>+ typeof v === "object" &&+ v !== null &&+ "keyword" in v &&+ "onlyShowStarred" in v &&+ "showMine" in v &&+ "showShared" in v &&+ "showDraft" in v;++const reloadFromStorage = () => {+ const scope = currentScope();+ if (!scope) return;++ const filter = safeReadJSON(+ storageKeySqlEditorWorksheetFilter(scope.project, scope.email),+ (v) => (isWorksheetFilter(v) ? v : undefined)+ ) ?? { ...INITIAL_FILTER };++ const expandedArray = safeReadJSON<string[]>(+ storageKeySqlEditorWorksheetTree(scope.project, scope.email),+ (v) =>+ Array.isArray(v) && v.every((entry) => typeof entry === "string")+ ? (v as string[])+ : undefined+ );+ const expandedKeys = expandedArray+ ? new Set(expandedArray)+ : new Set<string>([+ rootPathFor("my"),+ rootPathFor("shared"),+ rootPathFor("draft"),+ ]);+ expandedKeys.add(rootPathFor("my"));+ expandedKeys.add(rootPathFor("shared"));+ expandedKeys.add(rootPathFor("draft"));++ const viewStates: Record<SheetViewMode, ViewState> = {+ my: emptyViewState("my"),+ shared: emptyViewState("shared"),+ draft: emptyViewState("draft"),+ };- let empty = true;- for (const childNode of subfolders) {- const subtree = buildTree(childNode, worksheetsByFolder, hideEmpty);- if (!subtree.empty || !hideEmpty) {- parent.children.push(subtree);- }- if (!subtree.empty) {- empty = false;- }- }+ for (const view of ["my", "shared", "draft"] as const) {+ const folders = safeReadJSON<string[]>(+ storageKeySqlEditorWorksheetFolder(scope.project, view, scope.email),+ (v) =>+ Array.isArray(v) && v.every((entry) => typeof entry === "string")+ ? (v as string[])+ : undefined+ );+ const set = new Set(folders ?? []);+ set.add(rootPathFor(view));+ viewStates[view].folders = sortBy([...set]);+ }- const sheets = orderBy(- worksheetsByFolder.get(parent.key) || [],- (item) => item.title- ).map((worksheet) => ({- isLeaf: true,- key: getKeyForWorksheet(worksheet),- label: worksheet.title,- worksheet,- editable: true,- children: [],- }));+ useSheetContextStore.getState().hydrate({+ filter,+ expandedKeys,+ selectedKeys: [],+ editingNode: undefined,+ viewStates,+ });+};- parent.children.push(...sheets);- parent.empty = sheets.length === 0 && empty;- if (parent.key !== folderContext.rootPath.value) {- parent.isLeaf = parent.children.length === 0;- }+const persistFilter = (filter: WorksheetFilter) => {+ const scope = currentScope();+ if (!scope) return;+ safeWriteJSON(+ storageKeySqlEditorWorksheetFilter(scope.project, scope.email),+ filter+ );+};- return parent;- };+const persistExpandedKeys = (keys: Set<string>) => {+ const scope = currentScope();+ if (!scope) return;+ safeWriteJSON(storageKeySqlEditorWorksheetTree(scope.project, scope.email), [+ ...keys,+ ]);+};- const folderTree = computed(() =>- buildTree(getRootTreeNode(), new Map(), false)+const persistViewFolders = (view: SheetViewMode, folders: string[]) => {+ const scope = currentScope();+ if (!scope) return;+ safeWriteJSON(+ storageKeySqlEditorWorksheetFolder(scope.project, view, scope.email),+ folders);+};- const rebuildTree = useDebounceFn(() => {- const folderPaths = new Set<string>([]);- const worksheetsByFolder = new Map<string, WorksheetLikeItem[]>();+// ---- per-view helpers + folder context -------------------------------------- for (const worksheet of sheetLikeItemList.value) {- for (const path of getPathesForWorksheet(worksheet)) {- folderPaths.add(path);- }- const pwd = getPwdForWorksheet(worksheet);- if (!worksheetsByFolder.has(pwd)) {- worksheetsByFolder.set(pwd, []);- }- worksheetsByFolder.get(pwd)!.push(worksheet);- }+const convertToWorksheetLikeItem = (+ worksheet: Worksheet+): WorksheetLikeItem => ({+ name: worksheet.name,+ title: worksheet.title,+ folders: worksheet.folders,+ type: "worksheet",+});- folderContext.mergeFolders(folderPaths);- sheetTree.value = buildTree(- getRootTreeNode(),- worksheetsByFolder,- filterRef.value.onlyShowStarred- );- events.emit("on-built", { viewMode });- }, DEBOUNCE_SEARCH_DELAY);+const rootLabelFor = (view: SheetViewMode): string => {+ switch (view) {+ case "my":+ return t("sheet.mine");+ case "shared":+ return t("sheet.shared");+ case "draft":+ return t("common.draft");+ default:+ return "";+ }+};++const rootTreeNodeFor = (view: SheetViewMode): WorksheetFolderNode => ({+ isLeaf: false,+ children: [],+ key: rootPathFor(view),+ label: rootLabelFor(view),+ editable: false,+});- watch(- [() => folderContext.folders.value, () => sheetLikeItemList.value],- ([newFolders, newSheetList], [oldFolders, oldSheetList]) => {+const isSubFolder = ({+ parent,+ path,+ dig,+}: {+ parent: string;+ path: string;+ dig: boolean;+}) => {+ const parentPrefix = `${parent}/`;+ return path !== parentPrefix && path.startsWith(parentPrefix) && dig+ ? true+ : !path.replace(parentPrefix, "").includes("/");+};++const ensureFolderPath = (view: SheetViewMode, path: string): string => {+ const root = rootPathFor(view);+ let p = path+ .split("/")+ .map((seg) => seg.trim())+ .filter((seg) => seg)+ .join("/");+ if (!p) return root;+ if (!p.startsWith("/")) p = `/${p}`;+ if (!p.startsWith(root)) p = `${root}${p}`;+ return p;+};++const buildFolderContext = (view: SheetViewMode): FolderContext => {+ const rootPath = rootPathFor(view);++ return {+ get rootPath() {+ return rootPath;+ },+ get folders() {+ return useSheetContextStore.getState().viewStates[view].folders;+ },+ listSubFolders(parent) {+ return useSheetContextStore+ .getState()+ .viewStates[view].folders.filter((path) =>+ isSubFolder({ parent, path, dig: false })+ );+ },+ ensureFolderPath(path) {+ return ensureFolderPath(view, path);+ },+ addFolder(path) {+ const newPath = ensureFolderPath(view, path);+ const current = useSheetContextStore.getState().viewStates[view].folders;+ const set = new Set(current);+ set.add(newPath);+ const next = sortBy([...set]);+ useSheetContextStore.getState().setViewFolders(view, next);+ persistViewFolders(view, next);+ return newPath;+ },+ removeFolder(path) {+ const current = useSheetContextStore.getState().viewStates[view].folders;+ const next = current.filter(+ (value) =>+ !(+ value === path ||+ isSubFolder({ parent: path, path: value, dig: true })+ )+ );+ useSheetContextStore.getState().setViewFolders(view, next);+ persistViewFolders(view, next);+ },+ moveFolder(from, to) {+ const fromPath = ensureFolderPath(view, from);+ const toPath = ensureFolderPath(view, to);+ const current = useSheetContextStore.getState().viewStates[view].folders;+ const next = current.map((path) => {+ if (path === fromPath) return toPath;+ if (isSubFolder({ parent: fromPath, path, dig: true })) {+ return path.replace(fromPath, toPath);+ }+ return path;+ });+ const deduped = sortBy([...new Set(next)]);+ useSheetContextStore.getState().setViewFolders(view, deduped);+ persistViewFolders(view, deduped);+ },+ mergeFolders(paths) {+ const current = useSheetContextStore.getState().viewStates[view].folders;+ const set = new Set(current);+ for (const folder of paths.values()) {+ set.add(ensureFolderPath(view, folder));+ }+ const next = sortBy([...set]);if (- isEqual(newFolders, oldFolders) &&- isEqual(newSheetList, oldSheetList)+ next.length !== current.length ||+ !next.every((p, i) => current[i] === p)) {- return;- }- rebuildTree();- }- );-- const fetchSheetList = async () => {- isLoading.value = true;- try {- switch (viewMode) {- case "my":- await sheetStore.fetchWorksheetList(- project.value,- `creator == "users/${me.value.email}"`- );- break;- case "shared":- await sheetStore.fetchWorksheetList(- project.value,- [- `creator != "users/${me.value.email}"`,- `visibility in ["${Worksheet_Visibility[Worksheet_Visibility.PROJECT_READ]}","${Worksheet_Visibility[Worksheet_Visibility.PROJECT_WRITE]}"]`,- ].join(" && ")- );- break;- default:- break;+ useSheetContextStore.getState().setViewFolders(view, next);+ persistViewFolders(view, next);}- rebuildTree();- isInitialized.value = true;- } finally {- isLoading.value = false;- }+ },+ isSubFolder,};+};- return {- events,- isInitialized,- isLoading,- sheetTree,- folderTree,- fetchSheetList,- folderContext,- getKeyForWorksheet,- getFoldersForWorksheet,- getPathesForWorksheet,- getPwdForWorksheet,- };+const folderContextCache: Partial<Record<SheetViewMode, FolderContext>> = {};+const getFolderContext = (view: SheetViewMode): FolderContext => {+ const existed = folderContextCache[view];+ if (existed) return existed;+ const ctx = buildFolderContext(view);+ folderContextCache[view] = ctx;+ return ctx;};-export type ViewContext = ReturnType<typeof buildViewContext>;+const viewEvents: Partial<Record<SheetViewMode, SheetTreeEvents>> = {};+const getEvents = (view: SheetViewMode): SheetTreeEvents => {+ const existed = viewEvents[view];+ if (existed) return existed;+ const events: SheetTreeEvents = new Emittery();+ viewEvents[view] = events;+ return events;+};-// ---- top-level singleton ----------------------------------------------------+const getPathesForWorksheet = (+ view: SheetViewMode,+ worksheet: { folders: string[] }+): string[] => {+ const folderContext = getFolderContext(view);+ const pathes = [folderContext.rootPath];+ let currentPath = folderContext.rootPath;+ for (const folder of worksheet.folders) {+ currentPath = folderContext.ensureFolderPath(`${currentPath}/${folder}`);+ pathes.push(currentPath);+ }+ return pathes;+};-const INITIAL_FILTER: WorksheetFilter = {- keyword: "",- showShared: true,- showMine: true,- showDraft: true,- onlyShowStarred: false,+const getPwdForWorksheet = (+ view: SheetViewMode,+ worksheet: { folders: string[] }+): string =>+ getFolderContext(view).ensureFolderPath(worksheet.folders.join("/"));++const getKeyForWorksheet = (+ view: SheetViewMode,+ worksheet: WorksheetLikeItem+): string =>+ [+ getPwdForWorksheet(view, worksheet),+ `bytebase-${worksheet.type}-${worksheet.name.split("/").slice(-1)[0]}.sql`,+ ].join("/");++const getFoldersForWorksheet = (+ view: SheetViewMode,+ path: string+): string[] => {+ const root = getFolderContext(view).rootPath;+ const segs = path.replace(root, "").split("/");+ if (segs.slice(-1)[0]?.endsWith(".sql")) segs.pop();+ return segs.map((p) => p.trim()).filter((p) => p);};-/**- * The shared sheet-context state. Pulled out of Pinia's `defineStore`- * into a module-level lazy singleton because none of this state is- * actually shared with Vue components (all live consumers are React)- * — dropping Pinia removes the cross-framework store layer without- * needing to rewrite the Vue-reactive pipeline. The lazy singleton- * preserves "set up once, watchers stay alive" semantics that Pinia- * gave us for free.- */-const buildSheetState = () => {- const tabStore = useSQLEditorTabStore();- const me = useCurrentUserV1();- const worksheetV1Store = useWorkSheetStore();- const { project } = toRefs(useSQLEditorVueState());-- // ---- shared filter -------------------------------------------------------- const filter = useDynamicLocalStorage<WorksheetFilter>(- computed(() =>- storageKeySqlEditorWorksheetFilter(project.value, me.value.email)- ),- { ...INITIAL_FILTER }- );- const filterChanged = computed(() => !isEqual(filter.value, INITIAL_FILTER));+const buildTree = (+ view: SheetViewMode,+ parent: WorksheetFolderNode,+ worksheetsByFolder: Map<string, WorksheetLikeItem[]>,+ hideEmpty: boolean+): WorksheetFolderNode => {+ const folderContext = getFolderContext(view);+ const subfolders: WorksheetFolderNode[] = folderContext+ .listSubFolders(parent.key)+ .map((folder) => ({+ isLeaf: false,+ children: [],+ key: folder,+ label: folder.split("/").slice(-1)[0],+ editable: true,+ }));- // Safe computed ref — useDynamicLocalStorage can yield null during SSR- // or on first boot; fall back to INITIAL_FILTER so consumers always get- // a non-null WorksheetFilter.- const safeFilter = computed<WorksheetFilter>(- () => filter.value ?? { ...INITIAL_FILTER }- );+ let empty = true;+ for (const childNode of subfolders) {+ const subtree = buildTree(view, childNode, worksheetsByFolder, hideEmpty);+ if (!subtree.empty || !hideEmpty) {+ parent.children.push(subtree);+ }+ if (!subtree.empty) {+ empty = false;+ }+ }- // ---- per-view contexts (lazily initialised) ------------------------------ // Use a plain Map (not reactive) — the ViewContext objects have their own- // internal reactive state. Wrapping in reactive() would auto-unwrap refs.+ const sheets = orderBy(+ worksheetsByFolder.get(parent.key) ?? [],+ (item) => item.title+ ).map<WorksheetFolderNode>((worksheet) => ({+ isLeaf: true,+ key: getKeyForWorksheet(view, worksheet),+ label: worksheet.title,+ worksheet,+ editable: true,+ children: [],+ }));++ parent.children.push(...sheets);+ parent.empty = sheets.length === 0 && empty;+ if (parent.key !== folderContext.rootPath) {+ parent.isLeaf = parent.children.length === 0;+ }+ return parent;+};++const worksheetsForView = (view: SheetViewMode): Worksheet[] => {+ const sheetStore = useWorkSheetStore();+ const filter = useSheetContextStore.getState().filter;+ const project = getSQLEditorEditorState().project;+ let list: Worksheet[] = [];+ switch (view) {+ case "my":+ list = sheetStore.myWorksheetList;+ break;+ case "shared":+ list = sheetStore.sharedWorksheetList;+ break;+ default:+ break;+ }+ list = list.filter((sheet) => sheet.project === project);+ if (filter.onlyShowStarred) {+ return list.filter((sheet) => sheet.starred);+ }+ return list;+};++const sheetLikeItemsForView = (view: SheetViewMode): WorksheetLikeItem[] => {+ if (view === "draft") {+ const tabsState = getSQLEditorTabsState();+ return tabsState.openTmpTabList+ .map((p) => tabsState.tabsById.get(p.id))+ .filter((tab): tab is SQLEditorTab => !!tab && !tab.worksheet)+ .map((tab) => ({+ name: tab.id,+ title: tab.title,+ folders: [],+ type: "draft" as const,+ }));+ }+ return worksheetsForView(view).map(convertToWorksheetLikeItem);+};++const rebuildTreeImpl = (view: SheetViewMode) => {+ const filter = useSheetContextStore.getState().filter;+ const folderContext = getFolderContext(view);- const contexts = new Map<SheetViewMode, ViewContext>();+ const folderPaths = new Set<string>();+ const worksheetsByFolder = new Map<string, WorksheetLikeItem[]>();- const ensureContext = (view: SheetViewMode): ViewContext => {- if (!contexts.has(view)) {- contexts.set(view, buildViewContext(view, safeFilter));+ for (const worksheet of sheetLikeItemsForView(view)) {+ for (const path of getPathesForWorksheet(view, worksheet)) {+ folderPaths.add(path);}- return contexts.get(view)!;+ const pwd = getPwdForWorksheet(view, worksheet);+ if (!worksheetsByFolder.has(pwd)) worksheetsByFolder.set(pwd, []);+ worksheetsByFolder.get(pwd)!.push(worksheet);+ }++ folderContext.mergeFolders(folderPaths);++ const root: WorksheetFolderNode = {+ ...rootTreeNodeFor(view),+ label: rootLabelFor(view),+ key: folderContext.rootPath,};+ const tree = buildTree(+ view,+ root,+ worksheetsByFolder,+ filter.onlyShowStarred+ );+ useSheetContextStore.getState().setViewSheetTree(view, tree);+ getEvents(view).emit("on-built", { viewMode: view });+};- const getContextByView = (view: SheetViewMode) => ensureContext(view);+const rebuildTreeDebounced: Partial<Record<SheetViewMode, () => void>> = {};+const getRebuildTreeFn = (view: SheetViewMode): (() => void) => {+ const existed = rebuildTreeDebounced[view];+ if (existed) return existed;+ const debounced = debounce(+ () => rebuildTreeImpl(view),+ DEBOUNCE_SEARCH_DELAY+ );+ rebuildTreeDebounced[view] = debounced;+ return debounced;+};++const fetchSheetListFor = async (view: SheetViewMode) => {+ const state = useSheetContextStore.getState();+ state.setViewIsLoading(view, true);+ try {+ const sheetStore = useWorkSheetStore();+ const me = useCurrentUserV1();+ const project = getSQLEditorEditorState().project;+ switch (view) {+ case "my":+ await sheetStore.fetchWorksheetList(+ project,+ `creator == "users/${me.value.email}"`+ );+ break;+ case "shared":+ await sheetStore.fetchWorksheetList(+ project,+ [+ `creator != "users/${me.value.email}"`,+ `visibility in ["${Worksheet_Visibility[Worksheet_Visibility.PROJECT_READ]}","${Worksheet_Visibility[Worksheet_Visibility.PROJECT_WRITE]}"]`,+ ].join(" && ")+ );+ break;+ default:+ break;+ }+ rebuildTreeImpl(view);+ state.setViewIsInitialized(view, true);+ } finally {+ state.setViewIsLoading(view, false);+ }+};- // Eagerly build all three so watchers/selection logic works on startup.- const viewContexts = {- get my() {- return ensureContext("my");+const buildViewContext = (view: SheetViewMode): ViewContext => {+ const folderContext = getFolderContext(view);+ return {+ get isLoading() {+ return useSheetContextStore.getState().viewStates[view].isLoading;},- get shared() {- return ensureContext("shared");+ get isInitialized() {+ return useSheetContextStore.getState().viewStates[view].isInitialized;},- get draft() {- return ensureContext("draft");+ get sheetTree() {+ return useSheetContextStore.getState().viewStates[view].sheetTree;},+ get folderTree() {+ const root: WorksheetFolderNode = {+ ...rootTreeNodeFor(view),+ key: folderContext.rootPath,+ };+ return buildTree(view, root, new Map(), false);+ },+ folderContext,+ events: getEvents(view),+ fetchSheetList: () => fetchSheetListFor(view),+ rebuildTree: () => getRebuildTreeFn(view)(),+ getKeyForWorksheet: (ws) => getKeyForWorksheet(view, ws),+ getFoldersForWorksheet: (path) => getFoldersForWorksheet(view, path),+ getPathesForWorksheet: (ws) => getPathesForWorksheet(view, ws),+ getPwdForWorksheet: (ws) => getPwdForWorksheet(view, ws),};+};++const viewContextCache: Partial<Record<SheetViewMode, ViewContext>> = {};+const getViewContext = (view: SheetViewMode): ViewContext => {+ const existed = viewContextCache[view];+ if (existed) return existed;+ const ctx = buildViewContext(view);+ viewContextCache[view] = ctx;+ return ctx;+};++// ---- side effects (initialized lazily on first use) ------------------------- // ---- shared tree-selection state ------------------------------------------ const expandedKeys = useDynamicLocalStorage<Set<string>>(- computed(() =>- storageKeySqlEditorWorksheetTree(project.value, me.value.email)- ),- new Set([- ensureContext("my").folderContext.rootPath.value,- ensureContext("shared").folderContext.rootPath.value,- ensureContext("draft").folderContext.rootPath.value,- ])+const isWorksheetCreator = (worksheet: { creator: string }) => {+ try {+ const me = useCurrentUserV1();+ return worksheet.creator === `users/${me.value.email}`;+ } catch {+ return false;+ }+};++const batchUpdateWorksheetFolders = async (+ worksheets: { name: string; folders: string[] }[]+): Promise<void> => {+ if (worksheets.length === 0) return;+ await useWorkSheetStore().batchUpsertWorksheetOrganizers(+ worksheets.map((worksheet) => ({+ organizer: {+ worksheet: worksheet.name,+ folders: worksheet.folders,+ },+ updateMask: ["folders"],+ })));- const selectedKeys = ref<string[]>([]);-- const isWorksheetCreator = (worksheet: { creator: string }) =>- worksheet.creator === `users/${me.value.email}`;-- watch(- () => ({- tabId: tabStore.currentTab?.id,- worksheetName: tabStore.currentTab?.worksheet,- }),- async ({ tabId, worksheetName }) => {- selectedKeys.value = [];- if (!tabId) {- return;- }+};- let viewMode: SheetViewMode = "draft";- let worksheetLikeItem: WorksheetLikeItem | undefined;+let _watchersBound = false;+let _lastProject = "";+let _lastTabKey = "";+let _lastDraftSig = "";++// Signature of the draft view's source data — the open tabs that have+// no worksheet, keyed by id + title. The "draft" tree derives from+// these (see `sheetLikeItemsForView`), so the tree must rebuild when a+// draft tab is opened, closed, or renamed.+const computeDraftSignature = (+ tabsState: ReturnType<typeof getSQLEditorTabsState>+): string =>+ tabsState.openTmpTabList+ .map((persisted) => {+ const tab = tabsState.tabsById.get(persisted.id);+ if (!tab || tab.worksheet) return "";+ return `${tab.id}:${tab.title}`;+ })+ .filter((s) => s)+ .join("|");++const bindWatchers = () => {+ if (_watchersBound) return;+ _watchersBound = true;++ // Subscribe handlers immediately — these only register listeners and+ // don't mutate any store, so they're safe to invoke during a React+ // render. The initial state hydration is deferred to a microtask so+ // the calling component finishes its current render before any+ // setState lands.+ subscribeSQLEditorEditorState((state) => {+ if (state.project === _lastProject) return;+ _lastProject = state.project;+ reloadFromStorage();+ rebuildTreeImpl("my");+ rebuildTreeImpl("shared");+ rebuildTreeImpl("draft");+ });- if (worksheetName) {- const worksheet = worksheetV1Store.getWorksheetByName(worksheetName);- if (!worksheet) {- return;- }- worksheetLikeItem = {- name: worksheet.name,- title: worksheet.title,- folders: worksheet.folders,- type: "worksheet",- };- viewMode = isWorksheetCreator(worksheet) ? "my" : "shared";- } else {- worksheetLikeItem = {- name: tabId,- folders: [],- title: "",- type: "draft",- };+ useSheetContextStore.subscribe((state, prev) => {+ if (state.filter !== prev.filter) persistFilter(state.filter);+ if (state.expandedKeys !== prev.expandedKeys)+ persistExpandedKeys(state.expandedKeys);++ // Rebuild the worksheet-backed trees when `onlyShowStarred` toggles+ // — it changes both the worksheet list (`worksheetsForView` filters+ // to starred) and the `hideEmpty` pass inside `buildTree`. Mirrors+ // the Vue `watch(filter, rebuildTree)`. Keyword filtering is applied+ // component-side (SheetTree's `nodeMatches`), so it doesn't need a+ // rebuild here.+ if (state.filter.onlyShowStarred !== prev.filter.onlyShowStarred) {+ getRebuildTreeFn("my")();+ getRebuildTreeFn("shared")();+ }++ // Rebuild a view's tree when its folder set changes (add / remove /+ // move folder). Mirrors the Vue `watch(folderContext.folders,+ // rebuildTree)`. Debounced + idempotent `mergeFolders` inside the+ // rebuild keeps this from looping: the rebuild only writes folders+ // back when a worksheet introduces a brand-new path, which settles+ // after one extra pass.+ for (const view of SheetViewModeList) {+ if (state.viewStates[view].folders !== prev.viewStates[view].folders) {+ getRebuildTreeFn(view)();}+ }+ });- const viewContext = ensureContext(viewMode);- const key = viewContext.getKeyForWorksheet(worksheetLikeItem);- selectedKeys.value = [key];+ subscribeSQLEditorTabsState((tabsState) => {+ // Current-tab change → update tree selection + scroll-into-view.+ const tab = tabsState.tabsById.get(tabsState.currentTabId);+ const tabKey = `${tab?.id ?? ""}|${tab?.worksheet ?? ""}`;+ if (tabKey !== _lastTabKey) {+ _lastTabKey = tabKey;+ onCurrentTabChanged(tab);+ }- for (const path of viewContext.getPathesForWorksheet(worksheetLikeItem)) {- expandedKeys.value.add(path);- }+ // Draft-tab set / title change → rebuild the draft tree. The draft+ // view's `sheetLikeItemList` is derived from open tabs without a+ // worksheet, so adding / closing / renaming a draft must refresh it.+ // Mirrors the Vue `watch(sheetLikeItemList, rebuildTree)` for the+ // draft view context.+ const draftSig = computeDraftSignature(tabsState);+ if (draftSig !== _lastDraftSig) {+ _lastDraftSig = draftSig;+ getRebuildTreeFn("draft")();+ }+ });- await nextTick();- const dom = document.querySelector(`[data-item-key="${key}"]`);- if (dom) {- scrollIntoView(dom, {- scrollMode: "if-needed",- block: "nearest",- });- }- },- { immediate: true }- );+ // Rebuild the worksheet-backed trees whenever the worksheet cache+ // mutates — a fetch, a title patch (e.g. renamed from the editor tab),+ // a star toggle, or a delete. Mirrors the Vue+ // `watch(sheetLikeItemList, rebuildTree)` that drove the tree off the+ // worksheet list. The "draft" view is tab-derived, not worksheet-+ // derived, so it doesn't need this. Debounced rebuilds coalesce the+ // burst of cache writes a single fetch produces.+ worksheetCache.subscribe(() => {+ getRebuildTreeFn("my")();+ getRebuildTreeFn("shared")();+ });- // ---- editing node -------------------------------------------------------+ // Synchronous initial hydration. Runs once during the SQLEditorLayout+ // render via `provideSheetContext()`; descendants render AFTER this+ // and so their `useSyncExternalStore` snapshots match the already-+ // hydrated state. Deferring this to `queueMicrotask` caused the+ // snapshot to flip between render and effect-mount, which made React+ // force a re-render in a loop with strict-mode double-mounts.+ //+ // Seed `_lastProject` from the current editor state so the+ // `subscribeSQLEditorEditorState` listener above doesn't fire a+ // redundant reload on the next unrelated editor mutation.+ _lastProject = getSQLEditorEditorState().project;+ reloadFromStorage();+};- const editingNode = ref<- { node: WorksheetFolderNode; rawLabel: string } | undefined- >();+const onCurrentTabChanged = (tab: SQLEditorTab | undefined) => {+ useSheetContextStore.getState().setSelectedKeys([]);+ if (!tab) return;++ let view: SheetViewMode = "draft";+ let worksheetLikeItem: WorksheetLikeItem | undefined;+ const tabId = tab.id;+ const worksheetName = tab.worksheet;++ if (worksheetName) {+ const worksheet = useWorkSheetStore().getWorksheetByName(worksheetName);+ if (!worksheet) return;+ worksheetLikeItem = {+ name: worksheet.name,+ title: worksheet.title,+ folders: worksheet.folders,+ type: "worksheet",+ };+ view = isWorksheetCreator(worksheet) ? "my" : "shared";+ } else {+ worksheetLikeItem = {+ name: tabId,+ folders: [],+ title: "",+ type: "draft",+ };+ }- // ---- batch operations ---------------------------------------------------+ const viewCtx = getViewContext(view);+ const key = viewCtx.getKeyForWorksheet(worksheetLikeItem);+ useSheetContextStore.getState().setSelectedKeys([key]);- const batchUpdateWorksheetFolders = async (- worksheets: { name: string; folders: string[] }[]- ) => {- if (worksheets.length === 0) {- return;+ const expanded = new Set(useSheetContextStore.getState().expandedKeys);+ for (const path of viewCtx.getPathesForWorksheet(worksheetLikeItem)) {+ expanded.add(path);+ }+ useSheetContextStore.getState().setExpandedKeys(expanded);++ // Defer DOM scroll until after React paints.+ queueMicrotask(() => {+ const dom = document.querySelector(`[data-item-key="${key}"]`);+ if (dom) {+ scrollIntoView(dom, {+ scrollMode: "if-needed",+ block: "nearest",+ });}- await worksheetV1Store.batchUpsertWorksheetOrganizers(- worksheets.map((worksheet) => ({- organizer: {- worksheet: worksheet.name,- folders: worksheet.folders,- },- updateMask: ["folders"],- }))- );- };+ });+};- // ---- view ref -----------------------------------------------------------+// ---- public hook API -------------------------------------------------------++export interface SheetContext {+ filter: WorksheetFilter;+ filterChanged: boolean;+ expandedKeys: Set<string>;+ selectedKeys: string[];+ editingNode: { node: WorksheetFolderNode; rawLabel: string } | undefined;+ view: SheetViewMode;+ viewContexts: Record<SheetViewMode, ViewContext>;+ isWorksheetCreator: (worksheet: { creator: string }) => boolean;+ batchUpdateWorksheetFolders: (+ worksheets: { name: string; folders: string[] }[]+ ) => Promise<void>;+ getContextByView: (view: SheetViewMode) => ViewContext;+ setFilter: SheetContextState["setFilter"];+ setView: SheetContextState["setView"];+ setExpandedKeys: SheetContextState["setExpandedKeys"];+ setSelectedKeys: SheetContextState["setSelectedKeys"];+ setEditingNode: SheetContextState["setEditingNode"];+}- const view = ref<SheetViewMode>("my");+const VIEW_CONTEXTS_LAZY: Record<SheetViewMode, ViewContext> = {+ get my() {+ return getViewContext("my");+ },+ get shared() {+ return getViewContext("shared");+ },+ get draft() {+ return getViewContext("draft");+ },+} as Record<SheetViewMode, ViewContext>;++// Module-level action helpers — always-stable references, never go+// through the React subscription path.+const setFilterAction: SheetContextState["setFilter"] = (next) =>+ useSheetContextStore.getState().setFilter(next);+const setViewAction: SheetContextState["setView"] = (view) =>+ useSheetContextStore.getState().setView(view);+const setExpandedKeysAction: SheetContextState["setExpandedKeys"] = (next) =>+ useSheetContextStore.getState().setExpandedKeys(next);+const setSelectedKeysAction: SheetContextState["setSelectedKeys"] = (next) =>+ useSheetContextStore.getState().setSelectedKeys(next);+const setEditingNodeAction: SheetContextState["setEditingNode"] = (next) =>+ useSheetContextStore.getState().setEditingNode(next);+/**+ * Top-level sheet context. Returns plain values that re-render on the+ * Zustand store changes the hook subscribes to.+ *+ * The hook also lazy-initializes the cross-store watchers+ * (project change, current-tab change, persistence) the first time+ * it's called from anywhere in the app.+ *+ * Only the *reactive* subset goes through `useShallow` / the Zustand+ * subscription. Stable helpers (action setters, view contexts, pure+ * functions) are merged in afterwards as module-level references so+ * they never destabilize the shallow comparison.+ */+export function useSheetContext(): SheetContext {+ const reactive = useSheetContextStore(+ useShallow((state) => ({+ filter: state.filter,+ filterChanged: !isEqual(state.filter, INITIAL_FILTER),+ expandedKeys: state.expandedKeys,+ selectedKeys: state.selectedKeys,+ editingNode: state.editingNode,+ view: state.view,+ }))+ );return {- view,- viewContexts,- filter,- filterChanged,- expandedKeys,- selectedKeys,- editingNode,+ ...reactive,+ viewContexts: VIEW_CONTEXTS_LAZY,isWorksheetCreator,batchUpdateWorksheetFolders,- getContextByView,+ getContextByView: getViewContext,+ setFilter: setFilterAction,+ setView: setViewAction,+ setExpandedKeys: setExpandedKeysAction,+ setSelectedKeys: setSelectedKeysAction,+ setEditingNode: setEditingNodeAction,};-};--let _sheetState: ReturnType<typeof buildSheetState> | undefined;-const getSheetState = () => {- if (!_sheetState) _sheetState = buildSheetState();- return _sheetState;-};+}-// ---- public API ------------------------------------------------------------+export type { SheetContext as SheetContextType };/**- * Returns the full sheet context (filter, expandedKeys, selectedKeys, etc.).- * Previously delegated to a Pinia store; now reads directly from a- * module-level Vue-reactive singleton built by `buildSheetState()`.+ * Returns the per-view context. Components subscribed via this hook+ * re-render when ANY of that view's state changes+ * (isLoading / isInitialized / sheetTree / folders).*/-export const useSheetContext = () => getSheetState();--export type SheetContext = ReturnType<typeof useSheetContext>;--// ---- InjectionKey kept for source-compat (no longer used) --------------------export const KEY = Symbol("bb.sql-editor.sheet") as InjectionKey<SheetContext>;+export function useSheetContextByView(view: SheetViewMode): ViewContext {+ // Subscribe to the view's state so React re-renders on changes.+ // The returned ViewContext is the same stable reference; its+ // property getters read the latest Zustand state.+ useSheetContextStore((s) => s.viewStates[view]);+ return getViewContext(view);+}/**- * Returns the per-view context for `view`.+ * Eagerly initialize the sheet-state watchers + storage hydration so+ * the rest of the app sees a populated context on mount. Kept as a+ * no-op-shaped function for source compatibility with the Pinia-era+ * `provideSheetContext()` boot call.*/-export const useSheetContextByView = (view: SheetViewMode) =>- getSheetState().getContextByView(view);+export function provideSheetContext(): void {+ bindWatchers();+}++// `KEY` was a Vue `InjectionKey`; kept exported as a Symbol for source+// compatibility (no current consumers).+export const KEY = Symbol("bb.sql-editor.sheet");-// ---- tree helpers ----------------------------------------------------------+// ---- tree helpers (unchanged) ----------------------------------------------export const revealNodes = <T>(node: WorksheetFolderNode,@@ -545,21 +1093,12 @@ export const revealWorksheets = <T>(callback: (node: WorksheetFolderNode) => T | undefined): T[] => {return revealNodes(node, (n) => {- if (!n.worksheet) {- return undefined;- }+ if (!n.worksheet) return undefined;return callback(n);});};-/**- * Eagerly boot the sheet-state singleton so its watchers start firing on- * app mount. Kept as a no-op-shaped function so call sites match the- * Pinia-era `useSQLEditorWorksheetStore()` boot call.- */-export const provideSheetContext = () => getSheetState();--// ---- openWorksheetByName (unchanged) ----------------------------------------+// ---- openWorksheetByName (unchanged behavior) ------------------------------export const openWorksheetByName = async ({worksheet,@@ -571,9 +1110,7 @@ export const openWorksheetByName = async ({mode?: SQLEditorTabMode;}) => {const sheet = await useWorkSheetStore().getOrFetchWorksheetByName(worksheet);- if (!sheet) {- return undefined;- }+ if (!sheet) return undefined;if (!isWorksheetReadableV1(sheet)) {pushNotification({@@ -584,13 +1121,19 @@ export const openWorksheetByName = async ({return undefined;}- const tabStore = useSQLEditorTabStore();- const openingSheetTab = tabStore.getTabByWorksheet(sheet.name);+ const tabsState = getSQLEditorTabsState();+ const openingSheetTab = (() => {+ for (const persisted of tabsState.openTmpTabList) {+ const tab = tabsState.tabsById.get(persisted.id);+ if (tab?.worksheet === sheet.name) return tab;+ }+ return undefined;+ })();if (openingSheetTab && !forceNewTab) {- tabStore.setCurrentTabId(openingSheetTab.id);+ tabsState.setCurrentTabId(openingSheetTab.id);if (mode && mode !== openingSheetTab.mode) {- tabStore.updateTab(openingSheetTab.id, { mode });+ tabsState.updateTab(openingSheetTab.id, { mode });}return openingSheetTab;}@@ -606,5 +1149,10 @@ export const openWorksheetByName = async ({mode: mode ?? "WORKSHEET",};- return tabStore.addTab(newTab, forceNewTab /* beside */);+ return tabsState.addTab(newTab, forceNewTab /* beside */);};++// Touch the editor store import so it's eagerly evaluated alongside the+// tab store (matches the historical Pinia-era load order).+void useSQLEditorEditorStore;+void useSQLEditorTabsStore;diff --git a/frontend/src/views/sql-editor/events.ts b/frontend/src/views/sql-editor/events.tsindex de475e28a8..7abad2c7b5 100644--- a/frontend/src/views/sql-editor/events.ts+++ b/frontend/src/views/sql-editor/events.ts@@ -24,7 +24,7 @@ export type SQLEditorEvents = {// worksheet (`useExecuteSQL`) and admin/terminal (`webTerminal`)// paths. `HistoryPane` listens and refetches. Bypasses store// reactivity that doesn't reliably propagate the post-exec- // mutations into the React `useVueState` subscriber.+ // mutations into React selector subscribers."query-executed": undefined;};