From 35a5e29a236e7a0551ccb34561361b0c6a41f6f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 2 May 2026 08:55:10 +0000 Subject: [PATCH] fix(frontend): drop infectious preference fallback, add migration latch QA review of the previous hardening commit identified two cross-user infection paths created by the smart-fallback read chain (CRIT-1/2), plus a UI-desync hazard from validation guards in setters (HIGH-1). - Extracted localStorage helpers and migration logic into composables/preferenceStorage.ts as a single source of truth. - Reads now hit only the active user's namespace - no anon / legacy fallback in the hot path. Pre-existing values are migrated **once** per active user via migratePreferencesIntoUser, which adopts anon and legacy keys into the user namespace and then deletes the source keys, so a second user logging into the same browser cannot inherit the previous user's preferences. - Migration latch tracks which user has already been migrated this session; auth store's reloadUserPreferences resets the latch on setUser/logout so the next active user gets a fresh migration. - setSansFont / setMonoFont / setFontSize / setTheme now return a boolean; GeneralSettings.vue handlers roll the form back to the canonical state when validation rejects a value, preventing the UI from drifting out of sync with the source of truth. - safeSetItem now console.warn on persistence failures so quota / private-mode issues are at least diagnosable. - applyFont is diff-aware: only the CSS variables that actually changed are written to the root style, avoiding unnecessary style recalculation when only one knob is flipped. - applyTheme caches the last effective mode to skip redundant attribute writes and Wails IPC calls. https://claude.ai/code/session_01S1FVPf4jRfWXkTSnpMmMp7 --- frontend/src/composables/preferenceStorage.ts | 119 ++++++++++++++++++ frontend/src/composables/useFont.ts | 107 +++++++--------- frontend/src/composables/useTheme.ts | 67 +++------- frontend/src/stores/auth.ts | 3 + .../src/views/settings/GeneralSettings.vue | 22 +++- 5 files changed, 198 insertions(+), 120 deletions(-) create mode 100644 frontend/src/composables/preferenceStorage.ts diff --git a/frontend/src/composables/preferenceStorage.ts b/frontend/src/composables/preferenceStorage.ts new file mode 100644 index 00000000..239ea1bc --- /dev/null +++ b/frontend/src/composables/preferenceStorage.ts @@ -0,0 +1,119 @@ +/** + * Shared localStorage utilities for per-user UI preferences (theme, fonts). + * + * Storage layout: WeKnora_${userId}_${suffix}, where userId is the active + * user's id or "anon" before login. Read paths are intentionally narrow — + * no cross-namespace fallbacks — so one user's preferences cannot bleed + * into another user's session. + * + * One-shot migration adopts pre-existing values into the current user's + * namespace at login time: + * - Legacy un-namespaced keys (WeKnora_${suffix}) from earlier branch + * versions are inherited and removed. + * - The "anon" namespace (used while no user is logged in) is also + * adopted and cleared, so the next user to log in cannot inherit it. + */ + +const PREFERENCE_SUFFIXES = [ + 'theme', + 'font_sans', + 'font_mono', + 'font_size', +] as const + +export function readUserId(): string { + try { + const raw = localStorage.getItem('weknora_user') + if (!raw) return 'anon' + const parsed = JSON.parse(raw) + return parsed?.id ? String(parsed.id) : 'anon' + } catch { + return 'anon' + } +} + +export function safeGetItem(key: string): string | null { + try { + return localStorage.getItem(key) + } catch { + return null + } +} + +export function safeSetItem(key: string, value: string): void { + try { + localStorage.setItem(key, value) + } catch (err) { + // Quota exceeded, disabled storage, private mode — surface in DevTools + // so the issue is at least diagnosable, but don't break the UI. + console.warn(`[WeKnora] failed to persist preference "${key}":`, err) + } +} + +export function safeRemoveItem(key: string): void { + try { + localStorage.removeItem(key) + } catch { + // Same conditions as setItem; silent best-effort. + } +} + +export function userKey(suffix: string): string { + return `WeKnora_${readUserId()}_${suffix}` +} + +export function loadPreference(suffix: string): string | null { + return safeGetItem(userKey(suffix)) +} + +export function savePreference(suffix: string, value: string): void { + safeSetItem(userKey(suffix), value) +} + +let migratedForUser: string | null = null + +/** + * Adopt legacy and anon preferences into the current user's namespace, then + * remove the source keys. Idempotent per session per user — repeat calls for + * the same userId are no-ops. Safe to call before the user is logged in + * (it returns early when userId === "anon"). + */ +export function migratePreferencesIntoUser(): void { + const userId = readUserId() + if (userId === 'anon') return + if (migratedForUser === userId) return + migratedForUser = userId + + for (const suffix of PREFERENCE_SUFFIXES) { + const target = `WeKnora_${userId}_${suffix}` + const targetExists = safeGetItem(target) !== null + + const anonKey = `WeKnora_anon_${suffix}` + const legacyKey = `WeKnora_${suffix}` + + if (!targetExists) { + const anonValue = safeGetItem(anonKey) + if (anonValue !== null) { + safeSetItem(target, anonValue) + } else { + const legacyValue = safeGetItem(legacyKey) + if (legacyValue !== null) { + safeSetItem(target, legacyValue) + } + } + } + + // Always clean up source keys so subsequent users cannot inherit them. + safeRemoveItem(anonKey) + safeRemoveItem(legacyKey) + } +} + +/** Resets the per-session migration latch (used when the active user changes). */ +export function resetMigrationLatch(): void { + migratedForUser = null +} + +// Run migration once at module load so the composables that read from +// storage see post-migration values when initialising their refs. +migratePreferencesIntoUser() diff --git a/frontend/src/composables/useFont.ts b/frontend/src/composables/useFont.ts index 0abdf4ab..afa5026f 100644 --- a/frontend/src/composables/useFont.ts +++ b/frontend/src/composables/useFont.ts @@ -1,4 +1,9 @@ import { ref } from 'vue' +import { + loadPreference, + savePreference, + migratePreferencesIntoUser, +} from './preferenceStorage' export type FontKey = | 'system' @@ -72,66 +77,18 @@ const isMonoFontKey = (v: string | null): v is MonoFontKey => const isFontSizeKey = (v: string | null): v is FontSizeKey => v === 'small' || v === 'normal' || v === 'large' -function readUserId(): string { - try { - const raw = localStorage.getItem('weknora_user') - if (!raw) return 'anon' - const parsed = JSON.parse(raw) - return parsed?.id ? String(parsed.id) : 'anon' - } catch { - return 'anon' - } -} - -function safeGetItem(key: string): string | null { - try { - return localStorage.getItem(key) - } catch { - return null - } -} - -function safeSetItem(key: string, value: string): void { - try { - localStorage.setItem(key, value) - } catch { - // Quota / disabled storage / private mode — preference applies to this session only. - } -} - -/** - * Look up a stored preference, falling back through: - * 1. The current user's namespace - * 2. The "anon" namespace (settings chosen on the login screen) - * 3. A legacy un-namespaced key (from earlier versions of this branch) - */ -function resolveStorageValue(suffix: string): string | null { - const userId = readUserId() - const userValue = safeGetItem(`WeKnora_${userId}_${suffix}`) - if (userValue !== null) return userValue - if (userId !== 'anon') { - const anonValue = safeGetItem(`WeKnora_anon_${suffix}`) - if (anonValue !== null) return anonValue - } - return safeGetItem(`WeKnora_${suffix}`) -} - -function nsKey(suffix: string): string { - return `WeKnora_${readUserId()}_${suffix}` -} - function loadSans(): FontKey { - const v = resolveStorageValue(SANS_KEY) + const v = loadPreference(SANS_KEY) return isFontKey(v) ? v : DEFAULT_SANS } function loadMono(): MonoFontKey { - const v = resolveStorageValue(MONO_KEY) + const v = loadPreference(MONO_KEY) return isMonoFontKey(v) ? v : DEFAULT_MONO } function loadSize(): FontSizeKey { - const v = resolveStorageValue(SIZE_KEY) + const v = loadPreference(SIZE_KEY) return isFontSizeKey(v) ? v : DEFAULT_SIZE } @@ -139,37 +96,58 @@ const currentSans = ref(loadSans()) const currentMono = ref(loadMono()) const currentSize = ref(loadSize()) +// Track the last value applied to the DOM so we only rewrite CSS variables +// that actually changed. Avoids unnecessary style recalculation when the +// user only flips one of the three knobs. +const lastApplied: { sans: string; mono: string; scale: string } = { + sans: '', + mono: '', + scale: '', +} + function applyFont() { const root = document.documentElement if (!root) return const sansStack = SANS_STACKS[currentSans.value] ?? SANS_STACKS[DEFAULT_SANS] const monoStack = MONO_STACKS[currentMono.value] ?? MONO_STACKS[DEFAULT_MONO] - const scale = FONT_SCALES[currentSize.value] ?? FONT_SCALES[DEFAULT_SIZE] - root.style.setProperty('--app-font-family', sansStack) - root.style.setProperty('--app-font-family-mono', monoStack) - root.style.setProperty('--app-font-scale', String(scale)) + const scale = String(FONT_SCALES[currentSize.value] ?? FONT_SCALES[DEFAULT_SIZE]) + if (lastApplied.sans !== sansStack) { + root.style.setProperty('--app-font-family', sansStack) + lastApplied.sans = sansStack + } + if (lastApplied.mono !== monoStack) { + root.style.setProperty('--app-font-family-mono', monoStack) + lastApplied.mono = monoStack + } + if (lastApplied.scale !== scale) { + root.style.setProperty('--app-font-scale', scale) + lastApplied.scale = scale + } } export function useFont() { - function setSansFont(key: FontKey) { - if (!isFontKey(key)) return + function setSansFont(key: FontKey): boolean { + if (!isFontKey(key)) return false currentSans.value = key - safeSetItem(nsKey(SANS_KEY), key) + savePreference(SANS_KEY, key) applyFont() + return true } - function setMonoFont(key: MonoFontKey) { - if (!isMonoFontKey(key)) return + function setMonoFont(key: MonoFontKey): boolean { + if (!isMonoFontKey(key)) return false currentMono.value = key - safeSetItem(nsKey(MONO_KEY), key) + savePreference(MONO_KEY, key) applyFont() + return true } - function setFontSize(key: FontSizeKey) { - if (!isFontSizeKey(key)) return + function setFontSize(key: FontSizeKey): boolean { + if (!isFontSizeKey(key)) return false currentSize.value = key - safeSetItem(nsKey(SIZE_KEY), key) + savePreference(SIZE_KEY, key) applyFont() + return true } return { @@ -189,6 +167,7 @@ export function initFont() { /** Re-read preferences from storage (call after login / logout). */ export function reloadFontFromStorage() { + migratePreferencesIntoUser() currentSans.value = loadSans() currentMono.value = loadMono() currentSize.value = loadSize() diff --git a/frontend/src/composables/useTheme.ts b/frontend/src/composables/useTheme.ts index 01cd1877..24718a59 100644 --- a/frontend/src/composables/useTheme.ts +++ b/frontend/src/composables/useTheme.ts @@ -1,59 +1,16 @@ import { ref } from 'vue' +import { + loadPreference, + savePreference, + migratePreferencesIntoUser, +} from './preferenceStorage' export type ThemeMode = 'light' | 'dark' | 'system' const THEME_KEY = 'theme' -function readUserId(): string { - try { - const raw = localStorage.getItem('weknora_user') - if (!raw) return 'anon' - const parsed = JSON.parse(raw) - return parsed?.id ? String(parsed.id) : 'anon' - } catch { - return 'anon' - } -} - -function safeGetItem(key: string): string | null { - try { - return localStorage.getItem(key) - } catch { - return null - } -} - -function safeSetItem(key: string, value: string): void { - try { - localStorage.setItem(key, value) - } catch { - // Quota / disabled storage / private mode — preference applies to this session only. - } -} - -/** - * Look up a stored preference, falling back through: - * 1. The current user's namespace - * 2. The "anon" namespace (settings chosen on the login screen) - * 3. A legacy un-namespaced key (from earlier versions of this branch) - */ -function resolveStorageValue(suffix: string): string | null { - const userId = readUserId() - const userValue = safeGetItem(`WeKnora_${userId}_${suffix}`) - if (userValue !== null) return userValue - if (userId !== 'anon') { - const anonValue = safeGetItem(`WeKnora_anon_${suffix}`) - if (anonValue !== null) return anonValue - } - return safeGetItem(`WeKnora_${suffix}`) -} - -function nsKey(): string { - return `WeKnora_${readUserId()}_${THEME_KEY}` -} - function loadTheme(): ThemeMode { - const v = resolveStorageValue(THEME_KEY) + const v = loadPreference(THEME_KEY) if (v === 'light' || v === 'dark' || v === 'system') return v return 'light' } @@ -61,6 +18,8 @@ function loadTheme(): ThemeMode { // Shared reactive state across all consumers const currentTheme = ref(loadTheme()) +let lastEffective: 'light' | 'dark' | null = null + function getSystemTheme(): 'light' | 'dark' { return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' } @@ -103,16 +62,19 @@ function syncWailsNativeChrome(effective: 'light' | 'dark') { function applyTheme(mode: ThemeMode) { const effective = mode === 'system' ? getSystemTheme() : mode + if (lastEffective === effective) return + lastEffective = effective document.documentElement.setAttribute('theme-mode', effective) syncWailsNativeChrome(effective) } export function useTheme() { - function setTheme(mode: ThemeMode) { - if (mode !== 'light' && mode !== 'dark' && mode !== 'system') return + function setTheme(mode: ThemeMode): boolean { + if (mode !== 'light' && mode !== 'dark' && mode !== 'system') return false currentTheme.value = mode - safeSetItem(nsKey(), mode) + savePreference(THEME_KEY, mode) applyTheme(mode) + return true } return { currentTheme, setTheme } @@ -133,6 +95,7 @@ export function initTheme() { /** Re-read preferences from storage (call after login / logout). */ export function reloadThemeFromStorage() { + migratePreferencesIntoUser() currentTheme.value = loadTheme() applyTheme(currentTheme.value) } diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index 6730ba1a..0e7dc23b 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -5,10 +5,13 @@ import type { TenantInfo as TenantInfoFromAPI } from '@/api/tenant' import i18n from '@/i18n' import { reloadFontFromStorage } from '@/composables/useFont' import { reloadThemeFromStorage } from '@/composables/useTheme' +import { resetMigrationLatch } from '@/composables/preferenceStorage' // Per-user UI preferences are namespaced by user id in localStorage. // Reload them whenever the active user changes. function reloadUserPreferences() { + // Reset the latch so migration runs once for the new active user. + resetMigrationLatch() reloadFontFromStorage() reloadThemeFromStorage() } diff --git a/frontend/src/views/settings/GeneralSettings.vue b/frontend/src/views/settings/GeneralSettings.vue index 31e29426..248c7c13 100755 --- a/frontend/src/views/settings/GeneralSettings.vue +++ b/frontend/src/views/settings/GeneralSettings.vue @@ -292,23 +292,37 @@ const handleMemoryChange = (val: boolean) => { // 处理主题变化 const handleThemeChange = (val: ThemeMode) => { - setTheme(val) + if (!setTheme(val)) { + // Setter rejected the value (validation guard); roll the form back to + // the canonical state so the UI doesn't drift. + localTheme.value = currentTheme.value + return + } MessagePlugin.success(t('common.success')) } // 处理字体变化 const handleSansFontChange = (val: FontKey) => { - setSansFont(val) + if (!setSansFont(val)) { + localSansFont.value = currentSans.value + return + } MessagePlugin.success(t('common.success')) } const handleMonoFontChange = (val: MonoFontKey) => { - setMonoFont(val) + if (!setMonoFont(val)) { + localMonoFont.value = currentMono.value + return + } MessagePlugin.success(t('common.success')) } const handleFontSizeChange = (val: FontSizeKey) => { - setFontSize(val) + if (!setFontSize(val)) { + localFontSize.value = currentSize.value + return + } MessagePlugin.success(t('common.success')) }