fix(frontend): harden settings localStorage load after #1925
Validate parsed WeKnora_settings is a plain object, deep-clone defaults on reset, and reuse safeSetItem for reconcile write-back. Extracts load logic into settingsStorage with unit tests for corrupt and non-object JSON.
This commit is contained in:
@@ -3,7 +3,8 @@ import { nextTick } from "vue";
|
||||
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
|
||||
import { getApiBaseUrl } from "@/utils/api-base";
|
||||
import { updateMyPreferences, type UserPreferences } from "@/api/auth";
|
||||
import { isAgentStreamAgentId, reconcileBuiltinAgentMode } from "@/utils/agent-mode";
|
||||
import { isAgentStreamAgentId } from "@/utils/agent-mode";
|
||||
import { loadAndReconcileSettings } from "@/stores/settingsStorage";
|
||||
|
||||
// 定义设置接口
|
||||
interface Settings {
|
||||
@@ -110,35 +111,10 @@ const defaultSettings: Settings = {
|
||||
autoCheckUpdate: true,
|
||||
};
|
||||
|
||||
/** Keep builtin agent id and isAgentEnabled in sync after localStorage reload. */
|
||||
function loadAndReconcileSettings(): Settings {
|
||||
let loaded: Settings;
|
||||
try {
|
||||
const raw = localStorage.getItem("WeKnora_settings");
|
||||
loaded = raw ? (JSON.parse(raw) as Settings) : { ...defaultSettings };
|
||||
} catch (e) {
|
||||
console.error("[settings] Failed to parse WeKnora_settings from localStorage, resetting to defaults:", e);
|
||||
localStorage.removeItem("WeKnora_settings");
|
||||
return { ...defaultSettings };
|
||||
}
|
||||
loaded.selectedTags ||= [];
|
||||
loaded.selectedMCPServices ||= [];
|
||||
loaded.selectedSkills ||= loaded.selectedTools || [];
|
||||
loaded.selectedFileKbMap ||= {};
|
||||
if (reconcileBuiltinAgentMode(loaded)) {
|
||||
try {
|
||||
localStorage.setItem("WeKnora_settings", JSON.stringify(loaded));
|
||||
} catch {
|
||||
/* quota exceeded — non-critical */
|
||||
}
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
export const useSettingsStore = defineStore("settings", {
|
||||
state: () => ({
|
||||
// 从本地存储加载设置,如果没有则使用默认设置
|
||||
settings: loadAndReconcileSettings(),
|
||||
settings: loadAndReconcileSettings(defaultSettings),
|
||||
// 进入会话时拍下"全局默认"的快照;离开会话时还原。非持久化字段:
|
||||
// 刷新页面相当于重新走"进入会话"流程,自然会重新拍快照。
|
||||
_defaultsSnapshot: null as Settings | null,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const SETTINGS_STORAGE_KEY = "WeKnora_settings";
|
||||
const BUILTIN_QUICK_ANSWER_ID = "builtin-quick-answer";
|
||||
const BUILTIN_SMART_REASONING_ID = "builtin-smart-reasoning";
|
||||
|
||||
function reconcileBuiltinAgentMode(settings) {
|
||||
const agentId = settings.selectedAgentId || BUILTIN_QUICK_ANSWER_ID;
|
||||
if (agentId === BUILTIN_QUICK_ANSWER_ID && settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = false;
|
||||
return true;
|
||||
}
|
||||
if (agentId === BUILTIN_SMART_REASONING_ID && !settings.isAgentEnabled) {
|
||||
settings.isAgentEnabled = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function cloneSettings(settings) {
|
||||
return JSON.parse(JSON.stringify(settings));
|
||||
}
|
||||
|
||||
function isStoredSettingsRecord(value) {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function reconcileLoadedSettings(loaded) {
|
||||
loaded.selectedTags ||= [];
|
||||
loaded.selectedMCPServices ||= [];
|
||||
loaded.selectedSkills ||= loaded.selectedTools || [];
|
||||
loaded.selectedFileKbMap ||= {};
|
||||
if (reconcileBuiltinAgentMode(loaded)) {
|
||||
localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(loaded));
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
function resetStoredSettings(defaultSettings, reason) {
|
||||
localStorage.removeItem(SETTINGS_STORAGE_KEY);
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
|
||||
function loadAndReconcileSettings(defaultSettings) {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
const parsed = JSON.parse(raw);
|
||||
if (!isStoredSettingsRecord(parsed)) {
|
||||
return resetStoredSettings(
|
||||
defaultSettings,
|
||||
new Error("stored value is not a settings object"),
|
||||
);
|
||||
}
|
||||
return reconcileLoadedSettings(parsed);
|
||||
} catch (e) {
|
||||
return resetStoredSettings(defaultSettings, e);
|
||||
}
|
||||
}
|
||||
|
||||
function makeDefaults() {
|
||||
return {
|
||||
isAgentEnabled: false,
|
||||
selectedAgentId: BUILTIN_QUICK_ANSWER_ID,
|
||||
selectedTags: [],
|
||||
selectedMCPServices: [],
|
||||
selectedSkills: [],
|
||||
selectedFileKbMap: {},
|
||||
nested: { items: ["a"] },
|
||||
};
|
||||
}
|
||||
|
||||
function installMockLocalStorage() {
|
||||
const store = {};
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: {
|
||||
getItem: (key) => (key in store ? store[key] : null),
|
||||
setItem: (key, value) => {
|
||||
store[key] = value;
|
||||
},
|
||||
removeItem: (key) => {
|
||||
delete store[key];
|
||||
},
|
||||
},
|
||||
configurable: true,
|
||||
writable: true,
|
||||
});
|
||||
return store;
|
||||
}
|
||||
|
||||
test("isStoredSettingsRecord rejects non-object JSON values", () => {
|
||||
assert.equal(isStoredSettingsRecord(null), false);
|
||||
assert.equal(isStoredSettingsRecord([]), false);
|
||||
assert.equal(isStoredSettingsRecord("x"), false);
|
||||
assert.equal(isStoredSettingsRecord({}), true);
|
||||
});
|
||||
|
||||
test("cloneSettings deep-clones nested structures", () => {
|
||||
const defaults = makeDefaults();
|
||||
const cloned = cloneSettings(defaults);
|
||||
cloned.nested.items.push("b");
|
||||
assert.deepEqual(defaults.nested.items, ["a"]);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings returns deep-cloned defaults when key is missing", () => {
|
||||
const store = installMockLocalStorage();
|
||||
const defaults = makeDefaults();
|
||||
|
||||
const loaded = loadAndReconcileSettings(defaults);
|
||||
loaded.selectedTags.push("tag-1");
|
||||
|
||||
assert.deepEqual(defaults.selectedTags, []);
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings resets invalid JSON and removes corrupted key", () => {
|
||||
const store = installMockLocalStorage();
|
||||
store[SETTINGS_STORAGE_KEY] = "{broken";
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
assert.deepEqual(loaded.selectedTags, []);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings resets non-object JSON such as null", () => {
|
||||
const store = installMockLocalStorage();
|
||||
store[SETTINGS_STORAGE_KEY] = "null";
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(store[SETTINGS_STORAGE_KEY], undefined);
|
||||
assert.deepEqual(loaded.selectedTags, []);
|
||||
});
|
||||
|
||||
test("loadAndReconcileSettings keeps valid stored settings", () => {
|
||||
const store = installMockLocalStorage();
|
||||
const stored = {
|
||||
isAgentEnabled: true,
|
||||
selectedAgentId: BUILTIN_QUICK_ANSWER_ID,
|
||||
selectedTags: [{ id: "t1", name: "Tag", kbId: "kb1" }],
|
||||
};
|
||||
store[SETTINGS_STORAGE_KEY] = JSON.stringify(stored);
|
||||
|
||||
const loaded = loadAndReconcileSettings(makeDefaults());
|
||||
|
||||
assert.equal(loaded.isAgentEnabled, false);
|
||||
assert.equal(loaded.selectedTags.length, 1);
|
||||
assert.equal(loaded.selectedTags[0].id, "t1");
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import { safeRemoveItem, safeSetItem } from "@/composables/preferenceStorage";
|
||||
import { reconcileBuiltinAgentMode } from "@/utils/agent-mode";
|
||||
|
||||
export const SETTINGS_STORAGE_KEY = "WeKnora_settings";
|
||||
|
||||
/** Deep-clone settings so nested arrays/objects are not shared with defaults. */
|
||||
export function cloneSettings<T>(settings: T): T {
|
||||
return JSON.parse(JSON.stringify(settings));
|
||||
}
|
||||
|
||||
export function isStoredSettingsRecord(
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
type ReconcilableSettings = {
|
||||
selectedTags?: unknown;
|
||||
selectedMCPServices?: unknown;
|
||||
selectedSkills?: unknown;
|
||||
selectedTools?: unknown;
|
||||
selectedFileKbMap?: unknown;
|
||||
isAgentEnabled: boolean;
|
||||
selectedAgentId?: string;
|
||||
};
|
||||
|
||||
function reconcileLoadedSettings<T extends ReconcilableSettings>(loaded: T): T {
|
||||
loaded.selectedTags ||= [];
|
||||
loaded.selectedMCPServices ||= [];
|
||||
loaded.selectedSkills ||= (loaded.selectedTools as string[] | undefined) || [];
|
||||
loaded.selectedFileKbMap ||= {};
|
||||
if (reconcileBuiltinAgentMode(loaded)) {
|
||||
safeSetItem(SETTINGS_STORAGE_KEY, JSON.stringify(loaded));
|
||||
}
|
||||
return loaded;
|
||||
}
|
||||
|
||||
function resetStoredSettings<T extends ReconcilableSettings>(
|
||||
defaultSettings: T,
|
||||
reason: unknown,
|
||||
): T {
|
||||
console.error(
|
||||
"[settings] Failed to parse WeKnora_settings from localStorage, resetting to defaults:",
|
||||
reason,
|
||||
);
|
||||
safeRemoveItem(SETTINGS_STORAGE_KEY);
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
|
||||
/** Load settings from localStorage, reconcile builtin agent mode, fall back on corruption. */
|
||||
export function loadAndReconcileSettings<T extends ReconcilableSettings>(
|
||||
defaultSettings: T,
|
||||
): T {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return reconcileLoadedSettings(cloneSettings(defaultSettings));
|
||||
}
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
if (!isStoredSettingsRecord(parsed)) {
|
||||
return resetStoredSettings(
|
||||
defaultSettings,
|
||||
new Error("stored value is not a settings object"),
|
||||
);
|
||||
}
|
||||
return reconcileLoadedSettings(parsed as T);
|
||||
} catch (e) {
|
||||
return resetStoredSettings(defaultSettings, e);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user