Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore(frontend): centralize localStorage keys and add migration (#19218)
boojack9e174c0005c3
diff --git a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue b/frontend/src/components/AdvancedSearch/AdvancedSearch.vueindex 206f0093eb..225fd8333b 100644--- a/frontend/src/components/AdvancedSearch/AdvancedSearch.vue+++ b/frontend/src/components/AdvancedSearch/AdvancedSearch.vue@@ -98,6 +98,7 @@ import {getValueFromSearchParams,getValuesFromSearchParams,minmax,+ storageKeySearch,upsertScope,useDynamicLocalStorage,} from "@/utils";@@ -150,9 +151,8 @@ const router = useRouter();const me = useCurrentUserV1();const cachedQuery = useDynamicLocalStorage<string>(- computed(- () =>- `bb.advanced-search.${me.value.name}.${router.currentRoute.value.path}`+ computed(() =>+ storageKeySearch(router.currentRoute.value.path, me.value.email)),"");diff --git a/frontend/src/components/ExpirationSelector.vue b/frontend/src/components/ExpirationSelector.vueindex 605ef8ab75..42a4038d99 100644--- a/frontend/src/components/ExpirationSelector.vue+++ b/frontend/src/components/ExpirationSelector.vue@@ -50,6 +50,7 @@ import { computed, reactive, watch } from "vue";import { useI18n } from "vue-i18n";import { useSettingV1Store } from "@/store";import { PresetRoleType } from "@/types";+import { STORAGE_KEY_ROLES_EXPIRATION } from "@/utils";interface ExpirationOption {value: number;@@ -76,7 +77,7 @@ const settingV1Store = useSettingV1Store();// Remember the last selected expiration optionconst lastSelectedExpiration = useLocalStorage<number>(- "bb.roles.last-expiration-selection",+ STORAGE_KEY_ROLES_EXPIRATION,7 // Default to 1 week);diff --git a/frontend/src/components/IAMRemindModal.vue b/frontend/src/components/IAMRemindModal.vueindex a26496bf6c..6add36ebb4 100644--- a/frontend/src/components/IAMRemindModal.vue+++ b/frontend/src/components/IAMRemindModal.vue@@ -52,6 +52,7 @@ import {autoProjectRoute,displayRoleTitle,filterBindingsByUserName,+ storageKeyIamRemind,useDynamicLocalStorage,} from "@/utils";import { convertFromExpr } from "@/utils/issue/cel";@@ -74,7 +75,7 @@ const me = useCurrentUserV1();const iamRemindState = useDynamicLocalStorage<Map<string /* {project}.{pending expired roles} */, boolean /* show remind */>>(- computed(() => `bb.remind.iam.${me.value.name}`),+ computed(() => storageKeyIamRemind(me.value.email)),new Map());const projectStore = useProjectV1Store();diff --git a/frontend/src/components/Project/useRecentProjects.ts b/frontend/src/components/Project/useRecentProjects.tsindex 859ec1a44f..5a30b6a78d 100644--- a/frontend/src/components/Project/useRecentProjects.ts+++ b/frontend/src/components/Project/useRecentProjects.ts@@ -2,7 +2,7 @@ import { computedAsync } from "@vueuse/core";import { computed } from "vue";import { useCurrentUserV1, useProjectV1Store } from "@/store";import { isValidProjectName } from "@/types";-import { useDynamicLocalStorage } from "@/utils";+import { storageKeyRecentProjects, useDynamicLocalStorage } from "@/utils";const MAX_RECENT_PROJECT = 5;@@ -11,7 +11,7 @@ export const useRecentProjects = () => {const currentUser = useCurrentUserV1();const recentViewProjectNames = useDynamicLocalStorage<string[]>(- computed(() => `bb.project.recent-view.${currentUser.value.name}`),+ computed(() => storageKeyRecentProjects(currentUser.value.email)),[]);diff --git a/frontend/src/components/ProvideSQLEditorContext.vue b/frontend/src/components/ProvideSQLEditorContext.vueindex dc813acce4..9580d1895f 100644--- a/frontend/src/components/ProvideSQLEditorContext.vue+++ b/frontend/src/components/ProvideSQLEditorContext.vue@@ -68,6 +68,7 @@ import {getSheetStatement,isDatabaseV1Queryable,isWorksheetReadableV1,+ STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,suggestedTabTitleForSQLEditorConnection,} from "@/utils";import {@@ -376,7 +377,7 @@ const syncURLWithConnection = () => {const restoreLastVisitedSidebarTab = () => {const storedLastVisitedSidebarTab = useLocalStorage<AsidePanelTab>(- "bb.sql-editor.sidebar.last-visited-tab",+ STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB,"WORKSHEET");asidePanelTab.value = storedLastVisitedSidebarTab.value;diff --git a/frontend/src/components/SchemaEditorLite/Panels/PreviewPane.vue b/frontend/src/components/SchemaEditorLite/Panels/PreviewPane.vueindex 30f07a72e3..88b74f2d92 100644--- a/frontend/src/components/SchemaEditorLite/Panels/PreviewPane.vue+++ b/frontend/src/components/SchemaEditorLite/Panels/PreviewPane.vue@@ -62,7 +62,7 @@ import type {SchemaMetadata,} from "@/types/proto-es/v1/database_service_pb";import { GetSchemaStringRequestSchema } from "@/types/proto-es/v1/database_service_pb";-import { minmax } from "@/utils";+import { minmax, STORAGE_KEY_SCHEMA_EDITOR_PREVIEW } from "@/utils";import { extractGrpcErrorMessage } from "@/utils/connect";import { useSchemaEditorContext } from "../context";@@ -75,7 +75,7 @@ const props = defineProps<{}>();const { hidePreview, events } = useSchemaEditorContext();-const expanded = useLocalStorage("bb.schema-editor.preview.expanded", true);+const expanded = useLocalStorage(STORAGE_KEY_SCHEMA_EDITOR_PREVIEW, true);const parentElement = useParentElement();const { height: parentHeight } = useElementSize(parentElement);const layoutReady = computed(() => parentHeight.value > 0);diff --git a/frontend/src/components/v2/Button/ContextMenuButton.vue b/frontend/src/components/v2/Button/ContextMenuButton.vueindex 4b4240b1d0..6708573b27 100644--- a/frontend/src/components/v2/Button/ContextMenuButton.vue+++ b/frontend/src/components/v2/Button/ContextMenuButton.vue@@ -37,10 +37,9 @@ import type { ButtonGroupProps, SelectOption } from "naive-ui";import { NButton, NButtonGroup, NPopselect } from "naive-ui";import type { CSSProperties } from "vue";import { computed, ref } from "vue";+import { storageKeyContextMenu } from "@/utils";import type { ContextMenuButtonAction } from "./types";-const STORE_PREFIX = "bb.context-menu-button";-const props = withDefaults(defineProps<{preferenceKey: string;@@ -60,11 +59,13 @@ defineEmits<{const getStorage = () => {const { preferenceKey } = props;if (!preferenceKey) return undefined;- // e.g key = "bb.button-with-context-menu.task-status-transition"- const key = `${STORE_PREFIX}.${preferenceKey}`;- return useLocalStorage(key, props.defaultActionKey, {- listenToStorageChanges: false,- });+ return useLocalStorage(+ storageKeyContextMenu(preferenceKey),+ props.defaultActionKey,+ {+ listenToStorageChanges: false,+ }+ );};// Load user stored default action from localStorage if possible.diff --git a/frontend/src/components/v2/Model/PagedTable.vue b/frontend/src/components/v2/Model/PagedTable.vueindex 82ad8f90df..1091cf97da 100644--- a/frontend/src/components/v2/Model/PagedTable.vue+++ b/frontend/src/components/v2/Model/PagedTable.vue@@ -43,7 +43,11 @@ import { sortBy, uniq } from "lodash-es";import { type DataTableSortState, NButton, NSelect } from "naive-ui";import { computed, onMounted, onUnmounted, ref, shallowRef, watch } from "vue";import { useAuthStore, useCurrentUserV1 } from "@/store";-import { getDefaultPagination, useDynamicLocalStorage } from "@/utils";+import {+ getDefaultPagination,+ storageKeyPagedTable,+ useDynamicLocalStorage,+} from "@/utils";// ============================================================================// Props & Emits@@ -161,7 +165,9 @@ const pageSizeOptions = computed(() => {});const sessionState = useDynamicLocalStorage<{ pageSize: number }>(- computed(() => `${props.sessionKey}.${currentUser.value.name}`),+ computed(() =>+ storageKeyPagedTable(props.sessionKey, currentUser.value.email)+ ),{ pageSize: pageSizeOptions.value[0].value });diff --git a/frontend/src/composables/useLanguage.ts b/frontend/src/composables/useLanguage.tsindex bd37771f32..27a2dcc2d0 100644--- a/frontend/src/composables/useLanguage.ts+++ b/frontend/src/composables/useLanguage.ts@@ -1,8 +1,7 @@import { useLocalStorage } from "@vueuse/core";import { useI18n } from "vue-i18n";import { useRouter } from "vue-router";-import { type LanguageStorage } from "@/plugins/i18n";-import { emitStorageChangedEvent } from "@/utils";+import { emitStorageChangedEvent, STORAGE_KEY_LANGUAGE } from "@/utils";/*** Language hook for i18n@@ -11,19 +10,11 @@ import { emitStorageChangedEvent } from "@/utils";const useLanguage = () => {const { availableLocales, locale } = useI18n();const currentRoute = useRouter().currentRoute;- const storage = useLocalStorage<LanguageStorage>("bytebase_options", {- appearance: {- language: "",- },- });+ const storage = useLocalStorage<string>(STORAGE_KEY_LANGUAGE, "");const setLocale = (lang: string) => {locale.value = lang;- storage.value = {- appearance: {- language: lang,- },- };+ storage.value = lang;emitStorageChangedEvent();if (currentRoute.value.meta.title) {diff --git a/frontend/src/composables/useLastActivity.ts b/frontend/src/composables/useLastActivity.tsindex 6e41ba4c63..110ee4bac8 100644--- a/frontend/src/composables/useLastActivity.ts+++ b/frontend/src/composables/useLastActivity.ts@@ -1,11 +1,11 @@import { computed } from "vue";import { useCurrentUserV1 } from "@/store";-import { useDynamicLocalStorage } from "@/utils";+import { storageKeyLastActivity, useDynamicLocalStorage } from "@/utils";export const useLastActivity = () => {const currentUser = useCurrentUserV1();const lastActivityTs = useDynamicLocalStorage<number>(- computed(() => `bb.last-activity-ts.${currentUser.value.name}`),+ computed(() => storageKeyLastActivity(currentUser.value.email)),Date.now());return { lastActivityTs };diff --git a/frontend/src/main.ts b/frontend/src/main.tsindex 8309ad9554..21405b282e 100644--- a/frontend/src/main.ts+++ b/frontend/src/main.ts@@ -17,11 +17,20 @@ import {useAuthStore,useSubscriptionV1Store,} from "./store";-import { humanizeDate, humanizeTs, isDev, isRelease } from "./utils";+import {+ humanizeDate,+ humanizeTs,+ isDev,+ isRelease,+ migrateStorageKeys,+} from "./utils";console.debug("dev:", isDev());console.debug("release:", isRelease());+// Migrate renamed localStorage keys before any store reads from storage.+migrateStorageKeys();+(async () => {const app = createApp(App);diff --git a/frontend/src/plugins/ai/components/DynamicSuggestions.vue b/frontend/src/plugins/ai/components/DynamicSuggestions.vueindex 3c3aad8dfa..a4a27168e3 100644--- a/frontend/src/plugins/ai/components/DynamicSuggestions.vue+++ b/frontend/src/plugins/ai/components/DynamicSuggestions.vue@@ -56,7 +56,10 @@ import { NButton } from "naive-ui";import { computed, onMounted } from "vue";import { BBSpin } from "@/bbkit";import { useCurrentUserV1 } from "@/store";-import { useDynamicLocalStorage } from "@/utils";+import {+ storageKeySqlEditorAiSuggestion,+ useDynamicLocalStorage,+} from "@/utils";import { useDynamicSuggestions } from "../logic";const emit = defineEmits<{@@ -79,7 +82,7 @@ const suggestions = computed(() => dynamicSuggestions.value?.suggestions ?? []);const current = computed(() => dynamicSuggestions.value?.current());const showSuggestion = useDynamicLocalStorage<boolean>(- computed(() => `bb.sql-editor.ai-suggestion.${currentUser.value.name}`),+ computed(() => storageKeySqlEditorAiSuggestion(currentUser.value.email)),true);diff --git a/frontend/src/plugins/ai/components/state.ts b/frontend/src/plugins/ai/components/state.tsindex 3c606c2a97..5777e0e2fc 100644--- a/frontend/src/plugins/ai/components/state.ts+++ b/frontend/src/plugins/ai/components/state.ts@@ -1,6 +1,7 @@import { useLocalStorage } from "@vueuse/core";+import { STORAGE_KEY_AI_DISMISS } from "@/utils";export const DISMISS_PLACEHOLDER = useLocalStorage(- "bb.plugin.open-ai.dismiss-placeholder",+ STORAGE_KEY_AI_DISMISS,false);diff --git a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts b/frontend/src/plugins/ai/logic/useDynamicSuggestions.tsindex 801a3dac6e..b537ad64b4 100644--- a/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts+++ b/frontend/src/plugins/ai/logic/useDynamicSuggestions.ts@@ -10,7 +10,7 @@ import {AICompletionRequest_MessageSchema,AICompletionRequestSchema,} from "@/types/proto-es/v1/sql_service_pb";-import { WebStorageHelper } from "@/utils";+import { storageKeyAiSuggestions } from "@/utils";import { useAIContext } from "./context";import * as promptUtils from "./prompt";@@ -27,6 +27,23 @@ export type SuggestionContext = {next: () => Promise<string | undefined>; // returns next suggestion or empty (ended)};+function saveSuggestionCache(key: string, value: string[]) {+ try {+ localStorage.setItem(storageKeyAiSuggestions(key), JSON.stringify(value));+ } catch {+ // ignore+ }+}++function loadSuggestionCache(key: string): string[] {+ try {+ const raw = localStorage.getItem(storageKeyAiSuggestions(key));+ return raw ? JSON.parse(raw) : [];+ } catch {+ return [];+ }+}+const cache = ref(new Map<string, SuggestionContext>());const MAX_STORED_SUGGESTIONS = 10;@@ -34,8 +51,6 @@ const keyOf = (metadata: string) => String(hashCode(metadata));export const useDynamicSuggestions = () => {const context = useAIContext();- const storage = new WebStorageHelper("bb.plugin.open-ai.suggestions");-const metadata = computed(() => {const meta = context.databaseMetadata.value;const engine = context.engine.value;@@ -129,7 +144,7 @@ export const useDynamicSuggestions = () => {MAX_STORED_SUGGESTIONS);if (combined.length > 0) {- storage.save(key, combined);+ saveSuggestionCache(key, combined);}return more;@@ -148,7 +163,7 @@ export const useDynamicSuggestions = () => {return suggestion.current();},});- const stored = storage.load<string[]>(suggestion.key, []);+ const stored = loadSuggestionCache(suggestion.key);if (stored && stored.length > 0) {suggestion.suggestions = stored;}diff --git a/frontend/src/plugins/i18n.ts b/frontend/src/plugins/i18n.tsindex c7403d1025..32d2c5509d 100644--- a/frontend/src/plugins/i18n.ts+++ b/frontend/src/plugins/i18n.ts@@ -1,34 +1,21 @@import { useLocalStorage } from "@vueuse/core";import type { WritableComputedRef } from "vue";import { type Composer, createI18n } from "vue-i18n";+import { STORAGE_KEY_LANGUAGE } from "@/utils/storage-keys";import { mergedLocalMessage } from "./i18n-messages";-export interface LanguageStorage {- appearance: {- language: string;- };-}-const validLocaleList = ["en-US", "zh-CN", "es-ES", "ja-JP", "vi-VN"];const getValidLocale = () => {- const storage = useLocalStorage<LanguageStorage>("bytebase_options", {- appearance: {- language: "",- },- });+ const storage = useLocalStorage<string>(STORAGE_KEY_LANGUAGE, "");const params = new URL(globalThis.location.href).searchParams;let locale = params.get("locale") || "";if (validLocaleList.includes(locale)) {- storage.value = {- appearance: {- language: locale,- },- };+ storage.value = locale;}- locale = storage.value?.appearance?.language || "";+ locale = storage.value || "";if (validLocaleList.includes(locale)) {return locale;}diff --git a/frontend/src/router/useRecentVisit.ts b/frontend/src/router/useRecentVisit.tsindex 9e9d44119f..720a878304 100644--- a/frontend/src/router/useRecentVisit.ts+++ b/frontend/src/router/useRecentVisit.ts@@ -1,16 +1,15 @@import { computed } from "vue";import { useCurrentUserV1 } from "@/store";import { projectNamePrefix } from "@/store/modules/v1/common";-import { useDynamicLocalStorage } from "@/utils";+import { storageKeyRecentVisit, useDynamicLocalStorage } from "@/utils";-const STORAGE_KEY = "bb.space.recently_visited";const MAX_HISTORY = 10;export function useRecentVisit() {const currentUser = useCurrentUserV1();const recentVisit = useDynamicLocalStorage<string[]>(- computed(() => `${STORAGE_KEY}.${currentUser.value.email}`),+ computed(() => storageKeyRecentVisit(currentUser.value.email)),[]);diff --git a/frontend/src/store/modules/quickLink.ts b/frontend/src/store/modules/quickLink.tsindex c8d1babea3..377b6224a5 100644--- a/frontend/src/store/modules/quickLink.ts+++ b/frontend/src/store/modules/quickLink.ts@@ -14,6 +14,7 @@ import {import { useCurrentUserV1 } from "@/store";import {type DashboardSidebarItem,+ storageKeyQuickAccess,useDashboardSidebar,useDynamicLocalStorage,} from "@/utils";@@ -80,7 +81,7 @@ export function useQuickLink() {});const quickAccessConfig = useDynamicLocalStorage<string[]>(- computed(() => `bb.quick-access.${currentUser.value.name}`),+ computed(() => storageKeyQuickAccess(currentUser.value.email)),["visit-issues","visit-projects",diff --git a/frontend/src/store/modules/router.ts b/frontend/src/store/modules/router.tsindex 985b46393d..775c735859 100644--- a/frontend/src/store/modules/router.ts+++ b/frontend/src/store/modules/router.ts@@ -1,18 +1,17 @@+import { useLocalStorage } from "@vueuse/core";import { defineStore } from "pinia";+import { STORAGE_KEY_BACK_PATH } from "@/utils";-export const useRouterStore = defineStore("router", {- // need not to initialize a state since we store everything into localStorage- // state: () => ({}),+export const useRouterStore = defineStore("router", () => {+ const backPath = useLocalStorage(STORAGE_KEY_BACK_PATH, "/");- getters: {- backPath: () => () => {- return localStorage.getItem("ui.backPath") || "/";- },- },- actions: {- setBackPath(backPath: string) {- localStorage.setItem("ui.backPath", backPath);- return backPath;- },- },+ const setBackPath = (path: string) => {+ backPath.value = path;+ return path;+ };++ return {+ backPath,+ setBackPath,+ };});diff --git a/frontend/src/store/modules/sqlEditor/editor.ts b/frontend/src/store/modules/sqlEditor/editor.tsindex d6365c45cb..c2211f2a15 100644--- a/frontend/src/store/modules/sqlEditor/editor.ts+++ b/frontend/src/store/modules/sqlEditor/editor.ts@@ -4,15 +4,20 @@ import { defineStore } from "pinia";import { computed, ref } from "vue";import type { Database } from "@/types/proto-es/v1/database_service_pb";import { QueryOption_RedisRunCommandsOn } from "@/types/proto-es/v1/sql_service_pb";-import { hasWorkspacePermissionV2 } from "@/utils";+import {+ hasWorkspacePermissionV2,+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+} from "@/utils";export const useSQLEditorStore = defineStore("sqlEditor", () => {const resultRowsLimit = useLocalStorage(- "bb.sql-editor.result-rows-limit",+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,1000);const redisCommandOption = useLocalStorage<QueryOption_RedisRunCommandsOn>(- "bb.sql-editor.redis-command-node",+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,QueryOption_RedisRunCommandsOn.SINGLE_NODE,{// Use a custom merge function to ensure the value is valid.@@ -37,8 +42,9 @@ export const useSQLEditorStore = defineStore("sqlEditor", () => {// `false` if we are preparing project-scoped resources// we should render a skeleton layout with spinner placeholdersconst projectContextReady = ref<boolean>(false);+const storedLastViewedProject = useLocalStorage<string>(- "bb.sql-editor.last-viewed-project",+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,"",{ listenToStorageChanges: false });diff --git a/frontend/src/store/modules/sqlEditor/tab.ts b/frontend/src/store/modules/sqlEditor/tab.tsindex 1a16c7f648..d43a096254 100644--- a/frontend/src/store/modules/sqlEditor/tab.ts+++ b/frontend/src/store/modules/sqlEditor/tab.ts@@ -18,6 +18,8 @@ import {getInstanceResource,getSheetStatement,isConnectedSQLEditorTab,+ storageKeySqlEditorCurrentTab,+ storageKeySqlEditorTabs,suggestedTabTitleForSQLEditorConnection,useDynamicLocalStorage,} from "@/utils";@@ -46,8 +48,6 @@ const PERSISTENT_TAB_FIELDS = [] as const;type PersistentTab = Pick<SQLEditorTab, (typeof PERSISTENT_TAB_FIELDS)[number]>;-const LOCAL_STORAGE_KEY_PREFIX = "bb.sql-editor-tab";-export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {// re-expose selected project in sqlEditorStore for shortcutconst { project } = storeToRefs(useSQLEditorStore());@@ -55,12 +55,12 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {const worksheetStore = useWorkSheetStore();const me = useCurrentUserV1();- const keyNamespace = computed(- () => `${LOCAL_STORAGE_KEY_PREFIX}.${project.value}.${me.value.email}`+ const keyNamespace = computed(() =>+ storageKeySqlEditorTabs(project.value, me.value.email));const openTmpTabList = useDynamicLocalStorage<PersistentTab[]>(- computed(() => `${keyNamespace.value}.opening-tab-list`),+ computed(() => keyNamespace.value),[],localStorage,{@@ -69,7 +69,9 @@ export const useSQLEditorTabStore = defineStore("sqlEditorTab", () => {);const currentTabId = useDynamicLocalStorage<string>(- computed(() => `${keyNamespace.value}.current-tab-id`),+ computed(() =>+ storageKeySqlEditorCurrentTab(project.value, me.value.email)+ ),"",localStorage,{diff --git a/frontend/src/store/modules/uistate.ts b/frontend/src/store/modules/uistate.tsindex f5871bfaa0..44d4f3b952 100644--- a/frontend/src/store/modules/uistate.ts+++ b/frontend/src/store/modules/uistate.ts@@ -1,112 +1,49 @@-import { isUndefined } from "lodash-es";import { defineStore } from "pinia";-import { computed, reactive } from "vue";+import { computed } from "vue";import { useCurrentUserV1 } from "@/store";--export interface UIState {- collapseStateByKey: Map<string, boolean>;- introStateByKey: Map<string, boolean>;-}+import {+ storageKeyCollapseState,+ storageKeyIntroState,+ useDynamicLocalStorage,+} from "@/utils";export const useUIStateStore = defineStore("uistate", () => {- const state = reactive<UIState>({- collapseStateByKey: new Map(),- introStateByKey: new Map(),- });const currentUser = useCurrentUserV1();- const COLLAPSE_MODULE_KEY = computed(- () => `ui.list.collapse.${currentUser.value.email}`+ const collapseState = useDynamicLocalStorage<Record<string, boolean>>(+ computed(() => storageKeyCollapseState(currentUser.value.email)),+ {});- const INTRO_MODULE_KEY = computed(- () => `ui.intro.${currentUser.value.email}`++ const introState = useDynamicLocalStorage<Record<string, boolean>>(+ computed(() => storageKeyIntroState(currentUser.value.email)),+ {});const getIntroStateByKey = (key: string): boolean => {- return stateByKey(state.introStateByKey, INTRO_MODULE_KEY.value, key);- };-- const setCollapseState = (fullState: Record<string, boolean>) => {- const newMap = new Map();- for (const key of Object.keys(fullState)) {- newMap.set(key, fullState[key]);- }- state.collapseStateByKey = newMap;- };-- const setIntroState = (fullState: Record<string, boolean>) => {- const newMap = new Map();- for (const key of Object.keys(fullState)) {- newMap.set(key, fullState[key]);- }- state.introStateByKey = newMap;+ return introState.value[key] ?? false;};- const setIntroStateByKey = ({+ const saveIntroStateByKey = async ({key,newState,}: {key: string;newState: boolean;}) => {- state.introStateByKey.set(key, newState);+ introState.value = { ...introState.value, [key]: newState };+ return newState;};const restoreState = () => {- const storedCollapseState = localStorage.getItem(COLLAPSE_MODULE_KEY.value);- const collapseState = storedCollapseState- ? JSON.parse(storedCollapseState)- : {};- setCollapseState(collapseState);-- const storedIntroState = localStorage.getItem(INTRO_MODULE_KEY.value);- const introState = storedIntroState ? JSON.parse(storedIntroState) : {};- setIntroState(introState);- };-- const saveIntroStateByKey = async ({- key,- newState,- }: {- key: string;- newState: boolean;- }) => {- const state = saveStateByKey(INTRO_MODULE_KEY.value, key, newState);- setIntroStateByKey({ key, newState });- return state;+ // No-op: useDynamicLocalStorage handles restore automatically};return {+ collapseState,+ introState,saveIntroStateByKey,restoreState,getIntroStateByKey,};});--const stateByKey = function (- stateMap: Map<string, boolean>,- module: string,- key: string-): boolean {- const memState = stateMap.get(key);- if (!isUndefined(memState)) {- return memState;- }- const localStorageState = localStorage.getItem(module);- if (localStorageState) {- return JSON.parse(localStorageState)[key] || false;- }- return false;-};--const saveStateByKey = function (- module: string,- key: string,- state: boolean-): boolean {- const item = localStorage.getItem(module);- const fullState = item ? JSON.parse(item) : {};- fullState[key] = state;- localStorage.setItem(module, JSON.stringify(fullState));- return fullState[key];-};diff --git a/frontend/src/store/modules/v1/actuator.ts b/frontend/src/store/modules/v1/actuator.tsindex 885fe7ea7f..3f5132855c 100644--- a/frontend/src/store/modules/v1/actuator.ts+++ b/frontend/src/store/modules/v1/actuator.ts@@ -16,7 +16,11 @@ import type {} from "@/types/proto-es/v1/actuator_service_pb";import { State } from "@/types/proto-es/v1/common_pb";import { UserType } from "@/types/proto-es/v1/user_service_pb";-import { semverCompare } from "@/utils";+import {+ STORAGE_KEY_ONBOARDING,+ STORAGE_KEY_RELEASE,+ semverCompare,+} from "@/utils";const EXTERNAL_URL_PLACEHOLDER ="https://docs.bytebase.com/get-started/self-host/external-url";@@ -29,7 +33,7 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {const serverInfo = ref<ActuatorInfo | undefined>(undefined);const serverInfoTs = ref(0);const resourcePackage = ref<ResourcePackage | undefined>(undefined);- const releaseInfo = useLocalStorage<ReleaseInfo>("bytebase_release", {+ const releaseInfo = useLocalStorage<ReleaseInfo>(STORAGE_KEY_RELEASE, {ignoreRemindModalTillNextRelease: false,nextCheckTs: 0,});@@ -37,7 +41,7 @@ export const useActuatorV1Store = defineStore("actuator_v1", () => {const onboardingState = useLocalStorage<{isOnboarding: boolean;consumed: string[];- }>("bb.onboarding-state", {+ }>(STORAGE_KEY_ONBOARDING, {isOnboarding: false,consumed: [],});diff --git a/frontend/src/store/modules/v1/auth.ts b/frontend/src/store/modules/v1/auth.tsindex 642832508c..874ff170da 100644--- a/frontend/src/store/modules/v1/auth.ts+++ b/frontend/src/store/modules/v1/auth.ts@@ -27,6 +27,7 @@ import {UserSchema,UserType,} from "@/types/proto-es/v1/user_service_pb";+import { storageKeyResetPassword } from "@/utils";import { extractUserEmail } from "./common";export const useAuthStore = defineStore("auth_v1", () => {@@ -53,7 +54,7 @@ export const useAuthStore = defineStore("auth_v1", () => {return false;}return useLocalStorage<boolean>(- `${currentUserEmail.value}.require_reset_password`,+ storageKeyResetPassword(currentUserEmail.value),false).value;});@@ -63,7 +64,7 @@ export const useAuthStore = defineStore("auth_v1", () => {return false;}const needResetPasswordCache = useLocalStorage<boolean>(- `${currentUserEmail.value}.require_reset_password`,+ storageKeyResetPassword(currentUserEmail.value),false);needResetPasswordCache.value = requireResetPassword;@@ -169,12 +170,25 @@ export const useAuthStore = defineStore("auth_v1", () => {});};+ const cleanupUserStorage = (email: string) => {+ if (!email) return;+ const keysToRemove: string[] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (key?.endsWith(`.${email}`)) {+ keysToRemove.push(key);+ }+ }+ keysToRemove.forEach((key) => localStorage.removeItem(key));+ };+const logout = async () => {try {await authServiceClientConnect.logout({});} catch {// nothing} finally {+ cleanupUserStorage(currentUserEmail.value);unauthenticatedOccurred.value = false;const pathname = location.pathname;// Replace and reload the page to clear frontend state directly.diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.tsindex c7fb6320ca..dba74c5c42 100644--- a/frontend/src/utils/index.ts+++ b/frontend/src/utils/index.ts@@ -25,3 +25,5 @@ export * from "./iam";export * from "./auto-route";export * from "./pagination";export * from "./expr";+export * from "./storage-keys";+export * from "./storage-migrate";diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.tsnew file mode 100644index 0000000000..50556b0e2e--- /dev/null+++ b/frontend/src/utils/storage-keys.ts@@ -0,0 +1,80 @@+// Centralized localStorage key registry.+// Static keys are plain constants; dynamic (user-scoped) keys are builder functions.++// --- Global (no user scope) ---+export const STORAGE_KEY_BACK_PATH = "bb.back-path";+export const STORAGE_KEY_LANGUAGE = "bb.language";+export const STORAGE_KEY_RELEASE = "bb.release";+export const STORAGE_KEY_ONBOARDING = "bb.onboarding";+export const STORAGE_KEY_SCHEMA_EDITOR_PREVIEW =+ "bb.schema-editor.preview-expanded";+export const STORAGE_KEY_ROLES_EXPIRATION =+ "bb.roles.last-expiration-selection";+export const STORAGE_KEY_AI_DISMISS = "bb.ai.dismiss-placeholder";+export const STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT = "bb.sql-editor.result-limit";+export const STORAGE_KEY_SQL_EDITOR_REDIS_NODE = "bb.sql-editor.redis-node";+export const STORAGE_KEY_SQL_EDITOR_LAST_PROJECT = "bb.sql-editor.last-project";+export const STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE =+ "bb.sql-editor.ai-panel-size";+export const STORAGE_KEY_SQL_EDITOR_SIDEBAR_TAB =+ "bb.sql-editor.sidebar.last-visited-tab";+export const STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT =+ "bb.sql-editor.editor-panel.code-viewer.format";+export const STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT =+ "bb.sql-editor.detail-panel.format";+export const STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP =+ "bb.sql-editor.detail-panel.line-wrap";+export const STORAGE_KEY_MY_ISSUES_TAB = "bb.components.MY_ISSUES.id";++// --- User-scoped (cleaned on logout) ---+export const storageKeyRecentVisit = (email: string) =>+ `bb.recent-visit.${email}`;+export const storageKeyRecentProjects = (email: string) =>+ `bb.recent-projects.${email}`;+export const storageKeyQuickAccess = (email: string) =>+ `bb.quick-access.${email}`;+export const storageKeyLastActivity = (email: string) =>+ `bb.last-activity.${email}`;+export const storageKeyCollapseState = (email: string) =>+ `bb.collapse-state.${email}`;+export const storageKeyIntroState = (email: string) =>+ `bb.intro-state.${email}`;+export const storageKeyIamRemind = (email: string) => `bb.iam-remind.${email}`;+export const storageKeyResetPassword = (email: string) =>+ `bb.reset-password.${email}`;+export const storageKeySearch = (routePath: string, email: string) =>+ `bb.search.${routePath}.${email}`;+export const storageKeyContextMenu = (key: string) => `bb.context-menu.${key}`;++// --- SQL Editor (user-scoped) ---+export const storageKeySqlEditorTabs = (project: string, email: string) =>+ `bb.sql-editor.tabs.${project}.${email}`;+export const storageKeySqlEditorCurrentTab = (project: string, email: string) =>+ `bb.sql-editor.current-tab.${project}.${email}`;+export const storageKeySqlEditorConnExpanded = (env: string, email: string) =>+ `bb.sql-editor.conn-expanded.${env}.${email}`;+export const storageKeySqlEditorConnExpandedKeys = (email: string) =>+ `bb.sql-editor.conn-expanded-keys.${email}`;+export const storageKeySqlEditorWorksheetFilter = (+ project: string,+ email: string+) => `bb.sql-editor.worksheet-filter.${project}.${email}`;+export const storageKeySqlEditorWorksheetTree = (+ project: string,+ email: string+) => `bb.sql-editor.worksheet-tree.${project}.${email}`;+export const storageKeySqlEditorWorksheetFolder = (+ project: string,+ viewMode: string,+ email: string+) => `bb.sql-editor.worksheet-folder.${project}.${viewMode}.${email}`;+export const storageKeySqlEditorAiSuggestion = (email: string) =>+ `bb.sql-editor.ai-suggestion.${email}`;++// --- AI ---+export const storageKeyAiSuggestions = (hash: string) =>+ `bb.ai.suggestions.${hash}`;++// --- PagedTable session keys ---+export const storageKeyPagedTable = (sessionKey: string, email: string) =>+ `${sessionKey}.${email}`;diff --git a/frontend/src/utils/storage-migrate.test.ts b/frontend/src/utils/storage-migrate.test.tsnew file mode 100644index 0000000000..bb1a6b46ad--- /dev/null+++ b/frontend/src/utils/storage-migrate.test.ts@@ -0,0 +1,574 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import {+ STORAGE_KEY_AI_DISMISS,+ STORAGE_KEY_BACK_PATH,+ STORAGE_KEY_LANGUAGE,+ STORAGE_KEY_ONBOARDING,+ STORAGE_KEY_SCHEMA_EDITOR_PREVIEW,+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+} from "./storage-keys";+import { migrateStorageKeys } from "./storage-migrate";++const MIGRATION_MARKER = "bb.storage-migration-v1";++function createMockStorage(): Storage {+ let store: Record<string, string> = {};+ return {+ get length() {+ return Object.keys(store).length;+ },+ key(index: number) {+ return Object.keys(store)[index] ?? null;+ },+ getItem(key: string) {+ return store[key] ?? null;+ },+ setItem(key: string, value: string) {+ store[key] = String(value);+ },+ removeItem(key: string) {+ delete store[key];+ },+ clear() {+ store = {};+ },+ };+}++let mockStorage: Storage;++beforeEach(() => {+ mockStorage = createMockStorage();+ vi.stubGlobal("localStorage", mockStorage);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe("migrateStorageKeys", () => {+ test("sets migration marker after running", () => {+ migrateStorageKeys();+ expect(localStorage.getItem(MIGRATION_MARKER)).toBe("1");+ });++ test("skips if migration marker already set", () => {+ localStorage.setItem("ui.backPath", "/old");+ localStorage.setItem(MIGRATION_MARKER, "1");++ migrateStorageKeys();++ expect(localStorage.getItem("ui.backPath")).toBe("/old");+ expect(localStorage.getItem(STORAGE_KEY_BACK_PATH)).toBeNull();+ });+});++describe("static key renames", () => {+ test("migrates ui.backPath to bb.back-path", () => {+ localStorage.setItem("ui.backPath", "/some/path");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_BACK_PATH)).toBe("/some/path");+ expect(localStorage.getItem("ui.backPath")).toBeNull();+ });++ test("migrates bb.onboarding-state to bb.onboarding", () => {+ const state = JSON.stringify({ isOnboarding: true, consumed: ["step1"] });+ localStorage.setItem("bb.onboarding-state", state);+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_ONBOARDING)).toBe(state);+ expect(localStorage.getItem("bb.onboarding-state")).toBeNull();+ });++ test("migrates bb.schema-editor.preview.expanded", () => {+ localStorage.setItem("bb.schema-editor.preview.expanded", "true");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SCHEMA_EDITOR_PREVIEW)).toBe(+ "true"+ );+ expect(+ localStorage.getItem("bb.schema-editor.preview.expanded")+ ).toBeNull();+ });++ test("migrates bb.plugin.open-ai.dismiss-placeholder", () => {+ localStorage.setItem("bb.plugin.open-ai.dismiss-placeholder", "true");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_AI_DISMISS)).toBe("true");+ });++ test("migrates bb.plugin.editor.ai-panel-size", () => {+ localStorage.setItem("bb.plugin.editor.ai-panel-size", "0.5");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE)).toBe(+ "0.5"+ );+ });++ test("does not overwrite existing new key", () => {+ localStorage.setItem("ui.backPath", "/old");+ localStorage.setItem(STORAGE_KEY_BACK_PATH, "/new");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_BACK_PATH)).toBe("/new");+ expect(localStorage.getItem("ui.backPath")).toBeNull();+ });+});++describe("language migration", () => {+ test("migrates bytebase_options nested object to flat string", () => {+ localStorage.setItem(+ "bytebase_options",+ JSON.stringify({ appearance: { language: "zh-CN" } })+ );+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_LANGUAGE)).toBe('"zh-CN"');+ expect(localStorage.getItem("bytebase_options")).toBeNull();+ });++ test("skips language migration if language is empty", () => {+ localStorage.setItem(+ "bytebase_options",+ JSON.stringify({ appearance: { language: "" } })+ );+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_LANGUAGE)).toBeNull();+ expect(localStorage.getItem("bytebase_options")).toBeNull();+ });++ test("removes bytebase_options even if new key exists", () => {+ localStorage.setItem(+ "bytebase_options",+ JSON.stringify({ appearance: { language: "zh-CN" } })+ );+ localStorage.setItem(STORAGE_KEY_LANGUAGE, '"en-US"');+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_LANGUAGE)).toBe('"en-US"');+ expect(localStorage.getItem("bytebase_options")).toBeNull();+ });++ test("handles malformed bytebase_options gracefully", () => {+ localStorage.setItem("bytebase_options", "not-json");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_LANGUAGE)).toBeNull();+ expect(localStorage.getItem("bytebase_options")).toBeNull();+ });+});++describe("SQL editor migrations", () => {+ test("migrates bb.sql-editor.result-rows-limit", () => {+ localStorage.setItem("bb.sql-editor.result-rows-limit", "500");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT)).toBe(+ "500"+ );+ expect(localStorage.getItem("bb.sql-editor.result-rows-limit")).toBeNull();+ });++ test("migrates bb.sql-editor.redis-command-node", () => {+ localStorage.setItem("bb.sql-editor.redis-command-node", "1");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_REDIS_NODE)).toBe("1");+ expect(localStorage.getItem("bb.sql-editor.redis-command-node")).toBeNull();+ });++ test("migrates bb.sql-editor.last-viewed-project", () => {+ localStorage.setItem(+ "bb.sql-editor.last-viewed-project",+ '"projects/my-project"'+ );+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT)).toBe(+ '"projects/my-project"'+ );+ expect(+ localStorage.getItem("bb.sql-editor.last-viewed-project")+ ).toBeNull();+ });++ test("does not overwrite existing sql editor keys", () => {+ localStorage.setItem("bb.sql-editor.result-rows-limit", "500");+ localStorage.setItem(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT, "2000");+ migrateStorageKeys();+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT)).toBe(+ "2000"+ );+ });++ describe("connection pane expanded state", () => {+ test("migrates expanded_{env}.{email} keys", () => {+ const state = JSON.stringify({+ initialized: true,+ expandedKeys: ["env-1/db-1"],+ });+ localStorage.setItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]",+ state+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]"+ )+ ).toBe(state);+ expect(+ localStorage.getItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]"+ )+ ).toBeNull();+ });++ test("migrates multiple environment expanded keys", () => {+ localStorage.setItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]",+ "prod-state"+ );+ localStorage.setItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]",+ "dev-state"+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]"+ )+ ).toBe("prod-state");+ expect(+ localStorage.getItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]"+ )+ ).toBe("dev-state");+ });++ test("does not overwrite existing conn-expanded key when new key exists", () => {+ localStorage.setItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]",+ "old"+ );+ localStorage.setItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]",+ "new"+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]"+ )+ ).toBe("new");+ });+ });++ describe("tab keys (opening-tab-list and current-tab-id)", () => {+ test("migrates opening-tab-list to bb.sql-editor.tabs.*", () => {+ const tabs = JSON.stringify([+ { id: "tab-1", worksheet: "worksheets/ws-1" },+ { id: "tab-2", worksheet: "worksheets/ws-2" },+ ]);+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ tabs+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem(+ "bb.sql-editor.tabs.projects/[email protected]"+ )+ ).toBe(tabs);+ expect(+ localStorage.getItem(+ "bb.sql-editor-tab.projects/[email protected]"+ )+ ).toBeNull();+ });++ test("migrates current-tab-id to bb.sql-editor.current-tab.*", () => {+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '"tab-1"'+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem(+ "bb.sql-editor.current-tab.projects/[email protected]"+ )+ ).toBe('"tab-1"');+ expect(+ localStorage.getItem(+ "bb.sql-editor-tab.projects/[email protected]"+ )+ ).toBeNull();+ });++ test("migrates both tab list and current tab together", () => {+ const tabs = JSON.stringify([+ { id: "tab-a", worksheet: "worksheets/ws-a" },+ { id: "tab-b", worksheet: "worksheets/ws-b" },+ ]);+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ tabs+ );+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '"tab-b"'+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem("bb.sql-editor.tabs.projects/[email protected]")+ ).toBe(tabs);+ expect(+ localStorage.getItem("bb.sql-editor.current-tab.projects/[email protected]")+ ).toBe('"tab-b"');+ });++ test("migrates tabs for multiple projects", () => {+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '[{"id":"t1"}]'+ );+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '[{"id":"t2"}]'+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem("bb.sql-editor.tabs.projects/[email protected]")+ ).toBe('[{"id":"t1"}]');+ expect(+ localStorage.getItem("bb.sql-editor.tabs.projects/[email protected]")+ ).toBe('[{"id":"t2"}]');+ });++ test("does not overwrite existing new tab key", () => {+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '[{"id":"old"}]'+ );+ localStorage.setItem(+ "bb.sql-editor.tabs.projects/[email protected]",+ '[{"id":"new"}]'+ );+ migrateStorageKeys();+ expect(+ localStorage.getItem("bb.sql-editor.tabs.projects/[email protected]")+ ).toBe('[{"id":"new"}]');+ });++ test("preserves all tabs during migration (no data loss)", () => {+ const twoTabs = [+ {+ id: "tab-1",+ worksheet: "worksheets/ws-1",+ mode: "READONLY",+ viewState: {},+ },+ {+ id: "tab-2",+ worksheet: "worksheets/ws-2",+ mode: "READONLY",+ viewState: {},+ },+ ];+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ JSON.stringify(twoTabs)+ );+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '"tab-2"'+ );++ migrateStorageKeys();++ const migrated = JSON.parse(+ localStorage.getItem(+ "bb.sql-editor.tabs.projects/[email protected]"+ )!+ );+ expect(migrated).toHaveLength(2);+ expect(migrated[0].id).toBe("tab-1");+ expect(migrated[1].id).toBe("tab-2");+ expect(+ localStorage.getItem(+ "bb.sql-editor.current-tab.projects/[email protected]"+ )+ ).toBe('"tab-2"');+ });+ });+});++describe("prefix renames", () => {+ test("migrates bb.plugin.open-ai.suggestions.* keys", () => {+ localStorage.setItem(+ "bb.plugin.open-ai.suggestions.abc123",+ '["SELECT 1"]'+ );+ localStorage.setItem(+ "bb.plugin.open-ai.suggestions.def456",+ '["SELECT 2"]'+ );+ migrateStorageKeys();+ expect(localStorage.getItem("bb.ai.suggestions.abc123")).toBe(+ '["SELECT 1"]'+ );+ expect(localStorage.getItem("bb.ai.suggestions.def456")).toBe(+ '["SELECT 2"]'+ );+ expect(+ localStorage.getItem("bb.plugin.open-ai.suggestions.abc123")+ ).toBeNull();+ expect(+ localStorage.getItem("bb.plugin.open-ai.suggestions.def456")+ ).toBeNull();+ });++ test("migrates bb.context-menu-button.* keys", () => {+ localStorage.setItem("bb.context-menu-button.task-transition", '"approve"');+ migrateStorageKeys();+ expect(localStorage.getItem("bb.context-menu.task-transition")).toBe(+ '"approve"'+ );+ expect(+ localStorage.getItem("bb.context-menu-button.task-transition")+ ).toBeNull();+ });+});++describe("UI scope key renames", () => {+ test("migrates ui.list.collapse.{email}", () => {+ const state = JSON.stringify({ section1: true, section2: false });+ localStorage.setItem("[email protected]", state);+ migrateStorageKeys();+ expect(localStorage.getItem("[email protected]")).toBe(+ state+ );+ expect(+ localStorage.getItem("[email protected]")+ ).toBeNull();+ });++ test("migrates ui.intro.{email}", () => {+ const state = JSON.stringify({ tip1: true });+ localStorage.setItem("[email protected]", state);+ migrateStorageKeys();+ expect(localStorage.getItem("[email protected]")).toBe(state);+ expect(localStorage.getItem("[email protected]")).toBeNull();+ });++ test("migrates {email}.require_reset_password", () => {+ localStorage.setItem("[email protected]_reset_password", "true");+ migrateStorageKeys();+ expect(localStorage.getItem("[email protected]")).toBe(+ "true"+ );+ expect(+ localStorage.getItem("[email protected]_reset_password")+ ).toBeNull();+ });+});++describe("full migration scenario", () => {+ test("migrates all key types in a single run", () => {+ // Static+ localStorage.setItem("ui.backPath", "/dashboard");+ // Language+ localStorage.setItem(+ "bytebase_options",+ JSON.stringify({ appearance: { language: "ja-JP" } })+ );+ // SQL editor+ localStorage.setItem("bb.sql-editor.result-rows-limit", "100");+ localStorage.setItem("bb.sql-editor.last-viewed-project", '"projects/p1"');+ // Connection expanded+ localStorage.setItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]",+ '{"initialized":true,"expandedKeys":["k1"]}'+ );+ // Tab keys+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '[{"id":"t1"},{"id":"t2"}]'+ );+ localStorage.setItem(+ "bb.sql-editor-tab.projects/[email protected]",+ '"t2"'+ );+ // Prefix+ localStorage.setItem("bb.plugin.open-ai.suggestions.hash1", '["s1"]');+ // UI scope+ localStorage.setItem("[email protected]", '{"done":true}');++ migrateStorageKeys();++ // Verify all migrated+ expect(localStorage.getItem(STORAGE_KEY_BACK_PATH)).toBe("/dashboard");+ expect(localStorage.getItem(STORAGE_KEY_LANGUAGE)).toBe('"ja-JP"');+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT)).toBe(+ "100"+ );+ expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT)).toBe(+ '"projects/p1"'+ );+ expect(+ localStorage.getItem(+ "bb.sql-editor.conn-expanded.environments/[email protected]"+ )+ ).toBe('{"initialized":true,"expandedKeys":["k1"]}');+ expect(localStorage.getItem("bb.ai.suggestions.hash1")).toBe('["s1"]');+ expect(localStorage.getItem("[email protected]")).toBe(+ '{"done":true}'+ );+ // Tab keys+ const tabs = JSON.parse(+ localStorage.getItem("bb.sql-editor.tabs.projects/[email protected]")!+ );+ expect(tabs).toHaveLength(2);+ expect(+ localStorage.getItem("bb.sql-editor.current-tab.projects/[email protected]")+ ).toBe('"t2"');++ // Verify old keys removed+ expect(localStorage.getItem("ui.backPath")).toBeNull();+ expect(localStorage.getItem("bytebase_options")).toBeNull();+ expect(localStorage.getItem("bb.sql-editor.result-rows-limit")).toBeNull();+ expect(+ localStorage.getItem("bb.sql-editor.last-viewed-project")+ ).toBeNull();+ expect(+ localStorage.getItem(+ "bb.sql-editor.connection-pane.expanded_environments/[email protected]"+ )+ ).toBeNull();+ expect(+ localStorage.getItem("bb.plugin.open-ai.suggestions.hash1")+ ).toBeNull();+ expect(localStorage.getItem("[email protected]")).toBeNull();+ expect(+ localStorage.getItem(+ "bb.sql-editor-tab.projects/[email protected]"+ )+ ).toBeNull();+ expect(+ localStorage.getItem(+ "bb.sql-editor-tab.projects/[email protected]"+ )+ ).toBeNull();++ // Marker set+ expect(localStorage.getItem(MIGRATION_MARKER)).toBe("1");+ });++ test("handles empty localStorage gracefully", () => {+ migrateStorageKeys();+ expect(localStorage.getItem(MIGRATION_MARKER)).toBe("1");+ expect(localStorage.length).toBe(1); // only the marker+ });++ test("preserves unrelated keys", () => {+ localStorage.setItem("some.other.key", "value");+ localStorage.setItem("bb.sql-editor.result-rows-limit", "500");+ migrateStorageKeys();+ expect(localStorage.getItem("some.other.key")).toBe("value");+ });+});diff --git a/frontend/src/utils/storage-migrate.ts b/frontend/src/utils/storage-migrate.tsnew file mode 100644index 0000000000..a400e47575--- /dev/null+++ b/frontend/src/utils/storage-migrate.ts@@ -0,0 +1,187 @@+// One-time migration for renamed localStorage keys.+// Runs before stores/components initialize so they read from the new keys.++import {+ STORAGE_KEY_AI_DISMISS,+ STORAGE_KEY_BACK_PATH,+ STORAGE_KEY_LANGUAGE,+ STORAGE_KEY_ONBOARDING,+ STORAGE_KEY_SCHEMA_EDITOR_PREVIEW,+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,+ STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ STORAGE_KEY_SQL_EDITOR_REDIS_NODE,+ STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT,+} from "./storage-keys";++const MIGRATION_MARKER = "bb.storage-migration-v1";++// Static key renames: [oldKey, newKey]+const STATIC_KEY_RENAMES: [string, string][] = [+ ["ui.backPath", STORAGE_KEY_BACK_PATH],+ ["bb.onboarding-state", STORAGE_KEY_ONBOARDING],+ ["bb.sql-editor.result-rows-limit", STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT],+ ["bb.sql-editor.redis-command-node", STORAGE_KEY_SQL_EDITOR_REDIS_NODE],+ ["bb.schema-editor.preview.expanded", STORAGE_KEY_SCHEMA_EDITOR_PREVIEW],+ ["bb.plugin.open-ai.dismiss-placeholder", STORAGE_KEY_AI_DISMISS],+ ["bb.plugin.editor.ai-panel-size", STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE],+ ["bb.sql-editor.last-viewed-project", STORAGE_KEY_SQL_EDITOR_LAST_PROJECT],+];++// Prefix renames: [oldPrefix, newPrefix]+// Moves all keys matching `oldPrefix.*` to `newPrefix.*`+const PREFIX_RENAMES: [string, string][] = [+ ["bb.plugin.open-ai.suggestions.", "bb.ai.suggestions."],+ ["bb.context-menu-button.", "bb.context-menu."],+];++function moveKey(oldKey: string, newKey: string) {+ const value = localStorage.getItem(oldKey);+ if (value !== null && localStorage.getItem(newKey) === null) {+ localStorage.setItem(newKey, value);+ }+ localStorage.removeItem(oldKey);+}++function migrateLanguage() {+ // Old format: key "bytebase_options", value {"appearance":{"language":"zh-CN"}}+ // New format: key "bb.language", value "zh-CN" (plain string, JSON-serialized)+ const old = localStorage.getItem("bytebase_options");+ if (!old) return;++ if (localStorage.getItem(STORAGE_KEY_LANGUAGE) === null) {+ try {+ const parsed = JSON.parse(old) as {+ appearance?: { language?: string };+ };+ const lang = parsed?.appearance?.language;+ if (lang) {+ // useLocalStorage with string type stores as JSON-serialized string+ localStorage.setItem(STORAGE_KEY_LANGUAGE, JSON.stringify(lang));+ }+ } catch {+ // ignore malformed+ }+ }+ localStorage.removeItem("bytebase_options");+}++function migrateStaticKeys() {+ for (const [oldKey, newKey] of STATIC_KEY_RENAMES) {+ moveKey(oldKey, newKey);+ }+}++function migratePrefixKeys() {+ for (const [oldPrefix, newPrefix] of PREFIX_RENAMES) {+ const keysToMigrate: [string, string][] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (key?.startsWith(oldPrefix)) {+ const suffix = key.slice(oldPrefix.length);+ keysToMigrate.push([key, `${newPrefix}${suffix}`]);+ }+ }+ for (const [oldKey, newKey] of keysToMigrate) {+ moveKey(oldKey, newKey);+ }+ }+}++function migrateUIScopeKeys() {+ // Old UI state keys used different prefixes scoped by email:+ // "ui.list.collapse.{email}" → "bb.collapse-state.{email}"+ // "ui.intro.{email}" → "bb.intro-state.{email}"+ // "{email}.require_reset_password" → "bb.reset-password.{email}"+ const keysToMigrate: [string, string][] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (!key) continue;++ if (key.startsWith("ui.list.collapse.")) {+ const email = key.slice("ui.list.collapse.".length);+ keysToMigrate.push([key, `bb.collapse-state.${email}`]);+ } else if (key.startsWith("ui.intro.")) {+ const email = key.slice("ui.intro.".length);+ keysToMigrate.push([key, `bb.intro-state.${email}`]);+ } else if (key.endsWith(".require_reset_password")) {+ const email = key.slice(0, -".require_reset_password".length);+ keysToMigrate.push([key, `bb.reset-password.${email}`]);+ }+ }+ for (const [oldKey, newKey] of keysToMigrate) {+ moveKey(oldKey, newKey);+ }+}++function migrateSqlEditorTabKeys() {+ // Old: "bb.sql-editor-tab.{project}.{email}.opening-tab-list"+ // → "bb.sql-editor.tabs.{project}.{email}"+ // Old: "bb.sql-editor-tab.{project}.{email}.current-tab-id"+ // → "bb.sql-editor.current-tab.{project}.{email}"+ //+ // Must run here (before stores init) because useDynamicLocalStorage+ // writes default [] to the new key when it doesn't exist yet,+ // which would race with the in-store migrateTabKeys.+ const OLD_PREFIX = "bb.sql-editor-tab.";+ const TAB_LIST_SUFFIX = ".opening-tab-list";+ const CURRENT_TAB_SUFFIX = ".current-tab-id";++ const keysToMigrate: [string, string][] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (!key?.startsWith(OLD_PREFIX)) continue;++ if (key.endsWith(TAB_LIST_SUFFIX)) {+ // "bb.sql-editor-tab.{project}.{email}.opening-tab-list"+ // → middle = "{project}.{email}"+ const middle = key.slice(OLD_PREFIX.length, -TAB_LIST_SUFFIX.length);+ keysToMigrate.push([key, `bb.sql-editor.tabs.${middle}`]);+ } else if (key.endsWith(CURRENT_TAB_SUFFIX)) {+ const middle = key.slice(OLD_PREFIX.length, -CURRENT_TAB_SUFFIX.length);+ keysToMigrate.push([key, `bb.sql-editor.current-tab.${middle}`]);+ }+ }+ for (const [oldKey, newKey] of keysToMigrate) {+ moveKey(oldKey, newKey);+ }+}++function migrateSqlEditorConnKeys() {+ // "bb.sql-editor.connection-pane.expanded_{env}.{email}"+ // → "bb.sql-editor.conn-expanded.{env}.{email}"+ // "bb.sql-editor.connection-pane.expanded-keys.{name}"+ // → "bb.sql-editor.conn-expanded-keys.{email}" (name→email can't auto-migrate)+ const keysToMigrate: [string, string][] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (!key) continue;++ if (key.startsWith("bb.sql-editor.connection-pane.expanded_")) {+ // Format: bb.sql-editor.connection-pane.expanded_{env}.{email}+ const suffix = key.slice(+ "bb.sql-editor.connection-pane.expanded_".length+ );+ keysToMigrate.push([key, `bb.sql-editor.conn-expanded.${suffix}`]);+ }+ }+ for (const [oldKey, newKey] of keysToMigrate) {+ moveKey(oldKey, newKey);+ }+}++/**+ * Run all localStorage key migrations. Idempotent — skips if already done.+ * Must be called before any store or composable reads from localStorage.+ */+export function migrateStorageKeys() {+ if (localStorage.getItem(MIGRATION_MARKER)) return;++ migrateLanguage();+ migrateStaticKeys();+ migratePrefixKeys();+ migrateUIScopeKeys();+ migrateSqlEditorTabKeys();+ migrateSqlEditorConnKeys();++ localStorage.setItem(MIGRATION_MARKER, "1");+}diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vueindex f778ab93ba..fc5b8fa1de 100644--- a/frontend/src/views/DashboardHeader.vue+++ b/frontend/src/views/DashboardHeader.vue@@ -102,6 +102,7 @@ import { PlanType } from "@/types/proto-es/v1/subscription_service_pb";import {extractDatabaseResourceName,extractProjectResourceName,+ STORAGE_KEY_MY_ISSUES_TAB,} from "@/utils";import BytebaseLogo from "../components/BytebaseLogo.vue";import ProfileBrandingLogo from "../components/ProfileBrandingLogo.vue";@@ -202,10 +203,7 @@ const myIssueLink = computed(() => {const goToMyIssues = () => {record(myIssueLink.value.fullPath);// Trigger page reload manually.- useLocalStorage<string>(- `bb.components.${WORKSPACE_ROUTE_MY_ISSUES}.id`,- ""- ).value = uuidv4();+ useLocalStorage<string>(STORAGE_KEY_MY_ISSUES_TAB, "").value = uuidv4();};const handleWantHelp = () => {diff --git a/frontend/src/views/MyIssues.vue b/frontend/src/views/MyIssues.vueindex 537f4c20f6..fdc068bd52 100644--- a/frontend/src/views/MyIssues.vue+++ b/frontend/src/views/MyIssues.vue@@ -35,7 +35,6 @@ import { useRoute, useRouter } from "vue-router";import { IssueSearch } from "@/components/IssueV1/components";import IssueTableV1 from "@/components/IssueV1/components/IssueTableV1.vue";import PagedTable from "@/components/v2/Model/PagedTable.vue";-import { WORKSPACE_ROUTE_MY_ISSUES } from "@/router/dashboard/workspaceRoutes";import {useCurrentUserV1,useIssueV1Store,@@ -51,6 +50,7 @@ import {buildIssueFilterBySearchParams,buildSearchParamsBySearchText,buildSearchTextBySearchParams,+ STORAGE_KEY_MY_ISSUES_TAB,} from "@/utils";interface LocalState {@@ -63,10 +63,7 @@ const me = useCurrentUserV1();const issueStore = useIssueV1Store();const issuePagedTable = ref<ComponentExposed<typeof PagedTable<Issue>>>();-const viewId = useLocalStorage<string>(- `bb.components.${WORKSPACE_ROUTE_MY_ISSUES}.id`,- ""-);+const viewId = useLocalStorage<string>(STORAGE_KEY_MY_ISSUES_TAB, "");const defaultSearchParams = (): SearchParams => {const myEmail = me.value.email;diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vueindex c80a5dc13c..d64c1f7bf6 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/ConnectionPane.vue@@ -260,6 +260,7 @@ import {getValuesFromSearchParams,isDatabaseV1Queryable,isDescendantOf,+ storageKeySqlEditorConnExpandedKeys,useDynamicLocalStorage,} from "@/utils";import { useSQLEditorContext } from "../../context";@@ -301,10 +302,7 @@ const expandedState = useDynamicLocalStorage<{initialized: boolean;expandedKeys: string[];}>(- computed(- () =>- `bb.sql-editor.connection-pane.expanded-keys.${currentUser.value.name}`- ),+ computed(() => storageKeySqlEditorConnExpandedKeys(currentUser.value.email)),{initialized: false,expandedKeys: [],diff --git a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/tree.ts b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/tree.tsindex dad6454da6..230bb09a13 100644--- a/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/tree.ts+++ b/frontend/src/views/sql-editor/ConnectionPanel/ConnectionPane/tree.ts@@ -22,6 +22,7 @@ import type { Database } from "@/types/proto-es/v1/database_service_pb";import {getDefaultPagination,isDatabaseV1Queryable,+ storageKeySqlEditorConnExpanded,useDynamicLocalStorage,} from "@/utils";@@ -66,9 +67,8 @@ export const useSQLEditorTreeByEnvironment = (initialized: boolean;expandedKeys: string[];}>(- computed(- () =>- `bb.sql-editor.connection-pane.expanded_${environment}.${currentUser.value.email}`+ computed(() =>+ storageKeySqlEditorConnExpanded(environment, currentUser.value.email)),{initialized: false,diff --git a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vueindex dc13a8b489..a4bbb9697a 100644--- a/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue+++ b/frontend/src/views/sql-editor/EditorCommon/ResultView/DetailPanel/DetailPanel.vue@@ -159,6 +159,10 @@ import { NButton, NPopover, NScrollbar, NTooltip } from "naive-ui";import { computed } from "vue";import { CopyButton, DrawerContent } from "@/components/v2";import type { QueryResult } from "@/types/proto-es/v1/sql_service_pb";+import {+ STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,+ STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,+} from "@/utils";import { useSQLResultViewContext } from "../context";import BinaryFormatButton from "../DataTable/common/BinaryFormatButton.vue";import {@@ -176,11 +180,11 @@ const { dark, detail, disallowCopyingData } = useSQLResultViewContext();const { getBinaryFormat, setBinaryFormat } = useBinaryFormatContext();const format = useLocalStorage<boolean>(- "bb.sql-editor.detail-panel.format",+ STORAGE_KEY_SQL_EDITOR_DETAIL_FORMAT,false);const wrap = useLocalStorage<boolean>(- "bb.sql-editor.detail-panel.line-wrap",+ STORAGE_KEY_SQL_EDITOR_DETAIL_LINE_WRAP,true);diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vueindex a7a56060a4..057b190cc4 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/ViewsPanel/ViewDetail.vue@@ -87,6 +87,7 @@ import type {SchemaMetadata,ViewMetadata,} from "@/types/proto-es/v1/database_service_pb";+import { STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT } from "@/utils";import { OpenAIButton } from "@/views/sql-editor/EditorCommon";import { useCurrentTabViewStateContext } from "../../context/viewState";import ColumnsTable from "./ColumnsTable.vue";@@ -113,7 +114,7 @@ const state = reactive<LocalState>({keyword: "",});const format = useLocalStorage<boolean>(- "bb.sql-editor.editor-panel.code-viewer.format",+ STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT,false);const selectedStatement = ref("");diff --git a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vueindex 25eb27e36f..9e3637d92c 100644--- a/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue+++ b/frontend/src/views/sql-editor/EditorPanel/Panels/common/CodeViewer.vue@@ -89,6 +89,7 @@ import type { Database } from "@/types/proto-es/v1/database_service_pb";import {getInstanceResource,nextAnimationFrame,+ STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT,type VueClass,} from "@/utils";import { useSQLEditorContext } from "@/views/sql-editor/context";@@ -109,7 +110,7 @@ const { showAIPanel, editorPanelSize, handleEditorPanelResize } =useSQLEditorContext();const AIContext = useAIContext();const format = useLocalStorage<boolean>(- "bb.sql-editor.editor-panel.code-viewer.format",+ STORAGE_KEY_SQL_EDITOR_CODE_VIEWER_FORMAT,false);const instanceEngine = computed(() => getInstanceResource(props.db).engine);diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.tsindex 3966601e06..4973fab255 100644--- a/frontend/src/views/sql-editor/Sheet/context.ts+++ b/frontend/src/views/sql-editor/Sheet/context.ts@@ -24,6 +24,8 @@ import {extractWorksheetConnection,getSheetStatement,isWorksheetReadableV1,+ storageKeySqlEditorWorksheetFilter,+ storageKeySqlEditorWorksheetTree,useDynamicLocalStorage,} from "@/utils";import { useFolderByView } from "./folder";@@ -400,8 +402,8 @@ export const provideSheetContext = () => {const { project } = storeToRefs(useSQLEditorStore());const filter = useDynamicLocalStorage<WorksheetFilter>(- computed(- () => `bb.sql-editor.${project.value}.worksheet-filter.${me.value.name}`+ computed(() =>+ storageKeySqlEditorWorksheetFilter(project.value, me.value.email)),{...INITIAL_FILTER,@@ -428,9 +430,8 @@ export const provideSheetContext = () => {};const expandedKeys = useDynamicLocalStorage<Set<string>>(- computed(- () =>- `bb.sql-editor.${project.value}.worksheet-tree-expand-keys.${me.value.name}`+ computed(() =>+ storageKeySqlEditorWorksheetTree(project.value, me.value.email)),new Set([...Object.values(viewContexts).map(diff --git a/frontend/src/views/sql-editor/Sheet/folder.ts b/frontend/src/views/sql-editor/Sheet/folder.tsindex 13ab58bdc2..ef63e2d93f 100644--- a/frontend/src/views/sql-editor/Sheet/folder.ts+++ b/frontend/src/views/sql-editor/Sheet/folder.ts@@ -1,7 +1,10 @@import { sortBy } from "lodash-es";import { type ComputedRef, computed } from "vue";import { useCurrentUserV1 } from "@/store";-import { useDynamicLocalStorage } from "@/utils";+import {+ storageKeySqlEditorWorksheetFolder,+ useDynamicLocalStorage,+} from "@/utils";import type { SheetViewMode } from "./types";export const useFolderByView = (@@ -11,9 +14,8 @@ export const useFolderByView = (const me = useCurrentUserV1();const rootPath = computed(() => `/${viewMode}`);- const localCacheKey = computed(- () =>- `bb.sql-editor.${project.value}.worksheet-folder.${viewMode}.${me.value.name}`+ const localCacheKey = computed(() =>+ storageKeySqlEditorWorksheetFolder(project.value, viewMode, me.value.email));const localCache = useDynamicLocalStorage<Set<string>>(localCacheKey,diff --git a/frontend/src/views/sql-editor/context.ts b/frontend/src/views/sql-editor/context.tsindex 8065b87dee..eb17fce637 100644--- a/frontend/src/views/sql-editor/context.ts+++ b/frontend/src/views/sql-editor/context.ts@@ -26,6 +26,7 @@ import {isSimilarDefaultSQLEditorTabTitle,isWorksheetWritableV1,NEW_WORKSHEET_TITLE,+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,suggestedTabTitleForSQLEditorConnection,} from "@/utils";import { openWorksheetByName } from "@/views/sql-editor/Sheet";@@ -118,7 +119,7 @@ export const provideSQLEditorContext = () => {const showConnectionPanel = ref(false);const aiPanelSize = useLocalStorage(- "bb.plugin.editor.ai-panel-size",+ STORAGE_KEY_SQL_EDITOR_AI_PANEL_SIZE,0.3 /* panel size should in [0.1, 1-minimumEditorPanelSize]*/);const showAIPanel = ref(false);