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: add workspace to local storage cache key in saas mode (#20478)
ecmadao03525d53fb5c
diff --git a/frontend/src/react/components/IAMRemindDialog.tsx b/frontend/src/react/components/IAMRemindDialog.tsxindex 6026fb7987..a14d132a00 100644--- a/frontend/src/react/components/IAMRemindDialog.tsx+++ b/frontend/src/react/components/IAMRemindDialog.tsx@@ -21,7 +21,7 @@ import {} from "@/react/stores/app/utils";import type { Project } from "@/types/proto-es/v1/project_service_pb";import { displayRoleTitle, formatAbsoluteDateTime } from "@/utils";-import { storageKeyIamRemind } from "@/utils/storage-keys";+import { storageKeyIamRemind, workspaceCacheScope } from "@/utils/storage-keys";interface IAMRemindDialogProps {project: Project;@@ -32,6 +32,7 @@ export function IAMRemindDialog({ project }: IAMRemindDialogProps) {const route = useCurrentRoute();const navigate = useNavigate();const currentUser = useAppStore((state) => state.currentUser);+ const isSaaS = useAppStore((state) => state.isSaaSMode());const roles = useAppStore((state) => state.roles);const policy = useAppStore((state) => state.projectPoliciesByName[project.name]@@ -59,7 +60,10 @@ export function IAMRemindDialog({ project }: IAMRemindDialogProps) {}, [currentUser, policy, roles]);const storageKey = currentUser?.email- ? storageKeyIamRemind(currentUser.email)+ ? storageKeyIamRemind(+ workspaceCacheScope(isSaaS, currentUser.workspace),+ currentUser.email+ ): "";const remindKey =pendingExpireRoles.length > 0diff --git a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts b/frontend/src/react/components/sql-editor/ConnectionPane/tree.tsindex 9ee010f67b..922522b141 100644--- a/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts+++ b/frontend/src/react/components/sql-editor/ConnectionPane/tree.ts@@ -16,6 +16,7 @@ import {getDefaultPagination,isDatabaseV1Queryable,storageKeySqlEditorConnExpanded,+ workspaceCacheScope,} from "@/utils";const defaultEnvironmentFactor: StatefulFactor = {@@ -90,10 +91,17 @@ export function useSQLEditorTreeByEnvironment(const fetchDatabaseList = useAppStore((s) => s.fetchDatabases);const project = useSQLEditorEditorState((s) => s.project);const getEnvironmentByName = useAppStore((s) => s.getEnvironmentByName);+ const isSaaS = useAppStore((s) => s.isSaaSMode());+ const workspace = useAppStore((s) => s.currentUser?.workspace ?? "");const storageKey = useMemo(- () => storageKeySqlEditorConnExpanded(environment, email),- [environment, email]+ () =>+ storageKeySqlEditorConnExpanded(+ workspaceCacheScope(isSaaS, workspace),+ environment,+ ),+ [isSaaS, workspace, environment, email]);const [tree, setTree] = useState<SQLEditorTreeNode[]>([]);diff --git a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsxindex ee36c27c78..44c711ec76 100644--- a/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx+++ b/frontend/src/react/components/sql-editor/ResultView/SingleResultView.tsx@@ -29,6 +29,7 @@ import { Tooltip } from "@/react/components/ui/tooltip";import { useExecuteSQL } from "@/react/hooks/useExecuteSQL";import { useSQLEditorQueryDataPolicy } from "@/react/hooks/useSQLEditorBridge";import { cn } from "@/react/lib/utils";+import { useAppStore } from "@/react/stores/app";import { useSQLEditorEditorState } from "@/react/stores/sqlEditor/editor";import { useSQLEditorTabState } from "@/react/stores/sqlEditor/tab";import type {@@ -347,6 +348,12 @@ function SingleResultViewInner({[rows, columns, cellValueMatches]);+ // Tracks whether the previous searchParams already resolved to the+ // "active search, zero matches" state. Used to fire the no-results+ // notification only on the transition into that state — typing extra+ // characters that keep the match set empty must not re-notify.+ const wasInNoResultsRef = useRef(false);+useEffect(() => {const next = getNextCandidateRowIndex(0, searchParams);const indexes: number[] = [];@@ -357,7 +364,19 @@ function SingleResultViewInner({}setSearchCandidateRowIndexs(indexes);setSearchCandidateActiveIndex(0);- }, [searchParams, getNextCandidateRowIndex]);++ const searchActive =+ searchParams.query.trim().length > 0 || searchParams.scopes.length > 0;+ const isNoResults = searchActive && indexes.length === 0;+ if (isNoResults && !wasInNoResultsRef.current) {+ useAppStore.getState().notify({+ module: "bytebase",+ style: "INFO",+ title: t("sql-editor.search-no-result"),+ });+ }+ wasInNoResultsRef.current = isNoResults;+ }, [searchParams, getNextCandidateRowIndex, t]);const activeRowIndex =searchCandidateRowIndexs[searchCandidateActiveIndex] ?? -1;diff --git a/frontend/src/react/hooks/useAppState.ts b/frontend/src/react/hooks/useAppState.tsindex e6d97f745f..a8b9c96d2c 100644--- a/frontend/src/react/hooks/useAppState.ts+++ b/frontend/src/react/hooks/useAppState.ts@@ -17,7 +17,10 @@ import {unknownEnvironment,} from "@/types/v1/environment";import { unknownUser } from "@/types/v1/user";-import { storageKeyRecentProjects } from "@/utils/storage-keys";+import {+ storageKeyRecentProjects,+ workspaceCacheScope,+} from "@/utils/storage-keys";export { isConnectAlreadyExists };@@ -412,10 +415,10 @@ export function useProjectList(query: string) {};}-function readRecentProjectNames(email: string) {+function readRecentProjectNames(scope: string, email: string) {if (!email) return [];try {- const raw = localStorage.getItem(storageKeyRecentProjects(email));+ const raw = localStorage.getItem(storageKeyRecentProjects(scope, email));const parsed = raw ? JSON.parse(raw) : [];return Array.isArray(parsed)? parsed.filter((name): name is string => typeof name === "string")@@ -427,13 +430,15 @@ function readRecentProjectNames(email: string) {export function useRecentProjects() {const currentUser = useOptionalCurrentUser();+ const isSaaS = useIsSaaSMode();const batchFetchProjects = useAppStore((state) => state.batchFetchProjects);const projectsByName = useAppStore((state) => state.projectsByName);const [projectNames, setProjectNames] = useState<string[]>([]);+ const scope = workspaceCacheScope(isSaaS, currentUser?.workspace ?? "");const refreshNames = useCallback(() => {- setProjectNames(readRecentProjectNames(currentUser?.email ?? ""));- }, [currentUser?.email]);+ setProjectNames(readRecentProjectNames(scope, currentUser?.email ?? ""));+ }, [scope, currentUser?.email]);useEffect(() => {refreshNames();diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex 416a667896..be58162149 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -2656,6 +2656,7 @@"scroll-to-bottom": "Scroll to the bottom","scroll-to-top": "Scroll to the top","search-history-by-statement": "Search by statement",+ "search-no-result": "No matching result found","search-scope-column-description": "Column with {{type}} type. Enter a value and press Enter to jump to the matching row.","search-scope-row-number-description": "Enter a row number to jump to that row.","search-scope-row-number-title": "Row number",diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex 99a25c7b1c..cc137fba61 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -2656,6 +2656,7 @@"scroll-to-bottom": "Desplazarse hacia abajo","scroll-to-top": "Desplazarse hacia arriba","search-history-by-statement": "Búsqueda por enunciado",+ "search-no-result": "No se encontraron resultados coincidentes","search-scope-column-description": "Columna de tipo {{type}}. Ingrese un valor y presione Enter para saltar a la fila coincidente.","search-scope-row-number-description": "Ingrese un número de fila para saltar a esa fila.","search-scope-row-number-title": "Número de fila",diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex f2c586bfbb..0254f4a608 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -2656,6 +2656,7 @@"scroll-to-bottom": "末尾へスクロール","scroll-to-top": "先頭へスクロール","search-history-by-statement": "ステートメントで検索",+ "search-no-result": "一致する結果が見つかりません","search-scope-column-description": "{{type}}型の列。値を入力してEnterを押すと一致する行にジャンプします。","search-scope-row-number-description": "行番号を入力してその行にジャンプします。","search-scope-row-number-title": "行番号",diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 52e1c040ed..e06a2e7f92 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -2656,6 +2656,7 @@"scroll-to-bottom": "Cuộn xuống cuối","scroll-to-top": "Cuộn lên đầu","search-history-by-statement": "Tìm kiếm theo câu lệnh",+ "search-no-result": "Không tìm thấy kết quả phù hợp","search-scope-column-description": "Cột kiểu {{type}}. Nhập giá trị và nhấn Enter để chuyển đến dòng khớp.","search-scope-row-number-description": "Nhập số dòng để chuyển đến dòng đó.","search-scope-row-number-title": "Số dòng",diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex b925234ba3..7e09e0e52e 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -2656,6 +2656,7 @@"scroll-to-bottom": "滚动到底部","scroll-to-top": "滚动到顶部","search-history-by-statement": "搜索 SQL 语句",+ "search-no-result": "未找到匹配的结果","search-scope-column-description": "{{type}} 类型的列。输入值并按回车跳转到匹配行。","search-scope-row-number-description": "输入行号跳转到指定行。","search-scope-row-number-title": "行号",diff --git a/frontend/src/react/stores/app/index.test.ts b/frontend/src/react/stores/app/index.test.tsindex 4433921b71..7b2d7c5ed5 100644--- a/frontend/src/react/stores/app/index.test.ts+++ b/frontend/src/react/stores/app/index.test.ts@@ -1814,11 +1814,14 @@ describe("useAppStore", () => {store.getState().removeRecentVisit("/missing");store.getState().resetQuickstartProgress();+ // Not SaaS in this test, so keys are workspace-agnostic (scope "").expect(- JSON.parse(localStorage.getItem(storageKeyRecentProjects(user.email))!)+ JSON.parse(+ localStorage.getItem(storageKeyRecentProjects("", user.email))!+ )).toEqual([projectB.name, projectA.name]);expect(- JSON.parse(localStorage.getItem(storageKeyRecentVisit(user.email))!)+ JSON.parse(localStorage.getItem(storageKeyRecentVisit("", user.email))!)).toEqual(["/projects/a?tab=2"]);expect(JSON.parse(localStorage.getItem(storageKeyIntroState(user.email))!)@@ -1837,6 +1840,48 @@ describe("useAppStore", () => {window.removeEventListener(ReactShellBridgeEvent.quickstartReset, listener);});+ test("scopes recent projects by workspace in SaaS mode", () => {+ const store = createAppStore();+ // SaaS mode scopes cache keys by workspace.+ store.setState({+ serverInfo: createProto(ActuatorInfoSchema, { saas: true }),+ });+ store.setState({ currentUser: { ...user, workspace: "workspaces/a" } });+ store.getState().setRecentProject(projectA.name);+ store.getState().recordRecentVisit("/projects/a");++ // Same user, different workspace (e.g. after a SaaS workspace switch).+ store.setState({ currentUser: { ...user, workspace: "workspaces/b" } });+ store.getState().setRecentProject(projectB.name);+ store.getState().recordRecentVisit("/projects/b");++ expect(+ JSON.parse(+ localStorage.getItem(+ storageKeyRecentProjects("workspaces/a", user.email)+ )!+ )+ ).toEqual([projectA.name]);+ expect(+ JSON.parse(+ localStorage.getItem(+ storageKeyRecentProjects("workspaces/b", user.email)+ )!+ )+ ).toEqual([projectB.name]);+ // Recent-visit is isolated per workspace too.+ expect(+ JSON.parse(+ localStorage.getItem(storageKeyRecentVisit("workspaces/a", user.email))!+ )+ ).toEqual(["/projects/a"]);+ expect(+ JSON.parse(+ localStorage.getItem(storageKeyRecentVisit("workspaces/b", user.email))!+ )+ ).toEqual(["/projects/b"]);+ });+test("caches database metadata and reuses inflight request", async () => {const {DatabaseMetadataSchema,diff --git a/frontend/src/react/stores/app/preferences.ts b/frontend/src/react/stores/app/preferences.tsindex 230551ffd5..4426b26207 100644--- a/frontend/src/react/stores/app/preferences.ts+++ b/frontend/src/react/stores/app/preferences.ts@@ -7,6 +7,7 @@ import {import type { AppSliceCreator, PreferencesSlice } from "./types";import {getCurrentUserEmail,+ getWorkspaceCacheScope,MAX_RECENT_PROJECT,MAX_RECENT_VISIT,readJson,@@ -32,7 +33,7 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (setRecentProject: (name) => {const email = getCurrentUserEmail(get);if (!email || !name) return;- const key = storageKeyRecentProjects(email);+ const key = storageKeyRecentProjects(getWorkspaceCacheScope(get), email);const previous = readJson<string[]>(key, []);writeJson(key,@@ -46,7 +47,7 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (recordRecentVisit: (path) => {const email = getCurrentUserEmail(get);if (!email) return;- const key = storageKeyRecentVisit(email);+ const key = storageKeyRecentVisit(getWorkspaceCacheScope(get), email);const previous = readJson<string[]>(key, []);const pathOnly = path.replace(/[?#].*$/, "");const next = [@@ -59,7 +60,7 @@ export const createPreferencesSlice: AppSliceCreator<PreferencesSlice> = (removeRecentVisit: (path) => {const email = getCurrentUserEmail(get);if (!email) return;- const key = storageKeyRecentVisit(email);+ const key = storageKeyRecentVisit(getWorkspaceCacheScope(get), email);const previous = readJson<string[]>(key, []);writeJson(key,diff --git a/frontend/src/react/stores/app/utils.ts b/frontend/src/react/stores/app/utils.tsindex 6b761cdc06..c7bc54eaba 100644--- a/frontend/src/react/stores/app/utils.ts+++ b/frontend/src/react/stores/app/utils.ts@@ -16,6 +16,7 @@ import {unknownEnvironment,} from "@/types/v1/environment";import { isValidInstanceName } from "@/types/v1/instance";+import { workspaceCacheScope } from "@/utils/storage-keys";import type { AppStoreState } from "./types";export const MAX_RECENT_PROJECT = 5;@@ -27,6 +28,15 @@ export function getCurrentUserEmail(get: () => AppStoreState): string {return get().currentUser?.email ?? "";}+// Workspace segment for localStorage cache keys — "" for self-host (keys stay+// shared/unchanged), the workspace name for SaaS (keys are workspace-isolated).+export function getWorkspaceCacheScope(get: () => AppStoreState): string {+ return workspaceCacheScope(+ get().isSaaSMode(),+ get().currentUser?.workspace ?? ""+ );+}+export function readJson<T>(key: string, fallback: T): T {try {const raw = localStorage.getItem(key);diff --git a/frontend/src/react/stores/sqlEditor/editor.test.ts b/frontend/src/react/stores/sqlEditor/editor.test.tsindex 24fbedc14d..2202496d90 100644--- a/frontend/src/react/stores/sqlEditor/editor.test.ts+++ b/frontend/src/react/stores/sqlEditor/editor.test.ts@@ -1,8 +1,8 @@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,+ storageKeySqlEditorLastProject,} from "@/utils/storage-keys";import {getSQLEditorEditorState,@@ -63,7 +63,7 @@ describe("useSQLEditorEditorStore", () => {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(+ expect(JSON.parse(storage.get(storageKeySqlEditorLastProject(""))!)).toBe("projects/alpha");});diff --git a/frontend/src/react/stores/sqlEditor/editor.ts b/frontend/src/react/stores/sqlEditor/editor.tsindex 0437e1b6b1..057b1ebee6 100644--- a/frontend/src/react/stores/sqlEditor/editor.ts+++ b/frontend/src/react/stores/sqlEditor/editor.ts@@ -1,12 +1,14 @@import { useSyncExternalStore } from "react";import { create, type StoreApi, type UseBoundStore } from "zustand";import { immer } from "zustand/middleware/immer";+import { useAppStore } from "@/react/stores/app";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,+ storageKeySqlEditorLastProject,+ workspaceCacheScope,} from "@/utils/storage-keys";export interface SQLEditorEditorState {@@ -53,9 +55,25 @@ const safeWrite = (key: string, value: unknown) => {}};+// Workspace-scoped in SaaS so the last project of workspace A is never read+// after switching to workspace B (where it doesn't exist). Reads the app store+// at call time; if it isn't hydrated yet the scope falls back to "" and the+// project is re-resolved from the route anyway.+const lastProjectKey = () => {+ const state = useAppStore.getState();+ // Defensive: this runs at module-init (store may be pre-hydration) and the+ // app store is mocked in some tests, so isSaaSMode may be absent. Default to+ // the unscoped (self-host) key in that case.+ const isSaaS =+ typeof state?.isSaaSMode === "function" ? state.isSaaSMode() : false;+ return storageKeySqlEditorLastProject(+ workspaceCacheScope(isSaaS, state?.currentUser?.workspace ?? "")+ );+};+const readProject = () =>safeRead<string>(- STORAGE_KEY_SQL_EDITOR_LAST_PROJECT,+ lastProjectKey(),(v) => (typeof v === "string" ? v : undefined),"");@@ -95,7 +113,7 @@ export const useSQLEditorEditorStore: UseBoundStore<s.project = project;s.projectContextReady = true;});- safeWrite(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT, project);+ safeWrite(lastProjectKey(), project);},setProjectContextReady(ready) {set((s) => {diff --git a/frontend/src/react/stores/sqlEditor/tab.ts b/frontend/src/react/stores/sqlEditor/tab.tsindex b0b917abdc..4065838342 100644--- a/frontend/src/react/stores/sqlEditor/tab.ts+++ b/frontend/src/react/stores/sqlEditor/tab.ts@@ -24,6 +24,7 @@ import {getSheetStatement,storageKeySqlEditorCurrentTab,storageKeySqlEditorTabs,+ workspaceCacheScope,} from "@/utils";import {getSQLEditorEditorState,@@ -120,31 +121,50 @@ const safeWrite = (key: string, value: unknown) => {const isPersistentTabArray = (v: unknown): v is PersistentTab[] =>Array.isArray(v);-const currentScope = (): { project: string; email: string } | null => {+const currentScope = (): {+ wsScope: string;+ project: string;+ email: string;+} | null => {const project = getSQLEditorEditorState().project;if (!project) return null;// The current user is loaded into the app store during tab hydration// (see hydrateProjectTabs), so it's available by the time tabs are// persisted on user actions.- const email = useAppStore.getState().currentUser?.email ?? "";- return { project, email };+ const state = useAppStore.getState();+ const email = state.currentUser?.email ?? "";+ const wsScope = workspaceCacheScope(+ state.isSaaSMode(),+ state.currentUser?.workspace ?? ""+ );+ return { wsScope, project, email };};const persistOpenTabs = (openTabs: PersistentTab[]) => {const scope = currentScope();if (!scope) return;- safeWrite(storageKeySqlEditorTabs(scope.project, scope.email), openTabs);+ safeWrite(+ storageKeySqlEditorTabs(scope.wsScope, scope.project, scope.email),+ openTabs+ );};const persistCurrentTabId = (id: string) => {const scope = currentScope();if (!scope) return;- safeWrite(storageKeySqlEditorCurrentTab(scope.project, scope.email), id);+ safeWrite(+ storageKeySqlEditorCurrentTab(scope.wsScope, scope.project, scope.email),+ id+ );};-const readOpenTabs = (project: string, email: string): PersistentTab[] =>+const readOpenTabs = (+ wsScope: string,+ project: string,+ email: string+): PersistentTab[] =>safeRead<PersistentTab[]>(- storageKeySqlEditorTabs(project, email),+ storageKeySqlEditorTabs(wsScope, project, email),(v) => (isPersistentTabArray(v) ? v : undefined),[]);@@ -396,9 +416,14 @@ const hydrateProjectTabs = async (project: string): Promise<void> => {// Ensure the current user is loaded so tab storage is scoped to the// right email — the SQL editor route doesn't otherwise populate it.await useAppStore.getState().loadCurrentUser();- const email = useAppStore.getState().currentUser?.email ?? "";+ const state = useAppStore.getState();+ const email = state.currentUser?.email ?? "";+ const wsScope = workspaceCacheScope(+ state.isSaaSMode(),+ state.currentUser?.workspace ?? ""+ );- const storedTabs = readOpenTabs(project, email);+ const storedTabs = readOpenTabs(wsScope, project, email);const hydratedTabs: SQLEditorTab[] = [];const validPersistent: PersistentTab[] = [];diff --git a/frontend/src/router/useRecentVisit.ts b/frontend/src/router/useRecentVisit.tsindex 720a878304..7dba56ceb0 100644--- a/frontend/src/router/useRecentVisit.ts+++ b/frontend/src/router/useRecentVisit.ts@@ -1,15 +1,29 @@import { computed } from "vue";import { useCurrentUserV1 } from "@/store";+import { useActuatorV1Store } from "@/store/modules/v1/actuator";import { projectNamePrefix } from "@/store/modules/v1/common";-import { storageKeyRecentVisit, useDynamicLocalStorage } from "@/utils";+import {+ storageKeyRecentVisit,+ useDynamicLocalStorage,+ workspaceCacheScope,+} from "@/utils";const MAX_HISTORY = 10;export function useRecentVisit() {const currentUser = useCurrentUserV1();+ const actuatorStore = useActuatorV1Store();const recentVisit = useDynamicLocalStorage<string[]>(- computed(() => storageKeyRecentVisit(currentUser.value.email)),+ computed(() =>+ storageKeyRecentVisit(+ workspaceCacheScope(+ actuatorStore.isSaaSMode,+ currentUser.value.workspace+ ),+ currentUser.value.email+ )+ ),[]);diff --git a/frontend/src/utils/storage-keys.ts b/frontend/src/utils/storage-keys.tsindex 0c1f2711de..97c3093f7f 100644--- a/frontend/src/utils/storage-keys.ts+++ b/frontend/src/utils/storage-keys.ts@@ -1,18 +1,34 @@// Centralized localStorage key registry.// Static keys are plain constants; dynamic (user-scoped) keys are builder functions.+// Workspace cache scope. Self-host installs have a single workspace, so their+// keys stay workspace-agnostic — existing cached data is preserved with no+// migration. SaaS installs scope by workspace id so switching workspace (same+// email) never reads another workspace's cached resource references (project /+// database / environment names and route paths are unique only within a+// workspace). Returns "" for self-host, the workspace name for SaaS.+export const workspaceCacheScope = (+ isSaaS: boolean,+ workspace: string+): string => (isSaaS && workspace ? workspace : "");++// Joins a base key with an optional workspace scope segment and the rest.+// When scope is "" the key is byte-identical to the pre-scoping form (so+// self-host caches are untouched). `email` stays the trailing segment so the+// email-change migration (migrateUserStorage, renames by `.{email}` suffix)+// keeps working.+const withScope = (base: string, scope: string, ...rest: string[]): string =>+ [base, ...(scope ? [scope] : []), ...rest].join(".");+// --- Global (no user scope) ---export const STORAGE_KEY_BACK_PATH = "bb.back-path";export const STORAGE_KEY_LANGUAGE = "bb.language";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 =@@ -28,10 +44,11 @@ export const STORAGE_KEY_SQL_EDITOR_NOSQL_TABLE_VIEW =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}`;+// Workspace-scoped: holds route paths / project names that are workspace-local.+export const storageKeyRecentVisit = (scope: string, email: string) =>+ withScope("bb.recent-visit", scope, email);+export const storageKeyRecentProjects = (scope: string, email: string) =>+ withScope("bb.recent-projects", scope, email);export const storageKeyQuickAccess = (email: string) =>`bb.quick-access.${email}`;export const storageKeyLastActivity = (email: string) =>@@ -40,35 +57,52 @@ 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}`;+// Workspace-scoped: value keys embed project resource names.+export const storageKeyIamRemind = (scope: string, email: string) =>+ withScope("bb.iam-remind", scope, 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}`;+// Workspace-scoped: keys carry project / environment resource ids, which are+// unique only within a workspace (so they collide across workspaces in SaaS).+export const storageKeySqlEditorLastProject = (scope: string) =>+ withScope("bb.sql-editor.last-project", scope);+export const storageKeySqlEditorTabs = (+ scope: string,+ project: string,+ email: string+) => withScope("bb.sql-editor.tabs", scope, project, email);+export const storageKeySqlEditorCurrentTab = (+ scope: string,+ project: string,+ email: string+) => withScope("bb.sql-editor.current-tab", scope, project, email);+export const storageKeySqlEditorConnExpanded = (+ scope: string,+ env: string,+ email: string+) => withScope("bb.sql-editor.conn-expanded", scope, env, email);export const storageKeySqlEditorShowMissingQueryDb = (email: string) =>`bb.sql-editor.show-missing-query-db.${email}`;export const storageKeySqlEditorWorksheetFilter = (+ scope: string,project: string,email: string-) => `bb.sql-editor.worksheet-filter.${project}.${email}`;+) => withScope("bb.sql-editor.worksheet-filter", scope, project, email);export const storageKeySqlEditorWorksheetTree = (+ scope: string,project: string,email: string-) => `bb.sql-editor.worksheet-tree.${project}.${email}`;+) => withScope("bb.sql-editor.worksheet-tree", scope, project, email);export const storageKeySqlEditorWorksheetFolder = (+ scope: string,project: string,viewMode: string,email: string-) => `bb.sql-editor.worksheet-folder.${project}.${viewMode}.${email}`;+) =>+ withScope("bb.sql-editor.worksheet-folder", scope, project, viewMode, email);export const storageKeySqlEditorAiSuggestion = (email: string) =>`bb.sql-editor.ai-suggestion.${email}`;diff --git a/frontend/src/utils/storage-migrate.test.ts b/frontend/src/utils/storage-migrate.test.tsindex d85d430845..745f2b91f0 100644--- a/frontend/src/utils/storage-migrate.test.ts+++ b/frontend/src/utils/storage-migrate.test.ts@@ -6,9 +6,9 @@ import {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,+ storageKeySqlEditorLastProject,} from "./storage-keys";import { migrateStorageKeys } from "./storage-migrate";@@ -179,7 +179,7 @@ describe("SQL editor migrations", () => {'"projects/my-project"');migrateStorageKeys();- expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT)).toBe(+ expect(localStorage.getItem(storageKeySqlEditorLastProject(""))).toBe('"projects/my-project"');expect(@@ -507,7 +507,7 @@ describe("full migration scenario", () => {expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_RESULT_LIMIT)).toBe("100");- expect(localStorage.getItem(STORAGE_KEY_SQL_EDITOR_LAST_PROJECT)).toBe(+ expect(localStorage.getItem(storageKeySqlEditorLastProject(""))).toBe('"projects/p1"');expect(diff --git a/frontend/src/utils/storage-migrate.ts b/frontend/src/utils/storage-migrate.tsindex 113368b2d0..d0a82ca834 100644--- a/frontend/src/utils/storage-migrate.ts+++ b/frontend/src/utils/storage-migrate.ts@@ -8,9 +8,9 @@ import {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,+ storageKeySqlEditorLastProject,} from "./storage-keys";const MIGRATION_MARKER = "bb.storage-migration-v1";@@ -24,7 +24,9 @@ const STATIC_KEY_RENAMES: [string, string][] = [["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],+ // Pre-auth migration → unscoped key. Self-host reads it directly; SaaS+ // re-resolves the last project per-workspace on first use.+ ["bb.sql-editor.last-viewed-project", storageKeySqlEditorLastProject("")],];// Prefix renames: [oldPrefix, newPrefix]diff --git a/frontend/src/views/sql-editor/Sheet/context.ts b/frontend/src/views/sql-editor/Sheet/context.tsindex 55f60fc474..cccb8e73c5 100644--- a/frontend/src/views/sql-editor/Sheet/context.ts+++ b/frontend/src/views/sql-editor/Sheet/context.ts@@ -30,6 +30,7 @@ import {storageKeySqlEditorWorksheetFilter,storageKeySqlEditorWorksheetFolder,storageKeySqlEditorWorksheetTree,+ workspaceCacheScope,} from "@/utils";import { type SheetViewMode, SheetViewModeList } from "./types";@@ -260,12 +261,21 @@ const safeWriteJSON = (key: string, value: unknown) => {}};-const currentScope = (): { project: string; email: string } | null => {+const currentScope = (): {+ wsScope: string;+ project: string;+ email: string;+} | null => {const project = getSQLEditorEditorState().project;if (!project) return null;try {- const email = useAppStore.getState().currentUser?.email ?? "";- return { project, email };+ const state = useAppStore.getState();+ const email = state.currentUser?.email ?? "";+ const wsScope = workspaceCacheScope(+ state.isSaaSMode(),+ state.currentUser?.workspace ?? ""+ );+ return { wsScope, project, email };} catch {return null;}@@ -285,12 +295,16 @@ const reloadFromStorage = () => {if (!scope) return;const filter = safeReadJSON(- storageKeySqlEditorWorksheetFilter(scope.project, scope.email),+ storageKeySqlEditorWorksheetFilter(+ scope.wsScope,+ scope.project,+ scope.email+ ),(v) => (isWorksheetFilter(v) ? v : undefined)) ?? { ...INITIAL_FILTER };const expandedArray = safeReadJSON<string[]>(- storageKeySqlEditorWorksheetTree(scope.project, scope.email),+ storageKeySqlEditorWorksheetTree(scope.wsScope, scope.project, scope.email),(v) =>Array.isArray(v) && v.every((entry) => typeof entry === "string")? (v as string[])@@ -315,7 +329,12 @@ const reloadFromStorage = () => {for (const view of ["my", "shared", "draft"] as const) {const folders = safeReadJSON<string[]>(- storageKeySqlEditorWorksheetFolder(scope.project, view, scope.email),+ storageKeySqlEditorWorksheetFolder(+ scope.wsScope,+ scope.project,+ view,+ scope.email+ ),(v) =>Array.isArray(v) && v.every((entry) => typeof entry === "string")? (v as string[])@@ -339,7 +358,11 @@ const persistFilter = (filter: WorksheetFilter) => {const scope = currentScope();if (!scope) return;safeWriteJSON(- storageKeySqlEditorWorksheetFilter(scope.project, scope.email),+ storageKeySqlEditorWorksheetFilter(+ scope.wsScope,+ scope.project,+ scope.email+ ),filter);};@@ -347,16 +370,22 @@ const persistFilter = (filter: WorksheetFilter) => {const persistExpandedKeys = (keys: Set<string>) => {const scope = currentScope();if (!scope) return;- safeWriteJSON(storageKeySqlEditorWorksheetTree(scope.project, scope.email), [- ...keys,- ]);+ safeWriteJSON(+ storageKeySqlEditorWorksheetTree(scope.wsScope, scope.project, scope.email),+ [...keys]+ );};const persistViewFolders = (view: SheetViewMode, folders: string[]) => {const scope = currentScope();if (!scope) return;safeWriteJSON(- storageKeySqlEditorWorksheetFolder(scope.project, view, scope.email),+ storageKeySqlEditorWorksheetFolder(+ scope.wsScope,+ scope.project,+ view,+ scope.email+ ),folders);};