An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Hide disabled decision provider settings https://github.com/siyuan-note/siyuan/issues/19986
Daniel1fb5975b461c
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.syindex 24fff6ef0a..c4f91c5599 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260920123707-taf3ttd.sy@@ -6,7 +6,7 @@"id": "20260920123707-taf3ttd","title": "Decision model","type": "doc",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -43,7 +43,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-gv610zn",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -58,7 +58,7 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-omz7px3",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -90,7 +90,7 @@},{"Type": "NodeText",- "Data": ", open a provider card to edit its API endpoint, API key, model name and request timeout. Opening a card does not change the active provider. Save keeps that provider’s settings; Save and use also selects it for new requests. Each provider retains its own settings and key when you switch. The global switch is off by default; disabling it retains both configurations. TypeSafe defaults to https://api.typesafe.ai/v1/systemone with jev-latest; OpenAI defaults to https://api.openai.com/v1/decisions with gpt-6-luna. Both default to a 30-second timeout. A chat-compatible endpoint does not necessarily support Decisions. Existing TypeSafe settings are retained after upgrading."+ "Data": ", first turn on the global switch, then open a provider card to edit its API endpoint, API key, model name and request timeout. Opening a card does not change the active provider. Save keeps that provider’s settings; Save and use also selects it for new requests. Each provider retains its own settings and key when you switch. The global switch is off by default. When it is off, only the switch is shown; provider cards and configuration details are hidden, and the decision model cannot be called. Both saved configurations, their keys and the active provider selection are retained. TypeSafe defaults to https://api.typesafe.ai/v1/systemone with jev-latest; OpenAI defaults to https://api.openai.com/v1/decisions with gpt-6-luna. Both default to a 30-second timeout. A chat-compatible endpoint does not necessarily support Decisions. Existing TypeSafe settings are retained after upgrading."}]},@@ -128,7 +128,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-5yw9ara",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -143,12 +143,12 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-fvzl2j1",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{"Type": "NodeText",- "Data": "Relevant text is sent to the selected decision service and charges may apply. Tool calls follow the existing capability confirmation policy. Encrypted notebooks must be unlocked; encrypted sources also require their notebook ID, and their selected content is sent in readable form. The connection test uses the complete draft settings and a fixed sample, does not read notes, and may incur charges. Testing does not save settings, change the active provider or enable the service. A successful test checks the connection and basic protocol, not answer quality."+ "Data": "Turning on the switch alone does not send requests or incur usage charges. Requests are sent to the selected decision service only when you manually run a connection test or use a decision tool, and charges may apply. Tool calls follow the existing capability confirmation policy. Encrypted notebooks must be unlocked; encrypted sources also require their notebook ID, and their selected content is sent in readable form. After enabling the feature, you can manually run a connection test using the complete draft settings and a fixed sample; it does not read notes. Testing does not save settings or change the active provider. A successful test checks the connection and basic protocol, not answer quality."}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.syindex 23902e40cf..f0b7f2c5d3 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260920123707-1cgsb12.sy@@ -6,7 +6,7 @@"id": "20260920123707-1cgsb12","title": "决策模型","type": "doc",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -43,7 +43,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-dk1tbi0",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -58,7 +58,7 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-e5xvhrd",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -90,7 +90,7 @@},{"Type": "NodeText",- "Data": " 中点击提供商卡片,进入详情编辑接口地址、API 密钥、模型名称和请求超时。打开卡片不会切换当前提供商。“保存”仅保存该提供商的配置,“保存并使用”还会将其设为新请求使用的提供商。切换时各自的配置和密钥均保留。全局开关默认关闭,关闭后仍保留两套配置。TypeSafe 默认接口为 https://api.typesafe.ai/v1/systemone,模型为 jev-latest;OpenAI 默认接口为 https://api.openai.com/v1/decisions,模型为 gpt-6-luna;两者默认超时均为 30 秒。兼容聊天接口的服务不一定支持 Decisions。升级后保留原有 TypeSafe 配置。"+ "Data": " 中先开启全局开关,再点击提供商卡片,进入详情编辑接口地址、API 密钥、模型名称和请求超时。打开卡片不会切换当前提供商。“保存”仅保存该提供商的配置,“保存并使用”还会将其设为新请求使用的提供商。切换时各自的配置和密钥均保留。全局开关默认关闭。关闭时仅显示开关,隐藏提供商卡片和配置详情,决策模型不可调用,已保存的两套配置、密钥和当前提供商选择均保留。TypeSafe 默认接口为 https://api.typesafe.ai/v1/systemone,模型为 jev-latest;OpenAI 默认接口为 https://api.openai.com/v1/decisions,模型为 gpt-6-luna;两者默认超时均为 30 秒。兼容聊天接口的服务不一定支持 Decisions。升级后保留原有 TypeSafe 配置。"}]},@@ -128,7 +128,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-te89kkt",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -143,12 +143,12 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-au1tcls",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{"Type": "NodeText",- "Data": "相关文本会发送到选定的决策服务,可能产生费用。工具调用沿用现有的能力确认策略。加密笔记本必须先解锁,引用其中的区块还需要提供笔记本 ID,选中的内容会以可读形式发送。连接测试使用完整的配置草稿和固定样例,不读取笔记,可能产生费用。测试不会保存配置、切换当前提供商或启用服务。测试成功仅代表连接和基本协议可用,不代表答案质量已通过验证。"+ "Data": "开启开关本身不会发送请求或产生调用费用;手动执行连接测试或使用决策工具时,才会向选定的决策服务发送请求,并可能产生费用。工具调用沿用现有的能力确认策略。加密笔记本必须先解锁,引用其中的区块还需要提供笔记本 ID,选中的内容会以可读形式发送。启用后,可手动执行连接测试,使用完整的配置草稿和固定样例,不读取笔记。测试不会保存配置或切换当前提供商。测试成功仅代表连接和基本协议可用,不代表答案质量已通过验证。"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.syindex 1eb7b2307c..147529bd03 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260920123707-f5ggb0o.sy@@ -6,7 +6,7 @@"id": "20260920123707-f5ggb0o","title": "決策模型","type": "doc",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -43,7 +43,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-z1tozow",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -58,7 +58,7 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-2h90hjs",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -90,7 +90,7 @@},{"Type": "NodeText",- "Data": " 中點擊提供商卡片,進入詳細資料編輯介面位址、API 金鑰、模型名稱和請求逾時。開啟卡片不會切換目前的提供商。「儲存」僅儲存該提供商的設定,「儲存並使用」還會將其設為新請求使用的提供商。切換時各自的設定和金鑰均保留。全域開關預設關閉,關閉後仍保留兩套設定。TypeSafe 預設介面為 https://api.typesafe.ai/v1/systemone,模型為 jev-latest;OpenAI 預設介面為 https://api.openai.com/v1/decisions,模型為 gpt-6-luna;兩者預設逾時均為 30 秒。相容聊天介面的服務不一定支援 Decisions。升級後保留原有 TypeSafe 設定。"+ "Data": " 中先開啟全域開關,再點擊提供商卡片,進入詳細資料編輯介面位址、API 金鑰、模型名稱和請求逾時。開啟卡片不會切換目前的提供商。「儲存」僅儲存該提供商的設定,「儲存並使用」還會將其設為新請求使用的提供商。切換時各自的設定和金鑰均保留。全域開關預設關閉。關閉時僅顯示開關,隱藏提供商卡片和設定詳細資料,決策模型無法呼叫,已儲存的兩套設定、金鑰和目前的提供商選擇均保留。TypeSafe 預設介面為 https://api.typesafe.ai/v1/systemone,模型為 jev-latest;OpenAI 預設介面為 https://api.openai.com/v1/decisions,模型為 gpt-6-luna;兩者預設逾時均為 30 秒。相容聊天介面的服務不一定支援 Decisions。升級後保留原有 TypeSafe 設定。"}]},@@ -128,7 +128,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-sgt2wba",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -143,12 +143,12 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-hyptw2z",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{"Type": "NodeText",- "Data": "相關文字會傳送至選定的決策服務,可能產生費用。工具呼叫沿用既有的能力確認策略。加密筆記本必須先解鎖,引用其中的區塊還需要提供筆記本 ID,選取的內容會以可讀形式傳送。連線測試使用完整的設定草稿和固定範例,不讀取筆記,可能產生費用。測試不會儲存設定、切換目前的提供商或啟用服務。測試成功僅代表連線和基本協定可用,不代表答案品質已通過驗證。"+ "Data": "開啟開關本身不會傳送請求或產生呼叫費用;手動執行連線測試或使用決策工具時,才會向選定的決策服務傳送請求,並可能產生費用。工具呼叫沿用既有的能力確認策略。加密筆記本必須先解鎖,引用其中的區塊還需要提供筆記本 ID,選取的內容會以可讀形式傳送。啟用後,可手動執行連線測試,使用完整的設定草稿和固定範例,不讀取筆記。測試不會儲存設定或切換目前的提供商。測試成功僅代表連線和基本協定可用,不代表答案品質已通過驗證。"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.syindex 90c727df2e..7301640a5d 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260920123707-im3t4o6.sy@@ -6,7 +6,7 @@"id": "20260920123707-im3t4o6","title": "判定モデル","type": "doc",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -43,7 +43,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-4696u20",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -58,7 +58,7 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-wp7a1fq",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -86,7 +86,7 @@},{"Type": "NodeText",- "Data": " でプロバイダーのカードを開き、詳細画面で API エンドポイント、API キー、モデル名、リクエストのタイムアウトを編集します。カードを開くだけでは使用中のプロバイダーは変わりません。「保存」はそのプロバイダーの設定だけを保存し、「保存して使用」は新しいリクエストで使用するプロバイダーも変更します。切り替えても各プロバイダーの設定とキーは保持されます。全体のスイッチは既定で無効で、無効にしても両方の設定は保持されます。TypeSafe の既定値は https://api.typesafe.ai/v1/systemone と jev-latest、OpenAI は https://api.openai.com/v1/decisions と gpt-6-luna です。タイムアウトの既定値はいずれも30秒です。チャット互換サービスが Decisions に対応しているとは限りません。アップグレード後も既存の TypeSafe 設定は保持されます。"+ "Data": " で最初に全体のスイッチを有効にしてからプロバイダーのカードを開き、詳細画面で API エンドポイント、API キー、モデル名、リクエストのタイムアウトを編集します。カードを開くだけでは使用中のプロバイダーは変わりません。「保存」はそのプロバイダーの設定だけを保存し、「保存して使用」は新しいリクエストで使用するプロバイダーも変更します。切り替えても各プロバイダーの設定とキーは保持されます。全体のスイッチは既定で無効です。無効な間はスイッチだけが表示され、プロバイダーのカードと設定の詳細は非表示になり、判定モデルを呼び出せません。保存済みの両方の設定、キー、使用中のプロバイダーの選択は保持されます。TypeSafe の既定値は https://api.typesafe.ai/v1/systemone と jev-latest、OpenAI は https://api.openai.com/v1/decisions と gpt-6-luna です。タイムアウトの既定値はいずれも30秒です。チャット互換サービスが Decisions に対応しているとは限りません。アップグレード後も既存の TypeSafe 設定は保持されます。"}]},@@ -124,7 +124,7 @@"Type": "NodeHeading","Properties": {"id": "20260920123707-z2he5ii",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{@@ -139,12 +139,12 @@"Type": "NodeParagraph","Properties": {"id": "20260920122941-f8kxvml",- "updated": "20261007020517"+ "updated": "20261007050953"},"Children": [{"Type": "NodeText",- "Data": "関連するテキストは選択した判定サービスに送信され、料金が発生する場合があります。ツールの呼び出しには既存の機能確認ポリシーが適用されます。暗号化されたノートブックはロックを解除し、ブロックと共にノートブック ID を指定する必要があります。選択した内容は読み取り可能な形で送信されます。接続テストは編集中の設定一式と固定サンプルを使用し、ノートを読み取りませんが、料金が発生する場合があります。テストは設定の保存、使用中のプロバイダーの変更、サービスの有効化を行いません。成功は接続と基本的なプロトコルの確認を示すもので、回答品質の検証ではありません。"+ "Data": "スイッチを有効にするだけでは、リクエストは送信されず、呼び出しによる料金も発生しません。接続テストを手動で実行するか、判定ツールを使用したときに、選択した判定サービスにリクエストが送信され、料金が発生する場合があります。ツールの呼び出しには既存の機能確認ポリシーが適用されます。暗号化されたノートブックはロックを解除し、ブロックと共にノートブック ID を指定する必要があります。選択した内容は読み取り可能な形で送信されます。有効にした後、編集中の設定一式と固定サンプルを使って接続テストを手動で実行できます。テストではノートを読み取らず、設定の保存や使用中のプロバイダーの変更も行いません。成功は接続と基本的なプロトコルの確認を示すもので、回答品質の検証ではありません。"}]},diff --git a/app/src/config/tabs/ai/aiDecisionUi.test.ts b/app/src/config/tabs/ai/aiDecisionUi.test.tsindex b3434e200b..fb55c617af 100644--- a/app/src/config/tabs/ai/aiDecisionUi.test.ts+++ b/app/src/config/tabs/ai/aiDecisionUi.test.ts@@ -9,32 +9,57 @@ class ElementStub {innerHTML = "";textContent = "";disabled = false;+ checked = false;isConnected = true;+ classes = new Set<string>();+ classList = {+ toggle: (name: string, enabled: boolean) => {+ if (enabled) { this.classes.add(name); } else { this.classes.delete(name); }+ return enabled;+ },+ contains: (name: string) => this.classes.has(name),+ };dataset: Record<string, string> = {};events: Record<string, (event: any) => any> = {};+ listeners = new Map<string, Set<(event: any) => any>>();elements: Record<string, ElementStub> = {};attributes: Record<string, string> = {};emitted: string[] = [];focused = false;focusOptions?: FocusOptions;setAttribute(name: string, value: string) { this.attributes[name] = value; }- dispatchEvent(event: {type: string}) { this.emitted.push(event.type); }- addEventListener(name: string, callback: (event: any) => any) { this.events[name] = callback; }+ dispatchEvent(event: {type: string}) { this.emitted.push(event.type); this.events[event.type]?.(event); }+ addEventListener(name: string, callback: (event: any) => any) {+ if (!this.listeners.has(name)) { this.listeners.set(name, new Set()); }+ this.listeners.get(name).add(callback);+ this.events[name] = (event) => {+ let result: unknown;+ this.listeners.get(name).forEach(listener => { result = listener(event); });+ return result;+ };+ }+ removeEventListener(name: string, callback: (event: any) => any) { this.listeners.get(name)?.delete(callback); }querySelector(selector: string) { return this.elements[selector]; }- querySelectorAll(): ElementStub[] { return []; }+ querySelectorAll(selector: string): ElementStub[] { return selector === "input, button" ? Object.values(this.elements) : []; }closest() { return this; }+ contains(element: ElementStub) { return Object.values(this.elements).includes(element); }focus(options?: FocusOptions) { this.focused = true; this.focusOptions = options; }}-const loadUI = (provider = "openai") => {+const loadUI = (provider = "openai", enabled = true, withSwitch = true) => {const source = readFileSync(resolve(process.cwd(), "src/config/tabs/ai/aiDecisionUi.ts"), "utf8");const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;const profile = {endpoint: "https://type.example", apiKey: "type-key", name: "jev-latest", timeout: 30};- const decision = {enabled: true, provider: "typesafe", profiles: {typesafe: profile,+ const decision = {enabled, provider: "typesafe", profiles: {typesafe: profile,openai: {...profile, endpoint: "https://open.example", apiKey: "open-key", name: "gpt-6-luna"}}};const root = new ElementStub();const cards = new ElementStub();root.elements["#aiDecisionCards"] = cards;+ const block = new ElementStub();+ root.elements["#aiDecisionCardsBlock"] = block;+ const toggle = new ElementStub();+ toggle.checked = enabled;+ if (withSwitch) { root.elements['[id="ai.decision.enabled"]'] = toggle; }const view = new ElementStub();for (const selector of [".b3-dialog__body", "[data-type='testResult']", "[data-action='test']", "[data-decision-field='endpoint']"]) {view.elements[selector] = new ElementStub();@@ -46,13 +71,22 @@ const loadUI = (provider = "openai") => {let removed = false;let applySave = true;let backLabel = "";+ let opened = 0;+ let pendingSave = Promise.resolve(true);+ let saveReads = 0;let finishRemoval: () => void;const exports: any = {};+ const windowEvents = new ElementStub();+ const timers: Array<() => void> = [];+ const document = {activeElement: new ElementStub()};runInNewContext(code, {exports,+ document,CustomEvent: class { constructor(public type: string) {} },window: {siyuan: {config: {ai: {decision}}, languages: new Proxy({}, {get: (_target, key) => String(key)})},- addEventListener() {}, removeEventListener() {}},+ setTimeout: (callback: () => void) => timers.push(callback),+ addEventListener: windowEvents.addEventListener.bind(windowEvents),+ removeEventListener: windowEvents.removeEventListener.bind(windowEvents)},require: (name: string) => {if (name.endsWith("/escape")) { return {escapeHtmlTextAndAttr: (value: string) => value}; }if (name.endsWith("/fragments")) { return {genConfigItemMainHtml: () => "", bindPasswordIconaToggle() {}}; }@@ -62,17 +96,24 @@ const loadUI = (provider = "openai") => {new Promise<void>(done => requests.push({body, complete, fail, done}))};}if (name === "./aiRuntime") {- return {aiConfigApi: {patch: async (path: string, value: any, applied: () => void) => {+ return {AI_CONFIG_CHANGED_EVENT: "ai-config-changed", aiConfigApi: {waitForSave: () => { saveReads++; return pendingSave; }, patch: async (path: string, value: any, applied: () => void) => {patches.push({path, value});if (applySave) { applied(); }}}};}if (name === "./aiProviderUi") {return {createProviderView: (_root: unknown, label: string) => {+ opened++;backLabel = label;+ root.elements[`[data-decision-profile-view='${provider}'].config__view--show`] = view;return view;- }, removeProviderView: (_root: unknown, _view: unknown, callback: () => void) => {+ }, removeProviderView: (_root: unknown, _view?: unknown, callback?: () => void) => {+ if (!_view) {+ delete root.elements[".config__view--show:not(.fn__none)"];+ return;+ }removed = true;+ delete root.elements[`[data-decision-profile-view='${provider}'].config__view--show`];finishRemoval = callback;}};}@@ -80,19 +121,270 @@ const loadUI = (provider = "openai") => {},});exports.mountDecisionCards(root);- const target = new ElementStub();- target.dataset.decisionProvider = provider;- cards.events.click({target});+ const open = () => {+ const target = new ElementStub();+ target.dataset.decisionProvider = provider;+ cards.events.click({target});+ };+ open();const click = (action: string) => {const target = new ElementStub();target.dataset.action = action;return view.events.click({target});};const edit = (key: string, value: string) => view.events.input({target: {dataset: {decisionField: key}, value}});- return {exports, decision, patches, requests, view, root, click, edit, backLabel, finishRemoval: () => finishRemoval(),+ const setEnabled = (value: boolean) => {+ decision.enabled = value;+ windowEvents.events["ai-config-changed"]({});+ };+ const toggleEnabled = (value: boolean, save = Promise.resolve(true)) => {+ toggle.checked = value;+ toggle.events.change({});+ pendingSave = save;+ };+ const flushChanges = async () => {+ timers.splice(0).forEach(callback => callback());+ await new Promise<void>(resolve => setImmediate(resolve));+ };+ return {exports, decision, patches, requests, view, root, block, cards, toggle, document, click, edit, open,+ setEnabled, toggleEnabled, flushChanges, backLabel, opened: () => opened, saveReads: () => saveReads, finishRemoval: () => finishRemoval(),confirms: () => confirms, removed: () => removed, failSave: () => applySave = false};};+test("disabled decision settings initially hide the entire provider row and ignore card actions", () => {+ const ui = loadUI("openai", false);+ assert.match(ui.exports.genDecisionCardsHtml(), /^<div class="b3-label config-item fn__none" id="aiDecisionCardsBlock">/);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.opened(), 0);+ ui.open();+ ui.cards.events.keydown({key: "Enter", preventDefault: () => assert.fail("disabled cards must ignore keyboard actions")});+ assert.equal(ui.opened(), 0);+ assert.equal(ui.patches.length, 0);+ assert.equal(ui.requests.length, 0);+});++test("switch visibility follows the parent-document pattern without changing saved profiles", () => {+ const ui = loadUI("openai", false);+ const initial = JSON.stringify(ui.decision);+ ui.toggleEnabled(true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+ assert.equal(JSON.stringify(ui.decision), initial);+ ui.open();+ assert.equal(ui.opened(), 0);+ ui.setEnabled(true);+ ui.open();+ assert.equal(ui.opened(), 1);+ assert.doesNotMatch(ui.exports.genDecisionCardsHtml(), /fn__none/);+ ui.toggleEnabled(false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.view.classList.contains("fn__none"), true);+ ui.setEnabled(false);+ assert.equal(JSON.stringify(ui.decision), initial);+ assert.equal(ui.patches.length, 0);+ assert.equal(ui.requests.length, 0);+});++test("switch saves are observed after full event dispatch rather than an intervening microtask", async () => {+ const ui = loadUI("openai", false);+ ui.toggleEnabled(true);+ await Promise.resolve();+ await Promise.resolve();+ assert.equal(ui.saveReads(), 0);+ assert.equal(ui.toggle.checked, true);+ await ui.flushChanges();+ assert.equal(ui.saveReads(), 1);+ assert.equal(ui.toggle.checked, false);+});++test("older enable responses cannot overwrite a newer pending disable", async () => {+ const ui = loadUI("openai", false);+ let enabledSaved: (applied: boolean) => void;+ let disabledSaved: (applied: boolean) => void;+ ui.toggleEnabled(true, new Promise<boolean>(resolve => { enabledSaved = resolve; }));+ await ui.flushChanges();+ ui.toggleEnabled(false, new Promise<boolean>(resolve => { disabledSaved = resolve; }));+ await ui.flushChanges();+ ui.setEnabled(true);+ enabledSaved(true);+ await ui.flushChanges();+ assert.equal(ui.toggle.checked, false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ ui.open();+ assert.equal(ui.opened(), 0);+ ui.setEnabled(false);+ disabledSaved(true);+ await ui.flushChanges();+ assert.equal(ui.toggle.checked, false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.requests.length, 0);+ assert.equal(ui.patches.length, 0);+ ui.setEnabled(true);+ assert.equal(ui.toggle.checked, true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+});++test("failed switch saves restore saved visibility and the preserved detail", async () => {+ const ui = loadUI();+ ui.edit("apiKey", "draft-before-failed-disable");+ let finishSave: (applied: boolean) => void;+ ui.toggleEnabled(false, new Promise<boolean>(resolve => { finishSave = resolve; }));+ assert.equal(ui.view.classList.contains("fn__none"), true);+ ui.setEnabled(true);+ assert.equal(ui.toggle.checked, false);+ await ui.click("test");+ await ui.flushChanges();+ finishSave(false);+ await ui.flushChanges();+ assert.equal(ui.toggle.checked, true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+ assert.equal(ui.view.classList.contains("fn__none"), false);+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);+ assert.equal(ui.requests.length, 0);+ await ui.click("save");+ assert.equal(ui.patches[0].value.profiles.openai.apiKey, "draft-before-failed-disable");+});++test("an unsaved enable switch rolls back without revealing the provider settings", async () => {+ const ui = loadUI("openai", false);+ ui.toggleEnabled(true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+ await ui.flushChanges();+ assert.equal(ui.toggle.checked, false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.opened(), 0);+ assert.equal(ui.requests.length, 0);+ assert.equal(ui.patches.length, 0);+});++test("paused drafts wait behind other details and resume from their original card", async () => {+ const ui = loadUI();+ ui.edit("apiKey", "paused-draft-key");+ ui.setEnabled(false);+ ui.root.elements[".config__view--show:not(.fn__none)"] = new ElementStub();+ ui.setEnabled(true);+ assert.equal(ui.view.classList.contains("fn__none"), true);+ assert.equal(ui.view.elements["[data-action='test']"].disabled, true);+ await ui.click("save");+ await ui.click("test");+ assert.equal(ui.patches.length, 0);+ assert.equal(ui.requests.length, 0);+ ui.open();+ assert.equal(ui.opened(), 1);+ assert.equal(ui.view.classList.contains("fn__none"), false);+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);+ assert.equal(ui.view.elements["[data-decision-field='endpoint']"].focusOptions?.preventScroll, true);+ await ui.click("save");+ assert.equal(ui.patches[0].value.profiles.openai.apiKey, "paused-draft-key");+});++test("external disable suspends a detail and restores its unsaved draft without side effects", async () => {+ const ui = loadUI();+ const initialProfiles = JSON.stringify(ui.decision.profiles);+ ui.edit("apiKey", "draft-key");+ ui.document.activeElement = ui.view.elements["[data-decision-field='endpoint']"];+ ui.setEnabled(false);+ assert.equal(ui.toggle.checked, false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.view.classList.contains("fn__none"), true);+ assert.equal(ui.view.attributes["data-decision-profile-view"], "openai");+ assert.equal(ui.view.elements["[data-action='test']"].disabled, true);+ assert.equal(ui.toggle.focusOptions?.preventScroll, true);+ for (const action of ["test", "save", "use", "cancel", "back"]) { await ui.click(action); }+ ui.edit("apiKey", "disabled-edit");+ ui.open();+ assert.equal(ui.opened(), 1);+ assert.equal(ui.patches.length, 0);+ assert.equal(ui.requests.length, 0);+ assert.equal(ui.removed(), false);+ assert.equal(ui.confirms(), 0);+ assert.deepEqual(ui.root.emitted, []);+ assert.equal(JSON.stringify(ui.decision.profiles), initialProfiles);+ assert.equal(ui.decision.provider, "typesafe");+ ui.setEnabled(true);+ assert.equal(ui.toggle.checked, true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+ assert.equal(ui.view.classList.contains("fn__none"), false);+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);+ assert.equal(ui.opened(), 1);+ await ui.click("save");+ assert.equal(ui.patches[0].value.profiles.openai.apiKey, "draft-key");+ assert.equal(ui.patches[0].value.provider, undefined);+ assert.equal(ui.patches[0].value.enabled, undefined);+});++test("disable invalidates completed and pending tests even after the detail is re-enabled", async () => {+ const ui = loadUI();+ const result = ui.view.elements["[data-type='testResult']"];+ const completed = ui.click("test");+ ui.requests[0].complete({data: {matched: true}});+ ui.requests[0].done();+ await completed;+ assert.equal(result.textContent, "testConnectionSuccess");+ ui.setEnabled(false);+ assert.equal(result.textContent, "");+ ui.setEnabled(true);+ const pending = ui.click("test");+ ui.toggleEnabled(false);+ ui.setEnabled(false);+ ui.setEnabled(true);+ await ui.flushChanges();+ ui.requests[1].complete({data: {matched: true}});+ ui.requests[1].fail();+ ui.requests[1].done();+ await pending;+ assert.equal(result.textContent, "");+ assert.equal(ui.view.elements["[data-action='test']"].disabled, false);+ assert.equal(ui.requests.length, 2);+ assert.equal(ui.patches.length, 0);+});++test("late test completion keeps controls disabled while the feature is off", async () => {+ const ui = loadUI();+ const pending = ui.click("test");+ ui.setEnabled(false);+ ui.requests[0].complete({data: {matched: true}});+ ui.requests[0].done();+ await pending;+ assert.equal(ui.view.elements["[data-type='testResult']"].textContent, "");+ assert.equal(ui.view.elements["[data-action='test']"].disabled, true);+ assert.equal(ui.view.elements["[data-decision-field='endpoint']"].disabled, true);+});++test("standalone provider rows use saved enablement when no switch is mounted", () => {+ const ui = loadUI("openai", false, false);+ assert.equal(ui.block.classList.contains("fn__none"), true);+ assert.equal(ui.opened(), 0);+ ui.setEnabled(true);+ assert.equal(ui.block.classList.contains("fn__none"), false);+ ui.open();+ assert.equal(ui.opened(), 1);+ ui.setEnabled(false);+ assert.equal(ui.view.classList.contains("fn__none"), true);+ assert.equal(ui.patches.length, 0);+ assert.equal(ui.requests.length, 0);+});++test("decision switch and providers share search keywords while retaining the switch-only save", () => {+ const source = readFileSync("src/config/tabs/ai/aiTab.ts", "utf8");+ const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;+ const exports: {registerAiTab?: (tab: any) => void} = {};+ const definitions = new Map<string, any>();+ runInNewContext(code, {exports,+ window: {siyuan: {languages: new Proxy({}, {get: (_target, key) => String(key)})}},+ require: () => new Proxy({}, {get: () => (): unknown[] => []})});+ exports.registerAiTab({group: () => new Proxy({}, {get: (_target, method) => (id: string | {key: string}, spec: any) => {+ if (method === "switch") { definitions.set(String(id), spec); }+ if (method === "slot") { definitions.set((id as {key: string}).key, id); }+ }})});+ const toggle = definitions.get("ai.decision.enabled");+ const providers = definitions.get("decisionProviders");+ assert.deepEqual(toggle.keywords, providers.keywords);+ for (const keyword of ["TypeSafe", "OpenAI", "apiKey", "decisionModel"]) {+ assert.ok(toggle.keywords.includes(keyword));+ }+ assert.equal(toggle.save, undefined);+});+test("opening and cancelling a decision card never selects or saves it", async () => {const ui = loadUI();const endpoint = ui.view.elements["[data-decision-field='endpoint']"];@@ -221,7 +513,7 @@ test("closing animation never steals focus from a newly opened provider detail",const card = new ElementStub();ui.root.elements["[data-decision-provider='openai']"] = card;await ui.click("cancel");- ui.root.elements[".config-ai-provider__view.config__view--show"] = new ElementStub();+ ui.root.elements[".config__view--show:not(.fn__none)"] = new ElementStub();ui.finishRemoval();assert.equal(card.focused, false);assert.deepEqual(ui.root.emitted, ["siyuan-decision-profile-closed"]);diff --git a/app/src/config/tabs/ai/aiDecisionUi.ts b/app/src/config/tabs/ai/aiDecisionUi.tsindex 474081cdc3..7979853e12 100644--- a/app/src/config/tabs/ai/aiDecisionUi.ts+++ b/app/src/config/tabs/ai/aiDecisionUi.ts@@ -61,11 +61,17 @@ export const getDecisionProfilePatch = (provider: DecisionProvider, profile: Con...(use ? {provider} : {}),});-export const genDecisionCardsHtml = () => `<div class="b3-label config-item">+export const genDecisionCardsHtml = () => `<div class="b3-label config-item${window.siyuan.config.ai.decision.enabled ? "" : " fn__none"}" id="aiDecisionCardsBlock">${genConfigItemMainHtml(window.siyuan.languages.apiProvider, window.siyuan.languages.decisionProvidersTip)}<div class="fn__hr"></div><div id="aiDecisionCards"></div></div>`;+const getDecisionEnabledInput = (root: HTMLElement) =>+ root.querySelector<HTMLInputElement>('[id="ai.decision.enabled"]');++const isDecisionEnabled = (root: HTMLElement) =>+ Boolean(window.siyuan.config.ai.decision.enabled) && getDecisionEnabledInput(root)?.checked !== false;+const renderDecisionCards = (root: HTMLElement) => {const container = root.querySelector<HTMLElement>("#aiDecisionCards");if (!container) { return; }@@ -83,6 +89,13 @@ const renderDecisionCards = (root: HTMLElement) => {};const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {+ if (!isDecisionEnabled(root)) { return; }+ const host = root.closest<HTMLElement>(".config__tab-container") || root;+ const existing = host.querySelector<HTMLElement>(`[data-decision-profile-view='${provider}'].config__view--show`);+ if (existing) {+ existing.dispatchEvent(new CustomEvent("siyuan-decision-profile-resume"));+ return;+ }const draft = getDecisionProfileDraft(window.siyuan.config.ai.decision, provider);const initial = JSON.stringify(draft);const view = createProviderView(root, window.siyuan.languages.apiProvider);@@ -133,18 +146,52 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {let closed = false;let saving = false;let testing = false;+ const enabledInput = getDecisionEnabledInput(root);+ const canEdit = () => isDecisionEnabled(root) && !view.classList.contains("fn__none");+ const updateControls = () => {+ const disabled = !canEdit() || saving;+ view.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(element => element.disabled = disabled);+ testButton.disabled = disabled || testing;+ };+ const stopWatching = () => {+ enabledInput?.removeEventListener("change", updateVisibility);+ root.removeEventListener(AI_CONFIG_CHANGED_EVENT, updateVisibility);+ window.removeEventListener(AI_CONFIG_CHANGED_EVENT, updateVisibility);+ };+ const updateVisibility = () => {+ if (!view.isConnected) { stopWatching(); return; }+ const enabled = isDecisionEnabled(root);+ const otherView = host.querySelector(".config__view--show:not(.fn__none)");+ // 隐藏详情但保留 DOM 和草稿,继续阻止设置刷新替换未保存的内容。+ view.classList.toggle("fn__none", !enabled || view.classList.contains("fn__none") && !!otherView && otherView !== view);+ if (!enabled) {+ revision++;+ result.textContent = "";+ if (view.contains(document.activeElement)) { enabledInput?.focus({preventScroll: true}); }+ }+ updateControls();+ };+ enabledInput?.addEventListener("change", updateVisibility);+ root.addEventListener(AI_CONFIG_CHANGED_EVENT, updateVisibility);+ window.addEventListener(AI_CONFIG_CHANGED_EVENT, updateVisibility);+ view.addEventListener("siyuan-decision-profile-resume", () => {+ if (closed || !isDecisionEnabled(root) || !view.classList.contains("fn__none")) { return; }+ removeProviderView(root);+ updateVisibility();+ view.querySelector<HTMLInputElement>("[data-decision-field='endpoint']")?.focus({preventScroll: true});+ });const leave = () => {closed = true;+ stopWatching();removeProviderView(root, view, () => {- const host = root.closest<HTMLElement>(".config__tab-container") || root;- if (root.isConnected && !host.querySelector(".config-ai-provider__view.config__view--show")) {+ if (root.isConnected && isDecisionEnabled(root) && !host.querySelector(".config__view--show:not(.fn__none)")) {root.querySelector<HTMLElement>(`[data-decision-provider='${provider}']`)?.focus({preventScroll: true});}root.dispatchEvent(new CustomEvent("siyuan-decision-profile-closed", {bubbles: true}));});};const close = () => {- if (saving) { return; }+ if (saving || closed || !canEdit()) { return; }if (JSON.stringify(draft) !== initial) {confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.discardUnsavedChanges, leave);} else { leave(); }@@ -168,6 +215,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {return true;};view.addEventListener("input", event => {+ if (!canEdit() || saving || closed) { return; }const input = event.target as HTMLInputElement;const field = input.dataset.decisionField as keyof Config.IDecisionProfile;if (!field) { return; }@@ -176,6 +224,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {result.textContent = "";});view.addEventListener("click", async event => {+ if (!canEdit()) { return; }const action = (event.target as Element).closest<HTMLElement>("[data-action]")?.dataset.action;if (action === "back" || action === "cancel") { close(); return; }if (saving || closed) { return; }@@ -184,7 +233,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {saving = true;revision++;result.textContent = "";- view.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(element => element.disabled = true);+ updateControls();let applied = false;try {await aiConfigApi.patch("decision", getDecisionProfilePatch(provider, draft, action === "use"), () => {@@ -195,8 +244,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {} finally {if (!applied) { result.textContent = window.siyuan.languages.decisionSaveFailed; }saving = false;- view.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(element => element.disabled = false);- testButton.disabled = testing;+ updateControls();}} else if (action === "test" && !testing && validate(true)) {testing = true;@@ -204,7 +252,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {testLabel.textContent = window.siyuan.languages.testConnectionTesting;result.textContent = "";const testedRevision = revision;- const current = () => !closed && view.isConnected && testedRevision === revision;+ const current = () => !closed && view.isConnected && canEdit() && testedRevision === revision;try {await fetchPost("/api/ai/testDecisionModel", {provider, profile: {...draft}}, response => {if (!current()) { return; }@@ -218,7 +266,7 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {if (current()) { result.textContent = window.siyuan.languages.testConnectionFail; }} finally {testing = false;- testButton.disabled = saving;+ updateControls();testLabel.textContent = window.siyuan.languages.testConnection;}}@@ -227,13 +275,37 @@ const openDecisionProfile = (root: HTMLElement, provider: DecisionProvider) => {export const mountDecisionCards = (root: HTMLElement) => {const container = root.querySelector<HTMLElement>("#aiDecisionCards");- if (!container) { return; }+ const block = root.querySelector<HTMLElement>("#aiDecisionCardsBlock");+ if (!container || !block) { return; }+ const enabledInput = getDecisionEnabledInput(root);+ let changeRevision = 0;+ let pendingChange = 0;+ const updateVisibility = () => block.classList.toggle("fn__none", !(enabledInput?.checked ?? window.siyuan.config.ai.decision.enabled));+ enabledInput?.addEventListener("change", () => {+ const revision = ++changeRevision;+ pendingChange = revision;+ updateVisibility();+ const complete = () => {+ if (pendingChange !== revision || !container.isConnected) { return; }+ pendingChange = 0;+ enabledInput.checked = window.siyuan.config.ai.decision.enabled;+ updateVisibility();+ root.dispatchEvent(new CustomEvent(AI_CONFIG_CHANGED_EVENT));+ };+ // change 完整派发后委托保存已入队;旧响应不得覆盖用户最新一次切换。+ window.setTimeout(() => {+ if (pendingChange !== revision || !container.isConnected) { return; }+ void aiConfigApi.waitForSave().then(complete, complete);+ }, 0);+ });+ updateVisibility();renderDecisionCards(root);container.addEventListener("click", event => {const provider = (event.target as Element).closest<HTMLElement>("[data-decision-provider]")?.dataset.decisionProvider as DecisionProvider;if (PROVIDERS.includes(provider)) { openDecisionProfile(root, provider); }});container.addEventListener("keydown", event => {+ if (!isDecisionEnabled(root)) { return; }if (event.key === "Enter" || event.key === " ") {event.preventDefault();(event.target as HTMLElement).click();@@ -241,6 +313,8 @@ export const mountDecisionCards = (root: HTMLElement) => {});const update = () => {if (!container.isConnected) { window.removeEventListener(AI_CONFIG_CHANGED_EVENT, update); return; }+ if (enabledInput && !pendingChange) { enabledInput.checked = window.siyuan.config.ai.decision.enabled; }+ updateVisibility();renderDecisionCards(root);};window.addEventListener(AI_CONFIG_CHANGED_EVENT, update);diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex d62ba882ad..46830a8898 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -99,7 +99,9 @@ const getProviderViews = (root: HTMLElement) => {};export const removeProviderView = (root: HTMLElement, view?: HTMLElement, onRemoved?: () => void) => {- const views = view ? [view] : getProviderViews(root);+ // 暂停的决策详情保留未保存草稿,只有显式关闭该详情时才销毁。+ const views = view ? [view] : getProviderViews(root).filter(item =>+ !item.hasAttribute("data-decision-profile-view") || !item.classList.contains("fn__none"));views.forEach((item) => {let removed = false;const remove = () => {diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.tsindex 463a5cc26c..9154a7e9bc 100644--- a/app/src/config/tabs/ai/aiTab.ts+++ b/app/src/config/tabs/ai/aiTab.ts@@ -161,15 +161,18 @@ const registerAiAgentGroup = (tab: SettingTabBuilder) => {const registerAiDecisionGroup = (tab: SettingTabBuilder) => {const group = tab.group("decision", window.siyuan.languages.decisionModel);+ const keywords = [window.siyuan.languages.decisionModel, window.siyuan.languages.decisionModelTip,+ "TypeSafe", "OpenAI", "Decisions", window.siyuan.languages.apiKey,+ window.siyuan.languages.apiEndpoint, window.siyuan.languages.apiModel,+ window.siyuan.languages.apiTimeout, window.siyuan.languages.testConnection];group.switch("ai.decision.enabled", {title: window.siyuan.languages.decisionModel,desc: window.siyuan.languages.decisionModelTip,+ keywords,});group.slot({key: "decisionProviders",- keywords: ["TypeSafe", "OpenAI", "Decisions", window.siyuan.languages.apiKey,- window.siyuan.languages.apiEndpoint, window.siyuan.languages.apiModel,- window.siyuan.languages.apiTimeout, window.siyuan.languages.testConnection],+ keywords,html: genDecisionCardsHtml,afterMount: mountDecisionCards,});diff --git a/app/tests/decisionProviderFocus.test.js b/app/tests/decisionProviderFocus.test.jsindex 09a4295e56..dcdb6c88bf 100644--- a/app/tests/decisionProviderFocus.test.js+++ b/app/tests/decisionProviderFocus.test.js@@ -21,7 +21,9 @@ const runCases = async (sources, languages, reproduceUnsafeFocus = false) => {const wait = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));const unexpected = () => { throw new Error("Opening and closing decision profiles must not call an external service"); };const mocks = {- "config/tabs/ai/aiRuntime": {AI_CONFIG_CHANGED_EVENT: "siyuan-ai-config-changed", aiConfigApi: {patch: unexpected}},+ "config/tabs/ai/aiRuntime": {AI_CONFIG_CHANGED_EVENT: "siyuan-ai-config-changed", aiConfigApi: {+ patch: unexpected, waitForSave: async () => true,+ }},"dialog/confirmDialog": {confirmDialog: unexpected},"dialog/message": {showMessage: unexpected},"util/fetch": {fetchPost: unexpected},@@ -47,12 +49,11 @@ const runCases = async (sources, languages, reproduceUnsafeFocus = false) => {return exports;};window.siyuan = {languages, config: {ai: {decision: {- enabled: true, provider: "typesafe", profiles: {+ enabled: false, provider: "typesafe", profiles: {typesafe: {endpoint: "https://typesafe.example/v1/systemone", apiKey: "", name: "jev-latest", timeout: 30},openai: {endpoint: "https://openai.example/v1/decisions", apiKey: "", name: "gpt-6-luna", timeout: 30},},}}}};- const initialConfig = JSON.stringify(window.siyuan.config);const ui = load("config/tabs/ai/aiDecisionUi");// 复用桌面设置外壳,绝对定位参照是面板而非滚动页,保留真实溢出与动画规则。document.body.insertAdjacentHTML("beforeend", `<div class="b3-dialog b3-dialog--open">@@ -69,10 +70,31 @@ const runCases = async (sources, languages, reproduceUnsafeFocus = false) => {const dialog = document.querySelector(".b3-dialog");const panel = dialog.querySelector(".config__panel");const root = dialog.querySelector(".config__tab-container");+ const switchHTML = load("config/render/fragments").genSwitchRow("ai.decision.enabled",+ languages.decisionModel, languages.decisionModelTip, false);root.innerHTML = `<div class="config-group config-group--first config-group--last">- <div class="config-title">${languages.decisionModel}</div><div class="config-items">${ui.genDecisionCardsHtml()}</div>+ <div class="config-title">${languages.decisionModel}</div><div class="config-items">${switchHTML}${ui.genDecisionCardsHtml()}</div></div>`;ui.mountDecisionCards(root);+ const decision = window.siyuan.config.ai.decision;+ const preservedConfig = JSON.stringify({provider: decision.provider, profiles: decision.profiles});+ const enabledInput = root.querySelector('[id="ai.decision.enabled"]');+ const providerBlock = root.querySelector("#aiDecisionCardsBlock");+ const refreshConfig = enabled => {+ decision.enabled = enabled;+ window.dispatchEvent(new CustomEvent("siyuan-ai-config-changed"));+ };+ assert.equal(getComputedStyle(providerBlock).display, "none", "The entire provider configuration starts hidden while disabled");+ root.querySelector("[data-decision-provider='typesafe']").click();+ assert.equal(root.querySelector("[data-decision-profile-view]"), null, "Disabled cards cannot open a detail");+ enabledInput.checked = true;+ enabledInput.dispatchEvent(new Event("change", {bubbles: true}));+ assert.notEqual(getComputedStyle(providerBlock).display, "none", "Reuse immediate switch-controlled visibility");+ root.querySelector("[data-decision-provider='typesafe']").click();+ assert.equal(root.querySelector("[data-decision-profile-view]"), null, "Pending enable must not bypass saved configuration");+ refreshConfig(true);+ await wait(0);+ const initialConfig = JSON.stringify(window.siyuan.config);assert.equal(getComputedStyle(root).position, "static", "Do not hide the bug with a positioned tab fixture");assert.equal(getComputedStyle(panel).overflowX, "hidden");const ancestors = element => {@@ -204,6 +226,74 @@ const runCases = async (sources, languages, reproduceUnsafeFocus = false) => {assert.equal(JSON.stringify(window.siyuan.config), initialConfig, "Opening and cancelling never changes configuration");}}+ const card = root.querySelector("[data-decision-provider='openai']");+ card.click();+ await wait(360);+ const view = root.querySelector("[data-decision-profile-view='openai']");+ const draftInput = view.querySelector("[data-decision-field='endpoint']");+ const originalEndpoint = draftInput.value;+ draftInput.value = "https://unsaved.example/v1/decisions";+ draftInput.dispatchEvent(new Event("input", {bubbles: true}));+ enabledInput.checked = false;+ enabledInput.dispatchEvent(new Event("change", {bubbles: true}));+ assert.equal(getComputedStyle(providerBlock).display, "none", "Disabling immediately hides all provider content");+ assert.equal(getComputedStyle(view).display, "none", "Disabling also hides an already open detail");+ refreshConfig(false);+ assert.equal(enabledInput.checked, false);+ assert.equal(view.isConnected, true, "An unsaved draft stays mounted while disabled");+ for (const action of ["save", "use", "test"]) {+ const button = view.querySelector(`[data-action='${action}']`);+ assert.equal(button.disabled, true);+ button.dispatchEvent(new MouseEvent("click", {bubbles: true}));+ }+ await wait(0);+ assert.equal(JSON.stringify({provider: decision.provider, profiles: decision.profiles}), preservedConfig,+ "Disabling never clears saved profiles, credentials, or the active provider");+ const providerViews = load("config/tabs/ai/aiProviderUi");+ const ordinaryView = providerViews.createProviderView(root, languages.apiProvider);+ ordinaryView.querySelector(".b3-dialog__body").textContent = "Ordinary provider settings";+ await wait(360);+ assert.equal(view.isConnected, true, "Opening another provider must not destroy the paused decision draft");+ refreshConfig(true);+ assert.equal(getComputedStyle(view).display, "none", "Resuming enablement must not cover another provider detail");+ providerViews.removeProviderView(root, ordinaryView);+ await wait(360);+ root.querySelector("[data-decision-provider='openai']").click();+ await wait(360);+ assert.equal(root.querySelector("[data-decision-profile-view='openai']"), view, "Enabling resumes the same draft");+ assert.equal(draftInput.value, "https://unsaved.example/v1/decisions");+ assert.notEqual(getComputedStyle(view).display, "none");+ visible(draftInput, "resumed unsaved draft");+ draftInput.value = originalEndpoint;+ draftInput.dispatchEvent(new Event("input", {bubbles: true}));+ view.querySelector("[data-action='cancel']").click();+ await wait(360);+ refreshConfig(false);+ assert.equal(getComputedStyle(providerBlock).display, "none");+ assert.equal(root.querySelector("[data-decision-profile-view]"), null);+ refreshConfig(true);+ assert.equal(JSON.stringify(window.siyuan.config), initialConfig);+ // 原生输入会在目标与祖先监听器间执行微任务,不能只用 dispatchEvent 验证保存顺序。+ const savedSwitches = [];+ let pendingSave = Promise.resolve(true);+ mocks["config/tabs/ai/aiRuntime"].aiConfigApi.waitForSave = () => pendingSave;+ root.addEventListener("change", event => {+ if (event.target !== enabledInput) { return; }+ assert.equal(event.isTrusted, true);+ const enabled = enabledInput.checked;+ savedSwitches.push(enabled);+ pendingSave = wait(20).then(() => { refreshConfig(enabled); return true; });+ });+ for (const enabled of [false, true]) {+ enabledInput.focus({preventScroll: true});+ await require("electron").ipcRenderer.invoke("decision-test-toggle");+ await wait(60);+ assert.equal(enabledInput.checked, enabled, "Native switch input survives delegated save ordering");+ assert.equal(decision.enabled, enabled);+ assert.equal(getComputedStyle(providerBlock).display === "none", !enabled);+ }+ assert.deepEqual(savedSwitches, [false, true]);+ assert.equal(JSON.stringify(window.siyuan.config), initialConfig);} finally {HTMLElement.prototype.focus = nativeFocus;dialog.remove();@@ -214,7 +304,7 @@ const runCases = async (sources, languages, reproduceUnsafeFocus = false) => {};const runElectron = async () => {- const {app, BrowserWindow} = require("electron");+ const {app, BrowserWindow, ipcMain} = require("electron");const {ModuleKind, ScriptTarget, transpileModule} = require("typescript");const appRoot = path.join(__dirname, "..");const sources = Object.fromEntries(sourceModules.map(id => [id, transpileModule(@@ -233,6 +323,11 @@ const runElectron = async () => {nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true,}});const requests = [];+ ipcMain.handle("decision-test-toggle", event => {+ assert.equal(event.sender, win.webContents);+ win.webContents.sendInputEvent({type: "keyDown", keyCode: "Space"});+ win.webContents.sendInputEvent({type: "keyUp", keyCode: "Space"});+ });win.webContents.session.webRequest.onBeforeRequest({urls: ["http://*/*", "https://*/*"]}, (details, callback) => {requests.push(details.url);callback({cancel: true});@@ -257,6 +352,7 @@ const runElectron = async () => {assert.deepEqual(requests, [], "No external network requests are permitted");console.log("Unsafe focus negative control detected horizontal scrolling");} finally {+ ipcMain.removeHandler("decision-test-toggle");win.destroy();}app.exit(0);