An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Preserve settings clicks and merge configuration refreshes https://github.com/siyuan-note/siyuan/issues/20002
Daniel6b0f59869cea
diff --git a/app/src/config/setting/mount.test.ts b/app/src/config/setting/mount.test.tsindex 7d23da58f9..497766d1fb 100644--- a/app/src/config/setting/mount.test.ts+++ b/app/src/config/setting/mount.test.ts@@ -114,3 +114,46 @@ test("settings refresh preserves an unfocused profile draft and resumes after thawait Promise.resolve();assert.equal(mounted, 1);});++test("deferred refresh preserves a pressed label until its click completes or is canceled", async () => {+ const code = transpileModule(readFileSync("src/config/setting/mount.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const input = {};+ const label = {};+ let mounted = 0;+ const listeners = new Map<string, (event?: {target: object}) => void>();+ const timers: Array<() => void> = [];+ const root = {innerHTML: "settings", scrollTop: 12, scrollLeft: 0,+ contains: (element: unknown) => element === input || element === label,+ querySelector: (): Element | null => null};+ const document = {activeElement: input,+ addEventListener: (name: string, callback: (event?: {target: object}) => void) => listeners.set(name, callback)};+ const exports = {} as {remountOpenSettingTab: (tab: string) => Promise<void>; watchSettingTabInteractions: () => void};+ runInNewContext(code, {exports, document, setTimeout: (callback: () => void) => timers.push(callback),+ require: () => ({Constants: {DIALOG_SETTING: "settings"}, getSearchKeywordsLower: () => "",+ getSettingTab: () => ({mount: async () => { mounted++; }})}),+ window: {siyuan: {ws: {app: {}}, dialogs: [{element: {getAttribute: () => "settings", querySelector: () => root}}]}}});+ exports.watchSettingTabInteractions();+ await exports.remountOpenSettingTab("editor");+ listeners.get("pointerdown")({target: label});+ document.activeElement = {};+ listeners.get("focusout")();+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 0);+ listeners.get("pointerup")();+ assert.equal(mounted, 0);+ document.activeElement = input;+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 0);+ listeners.get("pointerdown")({target: label});+ document.activeElement = {};+ listeners.get("focusout")();+ timers.splice(0).forEach(callback => callback());+ listeners.get("pointercancel")();+ timers.splice(0).forEach(callback => callback());+ await Promise.resolve();+ assert.equal(mounted, 1);+});diff --git a/app/src/config/setting/mount.ts b/app/src/config/setting/mount.tsindex 7d86a84817..8404f8fe10 100644--- a/app/src/config/setting/mount.ts+++ b/app/src/config/setting/mount.ts@@ -6,6 +6,30 @@ import {getSettingTab, type TSettingTab} from "./tabs";const deferredTabs = new Set<TSettingTab>();let watchingFocus = false;+let watchingPointer = false;+let pressedTarget: EventTarget;++const refreshDeferredTabs = () => {+ if (!deferredTabs.size) return;+ setTimeout(() => {+ const tabs = [...deferredTabs];+ deferredTabs.clear();+ tabs.forEach(tab => { void remountOpenSettingTab(tab); });+ }, 0);+};++// 从按下到点击完成期间保留控件,避免失焦刷新移除本次点击的目标。+export const watchSettingTabInteractions = () => {+ if (watchingPointer) return;+ watchingPointer = true;+ document.addEventListener("pointerdown", event => { pressedTarget = event.target; }, true);+ const endPointer = () => {+ pressedTarget = undefined;+ refreshDeferredTabs();+ };+ document.addEventListener("pointerup", endPointer, true);+ document.addEventListener("pointercancel", endPointer, true);+};/** 首次挂载:渲染全部注册项并执行 afterMount */export const mountSettingTab = async (tabId: string, root: HTMLElement) => {@@ -27,16 +51,12 @@ export const remountOpenSettingTab = async (tabId: TSettingTab) => {if (!root?.innerHTML) {return;}- if (root.contains(document.activeElement) || root.querySelector(".config-entry-visibility__view")) {+ if (root.contains(document.activeElement) || pressedTarget && root.contains(pressedTarget as Node) ||+ root.querySelector(".config-entry-visibility__view")) {deferredTabs.add(tabId);if (!watchingFocus) {watchingFocus = true;// 离开输入控件或关闭入口方案编辑器后再刷新,保留尚未提交的输入与草稿。- const refreshDeferredTabs = () => setTimeout(() => {- const tabs = [...deferredTabs];- deferredTabs.clear();- tabs.forEach(tab => { void remountOpenSettingTab(tab); });- }, 0);document.addEventListener("focusout", refreshDeferredTabs);document.addEventListener("siyuan-entry-profile-closed", refreshDeferredTabs);}diff --git a/app/src/config/setting/save.ts b/app/src/config/setting/save.tsindex 3ad9c598a4..16c77c91e9 100644--- a/app/src/config/setting/save.ts+++ b/app/src/config/setting/save.ts@@ -1,4 +1,5 @@import {getSettingItem} from "./item";+import {watchSettingTabInteractions} from "./mount";const settingSaveBoundWraps = new WeakSet<HTMLElement>();@@ -7,6 +8,7 @@ export const bindSettingSaveDelegation = (tabWrap: HTMLElement) => {return;}settingSaveBoundWraps.add(tabWrap);+ watchSettingTabInteractions();tabWrap.addEventListener("input", onSettingTabWrapInput);tabWrap.addEventListener("change", onSettingTabWrapChange);};diff --git a/app/src/config/setting/sync.test.ts b/app/src/config/setting/sync.test.tsindex 83b72ade27..8b174ec2ee 100644--- a/app/src/config/setting/sync.test.ts+++ b/app/src/config/setting/sync.test.ts@@ -4,6 +4,94 @@ import {test} from "node:test";import {runInNewContext} from "node:vm";import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";import {getAgentDefaultModelID, getUsableAgentModels} from "../../layout/dock/agent/agentModel";+import {createNamespacePatchQueue} from "../util/namespacePatchQueue";+import {mergeRecordByDottedPath} from "../util/dotPath";++for (const mobile of [false, true]) {+ test(`namespace patch and its push read confirmed configuration once (mobile=${mobile})`, async () => {+ const {parse} = require("ifdef-loader/preprocessor");+ const compile = (file: string) => transpileModule(parse(readFileSync(file, "utf8"),+ {MOBILE: mobile, BROWSER: mobile}, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ const requests: string[] = [];+ const config = {editor: {fontSize: 16}};+ let fontSize = 16;+ const refresh = {} as {refreshSettingConfig: (namespace: string) => Promise<void>};+ const fetchSyncPost = async (url: string, data: {editor: {fontSize: number}}) => {+ requests.push(url);+ if (url.endsWith("patch")) {+ fontSize = data.editor.fontSize;+ void refresh.refreshSettingConfig("editor");+ await Promise.resolve();+ return {code: 0};+ }+ return {code: 0, data: {conf: {editor: {fontSize}}}};+ };+ runInNewContext(compile("src/config/setting/sync.ts"), {exports: refresh, window: {siyuan: {config}}, console,+ require: () => ({fetchSyncPost, systemConfig: (value: unknown) => value,+ objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),+ editorConfigApi: {apply: (value: typeof config.editor) => { config.editor = value; }},+ syncSettingTasks() {}, getSettingTabDefs: () => [{id: "editor"}], remountOpenSettingTab: async () => {},+ })});+ const api = {} as {createConfigNamespaceApi: (options: {+ namespace: string; getConfig: () => typeof config.editor;+ }) => {patch: (path: string, value: number, applied: (value: typeof config.editor) => void) => Promise<void>}};+ runInNewContext(compile("src/config/util/namespaceApi.ts"), {exports: api, require: () => ({+ ...refresh, fetchSyncPost, createNamespacePatchQueue, mergeRecordByDottedPath,+ })});+ let confirmed: typeof config.editor;+ await api.createConfigNamespaceApi({namespace: "editor", getConfig: () => config.editor})+ .patch("fontSize", 18, value => { confirmed = value; });+ assert.deepEqual(requests, ["/api/setting/patch", "/api/system/getConf"]);+ assert.equal(confirmed.fontSize, 18);+ fontSize = 20;+ await refresh.refreshSettingConfig("editor");+ assert.equal(config.editor.fontSize, 20);+ assert.equal(requests.length, 3);+ });++ for (const result of ["success", "failure", "throw"]) {+ test(`settings saves merge their notification with response refresh and release failures (mobile=${mobile}, ${result})`, async () => {+ const {parse} = require("ifdef-loader/preprocessor");+ const compiled = transpileModule(parse(readFileSync("src/config/setting/sync.ts", "utf8"),+ {MOBILE: mobile, BROWSER: mobile}, false, true), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText;+ let requests = 0;+ let finishSave: () => void;+ const config = {editor: {fontSize: 16}};+ const exports = {} as {+ refreshSettingConfig: (namespace: string) => Promise<void>;+ refreshSettingConfigAfter: (namespace: string, save: () => Promise<boolean>) => Promise<boolean>;+ };+ runInNewContext(compiled, {exports, window: {siyuan: {config}}, console, require: () => ({+ fetchSyncPost: async () => { requests++; return {code: 0, data: {conf: {editor: {fontSize: 18}}}}; },+ systemConfig: (value: unknown) => value,+ objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),+ editorConfigApi: {apply: (value: typeof config.editor) => { config.editor = value; }},+ syncSettingTasks() {}, getSettingTabDefs: () => [{id: "editor"}], remountOpenSettingTab: async () => {},+ })});+ const saving = exports.refreshSettingConfigAfter("editor", async () => {+ await new Promise<void>(resolve => { finishSave = resolve; });+ if (result === "throw") throw new Error("save failed");+ return result === "success";+ });+ const rejected = result === "throw" ? assert.rejects(saving, /save failed/) : undefined;+ const notified = exports.refreshSettingConfig("editor");+ await Promise.resolve();+ assert.equal(requests, 0);+ finishSave();+ if (rejected) await rejected;+ else assert.equal(await saving, result === "success");+ await notified;+ assert.equal(requests, 1);+ assert.equal(config.editor.fontSize, 18);+ await exports.refreshSettingConfig("editor");+ assert.equal(requests, 2, "later notifications still refresh configuration");+ });+ }+}test("settings notifications update runtime configuration and refresh the registered tab", async () => {const compiled = transpileModule(readFileSync("src/config/setting/sync.ts", "utf8"), {diff --git a/app/src/config/setting/sync.ts b/app/src/config/setting/sync.tsindex 02f5ad3ee4..101d40920d 100644--- a/app/src/config/setting/sync.ts+++ b/app/src/config/setting/sync.ts@@ -16,6 +16,24 @@ import {getSettingTabDefs, type TSettingTab} from "./tabs";let pending = new Set<string>();let refreshing: Promise<void>;+let saving = 0;+let saved: Promise<void>;+let finishSaving: () => void;++// 等待配置写入完成,将保存回调与同次写入的广播合并为一次配置读取。+export const refreshSettingConfigAfter = async (namespace: string, save: () => Promise<boolean>) => {+ if (saving++ === 0) {+ saved = new Promise(resolve => { finishSaving = resolve; });+ }+ let changed: boolean;+ try {+ changed = await save();+ } finally {+ if (--saving === 0) finishSaving();+ }+ if (changed) await refreshSettingConfig(namespace);+ return changed;+};// 合并通知并串行读取,重连也使用同一流程,避免旧响应覆盖更新后的配置。export const refreshSettingConfig = (namespace = "*"): Promise<void> => {@@ -25,6 +43,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {}refreshing = (async () => {while (pending.size) {+ while (saving) await saved;const namespaces = pending;pending = new Set();const response = await fetchSyncPost("/api/system/getConf", {});diff --git a/app/src/config/util/namespaceApi.ts b/app/src/config/util/namespaceApi.tsindex 4623f13239..6a306294e1 100644--- a/app/src/config/util/namespaceApi.ts+++ b/app/src/config/util/namespaceApi.ts@@ -1,7 +1,7 @@import {fetchPost, fetchSyncPost} from "../../util/fetch";import {createNamespacePatchQueue} from "./namespacePatchQueue";import {mergeRecordByDottedPath} from "./dotPath";-import {refreshSettingConfig} from "../setting/sync";+import {refreshSettingConfigAfter} from "../setting/sync";export function createConfigNamespaceApi<TData>(options: {namespace: string;@@ -36,14 +36,13 @@ export function createConfigNamespaceApi<TData>(options: {});});const patch = createNamespacePatchQueue({namespace, getConfig, submit, submitPatch: async (path, value) => {- const response = await fetchSyncPost("/api/setting/patch", {- [namespace]: mergeRecordByDottedPath({}, path, value),+ const changed = await refreshSettingConfigAfter(namespace, async () => {+ const response = await fetchSyncPost("/api/setting/patch", {+ [namespace]: mergeRecordByDottedPath({}, path, value),+ });+ return response.code === 0;});- if (response.code !== 0) {- return undefined;- }- await refreshSettingConfig(namespace);- return getConfig();+ return changed ? getConfig() : undefined;}});return {diff --git a/app/tests/settingsWindow.test.js b/app/tests/settingsWindow.test.jsindex e6c45f099c..e335208921 100644--- a/app/tests/settingsWindow.test.js+++ b/app/tests/settingsWindow.test.js@@ -135,6 +135,53 @@ const runCases = async (sources) => {legacy.dialog.destroy();await wait();+ const toggles = {first: false, second: false};+ const saves = [];+ const {genSwitchRow} = loadRendererModule(sources.fragments, {});+ const markup = () => genSwitchRow("first", "First setting", "Description", toggles.first) ++ genSwitchRow("second", "Second setting", "Description", toggles.second);+ const clickDialog = new Dialog({content: '<div class="config__tab-wrap"><div class="config__tab-container" data-name="editor">' ++ markup() + "</div></div>"});+ clickDialog.element.setAttribute("data-key", "settings");+ let remounted = 0;+ const mounting = loadRendererModule(sources.mount, {+ "../render/render": {}, "../search/normalize": {getSearchKeywordsLower: () => ""},+ "../../constants": {Constants: {DIALOG_SETTING: "settings"}},+ "./tabs": {getSettingTab: () => ({mount: async root => { remounted++; root.innerHTML = markup(); }})},+ });+ const saving = loadRendererModule(sources.save, {+ "./mount": mounting,+ "./item": {getSettingItem: id => ({readValue: input => input.checked, save: value => {+ toggles[id] = value;+ saves.push(id);+ void mounting.remountOpenSettingTab("editor");+ }})},+ });+ window.siyuan.config.readonly = false;+ saving.bindSettingSaveDelegation(clickDialog.element.querySelector(".config__tab-wrap"));+ const clickLabel = async id => {+ const rect = clickDialog.element.querySelector("#" + id).closest("label").getBoundingClientRect();+ await ipcRenderer.invoke("test-settings-pointer", "mouseDown", Math.round(rect.left + 10), Math.round(rect.top + rect.height / 2));+ // 离屏窗口不派发失焦事件,补发与按下标签时相同的事件,保留原生鼠标点击流程。+ document.dispatchEvent(new FocusEvent("focusout"));+ await wait();+ await ipcRenderer.invoke("test-settings-pointer", "mouseUp", Math.round(rect.left + 10), Math.round(rect.top + rect.height / 2));+ await wait();+ };+ await clickLabel("first");+ assert.deepEqual(saves, ["first"]);+ const secondInput = clickDialog.element.querySelector("#second");+ await clickLabel("second");+ assert.deepEqual(saves, ["first", "second"], "each settings label responds to its first physical click");+ assert.equal(clickDialog.element.querySelector("#second"), secondInput, "deferred refresh preserves the pressed label");+ assert.equal(secondInput.checked, true);+ document.activeElement.blur();+ document.dispatchEvent(new FocusEvent("focusout"));+ await wait();+ assert.equal(remounted, 1, "refresh resumes after leaving the input");+ clickDialog.destroy();+ await wait();+let confirmed = 0;let destroyed = 0;let created = 0;@@ -315,7 +362,8 @@ if (process.versions.electron && process.type === "browser") {"\n.config__panel {border-radius: var(--b3-border-radius-b);}\n"]));for (const [key, file] of Object.entries({dialog: "dialog/index.ts", setting: "plugin/Setting.ts",native: "config/setting/nativeWindow.ts", fit: "config/setting/windowDialog.ts", controls: "boot/windowControls.ts",- paint: "config/setting/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts"})) {+ paint: "config/setting/windowPaint.ts", frontend: "util/functions.ts", titles: "util/processTitle.ts",+ mount: "config/setting/mount.ts", save: "config/setting/save.ts", fragments: "config/render/fragments.ts"})) {let source = fs.readFileSync(path.join(__dirname, "../src", file), "utf8");if (key === "frontend") {source = require("ifdef-loader/preprocessor").parse(source, {MOBILE: false, BROWSER: false}, false, true);@@ -400,6 +448,9 @@ if (process.versions.electron && process.type === "browser") {commands.push(command);});ipcMain.handle("test-settings-commands", () => commands);+ ipcMain.handle("test-settings-pointer", (event, type, x, y) => {+ event.sender.sendInputEvent({type, x, y, button: "left", clickCount: 1});+ });ipcMain.handle("test-settings-token", () => new URL([...children][0].webContents.getURL()).searchParams.get("settingsWindowToken"));ipcMain.handle("test-settings-size", (_event, width, height) => {for (const child of children) child.setSize(width, height);