fix(desktop): persist UI state asynchronously
This commit is contained in:
1 parent
693eb0dbb9
commit
6b13564180
14 files changed
+547
-127
No files matched your search
@@ -160,13 +160,16 @@ describe("queryStore database open state", () => {
|
||||
storage.set(ACTIVE_TAB_STORAGE_KEY, "tab-1");
|
||||
setActivePinia(createPinia());
|
||||
|
||||
const { useSettingsStore } = await import("@/stores/settingsStore");
|
||||
const { useQueryStore } = await import("@/stores/queryStore");
|
||||
await useSettingsStore().initEditorSettings();
|
||||
const store = useQueryStore();
|
||||
await store.initOpenTabs();
|
||||
|
||||
expect(store.tabs).toEqual([]);
|
||||
expect(store.activeTabId).toBeNull();
|
||||
expect(storage.get(OPEN_TABS_STORAGE_KEY)).toBe(persistedTabs);
|
||||
expect(storage.get(ACTIVE_TAB_STORAGE_KEY)).toBe("tab-1");
|
||||
expect(storage.get(OPEN_TABS_STORAGE_KEY)).toBeUndefined();
|
||||
expect(storage.get(ACTIVE_TAB_STORAGE_KEY)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("restores only pinned tabs when launch restore mode is pinned", async () => {
|
||||
@@ -196,8 +199,11 @@ describe("queryStore database open state", () => {
|
||||
storage.set(ACTIVE_TAB_STORAGE_KEY, "tab-2");
|
||||
setActivePinia(createPinia());
|
||||
|
||||
const { useSettingsStore } = await import("@/stores/settingsStore");
|
||||
const { useQueryStore } = await import("@/stores/queryStore");
|
||||
await useSettingsStore().initEditorSettings();
|
||||
const store = useQueryStore();
|
||||
await store.initOpenTabs();
|
||||
|
||||
expect(store.tabs.map((tab) => tab.id)).toEqual(["tab-1"]);
|
||||
expect(store.activeTabId).toBe("tab-1");
|
||||
|
||||
@@ -7,7 +7,7 @@ import { orderPinnedFirst } from "@/lib/app/pinnedItems";
|
||||
import { canCancelQueryExecution } from "@/lib/sql/queryExecutionState";
|
||||
import { buildExplainSql, parseExplainResult, parseDamengExplainText } from "@/lib/diagram/explainPlan";
|
||||
import { allEditableColumnsWriteable, allPrimaryKeysPresent, analyzeEditableQuery, sourceColumnsForResult, type EditableQueryInfo } from "@/lib/sql/sqlAnalysis";
|
||||
import { ACTIVE_TAB_STORAGE_KEY, OPEN_TABS_STORAGE_KEY, restoreOpenTabsState, serializeOpenTabs } from "@/lib/app/openTabsPersistence";
|
||||
import { ACTIVE_TAB_STORAGE_KEY, OPEN_TABS_STORAGE_KEY, restoreOpenTabsPayload, restoreOpenTabsState, serializeOpenTabs } from "@/lib/app/openTabsPersistence";
|
||||
import {
|
||||
evaluateMongoAggregateSafety,
|
||||
evaluateMongoWriteSafety,
|
||||
@@ -44,7 +44,8 @@ import * as api from "@/lib/backend/api";
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useSavedSqlStore } from "@/stores/savedSqlStore";
|
||||
import { createSavedSqlEditorPosition, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
|
||||
import { createSavedSqlEditorPosition, initSavedSqlEditorPositions, restoreSavedSqlEditorPosition, saveSavedSqlEditorPosition } from "@/lib/app/savedSqlEditorPosition";
|
||||
import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
|
||||
import type { SavedSqlFile } from "@/types/database";
|
||||
|
||||
const ORACLE_LIKE_METADATA_TYPES = new Set<string>(["oracle", "dameng", "oceanbase-oracle"]);
|
||||
@@ -179,25 +180,41 @@ function normalizeOracleLikeQueryAnalysis(dbType: string, analysis: EditableQuer
|
||||
};
|
||||
}
|
||||
|
||||
function saveTabs(tabs: QueryTab[], activeTabId: string | null) {
|
||||
try {
|
||||
localStorage.setItem(OPEN_TABS_STORAGE_KEY, JSON.stringify(serializeOpenTabs(tabs)));
|
||||
localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, activeTabId || "");
|
||||
} catch {}
|
||||
let saveTabsQueue = Promise.resolve();
|
||||
|
||||
function saveTabs(tabs: QueryTab[], activeTabId: string | null): Promise<void> {
|
||||
const payload = { tabs: serializeOpenTabs(tabs), activeTabId };
|
||||
saveTabsQueue = saveTabsQueue.catch(() => undefined).then(() => api.saveOpenTabsState(payload));
|
||||
return saveTabsQueue;
|
||||
}
|
||||
|
||||
function loadSavedTabs(): { tabs: QueryTab[]; activeTabId: string | null } {
|
||||
try {
|
||||
const restoreMode = useSettingsStore().editorSettings.openTabsRestoreMode;
|
||||
if (restoreMode === "none") {
|
||||
return { tabs: [], activeTabId: null };
|
||||
}
|
||||
return restoreOpenTabsState(localStorage.getItem(OPEN_TABS_STORAGE_KEY), localStorage.getItem(ACTIVE_TAB_STORAGE_KEY), {
|
||||
filter: restoreMode === "pinned" ? "pinned" : "all",
|
||||
});
|
||||
} catch {
|
||||
return { tabs: [], activeTabId: null };
|
||||
}
|
||||
function loadLegacySavedTabs(): { rawTabs: string | null; rawActiveTabId: string | null } {
|
||||
return {
|
||||
rawTabs: safeLocalStorageGet(OPEN_TABS_STORAGE_KEY),
|
||||
rawActiveTabId: safeLocalStorageGet(ACTIVE_TAB_STORAGE_KEY),
|
||||
};
|
||||
}
|
||||
|
||||
function clearLegacySavedTabs() {
|
||||
safeLocalStorageRemove(OPEN_TABS_STORAGE_KEY);
|
||||
safeLocalStorageRemove(ACTIVE_TAB_STORAGE_KEY);
|
||||
}
|
||||
|
||||
function restoreSavedTabsFromPayload(payload: { tabs?: unknown; activeTabId?: unknown } | null | undefined): { tabs: QueryTab[]; activeTabId: string | null } {
|
||||
const restoreMode = useSettingsStore().editorSettings.openTabsRestoreMode;
|
||||
if (restoreMode === "none") return { tabs: [], activeTabId: null };
|
||||
return restoreOpenTabsPayload(payload, {
|
||||
filter: restoreMode === "pinned" ? "pinned" : "all",
|
||||
});
|
||||
}
|
||||
|
||||
function restoreLegacySavedTabs(): { tabs: QueryTab[]; activeTabId: string | null } {
|
||||
const restoreMode = useSettingsStore().editorSettings.openTabsRestoreMode;
|
||||
if (restoreMode === "none") return { tabs: [], activeTabId: null };
|
||||
const legacy = loadLegacySavedTabs();
|
||||
return restoreOpenTabsState(legacy.rawTabs, legacy.rawActiveTabId, {
|
||||
filter: restoreMode === "pinned" ? "pinned" : "all",
|
||||
});
|
||||
}
|
||||
|
||||
function getI18nT() {
|
||||
@@ -210,19 +227,16 @@ function getI18nT() {
|
||||
|
||||
export const useQueryStore = defineStore("query", () => {
|
||||
const t = getI18nT();
|
||||
const restored = loadSavedTabs();
|
||||
const tabs = ref<QueryTab[]>(restored.tabs);
|
||||
const activeTabId = ref<string | null>(restored.activeTabId);
|
||||
const activeTabHistory = ref<string[]>(restored.activeTabId ? [restored.activeTabId] : []);
|
||||
const tabs = ref<QueryTab[]>([]);
|
||||
const activeTabId = ref<string | null>(null);
|
||||
const isOpenTabsLoaded = ref(false);
|
||||
const activeTabHistory = ref<string[]>([]);
|
||||
const showCloseConfirm = ref(false);
|
||||
const pendingCloseTabId = ref<string | null>(null);
|
||||
const pendingBatchCloseTabIds = ref<string[] | null>(null);
|
||||
const pendingBatchCloseFinalActiveTabId = ref<string | null | undefined>(undefined);
|
||||
const isConfirmingAppClose = ref(false);
|
||||
const closeConfirmContext = ref<CloseConfirmContext>("tab");
|
||||
for (const tab of restored.tabs) {
|
||||
if (tab.mode === "data") void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
|
||||
}
|
||||
const tableStructureRefreshVersions = ref<Record<string, number>>({});
|
||||
const savedSqlEditorPositionTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
@@ -569,6 +583,41 @@ export const useQueryStore = defineStore("query", () => {
|
||||
clearResultPayload(tab, { evicted: true });
|
||||
}
|
||||
|
||||
function applyRestoredOpenTabs(restored: { tabs: QueryTab[]; activeTabId: string | null }) {
|
||||
tabs.value = restored.tabs;
|
||||
activeTabId.value = restored.activeTabId;
|
||||
activeTabHistory.value = restored.activeTabId ? [restored.activeTabId] : [];
|
||||
for (const tab of restored.tabs) {
|
||||
if (tab.mode === "data") void deleteTabResultSnapshot(tabResultCacheKey(tab.id));
|
||||
}
|
||||
}
|
||||
|
||||
async function initOpenTabs() {
|
||||
if (isOpenTabsLoaded.value) return;
|
||||
const saved = await api.loadOpenTabsState().catch(() => null);
|
||||
if (saved?.tabs && Array.isArray(saved.tabs)) {
|
||||
const restored = restoreSavedTabsFromPayload(saved);
|
||||
applyRestoredOpenTabs(restored);
|
||||
isOpenTabsLoaded.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const legacy = loadLegacySavedTabs();
|
||||
if (legacy.rawTabs || legacy.rawActiveTabId) {
|
||||
const restored = restoreLegacySavedTabs();
|
||||
applyRestoredOpenTabs(restored);
|
||||
try {
|
||||
await saveTabs(tabs.value, activeTabId.value);
|
||||
// Keep old desktop installs readable until the async store has the
|
||||
// migrated state; only then remove the synchronous startup payload.
|
||||
clearLegacySavedTabs();
|
||||
} catch {
|
||||
/* keep legacy values for a later migration attempt */
|
||||
}
|
||||
}
|
||||
isOpenTabsLoaded.value = true;
|
||||
}
|
||||
|
||||
const _persistSnapshot = computed(() =>
|
||||
tabs.value.map((t) => ({
|
||||
id: t.id,
|
||||
@@ -609,7 +658,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
() => {
|
||||
if (_persistTimer) clearTimeout(_persistTimer);
|
||||
_persistTimer = setTimeout(() => {
|
||||
saveTabs(tabs.value, activeTabId.value);
|
||||
void saveTabs(tabs.value, activeTabId.value).catch(() => {});
|
||||
_persistTimer = null;
|
||||
}, 300);
|
||||
},
|
||||
@@ -620,12 +669,12 @@ export const useQueryStore = defineStore("query", () => {
|
||||
// reflects the latest in-memory tabs without waiting for the 300ms debounce.
|
||||
// Lets callers (e.g. tests that reload the store) read back persisted state
|
||||
// deterministically instead of racing the debounce timer.
|
||||
function flushPendingPersist() {
|
||||
function flushPendingPersist(): Promise<void> {
|
||||
if (_persistTimer) {
|
||||
clearTimeout(_persistTimer);
|
||||
_persistTimer = null;
|
||||
}
|
||||
saveTabs(tabs.value, activeTabId.value);
|
||||
return saveTabs(tabs.value, activeTabId.value);
|
||||
}
|
||||
|
||||
function findTabByIdentity(connectionId: string, database: string, title: string, mode: QueryTab["mode"], schema?: string) {
|
||||
@@ -1473,6 +1522,7 @@ export const useQueryStore = defineStore("query", () => {
|
||||
}
|
||||
|
||||
async function hydrateSavedSqlTabs() {
|
||||
await initSavedSqlEditorPositions();
|
||||
const savedSqlStore = useSavedSqlStore();
|
||||
const linkedTabs = tabs.value.filter((tab) => tab.savedSqlId && tab.sql === "");
|
||||
for (const tab of linkedTabs) {
|
||||
@@ -2921,6 +2971,8 @@ export const useQueryStore = defineStore("query", () => {
|
||||
return {
|
||||
tabs,
|
||||
activeTabId,
|
||||
isOpenTabsLoaded,
|
||||
initOpenTabs,
|
||||
showCloseConfirm,
|
||||
pendingCloseTabId,
|
||||
closeConfirmContext,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { DEFAULT_SQL_SNIPPETS } from "@/lib/sql/sqlCompletion";
|
||||
import { setDebugLoggingEnabled } from "@/lib/backend/debugLog";
|
||||
import { DEFAULT_TABLE_COLUMN_TEMPLATE_FIELDS, normalizeTableColumnTemplateFields } from "@/lib/table/tableColumnTemplates";
|
||||
import { DEFAULT_UI_FONT_FAMILY } from "@/lib/app/appFonts";
|
||||
import { safeLocalStorageGet, safeLocalStorageRemove } from "@/lib/backend/safeStorage";
|
||||
|
||||
export type AiProvider = "claude" | "openai" | "gemini" | "deepseek" | "qwen" | "ollama" | "openai-compatible" | "codex-cli" | "custom";
|
||||
export type AiApiStyle = "completions" | "responses" | "anthropic-messages";
|
||||
@@ -751,46 +752,34 @@ export function normalizeEditorSettings(settings: Partial<EditorSettings>, exist
|
||||
};
|
||||
}
|
||||
|
||||
function loadEditorSettings(): EditorSettings {
|
||||
// Try new format first
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw) {
|
||||
function loadLegacyEditorSettings(): EditorSettings | null {
|
||||
const raw = safeLocalStorageGet(STORAGE_KEY);
|
||||
if (raw) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as Partial<EditorSettings>;
|
||||
if (parsed.exportBatchSize === LEGACY_DEFAULT_EXPORT_BATCH_SIZE && localStorage.getItem(EXPORT_BATCH_SIZE_DEFAULT_MIGRATION_KEY) !== "1") {
|
||||
if (parsed.exportBatchSize === LEGACY_DEFAULT_EXPORT_BATCH_SIZE && safeLocalStorageGet(EXPORT_BATCH_SIZE_DEFAULT_MIGRATION_KEY) !== "1") {
|
||||
parsed.exportBatchSize = DEFAULT_EDITOR_SETTINGS.exportBatchSize;
|
||||
localStorage.setItem(EXPORT_BATCH_SIZE_DEFAULT_MIGRATION_KEY, "1");
|
||||
const migrated = normalizeEditorSettings(parsed);
|
||||
saveEditorSettings(migrated);
|
||||
return migrated;
|
||||
}
|
||||
return normalizeEditorSettings(parsed);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
// Migrate old font-size key if new settings don't exist
|
||||
try {
|
||||
const oldSize = localStorage.getItem(OLD_FONT_SIZE_KEY);
|
||||
if (oldSize) {
|
||||
const parsed = parseInt(oldSize, 10);
|
||||
if (!isNaN(parsed)) {
|
||||
const migrated = normalizeEditorSettings({ fontSize: parsed });
|
||||
saveEditorSettings(migrated);
|
||||
localStorage.removeItem(OLD_FONT_SIZE_KEY);
|
||||
return migrated;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
const oldSize = safeLocalStorageGet(OLD_FONT_SIZE_KEY);
|
||||
if (!oldSize) return null;
|
||||
const parsed = parseInt(oldSize, 10);
|
||||
return Number.isNaN(parsed) ? null : normalizeEditorSettings({ fontSize: parsed });
|
||||
}
|
||||
|
||||
return normalizeEditorSettings({});
|
||||
function clearLegacyEditorSettings() {
|
||||
safeLocalStorageRemove(STORAGE_KEY);
|
||||
safeLocalStorageRemove(OLD_FONT_SIZE_KEY);
|
||||
safeLocalStorageRemove(EXPORT_BATCH_SIZE_DEFAULT_MIGRATION_KEY);
|
||||
}
|
||||
|
||||
function saveEditorSettings(settings: EditorSettings) {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
|
||||
void api.saveEditorSettings(settings).catch(() => {});
|
||||
}
|
||||
|
||||
export const useSettingsStore = defineStore("settings", () => {
|
||||
@@ -799,8 +788,33 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
const aiProviderConfigs = ref<Partial<Record<AiProvider, AiConfig>>>({});
|
||||
const desktopSettings = ref<DesktopSettings>({ ...DEFAULT_DESKTOP_SETTINGS });
|
||||
const isDesktopSettingsLoaded = ref(false);
|
||||
const isEditorSettingsLoaded = ref(false);
|
||||
|
||||
const editorSettings = ref<EditorSettings>(loadEditorSettings());
|
||||
const editorSettings = ref<EditorSettings>(normalizeEditorSettings({}));
|
||||
|
||||
async function initEditorSettings() {
|
||||
if (isEditorSettingsLoaded.value) return;
|
||||
const saved = await api.loadEditorSettings().catch(() => null);
|
||||
if (saved && typeof saved === "object" && !Array.isArray(saved)) {
|
||||
editorSettings.value = normalizeEditorSettings(saved as Partial<EditorSettings>);
|
||||
isEditorSettingsLoaded.value = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const legacy = loadLegacyEditorSettings();
|
||||
if (legacy) {
|
||||
editorSettings.value = legacy;
|
||||
try {
|
||||
await api.saveEditorSettings(legacy);
|
||||
// Existing desktop users keep settings in localStorage; remove them only
|
||||
// after the async store has accepted the migrated value.
|
||||
clearLegacyEditorSettings();
|
||||
} catch {
|
||||
/* keep legacy values for a later migration attempt */
|
||||
}
|
||||
}
|
||||
isEditorSettingsLoaded.value = true;
|
||||
}
|
||||
|
||||
async function initDesktopSettings() {
|
||||
if (isDesktopSettingsLoaded.value) return;
|
||||
@@ -1016,8 +1030,10 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
updateAiConfig,
|
||||
isConfigured,
|
||||
isAiProviderConfigured,
|
||||
isEditorSettingsLoaded,
|
||||
editorSettings,
|
||||
desktopSettings,
|
||||
initEditorSettings,
|
||||
updateEditorSettings,
|
||||
initDesktopSettings,
|
||||
updateDesktopSettings,
|
||||
|
||||
Reference in new issue
Block a user