Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Complete cross-window settings notifications https://github.com/siyuan-note/siyuan/issues/20002

Daniel1fa2acea2c1e
diff --git a/app/src/config/setting/sync.test.ts b/app/src/config/setting/sync.test.ts
index 721cb71ff9..eb4cff66f9 100644
--- a/app/src/config/setting/sync.test.ts
+++ b/app/src/config/setting/sync.test.ts
@@ -2,7 +2,7 @@ import * as assert from "node:assert/strict";
import {readFileSync} from "node:fs";
import {test} from "node:test";
import {runInNewContext} from "node:vm";
-import {createSourceFile, isClassDeclaration, isMethodDeclaration, ModuleKind, ScriptTarget, transpileModule} from "typescript";
+import {createSourceFile, isClassDeclaration, isMethodDeclaration, isVariableStatement, ModuleKind, ScriptTarget, transpileModule} from "typescript";
import {getAgentDefaultModelID, getUsableAgentModels} from "../../layout/dock/agent/agentModel";
test("settings notifications update runtime configuration and refresh the registered tab", async () => {
@@ -93,3 +93,92 @@ for (const mobile of [false, true]) {
assert.deepEqual(models, []);
});
}
+
+for (const mobile of [false, true]) {
+ test(`system notifications synchronize access fields and preserve masked values (mobile=${mobile})`, 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;
+ const config = {system: {autoLaunch2: 0}, api: {token: "old-token"}, oidc: {enabled: false, clientSecret: "old"},
+ accessAuthCode: "old-mask", editor: {}, appearance: {}, keymap: {}, ai: {}, sync: {enabled: true}};
+ let next = {...config, system: {autoLaunch2: 1}, api: {token: "new-token"},
+ oidc: {enabled: true, clientSecret: "******"}, accessAuthCode: "******"};
+ let failed = false;
+ const remounted: string[] = [];
+ const exports = {} as {refreshSettingConfig: (namespace?: string) => Promise<void>};
+ runInNewContext(compiled, {exports, window: {siyuan: {config}}, console, require: () => ({
+ fetchSyncPost: async () => failed ? {code: -1} : {code: 0, data: {conf: JSON.parse(JSON.stringify(next))}},
+ systemConfig: (value: unknown) => value,
+ objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),
+ syncSettingTasks() {}, processSync() {}, getSettingTabDefs: () => [{id: "app"}, {id: "access"}],
+ remountOpenSettingTab: async (tab: string) => { remounted.push(tab); },
+ })});
+ await exports.refreshSettingConfig("system");
+ assert.equal(config.system.autoLaunch2, 1);
+ assert.equal(config.api.token, "new-token");
+ assert.equal(config.oidc.clientSecret, "******");
+ assert.equal(config.oidc.enabled, true);
+ assert.equal(config.accessAuthCode, "******");
+ assert.deepEqual(remounted, mobile ? [] : ["app", "access"]);
+ remounted.length = 0;
+ await exports.refreshSettingConfig("system");
+ assert.deepEqual(remounted, mobile ? [] : ["app"]);
+ remounted.length = 0;
+ next = {...next, api: {token: "latest-token"}};
+ await exports.refreshSettingConfig();
+ assert.equal(config.api.token, "latest-token");
+ assert.equal(remounted.filter(tab => tab === "access").length, mobile ? 0 : 1);
+ failed = true;
+ next = {...next, api: {token: "unconfirmed-token"}};
+ await exports.refreshSettingConfig("system");
+ assert.equal(config.api.token, "latest-token");
+ });
+
+ test(`sync notifications refresh icons without resetting an active synchronization (mobile=${mobile})`, async () => {
+ const {parse} = require("ifdef-loader/preprocessor");
+ const compile = (source: string) => transpileModule(parse(source, {MOBILE: mobile, BROWSER: mobile}, false, true), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText;
+ const config = {sync: {enabled: true, provider: 0}};
+ let next = {enabled: false, provider: 0};
+ const classes = new Set<string>();
+ const classList = {contains: (value: string) => classes.has(value), add: (value: string) => classes.add(value),
+ remove: (value: string) => classes.delete(value)};
+ let icon = "#iconCloudSucc";
+ const useElement = {setAttribute: (_name: string, value: string) => { icon = value; }, parentElement: {classList}};
+ const element = {classList, querySelector: () => useElement, firstElementChild: {classList}};
+ const document = {querySelector: () => mobile ? useElement : element};
+ const window = {siyuan: {config}};
+ const systemSource = createSourceFile("processSystem.ts", parse(readFileSync("src/dialog/processSystem.ts", "utf8"),
+ {MOBILE: mobile, BROWSER: mobile}, false, true), ScriptTarget.ES2021, true);
+ const processSync = systemSource.statements.find(statement => isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => item.name.getText(systemSource) === "processSync"));
+ const runtime = {} as {processSync: () => void};
+ runInNewContext(compile(processSync.getText(systemSource)), {exports: runtime, window, document, needSubscribe: () => false});
+ let refreshes = 0;
+ const exports = {} as {refreshSettingConfig: (namespace: string) => Promise<void>};
+ runInNewContext(compile(readFileSync("src/config/setting/sync.ts", "utf8")), {
+ exports, window, console, require: () => ({
+ fetchSyncPost: async () => ({code: 0, data: {conf: {sync: {...next}}}}), systemConfig: (value: unknown) => value,
+ objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),
+ syncSettingTasks() {}, processSync: () => { refreshes++; runtime.processSync(); },
+ getSettingTabDefs: () => [{id: "sync"}], remountOpenSettingTab: async () => {},
+ }),
+ });
+ await exports.refreshSettingConfig("sync");
+ assert.equal(config.sync.enabled, false);
+ assert.equal(icon, "#iconCloudOff");
+ await exports.refreshSettingConfig("sync");
+ assert.equal(refreshes, 1);
+ icon = "#iconRefresh";
+ classes.add(mobile ? "fn__rotate" : "toolbar__item--active");
+ next = {enabled: true, provider: 0};
+ await exports.refreshSettingConfig("sync");
+ assert.equal(refreshes, 2);
+ assert.equal(config.sync.enabled, true);
+ assert.equal(icon, "#iconRefresh");
+ assert.ok(classes.has(mobile ? "fn__rotate" : "toolbar__item--active"));
+ });
+}
diff --git a/app/src/config/setting/sync.ts b/app/src/config/setting/sync.ts
index 44976efd5d..1276c10554 100644
--- a/app/src/config/setting/sync.ts
+++ b/app/src/config/setting/sync.ts
@@ -5,6 +5,7 @@ import {appearanceConfigApi} from "../tabs/appearanceRuntime";
import {aiConfigApi} from "../tabs/ai/aiRuntime";
import {objEquals} from "../../util/functions";
import {syncSettingTasks} from "./taskBlocker";
+import {processSync} from "../../dialog/processSystem";
/// #if !MOBILE
import {applyKeymap} from "../tabs/keymapRuntime";
import {remountOpenSettingTab} from "./mount";
@@ -40,6 +41,18 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
if (includes("ai") && !objEquals(window.siyuan.config.ai, next.ai)) {
aiConfigApi.apply(next.ai);
}
+ if (includes("sync") && !objEquals(window.siyuan.config.sync, next.sync)) {
+ window.siyuan.config.sync = next.sync;
+ processSync();
+ }
+ let accessChanged = false;
+ if (includes("system")) {
+ // 系统设置通知同时同步访问授权的顶层配置,值以内核返回的脱敏配置为准。
+ for (const key of ["api", "oidc", "accessAuthCode"] as const) {
+ accessChanged ||= !objEquals(window.siyuan.config[key], next[key]);
+ Object.assign(window.siyuan.config, {[key]: next[key]});
+ }
+ }
/// #if !MOBILE
if (includes("keymap") && !objEquals(window.siyuan.config.keymap, next.keymap)) {
applyKeymap(next.keymap);
@@ -49,7 +62,7 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
window.siyuan.config.keymap = next.keymap;
}
/// #endif
- const simple = ["export", "fileTree", "search", "flashcard", "secrets", "variables", "sync", "repo", "system", "bazaar", "publish"] as const;
+ const simple = ["export", "fileTree", "search", "flashcard", "secrets", "variables", "repo", "system", "bazaar", "publish"] as const;
for (const key of simple) {
if (includes(key)) {
Object.assign(window.siyuan.config, {[key]: next[key]});
@@ -57,10 +70,13 @@ export const refreshSettingConfig = (namespace = "*"): Promise<void> => {
}
/// #if !MOBILE
const tabs: Record<string, TSettingTab> = {fileTree: "file", secrets: "secretsVariables", variables: "secretsVariables", system: "app", publish: "access"};
- for (const namespace of namespaces.has("*") ? [...simple, "editor", "keymap", "appearance", "ai"] : namespaces) {
+ const remountTabs = new Set<TSettingTab>();
+ for (const namespace of namespaces.has("*") ? [...simple, "editor", "keymap", "appearance", "ai", "sync"] : namespaces) {
const tab = getSettingTabDefs().find(definition => definition.id === (tabs[namespace] || namespace));
- if (tab) void remountOpenSettingTab(tab.id);
+ if (tab) remountTabs.add(tab.id);
}
+ if (accessChanged) remountTabs.add("access");
+ remountTabs.forEach(tab => { void remountOpenSettingTab(tab); });
/// #endif
}
})().catch(error => console.error("Could not refresh settings", error)).finally(() => {
diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.ts
index eba096bd4a..ef14013d89 100644
--- a/app/src/config/setting/window.ts
+++ b/app/src/config/setting/window.ts
@@ -1,6 +1,7 @@
import "../../assets/scss/base.scss";
import {ipcRenderer, webFrame} from "electron";
import {Constants} from "../../constants";
+import {onAgentStreamingMarkdownStorageChanged} from "../tabs/ai/agentStreamingMarkdown";
import {Model} from "../../layout/Model";
import {Menus} from "../../menus";
import {genUUID} from "../../util/genID";
@@ -91,10 +92,22 @@ const initialize = async () => {
case "syncing": processSync(data); break;
case "setCloudUser": applyCloudUserState(data.data.user, data.data.userName); break;
case "setServerAddrs": updateServerAddresses(data.data); break;
- case "setLocalStorageVal": window.siyuan.storage[data.data.key] = data.data.val; break;
- case "setLocalStorageVals": Object.assign(window.siyuan.storage, data.data.keyVals); break;
- case "removeLocalStorageVal": delete window.siyuan.storage[data.data.key]; break;
- case "removeLocalStorageVals": data.data.keys.forEach((key: string) => delete window.siyuan.storage[key]); break;
+ case "setLocalStorageVal":
+ window.siyuan.storage[data.data.key] = data.data.val;
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
+ break;
+ case "setLocalStorageVals":
+ Object.assign(window.siyuan.storage, data.data.keyVals);
+ Object.keys(data.data.keyVals).forEach(onAgentStreamingMarkdownStorageChanged);
+ break;
+ case "removeLocalStorageVal":
+ delete window.siyuan.storage[data.data.key];
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
+ break;
+ case "removeLocalStorageVals":
+ data.data.keys.forEach((key: string) => delete window.siyuan.storage[key]);
+ data.data.keys.forEach(onAgentStreamingMarkdownStorageChanged);
+ break;
}
}});
const response = await fetchSyncPost("/api/system/getConf", {});
diff --git a/app/src/config/tabs/accountUi.ts b/app/src/config/tabs/accountUi.ts
index 0ec958097d..19215ad40c 100644
--- a/app/src/config/tabs/accountUi.ts
+++ b/app/src/config/tabs/accountUi.ts
@@ -456,7 +456,6 @@ const bindAccountAuthForm = (
showMessage(userResponse.msg);
return;
}
- window.dispatchEvent(new CustomEvent("siyuan-login-success"));
});
} else if (mode === "deactivate") {
confirmDeactivateAccount();
@@ -567,7 +566,7 @@ const renderAccount = (accountSettingsRoot: Element) => {
};
export const applyCloudUserState = (user: TCloudUser | null, userName = "", accountSettingsRoot?: Element) => {
- setCloudUser(user, userName);
+ const loggedIn = setCloudUser(user, userName);
const root = accountSettingsRoot || syncTabElement;
if (root) {
renderAccount(root);
@@ -575,6 +574,9 @@ export const applyCloudUserState = (user: TCloudUser | null, userName = "", acco
}
onSetaccount();
processSync();
+ if (loggedIn) {
+ window.dispatchEvent(new CustomEvent("siyuan-login-success"));
+ }
};
const genVIPIconHTML = (className = "") =>
diff --git a/app/src/config/tabs/ai/agentStreamingMarkdown.ts b/app/src/config/tabs/ai/agentStreamingMarkdown.ts
index 2503b3a97f..dbcbe1d5b5 100644
--- a/app/src/config/tabs/ai/agentStreamingMarkdown.ts
+++ b/app/src/config/tabs/ai/agentStreamingMarkdown.ts
@@ -7,8 +7,14 @@ export const isAgentStreamingMarkdownEnabled = (): boolean => {
return window.siyuan.storage[AGENT_STREAMING_MARKDOWN_KEY] === true;
};
+export const onAgentStreamingMarkdownStorageChanged = (key: string): void => {
+ if (key === AGENT_STREAMING_MARKDOWN_KEY) {
+ window.dispatchEvent(new CustomEvent(AGENT_STREAMING_MARKDOWN_CHANGED_EVENT));
+ }
+};
+
export const setAgentStreamingMarkdownEnabled = (enabled: boolean): void => {
window.siyuan.storage[AGENT_STREAMING_MARKDOWN_KEY] = enabled;
setStorageVal(AGENT_STREAMING_MARKDOWN_KEY, enabled);
- window.dispatchEvent(new CustomEvent(AGENT_STREAMING_MARKDOWN_CHANGED_EVENT));
+ onAgentStreamingMarkdownStorageChanged(AGENT_STREAMING_MARKDOWN_KEY);
};
diff --git a/app/src/config/tabs/cloudUser.ts b/app/src/config/tabs/cloudUser.ts
index 02836b9338..58c7ed8cb2 100644
--- a/app/src/config/tabs/cloudUser.ts
+++ b/app/src/config/tabs/cloudUser.ts
@@ -11,8 +11,11 @@ let cloudLoginUserName = "";
export const getCloudLoginUserName = () => cloudLoginUserName;
export const setCloudUser = (user: TCloudUser | null, userName = "") => {
+ // 重复的响应和推送保持登录状态,新增登录或切换账号时报告状态变化。
+ const loggedIn = Boolean(user && (!window.siyuan.user || window.siyuan.user.userId !== user.userId));
window.siyuan.user = user;
cloudLoginUserName = user ? "" : userName;
+ return loggedIn;
};
export const resolveCloudUserRefresh = (
diff --git a/app/src/index.ts b/app/src/index.ts
index 27d6ae8e3c..3f448bc2f5 100644
--- a/app/src/index.ts
+++ b/app/src/index.ts
@@ -1,5 +1,6 @@
import {Constants} from "./constants";
import {refreshSettingConfig} from "./config/setting/sync";
+import {onAgentStreamingMarkdownStorageChanged} from "./config/tabs/ai/agentStreamingMarkdown";
import {closeNotebookHistoryDialogs} from "./history/notebookDialogs";
import {systemConfig} from "./config/systemConfig";
import {openStandaloneDatabaseItemByURI} from "./protyle/render/av/openStandaloneDatabaseItem";
@@ -172,19 +173,23 @@ export class App {
case "setLocalStorageVal":
if (window.siyuan.storage) {
window.siyuan.storage[data.data.key] = data.data.val;
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
}
break;
case "setLocalStorageVals":
Object.keys(data.data.keyVals).forEach((k) => {
window.siyuan.storage[k] = data.data.keyVals[k];
+ onAgentStreamingMarkdownStorageChanged(k);
});
break;
case "removeLocalStorageVal":
delete window.siyuan.storage[data.data.key];
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
break;
case "removeLocalStorageVals":
data.data.keys.forEach((k: string) => {
delete window.siyuan.storage[k];
+ onAgentStreamingMarkdownStorageChanged(k);
});
break;
case "rename":
diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.ts
index edf4db405b..1c692cced5 100644
--- a/app/src/mobile/util/onMessage.ts
+++ b/app/src/mobile/util/onMessage.ts
@@ -1,5 +1,6 @@
import {openMobileFileById} from "../editor";
import {refreshSettingConfig} from "../../config/setting/sync";
+import {onAgentStreamingMarkdownStorageChanged} from "../../config/tabs/ai/agentStreamingMarkdown";
import {closeNotebookHistoryDialogs} from "../../history/notebookDialogs";
import {MOBILE_BARS_CONFIG_KEY} from "./mobileBarsConfig";
import {showMobileBars} from "./mobileBars";
@@ -146,6 +147,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
break;
case "setLocalStorageVal":
window.siyuan.storage[data.data.key] = data.data.val;
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
if (data.data.key === MOBILE_BARS_CONFIG_KEY) {
showMobileBars();
}
@@ -160,6 +162,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
Object.keys(data.data.keyVals).forEach((k) => {
window.siyuan.storage[k] = data.data.keyVals[k];
});
+ Object.keys(data.data.keyVals).forEach(onAgentStreamingMarkdownStorageChanged);
if (Object.prototype.hasOwnProperty.call(data.data.keyVals, MOBILE_BARS_CONFIG_KEY)) {
showMobileBars();
}
@@ -172,6 +175,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
break;
case "removeLocalStorageVal":
delete window.siyuan.storage[data.data.key];
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
if (data.data.key === MOBILE_BARS_CONFIG_KEY) {
showMobileBars();
}
@@ -186,6 +190,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {
data.data.keys.forEach((k: string) => {
delete window.siyuan.storage[k];
});
+ data.data.keys.forEach(onAgentStreamingMarkdownStorageChanged);
if (data.data.keys.includes(MOBILE_BARS_CONFIG_KEY)) {
showMobileBars();
}
diff --git a/app/src/window/index.ts b/app/src/window/index.ts
index 4e76608be9..2a54b2dfd4 100644
--- a/app/src/window/index.ts
+++ b/app/src/window/index.ts
@@ -2,6 +2,7 @@ import {onWindowWorkspaceStorageChanged} from "./workspace";
import {closeNotebookHistoryDialogs} from "../history/notebookDialogs";
import {Constants} from "../constants";
import {refreshSettingConfig} from "../config/setting/sync";
+import {onAgentStreamingMarkdownStorageChanged} from "../config/tabs/ai/agentStreamingMarkdown";
import {systemConfig} from "../config/systemConfig";
import {Menus} from "../menus";
import {Model} from "../layout/Model";
@@ -125,22 +126,26 @@ class App {
case "setLocalStorageVal":
if (window.siyuan.storage) {
window.siyuan.storage[data.data.key] = data.data.val;
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
onWindowWorkspaceStorageChanged(data.data.key);
}
break;
case "setLocalStorageVals":
Object.keys(data.data.keyVals).forEach((k) => {
window.siyuan.storage[k] = data.data.keyVals[k];
+ onAgentStreamingMarkdownStorageChanged(k);
onWindowWorkspaceStorageChanged(k);
});
break;
case "removeLocalStorageVal":
delete window.siyuan.storage[data.data.key];
+ onAgentStreamingMarkdownStorageChanged(data.data.key);
onWindowWorkspaceStorageChanged(data.data.key);
break;
case "removeLocalStorageVals":
data.data.keys.forEach((k: string) => {
delete window.siyuan.storage[k];
+ onAgentStreamingMarkdownStorageChanged(k);
onWindowWorkspaceStorageChanged(k);
});
break;
diff --git a/app/tests/settingsNotifications.test.js b/app/tests/settingsNotifications.test.js
new file mode 100644
index 0000000000..9d1197a4d2
--- /dev/null
+++ b/app/tests/settingsNotifications.test.js
@@ -0,0 +1,118 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const ts = require("typescript");
+
+const sourceFile = file => ts.createSourceFile(file, readFileSync(file, "utf8"), ts.ScriptTarget.ES2021, true);
+const compile = source => ts.transpileModule(source, {
+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2021},
+}).outputText;
+const storageCommands = ["setLocalStorageVal", "setLocalStorageVals", "removeLocalStorageVal", "removeLocalStorageVals"];
+
+for (const file of ["src/index.ts", "src/window/index.ts", "src/mobile/util/onMessage.ts", "src/config/setting/window.ts"]) {
+ test(`storage pushes notify the active streaming renderer without losing platform hooks (${file})`, () => {
+ const source = sourceFile(file);
+ const clauses = [];
+ const visit = node => {
+ if (ts.isCaseClause(node) && ts.isStringLiteral(node.expression) && storageCommands.includes(node.expression.text)) {
+ clauses.push(node.getText(source));
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source);
+ assert.equal(clauses.length, storageCommands.length);
+ const preference = {};
+ const events = [];
+ const storage = {};
+ const window = {siyuan: {storage}, dispatchEvent: event => {
+ events.push(event.type);
+ agent.checkStreamingMarkdownChanged();
+ }};
+ runInNewContext(compile(readFileSync("src/config/tabs/ai/agentStreamingMarkdown.ts", "utf8")), {
+ exports: preference, window, require: () => ({setStorageVal() {}}),
+ CustomEvent: class {constructor(type) {this.type = type;}},
+ });
+ const agentSource = sourceFile("src/layout/dock/agent/AgentChat.ts");
+ const agentClass = agentSource.statements.find(node => ts.isClassDeclaration(node) && node.name.text === "AgentChat");
+ const check = agentClass.members.find(member => member.name?.getText(agentSource) === "checkStreamingMarkdownChanged");
+ const agentExports = {};
+ runInNewContext(compile(`export class Observer {${check.getText(agentSource)}}`), {
+ exports: agentExports, isAgentStreamingMarkdownEnabled: preference.isAgentStreamingMarkdownEnabled,
+ });
+ const body = {textContent: "cached", classList: {remove() {}}};
+ let renders = 0;
+ const agent = Object.assign(new agentExports.Observer(), {
+ streamingMarkdownEnabled: false, currentContent: "cached", currentAIElement: {querySelector: () => body},
+ cancelTokenUpdate() {}, updateStreamingMarkdown: () => {renders++; body.textContent = "rendered";},
+ });
+ const platformCalls = [];
+ const receiver = {};
+ runInNewContext(compile(`export const receive = data => {switch(data.cmd){${clauses.join("\n")}}};`), {
+ exports: receiver, window, ...preference,
+ onWindowWorkspaceStorageChanged: key => platformCalls.push(key),
+ MOBILE_BARS_CONFIG_KEY: "mobile-bars", Constants: {LOCAL_MOBILE_BOTTOM_BAR: "mobile-bottom", LOCAL_MOBILE_SIDE_PANEL: "mobile-side"},
+ showMobileBars: () => platformCalls.push("bars"), renderMobileBottomBar: () => platformCalls.push("bottom"),
+ dispatchMobileSidePanelConfigChange: () => platformCalls.push("side"),
+ });
+ const key = preference.AGENT_STREAMING_MARKDOWN_KEY;
+ receiver.receive({cmd: "setLocalStorageVal", data: {key, val: true}});
+ assert.equal(agent.streamingMarkdownEnabled, true);
+ assert.equal(body.textContent, "rendered");
+ assert.equal(renders, 1);
+ receiver.receive({cmd: "setLocalStorageVal", data: {key: "unrelated", val: 1}});
+ assert.equal(events.length, 1);
+ receiver.receive({cmd: "setLocalStorageVal", data: {key, val: true}});
+ assert.equal(renders, 1);
+ receiver.receive({cmd: "setLocalStorageVals", data: {keyVals: {[key]: false, "mobile-bottom": true}}});
+ assert.equal(agent.streamingMarkdownEnabled, false);
+ assert.equal(body.textContent, "cached");
+ receiver.receive({cmd: "setLocalStorageVal", data: {key, val: true}});
+ receiver.receive({cmd: "removeLocalStorageVal", data: {key}});
+ assert.equal(agent.streamingMarkdownEnabled, false);
+ assert.ok(!Object.hasOwn(storage, key));
+ receiver.receive({cmd: "setLocalStorageVal", data: {key, val: true}});
+ receiver.receive({cmd: "removeLocalStorageVals", data: {keys: [key, "mobile-side"]}});
+ assert.equal(agent.streamingMarkdownEnabled, false);
+ assert.equal(body.textContent, "cached");
+ assert.ok(events.every(type => type === preference.AGENT_STREAMING_MARKDOWN_CHANGED_EVENT));
+ assert.equal(events.length, 7);
+ if (file.includes("mobile/")) assert.deepEqual(platformCalls, ["bottom", "side"]);
+ if (file.includes("window/index")) assert.ok(platformCalls.includes(key));
+ });
+}
+
+test("cloud account pushes and responses deliver one login notification after UI state is applied", () => {
+ const events = [];
+ const order = [];
+ const window = {siyuan: {user: null}, dispatchEvent: event => {
+ events.push(event.type);
+ order.push("login");
+ }};
+ const cloud = {};
+ runInNewContext(compile(readFileSync("src/config/tabs/cloudUser.ts", "utf8")), {exports: cloud, window});
+ const source = sourceFile("src/config/tabs/accountUi.ts");
+ const apply = source.statements.find(node => ts.isVariableStatement(node) &&
+ node.declarationList.declarations.some(item => item.name.getText(source) === "applyCloudUserState"));
+ const account = {};
+ runInNewContext(compile(apply.getText(source)), {
+ exports: account, window, ...cloud, syncTabElement: {},
+ renderAccount: () => order.push("account"), refreshSyncCloudSpaceGroup: () => order.push("space"),
+ onSetaccount: () => order.push("toolbar"), processSync: () => order.push("sync"),
+ CustomEvent: class {constructor(type) {this.type = type;}},
+ });
+ const user = {userId: "alice", userName: "Alice"};
+ account.applyCloudUserState(user);
+ assert.deepEqual(order, ["account", "space", "toolbar", "sync", "login"]);
+ account.applyCloudUserState({...user});
+ account.applyCloudUserState({...user, userNickname: "Updated"});
+ assert.deepEqual(events, ["siyuan-login-success"]);
+ assert.equal(window.siyuan.user.userNickname, "Updated");
+ account.applyCloudUserState({userId: "bob", userName: "Bob"});
+ assert.equal(events.length, 2);
+ account.applyCloudUserState(null, "Bob");
+ assert.equal(events.length, 2);
+ account.applyCloudUserState({userId: "bob", userName: "Bob"});
+ assert.equal(events.length, 3);
+ assert.equal(order.at(-1), "login");
+});