From b84db8983d63a9a981083ebce1a139860c6bdf25 Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期五, 14 八月 2026 15:35:21 +0800
Subject: [PATCH] commit
---
docs/architecture/global-hotkeys.md | 70 +
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs | 241 +++
src/Moli.Desktop/Llm/LlmModels.cs | 30
src/Moli.Desktop/Configuration/JsonConfigurationService.cs | 20
src/Moli.Desktop/Llm/LlmOpenAiUrls.cs | 90 +
src/Moli.Desktop/Management/ManagementWindow.xaml | 33
src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs | 169 ++
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs | 25
src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs | 56
docs/product/llm-command-palette-plugin-prd.md | 38
src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs | 59
src/Moli.Desktop/Hotkeys/HotkeysDocument.cs | 74 +
src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs | 1
docs/qa/global-hotkeys-acceptance.md | 37
src/Moli.Desktop/Llm/LlmGatewayService.cs | 240 ++
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs | 17
src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs | 39
src/Moli.Desktop/Runtime/IDesktopRuntime.cs | 30
src/Moli.Desktop/Runtime/HotkeyService.cs | 421 ++++++
docs/README.md | 2
src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs | 43
src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs | 105 +
src/Moli.Desktop/Hotkeys/HotkeysValidator.cs | 74 +
src/Moli.Desktop/Configuration/IConfigurationService.cs | 4
src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs | 51
src/Moli.Desktop/Layout/Geometry.cs | 4
src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs | 44
src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs | 57
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs | 509 +++++++
src/Moli.Desktop/Configuration/ConfigurationDocuments.cs | 2
samples/plugins/sample.llm-command-palette/index.html | 118 +
docs/ops/user-manual/plugins/sample.llm-command-palette.md | 126 +
src/Moli.Desktop/Diagnostics/DiagnosticModels.cs | 8
src/Moli.Desktop/Windows/WidgetWindow.cs | 43
src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs | 10
samples/plugins/sample.llm-command-palette/plugin.json | 77
src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs | 8
src/Moli.Desktop/Llm/LlmModelRegistry.cs | 13
docs/data/configuration-and-storage.md | 38
src/Moli.Desktop/Host/DesktopHostBuilder.cs | 3
src/Moli.Desktop/Interop/NativeMethods.cs | 10
src/Moli.Desktop/Management/ManagementWindow.xaml.cs | 421 ++++++
src/Moli.Desktop/Runtime/IHotkeyService.cs | 42
docs/architecture/llm-command-palette-architecture.md | 93 +
src/Moli.Desktop/Llm/ILlmServices.cs | 7
docs/ops/user-manual/moli-desktop.md | 22
src/Moli.Desktop/Hotkeys/HotkeyChord.cs | 189 ++
src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs | 311 ++++
48 files changed, 3,867 insertions(+), 257 deletions(-)
diff --git a/docs/README.md b/docs/README.md
index ca08da6..9c37154 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -23,6 +23,7 @@
- [Moli.Desktop Runtime 鏋舵瀯璁捐](architecture/runtime-architecture.md)
- [Moli.Desktop MVP 璇︾粏璁捐](architecture/detailed-design.md)
- [LLM 妗岄潰杈撳叆鎻掍欢鏋舵瀯璁捐](architecture/llm-command-palette-architecture.md)
+- [鍏ㄥ眬蹇嵎閿笌浼氳瘽鍙氦浜抅(architecture/global-hotkeys.md)
## 褰撳墠寮�鍙戞枃妗�
@@ -43,6 +44,7 @@
- [Moli.Desktop MVP QA 娴嬭瘯璁″垝涓庢姤鍛奭(qa/mvp-qa-report-2026-05-02.md)
- [LLM 妗岄潰杈撳叆鎻掍欢楠屾敹璁板綍](qa/llm-command-palette-acceptance-2026-05-04.md)
- [LLM 妗岄潰杈撳叆鎻掍欢 AiChat 妯″紡楠屾敹璁板綍](qa/llm-command-palette-aichat-mode-acceptance-2026-05-04.md)
+- [鍏ㄥ眬蹇嵎閿笌浼氳瘽鍙氦浜掗獙鏀舵竻鍗昡(qa/global-hotkeys-acceptance.md)
## 褰撳墠杩愮淮鏂囨。
diff --git a/docs/architecture/global-hotkeys.md b/docs/architecture/global-hotkeys.md
new file mode 100644
index 0000000..147e5b8
--- /dev/null
+++ b/docs/architecture/global-hotkeys.md
@@ -0,0 +1,70 @@
+# 鍏ㄥ眬蹇嵎閿笌浼氳瘽鍙氦浜�
+
+鏃ユ湡锛�2026-08-13
+
+## 鑳屾櫙
+
+`sample.llm-command-palette` 杩欑被甯告樉缁勪欢绌洪棽鏃朵細鎸′綇妗岄潰鐐瑰嚮銆傚涓荤敤 Win32 `RegisterHotKey` 鎻愪緵杩涚▼绾у叏灞�蹇嵎閿紝骞跺湪鍐呭瓨涓淮鎶や細璇濆彲浜や簰瑕嗙洊灞傦紝鐑敭鍒囨崲涓嶅啀璧� `UpdateWidgetLayoutAsync`銆�
+
+## 妯″潡杈圭晫
+
+```mermaid
+flowchart LR
+ MessageWnd["UI-thread hidden HWND"]
+ Runtime["IDesktopRuntime"]
+ Session["WidgetSessionOverlay"]
+ Surfaces["RuntimeSurfaceController / WidgetWindow"]
+ Config["hotkeys.json"]
+ Layout["layout.json"]
+ UI["Tray / Management / Local API"]
+
+ MessageWnd -->|"HotkeyPressed"| Runtime
+ UI --> Runtime
+ Runtime --> Session
+ Runtime --> Surfaces
+ Runtime --> Config
+ Surfaces -.->|"涓嶅啓"| Layout
+```
+
+- 蹇嵎閿懡浠や笌鎵樼洏銆佺鐞嗙獥鍙c�佹湰鍦� API 涓�鏍凤紝鍙繘鍏� `IDesktopRuntime`銆�
+- `IRuntimeEventBus` 鍙仛浜嬪悗閫氱煡锛屼笉褰撳懡浠ゆ�荤嚎銆�
+- `HotkeyService` 鍙礋璐� `RegisterHotKey` / `UnregisterHotKey` 鍜� `WM_HOTKEY` 娑堟伅绐楀彛锛屼笉瑙f瀽涓氬姟鍔ㄤ綔銆�
+- 鎻掍欢涓嶅紑鏀� `RegisterHotKey`锛屼篃涓嶄娇鐢� `WH_KEYBOARD_LL`銆�
+
+## 鎸佷箙鍖栧垎灞�
+
+| 鐘舵�� | 瀛樺偍 | 杩涚▼閲嶅惎 |
+| --- | --- | --- |
+| 蹇嵎閿粦瀹� | `%AppData%\DesktopEnhancer\config\hotkeys.json` | 淇濈暀 |
+| 浼氳瘽鍙氦浜� / 浼氳瘽鏄鹃殣 | 鍐呭瓨 `WidgetSessionOverlay` | 涓㈠純锛屽洖鍒扮┖闂茬┛閫� |
+| 甯冨眬鐐瑰嚮绌块�� / 鍙鎬� | `layout.json` | 淇濈暀 |
+
+## 鏈夋晥绌块�忓叕寮�
+
+1. `EditMode` 鎴� `SafeInputMode` 鈫� 寮哄埗鍙偣锛坄clickThrough = false`锛�
+2. 鍚﹀垯鑻ヨ瀹炰緥瀛樺湪浼氳瘽瑕嗙洊 鈫� `clickThrough = !Interactable`
+3. 鍚﹀垯 鈫� `layout.ClickThrough`
+
+鏈夊惎鐢ㄧ殑 `widget.toggleInteractable` 缁戝畾鏃讹紝鐩爣瀹炰緥鍚姩鍗冲啓鍏ヤ細璇濊鐩� `Interactable = false`锛屽洜姝ゅ嵆浣� `layout.clickThrough = false` 涔熶細绌洪棽绌块�忋�傜鐞嗙獥鍙f垨鏈湴 API 鏄惧紡鏀� `layout.ClickThrough` 鏃讹紝浼氭妸浼氳瘽瑕嗙洊鍚屾涓� `Interactable = !clickThrough`锛岃绐楀彛绔嬪埢鍙偣鎴栫┛閫忋��
+
+`HotkeyService` 蹇呴』鍦� WPF UI 绾跨▼鍒涘缓闅愯棌椤跺眰绐楀彛骞惰皟鐢� `RegisterHotKey`銆俙HWND_MESSAGE` 鎴栫嚎绋嬫睜涓婄殑 `hwnd=0` 浼氫娇娉ㄥ唽鐪嬭捣鏉ユ垚鍔燂紝浣� `WM_HOTKEY` 姘歌繙杩涗笉浜嗘秷鎭惊鐜��
+
+## 榛樿缁戝畾
+
+- `Ctrl+Shift+K` 鈫� `widget.toggleInteractable` 鈫� `sample.llm-command-palette`
+- 鍚屼竴蹇嵎閿湪銆屽彲浜や簰銆嶄笌銆岀┖闂茬┛閫忋�嶄箣闂村垏鎹�
+- 澶辩劍涓嶉��鍑猴紝鍙兘鍐嶆寜涓�娆″揩鎹烽敭
+- 涓嶈浣跨敤 `Alt+Space` 浣滀负榛樿缁戝畾
+
+## 鍔ㄤ綔鐧藉悕鍗�
+
+- `widget.toggleInteractable`
+- `widget.toggleVisible`锛堜細璇濇樉闅愶紝涓嶅啓 `layout.json`锛�
+- `runtime.toggleEditMode`
+- `runtime.toggleSafeInputMode`
+
+## 闈炵洰鏍�
+
+- 鎻掍欢鑷娉ㄥ唽鍏ㄥ眬鐑敭
+- 閿洏閽╁瓙 / 缁勫悎閿簭鍒�
+- 澶辩劍鑷姩 dismiss
diff --git a/docs/architecture/llm-command-palette-architecture.md b/docs/architecture/llm-command-palette-architecture.md
index 2c8f425..d503ddb 100644
--- a/docs/architecture/llm-command-palette-architecture.md
+++ b/docs/architecture/llm-command-palette-architecture.md
@@ -10,13 +10,14 @@
- 鎻掍欢鍓嶇鍙礋璐h緭鍏ャ�佹ā鍨嬮�夋嫨鍜屾祦寮忔覆鏌撱��
- 鎻掍欢鍓嶇鍙紶 `mode`銆乣projectId`銆乣modelId`銆乣messages` 鍜岃姹傚弬鏁帮紝涓嶇洿鎺ヤ紶 provider銆乪ndpoint銆丄PI key銆丄iChat 瀵嗙爜鎴� Session Token銆�
-- 瀹夸富缁存姢 LLM 妯″瀷娉ㄥ唽琛紝姣忎釜妯″瀷鍙嫭绔嬮厤缃� `provider`銆乣endpoint`銆乣authRef` 鍜� `apiModel`銆�
-- 瀹夸富鎸� `modelId` 閫夋嫨 provider adapter锛屽苟鎶婁笉鍚屼緵搴斿晢鐨勬祦寮忓搷搴旂粺涓�杞崲鎴愭彃浠跺彲娑堣垂鐨勪簨浠躲��
+- 瀹夸富缁存姢 LLM 妯″瀷娉ㄥ唽琛紝姣忎釜妯″瀷鍙嫭绔嬮厤缃� `provider`銆乣baseUrl`銆乣authRef` 鍜� `apiModel`銆傛棫閰嶇疆涓殑 `endpoint`锛堝畬鏁� `/chat/completions` URL锛変細瑙勮寖鍖栦负 `baseUrl`銆�
+- 瀹夸富鎸� `modelId` 閫夋嫨 provider adapter锛屽苟鎶婁笉鍚屼緵搴斿晢鐨勬祦寮忓搷搴旂粺涓�杞崲鎴愭彃浠跺彲娑堣垂鐨勪簨浠躲�傝亰澶╄姹傚彂寰� `{baseUrl}/chat/completions`銆�
- API key 涓嶈繘鍏ユ彃浠跺墠绔祫婧愩�乵anifest 绀轰緥鎴栨櫘閫氭棩蹇椼��
- 鎻掍欢杩愯妯″紡鐢遍厤缃喅瀹氾細
- - `provider-direct`锛氭部鐢ㄥ綋鍓嶄緵搴斿晢鐩磋繛閾捐矾锛屽苟鍙皟鐢� AiChat 璁板繂鎺ュ彛绠$悊/鍙洖璁板繂銆�
- - `aichat-api`锛氶�氳繃鑷湁 AiChat API 鐧诲綍銆佽鍙栭」鐩�佸彂閫佽亰澶╁拰璁㈤槄 SSE锛涙彃浠朵晶涓嶅鐞嗚蹇嗐��
-- AiChat 缁熶竴 Host 榛樿鍥哄畾涓� `http://192.168.1.111:13000`锛屼笉浠� AiChat 鎺ュ彛鏂囨。鐨勭幆澧冭〃鎺ㄥ銆�
+ - `provider-direct`锛氭部鐢ㄥ綋鍓嶄緵搴斿晢鐩磋繛閾捐矾锛涗粎鍦ㄥ凡閰嶇疆 AiChat 璐﹀彿鏃惰皟鐢ㄨ蹇嗘帴鍙c��
+ - `aichat-api`锛氶�氳繃鑷湁 AiChat API 鐧诲綍銆佽鍙栭」鐩�佸彂閫佽亰澶╁拰璁㈤槄 SSE锛涙彃浠朵晶涓嶅鐞嗚蹇嗐�侫iChat 璐﹀彿涓庨」鐩潎涓哄彲閫夈��
+- 鎻愪緵鍟嗗彲閰嶇疆 `providers[]`锛屽涓绘寜 `GET {baseUrl}/models` 鎷夊彇妯″瀷鍒楄〃锛涜嚜瀹氫箟 `models[]` 浠嶅彲鎵嬪啓銆�
+- AiChat 缁熶竴 Host 榛樿鍥哄畾涓� `http://192.168.1.111:13000`锛屼粎鏈夐粯璁� `baseUrl` 涓嶇畻宸查厤缃紝涓嶄細鐧诲綍銆�
## Goals
@@ -126,19 +127,27 @@
Bridge->>Runtime: GetLlmModels(pluginId, instanceId)
Runtime->>Llm: GetAvailableModels(pluginId)
Llm->>Registry: Load enabled model summaries
+ Llm->>Llm: Merge custom models[] then providers[] catalogs
Registry-->>Llm: model id, label, provider, supportsStreaming
Llm-->>Runtime: safe model summaries
- Runtime-->>Bridge: summaries without endpoint/authRef
+ Runtime-->>Bridge: summaries without baseUrl/endpoint/authRef
Bridge-->>Plugin: Promise resolve
```
-鎻掍欢妯″瀷涓嬫媺鍙兘鎷垮埌瀹夊叏鎽樿锛�
+鎻掍欢妯″瀷涓嬫媺鍙兘鎷垮埌瀹夊叏鎽樿銆傚睍绀哄悕鐢卞涓绘牸寮忓寲锛�
```json
[
{
- "id": "gpt-5.4",
- "label": "GPT-5.4",
+ "id": "local-qwen",
+ "label": "qwen2.5:14b(Custom)",
+ "provider": "openai-compatible",
+ "supportsStreaming": true,
+ "enabled": true
+ },
+ {
+ "id": "provider:deepseek:deepseek-v4-flash",
+ "label": "deepseek-v4-flash(DeepSeek)",
"provider": "openai-compatible",
"supportsStreaming": true,
"enabled": true
@@ -146,15 +155,15 @@
]
```
-榛樿涓嶈繑鍥� `endpoint`銆乣authRef`銆丄PI key 鎴栧叾浠栨晱鎰熼厤缃�傜鐞嗙獥鍙e彲浠ュ湪鍙楁帶 UI 涓睍绀哄拰缂栬緫 endpoint锛屼絾鎻掍欢鍓嶇涓嶉渶瑕佺煡閬撱��
+榛樿涓嶈繑鍥� `baseUrl`銆乣endpoint`銆乣authRef`銆丄PI key 鎴栧叾浠栨晱鎰熼厤缃�俙providers[]` 涓竴瀹跺け璐ヤ笉褰卞搷鑷畾涔夋ā鍨嬪拰鍏朵粬鎻愪緵鍟嗐��
-`aichat-api` 妯″紡涓嬫ā鍨嬪垪琛ㄦ潵鑷� AiChat `GET /api/chat/models`锛岃繑鍥炲悓鏍风殑瀹夊叏鎽樿缁撴瀯锛�
+`aichat-api` 妯″紡涓嬫ā鍨嬪垪琛ㄦ潵鑷� AiChat `GET /api/chat/models`锛屽睍绀� `{id}(AiChat)`锛涙湭閰嶇疆璐﹀彿鏃朵笉鐧诲綍锛岃繑鍥炵┖鍒楄〃锛�
```json
[
{
"id": "deepseek-v4-flash",
- "label": "deepseek-v4-flash",
+ "label": "deepseek-v4-flash(AiChat)",
"provider": "aichat",
"supportsStreaming": true,
"enabled": true
@@ -175,7 +184,7 @@
Plugin->>Bridge: getProjects()
Bridge->>Runtime: GetAiChatProjects(pluginId, instanceId)
- Runtime->>AiChat: GetProjectsAsync()
+ Runtime->>AiChat: GetProjectsAsync() only when email is configured
AiChat->>Session: EnsureSessionAsync()
Session->>Session: Resolve passwordEnv before password
Session->>Api: POST /api/auth/login
@@ -183,9 +192,19 @@
AiChat->>Api: GET /api/projects with x-session-token
Api-->>AiChat: projects
AiChat-->>Runtime: safe project summaries
- Runtime-->>Bridge: project summaries
+ Runtime-->>Bridge: { status, message, projects }
Bridge-->>Plugin: Promise resolve
```
+
+`llm.getProjects` 鎴愬姛杩斿洖鐘舵�佸寘锛岃�屼笉鏄妸鏈厤缃�/鐧诲綍澶辫触褰撴垚妗ユ帴閿欒锛�
+
+| `status` | 鍓嶇灞曠ず | 鏄惁鐧诲綍 |
+| --- | --- | --- |
+| `not-configured` | `Not configured` | 鍚︼紱浠呮湁榛樿 `baseUrl` 涓嶇畻宸查厤缃� |
+| `not-connected` | `Not connected`锛宼ooltip 涓哄師鍥� | 宸插皾璇曠櫥褰曚絾澶辫触 |
+| `ready` | 鐪熷疄椤圭洰鍚� | 鏄紱涓嶈嚜鍔ㄩ�夌涓�椤癸紝浠呭綋 `defaultProjectId` 浠嶅湪鍒楄〃涓墠閫変腑 |
+
+鏈厤缃� AiChat 鏃朵笉鎻愪緵闀挎湡璁板繂锛歚canUseMemory` / `canViewMemory` / `canManageMemory` 鍏ㄤ负 false锛屼笖涓嶈皟鐢ㄨ蹇嗘煡璇�/鍒涘缓/鍒犻櫎/鍙洖銆俙provider-direct` 浠嶅彲鎸夋墍閫夋ā鍨嬬洿杩炴彁闂��
椤圭洰鎽樿寤鸿鍙繑鍥炴彃浠� UI 闇�瑕佺殑瀛楁锛�
@@ -218,7 +237,7 @@
Runtime->>Runtime: Validate plugin permission llm.stream
Runtime->>Llm: StreamChatAsync(request)
Llm->>Registry: Get model by modelId when provider-direct
- Registry-->>Llm: provider, endpoint, authRef, apiModel
+ Registry-->>Llm: provider, baseUrl, authRef, apiModel
Llm->>Secret: Resolve authRef
Secret-->>Llm: credential or null
Llm->>Adapter: StreamAsync(normalized request)
@@ -335,7 +354,7 @@
"id": "gpt-5.4",
"label": "GPT-5.4",
"provider": "openai-compatible",
- "endpoint": "https://api.openai.example/v1/chat/completions",
+ "baseUrl": "https://api.openai.example/v1",
"authRef": "llm.openai.primary",
"apiModel": "gpt-5.4",
"supportsStreaming": true,
@@ -350,7 +369,7 @@
"id": "deepseek-chat",
"label": "DeepSeek",
"provider": "deepseek",
- "endpoint": "https://api.deepseek.com/chat/completions",
+ "baseUrl": "https://api.deepseek.com",
"authRef": "llm.deepseek.primary",
"apiModel": "deepseek-chat",
"supportsStreaming": true,
@@ -365,7 +384,7 @@
"id": "local-qwen",
"label": "Local Qwen",
"provider": "openai-compatible",
- "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
+ "baseUrl": "http://127.0.0.1:11434/v1",
"authRef": null,
"apiModel": "qwen2.5:14b",
"supportsStreaming": true,
@@ -391,17 +410,38 @@
"aichat": {
"baseUrl": "http://192.168.1.111:13000",
"account": {
- "email": "user@example.com",
+ "email": null,
"password": null,
"passwordEnv": "MOLI_AICHAT_PASSWORD"
},
- "defaultProjectId": "",
+ "defaultProjectId": null,
"memory": {
"enabledInProviderDirect": true,
"defaultScope": "PROJECT",
"recallLimit": 8
}
- }
+ },
+ "providers": [
+ {
+ "id": "deepseek",
+ "label": "DeepSeek",
+ "baseUrl": "https://api.deepseek.com",
+ "authRef": "llm_deepseek_api_key",
+ "enabled": true
+ }
+ ],
+ "models": [
+ {
+ "id": "local-qwen",
+ "label": "qwen2.5:14b",
+ "provider": "openai-compatible",
+ "baseUrl": "http://127.0.0.1:11434/v1",
+ "authRef": null,
+ "apiModel": "qwen2.5:14b",
+ "supportsStreaming": true,
+ "enabled": true
+ }
+ ]
}
```
@@ -411,11 +451,16 @@
| --- | --- |
| `mode` | `provider-direct` 鎴� `aichat-api`锛岀己澶辨椂榛樿涓� `provider-direct` |
| `aichat.baseUrl` | `http` 鎴� `https` 缁濆 URL锛岄粯璁� `http://192.168.1.111:13000` |
-| `aichat.account.email` | 鍙负绌猴紱璋冪敤 AiChat API 鍓嶅繀椤诲瓨鍦� |
+| `aichat.account.email` | 鍙负绌猴紱闈炵┖鎵嶈涓哄凡閰嶇疆 AiChat锛屾墠浼氱櫥褰� |
| `aichat.account.passwordEnv` | 鍙负绌猴紱瀛樺湪鏃朵紭鍏堣鍙栫幆澧冨彉閲� |
| `aichat.account.password` | 鍙负绌猴紱鍙綔涓烘湰鍦版祴璇� fallback |
-| `aichat.defaultProjectId` | 鍙负绌猴紱涓嶄负绌烘椂搴斿瓨鍦ㄤ簬椤圭洰鍒楄〃 |
+| `aichat.defaultProjectId` | 鍙负绌猴紱涓嶄负绌轰笖浠嶅湪椤圭洰鍒楄〃涓墠榛樿閫変腑 |
| `aichat.memory.recallLimit` | `1..20` |
+| `providers[].id` | 鎻愪緵鍟� id锛岀敤浜� `provider:{id}:{apiModel}` |
+| `providers[].label` | 涓嬫媺灞曠ず `apiModel(label)` |
+| `providers[].baseUrl` | OpenAI-compatible 鏍瑰湴鍧�锛涜亰澶╄蛋 `{baseUrl}/chat/completions`锛屾媺妯″瀷璧� `{baseUrl}/models` |
+| `providers[].authRef` | 鍙负绌� |
+| `models[].baseUrl` | 鑷畾涔夋ā鍨嬫牴鍦板潃锛涙棫 `endpoint` 鑻ヤ互 `/chat/completions` 缁撳熬浼氳鑼冨寲涓� `baseUrl` |
瀵嗙爜瑙f瀽椤哄簭锛�
@@ -434,7 +479,7 @@
| `models[].id` | 鍏ㄥ眬鍞竴锛屾帹鑽� `provider-name` 鎴栫敤鎴峰彲璇� id |
| `models[].label` | 1 鍒� 40 瀛楃锛屼緵涓嬫媺灞曠ず |
| `models[].provider` | 蹇呴』瀛樺湪瀵瑰簲 adapter |
-| `models[].endpoint` | 蹇呴』鏄� `http` 鎴� `https` 缁濆 URL |
+| `models[].baseUrl` | 蹇呴』鏄� `http` 鎴� `https` 缁濆 URL锛涙棫 `endpoint` 鍏煎 |
| `models[].authRef` | 鍙负绌猴紱涓嶄负绌烘椂涓嶅緱鍖呭惈鏄庢枃 key |
| `models[].apiModel` | 蹇呭~锛屽彂閫佺粰涓婃父渚涘簲鍟嗙殑鐪熷疄妯″瀷鍚� |
| `models[].timeoutMs` | 寤鸿 `5000..300000` |
diff --git a/docs/data/configuration-and-storage.md b/docs/data/configuration-and-storage.md
index 16476cc..be15b85 100644
--- a/docs/data/configuration-and-storage.md
+++ b/docs/data/configuration-and-storage.md
@@ -24,13 +24,14 @@
## 閰嶇疆鏂囦欢
-MVP 鏈湴閰嶇疆鍖呭惈 3 涓� JSON 鏂囦欢銆�
+MVP 鏈湴閰嶇疆鍖呭惈 4 涓� JSON 鏂囦欢銆�
| 鏂囦欢 | 璐熻矗鍐呭 | 榛樿琛屼负 |
| --- | --- | --- |
| `appsettings.json` | 鍚姩椤广�丄PI 绔彛銆佽繍琛屾ā寮忔寔涔呯姸鎬� | 缂哄け鏃剁敓鎴愰粯璁ゅ�� |
| `plugins.json` | 鎻掍欢鍚敤/绂佺敤鐘舵�佹敞鍐岃〃 | 缂哄け鏃剁敓鎴愮┖鍒楄〃锛屽苟鐢遍粯璁ゅ唴瀹瑰畨瑁呭櫒琛ユ牱渚嬫彃浠� |
| `layout.json` | 鏄剧ず鍣ㄥ揩鐓у拰 widget 瀹炰緥甯冨眬 | 缂哄け鏃剁敓鎴愮┖甯冨眬锛屽苟鐢遍粯璁ゅ唴瀹瑰畨瑁呭櫒琛ユ牱渚� widget |
+| `hotkeys.json` | 鍏ㄥ眬蹇嵎閿粦瀹� | 缂哄け鏃剁敓鎴愬甫榛樿 `Ctrl+Shift+K` 缁戝畾鐨勬枃妗� |
鎵�鏈夐厤缃枃妗e寘鍚� `schemaVersion`锛屽綋鍓嶇増鏈负 `1`銆�
@@ -223,3 +224,38 @@
- `schemaVersion` 浣滀负鍗囩骇鍏ュ彛銆�
- 鎻掍欢 manifest 涓庣敤鎴峰竷灞�鍒嗙锛岄伩鍏嶆彃浠跺崌绾ц鐩栫敤鎴峰竷灞�銆�
- API 鍜� UI 閫氳繃 `IDesktopRuntime` 淇敼鐘舵�侊紝涓嶇洿鎺ュ啓閰嶇疆鏂囦欢銆�
+
+## hotkeys.json
+
+```json
+{
+ "schemaVersion": 1,
+ "bindings": [
+ {
+ "id": "llm-palette-toggle-interactable",
+ "keys": "Ctrl+Shift+K",
+ "action": "widget.toggleInteractable",
+ "target": {
+ "pluginId": "sample.llm-command-palette"
+ },
+ "enabled": true,
+ "source": "builtin"
+ }
+ ]
+}
+```
+
+瀛楁璇存槑锛�
+
+| 瀛楁 | 绫诲瀷 | 璇存槑 |
+| --- | --- | --- |
+| `id` | string | 缁戝畾鏍囪瘑銆傚唴缃� id 涓� `llm-palette-toggle-interactable` |
+| `keys` | string | 缁勫悎閿紝渚嬪 `Ctrl+Shift+K` |
+| `action` | string | 鐧藉悕鍗曞姩浣� |
+| `target.pluginId` | string | 鐩爣鎻掍欢銆傚懡涓鎻掍欢鍏ㄩ儴瀹炰緥 |
+| `target.instanceId` | string | 鍙�夛紝鏀剁獎鍒板崟涓疄渚� |
+| `enabled` | boolean | 鏄惁鍚敤 |
+| `source` | `builtin` 鎴� `user` | 鍐呯疆缁戝畾鍙敼閿�/绂佺敤銆佷笉鍙垹 |
+
+浼氳瘽鍙氦浜掑拰浼氳瘽鏄鹃殣涓嶅啓鍏� `layout.json`銆�
+
diff --git a/docs/ops/user-manual/moli-desktop.md b/docs/ops/user-manual/moli-desktop.md
index d7951e4..a4ec9df 100644
--- a/docs/ops/user-manual/moli-desktop.md
+++ b/docs/ops/user-manual/moli-desktop.md
@@ -111,11 +111,31 @@
| --- | --- |
| 鐘舵�� | 杩愯妯″紡銆丄PI 鐘舵�併�佸绾哥姸鎬併�乄ebView2 鍒濆鍖栫姸鎬佸拰鏈�杩戣瘖鏂� |
| 澹佺焊 | 褰撳墠澹佺焊鍚敤鐘舵�併�佹殏鍋滅姸鎬併�侀�忔槑搴︺�佺偣鍑荤┛閫忕姸鎬� |
-| 缁勪欢 | 灏忕粍浠跺疄渚嬪垪琛紝鍙�夋嫨缁勪欢骞舵樉绀�/闅愯棌鎴栭攣瀹�/瑙i攣 |
+| 缁勪欢 | 灏忕粍浠跺疄渚嬪垪琛紝鍙�夋嫨缁勪欢骞舵樉绀�/闅愯棌鎴栭攣瀹�/瑙i攣銆傚睍绀恒�屾湰娆′細璇濆彲浜や簰 / 鏈夋晥绌块�忋�嶏紱銆岀偣鍑荤┛閫忋�嶆寜鏈夋晥绌块�忓垏鎹紝鍐欏叆 `layout.json` 骞跺悓姝ヤ細璇濊鐩� |
+| 蹇嵎閿� | 绠$悊鍏ㄥ眬蹇嵎閿細鏀归敭銆佸惎鐢ㄣ�佹柊澧炪�佸垹闄ょ敤鎴风粦瀹氥�佹仮澶嶉粯璁ゃ�傚綍鍒舵椂浼氭殏鏃舵敞閿�宸叉敞鍐岀儹閿� |
| 鎻掍欢 | 宸叉壂鎻忔彃浠剁殑鍚嶇О銆佺被鍨嬨�佺姸鎬併�佸叆鍙e拰閿欒鐮� |
| 璇婃柇 | 璇婃柇璁板綍鍜屾彃浠� manifest 閿欒鎽樿 |
| Log | 鍔犺浇褰撳ぉ鏃ュ織锛屽苟闅忕鐞嗙獥鍙e埛鏂板懆鏈熸樉绀烘柊澧炴棩蹇� |
+## 鍏ㄥ眬蹇嵎閿�
+
+榛樿缁戝畾锛�
+
+| 蹇嵎閿� | 鍔ㄤ綔 | 鐩爣 |
+| --- | --- | --- |
+| `Ctrl+Shift+K` | 鍒囨崲浼氳瘽鍙氦浜� | `sample.llm-command-palette` |
+
+瑙勫垯锛�
+
+- 绌洪棽鎬侊細绐楀彛甯告樉锛岀偣鍑荤┛閫忥紝妗岄潰鍥炬爣鍙偣銆�
+- 鍐嶆寜涓�娆″悓涓�蹇嵎閿墠閫�鍑哄彲浜や簰锛涚偣鍑绘闈㈠け鐒︿笉浼氳嚜鍔ㄩ��鍑恒��
+- 鐑敭瀵艰嚧鐨勫彲浜や簰/浼氳瘽鏄鹃殣涓嶅啓 `layout.json`锛岄噸鍚悗鍥炲埌绌洪棽绌块�忋��
+- 缁戝畾鏈韩淇濆瓨鍦� `%AppData%\DesktopEnhancer\config\hotkeys.json`銆�
+- 绠$悊绐楀彛銆岀粍浠躲�嶉〉鐨勭偣鍑荤┛閫忔寜**鏈夋晥绌块��**鍒囨崲锛氬啓鍏� `layout.json`锛屽苟鍚屾鏈浼氳瘽瑕嗙洊锛岀獥鍙d細绔嬪埢鍙偣鎴栫┛閫忋��
+- 绯荤粺宸插崰鐢ㄧ殑缁勫悎閿細鍦ㄥ揩鎹烽敭鍒楄〃鏍囦负鍐茬獊锛涘綍鍒舵柊閿椂鍏堟殏鍋滃叏閮ㄧ儹閿紝閬垮厤鎶㈤敭銆�
+- 鍐呯疆缁戝畾鍙敼閿垨绂佺敤锛屼笉鑳藉垹闄わ紱銆屾仮澶嶉粯璁ゅ揩鎹烽敭銆嶅彧閲嶇疆鍐呯疆缁戝畾銆�
+- 涓嶈浣跨敤 `Alt+Space`銆傛彃浠朵笉鑳借嚜宸辨敞鍐屽叏灞�鐑敭銆�
+
## 閫氱敤缁勪欢鎿嶄綔
灏忕粍浠舵潵鑷湰鍦� HTML 鎻掍欢銆傛瘡涓皬缁勪欢閮藉彲浠ラ�氳繃绠$悊绐楀彛杩涜鏄剧ず銆侀殣钘忋�侀攣瀹氬拰瑙i攣銆�
diff --git a/docs/ops/user-manual/plugins/sample.llm-command-palette.md b/docs/ops/user-manual/plugins/sample.llm-command-palette.md
index 69182c5..6c18598 100644
--- a/docs/ops/user-manual/plugins/sample.llm-command-palette.md
+++ b/docs/ops/user-manual/plugins/sample.llm-command-palette.md
@@ -35,6 +35,19 @@
| 鎹㈣鏂瑰紡 | Shift+Enter |
| 杈撳嚭鍖哄煙 | 杈撳叆妗嗗簳閮ㄥ睍寮�锛屾渶澶ч珮搴︾害涓哄睆骞曢珮搴� `50%` |
+## 鍏ㄥ眬蹇嵎閿笌鑱氱劍
+
+瀹夸富榛樿鐢� `Ctrl+Shift+K` 鍒囨崲鏈彃浠剁殑浼氳瘽鍙氦浜掞紝涓嶅啓 `layout.json`銆�
+
+| 鐘舵�� | 琛屼负 |
+| --- | --- |
+| 绌洪棽绌块�� | 杈撳叆鏉″父鏄撅紝榧犳爣鐐瑰嚮浼氱┛杩囩獥鍙o紝妗岄潰鍥炬爣鍙偣 |
+| 鍙氦浜� | 绐楀彛鍙偣锛岃緭鍏ユ鑷姩鑾峰緱鐒︾偣锛屽彲鐩存帴鎵撳瓧骞� Enter 鎻愪氦 |
+| 鍐嶆寜涓�娆� | 鎭㈠绌洪棽绌块�忥紱澶辩劍涓嶄細鑷姩閫�鍑� |
+| 杩涚▼閲嶅惎 | 鍥炲埌绌洪棽绌块�� |
+
+鎻掍欢鏈韩涓嶆敞鍐屽叏灞�鐑敭鎴栭敭鐩橀挬瀛愶紝鍙洃鍚涓讳笅鍙戠殑 `moli:interactable-changed`銆備笉瑕佺敤 `requestShow` / `requestHide` 鍏呭綋鏄鹃殣銆傛敼閿浣跨敤绠$悊绐楀彛銆屽揩鎹烽敭銆嶉〉銆�
+
## 閫夋嫨杩愯妯″紡
LLM 鎻掍欢鏀寔涓ょ妯″紡锛�
@@ -72,6 +85,8 @@
AiChat 璐﹀彿淇℃伅鍙敤浜庢彃浠朵笌 AiChat 鏈嶅姟浜や簰銆�
+鏍蜂緥榛樿涓嶉濉� AiChat 璐﹀彿銆傚彧淇濈暀榛樿 `baseUrl` 鏃讹紝椤圭洰涓嬫媺鏄剧ず `Not configured`锛岃蹇嗕笉鍙敤锛屼絾鎻愪緵鍟嗙洿杩炰粛鍙彁闂��
+
璐﹀彿鍏佽鐩存帴鍐欏湪閰嶇疆涓細
```json
@@ -94,7 +109,7 @@
## 閰嶇疆妯″瀷
-LLM 鎻掍欢涓嶄細鐩存帴淇濆瓨渚涘簲鍟嗗瘑閽ワ紝涔熶笉浼氭妸 endpoint 鏆撮湶缁欐彃浠跺墠绔�傚涓讳細璇诲彇妯″瀷娉ㄥ唽琛紝鏍规嵁鐢ㄦ埛閫夋嫨鐨� `modelId` 璺敱鍒板搴斾緵搴斿晢鍜� endpoint銆�
+LLM 鎻掍欢涓嶄細鐩存帴淇濆瓨渚涘簲鍟嗗瘑閽ワ紝涔熶笉浼氭妸 `baseUrl` / `authRef` 鏆撮湶缁欐彃浠跺墠绔�傚涓昏鍙栨彃浠� `providers[]`銆佽嚜瀹氫箟 `models[]` 鎴� `llm-models.json`锛屾牴鎹敤鎴烽�夋嫨鐨� `modelId` 璺敱鍒板搴斾緵搴斿晢銆傝亰澶╄姹傚彂寰� `{baseUrl}/chat/completions`銆�
妯″瀷閰嶇疆鏂囦欢浣嶄簬锛�
@@ -109,28 +124,13 @@
```json
{
"schemaVersion": 1,
- "defaultModel": "deepseek-chat",
+ "defaultModel": "local-qwen",
"models": [
{
- "id": "deepseek-chat",
- "label": "DeepSeek",
- "provider": "deepseek",
- "endpoint": "https://api.deepseek.com/chat/completions",
- "authRef": "llm.deepseek.primary",
- "apiModel": "deepseek-chat",
- "supportsStreaming": true,
- "enabled": true,
- "requestDefaults": {
- "temperature": 0.7,
- "maxTokens": 2048,
- "timeoutMs": 60000
- }
- },
- {
"id": "local-qwen",
- "label": "Local Qwen",
+ "label": "qwen2.5:14b",
"provider": "openai-compatible",
- "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
+ "baseUrl": "http://127.0.0.1:11434/v1",
"authRef": null,
"apiModel": "qwen2.5:14b",
"supportsStreaming": true,
@@ -145,20 +145,60 @@
}
```
+鏃ч厤缃鏋滀粛鍐� `endpoint: https://api.example/v1/chat/completions`锛屽涓讳細鍘绘帀鏈熬 `/chat/completions` 褰撲綔 `baseUrl`銆�
+
+鏇村父瑙佺殑鍋氭硶鏄湪鎻掍欢 `plugin.json` 鐨� `config.providers` 涓厤缃彁渚涘晢锛岀敱瀹夸富璋冪敤 `GET {baseUrl}/models` 鎷夊彇鍒楄〃锛�
+
+```json
+{
+ "providers": [
+ {
+ "id": "deepseek",
+ "label": "DeepSeek",
+ "baseUrl": "https://api.deepseek.com",
+ "authRef": "llm_deepseek_api_key",
+ "enabled": true
+ },
+ {
+ "id": "kimi",
+ "label": "Kimi",
+ "baseUrl": "https://api.moonshot.cn/v1",
+ "authRef": "llm_kimi_api_key",
+ "enabled": true
+ },
+ {
+ "id": "bigmodel",
+ "label": "鏅鸿氨",
+ "baseUrl": "https://open.bigmodel.cn/api/paas/v4",
+ "authRef": "llm_bigmodel_api_key",
+ "enabled": true
+ },
+ {
+ "id": "qwen",
+ "label": "閫氫箟",
+ "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
+ "authRef": "llm_qwen_api_key",
+ "enabled": true
+ }
+ ],
+ "models": []
+}
+```
+
瀛楁璇存槑锛�
| 瀛楁 | 璇存槑 |
| --- | --- |
-| `id` | 鎻掍欢涓嬫媺鍜岃姹備娇鐢ㄧ殑妯″瀷 ID锛屽繀椤诲敮涓� |
-| `label` | 涓嬫媺涓樉绀虹殑鍚嶇О锛屽缓璁煭涓�鐐� |
-| `provider` | 渚涘簲鍟嗘垨鍗忚閫傞厤鍣紝渚嬪 `openai-compatible`銆乣deepseek`銆乣ollama` |
-| `endpoint` | 褰撳墠妯″瀷鑷繁鐨勮姹� URL锛屽彲姣忎釜妯″瀷涓嶅悓 |
+| `id` | 鎻掍欢涓嬫媺鍜岃姹備娇鐢ㄧ殑妯″瀷 ID锛屽繀椤诲敮涓�锛涙彁渚涘晢妯″瀷涓� `provider:{providerId}:{apiModel}` |
+| `label` | 鑷畾涔夋ā鍨嬬殑鏄剧ず鍚嶏紱涓嬫媺瀹為檯灞曠ず `{label}(Custom)` 鎴� `{apiModel}({provider.label})` |
+| `provider` | 渚涘簲鍟嗘垨鍗忚閫傞厤鍣紝渚嬪 `openai-compatible`銆乣deepseek` |
+| `baseUrl` | OpenAI-compatible 鏍瑰湴鍧�锛岃亰澶╄蛋 `{baseUrl}/chat/completions` |
| `authRef` | 瀵嗛挜寮曠敤锛屼笉鏄槑鏂囧瘑閽ワ紱鏈湴鏃犻壌鏉冩ā鍨嬪彲濉� `null` |
| `apiModel` | 鍙戦�佺粰涓婃父鎺ュ彛鐨勭湡瀹炴ā鍨嬪悕 |
| `supportsStreaming` | 鏄惁鏀寔娴佸紡杈撳嚭 |
| `enabled` | 鏄惁鏄剧ず鍦ㄦ彃浠舵ā鍨嬩笅鎷変腑 |
-褰撳墠 `deepseek`銆乣ollama` 鍜� `local-openai-compatible` 浼氬鐢� OpenAI-compatible 閫傞厤鍣ㄣ�傚鏋滄煇涓緵搴斿晢鎺ュ彛涓嶅吋瀹� OpenAI-compatible 娴佸紡鏍煎紡锛岄渶瑕佸悗缁柊澧炵嫭绔嬮�傞厤鍣ㄣ��
+褰撳墠 `deepseek`銆乣kimi`銆乣qwen`銆乣ollama` 绛変細澶嶇敤 OpenAI-compatible 閫傞厤鍣ㄣ�傚鏋滄煇涓緵搴斿晢鎺ュ彛涓嶅吋瀹� OpenAI-compatible 娴佸紡鏍煎紡锛岄渶瑕佸悗缁柊澧炵嫭绔嬮�傞厤鍣ㄣ��
鑷湁 API 妯″紡涓嬶紝妯″瀷鍒楄〃鏉ヨ嚜 AiChat锛�
@@ -166,7 +206,7 @@
GET /api/chat/models
```
-鎻掍欢鍙睍绀� AiChat 杩斿洖鐨勫彲鐢ㄦā鍨嬶紝骞跺湪鎻愪氦鏃舵妸鎵�閫夋ā鍨嬩綔涓� `modelName` 浼犵粰 AiChat銆�
+鎻掍欢鍙睍绀� AiChat 杩斿洖鐨勫彲鐢ㄦā鍨嬶紙`{id}(AiChat)`锛夛紝骞跺湪鎻愪氦鏃舵妸鎵�閫夋ā鍨嬩綔涓� `modelName` 浼犵粰 AiChat銆傛湭閰嶇疆 AiChat 璐﹀彿鏃朵笉浼氱櫥褰曘��
## 閰嶇疆瀵嗛挜
@@ -200,8 +240,8 @@
1. 鍚姩 Moli.Desktop銆�
2. 纭 `sample.llm-command-palette` 宸插湪鈥滄彃浠垛�濋〉闈腑鍚敤銆�
3. 鍦ㄦ闈㈤《閮ㄦ壘鍒板崐閫忔槑杈撳叆鏉°��
-4. 鍦ㄥ乏渚ч」鐩笅鎷変腑閫夋嫨 AiChat 椤圭洰銆�
-5. 鍦ㄥ彸渚фā鍨嬩笅鎷変腑閫夋嫨妯″瀷銆�
+4. 鍦ㄥ乏渚ч」鐩笅鎷変腑鏌ョ湅 AiChat 椤圭洰锛堝彲閫夛紝鏈厤缃篃鍙彁闂級銆�
+5. 鍦ㄥ彸渚фā鍨嬩笅鎷変腑閫夋嫨妯″瀷銆傚睍绀哄悕涓� `model(Provider)`銆乣model(Custom)` 鎴� `model(AiChat)`銆傚垪琛ㄨ秴杩� 20 鏉℃椂鍏堟樉绀� 20 鏉★紝婊氬姩鍚庡啀杩藉姞銆�
6. 杈撳叆闂銆�
7. 鎸� Enter 鎻愪氦銆�
8. 鍦ㄨ緭鍏ユ涓嬫柟鏌ョ湅娴佸紡杈撳嚭銆�
@@ -210,17 +250,18 @@
| 鐘舵�� | 鍚箟 |
| --- | --- |
-| 鏄剧ず椤圭洰鍚嶇О | 宸叉垚鍔熻皟鐢� AiChat `GET /api/projects` |
-| `No project` | 鏈厤缃� AiChat銆佺櫥褰曞け璐ユ垨椤圭洰鍒楄〃涓虹┖ |
-| 鐧诲綍/鏉冮檺閿欒 | 妫�鏌ヨ处鍙峰鎵圭姸鎬併�佸瘑鐮佺幆澧冨彉閲忓拰 AiChat 鏈嶅姟鍦板潃 |
+| 鏄剧ず椤圭洰鍚嶇О | 宸查厤缃处鍙蜂笖 `GET /api/projects` 鎴愬姛锛坄ready`锛� |
+| `Not configured` | 鏈厤缃� AiChat 璐﹀彿锛堜粎鏈夐粯璁� `baseUrl` 涓嶇畻宸查厤缃級锛屼笉浼氱櫥褰� |
+| `Not connected` | 宸查厤缃� email 浣嗙櫥褰曟垨鎷夊彇椤圭洰澶辫触锛宼ooltip 鍚師鍥� |
+| `No project` | 宸茶繛鎺ヤ絾椤圭洰鍒楄〃涓虹┖锛涘彲涓嶉�夐」鐩氨鎻愰棶 |
-鍦ㄨ嚜鏈� API 妯″紡涓嬶紝鎻愪氦浼氭惡甯﹀綋鍓嶉」鐩� ID銆傛湭閫夋嫨椤圭洰鏃讹紝AiChat 浼氭寜鑷韩鎺ュ彛瑙勫垯浣跨敤鎴栧垱寤洪粯璁ら」鐩紝浣嗗缓璁槑纭�夋嫨椤圭洰銆�
+鍦ㄨ嚜鏈� API 妯″紡涓嬶紝鎻愪氦浼氭惡甯﹀綋鍓嶉」鐩� ID锛堝彲绌猴級銆傛湭閫夋嫨椤圭洰鏃讹紝AiChat 浼氭寜鑷韩鎺ュ彛瑙勫垯澶勭悊銆傞」鐩笉鏄繀濉」銆�
椤圭洰鍜屾ā鍨嬩笅鎷変娇鐢ㄦ彃浠惰嚜缁樼殑鍦嗚鎵佸钩鎺т欢銆傚睍寮�涓嬫媺鏃讹紝杈撳叆鏉′細涓存椂璇锋眰瀹夸富澧為珮缁勪欢绐楀彛锛岄伩鍏嶉�夐」鍒楄〃琚師濮嬬粍浠堕珮搴﹁鍓紱閫夋嫨瀹屾垚鎴栫偣鍑诲閮ㄥ悗浼氭仮澶嶅埌榛樿楂樺害銆�
## 璁板繂绠$悊
-渚涘簲鍟嗙洿杩炴ā寮忎笅锛屾彃浠跺彲浠ヤ娇鐢� AiChat 璁板繂鎺ュ彛锛�
+渚涘簲鍟嗙洿杩炴ā寮忎笅锛�**浠呭湪宸查厤缃� AiChat 璐﹀彿**鏃跺彲浠ヤ娇鐢ㄨ蹇嗘帴鍙c�傛湭閰嶇疆鏃惰蹇嗘寜閽笉鍙敤锛屽涓讳笉浼氳皟鐢ㄨ蹇嗘煡璇�/鍒涘缓/鍒犻櫎/鍙洖銆�
| 鎿嶄綔 | AiChat 鎺ュ彛 |
| --- | --- |
@@ -277,16 +318,16 @@
- 妫�鏌� `%AppData%\DesktopEnhancer\config\llm-models.json` 鏄惁瀛樺湪銆�
- 纭鑷冲皯鏈変竴涓ā鍨嬬殑 `enabled` 涓� `true`銆�
-- 纭妯″瀷鐨� `endpoint` 鏄� `http` 鎴� `https` 缁濆 URL銆�
+- 纭妯″瀷鐨� `baseUrl` 鏄� `http` 鎴� `https` 缁濆 URL銆�
+- 濡傛灉浣跨敤 `providers[]`锛岀‘璁ゆ彁渚涘晢鍙闂� `{baseUrl}/models`銆�
- 濡傛灉褰撳墠鏄嚜鏈� API 妯″紡锛屾鏌� AiChat `GET /api/chat/models` 鏄惁鍙敤銆�
- 淇閰嶇疆鍚庨噸鍚簲鐢紝鎴栧湪绠$悊绐楀彛涓噸杞芥彃浠躲��
-### 椤圭洰涓嬫媺涓虹┖
+### 椤圭洰涓嬫媺涓� Not configured / Not connected
-- 妫�鏌� AiChat 鏈嶅姟鍦板潃鏄惁涓� `http://192.168.1.111:13000` 鎴栦綘鐨勫疄闄呴厤缃��
-- 妫�鏌ヨ处鍙峰拰瀵嗙爜鐜鍙橀噺鏄惁姝g‘銆�
-- 璋冪敤 AiChat `GET /api/auth/me` 纭璐﹀彿宸插鎵广��
-- 璋冪敤 AiChat `GET /api/projects` 纭璐﹀彿鏈夐」鐩��
+- `Not configured`锛氬湪鎻掍欢閰嶇疆涓~鍐欓潪绌虹殑 `aichat.account.email`銆備粎鏈夐粯璁� AiChat `baseUrl` 涓嶄細鐧诲綍銆�
+- `Not connected`锛氭鏌ヨ处鍙枫�佸瘑鐮佺幆澧冨彉閲忓拰 AiChat 鏈嶅姟鏄惁鍙揪锛泃ooltip 浼氭樉绀哄け璐ュ師鍥犮��
+- 杩欎袱绉嶇姸鎬佷笅閮藉彲浠ョ敤鎻愪緵鍟嗘垨鑷畾涔夋ā鍨嬬洿杩炴彁闂��
### 鑷湁 API 妯″紡鏃犳硶杈撳嚭
@@ -305,16 +346,17 @@
### 璇锋眰鎻愮ず endpoint 涓嶅彲杈�
-- 纭 `endpoint` 鍦板潃姝g‘銆�
+- 纭 `baseUrl` 姝g‘锛岃亰澶╁疄闄呰姹� `{baseUrl}/chat/completions`銆�
- 濡傛灉鏄湰鍦版ā鍨嬫湇鍔★紝纭鏈嶅姟宸插惎鍔ㄥ苟鐩戝惉瀵瑰簲绔彛銆�
- 濡傛灉鏄繙绋嬩緵搴斿晢锛岀‘璁ゅ綋鍓嶇綉缁滃彲璁块棶璇ヤ緵搴斿晢 API銆�
-- 妫�鏌ユ棩蹇楃洰褰� `%LocalAppData%\DesktopEnhancer\logs`锛屾棩蹇楀彧浼氳褰� endpoint host锛屼笉浼氳褰曞畬鏁� API key銆�
+- 妫�鏌ユ棩蹇楃洰褰� `%LocalAppData%\DesktopEnhancer\logs`锛屾棩蹇楀彧浼氳褰� host锛屼笉浼氳褰曞畬鏁� API key銆�
### 璁板繂鍔熻兘涓嶅彲鐢�
-- 璁板繂绠$悊鍙湪渚涘簲鍟嗙洿杩炴ā寮忎笅鐢辨彃浠跺鐞嗐��
+- 鏈厤缃� AiChat 璐﹀彿鏃惰蹇嗗叆鍙d笉鍙敤锛岃繖鏄鏈熻涓恒��
+- 璁板繂绠$悊鍙湪渚涘簲鍟嗙洿杩炴ā寮忎笖宸查厤缃� AiChat 鏃剁敱鎻掍欢澶勭悊銆�
- 妫�鏌� AiChat 褰撳墠鐢ㄦ埛鏄惁鏈� `canUseMemory`銆乣canViewMemory` 鎴� `canManageMemory` 鏉冮檺銆�
-- 椤圭洰璁板繂蹇呴』閫夋嫨椤圭洰鍚庝娇鐢ㄣ��
+- 鏈夐」鐩椂璁板繂璧� PROJECT锛屾棤椤圭洰鏃惰蛋 GLOBAL銆�
### 娌℃湁娴佸紡杈撳嚭
diff --git a/docs/product/llm-command-palette-plugin-prd.md b/docs/product/llm-command-palette-plugin-prd.md
index 1475a83..6426acc 100644
--- a/docs/product/llm-command-palette-plugin-prd.md
+++ b/docs/product/llm-command-palette-plugin-prd.md
@@ -188,20 +188,20 @@
## 妯″瀷閰嶇疆
-鎻掍欢閰嶇疆蹇呴』鏄惧紡鍖哄垎杩愯妯″紡銆傛彃浠跺墠绔彧闇�瑕佺煡閬撳彲灞曠ず鐨勯」鐩�佹ā鍨嬫竻鍗曞拰榛樿妯″瀷銆傚叿浣撲緵搴斿晢銆乪ndpoint銆侀壌鏉冩柟寮忋�丄iChat 鐧诲綍鎬佸拰璇锋眰閫傞厤搴斾紭鍏堢敱瀹夸富渚� LLM 浠g悊绠$悊锛屾彃浠舵彁浜ゆ椂鍙紶 `mode`銆乣projectId`銆乣modelId` 鍜屾秷鎭唴瀹广��
+鎻掍欢閰嶇疆蹇呴』鏄惧紡鍖哄垎杩愯妯″紡銆傛彃浠跺墠绔彧闇�瑕佺煡閬撳彲灞曠ず鐨勯」鐩�佹ā鍨嬫竻鍗曞拰榛樿妯″瀷銆傚叿浣撲緵搴斿晢銆乣baseUrl`銆侀壌鏉冩柟寮忋�丄iChat 鐧诲綍鎬佸拰璇锋眰閫傞厤搴斾紭鍏堢敱瀹夸富渚� LLM 浠g悊绠$悊锛屾彃浠舵彁浜ゆ椂鍙紶 `mode`銆乣projectId`銆乣modelId` 鍜屾秷鎭唴瀹广�俙projectId` 鍙┖銆�
### 杩愯妯″紡
| 妯″紡 | 閰嶇疆鍊� | 鑱婂ぉ鍏ュ彛 | 妯″瀷鏉ユ簮 | 璁板繂绠$悊 |
| --- | --- | --- | --- | --- |
-| 渚涘簲鍟嗙洿杩炴ā寮� | `provider-direct` | `window.moliDesktop.llm.streamChat` -> 渚涘簲鍟嗛�傞厤鍣� | `llm-models.json` 鎴栧涓绘ā鍨嬫敞鍐岃〃 | 閫氳繃 AiChat 璁板繂鎺ュ彛绠$悊鍜屽彫鍥� |
+| 渚涘簲鍟嗙洿杩炴ā寮� | `provider-direct` | `window.moliDesktop.llm.streamChat` -> 渚涘簲鍟嗛�傞厤鍣� | `providers[]` 鎷夋ā鍨嬨�佽嚜瀹氫箟 `models[]` 鎴� `llm-models.json` | 浠呭凡閰嶇疆 AiChat 鏃堕�氳繃璁板繂鎺ュ彛绠$悊鍜屽彫鍥� |
| 鑷湁 API 妯″紡 | `aichat-api` | AiChat `POST /api/chat/send` + SSE | AiChat `GET /api/chat/models` | 鎻掍欢鏃犻渶澶勭悊锛屼氦鐢� AiChat 鑱婂ぉ閾捐矾 |
妯″紡鍒囨崲瑙勫垯锛�
- 榛樿淇濇寔 `provider-direct`锛屼繚璇佺幇鏈夎涓轰笉琚牬鍧忋��
-- 鍒囨崲鍒� `aichat-api` 鍚庯紝鎻掍欢蹇呴』鍏堢櫥褰� AiChat 骞惰幏鍙栭」鐩垪琛ㄣ��
-- `aichat-api` 妯″紡涓嬫彁浜ゆ秷鎭椂搴斾紶鍏ュ綋鍓� `projectId`锛涘鏈�夐」鐩紝鍙敱 AiChat 鎸夋帴鍙h鍒欎娇鐢ㄦ垨鍒涘缓榛樿椤圭洰锛屼絾 UI 搴斿敖閲忛�夋嫨鏄庣‘椤圭洰銆�
+- 鍒囨崲鍒� `aichat-api` 鍚庯紝鑻ュ凡閰嶇疆璐﹀彿鍒欑櫥褰� AiChat 骞惰幏鍙栭」鐩垪琛紱鏈厤缃垯椤圭洰鏄剧ず `Not configured`锛屼笉鐧诲綍銆�
+- `aichat-api` 妯″紡涓嬫彁浜ゆ秷鎭椂搴斾紶鍏ュ綋鍓� `projectId`锛堝彲绌猴級锛涢」鐩笉鏄繀濉」銆�
- 涓ょ妯″紡閮戒笉寰楁妸瀵嗙爜銆丼ession Token銆佷緵搴斿晢 API key 鏆撮湶缁欐彃浠堕〉闈㈡棩蹇楁垨鍙鍒堕敊璇俊鎭��
### AiChat 鐢ㄦ埛閰嶇疆
@@ -250,7 +250,7 @@
4. 鍙�夎皟鐢� `GET /api/auth/me` 鏍¢獙瀹℃壒鐘舵�併�佽蹇嗘潈闄愬拰椤圭洰鏉冮檺銆�
5. Session 杩囨湡鎴栬繑鍥� `401` 鏃堕噸鏂扮櫥褰曚竴娆★紱浠嶅け璐ュ垯鍦ㄦ彃浠惰緭鍑哄尯灞曠ず鍙搷浣滈敊璇��
-鎺ㄨ崘閲囩敤鈥滄寜妯″瀷璺敱鈥濈殑閰嶇疆缁撴瀯锛氭瘡涓ā鍨嬮兘鍙互缁戝畾鐙珛 provider銆乁RL銆侀壌鏉冨紩鐢ㄥ拰璇锋眰閫傞厤鍙傛暟銆傝繖鏍峰悓涓�涓彃浠跺彲浠ュ悓鏃舵帴鍏ヤ笉鍚屼緵搴斿晢锛屼篃鍙互鎺ュ叆鍚屼竴渚涘簲鍟嗙殑涓嶅悓 base URL銆�
+鎺ㄨ崘閲囩敤鈥滄寜妯″瀷璺敱鈥濈殑閰嶇疆缁撴瀯锛氭瘡涓嚜瀹氫箟妯″瀷閮藉彲浠ョ粦瀹氱嫭绔� provider銆乣baseUrl`銆侀壌鏉冨紩鐢ㄥ拰璇锋眰閫傞厤鍙傛暟銆傛彁渚涘晢鐢� `providers[]` 閰嶇疆 `baseUrl`锛岀敱瀹夸富 `GET {baseUrl}/models` 鎷夊垪琛ㄣ�傛棫 `endpoint` 瀹屾暣 chat URL 浠嶅吋瀹广��
```json
{
@@ -260,7 +260,7 @@
"id": "gpt-5.4",
"label": "GPT-5.4",
"provider": "openai-compatible",
- "endpoint": "https://api.openai.example/v1/chat/completions",
+ "baseUrl": "https://api.openai.example/v1",
"authRef": "llm.openai.primary",
"apiModel": "gpt-5.4",
"supportsStreaming": true,
@@ -270,7 +270,7 @@
"id": "deepseek-chat",
"label": "DeepSeek",
"provider": "deepseek",
- "endpoint": "https://api.deepseek.com/chat/completions",
+ "baseUrl": "https://api.deepseek.com",
"authRef": "llm.deepseek.primary",
"apiModel": "deepseek-chat",
"supportsStreaming": true,
@@ -280,7 +280,7 @@
"id": "local-qwen",
"label": "Local Qwen",
"provider": "openai-compatible",
- "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
+ "baseUrl": "http://127.0.0.1:11434/v1",
"authRef": null,
"apiModel": "qwen2.5:14b",
"supportsStreaming": true,
@@ -302,13 +302,13 @@
| `id` | 鎻掍欢 UI 鍜岃姹備腑浣跨敤鐨勭ǔ瀹氭ā鍨� id銆� |
| `label` | 涓嬫媺涓睍绀虹殑鐭悕绉般�� |
| `provider` | 渚涘簲鍟嗘垨鍗忚閫傞厤鍣紝渚嬪 `openai-compatible`銆乣deepseek`銆乣anthropic`銆乣ollama`銆� |
-| `endpoint` | 褰撳墠妯″瀷浣跨敤鐨勫畬鏁磋姹� URL锛屽厑璁告瘡涓ā鍨嬩笉鍚屻�� |
+| `baseUrl` | OpenAI-compatible 鏍瑰湴鍧�锛涜亰澶╄姹� `{baseUrl}/chat/completions`銆傛棫 `endpoint` 瀹屾暣璺緞浠嶅吋瀹广�� |
| `authRef` | 瀹夸富渚у瘑閽ュ紩鐢紝涓嶆槸鏄庢枃瀵嗛挜锛涙湰鍦版棤閴存潈妯″瀷鍙负 `null`銆� |
| `apiModel` | 鍙戦�佺粰涓婃父 API 鐨勭湡瀹炴ā鍨嬪悕銆� |
| `supportsStreaming` | 鏄惁鍏佽娴佸紡杈撳嚭锛涗笉鏀寔鏃跺涓诲彲闄嶇骇涓轰竴娆℃�ц繑鍥炪�� |
| `enabled` | 鏄惁鍦ㄦ彃浠舵ā鍨嬩笅鎷変腑鏄剧ず銆� |
-API key 涓嶅簲瀛樻斁鍦ㄥ墠绔� `index.html` 鎴栧叕寮�閰嶇疆涓�侻VP 寤鸿鐢卞涓绘彁渚涙湰鍦� LLM 浠g悊鑳藉姏锛屾彃浠跺彧鍚戝涓昏姹傛祦寮忕敓鎴愶紱瀹夸富鍐嶆牴鎹� `modelId` 鎵惧埌 provider銆乪ndpoint銆乤uthRef 鍜� apiModel 骞惰皟鐢ㄥ搴斾緵搴斿晢銆傚鏋滅煭鏈熺洿鎺ヤ粠鎻掍欢璋冪敤杩滅▼ endpoint锛屽垯蹇呴』鍦ㄦ枃妗e拰绠$悊鐣岄潰涓槑纭彁绀哄瘑閽ユ毚闇查闄╋紝骞朵粎鐢ㄤ簬鏈湴涓汉娴嬭瘯銆�
+API key 涓嶅簲瀛樻斁鍦ㄥ墠绔� `index.html` 鎴栧叕寮�閰嶇疆涓�侻VP 寤鸿鐢卞涓绘彁渚涙湰鍦� LLM 浠g悊鑳藉姏锛屾彃浠跺彧鍚戝涓昏姹傛祦寮忕敓鎴愶紱瀹夸富鍐嶆牴鎹� `modelId` 鎵惧埌 provider銆乣baseUrl`銆乤uthRef 鍜� apiModel 骞惰皟鐢ㄥ搴斾緵搴斿晢銆傚鏋滅煭鏈熺洿鎺ヤ粠鎻掍欢璋冪敤杩滅▼鎺ュ彛锛屽垯蹇呴』鍦ㄦ枃妗e拰绠$悊鐣岄潰涓槑纭彁绀哄瘑閽ユ毚闇查闄╋紝骞朵粎鐢ㄤ簬鏈湴涓汉娴嬭瘯銆�
### 璺敱绛栫暐
@@ -318,7 +318,7 @@
2. 瀹夸富璇诲彇 LLM 妯″瀷娉ㄥ唽琛ㄣ��
3. 瀹夸富鎸� `modelId` 鎵惧埌瀵瑰簲妯″瀷閰嶇疆銆�
4. 瀹夸富鎸� `provider` 閫夋嫨閫傞厤鍣ㄣ��
-5. 閫傞厤鍣ㄦ寜璇ユā鍨嬬殑 `endpoint`銆乣authRef`銆乣apiModel` 鍙戣捣璇锋眰銆�
+5. 閫傞厤鍣ㄦ寜璇ユā鍨嬬殑 `baseUrl`銆乣authRef`銆乣apiModel` 鍙戣捣 `{baseUrl}/chat/completions` 璇锋眰銆�
6. 瀹夸富鎶婁緵搴斿晢娴佸紡鍝嶅簲缁熶竴杞崲涓� `llm.delta`銆乣llm.completed`銆乣llm.error` 浜嬩欢銆�
杩欑璁捐姣旀彃浠剁鐩存帴鎸変緵搴斿晢鍐欏濂楄姹傛洿绋筹細妯″瀷鍙嫭绔嬮厤缃� URL锛屽瘑閽ョ暀鍦ㄥ涓讳晶锛屾彃浠� UI 鍙叧蹇冣�滅敤鎴烽�変簡鍝釜妯″瀷鈥濄��
@@ -342,7 +342,7 @@
});
```
-鎻掍欢涓嶅簲鐩存帴浼� provider銆乪ndpoint 鎴栧瘑閽ャ�傚涓诲搷搴斾腑鍙繑鍥炴湰娆¤姹傚疄闄呭懡涓殑渚涘簲鍟嗗拰妯″瀷锛岀敤浜庤瘖鏂拰 UI tooltip锛屼絾涓嶈繑鍥炲瘑閽ャ��
+鎻掍欢涓嶅簲鐩存帴浼� provider銆乣baseUrl` 鎴栧瘑閽ャ�傚涓诲搷搴斾腑鍙繑鍥炴湰娆¤姹傚疄闄呭懡涓殑渚涘簲鍟嗗拰妯″瀷锛岀敤浜庤瘖鏂拰 UI tooltip锛屼絾涓嶈繑鍥炲瘑閽ャ��
鏂板 AiChat 鐩稿叧妗ユ帴鑳藉姏寤鸿锛�
@@ -484,17 +484,17 @@
### FR-LLM-08 AiChat 椤圭洰涓嬫媺
- 杈撳叆妗嗗乏渚у繀椤绘彁渚� AiChat 椤圭洰涓嬫媺鍒楄〃銆�
-- 椤圭洰鍒楄〃蹇呴』璋冪敤 AiChat `GET /api/projects` 鑾峰彇銆�
-- 鐧诲綍澶辫触銆佽处鍙锋湭瀹℃壒銆佹棤鏉冮檺鎴栨帴鍙d笉鍙揪鏃讹紝椤圭洰涓嬫媺蹇呴』灞曠ず鍙悊瑙i檷绾х姸鎬併��
-- 鑷湁 API 妯″紡涓嬫彁浜よ亰澶╂椂蹇呴』浣跨敤褰撳墠閫変腑椤圭洰锛涙湭閫夐」鐩椂鍏佽鎸� AiChat 榛樿椤圭洰瑙勫垯闄嶇骇銆�
+- 椤圭洰鍒楄〃蹇呴』璋冪敤 AiChat `GET /api/projects` 鑾峰彇锛涙湭閰嶇疆璐﹀彿鏃惰繑鍥� `not-configured`锛屼笉寰楃櫥褰曘��
+- 鐧诲綍澶辫触銆佽处鍙锋湭瀹℃壒銆佹棤鏉冮檺鎴栨帴鍙d笉鍙揪鏃讹紝椤圭洰涓嬫媺蹇呴』灞曠ず `Not connected` 鍙婂師鍥犮��
+- 鑷湁 API 妯″紡涓嬫彁浜よ亰澶╂椂浣跨敤褰撳墠閫変腑椤圭洰锛宍projectId` 鍙┖銆�
- 渚涘簲鍟嗙洿杩炴ā寮忎笅锛岄」鐩�夋嫨鐢ㄤ簬璁板繂绠$悊鍜屽彫鍥炰笂涓嬫枃锛屼笉寰楀己鍒堕樆濉炵洿杩炶亰澶┿��
浼樺厛绾э細P1
### FR-LLM-09 AiChat 鐢ㄦ埛閰嶇疆
-- 鎻掍欢閰嶇疆蹇呴』鍖呭惈 AiChat `baseUrl`銆佽处鍙峰拰瀵嗙爜寮曠敤銆�
-- `baseUrl` 榛樿鍊间负 `http://192.168.1.111:13000`銆�
+- 鎻掍欢閰嶇疆鍙寘鍚� AiChat `baseUrl`銆佽处鍙峰拰瀵嗙爜寮曠敤锛涜处鍙峰彲绌恒��
+- `baseUrl` 榛樿鍊间负 `http://192.168.1.111:13000`銆備粎鏈夐粯璁� `baseUrl` 涓嶇畻宸查厤缃紝涓嶅緱鐧诲綍銆�
- 璐﹀彿鍏佽鏄庢枃閰嶇疆銆�
- 瀵嗙爜蹇呴』鏀寔鐜鍙橀噺寮曠敤锛屼笖鐜鍙橀噺鍊间紭鍏堜簬鏄庢枃瀛楁銆�
- 鐧诲綍鎴愬姛鍚庣殑 `sessionToken` 蹇呴』鍙繚瀛樺湪瀹夸富杩愯鎬侊紝涓嶅啓鍏ユ彃浠跺墠绔垨鏅�氶厤缃枃浠躲��
@@ -555,8 +555,8 @@
### FR-LLM-05 閰嶇疆涓庡瘑閽�
- 鎻掍欢蹇呴』鏀寔閰嶇疆妯″瀷鍒楄〃銆侀粯璁ゆā鍨嬪拰璇锋眰鍙傛暟銆�
-- 姣忎釜妯″瀷蹇呴』鑳藉閰嶇疆鐙珛鐨� provider銆乪ndpoint銆佺湡瀹炰笂娓告ā鍨嬪悕鍜屽惎鐢ㄧ姸鎬併��
-- 瀹夸富搴旀牴鎹� `modelId` 璺敱鍒板搴� provider 閫傞厤鍣紝骞惰皟鐢ㄨ妯″瀷鑷繁鐨� endpoint銆�
+- 姣忎釜妯″瀷蹇呴』鑳藉閰嶇疆鐙珛鐨� provider銆乣baseUrl`銆佺湡瀹炰笂娓告ā鍨嬪悕鍜屽惎鐢ㄧ姸鎬併��
+- 瀹夸富搴旀牴鎹� `modelId` 璺敱鍒板搴� provider 閫傞厤鍣紝骞惰皟鐢� `{baseUrl}/chat/completions`銆�
- API key 涓嶅緱鍐欐鍦ㄦ彃浠跺墠绔祫婧愪腑銆�
- API key 搴斾互 `authRef` 褰㈠紡寮曠敤瀹夸富渚у瘑閽ュ瓨鍌ㄦ垨鐢ㄦ埛鐜閰嶇疆銆�
- 濡傛灉瀹夸富鏆傛湭鎻愪緵瀵嗛挜瀹夊叏瀛樺偍锛孧VP 蹇呴』灏嗚鑳藉姏鏍囪涓哄彈闄愶紝骞舵彁渚涙竻鏅伴闄╂彁绀恒��
diff --git a/docs/qa/global-hotkeys-acceptance.md b/docs/qa/global-hotkeys-acceptance.md
new file mode 100644
index 0000000..f676d9d
--- /dev/null
+++ b/docs/qa/global-hotkeys-acceptance.md
@@ -0,0 +1,37 @@
+# 鍏ㄥ眬蹇嵎閿笌浼氳瘽鍙氦浜掗獙鏀舵竻鍗�
+
+鏃ユ湡锛�2026-08-13
+
+## 鑼冨洿
+
+楠岃瘉 `desktop-ops` Epic銆屽叏灞�蹇嵎閿寮猴細浼氳瘽鍙氦浜掍笌蹇嵎閿鐞嗐�嶏紙HK-1 ~ HK-7锛夈��
+
+## 鎵嬪伐楠屾敹
+
+- [ ] 搴旂敤鍦ㄥ墠鍙版椂锛宍Ctrl+Shift+K` 鍙垏鎹� `sample.llm-command-palette`锛氱┖闂茬┛閫� 鈫� 鍙氦浜�
+- [ ] 搴旂敤涓嶅湪鍓嶅彴鏃讹紝鍚屼竴蹇嵎閿粛鐢熸晥
+- [ ] 闀挎寜涓嶄細鍥犻噸澶嶆秷鎭繛缈伙紙`MOD_NOREPEAT`锛�
+- [ ] 鍙氦浜掑悗鍙洿鎺ュ湪杈撳叆妗嗘墦瀛楀苟 Enter 鎻愪氦
+- [ ] 鍐嶆寜涓�娆℃墠閫�鍑哄彲浜や簰锛涚偣鍑绘闈㈠け鐒︿笉閫�鍑�
+- [ ] 鍒囨崲鍙氦浜掑悗 `layout.json` 鐨� `clickThrough` / `isVisible` 涓嶅彉
+- [ ] 杩涚▼閲嶅惎鍚庡洖鍒扮┖闂茬┛閫忥紝palette 涓嶅啀鎸′綇妗岄潰鍥炬爣
+- [ ] 缂栬緫妯″紡寮�鍚椂鎸夌儹閿粛缈昏浆浼氳瘽浣嶏紝浣嗘湁鏁堢┛閫忚缂栬緫妯″紡瑕嗙洊锛堢粍浠堕〉鍙瀵燂級
+- [ ] 绠$悊绐楀彛鑳芥妸榛樿 `Ctrl+Shift+K` 鏀规垚鍙︿竴缁勬湭鍗犵敤缁勫悎閿紝绔嬪嵆鐢熸晥涓旈噸鍚粛鍦�
+- [ ] 绂佺敤缁戝畾鍚庢寜鍘熼敭鏃犲搷搴旓紱鍐嶅惎鐢ㄦ仮澶�
+- [ ] 鍒犻櫎鐢ㄦ埛缁戝畾鎴愬姛锛涘唴缃粦瀹氫笉鑳藉垹锛涙仮澶嶉粯璁ゅ悗鍥炲埌 `Ctrl+Shift+K`
+- [ ] 褰曞埗杩囩▼涓凡娉ㄥ唽鐑敭涓嶄細鎶㈣蛋鎸夐敭
+- [ ] 鍐茬獊缁戝畾涓嶅奖鍝嶅叾浠栫粦瀹氭敞鍐岋紝鍒楄〃鏍囩孩骞跺啓璇婃柇
+- [ ] 閫�鍑鸿繘绋嬪悗鐑敭涓嶅啀琚郴缁熷崰鐢�
+
+## 鍗曞厓娴嬭瘯
+
+`dotnet test src/Moli.Desktop.Tests/Moli.Desktop.Tests.csproj`
+
+瑕嗙洊锛氭湁鏁堢┛閫忕煩闃点�佷笉鍐� layout銆乭otkeys.json 榛樿/鎹熷潖鎭㈠/round-trip銆佹牎楠岋紙閲嶅 chord銆侀潪娉� keys銆佹湭鐭ュ姩浣溿�佺┖ target銆乥uiltin 涓嶅彲鍒狅級銆丷egisterHotKey 鍐茬獊璺宠繃銆丳ause/Resume銆�
+
+## 闈炵洰鏍�
+
+- 鎻掍欢鑷娉ㄥ唽鍏ㄥ眬鐑敭
+- `WH_KEYBOARD_LL` 閿洏閽╁瓙
+- 澶辩劍鑷姩閫�鍑�
+- 榛樿缁戝畾浣跨敤 `Alt+Space`
diff --git a/samples/plugins/sample.llm-command-palette/index.html b/samples/plugins/sample.llm-command-palette/index.html
index 6057f32..fded937 100644
--- a/samples/plugins/sample.llm-command-palette/index.html
+++ b/samples/plugins/sample.llm-command-palette/index.html
@@ -514,6 +514,7 @@
mode: "provider-direct",
models: [],
projects: [],
+ projectStatus: "",
selectedModelId: "",
selectedProjectId: "",
requestId: "",
@@ -558,6 +559,7 @@
{ id: "kimi-k2.6", label: "Kimi", provider: "kimi", supportsStreaming: true, enabled: true },
{ id: "glm-4.7-flash", label: "GLM", provider: "bigmodel", supportsStreaming: true, enabled: true }
];
+ const MODEL_PAGE_SIZE = 20;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -692,9 +694,11 @@
control.dispatchEvent(new CustomEvent("change", { detail: { value } }));
}
- function setSelectOptions(control, menu, items, emptyLabel, selectedId) {
+ function setSelectOptions(control, menu, items, emptyLabel, selectedId, settings) {
+ const config = settings || {};
+ const autoSelectFirst = config.autoSelectFirst !== false;
+ const pageSize = config.pageSize || 0;
control.dataset.emptyLabel = emptyLabel;
- menu.textContent = "";
const options = items
.map((item) => ({
@@ -704,7 +708,29 @@
}))
.filter((item) => item.value);
- for (const option of options) {
+ menu._allOptions = options;
+ menu._pageSize = pageSize;
+ renderSelectPage(control, menu, true);
+
+ const selected = options.find((option) => option.value === selectedId)
+ || (autoSelectFirst ? options[0] : null)
+ || null;
+ setSelectValue(control, menu, selected || { value: "", label: emptyLabel, title: emptyLabel });
+ }
+
+ function renderSelectPage(control, menu, reset) {
+ const options = menu._allOptions || [];
+ const pageSize = menu._pageSize || 0;
+ if (reset) {
+ menu._renderedCount = 0;
+ menu.textContent = "";
+ }
+
+ const start = menu._renderedCount || 0;
+ const end = pageSize > 0 ? Math.min(options.length, start + pageSize) : options.length;
+ const selectedValue = control.dataset.value || "";
+ for (let index = start; index < end; index += 1) {
+ const option = options[index];
const item = document.createElement("div");
item.className = "select-option";
item.setAttribute("role", "option");
@@ -712,6 +738,7 @@
item.dataset.value = option.value;
item.textContent = option.label;
item.title = option.title || option.label;
+ if (option.value === selectedValue) item.classList.add("selected");
item.addEventListener("click", () => {
setSelectValue(control, menu, option);
closeSelects();
@@ -719,14 +746,23 @@
menu.appendChild(item);
}
- const selected = options.find((option) => option.value === selectedId) || options[0] || null;
- setSelectValue(control, menu, selected || { value: "", label: emptyLabel, title: emptyLabel });
+ menu._renderedCount = end;
+ menu.style.overflow = end > 6 ? "auto" : "hidden";
}
function bindSelect(control, menu) {
invokeOnAction(control, () => {
const willOpen = !control.classList.contains("open");
closeSelects();
+ if (willOpen && menu._pageSize) {
+ renderSelectPage(control, menu, true);
+ const selected = (menu._allOptions || []).find((option) => option.value === (control.dataset.value || ""));
+ if (selected) {
+ for (const child of menu.children) {
+ child.classList.toggle("selected", child.dataset.value === selected.value);
+ }
+ }
+ }
control.classList.toggle("open", willOpen);
control.setAttribute("aria-expanded", willOpen ? "true" : "false");
});
@@ -742,6 +778,14 @@
options[nextIndex].click();
} else if (event.key === "Escape") {
closeSelects();
+ }
+ });
+ menu.addEventListener("scroll", () => {
+ if (!menu._pageSize) return;
+ const all = menu._allOptions || [];
+ if ((menu._renderedCount || 0) >= all.length) return;
+ if (menu.scrollTop + menu.clientHeight >= menu.scrollHeight - 24) {
+ renderSelectPage(control, menu, false);
}
});
}
@@ -774,13 +818,46 @@
async function loadProjects() {
try {
if (!llm || typeof llm.getProjects !== "function") throw new Error("AiChat bridge unavailable.");
- state.projects = asArray(await llm.getProjects());
- setSelectOptions(els.projectSelect, els.projectMenu, state.projects, state.projects.length ? "Project" : "No project", state.selectedProjectId);
+ const result = await llm.getProjects();
+ const packed = result && !Array.isArray(result);
+ const status = String((packed ? (result.status || result.Status) : "ready") || "ready").toLowerCase();
+ const projects = packed ? asArray(result.projects || result.Projects) : asArray(result);
+ const message = packed ? (result.message || result.Message || "") : "";
+ state.projects = projects;
+ state.projectStatus = status;
+
+ if (status === "not-configured") {
+ setSelectOptions(els.projectSelect, els.projectMenu, [], "Not configured", "", { autoSelectFirst: false });
+ els.projectSelect.title = "AiChat is not configured.";
+ state.selectedProjectId = "";
+ return;
+ }
+
+ if (status === "not-connected") {
+ setSelectOptions(els.projectSelect, els.projectMenu, [], "Not connected", "", { autoSelectFirst: false });
+ els.projectSelect.title = message || "AiChat is not connected.";
+ state.selectedProjectId = "";
+ return;
+ }
+
+ const selectedId = projects.some((item) => (item.id || item.Id) === state.selectedProjectId)
+ ? state.selectedProjectId
+ : "";
+ setSelectOptions(
+ els.projectSelect,
+ els.projectMenu,
+ projects,
+ projects.length ? "Project" : "No project",
+ selectedId,
+ { autoSelectFirst: false }
+ );
state.selectedProjectId = getSelectValue(els.projectSelect);
} catch (error) {
state.projects = [];
- setSelectOptions(els.projectSelect, els.projectMenu, [], "No project", "");
+ state.projectStatus = "not-connected";
+ setSelectOptions(els.projectSelect, els.projectMenu, [], "Not connected", "", { autoSelectFirst: false });
els.projectSelect.title = getErrorMessage(error, "Project list unavailable.");
+ state.selectedProjectId = "";
}
}
@@ -794,13 +871,26 @@
if (!state.models.length) state.models = fallbackModels;
state.selectedModelId = state.config.defaultModel || state.selectedModelId || "";
- setSelectOptions(els.modelSelect, els.modelMenu, state.models, "Model", state.selectedModelId);
+ setSelectOptions(els.modelSelect, els.modelMenu, state.models, "Model", state.selectedModelId, { pageSize: MODEL_PAGE_SIZE });
state.selectedModelId = getSelectValue(els.modelSelect);
+ }
+
+ function applyMemoryAvailability() {
+ const available = state.memoryCapabilities.canUseMemory ||
+ state.memoryCapabilities.canViewMemory ||
+ state.memoryCapabilities.canManageMemory;
+ setDisabled(els.memoryButton, !available);
+ els.memoryButton.title = available ? "Memories" : "Memory requires a configured AiChat account";
+ if (!available) {
+ els.memoryPanel.classList.remove("open");
+ els.memoryButton.classList.remove("active");
+ }
}
async function loadMemoryCapabilities() {
if (state.mode === "aichat-api") {
state.memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
+ applyMemoryAvailability();
renderMemories("AiChat mode uses service-side memory.");
return;
}
@@ -816,7 +906,7 @@
} catch {
state.memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
}
- setDisabled(els.memoryButton, false);
+ applyMemoryAvailability();
}
async function loadMemories() {
@@ -1013,6 +1103,14 @@
bindSelect(els.projectSelect, els.projectMenu);
bindSelect(els.modelSelect, els.modelMenu);
+ window.addEventListener("moli:interactable-changed", (event) => {
+ const detail = event.detail || {};
+ const enabled = Boolean(detail.enabled ?? detail.Enabled);
+ if (enabled) {
+ els.promptInput.focus({ preventScroll: true });
+ }
+ });
+
els.promptInput.addEventListener("input", resizeTextarea);
els.promptInput.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
diff --git a/samples/plugins/sample.llm-command-palette/plugin.json b/samples/plugins/sample.llm-command-palette/plugin.json
index 61e21ae..b45d761 100644
--- a/samples/plugins/sample.llm-command-palette/plugin.json
+++ b/samples/plugins/sample.llm-command-palette/plugin.json
@@ -26,79 +26,48 @@
"aichat": {
"baseUrl": "http://192.168.1.111:13000",
"account": {
- "email": "linmolilin@163.com",
+ "email": null,
"password": null,
"passwordEnv": "MOLI_AICHAT_PASSWORD"
},
- "defaultProjectId": "cmnd8uzcl0002c9usch183a01",
+ "defaultProjectId": null,
"memory": {
"enabledInProviderDirect": true,
"defaultScope": "PROJECT",
"recallLimit": 8
}
},
- "defaultModel": "deepseek-v4-flash",
- "models": [
+ "defaultModel": null,
+ "providers": [
{
- "id": "deepseek-v4-flash",
- "label": "deepseek-v4-flash",
- "provider": "deepseek",
- "endpoint": "https://api.deepseek.com/chat/completions",
+ "id": "deepseek",
+ "label": "DeepSeek",
+ "baseUrl": "https://api.deepseek.com",
"authRef": "llm_deepseek_api_key",
- "apiModel": "deepseek-v4-flash",
- "supportsStreaming": true,
- "enabled": true,
- "requestDefaults": {
- "temperature": 0.9,
- "maxTokens": 8192,
- "timeoutMs": 60000
- }
+ "enabled": true
},
{
- "id": "kimi-k2.6",
- "label": "kimi-k2.6",
- "provider": "kimi",
- "endpoint": "https://api.moonshot.cn/v1/chat/completions",
+ "id": "kimi",
+ "label": "Kimi",
+ "baseUrl": "https://api.moonshot.cn/v1",
"authRef": "llm_kimi_api_key",
- "apiModel": "kimi-k2.6",
- "supportsStreaming": true,
- "enabled": true,
- "requestDefaults": {
- "temperature": 0.9,
- "maxTokens": 8192,
- "timeoutMs": 60000
- }
+ "enabled": true
},
{
- "id": "glm-4.7-flash",
- "label": "glm-4.7-flash",
- "provider": "bigmodel",
- "endpoint": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
+ "id": "bigmodel",
+ "label": "鏅鸿氨",
+ "baseUrl": "https://open.bigmodel.cn/api/paas/v4",
"authRef": "llm_bigmodel_api_key",
- "apiModel": "glm-4.7-flash",
- "supportsStreaming": true,
- "enabled": true,
- "requestDefaults": {
- "temperature": 0.9,
- "maxTokens": 8192,
- "timeoutMs": 60000
- }
+ "enabled": true
},
{
- "id": "qwen3.6-plus",
- "label": "qwen3.6-plus",
- "provider": "qwen",
- "endpoint": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
- "authRef": "llm_bigmodel_api_key",
- "apiModel": "qwen3.6-plus",
- "supportsStreaming": true,
- "enabled": true,
- "requestDefaults": {
- "temperature": 0.9,
- "maxTokens": 8192,
- "timeoutMs": 60000
- }
+ "id": "qwen",
+ "label": "閫氫箟",
+ "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
+ "authRef": "llm_qwen_api_key",
+ "enabled": true
}
- ]
+ ],
+ "models": []
}
}
diff --git a/src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs b/src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs
index 25fc18b..22ce89b 100644
--- a/src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs
+++ b/src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs
@@ -2,6 +2,7 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
@@ -19,9 +20,12 @@
Assert.Equal(1, snapshot.AppSettings.SchemaVersion);
Assert.Equal(1, snapshot.Plugins.SchemaVersion);
Assert.Equal(1, snapshot.Layout.SchemaVersion);
+ Assert.Equal(1, snapshot.Hotkeys.SchemaVersion);
Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, "appsettings.json")));
Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, "plugins.json")));
Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, "layout.json")));
+ Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, "hotkeys.json")));
+ Assert.Contains(snapshot.Hotkeys.Bindings, binding => binding.Id == "llm-palette-toggle-interactable");
}
[Fact]
@@ -79,6 +83,58 @@
Assert.Equal(DisplayLayer.AppTop, Assert.Single(loaded.Instances).DisplayLayer);
}
+ [Fact]
+ public async Task LoadHotkeysAsync_CreatesDefaultBuiltinBinding()
+ {
+ var (service, paths, _) = CreateService();
+
+ var document = await service.LoadHotkeysAsync();
+
+ var binding = Assert.Single(document.Bindings);
+ Assert.Equal("llm-palette-toggle-interactable", binding.Id);
+ Assert.Equal("Ctrl+Shift+K", binding.Keys);
+ Assert.Equal("widget.toggleInteractable", binding.Action);
+ Assert.Equal("sample.llm-command-palette", binding.Target?.PluginId);
+ Assert.Equal(HotkeySource.Builtin, binding.Source);
+ Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, "hotkeys.json")));
+ }
+
+ [Fact]
+ public async Task LoadHotkeysAsync_BacksUpInvalidJsonAndRecoversDefault()
+ {
+ var (service, paths, diagnostics) = CreateService();
+ Directory.CreateDirectory(paths.ConfigDirectory);
+ await File.WriteAllTextAsync(Path.Combine(paths.ConfigDirectory, "hotkeys.json"), "{ broken json");
+
+ var document = await service.LoadHotkeysAsync();
+
+ Assert.Equal(1, document.SchemaVersion);
+ Assert.Contains(document.Bindings, binding => binding.Id == "llm-palette-toggle-interactable");
+ Assert.NotEmpty(Directory.GetFiles(paths.ConfigDirectory, "hotkeys.invalid.*.json"));
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == DiagnosticCodes.ConfigurationRecovered);
+ }
+
+ [Fact]
+ public async Task SaveAndLoadHotkeysAsync_RoundTripsUserBinding()
+ {
+ var (service, _, _) = CreateService();
+ var document = HotkeysDocument.CreateDefault();
+ document.Bindings.Add(new HotkeyBinding
+ {
+ Id = "user-edit-mode",
+ Keys = "Ctrl+Alt+E",
+ Action = HotkeyActions.RuntimeToggleEditMode,
+ Enabled = true,
+ Source = HotkeySource.User
+ });
+
+ await service.SaveHotkeysAsync(document);
+ var loaded = await service.LoadHotkeysAsync();
+
+ Assert.Equal(2, loaded.Bindings.Count);
+ Assert.Contains(loaded.Bindings, binding => binding.Id == "user-edit-mode" && binding.Keys == "Ctrl+Alt+E");
+ }
+
private static (JsonConfigurationService Service, DesktopPaths Paths, DiagnosticsService Diagnostics) CreateService()
{
var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
diff --git a/src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs b/src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs
new file mode 100644
index 0000000..088a4dd
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs
@@ -0,0 +1,105 @@
+using Moli.Desktop.Hotkeys;
+
+namespace Moli.Desktop.Tests.Hotkeys;
+
+public class HotkeyChordTests
+{
+ [Theory]
+ [InlineData("Ctrl+Shift+K", "Ctrl+Shift+K")]
+ [InlineData("shift+ctrl+k", "Ctrl+Shift+K")]
+ [InlineData("Control+Alt+E", "Ctrl+Alt+E")]
+ public void TryParse_NormalizesCanonicalForm(string input, string canonical)
+ {
+ Assert.True(HotkeyChord.TryParse(input, out var chord, out _));
+ Assert.Equal(canonical, chord.Canonical);
+ Assert.Equal(HotkeyChord.ModNoRepeat, chord.RegisterModifiers & HotkeyChord.ModNoRepeat);
+ }
+
+ [Theory]
+ [InlineData("Ctrl")]
+ [InlineData("Alt+Shift")]
+ public void TryParse_RejectsModifierOnly(string input)
+ {
+ Assert.False(HotkeyChord.TryParse(input, out _, out var error));
+ Assert.Equal("HotkeyModifierOnly", error);
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData("K")]
+ [InlineData("Ctrl+Shift+NotAKey")]
+ public void TryParse_RejectsInvalidKeys(string input)
+ {
+ Assert.False(HotkeyChord.TryParse(input, out _, out var error));
+ Assert.Equal("HotkeyInvalidKeys", error);
+ }
+}
+
+public class HotkeysValidatorTests
+{
+ [Fact]
+ public void Validate_AcceptsDefaultDocument()
+ {
+ var result = HotkeysValidator.Validate(HotkeysDocument.CreateDefault());
+ Assert.True(result.Succeeded);
+ }
+
+ [Fact]
+ public void Validate_RejectsDuplicateChord()
+ {
+ var document = HotkeysDocument.CreateDefault();
+ document.Bindings.Add(new HotkeyBinding
+ {
+ Id = "user-dup",
+ Keys = "Shift+Ctrl+K",
+ Action = HotkeyActions.RuntimeToggleEditMode,
+ Source = HotkeySource.User
+ });
+
+ var result = HotkeysValidator.Validate(document);
+
+ Assert.False(result.Succeeded);
+ Assert.Equal("HotkeyDuplicateChord", result.ErrorCode);
+ }
+
+ [Fact]
+ public void Validate_RejectsUnknownActionAndEmptyTarget()
+ {
+ var unknown = HotkeysDocument.CreateDefault();
+ unknown.Bindings[0] = unknown.Bindings[0] with { Action = "plugin.registerHotKey" };
+ Assert.Equal("HotkeyUnknownAction", HotkeysValidator.Validate(unknown).ErrorCode);
+
+ var emptyTarget = HotkeysDocument.CreateDefault();
+ emptyTarget.Bindings[0] = emptyTarget.Bindings[0] with { Target = new HotkeyTarget() };
+ Assert.Equal("HotkeyEmptyTarget", HotkeysValidator.Validate(emptyTarget).ErrorCode);
+ }
+
+ [Fact]
+ public void ValidateDelete_ForbidsBuiltin()
+ {
+ var result = HotkeysValidator.ValidateDelete(HotkeysDocument.CreateBuiltinPaletteBinding());
+ Assert.False(result.Succeeded);
+ Assert.Equal("HotkeyBuiltinDeleteForbidden", result.ErrorCode);
+ }
+
+ [Fact]
+ public void RestoreBuiltins_ResetsBuiltinAndKeepsUserBindings()
+ {
+ var document = HotkeysDocument.CreateDefault();
+ document.Bindings[0] = document.Bindings[0] with { Keys = "Ctrl+Shift+P", Enabled = false };
+ document.Bindings.Add(new HotkeyBinding
+ {
+ Id = "user-safe",
+ Keys = "Ctrl+Alt+S",
+ Action = HotkeyActions.RuntimeToggleSafeInputMode,
+ Source = HotkeySource.User
+ });
+
+ var restored = HotkeysValidator.RestoreBuiltins(document);
+
+ var builtin = Assert.Single(restored.Bindings, binding => binding.Source == HotkeySource.Builtin);
+ Assert.Equal("Ctrl+Shift+K", builtin.Keys);
+ Assert.True(builtin.Enabled);
+ Assert.Contains(restored.Bindings, binding => binding.Id == "user-safe");
+ }
+}
diff --git a/src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs b/src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs
new file mode 100644
index 0000000..5f1b986
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs
@@ -0,0 +1,169 @@
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Hotkeys;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Tests.Hotkeys;
+
+public class HotkeyServiceTests
+{
+ [Fact]
+ public async Task ReplaceBindingsAsync_RegistersEnabledAndSkipsConflicts()
+ {
+ var diagnostics = new InMemoryDiagnostics();
+ var api = new FakeNativeHotkeyApi();
+ api.ConflictChords.Add("Ctrl+Shift+K");
+ using var service = CreateService(api, diagnostics);
+
+ await service.ReplaceBindingsAsync(
+ [
+ HotkeysDocument.CreateBuiltinPaletteBinding(),
+ new HotkeyBinding
+ {
+ Id = "user-edit",
+ Keys = "Ctrl+Alt+E",
+ Action = HotkeyActions.RuntimeToggleEditMode,
+ Enabled = true,
+ Source = HotkeySource.User
+ },
+ new HotkeyBinding
+ {
+ Id = "disabled",
+ Keys = "Ctrl+Alt+D",
+ Action = HotkeyActions.RuntimeToggleSafeInputMode,
+ Enabled = false,
+ Source = HotkeySource.User
+ }
+ ]);
+
+ Assert.Equal(HotkeyRegistrationState.Conflict, service.Registrations.Single(item => item.BindingId == "llm-palette-toggle-interactable").State);
+ Assert.Equal(HotkeyRegistrationState.Registered, service.Registrations.Single(item => item.BindingId == "user-edit").State);
+ Assert.Equal(HotkeyRegistrationState.Disabled, service.Registrations.Single(item => item.BindingId == "disabled").State);
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == DiagnosticCodes.HotkeyConflict);
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == DiagnosticCodes.HotkeyRegistered);
+ Assert.Single(api.Registered);
+ Assert.Equal(new IntPtr(1), api.LastHwnd);
+ }
+
+ [Fact]
+ public async Task PauseAndResume_UnregistersThenRegistersAgain()
+ {
+ var api = new FakeNativeHotkeyApi();
+ using var service = CreateService(api);
+ await service.ReplaceBindingsAsync([HotkeysDocument.CreateBuiltinPaletteBinding()]);
+
+ service.Pause();
+ Assert.Empty(api.Registered);
+ Assert.All(service.Registrations, item => Assert.Equal(HotkeyRegistrationState.Disabled, item.State));
+
+ service.Resume();
+ Assert.Single(api.Registered);
+ Assert.Equal(HotkeyRegistrationState.Registered, Assert.Single(service.Registrations).State);
+ }
+
+ [Fact]
+ public async Task ReplaceBindingsAsync_DoesNotRegisterAgainstZeroHwnd()
+ {
+ var diagnostics = new InMemoryDiagnostics();
+ var api = new FakeNativeHotkeyApi();
+ using var service = CreateService(api, diagnostics, hwnd: IntPtr.Zero);
+
+ await service.ReplaceBindingsAsync([HotkeysDocument.CreateBuiltinPaletteBinding()]);
+
+ Assert.Empty(api.Registered);
+ Assert.Equal(new IntPtr(-1), api.LastHwnd);
+ Assert.Equal(HotkeyRegistrationState.Invalid, Assert.Single(service.Registrations).State);
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == DiagnosticCodes.HotkeyMessageWindowFailed);
+ }
+
+ [Fact]
+ public async Task PostedHotkey_RaisesHotkeyPressed()
+ {
+ var api = new FakeNativeHotkeyApi();
+ var window = new FakeHotkeyMessageWindow(new IntPtr(1));
+ using var service = new HotkeyService(new InMemoryDiagnostics(), api, window);
+ var tcs = new TaskCompletionSource<HotkeyBinding>(TaskCreationOptions.RunContinuationsAsynchronously);
+ service.HotkeyPressed += binding =>
+ {
+ tcs.TrySetResult(binding);
+ return Task.CompletedTask;
+ };
+
+ await service.ReplaceBindingsAsync([HotkeysDocument.CreateBuiltinPaletteBinding()]);
+ window.Post(1);
+
+ var invoked = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(2));
+ Assert.Equal(HotkeysDocument.BuiltinPaletteToggleId, invoked.Id);
+ }
+
+ private static HotkeyService CreateService(
+ FakeNativeHotkeyApi api,
+ IDiagnosticsService? diagnostics = null,
+ IntPtr? hwnd = null)
+ => new(diagnostics ?? new InMemoryDiagnostics(), api, new FakeHotkeyMessageWindow(hwnd ?? new IntPtr(1)));
+}
+
+internal sealed class FakeHotkeyMessageWindow : IHotkeyMessageWindow
+{
+ public FakeHotkeyMessageWindow(IntPtr hwnd) => Handle = hwnd;
+
+ public IntPtr Handle { get; }
+
+ public event Action<int>? HotkeyPosted;
+
+ public void EnsureCreated()
+ {
+ }
+
+ public void Post(int id) => HotkeyPosted?.Invoke(id);
+
+ public void Dispose()
+ {
+ }
+}
+
+internal sealed class FakeNativeHotkeyApi : INativeHotkeyApi
+{
+ public HashSet<string> ConflictChords { get; } = new(StringComparer.OrdinalIgnoreCase);
+ public Dictionary<int, (uint Modifiers, uint VirtualKey)> Registered { get; } = [];
+ public IntPtr LastHwnd { get; private set; } = new(-1);
+
+ public bool Register(IntPtr hwnd, int id, uint modifiers, uint virtualKey, out int win32Error)
+ {
+ LastHwnd = hwnd;
+ if (ConflictChords.Contains("Ctrl+Shift+K") && virtualKey == 'K' && (modifiers & HotkeyChord.ModControl) != 0 && (modifiers & HotkeyChord.ModShift) != 0)
+ {
+ win32Error = 1409;
+ return false;
+ }
+
+ Registered[id] = (modifiers, virtualKey);
+ win32Error = 0;
+ return true;
+ }
+
+ public bool Unregister(IntPtr hwnd, int id) => Registered.Remove(id);
+}
+
+internal sealed class InMemoryDiagnostics : IDiagnosticsService
+{
+ private readonly List<DiagnosticEntry> _entries = [];
+
+ public DiagnosticEntry Record(
+ DiagnosticSeverity severity,
+ string code,
+ string message,
+ IReadOnlyDictionary<string, string>? properties = null)
+ {
+ var entry = new DiagnosticEntry
+ {
+ Code = code,
+ Severity = severity,
+ Message = message,
+ Properties = properties ?? new Dictionary<string, string>()
+ };
+ _entries.Add(entry);
+ return entry;
+ }
+
+ public IReadOnlyList<DiagnosticEntry> Snapshot() => [.. _entries];
+}
diff --git a/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs b/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
index cfabb6e..daaec2c 100644
--- a/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
+++ b/src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
@@ -1,3 +1,4 @@
+using System.Net.Http;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
@@ -30,7 +31,7 @@
Messages = [new LlmMessage { Role = "user", Content = "hello" }]
}).ToListAsync();
- Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.Endpoint);
+ Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
Assert.Contains(events, item => item is LlmCompletedEvent);
}
@@ -89,6 +90,209 @@
}
[Fact]
+ public async Task StreamChatAsync_UsesBaseUrlOnlyModel()
+ {
+ var adapter = new CapturingAdapter("openai-compatible");
+ var gateway = CreateGateway(adapter, new LlmModelConfig
+ {
+ Id = "model-a",
+ Label = "Model A",
+ Provider = "openai-compatible",
+ BaseUrl = "http://127.0.0.1:11434/v1",
+ ApiModel = "actual-model",
+ Enabled = true
+ });
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-base",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "model-a",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }]
+ }).ToListAsync();
+
+ Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
+ }
+
+ [Fact]
+ public async Task StreamChatAsync_ResolvesProviderModelId()
+ {
+ var adapter = new CapturingAdapter("openai-compatible");
+ var gateway = CreateGateway(adapter);
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-provider",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "provider:deepseek:deepseek-v4-flash",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }],
+ RuntimeConfig = new LlmPluginRuntimeConfig
+ {
+ Providers =
+ [
+ new LlmProviderConfig
+ {
+ Id = "deepseek",
+ Label = "DeepSeek",
+ BaseUrl = "https://api.deepseek.com"
+ }
+ ]
+ }
+ }).ToListAsync();
+
+ Assert.Equal("deepseek-v4-flash", adapter.LastRequest?.Model.ApiModel);
+ Assert.Equal("https://api.deepseek.com/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
+ }
+
+ [Fact]
+ public async Task GetModelsAsync_MergesCustomThenProviderAndIsolatesFailures()
+ {
+ var adapter = new CapturingAdapter("openai-compatible")
+ {
+ ListModels = baseUrl => baseUrl.Contains("bad", StringComparison.Ordinal)
+ ? throw new HttpRequestException("down")
+ : ["deepseek-v4-flash"]
+ };
+ var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter);
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ DefaultModel = "local-qwen",
+ Models =
+ [
+ new LlmModelConfig
+ {
+ Id = "local-qwen",
+ Label = "qwen2.5:14b",
+ Provider = "openai-compatible",
+ BaseUrl = "http://127.0.0.1:11434/v1",
+ ApiModel = "qwen2.5:14b",
+ Enabled = true
+ }
+ ],
+ Providers =
+ [
+ new LlmProviderConfig { Id = "bad", Label = "Bad", BaseUrl = "https://bad.example" },
+ new LlmProviderConfig { Id = "deepseek", Label = "DeepSeek", BaseUrl = "https://api.deepseek.com" }
+ ]
+ });
+
+ Assert.Equal("local-qwen", models[0].Id);
+ Assert.Equal("qwen2.5:14b(Custom) *", models[0].Label);
+ Assert.Equal("provider:deepseek:deepseek-v4-flash", models[1].Id);
+ Assert.Equal("deepseek-v4-flash(DeepSeek)", models[1].Label);
+ Assert.Equal(2, models.Count);
+ Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == LlmErrorCodes.EndpointUnavailable);
+ Assert.All(diagnostics.Snapshot(), entry =>
+ {
+ Assert.DoesNotContain("sk-", string.Join(" ", entry.Properties.Values), StringComparison.OrdinalIgnoreCase);
+ });
+ }
+
+ [Fact]
+ public async Task GetModelsAsync_FormatsAiChatLabels()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ Mode = LlmConnectionModes.AiChatApi,
+ AiChat = new AiChatRuntimeConfig
+ {
+ Account = new AiChatAccountConfig { Email = "user@example.com" }
+ }
+ });
+
+ var model = Assert.Single(models);
+ Assert.Equal("deepseek-v4-flash(AiChat)", model.Label);
+ Assert.Equal(1, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task GetProjectsAsync_ReturnsNotConfiguredWithoutCallingAiChat()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
+ {
+ AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
+ });
+
+ Assert.Equal(AiChatProjectStatuses.NotConfigured, result.Status);
+ Assert.Empty(result.Projects);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task GetProjectsAsync_ReturnsNotConnectedWhenLoginFails()
+ {
+ var aiChat = new FakeAiChatClient { ThrowOnProjects = new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "password rejected") };
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
+ {
+ AiChat = new AiChatRuntimeConfig
+ {
+ Account = new AiChatAccountConfig { Email = "user@example.com" }
+ }
+ });
+
+ Assert.Equal(AiChatProjectStatuses.NotConnected, result.Status);
+ Assert.Equal("password rejected", result.Message);
+ Assert.Empty(result.Projects);
+ }
+
+ [Fact]
+ public async Task MemoryApis_DoNotCallAiChatWhenAccountMissing()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+ var config = new LlmPluginRuntimeConfig();
+
+ var capabilities = await gateway.GetMemoryCapabilitiesAsync(config);
+ await gateway.GetMemoriesAsync(config, new AiChatGetMemoriesRequest());
+ await gateway.CreateMemoryAsync(config, new AiChatCreateMemoryRequest { Scope = "GLOBAL", Content = "x" });
+ await gateway.DeleteMemoryAsync(config, "mem-1");
+ await gateway.RecallMemoriesAsync(config, new AiChatRecallMemoriesRequest { Query = "hello" });
+
+ Assert.False(capabilities.CanUseMemory);
+ Assert.False(capabilities.CanViewMemory);
+ Assert.False(capabilities.CanManageMemory);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
+ [Fact]
+ public async Task StreamChatAsync_RecordsHostWithoutApiKey()
+ {
+ var adapter = new CapturingAdapter("openai-compatible") { ThrowOnStream = new HttpRequestException("boom") };
+ var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter, new LlmModelConfig
+ {
+ Id = "model-a",
+ Label = "Model A",
+ Provider = "openai-compatible",
+ BaseUrl = "https://api.deepseek.com",
+ ApiModel = "deepseek-v4-flash",
+ Enabled = true
+ });
+
+ await gateway.StreamChatAsync(new LlmChatRequest
+ {
+ RequestId = "req-fail",
+ PluginId = "sample.llm-command-palette",
+ InstanceId = "host-1",
+ ModelId = "model-a",
+ Messages = [new LlmMessage { Role = "user", Content = "hello" }]
+ }).ToListAsync();
+
+ var entry = Assert.Single(diagnostics.Snapshot(), item => item.Code == LlmErrorCodes.EndpointUnavailable);
+ Assert.Equal("api.deepseek.com", entry.Properties["endpointHost"]);
+ Assert.DoesNotContain("test-key", string.Join(" ", entry.Properties.Select(pair => pair.Key + pair.Value)));
+ }
+
+ [Fact]
public async Task StreamChatAsync_UsesAiChatClientWhenModeIsAiChatApi()
{
var aiChat = new FakeAiChatClient();
@@ -121,20 +325,47 @@
Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "from-aichat" });
}
+ [Fact]
+ public async Task GetModelsAsync_AiChatModeWithoutAccountDoesNotCallClient()
+ {
+ var aiChat = new FakeAiChatClient();
+ var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
+
+ var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
+ {
+ Mode = LlmConnectionModes.AiChatApi,
+ AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
+ });
+
+ Assert.Empty(models);
+ Assert.Equal(0, aiChat.Calls);
+ }
+
private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models)
- => CreateGateway(adapter, null, models);
+ => CreateGatewayWithDiagnostics(adapter, null, models).Gateway;
private static LlmGatewayService CreateGateway(CapturingAdapter adapter, IAiChatClient? aiChatClient, params LlmModelConfig[] models)
+ => CreateGatewayWithDiagnostics(adapter, aiChatClient, models).Gateway;
+
+ private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
+ CapturingAdapter adapter,
+ params LlmModelConfig[] models)
+ => CreateGatewayWithDiagnostics(adapter, null, models);
+
+ private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
+ CapturingAdapter adapter,
+ IAiChatClient? aiChatClient,
+ params LlmModelConfig[] models)
{
var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
- return new LlmGatewayService(
+ return (new LlmGatewayService(
new InMemoryRegistry(models),
new EnvironmentCredentialStore(),
new LlmProviderAdapterFactory([adapter]),
diagnostics,
- aiChatClient);
+ aiChatClient), diagnostics);
}
private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry
@@ -152,6 +383,8 @@
{
public string Provider { get; } = provider;
public LlmProviderRequest? LastRequest { get; private set; }
+ public Func<string, IReadOnlyList<string>>? ListModels { get; set; }
+ public Exception? ThrowOnStream { get; set; }
public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
LlmProviderRequest request,
@@ -159,26 +392,67 @@
{
await Task.Yield();
LastRequest = request;
+ if (ThrowOnStream is not null)
+ {
+ throw ThrowOnStream;
+ }
+
yield return new LlmProviderChunk { Delta = "ok" };
yield return new LlmProviderChunk { IsCompleted = true };
+ }
+
+ public Task<IReadOnlyList<string>> ListModelIdsAsync(
+ string baseUrl,
+ string? apiKey,
+ CancellationToken cancellationToken = default)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return Task.FromResult(ListModels?.Invoke(baseUrl) ?? (IReadOnlyList<string>)[]);
}
}
private sealed class FakeAiChatClient : IAiChatClient
{
public LlmChatRequest? LastRequest { get; private set; }
+ public int Calls { get; private set; }
+ public Exception? ThrowOnProjects { get; set; }
public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
- => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
+ {
+ Calls++;
+ return Task.FromResult<IReadOnlyList<LlmModelSummary>>(
+ [
+ new LlmModelSummary
+ {
+ Id = "deepseek-v4-flash",
+ Label = "deepseek-v4-flash",
+ Provider = "aichat",
+ SupportsStreaming = true,
+ Enabled = true
+ }
+ ]);
+ }
public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
- => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([]);
+ {
+ Calls++;
+ if (ThrowOnProjects is not null)
+ {
+ throw ThrowOnProjects;
+ }
+
+ return Task.FromResult<IReadOnlyList<AiChatProjectSummary>>(
+ [
+ new AiChatProjectSummary { Id = "project-1", Name = "Project 1" }
+ ]);
+ }
public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
LlmChatRequest request,
LlmPluginRuntimeConfig runtimeConfig,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
+ Calls++;
await Task.Yield();
LastRequest = request;
yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "from-aichat" };
@@ -186,19 +460,34 @@
}
public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
- => Task.FromResult(new AiChatMemoryCapabilities());
+ {
+ Calls++;
+ return Task.FromResult(new AiChatMemoryCapabilities());
+ }
public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
- => Task.FromResult(new AiChatJsonResult());
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
- => Task.FromResult(new AiChatJsonResult());
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
- => Task.CompletedTask;
+ {
+ Calls++;
+ return Task.CompletedTask;
+ }
public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
- => Task.FromResult(new AiChatJsonResult());
+ {
+ Calls++;
+ return Task.FromResult(new AiChatJsonResult());
+ }
}
}
diff --git a/src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs b/src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs
index 03c53b1..018232b 100644
--- a/src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs
+++ b/src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs
@@ -15,7 +15,13 @@
var document = await registry.LoadAsync();
Assert.Equal(1, document.SchemaVersion);
+ var model = Assert.Single(document.Models);
+ Assert.Equal("http://127.0.0.1:11434/v1", model.BaseUrl);
+ Assert.Null(model.Endpoint);
Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName)));
+ var saved = await File.ReadAllTextAsync(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName));
+ Assert.Contains("baseUrl", saved, StringComparison.Ordinal);
+ Assert.DoesNotContain("chat/completions", saved, StringComparison.Ordinal);
}
[Fact]
@@ -64,6 +70,44 @@
}
[Fact]
+ public async Task LoadAsync_AcceptsBaseUrlAndLegacyChatEndpoint()
+ {
+ var (registry, paths, _) = CreateRegistry();
+ Directory.CreateDirectory(paths.ConfigDirectory);
+ await File.WriteAllTextAsync(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName), """
+ {
+ "schemaVersion": 1,
+ "defaultModel": "from-base",
+ "models": [
+ {
+ "id": "from-base",
+ "label": "Base",
+ "provider": "openai-compatible",
+ "baseUrl": "https://api.deepseek.com",
+ "apiModel": "deepseek-v4-flash",
+ "enabled": true
+ },
+ {
+ "id": "from-endpoint",
+ "label": "Legacy",
+ "provider": "openai-compatible",
+ "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
+ "apiModel": "qwen2.5:14b",
+ "enabled": true
+ }
+ ]
+ }
+ """);
+
+ var document = await registry.LoadAsync();
+
+ Assert.Equal(2, document.Models.Count);
+ Assert.Equal("https://api.deepseek.com", document.Models[0].BaseUrl);
+ Assert.Equal("http://127.0.0.1:11434/v1", document.Models[1].BaseUrl);
+ Assert.All(document.Models, model => Assert.Null(model.Endpoint));
+ }
+
+ [Fact]
public async Task LoadAsync_BacksUpInvalidJsonAndRecovers()
{
var (registry, paths, diagnostics) = CreateRegistry();
diff --git a/src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs b/src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs
new file mode 100644
index 0000000..f4ade0f
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs
@@ -0,0 +1,51 @@
+using Moli.Desktop.Llm;
+
+namespace Moli.Desktop.Tests.Llm;
+
+public class LlmOpenAiUrlsTests
+{
+ [Theory]
+ [InlineData("https://api.deepseek.com", null, "https://api.deepseek.com")]
+ [InlineData("https://api.deepseek.com/", null, "https://api.deepseek.com")]
+ [InlineData("https://api.moonshot.cn/v1", null, "https://api.moonshot.cn/v1")]
+ [InlineData(null, "https://api.deepseek.com/chat/completions", "https://api.deepseek.com")]
+ [InlineData(null, "https://api.deepseek.com/chat/completions/", "https://api.deepseek.com")]
+ [InlineData("https://api.deepseek.com", "https://ignored.example/chat/completions", "https://api.deepseek.com")]
+ [InlineData(null, "http://127.0.0.1:11434/v1/chat/completions", "http://127.0.0.1:11434/v1")]
+ public void ResolveBaseUrl_NormalizesBaseUrlAndLegacyEndpoint(string? baseUrl, string? endpoint, string expected)
+ => Assert.Equal(expected, LlmOpenAiUrls.ResolveBaseUrl(baseUrl, endpoint));
+
+ [Fact]
+ public void ToChatCompletionsUrl_AppendsChatPath()
+ => Assert.Equal(
+ "https://api.deepseek.com/chat/completions",
+ LlmOpenAiUrls.ToChatCompletionsUrl("https://api.deepseek.com", null));
+
+ [Fact]
+ public void ToModelsUrl_AppendsModelsPath()
+ => Assert.Equal(
+ "https://api.moonshot.cn/v1/models",
+ LlmOpenAiUrls.ToModelsUrl("https://api.moonshot.cn/v1"));
+
+ [Fact]
+ public void Host_ReturnsHostWithoutKey()
+ => Assert.Equal("api.deepseek.com", LlmOpenAiUrls.Host("https://api.deepseek.com/chat/completions"));
+
+ [Theory]
+ [InlineData("provider:deepseek:deepseek-v4-flash", "deepseek", "deepseek-v4-flash")]
+ [InlineData("provider:local:qwen2.5:14b", "local", "qwen2.5:14b")]
+ public void TryParse_ReadsProviderAndApiModel(string modelId, string providerId, string apiModel)
+ {
+ Assert.True(LlmProviderModelIds.TryParse(modelId, out var parsedProvider, out var parsedModel));
+ Assert.Equal(providerId, parsedProvider);
+ Assert.Equal(apiModel, parsedModel);
+ }
+
+ [Theory]
+ [InlineData("deepseek-v4-flash")]
+ [InlineData("provider:")]
+ [InlineData("provider:deepseek")]
+ [InlineData("provider:deepseek:")]
+ public void TryParse_RejectsInvalidIds(string modelId)
+ => Assert.False(LlmProviderModelIds.TryParse(modelId, out _, out _));
+}
diff --git a/src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs b/src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs
index be56bd9..97449ce 100644
--- a/src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs
+++ b/src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs
@@ -7,16 +7,41 @@
public class OpenAICompatibleAdapterTests
{
[Fact]
+ public async Task StreamAsync_PostsToBaseUrlChatCompletions()
+ {
+ var handler = new RecordingHandler(HttpStatusCode.OK, "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n");
+ using var httpClient = new HttpClient(handler);
+ var adapter = new OpenAICompatibleAdapter(httpClient);
+
+ var chunks = await adapter.StreamAsync(CreateRequest(baseUrl: "https://api.deepseek.com")).ToListAsync();
+
+ Assert.Equal("https://api.deepseek.com/chat/completions", handler.LastRequest?.RequestUri?.ToString());
+ Assert.Contains(chunks, chunk => chunk.Delta == "ok");
+ }
+
+ [Fact]
+ public async Task StreamAsync_AcceptsLegacyChatCompletionsEndpoint()
+ {
+ var handler = new RecordingHandler(HttpStatusCode.OK, "data: {\"choices\":[{\"delta\":{\"content\":\"ok\"}}]}\n\ndata: [DONE]\n");
+ using var httpClient = new HttpClient(handler);
+ var adapter = new OpenAICompatibleAdapter(httpClient);
+
+ await adapter.StreamAsync(CreateRequest(endpoint: "https://api.deepseek.com/chat/completions")).ToListAsync();
+
+ Assert.Equal("https://api.deepseek.com/chat/completions", handler.LastRequest?.RequestUri?.ToString());
+ }
+
+ [Fact]
public async Task StreamAsync_IncludesProviderErrorMessageWhenRequestFails()
{
- using var httpClient = new HttpClient(new StaticResponseHandler(
+ using var httpClient = new HttpClient(new RecordingHandler(
HttpStatusCode.BadRequest,
"""{"error":{"message":"Invalid max_tokens value, the valid range of max_tokens is [1, 393216]"}}"""));
var adapter = new OpenAICompatibleAdapter(httpClient);
var exception = await Assert.ThrowsAsync<LlmProviderException>(async () =>
{
- await adapter.StreamAsync(CreateRequest()).ToListAsync();
+ await adapter.StreamAsync(CreateRequest(baseUrl: "https://api.deepseek.com")).ToListAsync();
});
Assert.Equal(LlmErrorCodes.EndpointUnavailable, exception.Code);
@@ -24,7 +49,23 @@
Assert.Contains("Invalid max_tokens value", exception.Message);
}
- private static LlmProviderRequest CreateRequest()
+ [Fact]
+ public async Task ListModelIdsAsync_ReadsOpenAiDataIds()
+ {
+ var handler = new RecordingHandler(
+ HttpStatusCode.OK,
+ """{"data":[{"id":"deepseek-v4-flash"},{"id":"deepseek-chat"}]}""");
+ using var httpClient = new HttpClient(handler);
+ var adapter = new OpenAICompatibleAdapter(httpClient);
+
+ var ids = await adapter.ListModelIdsAsync("https://api.deepseek.com", "secret-key");
+
+ Assert.Equal("https://api.deepseek.com/models", handler.LastRequest?.RequestUri?.ToString());
+ Assert.Equal("secret-key", handler.LastRequest?.Headers.Authorization?.Parameter);
+ Assert.Equal(["deepseek-v4-flash", "deepseek-chat"], ids);
+ }
+
+ private static LlmProviderRequest CreateRequest(string? baseUrl = null, string? endpoint = null)
=> new()
{
RequestId = "req-1",
@@ -33,7 +74,8 @@
Id = "deepseek-v4-flash",
Label = "DeepSeek",
Provider = "deepseek",
- Endpoint = "https://api.deepseek.com/chat/completions",
+ BaseUrl = baseUrl,
+ Endpoint = endpoint,
ApiModel = "deepseek-v4-flash",
Enabled = true
},
@@ -42,12 +84,17 @@
ApiKey = "test-key"
};
- private sealed class StaticResponseHandler(HttpStatusCode statusCode, string content) : HttpMessageHandler
+ private sealed class RecordingHandler(HttpStatusCode statusCode, string content) : HttpMessageHandler
{
+ public HttpRequestMessage? LastRequest { get; private set; }
+
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
- => Task.FromResult(new HttpResponseMessage(statusCode)
+ {
+ LastRequest = request;
+ return Task.FromResult(new HttpResponseMessage(statusCode)
{
Content = new StringContent(content, Encoding.UTF8, "application/json")
});
+ }
}
}
diff --git a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
index 00e8102..b8330ce 100644
--- a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
+++ b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
@@ -3,6 +3,7 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Llm;
@@ -100,6 +101,185 @@
Assert.Equal(1, fixture.Surface.AppliedLayoutCount);
}
+ [Fact]
+ public async Task ToggleWidgetInteractableAsync_DoesNotWriteLayoutAndOverridesClickThrough()
+ {
+ var fixture = await RuntimeFixture.CreateAsync();
+ await fixture.Configuration.SaveLayoutAsync(new LayoutDocument
+ {
+ Monitors =
+ [
+ new MonitorSnapshot { Monitors = [RuntimeFixture.PrimaryMonitor()] }
+ ],
+ Instances =
+ [
+ new WidgetLayout
+ {
+ InstanceId = fixture.WidgetId,
+ PluginId = new PluginId("sample.clock"),
+ MonitorId = new MonitorId("primary"),
+ Bounds = new RectD(100, 100, 320, 160),
+ ClickThrough = false,
+ IsVisible = true
+ }
+ ]
+ });
+ await fixture.Runtime.StartAsync();
+ var before = await fixture.Configuration.LoadLayoutAsync();
+
+ var result = await fixture.Runtime.ToggleWidgetInteractableAsync(fixture.WidgetId);
+
+ Assert.True(result.Succeeded);
+ Assert.True(result.Value!.IsInteractable);
+ Assert.True(result.Value.HasSessionInteractable);
+ Assert.False(result.Value.ClickThrough);
+ Assert.False(result.Value.LayoutClickThrough);
+ Assert.Equal(1, fixture.Surface.SessionOverlayCount);
+ Assert.True(fixture.Surface.LastSessionOverlay?.Interactable);
+
+ var idle = await fixture.Runtime.ToggleWidgetInteractableAsync(fixture.WidgetId);
+ Assert.True(idle.Succeeded);
+ Assert.False(idle.Value!.IsInteractable);
+ Assert.True(idle.Value.ClickThrough);
+
+ var after = await fixture.Configuration.LoadLayoutAsync();
+ var saved = Assert.Single(after.Instances);
+ Assert.Equal(before.Instances[0].ClickThrough, saved.ClickThrough);
+ Assert.Equal(before.Instances[0].IsVisible, saved.IsVisible);
+ }
+
+ [Fact]
+ public async Task SetEditModeAsync_ForcesClickableOverSessionIdleOverlay()
+ {
+ var fixture = await RuntimeFixture.CreateAsync();
+ await fixture.Runtime.StartAsync();
+ await fixture.Runtime.SetWidgetInteractableAsync(fixture.WidgetId, false);
+
+ var result = await fixture.Runtime.SetEditModeAsync(true);
+
+ var widget = Assert.Single(result.Value!.Widgets);
+ Assert.False(widget.IsInteractable);
+ Assert.True(widget.HasSessionInteractable);
+ Assert.False(widget.ClickThrough);
+ Assert.True(widget.LayoutClickThrough);
+ }
+
+ [Fact]
+ public async Task StartAsync_AppliesIdleClickThroughForEnabledToggleInteractableBinding()
+ {
+ var fixture = await CreateIdleToggleInteractableFixtureAsync();
+
+ var result = await fixture.Runtime.StartAsync();
+
+ var widget = Assert.Single(result.Value!.Widgets);
+ Assert.False(widget.IsInteractable);
+ Assert.True(widget.HasSessionInteractable);
+ Assert.True(widget.ClickThrough);
+ Assert.False(widget.LayoutClickThrough);
+ var saved = Assert.Single((await fixture.Configuration.LoadLayoutAsync()).Instances);
+ Assert.False(saved.ClickThrough);
+ }
+
+ [Fact]
+ public async Task UpdateWidgetLayoutAsync_ClickThroughPatch_SyncsIdleOverlaySoOpenAndCloseBothTakeEffect()
+ {
+ var fixture = await CreateIdleToggleInteractableFixtureAsync();
+ await fixture.Runtime.StartAsync();
+
+ var opened = await fixture.Runtime.UpdateWidgetLayoutAsync(
+ fixture.WidgetId,
+ new WidgetLayoutPatch { ClickThrough = true });
+
+ Assert.True(opened.Succeeded);
+ Assert.True(opened.Value!.ClickThrough);
+ Assert.True(opened.Value.LayoutClickThrough);
+ Assert.False(opened.Value.IsInteractable);
+ Assert.True(opened.Value.HasSessionInteractable);
+ Assert.False(fixture.Surface.LastSessionOverlay?.Interactable);
+
+ var closed = await fixture.Runtime.UpdateWidgetLayoutAsync(
+ fixture.WidgetId,
+ new WidgetLayoutPatch { ClickThrough = false });
+
+ Assert.True(closed.Succeeded);
+ Assert.False(closed.Value!.ClickThrough);
+ Assert.False(closed.Value.LayoutClickThrough);
+ Assert.True(closed.Value.IsInteractable);
+ Assert.True(closed.Value.HasSessionInteractable);
+ Assert.True(fixture.Surface.LastSessionOverlay?.Interactable);
+
+ var saved = Assert.Single((await fixture.Configuration.LoadLayoutAsync()).Instances);
+ Assert.False(saved.ClickThrough);
+ }
+
+ [Fact]
+ public async Task HotkeyToggleInteractable_FlipsIdleSessionOverlay()
+ {
+ var fixture = await CreateIdleToggleInteractableFixtureAsync();
+ await fixture.Runtime.StartAsync();
+ Assert.True(Assert.Single((await fixture.Runtime.GetStateAsync()).Widgets).ClickThrough);
+
+ await fixture.Hotkeys.RaiseAsync(HotkeysDocument.CreateBuiltinPaletteBinding() with
+ {
+ Target = new HotkeyTarget { PluginId = "sample.clock" }
+ });
+
+ var widget = Assert.Single((await fixture.Runtime.GetStateAsync()).Widgets);
+ Assert.True(widget.IsInteractable);
+ Assert.False(widget.ClickThrough);
+ }
+
+ [Fact]
+ public async Task SaveHotkeysAsync_RejectsDuplicateChord()
+ {
+ var fixture = await RuntimeFixture.CreateAsync();
+ await fixture.Runtime.StartAsync();
+ var document = HotkeysDocument.CreateDefault();
+ document.Bindings.Add(new HotkeyBinding
+ {
+ Id = "user-dup",
+ Keys = "Shift+Ctrl+K",
+ Action = HotkeyActions.RuntimeToggleEditMode,
+ Source = HotkeySource.User
+ });
+
+ var result = await fixture.Runtime.SaveHotkeysAsync(document);
+
+ Assert.False(result.Succeeded);
+ Assert.Equal("HotkeyDuplicateChord", result.ErrorCode);
+ }
+
+ private static async Task<RuntimeFixture> CreateIdleToggleInteractableFixtureAsync()
+ {
+ var fixture = await RuntimeFixture.CreateAsync();
+ await fixture.Configuration.SaveLayoutAsync(new LayoutDocument
+ {
+ Monitors = [new MonitorSnapshot { Monitors = [RuntimeFixture.PrimaryMonitor()] }],
+ Instances =
+ [
+ new WidgetLayout
+ {
+ InstanceId = fixture.WidgetId,
+ PluginId = new PluginId("sample.clock"),
+ MonitorId = new MonitorId("primary"),
+ Bounds = new RectD(100, 100, 320, 160),
+ ClickThrough = false
+ }
+ ]
+ });
+ await fixture.Configuration.SaveHotkeysAsync(new HotkeysDocument
+ {
+ Bindings =
+ [
+ HotkeysDocument.CreateBuiltinPaletteBinding() with
+ {
+ Target = new HotkeyTarget { PluginId = "sample.clock" }
+ }
+ ]
+ });
+ return fixture;
+ }
+
private sealed class RuntimeFixture
{
private RuntimeFixture(
@@ -107,12 +287,14 @@
JsonConfigurationService configuration,
RuntimeEventBus events,
FakeRuntimeSurfaceController surface,
+ FakeHotkeyService hotkeys,
WidgetInstanceId widgetId)
{
Runtime = runtime;
Configuration = configuration;
Events = events;
Surface = surface;
+ Hotkeys = hotkeys;
WidgetId = widgetId;
}
@@ -120,6 +302,7 @@
public JsonConfigurationService Configuration { get; }
public RuntimeEventBus Events { get; }
public FakeRuntimeSurfaceController Surface { get; }
+ public FakeHotkeyService Hotkeys { get; }
public WidgetInstanceId WidgetId { get; }
public static async Task<RuntimeFixture> CreateAsync(RuntimeSettings? runtimeSettings = null)
@@ -164,6 +347,7 @@
]
});
+ var hotkeys = new FakeHotkeyService();
var runtime = new DesktopRuntimeCoordinator(
configuration,
pluginManager,
@@ -173,9 +357,10 @@
events,
surface,
new DisplayChangeMonitor(),
- new FakeLlmGateway());
+ new FakeLlmGateway(),
+ hotkeys);
- return new RuntimeFixture(runtime, configuration, events, surface, widgetId);
+ return new RuntimeFixture(runtime, configuration, events, surface, hotkeys, widgetId);
}
private static async Task CreatePluginAsync(DesktopPaths paths)
@@ -201,7 +386,7 @@
""");
}
- private static MonitorInfo PrimaryMonitor() => new()
+ public static MonitorInfo PrimaryMonitor() => new()
{
Id = new MonitorId("primary"),
Bounds = new RectD(0, 0, 1920, 1080),
@@ -216,6 +401,8 @@
public bool SafeInputModeEnabled { get; private set; }
public WidgetLayout? LastAppliedLayout { get; private set; }
public int AppliedLayoutCount { get; private set; }
+ public WidgetSessionOverlay? LastSessionOverlay { get; private set; }
+ public int SessionOverlayCount { get; private set; }
public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
{
@@ -236,6 +423,14 @@
return Task.CompletedTask;
}
+ public Task ApplyWidgetSessionOverlayAsync(WidgetLayout layout, WidgetSessionOverlay overlay, CancellationToken cancellationToken = default)
+ {
+ LastAppliedLayout = layout;
+ LastSessionOverlay = overlay;
+ SessionOverlayCount++;
+ return Task.CompletedTask;
+ }
+
public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task DisableWallpaperAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
@@ -249,6 +444,38 @@
public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
}
+ private sealed class FakeHotkeyService : IHotkeyService
+ {
+ public event Func<HotkeyBinding, Task>? HotkeyPressed;
+ public IReadOnlyList<HotkeyRegistration> Registrations { get; private set; } = [];
+ public IReadOnlyList<HotkeyBinding> Bindings { get; private set; } = [];
+ public bool Paused { get; private set; }
+
+ public Task ReplaceBindingsAsync(IReadOnlyList<HotkeyBinding> bindings, CancellationToken cancellationToken = default)
+ {
+ Bindings = bindings.ToArray();
+ Registrations = bindings.Select(binding => new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = binding.Keys,
+ State = !binding.Enabled || Paused ? HotkeyRegistrationState.Disabled : HotkeyRegistrationState.Registered
+ }).ToArray();
+ return Task.CompletedTask;
+ }
+
+ public void Pause() => Paused = true;
+
+ public void Resume() => Paused = false;
+
+ public void UnregisterAll() => Registrations = [];
+
+ public Task RaiseAsync(HotkeyBinding binding) => HotkeyPressed?.Invoke(binding) ?? Task.CompletedTask;
+
+ public void Dispose()
+ {
+ }
+ }
+
private sealed class FakeLlmGateway : ILlmGatewayService
{
public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
@@ -257,8 +484,12 @@
public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
=> Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
- public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
- => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([]);
+ public Task<AiChatProjectsResult> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
+ => Task.FromResult(new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConfigured,
+ Projects = []
+ });
public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
=> Task.FromResult(new AiChatMemoryCapabilities());
diff --git a/src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs b/src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs
new file mode 100644
index 0000000..537debf
--- /dev/null
+++ b/src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs
@@ -0,0 +1,43 @@
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Tests.Runtime;
+
+public class WidgetSurfaceRulesTests
+{
+ public static TheoryData<bool, bool, bool?, bool, bool> ClickThroughMatrix => new()
+ {
+ { false, false, null, true, true },
+ { false, false, null, false, false },
+ { false, false, false, false, true },
+ { false, false, true, true, false },
+ { true, false, false, true, false },
+ { false, true, true, true, false },
+ { true, true, false, true, false }
+ };
+
+ [Theory]
+ [MemberData(nameof(ClickThroughMatrix))]
+ public void ComputeClickThrough_FollowsEditSafeThenSessionThenLayout(
+ bool editMode,
+ bool safeInputMode,
+ bool? interactable,
+ bool layoutClickThrough,
+ bool expected)
+ {
+ var overlay = interactable is null
+ ? WidgetSessionOverlay.Empty
+ : new WidgetSessionOverlay { Interactable = interactable };
+
+ var actual = WidgetSurfaceRules.ComputeClickThrough(editMode, safeInputMode, overlay, layoutClickThrough);
+
+ Assert.Equal(expected, actual);
+ }
+
+ [Fact]
+ public void ComputeVisible_UsesSessionOverrideWhenPresent()
+ {
+ Assert.False(WidgetSurfaceRules.ComputeVisible(new WidgetSessionOverlay { Visible = false }, layoutVisible: true));
+ Assert.True(WidgetSurfaceRules.ComputeVisible(WidgetSessionOverlay.Empty, layoutVisible: true));
+ Assert.False(WidgetSurfaceRules.ComputeVisible(WidgetSessionOverlay.Empty, layoutVisible: false));
+ }
+}
diff --git a/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs b/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
index 0502097..d012cfa 100644
--- a/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
+++ b/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
@@ -67,6 +67,8 @@
var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
Assert.Contains("gpt-test", json);
Assert.DoesNotContain("endpoint", json, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("baseUrl", json, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("authRef", json, StringComparison.OrdinalIgnoreCase);
}
[Fact]
@@ -108,6 +110,7 @@
Assert.True(response.Success);
var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
Assert.Contains("project-1", json);
+ Assert.Contains("ready", json);
}
[Fact]
@@ -244,11 +247,15 @@
.ToList())
: GetModelsAsync(cancellationToken);
- public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
- => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>(
- [
- new AiChatProjectSummary { Id = "project-1", Name = "Project 1" }
- ]);
+ public Task<AiChatProjectsResult> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
+ => Task.FromResult(new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.Ready,
+ Projects =
+ [
+ new AiChatProjectSummary { Id = "project-1", Name = "Project 1" }
+ ]
+ });
public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
=> Task.FromResult(new AiChatMemoryCapabilities { CanUseMemory = true, CanViewMemory = true, CanManageMemory = true });
diff --git a/src/Moli.Desktop/Configuration/ConfigurationDocuments.cs b/src/Moli.Desktop/Configuration/ConfigurationDocuments.cs
index fe4aa65..e0a1226 100644
--- a/src/Moli.Desktop/Configuration/ConfigurationDocuments.cs
+++ b/src/Moli.Desktop/Configuration/ConfigurationDocuments.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
@@ -77,4 +78,5 @@
public AppSettingsDocument AppSettings { get; init; } = new();
public PluginRegistryDocument Plugins { get; init; } = new();
public LayoutDocument Layout { get; init; } = new();
+ public HotkeysDocument Hotkeys { get; init; } = HotkeysDocument.CreateDefault();
}
diff --git a/src/Moli.Desktop/Configuration/IConfigurationService.cs b/src/Moli.Desktop/Configuration/IConfigurationService.cs
index 7117f02..0b0db1e 100644
--- a/src/Moli.Desktop/Configuration/IConfigurationService.cs
+++ b/src/Moli.Desktop/Configuration/IConfigurationService.cs
@@ -1,3 +1,5 @@
+using Moli.Desktop.Hotkeys;
+
namespace Moli.Desktop.Configuration;
public interface IConfigurationService
@@ -8,6 +10,8 @@
Task SavePluginRegistryAsync(PluginRegistryDocument document, CancellationToken cancellationToken = default);
Task<LayoutDocument> LoadLayoutAsync(CancellationToken cancellationToken = default);
Task SaveLayoutAsync(LayoutDocument document, CancellationToken cancellationToken = default);
+ Task<HotkeysDocument> LoadHotkeysAsync(CancellationToken cancellationToken = default);
+ Task SaveHotkeysAsync(HotkeysDocument document, CancellationToken cancellationToken = default);
Task<ConfigurationSnapshot> LoadAllAsync(CancellationToken cancellationToken = default);
Task SaveAllAsync(ConfigurationSnapshot snapshot, CancellationToken cancellationToken = default);
}
diff --git a/src/Moli.Desktop/Configuration/JsonConfigurationService.cs b/src/Moli.Desktop/Configuration/JsonConfigurationService.cs
index 54303e9..0ee83a0 100644
--- a/src/Moli.Desktop/Configuration/JsonConfigurationService.cs
+++ b/src/Moli.Desktop/Configuration/JsonConfigurationService.cs
@@ -3,6 +3,7 @@
using System.Text.Json.Serialization;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
+using Moli.Desktop.Hotkeys;
namespace Moli.Desktop.Configuration;
@@ -42,13 +43,29 @@
public Task SaveLayoutAsync(LayoutDocument document, CancellationToken cancellationToken = default)
=> SaveDocumentAsync("layout.json", document, cancellationToken);
+ public async Task<HotkeysDocument> LoadHotkeysAsync(CancellationToken cancellationToken = default)
+ {
+ var document = await LoadDocumentAsync("hotkeys.json", HotkeysDocument.CreateDefault, cancellationToken).ConfigureAwait(false);
+ if (document.Bindings.All(binding =>
+ !string.Equals(binding.Id, HotkeysDocument.BuiltinPaletteToggleId, StringComparison.OrdinalIgnoreCase)))
+ {
+ document.Bindings.Insert(0, HotkeysDocument.CreateBuiltinPaletteBinding());
+ }
+
+ return document;
+ }
+
+ public Task SaveHotkeysAsync(HotkeysDocument document, CancellationToken cancellationToken = default)
+ => SaveDocumentAsync("hotkeys.json", document, cancellationToken);
+
public async Task<ConfigurationSnapshot> LoadAllAsync(CancellationToken cancellationToken = default)
{
return new ConfigurationSnapshot
{
AppSettings = await LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false),
Plugins = await LoadPluginRegistryAsync(cancellationToken).ConfigureAwait(false),
- Layout = await LoadLayoutAsync(cancellationToken).ConfigureAwait(false)
+ Layout = await LoadLayoutAsync(cancellationToken).ConfigureAwait(false),
+ Hotkeys = await LoadHotkeysAsync(cancellationToken).ConfigureAwait(false)
};
}
@@ -57,6 +74,7 @@
await SaveAppSettingsAsync(snapshot.AppSettings, cancellationToken).ConfigureAwait(false);
await SavePluginRegistryAsync(snapshot.Plugins, cancellationToken).ConfigureAwait(false);
await SaveLayoutAsync(snapshot.Layout, cancellationToken).ConfigureAwait(false);
+ await SaveHotkeysAsync(snapshot.Hotkeys, cancellationToken).ConfigureAwait(false);
}
private async Task<T> LoadDocumentAsync<T>(string fileName, Func<T> createDefault, CancellationToken cancellationToken)
diff --git a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
index 5876304..19cabe9 100644
--- a/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
+++ b/src/Moli.Desktop/Diagnostics/DiagnosticModels.cs
@@ -32,6 +32,14 @@
public const string DesktopLayerStrategySelected = "DesktopLayerStrategySelected";
public const string DesktopLayerAttachFailed = "DesktopLayerAttachFailed";
public const string Win32InteropFailed = "Win32InteropFailed";
+ public const string HotkeyRegistered = "HotkeyRegistered";
+ public const string HotkeyConflict = "HotkeyConflict";
+ public const string HotkeyInvoked = "HotkeyInvoked";
+ public const string HotkeyUnregistered = "HotkeyUnregistered";
+ public const string HotkeyInvalidTarget = "HotkeyInvalidTarget";
+ public const string HotkeyUnknownAction = "HotkeyUnknownAction";
+ public const string HotkeyDropped = "HotkeyDropped";
+ public const string HotkeyMessageWindowFailed = "HotkeyMessageWindowFailed";
}
public interface IDiagnosticsService
diff --git a/src/Moli.Desktop/Host/DesktopHostBuilder.cs b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
index e2f0b12..501c195 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -55,6 +55,9 @@
services.AddSingleton<IDesktopLayerStrategy, WorkerWDesktopLayerStrategy>();
services.AddSingleton<IDesktopLayerStrategy, BottomDesktopLayerStrategy>();
services.AddSingleton<DisplayChangeMonitor>();
+ services.AddSingleton<INativeHotkeyApi, Win32HotkeyApi>();
+ services.AddSingleton<IHotkeyMessageWindow, WpfHotkeyMessageWindow>();
+ services.AddSingleton<IHotkeyService, HotkeyService>();
services.AddSingleton<IWin32InteropService, Win32InteropService>();
services.AddSingleton<PluginBridgeDispatcher>();
services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>();
diff --git a/src/Moli.Desktop/Hotkeys/HotkeyChord.cs b/src/Moli.Desktop/Hotkeys/HotkeyChord.cs
new file mode 100644
index 0000000..75c0b45
--- /dev/null
+++ b/src/Moli.Desktop/Hotkeys/HotkeyChord.cs
@@ -0,0 +1,189 @@
+using System.Globalization;
+using System.Text;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Hotkeys;
+
+public readonly record struct HotkeyChord(uint Modifiers, uint VirtualKey, string Canonical)
+{
+ public const uint ModAlt = 0x0001;
+ public const uint ModControl = 0x0002;
+ public const uint ModShift = 0x0004;
+ public const uint ModWin = 0x0008;
+ public const uint ModNoRepeat = 0x4000;
+
+ public uint RegisterModifiers => Modifiers | ModNoRepeat;
+
+ public static bool TryParse(string? keys, out HotkeyChord chord, out string? errorCode)
+ {
+ chord = default;
+ errorCode = null;
+ if (string.IsNullOrWhiteSpace(keys))
+ {
+ errorCode = "HotkeyInvalidKeys";
+ return false;
+ }
+
+ var parts = keys.Split('+', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
+ if (parts.Length == 0)
+ {
+ errorCode = "HotkeyInvalidKeys";
+ return false;
+ }
+
+ uint modifiers = 0;
+ string? keyToken = null;
+ foreach (var part in parts)
+ {
+ if (TryParseModifier(part, out var modifier))
+ {
+ modifiers |= modifier;
+ continue;
+ }
+
+ if (keyToken is not null)
+ {
+ errorCode = "HotkeyInvalidKeys";
+ return false;
+ }
+
+ keyToken = part;
+ }
+
+ if (keyToken is null)
+ {
+ errorCode = "HotkeyModifierOnly";
+ return false;
+ }
+
+ if (!TryParseVirtualKey(keyToken, out var virtualKey, out var canonicalKey))
+ {
+ errorCode = "HotkeyInvalidKeys";
+ return false;
+ }
+
+ if (modifiers == 0)
+ {
+ errorCode = "HotkeyInvalidKeys";
+ return false;
+ }
+
+ chord = new HotkeyChord(modifiers, virtualKey, FormatCanonical(modifiers, canonicalKey));
+ return true;
+ }
+
+ public static OperationResult ValidateKeys(string? keys)
+ => TryParse(keys, out _, out var errorCode)
+ ? OperationResult.Success()
+ : OperationResult.Failure(errorCode ?? "HotkeyInvalidKeys", $"Shortcut '{keys}' is invalid.");
+
+ private static bool TryParseModifier(string token, out uint modifier)
+ {
+ modifier = token.ToLowerInvariant() switch
+ {
+ "ctrl" or "control" => ModControl,
+ "alt" => ModAlt,
+ "shift" => ModShift,
+ "win" or "windows" or "meta" => ModWin,
+ _ => 0
+ };
+ return modifier != 0;
+ }
+
+ private static bool TryParseVirtualKey(string token, out uint virtualKey, out string canonicalKey)
+ {
+ virtualKey = 0;
+ canonicalKey = token;
+ if (token.Length == 1)
+ {
+ var ch = char.ToUpperInvariant(token[0]);
+ if (ch is >= 'A' and <= 'Z')
+ {
+ virtualKey = ch;
+ canonicalKey = ch.ToString();
+ return true;
+ }
+
+ if (ch is >= '0' and <= '9')
+ {
+ virtualKey = ch;
+ canonicalKey = ch.ToString();
+ return true;
+ }
+ }
+
+ if (token.StartsWith("F", StringComparison.OrdinalIgnoreCase)
+ && int.TryParse(token[1..], NumberStyles.Integer, CultureInfo.InvariantCulture, out var function)
+ && function is >= 1 and <= 24)
+ {
+ virtualKey = (uint)(0x6F + function);
+ canonicalKey = "F" + function.ToString(CultureInfo.InvariantCulture);
+ return true;
+ }
+
+ switch (token.ToLowerInvariant())
+ {
+ case "space":
+ virtualKey = 0x20;
+ canonicalKey = "Space";
+ return true;
+ case "tab":
+ virtualKey = 0x09;
+ canonicalKey = "Tab";
+ return true;
+ case "esc" or "escape":
+ virtualKey = 0x1B;
+ canonicalKey = "Esc";
+ return true;
+ case "enter" or "return":
+ virtualKey = 0x0D;
+ canonicalKey = "Enter";
+ return true;
+ case "up":
+ virtualKey = 0x26;
+ canonicalKey = "Up";
+ return true;
+ case "down":
+ virtualKey = 0x28;
+ canonicalKey = "Down";
+ return true;
+ case "left":
+ virtualKey = 0x25;
+ canonicalKey = "Left";
+ return true;
+ case "right":
+ virtualKey = 0x27;
+ canonicalKey = "Right";
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ private static string FormatCanonical(uint modifiers, string key)
+ {
+ var builder = new StringBuilder();
+ if ((modifiers & ModControl) != 0)
+ {
+ builder.Append("Ctrl+");
+ }
+
+ if ((modifiers & ModAlt) != 0)
+ {
+ builder.Append("Alt+");
+ }
+
+ if ((modifiers & ModShift) != 0)
+ {
+ builder.Append("Shift+");
+ }
+
+ if ((modifiers & ModWin) != 0)
+ {
+ builder.Append("Win+");
+ }
+
+ builder.Append(key);
+ return builder.ToString();
+ }
+}
diff --git a/src/Moli.Desktop/Hotkeys/HotkeysDocument.cs b/src/Moli.Desktop/Hotkeys/HotkeysDocument.cs
new file mode 100644
index 0000000..827c3c5
--- /dev/null
+++ b/src/Moli.Desktop/Hotkeys/HotkeysDocument.cs
@@ -0,0 +1,74 @@
+namespace Moli.Desktop.Hotkeys;
+
+public enum HotkeySource
+{
+ Builtin,
+ User
+}
+
+public static class HotkeyActions
+{
+ public const string WidgetToggleInteractable = "widget.toggleInteractable";
+ public const string WidgetToggleVisible = "widget.toggleVisible";
+ public const string RuntimeToggleEditMode = "runtime.toggleEditMode";
+ public const string RuntimeToggleSafeInputMode = "runtime.toggleSafeInputMode";
+
+ public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
+ {
+ WidgetToggleInteractable,
+ WidgetToggleVisible,
+ RuntimeToggleEditMode,
+ RuntimeToggleSafeInputMode
+ };
+}
+
+public sealed record HotkeyTarget
+{
+ public string? PluginId { get; init; }
+ public string? InstanceId { get; init; }
+
+ public bool IsEmpty => string.IsNullOrWhiteSpace(PluginId) && string.IsNullOrWhiteSpace(InstanceId);
+}
+
+public sealed record HotkeyBinding
+{
+ public required string Id { get; init; }
+ public required string Keys { get; init; }
+ public required string Action { get; init; }
+ public HotkeyTarget? Target { get; init; }
+ public bool Enabled { get; init; } = true;
+ public HotkeySource Source { get; init; } = HotkeySource.User;
+}
+
+public sealed record HotkeyBindingStatus
+{
+ public required HotkeyBinding Binding { get; init; }
+ public required string Status { get; init; }
+ public string? Detail { get; init; }
+}
+
+public sealed record HotkeysDocument
+{
+ public const string BuiltinPaletteToggleId = "llm-palette-toggle-interactable";
+ public const string DefaultPaletteChord = "Ctrl+Shift+K";
+ public const string DefaultPalettePluginId = "sample.llm-command-palette";
+
+ public int SchemaVersion { get; init; } = 1;
+ public List<HotkeyBinding> Bindings { get; init; } = [];
+
+ public static HotkeysDocument CreateDefault() => new()
+ {
+ SchemaVersion = 1,
+ Bindings = [CreateBuiltinPaletteBinding()]
+ };
+
+ public static HotkeyBinding CreateBuiltinPaletteBinding() => new()
+ {
+ Id = BuiltinPaletteToggleId,
+ Keys = DefaultPaletteChord,
+ Action = HotkeyActions.WidgetToggleInteractable,
+ Target = new HotkeyTarget { PluginId = DefaultPalettePluginId },
+ Enabled = true,
+ Source = HotkeySource.Builtin
+ };
+}
diff --git a/src/Moli.Desktop/Hotkeys/HotkeysValidator.cs b/src/Moli.Desktop/Hotkeys/HotkeysValidator.cs
new file mode 100644
index 0000000..c318cc6
--- /dev/null
+++ b/src/Moli.Desktop/Hotkeys/HotkeysValidator.cs
@@ -0,0 +1,74 @@
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Hotkeys;
+
+public static class HotkeysValidator
+{
+ public static OperationResult Validate(HotkeysDocument document)
+ {
+ if (document.SchemaVersion <= 0)
+ {
+ return OperationResult.Failure("HotkeyInvalidDocument", "hotkeys.json is missing schemaVersion.");
+ }
+
+ var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ var chords = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
+ foreach (var binding in document.Bindings)
+ {
+ if (string.IsNullOrWhiteSpace(binding.Id))
+ {
+ return OperationResult.Failure("HotkeyInvalidId", "A hotkey binding is missing an id.");
+ }
+
+ if (!ids.Add(binding.Id))
+ {
+ return OperationResult.Failure("HotkeyDuplicateId", $"Duplicate hotkey id '{binding.Id}'.");
+ }
+
+ if (!HotkeyActions.All.Contains(binding.Action))
+ {
+ return OperationResult.Failure("HotkeyUnknownAction", $"Unknown hotkey action '{binding.Action}'.");
+ }
+
+ if (RequiresTarget(binding.Action) && (binding.Target is null || binding.Target.IsEmpty))
+ {
+ return OperationResult.Failure("HotkeyEmptyTarget", $"Hotkey '{binding.Id}' is missing a target.");
+ }
+
+ if (!HotkeyChord.TryParse(binding.Keys, out var chord, out var errorCode))
+ {
+ return OperationResult.Failure(errorCode ?? "HotkeyInvalidKeys", $"Hotkey '{binding.Id}' has invalid keys '{binding.Keys}'.");
+ }
+
+ if (!chords.Add(chord.Canonical))
+ {
+ return OperationResult.Failure("HotkeyDuplicateChord", $"Shortcut '{chord.Canonical}' is already used.");
+ }
+ }
+
+ return OperationResult.Success();
+ }
+
+ public static OperationResult ValidateDelete(HotkeyBinding binding)
+ {
+ if (binding.Source == HotkeySource.Builtin)
+ {
+ return OperationResult.Failure("HotkeyBuiltinDeleteForbidden", "Built-in hotkeys cannot be deleted.");
+ }
+
+ return OperationResult.Success();
+ }
+
+ public static HotkeysDocument RestoreBuiltins(HotkeysDocument document)
+ {
+ var bindings = document.Bindings
+ .Where(binding => binding.Source != HotkeySource.Builtin)
+ .ToList();
+ bindings.Insert(0, HotkeysDocument.CreateBuiltinPaletteBinding());
+ return document with { Bindings = bindings };
+ }
+
+ private static bool RequiresTarget(string action)
+ => string.Equals(action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(action, HotkeyActions.WidgetToggleVisible, StringComparison.OrdinalIgnoreCase);
+}
diff --git a/src/Moli.Desktop/Interop/NativeMethods.cs b/src/Moli.Desktop/Interop/NativeMethods.cs
index d3fa8d1..9bc2ea8 100644
--- a/src/Moli.Desktop/Interop/NativeMethods.cs
+++ b/src/Moli.Desktop/Interop/NativeMethods.cs
@@ -25,7 +25,9 @@
internal const int WmDisplayChange = 0x007E;
internal const int WmSettingChange = 0x001A;
internal const int WmDeviceChange = 0x0219;
+ internal const int WmHotkey = 0x0312;
internal const int MdtEffectiveDpi = 0;
+ internal const int ErrorHotkeyAlreadyRegistered = 1409;
internal static readonly IntPtr HwndBottom = new(1);
internal static readonly IntPtr HwndMessage = new(-3);
@@ -79,6 +81,14 @@
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
+
+ [DllImport("user32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool UnregisterHotKey(IntPtr hWnd, int id);
+
[DllImport("user32.dll", SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWindow(IntPtr hWnd);
diff --git a/src/Moli.Desktop/Layout/Geometry.cs b/src/Moli.Desktop/Layout/Geometry.cs
index 342204d..e3f5fcd 100644
--- a/src/Moli.Desktop/Layout/Geometry.cs
+++ b/src/Moli.Desktop/Layout/Geometry.cs
@@ -46,9 +46,13 @@
public required RectD Bounds { get; init; }
public required MonitorId MonitorId { get; init; }
public bool IsVisible { get; init; } = true;
+ public bool LayoutIsVisible { get; init; } = true;
public bool IsLocked { get; init; }
public double Opacity { get; init; } = 1;
public bool ClickThrough { get; init; } = true;
+ public bool LayoutClickThrough { get; init; } = true;
+ public bool IsInteractable { get; init; }
+ public bool HasSessionInteractable { get; init; }
public DisplayLayer DisplayLayer { get; init; } = DisplayLayer.Desktop;
}
diff --git a/src/Moli.Desktop/Llm/ILlmServices.cs b/src/Moli.Desktop/Llm/ILlmServices.cs
index c4552f0..844e1aa 100644
--- a/src/Moli.Desktop/Llm/ILlmServices.cs
+++ b/src/Moli.Desktop/Llm/ILlmServices.cs
@@ -8,7 +8,7 @@
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default);
- Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
+ Task<AiChatProjectsResult> GetProjectsAsync(
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default);
@@ -57,6 +57,11 @@
IAsyncEnumerable<LlmProviderChunk> StreamAsync(
LlmProviderRequest request,
CancellationToken cancellationToken = default);
+
+ Task<IReadOnlyList<string>> ListModelIdsAsync(
+ string baseUrl,
+ string? apiKey,
+ CancellationToken cancellationToken = default);
}
public interface ILlmProviderAdapterFactory
diff --git a/src/Moli.Desktop/Llm/LlmGatewayService.cs b/src/Moli.Desktop/Llm/LlmGatewayService.cs
index e068be6..06e7f65 100644
--- a/src/Moli.Desktop/Llm/LlmGatewayService.cs
+++ b/src/Moli.Desktop/Llm/LlmGatewayService.cs
@@ -58,43 +58,77 @@
{
if (runtimeConfig.IsAiChatMode)
{
- return _aiChatClient is null
- ? []
- : await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ if (!runtimeConfig.HasAiChatAccount || _aiChatClient is null)
+ {
+ return [];
+ }
+
+ var aiChatModels = await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ return aiChatModels
+ .Select(model => model with { Label = FormatAiChatLabel(model) })
+ .ToList();
}
- var configuredModels = runtimeConfig.Models
+ var customModels = runtimeConfig.Models
.Where(IsUsableRuntimeModel)
- .Select(model => new LlmModelSummary
- {
- Id = model.Id,
- Label = string.Equals(model.Id, runtimeConfig.DefaultModel, StringComparison.OrdinalIgnoreCase)
- ? $"{model.Label} *"
- : model.Label,
- Provider = model.Provider,
- SupportsStreaming = model.SupportsStreaming,
- Enabled = model.Enabled
- })
+ .Select(model => ToCustomSummary(model, runtimeConfig.DefaultModel))
.ToList();
- if (configuredModels.Count > 0)
+ var providerModels = await GetProviderModelSummariesAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ if (customModels.Count > 0 || providerModels.Count > 0)
{
- return configuredModels;
+ return [.. customModels, .. providerModels];
}
return await GetModelsAsync(cancellationToken).ConfigureAwait(false);
}
- public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
+ public async Task<AiChatProjectsResult> GetProjectsAsync(
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
- ? Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([])
- : _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken);
+ {
+ if (!runtimeConfig.HasAiChatAccount)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConfigured,
+ Projects = []
+ };
+ }
+
+ if (_aiChatClient is null)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConnected,
+ Message = "AiChat client is not available.",
+ Projects = []
+ };
+ }
+
+ try
+ {
+ var projects = await _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.Ready,
+ Projects = projects
+ };
+ }
+ catch (Exception ex) when (ex is AiChatClientException or HttpRequestException)
+ {
+ return new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConnected,
+ Message = ex.Message,
+ Projects = []
+ };
+ }
+ }
public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
LlmPluginRuntimeConfig runtimeConfig,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatMemoryCapabilities())
: _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken);
@@ -102,7 +136,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatGetMemoriesRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken);
@@ -110,7 +144,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatCreateMemoryRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken);
@@ -118,7 +152,7 @@
LlmPluginRuntimeConfig runtimeConfig,
string memoryId,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.CompletedTask
: _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken);
@@ -126,7 +160,7 @@
LlmPluginRuntimeConfig runtimeConfig,
AiChatRecallMemoriesRequest request,
CancellationToken cancellationToken = default)
- => _aiChatClient is null
+ => !runtimeConfig.HasAiChatAccount || _aiChatClient is null
? Task.FromResult(new AiChatJsonResult())
: _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken);
@@ -166,10 +200,7 @@
yield break;
}
- var model = request.RuntimeConfig.Models.FirstOrDefault(model =>
- IsUsableRuntimeModel(model) &&
- string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase));
- model ??= await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false);
+ var model = await ResolveDirectModelAsync(request, cancellationToken).ConfigureAwait(false);
if (model is null)
{
yield return new LlmErrorEvent
@@ -358,14 +389,139 @@
!string.IsNullOrWhiteSpace(model.Id) &&
!string.IsNullOrWhiteSpace(model.Label) &&
!string.IsNullOrWhiteSpace(model.Provider) &&
- !string.IsNullOrWhiteSpace(model.Endpoint) &&
- !string.IsNullOrWhiteSpace(model.ApiModel);
+ !string.IsNullOrWhiteSpace(model.ApiModel) &&
+ LlmOpenAiUrls.IsAbsoluteHttpUrl(model.GetBaseUrl());
+
+ private async Task<LlmModelConfig?> ResolveDirectModelAsync(LlmChatRequest request, CancellationToken cancellationToken)
+ {
+ var custom = request.RuntimeConfig.Models.FirstOrDefault(model =>
+ IsUsableRuntimeModel(model) &&
+ string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase));
+ if (custom is not null)
+ {
+ return custom;
+ }
+
+ if (LlmProviderModelIds.TryParse(request.ModelId, out var providerId, out var apiModel))
+ {
+ var provider = request.RuntimeConfig.Providers.FirstOrDefault(item =>
+ IsUsableProvider(item) &&
+ string.Equals(item.Id, providerId, StringComparison.OrdinalIgnoreCase));
+ if (provider is not null)
+ {
+ return CreateProviderModel(provider, apiModel);
+ }
+ }
+
+ return await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task<IReadOnlyList<LlmModelSummary>> GetProviderModelSummariesAsync(
+ LlmPluginRuntimeConfig runtimeConfig,
+ CancellationToken cancellationToken)
+ {
+ var providers = runtimeConfig.Providers.Where(IsUsableProvider).ToList();
+ if (providers.Count == 0)
+ {
+ return [];
+ }
+
+ var tasks = providers.Select(provider => LoadProviderModelsAsync(provider, runtimeConfig.DefaultModel, cancellationToken)).ToList();
+ var batches = await Task.WhenAll(tasks).ConfigureAwait(false);
+ return batches.SelectMany(item => item).ToList();
+ }
+
+ private async Task<IReadOnlyList<LlmModelSummary>> LoadProviderModelsAsync(
+ LlmProviderConfig provider,
+ string? defaultModel,
+ CancellationToken cancellationToken)
+ {
+ try
+ {
+ var adapter = _adapterFactory.Get(ResolveProtocol(provider));
+ if (adapter is null)
+ {
+ return [];
+ }
+
+ var apiKey = await _credentialStore.ResolveSecretAsync(provider.AuthRef, cancellationToken).ConfigureAwait(false);
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ timeout.CancelAfter(TimeSpan.FromSeconds(10));
+ var ids = await adapter.ListModelIdsAsync(provider.BaseUrl, apiKey, timeout.Token).ConfigureAwait(false);
+ return ids
+ .Where(id => !string.IsNullOrWhiteSpace(id))
+ .Select(apiModel => ToProviderSummary(provider, apiModel, defaultModel))
+ .ToList();
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ RecordProviderCatalogFailure(provider, ex);
+ return [];
+ }
+ }
+
+ private static LlmModelSummary ToCustomSummary(LlmModelConfig model, string? defaultModel)
+ => new()
+ {
+ Id = model.Id,
+ Label = WithDefaultMark($"{model.Label}(Custom)", model.Id, defaultModel),
+ Provider = model.Provider,
+ SupportsStreaming = model.SupportsStreaming,
+ Enabled = model.Enabled
+ };
+
+ private static LlmModelSummary ToProviderSummary(LlmProviderConfig provider, string apiModel, string? defaultModel)
+ {
+ var id = LlmProviderModelIds.Create(provider.Id, apiModel);
+ return new LlmModelSummary
+ {
+ Id = id,
+ Label = WithDefaultMark($"{apiModel}({provider.Label})", id, defaultModel),
+ Provider = ResolveProtocol(provider),
+ SupportsStreaming = true,
+ Enabled = true
+ };
+ }
+
+ private static string FormatAiChatLabel(LlmModelSummary model)
+ {
+ var isDefault = model.Label.EndsWith(" *", StringComparison.Ordinal);
+ return isDefault ? $"{model.Id}(AiChat) *" : $"{model.Id}(AiChat)";
+ }
+
+ private static string WithDefaultMark(string label, string id, string? defaultModel)
+ => string.Equals(id, defaultModel, StringComparison.OrdinalIgnoreCase)
+ ? $"{label} *"
+ : label;
+
+ private static bool IsUsableProvider(LlmProviderConfig provider)
+ => provider.Enabled &&
+ !string.IsNullOrWhiteSpace(provider.Id) &&
+ !string.IsNullOrWhiteSpace(provider.Label) &&
+ LlmOpenAiUrls.IsAbsoluteHttpUrl(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null));
+
+ private static string ResolveProtocol(LlmProviderConfig provider)
+ => string.IsNullOrWhiteSpace(provider.Protocol) ? "openai-compatible" : provider.Protocol;
+
+ private static LlmModelConfig CreateProviderModel(LlmProviderConfig provider, string apiModel)
+ => new()
+ {
+ Id = LlmProviderModelIds.Create(provider.Id, apiModel),
+ Label = $"{apiModel}({provider.Label})",
+ Provider = ResolveProtocol(provider),
+ BaseUrl = LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null),
+ AuthRef = provider.AuthRef,
+ ApiModel = apiModel,
+ SupportsStreaming = true,
+ Enabled = true
+ };
private void RecordFailure(LlmChatRequest request, LlmModelConfig model, string code, string exception)
{
- var host = Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint)
- ? endpoint.Host
- : "";
_diagnostics.Record(
DiagnosticSeverity.Warning,
code,
@@ -375,8 +531,22 @@
["requestId"] = request.RequestId,
["modelId"] = request.ModelId,
["provider"] = model.Provider,
- ["endpointHost"] = host,
+ ["endpointHost"] = LlmOpenAiUrls.Host(model.GetBaseUrl()),
["exception"] = exception
});
}
+
+ private void RecordProviderCatalogFailure(LlmProviderConfig provider, Exception exception)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ LlmErrorCodes.EndpointUnavailable,
+ "LLM provider model catalog could not be loaded.",
+ new Dictionary<string, string>
+ {
+ ["providerId"] = provider.Id,
+ ["endpointHost"] = LlmOpenAiUrls.Host(LlmOpenAiUrls.ResolveBaseUrl(provider.BaseUrl, null)),
+ ["exception"] = exception.GetType().Name
+ });
+ }
}
diff --git a/src/Moli.Desktop/Llm/LlmModelRegistry.cs b/src/Moli.Desktop/Llm/LlmModelRegistry.cs
index ca8ee57..e808a8d 100644
--- a/src/Moli.Desktop/Llm/LlmModelRegistry.cs
+++ b/src/Moli.Desktop/Llm/LlmModelRegistry.cs
@@ -109,7 +109,11 @@
}
seen.Add(model.Id);
- normalized.Add(model);
+ normalized.Add(model with
+ {
+ BaseUrl = model.GetBaseUrl(),
+ Endpoint = null
+ });
}
var defaultModel = normalized.Any(model =>
@@ -145,10 +149,9 @@
return false;
}
- if (!Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint) ||
- endpoint.Scheme is not ("http" or "https"))
+ if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(model.GetBaseUrl()))
{
- RecordInvalid(model.Id, "Model endpoint must be an absolute HTTP or HTTPS URL.");
+ RecordInvalid(model.Id, "Model baseUrl must be an absolute HTTP or HTTPS URL.");
return false;
}
@@ -180,7 +183,7 @@
Id = "local-openai-compatible",
Label = "Local",
Provider = "openai-compatible",
- Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
+ BaseUrl = "http://127.0.0.1:11434/v1",
AuthRef = null,
ApiModel = "qwen2.5:14b",
SupportsStreaming = true,
diff --git a/src/Moli.Desktop/Llm/LlmModels.cs b/src/Moli.Desktop/Llm/LlmModels.cs
index aab6a29..a91906e 100644
--- a/src/Moli.Desktop/Llm/LlmModels.cs
+++ b/src/Moli.Desktop/Llm/LlmModels.cs
@@ -14,12 +14,18 @@
public required string Id { get; init; }
public required string Label { get; init; }
public required string Provider { get; init; }
- public required string Endpoint { get; init; }
+ public string? BaseUrl { get; init; }
+ [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+ public string? Endpoint { get; init; }
public string? AuthRef { get; init; }
public required string ApiModel { get; init; }
public bool SupportsStreaming { get; init; } = true;
public bool Enabled { get; init; }
public LlmRequestDefaults RequestDefaults { get; init; } = new();
+
+ public string? GetBaseUrl() => LlmOpenAiUrls.ResolveBaseUrl(BaseUrl, Endpoint);
+
+ public string? GetChatCompletionsUrl() => LlmOpenAiUrls.ToChatCompletionsUrl(BaseUrl, Endpoint);
}
public sealed record LlmRequestDefaults
@@ -142,9 +148,24 @@
public string Mode { get; init; } = LlmConnectionModes.ProviderDirect;
public AiChatRuntimeConfig AiChat { get; init; } = new();
public string? DefaultModel { get; init; }
+ public List<LlmProviderConfig> Providers { get; init; } = [];
public List<LlmModelConfig> Models { get; init; } = [];
+ [JsonIgnore]
public bool IsAiChatMode => string.Equals(Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase);
+
+ [JsonIgnore]
+ public bool HasAiChatAccount => !string.IsNullOrWhiteSpace(AiChat?.Account?.Email);
+}
+
+public sealed record LlmProviderConfig
+{
+ public string Id { get; init; } = "";
+ public string Label { get; init; } = "";
+ public string BaseUrl { get; init; } = "";
+ public string? AuthRef { get; init; }
+ public bool Enabled { get; init; } = true;
+ public string Protocol { get; init; } = "openai-compatible";
}
public sealed record AiChatRuntimeConfig
@@ -177,6 +198,13 @@
public string MemoryMode { get; init; } = "ISOLATED";
}
+public sealed record AiChatProjectsResult
+{
+ public required string Status { get; init; }
+ public string? Message { get; init; }
+ public IReadOnlyList<AiChatProjectSummary> Projects { get; init; } = [];
+}
+
public sealed record AiChatMemoryCapabilities
{
public bool CanUseMemory { get; init; }
diff --git a/src/Moli.Desktop/Llm/LlmOpenAiUrls.cs b/src/Moli.Desktop/Llm/LlmOpenAiUrls.cs
new file mode 100644
index 0000000..ec4ea38
--- /dev/null
+++ b/src/Moli.Desktop/Llm/LlmOpenAiUrls.cs
@@ -0,0 +1,90 @@
+namespace Moli.Desktop.Llm;
+
+public static class LlmOpenAiUrls
+{
+ public const string ChatCompletionsPath = "/chat/completions";
+ public const string ModelsPath = "/models";
+
+ public static string? ResolveBaseUrl(string? baseUrl, string? endpoint)
+ {
+ var raw = FirstNonEmpty(baseUrl, endpoint);
+ if (raw is null)
+ {
+ return null;
+ }
+
+ raw = raw.Trim().TrimEnd('/');
+ if (raw.EndsWith(ChatCompletionsPath, StringComparison.OrdinalIgnoreCase))
+ {
+ raw = raw[..^ChatCompletionsPath.Length].TrimEnd('/');
+ }
+
+ return string.IsNullOrWhiteSpace(raw) ? null : raw;
+ }
+
+ public static string? ToChatCompletionsUrl(string? baseUrl, string? endpoint)
+ {
+ var resolved = ResolveBaseUrl(baseUrl, endpoint);
+ return resolved is null ? null : resolved + ChatCompletionsPath;
+ }
+
+ public static string? ToModelsUrl(string? baseUrl, string? endpoint = null)
+ {
+ var resolved = ResolveBaseUrl(baseUrl, endpoint);
+ return resolved is null ? null : resolved + ModelsPath;
+ }
+
+ public static bool IsAbsoluteHttpUrl(string? url)
+ => Uri.TryCreate(url, UriKind.Absolute, out var uri) &&
+ uri.Scheme is "http" or "https";
+
+ public static string Host(string? url)
+ => Uri.TryCreate(url, UriKind.Absolute, out var uri) ? uri.Host : "";
+
+ private static string? FirstNonEmpty(string? primary, string? fallback)
+ {
+ if (!string.IsNullOrWhiteSpace(primary))
+ {
+ return primary;
+ }
+
+ return string.IsNullOrWhiteSpace(fallback) ? null : fallback;
+ }
+}
+
+public static class LlmProviderModelIds
+{
+ public const string Prefix = "provider:";
+
+ public static string Create(string providerId, string apiModel)
+ => $"{Prefix}{providerId}:{apiModel}";
+
+ public static bool TryParse(string? modelId, out string providerId, out string apiModel)
+ {
+ providerId = "";
+ apiModel = "";
+ if (string.IsNullOrWhiteSpace(modelId) ||
+ !modelId.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+
+ var rest = modelId[Prefix.Length..];
+ var separator = rest.IndexOf(':');
+ if (separator <= 0 || separator >= rest.Length - 1)
+ {
+ return false;
+ }
+
+ providerId = rest[..separator];
+ apiModel = rest[(separator + 1)..];
+ return !string.IsNullOrWhiteSpace(providerId) && !string.IsNullOrWhiteSpace(apiModel);
+ }
+}
+
+public static class AiChatProjectStatuses
+{
+ public const string NotConfigured = "not-configured";
+ public const string NotConnected = "not-connected";
+ public const string Ready = "ready";
+}
diff --git a/src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs b/src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs
index 4699934..9e4f178 100644
--- a/src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs
+++ b/src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs
@@ -5,6 +5,14 @@
private static readonly IReadOnlyDictionary<string, string> ProviderAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["deepseek"] = "openai-compatible",
+ ["kimi"] = "openai-compatible",
+ ["moonshot"] = "openai-compatible",
+ ["bigmodel"] = "openai-compatible",
+ ["zhipu"] = "openai-compatible",
+ ["glm"] = "openai-compatible",
+ ["qwen"] = "openai-compatible",
+ ["dashscope"] = "openai-compatible",
+ ["tongyi"] = "openai-compatible",
["ollama"] = "openai-compatible",
["local-openai-compatible"] = "openai-compatible"
};
diff --git a/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs b/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
index 2b5c1cd..5700ec8 100644
--- a/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
+++ b/src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
@@ -24,7 +24,13 @@
LlmProviderRequest request,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
- using var httpRequest = new HttpRequestMessage(HttpMethod.Post, request.Model.Endpoint);
+ var chatUrl = request.Model.GetChatCompletionsUrl();
+ if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(chatUrl))
+ {
+ throw new LlmProviderException(LlmErrorCodes.RequestInvalid, "Model baseUrl must be an absolute HTTP or HTTPS URL.");
+ }
+
+ using var httpRequest = new HttpRequestMessage(HttpMethod.Post, chatUrl);
if (!string.IsNullOrWhiteSpace(request.ApiKey))
{
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.ApiKey);
@@ -91,6 +97,55 @@
yield return new LlmProviderChunk { IsCompleted = true };
}
+ public async Task<IReadOnlyList<string>> ListModelIdsAsync(
+ string baseUrl,
+ string? apiKey,
+ CancellationToken cancellationToken = default)
+ {
+ var modelsUrl = LlmOpenAiUrls.ToModelsUrl(baseUrl);
+ if (!LlmOpenAiUrls.IsAbsoluteHttpUrl(modelsUrl))
+ {
+ throw new LlmProviderException(LlmErrorCodes.RequestInvalid, "Provider baseUrl must be an absolute HTTP or HTTPS URL.");
+ }
+
+ using var httpRequest = new HttpRequestMessage(HttpMethod.Get, modelsUrl);
+ if (!string.IsNullOrWhiteSpace(apiKey))
+ {
+ httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
+ }
+
+ using var response = await _httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
+ if (!response.IsSuccessStatusCode)
+ {
+ throw new LlmProviderException(MapStatusCode(response.StatusCode), $"LLM provider returned {(int)response.StatusCode}.");
+ }
+
+ await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
+ using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (!document.RootElement.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Array)
+ {
+ return [];
+ }
+
+ return data.EnumerateArray()
+ .Select(ReadModelId)
+ .Where(id => !string.IsNullOrWhiteSpace(id))
+ .Select(id => id!)
+ .ToList();
+ }
+
+ private static string? ReadModelId(JsonElement item)
+ {
+ if (item.ValueKind == JsonValueKind.Object &&
+ item.TryGetProperty("id", out var id) &&
+ id.ValueKind == JsonValueKind.String)
+ {
+ return id.GetString();
+ }
+
+ return null;
+ }
+
private LlmProviderChunk? ParseChunk(string data)
{
using var document = JsonDocument.Parse(data);
diff --git a/src/Moli.Desktop/Management/ManagementWindow.xaml b/src/Moli.Desktop/Management/ManagementWindow.xaml
index 564c81f..848e0fc 100644
--- a/src/Moli.Desktop/Management/ManagementWindow.xaml
+++ b/src/Moli.Desktop/Management/ManagementWindow.xaml
@@ -59,14 +59,17 @@
</TabItem>
<TabItem Header="缁勪欢">
<DockPanel Margin="8">
- <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8">
- <ComboBox x:Name="WidgetSelector" Width="260" DisplayMemberPath="InstanceId" Margin="0,0,8,0" />
- <Button Content="鏄剧ず/闅愯棌" Width="96" Margin="0,0,8,0" Click="ToggleWidgetVisible_Click" />
- <Button Content="閿佸畾/瑙i攣" Width="96" Margin="0,0,8,0" Click="ToggleWidgetLocked_Click" />
- <Button x:Name="ClickThroughButton" Content="鐐瑰嚮绌块��" Width="96" Margin="0,0,8,0" Click="ToggleWidgetClickThrough_Click" />
- <ComboBox x:Name="DisplayLayerSelector" Width="132" Margin="0,0,8,0" />
- <Button Content="搴旂敤灞傜骇" Width="104" Margin="0,0,8,0" Click="ApplyDisplayLayer_Click" />
- </WrapPanel>
+ <StackPanel DockPanel.Dock="Top">
+ <WrapPanel Margin="0,0,0,8">
+ <ComboBox x:Name="WidgetSelector" Width="260" DisplayMemberPath="InstanceId" Margin="0,0,8,0" />
+ <Button Content="鏄剧ず/闅愯棌" Width="96" Margin="0,0,8,0" Click="ToggleWidgetVisible_Click" />
+ <Button Content="閿佸畾/瑙i攣" Width="96" Margin="0,0,8,0" Click="ToggleWidgetLocked_Click" />
+ <Button x:Name="ClickThroughButton" Content="鐐瑰嚮绌块��" Width="96" Margin="0,0,8,0" Click="ToggleWidgetClickThrough_Click" />
+ <ComboBox x:Name="DisplayLayerSelector" Width="132" Margin="0,0,8,0" />
+ <Button Content="搴旂敤灞傜骇" Width="104" Margin="0,0,8,0" Click="ApplyDisplayLayer_Click" />
+ </WrapPanel>
+ <TextBlock x:Name="WidgetSessionText" Margin="0,0,0,8" Foreground="#5B6573" TextWrapping="Wrap" />
+ </StackPanel>
<DataGrid x:Name="WidgetsGrid" AutoGenerateColumns="True" IsReadOnly="True">
<DataGrid.ContextMenu>
<ContextMenu>
@@ -77,6 +80,20 @@
</DataGrid>
</DockPanel>
</TabItem>
+ <TabItem Header="蹇嵎閿�">
+ <DockPanel Margin="8">
+ <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8">
+ <Button Content="鏂板" Width="88" Margin="0,0,8,0" Click="AddHotkey_Click" />
+ <Button Content="缂栬緫" Width="88" Margin="0,0,8,0" Click="EditHotkey_Click" />
+ <Button Content="鍒犻櫎" Width="88" Margin="0,0,8,0" Click="DeleteHotkey_Click" />
+ <Button Content="鍚敤/绂佺敤" Width="96" Margin="0,0,8,0" Click="ToggleHotkeyEnabled_Click" />
+ <Button Content="鎭㈠榛樿蹇嵎閿�" Width="128" Click="RestoreDefaultHotkeys_Click" />
+ </WrapPanel>
+ <TextBlock DockPanel.Dock="Bottom" Margin="0,8,0,0" TextWrapping="Wrap" Foreground="#5B6573"
+ Text="褰曞埗蹇嵎閿椂浼氭殏鏃舵敞閿�鍏ㄥ眬鐑敭锛岄伩鍏嶆姠閿�傚唴缃粦瀹氬彲鏀归敭鎴栫鐢紝浣嗕笉鑳藉垹闄ゃ��" />
+ <DataGrid x:Name="HotkeysGrid" AutoGenerateColumns="True" IsReadOnly="True" />
+ </DockPanel>
+ </TabItem>
<TabItem Header="鎻掍欢">
<DataGrid x:Name="PluginsGrid" Margin="8" AutoGenerateColumns="True" IsReadOnly="True">
<DataGrid.ContextMenu>
diff --git a/src/Moli.Desktop/Management/ManagementWindow.xaml.cs b/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
index f21754e..dd8643b 100644
--- a/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
+++ b/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
@@ -12,6 +12,7 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
@@ -19,6 +20,8 @@
using MessageBox = System.Windows.MessageBox;
using WpfButton = System.Windows.Controls.Button;
using WpfTextBox = System.Windows.Controls.TextBox;
+using WpfComboBox = System.Windows.Controls.ComboBox;
+using WpfCheckBox = System.Windows.Controls.CheckBox;
namespace Moli.Desktop.Management;
@@ -31,6 +34,7 @@
private readonly DesktopPaths _paths;
private readonly DispatcherTimer _timer;
private AppRuntimeState? _state;
+ private IReadOnlyList<HotkeyBindingStatus> _hotkeys = [];
private string? _selectedWidgetForDisplayLayer;
private bool _isRefreshing;
@@ -65,6 +69,7 @@
try
{
_state = await _runtime.GetStateAsync();
+ _hotkeys = await _runtime.GetHotkeyStatusesAsync();
var api = _apiStatus.GetStatus();
var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray();
var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null
@@ -86,6 +91,7 @@
WidgetSelector.ItemsSource = widgets;
WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
WidgetsGrid.ItemsSource = widgets;
+ HotkeysGrid.ItemsSource = _hotkeys.Select(HotkeyRow.From).ToArray();
SyncDisplayLayerSelector(force: _selectedWidgetForDisplayLayer != (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId);
PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
@@ -138,7 +144,7 @@
return;
}
- await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.IsVisible });
+ await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.LayoutIsVisible });
}
private async void ToggleWidgetLocked_Click(object sender, RoutedEventArgs e)
@@ -290,10 +296,12 @@
DisplayLayerSelector.SelectedItem = DisplayLayer.Desktop;
_selectedWidgetForDisplayLayer = null;
ClickThroughButton.Content = "鐐瑰嚮绌块��";
+ WidgetSessionText.Text = "閫夋嫨涓�涓粍浠跺悗鍙煡鐪嬫湰娆′細璇濆彲浜や簰鍜屾湁鏁堢┛閫忋��";
return;
}
ClickThroughButton.Content = widget.ClickThrough ? "鍏抽棴绌块��" : "寮�鍚┛閫�";
+ WidgetSessionText.Text = $"鏈浼氳瘽鍙氦浜掞細{(widget.IsInteractable ? "鏄�" : "鍚�")}锛涙湁鏁堢┛閫忥細{(widget.ClickThrough ? "鏄�" : "鍚�")}銆傜偣鍑荤┛閫忎細鍐欏叆 layout.json锛屽苟鍚屾鏈浼氳瘽瑕嗙洊锛屼娇绐楀彛绔嬪埢鍙偣鎴栫┛閫忋��";
if (!force)
{
@@ -458,7 +466,19 @@
private static string Html(string value) => System.Net.WebUtility.HtmlEncode(value);
- private sealed record WidgetRow(string InstanceId, string PluginId, string Bounds, string MonitorId, bool IsVisible, bool IsLocked, double Opacity, bool ClickThrough, DisplayLayer DisplayLayer)
+ private sealed record WidgetRow(
+ string InstanceId,
+ string PluginId,
+ string Bounds,
+ string MonitorId,
+ bool IsVisible,
+ bool LayoutIsVisible,
+ bool IsLocked,
+ double Opacity,
+ bool ClickThrough,
+ bool LayoutClickThrough,
+ bool IsInteractable,
+ DisplayLayer DisplayLayer)
{
public static WidgetRow From(WidgetRuntimeState state)
=> new(
@@ -467,10 +487,179 @@
$"{state.Bounds.X:0},{state.Bounds.Y:0} {state.Bounds.Width:0}x{state.Bounds.Height:0}",
state.MonitorId.Value,
state.IsVisible,
+ state.LayoutIsVisible,
state.IsLocked,
state.Opacity,
state.ClickThrough,
+ state.LayoutClickThrough,
+ state.IsInteractable,
state.DisplayLayer);
+ }
+
+ private async void AddHotkey_Click(object sender, RoutedEventArgs e)
+ => await EditHotkeyAsync(null);
+
+ private async void EditHotkey_Click(object sender, RoutedEventArgs e)
+ {
+ if (SelectedHotkey() is not { } row)
+ {
+ return;
+ }
+
+ await EditHotkeyAsync(row);
+ }
+
+ private async void DeleteHotkey_Click(object sender, RoutedEventArgs e)
+ {
+ if (SelectedHotkey() is not { } row)
+ {
+ return;
+ }
+
+ if (string.Equals(row.Source, "builtin", StringComparison.OrdinalIgnoreCase))
+ {
+ MessageBox.Show(this, "鍐呯疆蹇嵎閿笉鑳藉垹闄わ紝鍙兘鏀归敭銆佺鐢ㄦ垨鎭㈠榛樿銆�", "蹇嵎閿�", MessageBoxButton.OK, MessageBoxImage.Information);
+ return;
+ }
+
+ var document = CurrentHotkeysDocument();
+ document.Bindings.RemoveAll(binding => string.Equals(binding.Id, row.Id, StringComparison.OrdinalIgnoreCase));
+ await SaveHotkeysDocumentAsync(document);
+ }
+
+ private async void ToggleHotkeyEnabled_Click(object sender, RoutedEventArgs e)
+ {
+ if (SelectedHotkey() is not { } row)
+ {
+ return;
+ }
+
+ var document = CurrentHotkeysDocument();
+ var index = document.Bindings.FindIndex(binding => string.Equals(binding.Id, row.Id, StringComparison.OrdinalIgnoreCase));
+ if (index < 0)
+ {
+ return;
+ }
+
+ document.Bindings[index] = document.Bindings[index] with { Enabled = !document.Bindings[index].Enabled };
+ await SaveHotkeysDocumentAsync(document);
+ }
+
+ private async void RestoreDefaultHotkeys_Click(object sender, RoutedEventArgs e)
+ {
+ var result = await _runtime.RestoreDefaultHotkeysAsync();
+ if (!result.Succeeded)
+ {
+ MessageBox.Show(this, result.Message ?? "鎭㈠榛樿蹇嵎閿け璐ャ��", result.ErrorCode ?? "HotkeyRestoreFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
+ }
+
+ await RefreshAsync();
+ }
+
+ private HotkeyRow? SelectedHotkey() => HotkeysGrid.SelectedItem as HotkeyRow;
+
+ private HotkeysDocument CurrentHotkeysDocument()
+ => new()
+ {
+ SchemaVersion = 1,
+ Bindings = [.. _hotkeys.Select(item => item.Binding)]
+ };
+
+ private async Task EditHotkeyAsync(HotkeyRow? existing)
+ {
+ var plugins = _state?.Plugins.Select(plugin => plugin.Id.Value).Distinct().ToArray() ?? [];
+ var instances = _state?.Widgets.Select(widget => (widget.PluginId.Value, widget.InstanceId.Value)).ToArray() ?? [];
+ var dialog = new HotkeyEditorDialog(existing?.ToBinding(), plugins, instances, PauseRecordingAsync, ResumeRecordingAsync)
+ {
+ Owner = this
+ };
+ if (dialog.ShowDialog() != true || dialog.Result is null)
+ {
+ return;
+ }
+
+ var document = CurrentHotkeysDocument();
+ var index = document.Bindings.FindIndex(binding => string.Equals(binding.Id, dialog.Result.Id, StringComparison.OrdinalIgnoreCase));
+ if (index >= 0)
+ {
+ document.Bindings[index] = dialog.Result;
+ }
+ else
+ {
+ document.Bindings.Add(dialog.Result);
+ }
+
+ await SaveHotkeysDocumentAsync(document);
+ }
+
+ private async Task SaveHotkeysDocumentAsync(HotkeysDocument document)
+ {
+ var result = await _runtime.SaveHotkeysAsync(document);
+ if (!result.Succeeded)
+ {
+ MessageBox.Show(this, result.Message ?? "淇濆瓨蹇嵎閿け璐ャ��", result.ErrorCode ?? "HotkeySaveFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
+ }
+
+ await RefreshAsync();
+ }
+
+ private Task PauseRecordingAsync() => _runtime.PauseHotkeyRegistrationAsync();
+
+ private Task ResumeRecordingAsync() => _runtime.ResumeHotkeyRegistrationAsync();
+
+ private sealed record HotkeyRow(string Id, string Keys, string Action, string Target, bool Enabled, string Source, string Status)
+ {
+ public static HotkeyRow From(HotkeyBindingStatus status)
+ => new(
+ status.Binding.Id,
+ status.Binding.Keys,
+ status.Binding.Action,
+ FormatTarget(status.Binding.Target),
+ status.Binding.Enabled,
+ status.Binding.Source.ToString().ToLowerInvariant(),
+ status.Status);
+
+ public HotkeyBinding ToBinding()
+ {
+ var parts = Target.Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ string? pluginId = null;
+ string? instanceId = null;
+ foreach (var part in parts)
+ {
+ if (part.StartsWith("plugin:", StringComparison.OrdinalIgnoreCase))
+ {
+ pluginId = part["plugin:".Length..];
+ }
+ else if (part.StartsWith("instance:", StringComparison.OrdinalIgnoreCase))
+ {
+ instanceId = part["instance:".Length..];
+ }
+ }
+
+ return new HotkeyBinding
+ {
+ Id = Id,
+ Keys = Keys,
+ Action = Action,
+ Target = string.IsNullOrWhiteSpace(pluginId) && string.IsNullOrWhiteSpace(instanceId)
+ ? null
+ : new HotkeyTarget { PluginId = pluginId, InstanceId = instanceId },
+ Enabled = Enabled,
+ Source = string.Equals(Source, "builtin", StringComparison.OrdinalIgnoreCase) ? HotkeySource.Builtin : HotkeySource.User
+ };
+ }
+
+ private static string FormatTarget(HotkeyTarget? target)
+ {
+ if (target is null || target.IsEmpty)
+ {
+ return "";
+ }
+
+ var plugin = string.IsNullOrWhiteSpace(target.PluginId) ? "" : $"plugin:{target.PluginId}";
+ var instance = string.IsNullOrWhiteSpace(target.InstanceId) ? "" : $"instance:{target.InstanceId}";
+ return string.Join(" ", new[] { plugin, instance }.Where(item => item.Length > 0));
+ }
}
private sealed record PluginRow(string Id, string Name, string Type, string State, string? ErrorCode, string Entry)
@@ -485,6 +674,234 @@
=> new(entry.Timestamp, entry.Severity.ToString(), entry.Code, entry.Message);
}
+ private sealed class HotkeyEditorDialog : Window
+ {
+ private readonly WpfTextBox _keys;
+ private readonly WpfComboBox _action;
+ private readonly WpfComboBox _plugin;
+ private readonly WpfComboBox _instance;
+ private readonly WpfCheckBox _enabled;
+ private readonly HotkeyBinding? _existing;
+ private readonly Func<Task> _pauseAsync;
+ private readonly Func<Task> _resumeAsync;
+ private readonly (string PluginId, string InstanceId)[] _instances;
+ private bool _recording;
+
+ public HotkeyEditorDialog(
+ HotkeyBinding? existing,
+ IReadOnlyList<string> plugins,
+ IReadOnlyList<(string PluginId, string InstanceId)> instances,
+ Func<Task> pauseAsync,
+ Func<Task> resumeAsync)
+ {
+ _existing = existing;
+ _pauseAsync = pauseAsync;
+ _resumeAsync = resumeAsync;
+ _instances = instances.ToArray();
+ Title = existing is null ? "鏂板蹇嵎閿�" : "缂栬緫蹇嵎閿�";
+ Width = 420;
+ Height = 360;
+ WindowStartupLocation = WindowStartupLocation.CenterOwner;
+ ResizeMode = ResizeMode.NoResize;
+
+ _keys = new WpfTextBox { Text = existing?.Keys ?? "Ctrl+Shift+K", Margin = new Thickness(0, 0, 0, 8) };
+ _action = new WpfComboBox
+ {
+ ItemsSource = HotkeyActions.All.ToArray(),
+ SelectedItem = existing?.Action ?? HotkeyActions.WidgetToggleInteractable,
+ Margin = new Thickness(0, 0, 0, 8)
+ };
+ _plugin = new WpfComboBox
+ {
+ ItemsSource = plugins.ToArray(),
+ SelectedItem = existing?.Target?.PluginId ?? plugins.FirstOrDefault(),
+ Margin = new Thickness(0, 0, 0, 8)
+ };
+ _instance = new WpfComboBox { Margin = new Thickness(0, 0, 0, 8) };
+ _enabled = new WpfCheckBox { Content = "鍚敤", IsChecked = existing?.Enabled ?? true, Margin = new Thickness(0, 0, 0, 8) };
+ _plugin.SelectionChanged += (_, _) => RefreshInstances();
+ RefreshInstances();
+ if (!string.IsNullOrWhiteSpace(existing?.Target?.InstanceId))
+ {
+ _instance.SelectedItem = existing!.Target!.InstanceId;
+ }
+
+ var grid = new Grid { Margin = new Thickness(16) };
+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(88) });
+ grid.ColumnDefinitions.Add(new ColumnDefinition());
+ for (var i = 0; i < 7; i++)
+ {
+ grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
+ }
+
+ AddRow(grid, 0, "蹇嵎閿�", _keys);
+ var record = new WpfButton { Content = "褰曞埗", Width = 72, HorizontalAlignment = System.Windows.HorizontalAlignment.Left, Margin = new Thickness(0, 0, 0, 8) };
+ record.Click += async (_, _) => await ToggleRecordingAsync(record);
+ Grid.SetRow(record, 1);
+ Grid.SetColumn(record, 1);
+ grid.Children.Add(record);
+ AddRow(grid, 2, "鍔ㄤ綔", _action);
+ AddRow(grid, 3, "鎻掍欢", _plugin);
+ AddRow(grid, 4, "瀹炰緥", _instance);
+ Grid.SetRow(_enabled, 5);
+ Grid.SetColumn(_enabled, 1);
+ grid.Children.Add(_enabled);
+
+ var buttons = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right, Margin = new Thickness(0, 12, 0, 0) };
+ var ok = new WpfButton { Content = "纭畾", Width = 72, Margin = new Thickness(0, 0, 8, 0) };
+ var cancel = new WpfButton { Content = "鍙栨秷", Width = 72 };
+ ok.Click += async (_, _) =>
+ {
+ await StopRecordingAsync(record);
+ if (TryBuild())
+ {
+ DialogResult = true;
+ }
+ };
+ cancel.Click += async (_, _) =>
+ {
+ await StopRecordingAsync(record);
+ DialogResult = false;
+ };
+ buttons.Children.Add(ok);
+ buttons.Children.Add(cancel);
+ Grid.SetRow(buttons, 6);
+ Grid.SetColumnSpan(buttons, 2);
+ grid.Children.Add(buttons);
+ Content = grid;
+ PreviewKeyDown += OnPreviewKeyDown;
+ Closed += async (_, _) => await StopRecordingAsync(record);
+ }
+
+ public HotkeyBinding? Result { get; private set; }
+
+ private void RefreshInstances()
+ {
+ var pluginId = _plugin.SelectedItem as string;
+ var items = new List<string> { "" };
+ items.AddRange(_instances.Where(item => string.Equals(item.PluginId, pluginId, StringComparison.OrdinalIgnoreCase)).Select(item => item.InstanceId));
+ _instance.ItemsSource = items;
+ _instance.SelectedIndex = 0;
+ }
+
+ private async Task ToggleRecordingAsync(WpfButton button)
+ {
+ if (_recording)
+ {
+ await StopRecordingAsync(button);
+ return;
+ }
+
+ _recording = true;
+ button.Content = "鍋滄";
+ _keys.Text = "璇锋寜涓嬬粍鍚堥敭鈥�";
+ await _pauseAsync();
+ }
+
+ private async Task StopRecordingAsync(WpfButton button)
+ {
+ if (!_recording)
+ {
+ return;
+ }
+
+ _recording = false;
+ button.Content = "褰曞埗";
+ await _resumeAsync();
+ }
+
+ private void OnPreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
+ {
+ if (!_recording)
+ {
+ return;
+ }
+
+ e.Handled = true;
+ var key = e.Key == System.Windows.Input.Key.System ? e.SystemKey : e.Key;
+ if (key is System.Windows.Input.Key.LeftCtrl or System.Windows.Input.Key.RightCtrl
+ or System.Windows.Input.Key.LeftShift or System.Windows.Input.Key.RightShift
+ or System.Windows.Input.Key.LeftAlt or System.Windows.Input.Key.RightAlt
+ or System.Windows.Input.Key.LWin or System.Windows.Input.Key.RWin)
+ {
+ return;
+ }
+
+ var modifiers = new List<string>();
+ if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Control) != 0)
+ {
+ modifiers.Add("Ctrl");
+ }
+
+ if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Alt) != 0)
+ {
+ modifiers.Add("Alt");
+ }
+
+ if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Shift) != 0)
+ {
+ modifiers.Add("Shift");
+ }
+
+ if ((System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Windows) != 0)
+ {
+ modifiers.Add("Win");
+ }
+
+ if (modifiers.Count == 0)
+ {
+ _keys.Text = "闇�瑕佸寘鍚� Ctrl/Shift/Alt";
+ return;
+ }
+
+ modifiers.Add(key.ToString());
+ var chord = string.Join("+", modifiers);
+ if (!HotkeyChord.TryParse(chord, out var parsed, out _))
+ {
+ _keys.Text = "缁勫悎閿棤鏁�";
+ return;
+ }
+
+ _keys.Text = parsed.Canonical;
+ }
+
+ private bool TryBuild()
+ {
+ if (!HotkeyChord.TryParse(_keys.Text, out var chord, out var errorCode))
+ {
+ MessageBox.Show(this, "璇疯緭鍏ユ湁鏁堢粍鍚堥敭锛屼笉鑳藉彧鎸変慨楗伴敭銆�", errorCode ?? "HotkeyInvalidKeys", MessageBoxButton.OK, MessageBoxImage.Warning);
+ return false;
+ }
+
+ var action = _action.SelectedItem as string ?? HotkeyActions.WidgetToggleInteractable;
+ var pluginId = _plugin.SelectedItem as string;
+ var instanceId = _instance.SelectedItem as string;
+ Result = new HotkeyBinding
+ {
+ Id = _existing?.Id ?? $"user-{Guid.NewGuid():N}"[..16],
+ Keys = chord.Canonical,
+ Action = action,
+ Target = HotkeyActions.All.Contains(action) && (action.StartsWith("widget.", StringComparison.OrdinalIgnoreCase))
+ ? new HotkeyTarget { PluginId = pluginId, InstanceId = string.IsNullOrWhiteSpace(instanceId) ? null : instanceId }
+ : null,
+ Enabled = _enabled.IsChecked == true,
+ Source = _existing?.Source ?? HotkeySource.User
+ };
+ return true;
+ }
+
+ private static void AddRow(Grid grid, int row, string label, UIElement field)
+ {
+ var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(0, 0, 8, 8) };
+ Grid.SetRow(text, row);
+ Grid.SetColumn(text, 0);
+ Grid.SetRow(field, row);
+ Grid.SetColumn(field, 1);
+ grid.Children.Add(text);
+ grid.Children.Add(field);
+ }
+ }
+
private sealed class WidgetLayoutDialog : Window
{
private readonly WpfTextBox _x;
diff --git a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
index 13f1d1d..2fb8ffc 100644
--- a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
+++ b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -1,5 +1,6 @@
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Llm;
@@ -18,13 +19,17 @@
private readonly IRuntimeSurfaceController _surfaces;
private readonly DisplayChangeMonitor _displayMonitor;
private readonly ILlmGatewayService _llmGateway;
+ private readonly IHotkeyService _hotkeys;
private readonly SemaphoreSlim _lock = new(1, 1);
private AppSettingsDocument _settings = new();
+ private HotkeysDocument _hotkeyDocument = HotkeysDocument.CreateDefault();
private IReadOnlyList<PluginDescriptor> _pluginSnapshot = [];
private WallpaperRuntimeState _wallpaper = new();
private bool _isEditMode;
private bool _isGlobalLocked;
private bool _isSafeInputMode;
+ private readonly Dictionary<WidgetInstanceId, WidgetSessionOverlay> _sessions = [];
+ private int _hotkeyDispatching;
public DesktopRuntimeCoordinator(
IConfigurationService configuration,
@@ -35,7 +40,8 @@
IRuntimeEventBus events,
IRuntimeSurfaceController surfaces,
DisplayChangeMonitor displayMonitor,
- ILlmGatewayService llmGateway)
+ ILlmGatewayService llmGateway,
+ IHotkeyService hotkeys)
{
_configuration = configuration;
_plugins = plugins;
@@ -46,6 +52,8 @@
_surfaces = surfaces;
_displayMonitor = displayMonitor;
_llmGateway = llmGateway;
+ _hotkeys = hotkeys;
+ _hotkeys.HotkeyPressed += OnHotkeyPressedAsync;
}
public async Task<OperationResult<AppRuntimeState>> StartAsync(CancellationToken cancellationToken = default)
@@ -69,6 +77,10 @@
await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(layout), cancellationToken).ConfigureAwait(false);
}
+ _hotkeyDocument = await _configuration.LoadHotkeysAsync(cancellationToken).ConfigureAwait(false);
+ await ApplyIdleInteractableOverlaysAsync(cancellationToken).ConfigureAwait(false);
+ await _hotkeys.ReplaceBindingsAsync(_hotkeyDocument.Bindings, cancellationToken).ConfigureAwait(false);
+
_displayMonitor.DisplayChanged += () => OnDisplayTopologyChangedAsync();
_displayMonitor.Start();
@@ -88,6 +100,7 @@
await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
+ _hotkeys.UnregisterAll();
await SaveRuntimeSettingsAsync(cancellationToken).ConfigureAwait(false);
await _layout.SaveAsync(cancellationToken).ConfigureAwait(false);
await _surfaces.ShutdownAsync(cancellationToken).ConfigureAwait(false);
@@ -231,6 +244,11 @@
return OperationResult<WidgetRuntimeState>.Failure(result.ErrorCode ?? "WidgetLayoutUpdateFailed", result.Message ?? "Widget layout update failed.");
}
+ if (patch.ClickThrough is not null)
+ {
+ await SyncSessionInteractableToLayoutClickThroughAsync(result.Value, cancellationToken).ConfigureAwait(false);
+ }
+
await _surfaces.ApplyWidgetLayoutAsync(ToSurfaceLayout(result.Value), cancellationToken).ConfigureAwait(false);
await _layout.SaveAsync(cancellationToken).ConfigureAwait(false);
var runtimeState = ToWidgetRuntimeState(result.Value);
@@ -243,6 +261,72 @@
_lock.Release();
}
}
+
+ public Task<OperationResult<WidgetRuntimeState>> SetWidgetInteractableAsync(
+ WidgetInstanceId instanceId,
+ bool enabled,
+ CancellationToken cancellationToken = default)
+ => MutateWidgetSessionAsync(
+ instanceId,
+ (_, overlay) => overlay with { Interactable = enabled },
+ "widget.interactableChanged",
+ cancellationToken);
+
+ public Task<OperationResult<WidgetRuntimeState>> ToggleWidgetInteractableAsync(
+ WidgetInstanceId instanceId,
+ CancellationToken cancellationToken = default)
+ => MutateWidgetSessionAsync(
+ instanceId,
+ (_, overlay) => overlay with { Interactable = overlay.Interactable != true },
+ "widget.interactableChanged",
+ cancellationToken);
+
+ public Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> SetPluginWidgetsInteractableAsync(
+ PluginId pluginId,
+ bool enabled,
+ CancellationToken cancellationToken = default)
+ => MutatePluginWidgetSessionsAsync(
+ pluginId,
+ (_, overlay) => overlay with { Interactable = enabled },
+ "widget.interactableChanged",
+ cancellationToken);
+
+ public Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> TogglePluginWidgetsInteractableAsync(
+ PluginId pluginId,
+ CancellationToken cancellationToken = default)
+ => MutatePluginWidgetSessionsAsync(
+ pluginId,
+ (_, overlay) => overlay with { Interactable = overlay.Interactable != true },
+ "widget.interactableChanged",
+ cancellationToken);
+
+ public Task<OperationResult<WidgetRuntimeState>> SetWidgetSessionVisibleAsync(
+ WidgetInstanceId instanceId,
+ bool visible,
+ CancellationToken cancellationToken = default)
+ => MutateWidgetSessionAsync(
+ instanceId,
+ (_, overlay) => overlay with { Visible = visible },
+ "widget.sessionVisibleChanged",
+ cancellationToken);
+
+ public Task<OperationResult<WidgetRuntimeState>> ToggleWidgetSessionVisibleAsync(
+ WidgetInstanceId instanceId,
+ CancellationToken cancellationToken = default)
+ => MutateWidgetSessionAsync(
+ instanceId,
+ (layout, overlay) => overlay with { Visible = !WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible) },
+ "widget.sessionVisibleChanged",
+ cancellationToken);
+
+ public Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> TogglePluginWidgetsSessionVisibleAsync(
+ PluginId pluginId,
+ CancellationToken cancellationToken = default)
+ => MutatePluginWidgetSessionsAsync(
+ pluginId,
+ (layout, overlay) => overlay with { Visible = !WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible) },
+ "widget.sessionVisibleChanged",
+ cancellationToken);
public async Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default)
{
@@ -270,6 +354,63 @@
await _llmGateway.CancelPluginRequestsAsync(pluginId.Value, cancellationToken).ConfigureAwait(false);
}
+ public async Task<IReadOnlyList<HotkeyBindingStatus>> GetHotkeyStatusesAsync(CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ return BuildHotkeyStatuses();
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ public async Task<OperationResult<HotkeysDocument>> SaveHotkeysAsync(HotkeysDocument document, CancellationToken cancellationToken = default)
+ {
+ await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var validation = ValidateHotkeysDocument(document);
+ if (!validation.Succeeded)
+ {
+ return OperationResult<HotkeysDocument>.Failure(validation.ErrorCode ?? "HotkeyInvalidDocument", validation.Message ?? "Hotkeys document is invalid.");
+ }
+
+ await _configuration.SaveHotkeysAsync(document, cancellationToken).ConfigureAwait(false);
+ _hotkeyDocument = document;
+ await ApplyIdleInteractableOverlaysAsync(cancellationToken).ConfigureAwait(false);
+ await _hotkeys.ReplaceBindingsAsync(document.Bindings, cancellationToken).ConfigureAwait(false);
+ await _events.PublishAsync(new RuntimeEvent { Name = "hotkeys.changed", Payload = BuildHotkeyStatuses() }, cancellationToken).ConfigureAwait(false);
+ return OperationResult<HotkeysDocument>.Success(document);
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ public async Task<OperationResult<HotkeysDocument>> RestoreDefaultHotkeysAsync(CancellationToken cancellationToken = default)
+ {
+ var restored = HotkeysValidator.RestoreBuiltins(_hotkeyDocument);
+ return await SaveHotkeysAsync(restored, cancellationToken).ConfigureAwait(false);
+ }
+
+ public Task PauseHotkeyRegistrationAsync(CancellationToken cancellationToken = default)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _hotkeys.Pause();
+ return Task.CompletedTask;
+ }
+
+ public Task ResumeHotkeyRegistrationAsync(CancellationToken cancellationToken = default)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ _hotkeys.Resume();
+ return Task.CompletedTask;
+ }
+
private async Task<OperationResult<AppRuntimeState>> UpdateRuntimeFlagAsync(
string eventName,
Action update,
@@ -292,6 +433,78 @@
_lock.Release();
}
}
+
+ private async Task<OperationResult<WidgetRuntimeState>> MutateWidgetSessionAsync(
+ WidgetInstanceId instanceId,
+ Func<WidgetLayout, WidgetSessionOverlay, WidgetSessionOverlay> update,
+ string eventName,
+ CancellationToken cancellationToken)
+ {
+ await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var layout = _layout.Get(instanceId);
+ if (layout is null)
+ {
+ return OperationResult<WidgetRuntimeState>.Failure("WidgetNotFound", $"Widget '{instanceId.Value}' was not found.");
+ }
+
+ var overlay = update(layout, GetSession(instanceId));
+ _sessions[instanceId] = overlay;
+ await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false);
+ var runtimeState = ToWidgetRuntimeState(layout);
+ await _events.PublishAsync(new RuntimeEvent { Name = eventName, Payload = runtimeState }, cancellationToken).ConfigureAwait(false);
+ await PublishStatusAsync(BuildState(), cancellationToken).ConfigureAwait(false);
+ return OperationResult<WidgetRuntimeState>.Success(runtimeState);
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ private async Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> MutatePluginWidgetSessionsAsync(
+ PluginId pluginId,
+ Func<WidgetLayout, WidgetSessionOverlay, WidgetSessionOverlay> update,
+ string eventName,
+ CancellationToken cancellationToken)
+ {
+ await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ var layouts = _layout.GetAll()
+ .Where(layout => layout.PluginId.Equals(pluginId))
+ .ToArray();
+ if (layouts.Length == 0)
+ {
+ return OperationResult<IReadOnlyList<WidgetRuntimeState>>.Failure(
+ "WidgetInstanceNotFound",
+ $"No widget instances found for plugin '{pluginId.Value}'.");
+ }
+
+ var states = new List<WidgetRuntimeState>(layouts.Length);
+ foreach (var layout in layouts)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var overlay = update(layout, GetSession(layout.InstanceId));
+ _sessions[layout.InstanceId] = overlay;
+ await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false);
+ var runtimeState = ToWidgetRuntimeState(layout);
+ states.Add(runtimeState);
+ await _events.PublishAsync(new RuntimeEvent { Name = eventName, Payload = runtimeState }, cancellationToken).ConfigureAwait(false);
+ }
+
+ await PublishStatusAsync(BuildState(), cancellationToken).ConfigureAwait(false);
+ return OperationResult<IReadOnlyList<WidgetRuntimeState>>.Success(states);
+ }
+ finally
+ {
+ _lock.Release();
+ }
+ }
+
+ private WidgetSessionOverlay GetSession(WidgetInstanceId instanceId)
+ => _sessions.TryGetValue(instanceId, out var overlay) ? overlay : WidgetSessionOverlay.Empty;
private void ReconcileCurrentMonitors()
{
@@ -354,22 +567,294 @@
Entry = plugin.EntryUri.ToString()
};
- private WidgetRuntimeState ToWidgetRuntimeState(WidgetLayout layout) => new()
+ private WidgetRuntimeState ToWidgetRuntimeState(WidgetLayout layout)
{
- InstanceId = layout.InstanceId,
- PluginId = layout.PluginId,
- Bounds = layout.Bounds,
- MonitorId = layout.MonitorId,
- IsVisible = layout.IsVisible,
- IsLocked = _isGlobalLocked || layout.IsLocked,
- Opacity = layout.Opacity,
- ClickThrough = _isEditMode || _isSafeInputMode ? false : layout.ClickThrough,
- DisplayLayer = layout.DisplayLayer
- };
+ var overlay = GetSession(layout.InstanceId);
+ return new WidgetRuntimeState
+ {
+ InstanceId = layout.InstanceId,
+ PluginId = layout.PluginId,
+ Bounds = layout.Bounds,
+ MonitorId = layout.MonitorId,
+ IsVisible = WidgetSurfaceRules.ComputeVisible(overlay, layout.IsVisible),
+ LayoutIsVisible = layout.IsVisible,
+ IsLocked = _isGlobalLocked || layout.IsLocked,
+ Opacity = layout.Opacity,
+ ClickThrough = WidgetSurfaceRules.ComputeClickThrough(_isEditMode, _isSafeInputMode, overlay, layout.ClickThrough),
+ LayoutClickThrough = layout.ClickThrough,
+ IsInteractable = overlay.Interactable == true,
+ HasSessionInteractable = overlay.HasInteractableOverride,
+ DisplayLayer = layout.DisplayLayer
+ };
+ }
private WidgetLayout ToSurfaceLayout(WidgetLayout layout)
=> _isGlobalLocked ? layout with { IsLocked = true } : layout;
private static bool IsGeometryPatch(WidgetLayoutPatch patch)
=> patch.Bounds is not null || patch.MonitorId is not null || patch.Scale is not null;
+
+ private async Task OnHotkeyPressedAsync(HotkeyBinding binding)
+ {
+ if (Interlocked.CompareExchange(ref _hotkeyDispatching, 1, 0) != 0)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.HotkeyDropped,
+ "Dropped hotkey because a previous action is still running.",
+ new Dictionary<string, string> { ["id"] = binding.Id, ["keys"] = binding.Keys });
+ return;
+ }
+
+ try
+ {
+ await DispatchHotkeyActionAsync(binding).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.Win32InteropFailed,
+ "Hotkey dispatch failed.",
+ new Dictionary<string, string> { ["id"] = binding.Id, ["exception"] = ex.GetType().Name });
+ }
+ finally
+ {
+ Interlocked.Exchange(ref _hotkeyDispatching, 0);
+ }
+ }
+
+ private async Task DispatchHotkeyActionAsync(HotkeyBinding binding)
+ {
+ if (string.Equals(binding.Action, HotkeyActions.RuntimeToggleEditMode, StringComparison.OrdinalIgnoreCase))
+ {
+ var state = await GetStateAsync().ConfigureAwait(false);
+ await SetEditModeAsync(!state.IsEditMode).ConfigureAwait(false);
+ return;
+ }
+
+ if (string.Equals(binding.Action, HotkeyActions.RuntimeToggleSafeInputMode, StringComparison.OrdinalIgnoreCase))
+ {
+ var state = await GetStateAsync().ConfigureAwait(false);
+ await SetSafeInputModeAsync(!state.IsSafeInputMode).ConfigureAwait(false);
+ return;
+ }
+
+ if (string.Equals(binding.Action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase))
+ {
+ await DispatchWidgetHotkeyAsync(
+ binding,
+ ToggleWidgetInteractableAsync,
+ TogglePluginWidgetsInteractableAsync).ConfigureAwait(false);
+ return;
+ }
+
+ if (string.Equals(binding.Action, HotkeyActions.WidgetToggleVisible, StringComparison.OrdinalIgnoreCase))
+ {
+ await DispatchWidgetHotkeyAsync(
+ binding,
+ ToggleWidgetSessionVisibleAsync,
+ TogglePluginWidgetsSessionVisibleAsync).ConfigureAwait(false);
+ return;
+ }
+
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.HotkeyUnknownAction,
+ $"Unknown hotkey action '{binding.Action}'.",
+ new Dictionary<string, string> { ["id"] = binding.Id, ["action"] = binding.Action });
+ }
+
+ private async Task DispatchWidgetHotkeyAsync(
+ HotkeyBinding binding,
+ Func<WidgetInstanceId, CancellationToken, Task<OperationResult<WidgetRuntimeState>>> instanceAction,
+ Func<PluginId, CancellationToken, Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>>> pluginAction)
+ {
+ if (!string.IsNullOrWhiteSpace(binding.Target?.InstanceId))
+ {
+ var instanceId = new WidgetInstanceId(binding.Target.InstanceId);
+ var result = await instanceAction(instanceId, CancellationToken.None).ConfigureAwait(false);
+ if (!result.Succeeded)
+ {
+ RecordInvalidTarget(binding, result.Message);
+ }
+
+ return;
+ }
+
+ if (!string.IsNullOrWhiteSpace(binding.Target?.PluginId))
+ {
+ var pluginId = new PluginId(binding.Target.PluginId);
+ if (!IsPluginAvailable(pluginId))
+ {
+ RecordInvalidTarget(binding, $"Plugin '{pluginId.Value}' is not available.");
+ return;
+ }
+
+ var result = await pluginAction(pluginId, CancellationToken.None).ConfigureAwait(false);
+ if (!result.Succeeded)
+ {
+ RecordInvalidTarget(binding, result.Message);
+ }
+
+ return;
+ }
+
+ RecordInvalidTarget(binding, "Hotkey target is empty.");
+ }
+
+ private void RecordInvalidTarget(HotkeyBinding binding, string? message)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Warning,
+ DiagnosticCodes.HotkeyInvalidTarget,
+ message ?? "Hotkey target is invalid.",
+ new Dictionary<string, string>
+ {
+ ["id"] = binding.Id,
+ ["action"] = binding.Action,
+ ["pluginId"] = binding.Target?.PluginId ?? "",
+ ["instanceId"] = binding.Target?.InstanceId ?? ""
+ });
+ }
+
+ private async Task SyncSessionInteractableToLayoutClickThroughAsync(
+ WidgetLayout layout,
+ CancellationToken cancellationToken)
+ {
+ var overlay = GetSession(layout.InstanceId);
+ if (!overlay.HasInteractableOverride)
+ {
+ return;
+ }
+
+ overlay = overlay with { Interactable = !layout.ClickThrough };
+ _sessions[layout.InstanceId] = overlay;
+ await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false);
+ }
+
+ private async Task ApplyIdleInteractableOverlaysAsync(CancellationToken cancellationToken)
+ {
+ foreach (var binding in _hotkeyDocument.Bindings.Where(binding =>
+ binding.Enabled
+ && string.Equals(binding.Action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase)))
+ {
+ foreach (var layout in ResolveHotkeyTargets(binding.Target))
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var overlay = GetSession(layout.InstanceId);
+ if (overlay.HasInteractableOverride)
+ {
+ continue;
+ }
+
+ overlay = overlay with { Interactable = false };
+ _sessions[layout.InstanceId] = overlay;
+ await _surfaces.ApplyWidgetSessionOverlayAsync(layout, overlay, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ }
+
+ private IEnumerable<WidgetLayout> ResolveHotkeyTargets(HotkeyTarget? target)
+ {
+ if (target is null || target.IsEmpty)
+ {
+ return [];
+ }
+
+ var layouts = _layout.GetAll();
+ if (!string.IsNullOrWhiteSpace(target.InstanceId))
+ {
+ return layouts.Where(layout => layout.InstanceId.Value.Equals(target.InstanceId, StringComparison.OrdinalIgnoreCase));
+ }
+
+ return layouts.Where(layout => layout.PluginId.Value.Equals(target.PluginId, StringComparison.OrdinalIgnoreCase));
+ }
+
+ private IReadOnlyList<HotkeyBindingStatus> BuildHotkeyStatuses()
+ {
+ var registrations = _hotkeys.Registrations.ToDictionary(item => item.BindingId, StringComparer.OrdinalIgnoreCase);
+ var statuses = new List<HotkeyBindingStatus>(_hotkeyDocument.Bindings.Count);
+ foreach (var binding in _hotkeyDocument.Bindings)
+ {
+ var status = "registered";
+ string? detail = null;
+ if (!binding.Enabled)
+ {
+ status = "disabled";
+ }
+ else if (registrations.TryGetValue(binding.Id, out var registration))
+ {
+ status = registration.State switch
+ {
+ HotkeyRegistrationState.Conflict => "conflict",
+ HotkeyRegistrationState.Disabled => "disabled",
+ HotkeyRegistrationState.Invalid => "conflict",
+ _ => "registered"
+ };
+ detail = registration.Detail;
+ }
+
+ if (status == "registered" && IsWidgetHotkey(binding.Action) && !HasValidTarget(binding.Target))
+ {
+ status = "invalid-target";
+ }
+
+ statuses.Add(new HotkeyBindingStatus
+ {
+ Binding = binding,
+ Status = status,
+ Detail = detail
+ });
+ }
+
+ return statuses;
+ }
+
+ private static bool IsWidgetHotkey(string action)
+ => string.Equals(action, HotkeyActions.WidgetToggleInteractable, StringComparison.OrdinalIgnoreCase)
+ || string.Equals(action, HotkeyActions.WidgetToggleVisible, StringComparison.OrdinalIgnoreCase);
+
+ private bool HasValidTarget(HotkeyTarget? target)
+ {
+ if (target is null || target.IsEmpty)
+ {
+ return false;
+ }
+
+ if (!string.IsNullOrWhiteSpace(target.InstanceId))
+ {
+ return _layout.Get(new WidgetInstanceId(target.InstanceId)) is not null;
+ }
+
+ var pluginId = new PluginId(target.PluginId!);
+ return IsPluginAvailable(pluginId) && ResolveHotkeyTargets(target).Any();
+ }
+
+ private bool IsPluginAvailable(PluginId pluginId)
+ {
+ var plugin = _pluginSnapshot.FirstOrDefault(item => item.Id.Equals(pluginId));
+ return plugin is not null
+ && plugin.State is not PluginState.Disabled
+ and not PluginState.Invalid
+ and not PluginState.Removed
+ and not PluginState.Error;
+ }
+
+ private static OperationResult ValidateHotkeysDocument(HotkeysDocument document)
+ {
+ var validation = HotkeysValidator.Validate(document);
+ if (!validation.Succeeded)
+ {
+ return validation;
+ }
+
+ if (document.Bindings.All(binding =>
+ !string.Equals(binding.Id, HotkeysDocument.BuiltinPaletteToggleId, StringComparison.OrdinalIgnoreCase)))
+ {
+ return OperationResult.Failure("HotkeyBuiltinDeleteForbidden", "Built-in hotkeys cannot be deleted.");
+ }
+
+ return OperationResult.Success();
+ }
}
diff --git a/src/Moli.Desktop/Runtime/HotkeyService.cs b/src/Moli.Desktop/Runtime/HotkeyService.cs
new file mode 100644
index 0000000..4786864
--- /dev/null
+++ b/src/Moli.Desktop/Runtime/HotkeyService.cs
@@ -0,0 +1,421 @@
+using System.Windows;
+using System.Windows.Interop;
+using System.Windows.Threading;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Hotkeys;
+using Moli.Desktop.Interop;
+using Application = System.Windows.Application;
+
+namespace Moli.Desktop.Runtime;
+
+public sealed class Win32HotkeyApi : INativeHotkeyApi
+{
+ public bool Register(IntPtr hwnd, int id, uint modifiers, uint virtualKey, out int win32Error)
+ {
+ var succeeded = NativeMethods.RegisterHotKey(hwnd, id, modifiers, virtualKey);
+ win32Error = succeeded ? 0 : NativeMethods.GetLastError();
+ return succeeded;
+ }
+
+ public bool Unregister(IntPtr hwnd, int id)
+ => NativeMethods.UnregisterHotKey(hwnd, id);
+}
+
+/// <summary>
+/// Hidden top-level window that receives <c>WM_HOTKEY</c>. Message-only windows and
+/// thread-pool HWNDs never pump those messages, so this must be created on the WPF UI thread.
+/// </summary>
+public sealed class WpfHotkeyMessageWindow : IHotkeyMessageWindow
+{
+ private HwndSource? _source;
+
+ public IntPtr Handle => _source?.Handle ?? IntPtr.Zero;
+
+ public event Action<int>? HotkeyPosted;
+
+ public void EnsureCreated()
+ {
+ if (_source is not null)
+ {
+ return;
+ }
+
+ var parameters = new HwndSourceParameters("MoliHotkeyMonitor")
+ {
+ Width = 1,
+ Height = 1,
+ PositionX = -32000,
+ PositionY = -32000,
+ WindowStyle = unchecked((int)NativeMethods.WsPopup),
+ ExtendedWindowStyle = NativeMethods.WsExToolWindow | NativeMethods.WsExNoActivate
+ };
+ _source = new HwndSource(parameters);
+ _source.AddHook(WndProc);
+ }
+
+ public void Dispose()
+ {
+ if (_source is null)
+ {
+ return;
+ }
+
+ _source.RemoveHook(WndProc);
+ _source.Dispose();
+ _source = null;
+ }
+
+ private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
+ {
+ if (msg != NativeMethods.WmHotkey)
+ {
+ return IntPtr.Zero;
+ }
+
+ HotkeyPosted?.Invoke(wParam.ToInt32());
+ handled = true;
+ return IntPtr.Zero;
+ }
+}
+
+public sealed class HotkeyService : IHotkeyService
+{
+ private readonly IDiagnosticsService _diagnostics;
+ private readonly INativeHotkeyApi _api;
+ private readonly IHotkeyMessageWindow _window;
+ private readonly object _gate = new();
+ private readonly Dictionary<int, HotkeyBinding> _registered = [];
+ private readonly List<HotkeyRegistration> _registrations = [];
+ private IReadOnlyList<HotkeyBinding> _bindings = [];
+ private IntPtr _hwnd;
+ private bool _paused;
+ private bool _disposed;
+ private bool _subscribed;
+
+ public HotkeyService(
+ IDiagnosticsService diagnostics,
+ INativeHotkeyApi? api = null,
+ IHotkeyMessageWindow? messageWindow = null)
+ {
+ _diagnostics = diagnostics;
+ _api = api ?? new Win32HotkeyApi();
+ _window = messageWindow ?? new WpfHotkeyMessageWindow();
+ }
+
+ public event Func<HotkeyBinding, Task>? HotkeyPressed;
+
+ public IReadOnlyList<HotkeyRegistration> Registrations
+ {
+ get
+ {
+ lock (_gate)
+ {
+ return [.. _registrations];
+ }
+ }
+ }
+
+ public Task ReplaceBindingsAsync(IReadOnlyList<HotkeyBinding> bindings, CancellationToken cancellationToken = default)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ return RunOnUiAsync(() =>
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ lock (_gate)
+ {
+ EnsureMessageWindow();
+ UnregisterAllCore();
+ _bindings = bindings.ToArray();
+ if (!_paused)
+ {
+ RegisterAllCore();
+ }
+ else
+ {
+ _registrations.Clear();
+ foreach (var binding in _bindings)
+ {
+ _registrations.Add(ToPausedRegistration(binding));
+ }
+ }
+ }
+ });
+ }
+
+ public void Pause()
+ {
+ RunOnUi(() =>
+ {
+ lock (_gate)
+ {
+ if (_paused)
+ {
+ return;
+ }
+
+ _paused = true;
+ UnregisterAllCore();
+ _registrations.Clear();
+ foreach (var binding in _bindings)
+ {
+ _registrations.Add(ToPausedRegistration(binding));
+ }
+ }
+ });
+ }
+
+ public void Resume()
+ {
+ RunOnUi(() =>
+ {
+ lock (_gate)
+ {
+ if (!_paused)
+ {
+ return;
+ }
+
+ _paused = false;
+ EnsureMessageWindow();
+ RegisterAllCore();
+ }
+ });
+ }
+
+ public void UnregisterAll()
+ {
+ RunOnUi(() =>
+ {
+ lock (_gate)
+ {
+ UnregisterAllCore();
+ }
+ });
+ }
+
+ public void Dispose()
+ {
+ if (_disposed)
+ {
+ return;
+ }
+
+ _disposed = true;
+ RunOnUi(() =>
+ {
+ lock (_gate)
+ {
+ UnregisterAllCore();
+ if (_subscribed)
+ {
+ _window.HotkeyPosted -= OnHotkeyPosted;
+ _subscribed = false;
+ }
+
+ _window.Dispose();
+ _hwnd = IntPtr.Zero;
+ }
+ });
+ }
+
+ private void EnsureMessageWindow()
+ {
+ try
+ {
+ _window.EnsureCreated();
+ }
+ catch (InvalidOperationException ex)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Error,
+ DiagnosticCodes.HotkeyMessageWindowFailed,
+ "Failed to create the hotkey message window on the UI thread.",
+ new Dictionary<string, string> { ["exception"] = ex.Message });
+ }
+
+ _hwnd = _window.Handle;
+ if (_subscribed)
+ {
+ return;
+ }
+
+ _window.HotkeyPosted += OnHotkeyPosted;
+ _subscribed = true;
+ }
+
+ private void RegisterAllCore()
+ {
+ UnregisterAllCore();
+ if (_hwnd == IntPtr.Zero)
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Error,
+ DiagnosticCodes.HotkeyMessageWindowFailed,
+ "Hotkey message window handle is zero; WM_HOTKEY would never be delivered.");
+ foreach (var binding in _bindings)
+ {
+ _registrations.Add(new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = binding.Keys,
+ State = binding.Enabled ? HotkeyRegistrationState.Invalid : HotkeyRegistrationState.Disabled,
+ Detail = binding.Enabled ? DiagnosticCodes.HotkeyMessageWindowFailed : null
+ });
+ }
+
+ return;
+ }
+
+ var nextId = 1;
+ foreach (var binding in _bindings)
+ {
+ if (!binding.Enabled)
+ {
+ _registrations.Add(new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = binding.Keys,
+ State = HotkeyRegistrationState.Disabled
+ });
+ continue;
+ }
+
+ if (!HotkeyChord.TryParse(binding.Keys, out var chord, out var errorCode))
+ {
+ _registrations.Add(new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = binding.Keys,
+ State = HotkeyRegistrationState.Invalid,
+ Detail = errorCode
+ });
+ continue;
+ }
+
+ var id = nextId++;
+ if (_api.Register(_hwnd, id, chord.RegisterModifiers, chord.VirtualKey, out var win32Error))
+ {
+ _registered[id] = binding;
+ _registrations.Add(new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = chord.Canonical,
+ State = HotkeyRegistrationState.Registered
+ });
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.HotkeyRegistered,
+ $"Registered hotkey {chord.Canonical}.",
+ new Dictionary<string, string>
+ {
+ ["id"] = binding.Id,
+ ["keys"] = chord.Canonical,
+ ["hwnd"] = _hwnd.ToString("X")
+ });
+ continue;
+ }
+
+ var conflict = win32Error == NativeMethods.ErrorHotkeyAlreadyRegistered;
+ _registrations.Add(new HotkeyRegistration
+ {
+ BindingId = binding.Id,
+ Keys = chord.Canonical,
+ State = conflict ? HotkeyRegistrationState.Conflict : HotkeyRegistrationState.Invalid,
+ Detail = win32Error.ToString()
+ });
+ _diagnostics.Record(
+ conflict ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error,
+ conflict ? DiagnosticCodes.HotkeyConflict : DiagnosticCodes.Win32InteropFailed,
+ conflict
+ ? $"Hotkey {chord.Canonical} is already registered."
+ : $"Failed to register hotkey {chord.Canonical}.",
+ new Dictionary<string, string>
+ {
+ ["id"] = binding.Id,
+ ["keys"] = chord.Canonical,
+ ["win32Error"] = win32Error.ToString()
+ });
+ }
+ }
+
+ private void UnregisterAllCore()
+ {
+ foreach (var id in _registered.Keys.ToArray())
+ {
+ _api.Unregister(_hwnd, id);
+ if (_registered.TryGetValue(id, out var binding))
+ {
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.HotkeyUnregistered,
+ $"Unregistered hotkey {binding.Keys}.",
+ new Dictionary<string, string> { ["id"] = binding.Id, ["keys"] = binding.Keys });
+ }
+ }
+
+ _registered.Clear();
+ _registrations.Clear();
+ }
+
+ private static HotkeyRegistration ToPausedRegistration(HotkeyBinding binding)
+ => new()
+ {
+ BindingId = binding.Id,
+ Keys = binding.Keys,
+ State = HotkeyRegistrationState.Disabled,
+ Detail = "paused"
+ };
+
+ private void OnHotkeyPosted(int id)
+ {
+ HotkeyBinding? binding = null;
+ lock (_gate)
+ {
+ if (_registered.TryGetValue(id, out var found))
+ {
+ binding = found;
+ }
+ }
+
+ if (binding is null)
+ {
+ return;
+ }
+
+ _diagnostics.Record(
+ DiagnosticSeverity.Info,
+ DiagnosticCodes.HotkeyInvoked,
+ $"Hotkey {binding.Keys} invoked.",
+ new Dictionary<string, string> { ["id"] = binding.Id, ["keys"] = binding.Keys });
+
+ var handler = HotkeyPressed;
+ if (handler is not null)
+ {
+ _ = Task.Run(() => handler(binding));
+ }
+ }
+
+ private static void RunOnUi(Action action)
+ {
+ var dispatcher = Application.Current?.Dispatcher;
+ if (dispatcher is null || dispatcher.CheckAccess())
+ {
+ action();
+ return;
+ }
+
+ dispatcher.Invoke(action, DispatcherPriority.Send);
+ }
+
+ private static Task RunOnUiAsync(Action action)
+ {
+ var dispatcher = Application.Current?.Dispatcher;
+ if (dispatcher is null || dispatcher.CheckAccess())
+ {
+ action();
+ return Task.CompletedTask;
+ }
+
+ return dispatcher.InvokeAsync(action, DispatcherPriority.Send).Task;
+ }
+}
diff --git a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs b/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
index 47ba35f..fef9abe 100644
--- a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
+++ b/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
@@ -1,3 +1,4 @@
+using Moli.Desktop.Hotkeys;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
@@ -19,6 +20,35 @@
WidgetInstanceId instanceId,
WidgetLayoutPatch patch,
CancellationToken cancellationToken = default);
+ Task<OperationResult<WidgetRuntimeState>> SetWidgetInteractableAsync(
+ WidgetInstanceId instanceId,
+ bool enabled,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<WidgetRuntimeState>> ToggleWidgetInteractableAsync(
+ WidgetInstanceId instanceId,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> SetPluginWidgetsInteractableAsync(
+ PluginId pluginId,
+ bool enabled,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> TogglePluginWidgetsInteractableAsync(
+ PluginId pluginId,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<WidgetRuntimeState>> SetWidgetSessionVisibleAsync(
+ WidgetInstanceId instanceId,
+ bool visible,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<WidgetRuntimeState>> ToggleWidgetSessionVisibleAsync(
+ WidgetInstanceId instanceId,
+ CancellationToken cancellationToken = default);
+ Task<OperationResult<IReadOnlyList<WidgetRuntimeState>>> TogglePluginWidgetsSessionVisibleAsync(
+ PluginId pluginId,
+ CancellationToken cancellationToken = default);
Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default);
Task CancelPluginRequestsAsync(PluginId pluginId, CancellationToken cancellationToken = default);
+ Task<IReadOnlyList<HotkeyBindingStatus>> GetHotkeyStatusesAsync(CancellationToken cancellationToken = default);
+ Task<OperationResult<HotkeysDocument>> SaveHotkeysAsync(HotkeysDocument document, CancellationToken cancellationToken = default);
+ Task<OperationResult<HotkeysDocument>> RestoreDefaultHotkeysAsync(CancellationToken cancellationToken = default);
+ Task PauseHotkeyRegistrationAsync(CancellationToken cancellationToken = default);
+ Task ResumeHotkeyRegistrationAsync(CancellationToken cancellationToken = default);
}
diff --git a/src/Moli.Desktop/Runtime/IHotkeyService.cs b/src/Moli.Desktop/Runtime/IHotkeyService.cs
new file mode 100644
index 0000000..89a6ba7
--- /dev/null
+++ b/src/Moli.Desktop/Runtime/IHotkeyService.cs
@@ -0,0 +1,42 @@
+using Moli.Desktop.Hotkeys;
+
+namespace Moli.Desktop.Runtime;
+
+public enum HotkeyRegistrationState
+{
+ Registered,
+ Conflict,
+ Disabled,
+ Invalid
+}
+
+public sealed record HotkeyRegistration
+{
+ public required string BindingId { get; init; }
+ public required string Keys { get; init; }
+ public required HotkeyRegistrationState State { get; init; }
+ public string? Detail { get; init; }
+}
+
+public interface IHotkeyService : IDisposable
+{
+ event Func<HotkeyBinding, Task>? HotkeyPressed;
+ IReadOnlyList<HotkeyRegistration> Registrations { get; }
+ Task ReplaceBindingsAsync(IReadOnlyList<HotkeyBinding> bindings, CancellationToken cancellationToken = default);
+ void Pause();
+ void Resume();
+ void UnregisterAll();
+}
+
+public interface INativeHotkeyApi
+{
+ bool Register(IntPtr hwnd, int id, uint modifiers, uint virtualKey, out int win32Error);
+ bool Unregister(IntPtr hwnd, int id);
+}
+
+public interface IHotkeyMessageWindow : IDisposable
+{
+ IntPtr Handle { get; }
+ event Action<int>? HotkeyPosted;
+ void EnsureCreated();
+}
diff --git a/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs b/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
index 44699ce..e71842b 100644
--- a/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
+++ b/src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs
@@ -8,6 +8,7 @@
Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default);
Task ApplySafeInputModeAsync(bool enabled, CancellationToken cancellationToken = default);
Task ApplyWidgetLayoutAsync(WidgetLayout layout, CancellationToken cancellationToken = default);
+ Task ApplyWidgetSessionOverlayAsync(WidgetLayout layout, WidgetSessionOverlay overlay, CancellationToken cancellationToken = default);
Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default);
Task DisableWallpaperAsync(CancellationToken cancellationToken = default);
Task ShutdownAsync(CancellationToken cancellationToken = default);
diff --git a/src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs b/src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs
new file mode 100644
index 0000000..9cf3360
--- /dev/null
+++ b/src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs
@@ -0,0 +1,39 @@
+namespace Moli.Desktop.Runtime;
+
+/// <summary>In-memory per-widget overlay that never writes <c>layout.json</c>.</summary>
+public sealed record WidgetSessionOverlay
+{
+ public static WidgetSessionOverlay Empty { get; } = new();
+
+ public bool? Interactable { get; init; }
+ public bool? Visible { get; init; }
+
+ public bool HasInteractableOverride => Interactable is not null;
+ public bool HasVisibleOverride => Visible is not null;
+}
+
+/// <summary>Effective click-through / visibility rules used by runtime, surfaces and tests.</summary>
+public static class WidgetSurfaceRules
+{
+ public static bool ComputeClickThrough(
+ bool isEditMode,
+ bool isSafeInputMode,
+ WidgetSessionOverlay overlay,
+ bool layoutClickThrough)
+ {
+ if (isEditMode || isSafeInputMode)
+ {
+ return false;
+ }
+
+ if (overlay.Interactable is { } interactable)
+ {
+ return !interactable;
+ }
+
+ return layoutClickThrough;
+ }
+
+ public static bool ComputeVisible(WidgetSessionOverlay overlay, bool layoutVisible)
+ => overlay.Visible ?? layoutVisible;
+}
diff --git a/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs b/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
index e6f3e91..885b90e 100644
--- a/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
+++ b/src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
@@ -1,3 +1,4 @@
+using System.Net.Http;
using System.Text.Json;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Llm;
@@ -118,9 +119,14 @@
var projects = await _llmGateway.GetProjectsAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false);
return PluginBridgeResponse.Ok(request.Id ?? string.Empty, projects);
}
- catch (AiChatClientException ex)
+ catch (Exception ex) when (ex is AiChatClientException or HttpRequestException)
{
- return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
+ return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new AiChatProjectsResult
+ {
+ Status = AiChatProjectStatuses.NotConnected,
+ Message = ex.Message,
+ Projects = []
+ });
}
}
diff --git a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
index 68b4983..0e70893 100644
--- a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
+++ b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -29,6 +29,7 @@
private bool _editMode;
private bool _safeInputMode;
private IDisposable? _eventSubscription;
+ private readonly Dictionary<WidgetInstanceId, WidgetSessionOverlay> _sessions = [];
public RuntimeSurfaceController(
IPluginManager plugins,
@@ -114,7 +115,19 @@
window.SetMonitorInfo(monitor);
}
- window.ApplyLayout(layout, _editMode, _safeInputMode);
+ window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(layout.InstanceId));
+ });
+
+ public Task ApplyWidgetSessionOverlayAsync(WidgetLayout layout, WidgetSessionOverlay overlay, CancellationToken cancellationToken = default)
+ => OnUiThreadAsync(async () =>
+ {
+ _sessions[layout.InstanceId] = overlay;
+ if (!_widgets.TryGetValue(layout.InstanceId, out var window))
+ {
+ return;
+ }
+
+ await window.ApplySessionOverlayAsync(overlay, _editMode, _safeInputMode, cancellationToken).ConfigureAwait(true);
});
public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default)
@@ -181,6 +194,7 @@
}
_widgets.Clear();
+ _sessions.Clear();
foreach (var (_, wallpaper) in _wallpapers)
{
wallpaper.Close();
@@ -206,7 +220,7 @@
window.SetMonitorInfo(monitor);
}
- window.ApplyLayout(layout, _editMode, _safeInputMode);
+ window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(id));
}
return Task.CompletedTask;
@@ -272,7 +286,7 @@
window.SetMonitorInfo(monitor);
}
- window.ApplyLayout(layout, _editMode, _safeInputMode);
+ window.ApplyLayout(layout, _editMode, _safeInputMode, GetSession(window.InstanceId));
}
foreach (var (monitorId, wallpaper) in _wallpapers)
@@ -288,6 +302,9 @@
return Task.CompletedTask;
});
+ private WidgetSessionOverlay GetSession(WidgetInstanceId instanceId)
+ => _sessions.TryGetValue(instanceId, out var overlay) ? overlay : WidgetSessionOverlay.Empty;
+
private async Task CommitWidgetLayoutAsync(
WidgetInstanceId instanceId,
WidgetLayoutPatch patch,
@@ -301,7 +318,7 @@
{
foreach (var widget in _widgets.Values.Where(widget => widget.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
{
- widget.ApplyLayout(widget.CurrentLayout, _editMode, _safeInputMode);
+ widget.ApplyLayout(widget.CurrentLayout, _editMode, _safeInputMode, GetSession(widget.InstanceId));
}
}
diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
index d9041f3..4d6a24e 100644
--- a/src/Moli.Desktop/Windows/WidgetWindow.cs
+++ b/src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -51,6 +51,7 @@
private bool _resizing;
private DisplayLayer? _lastDisplayLayer;
private bool _desktopLayerAttached;
+ private WidgetSessionOverlay _session = WidgetSessionOverlay.Empty;
public WidgetWindow(
PluginDescriptor plugin,
@@ -117,7 +118,7 @@
public async Task LoadAsync(CancellationToken cancellationToken = default)
{
- ApplyLayout(_layout, _editMode, _safeInputMode);
+ ApplyLayout(_layout, _editMode, _safeInputMode, _session);
await _webView.InitializeAsync(new WebViewHostOptions
{
UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "widgets", _layout.InstanceId.Value),
@@ -132,21 +133,43 @@
await _webView.DispatchLifecycleEventAsync("moli:widget-loaded", ToRuntimeState(), cancellationToken).ConfigureAwait(true);
}
- public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode)
+ public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode, WidgetSessionOverlay? session = null)
{
_layout = layout;
_editMode = editMode;
_safeInputMode = safeInputMode;
+ if (session is not null)
+ {
+ _session = session;
+ }
+
Left = layout.Bounds.X;
Top = layout.Bounds.Y;
Width = layout.Bounds.Width;
Height = Math.Max(layout.Bounds.Height, _requestedHeight ?? layout.Bounds.Height);
Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0);
- Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden;
+ Visibility = WidgetSurfaceRules.ComputeVisible(_session, layout.IsVisible) ? Visibility.Visible : Visibility.Hidden;
Topmost = layout.DisplayLayer == DisplayLayer.GlobalTop;
_editBorder.Visibility = editMode ? Visibility.Visible : Visibility.Collapsed;
_resizeGrip.Visibility = editMode && !layout.IsLocked ? Visibility.Visible : Visibility.Collapsed;
ApplyWin32Styles();
+ }
+
+ public async Task ApplySessionOverlayAsync(
+ WidgetSessionOverlay overlay,
+ bool editMode,
+ bool safeInputMode,
+ CancellationToken cancellationToken = default)
+ {
+ var wasInteractable = _session.Interactable == true;
+ ApplyLayout(_layout, editMode, safeInputMode, overlay);
+ var enabled = overlay.Interactable == true;
+ if (enabled && !wasInteractable)
+ {
+ Activate();
+ }
+
+ await _webView.DispatchLifecycleEventAsync("moli:interactable-changed", new { enabled }, cancellationToken).ConfigureAwait(true);
}
public void ApplyRequestedSize(double? width, double? height)
@@ -164,7 +187,7 @@
public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
{
- ApplyLayout(_layout, enabled, _safeInputMode);
+ ApplyLayout(_layout, enabled, _safeInputMode, _session);
return _webView.DispatchLifecycleEventAsync("moli:edit-mode-changed", new { enabled }, cancellationToken);
}
@@ -294,10 +317,14 @@
PluginId = _layout.PluginId,
Bounds = _layout.Bounds,
MonitorId = _layout.MonitorId,
- IsVisible = _layout.IsVisible,
+ IsVisible = WidgetSurfaceRules.ComputeVisible(_session, _layout.IsVisible),
+ LayoutIsVisible = _layout.IsVisible,
IsLocked = _layout.IsLocked,
Opacity = _layout.Opacity,
- ClickThrough = _layout.ClickThrough,
+ ClickThrough = WidgetSurfaceRules.ComputeClickThrough(_editMode, _safeInputMode, _session, _layout.ClickThrough),
+ LayoutClickThrough = _layout.ClickThrough,
+ IsInteractable = _session.Interactable == true,
+ HasSessionInteractable = _session.HasInteractableOverride,
DisplayLayer = _layout.DisplayLayer
};
@@ -327,7 +354,9 @@
{
_interop.SetToolWindow(hwnd, true);
_interop.SetLayered(hwnd, true);
- _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
+ _interop.SetClickThrough(
+ hwnd,
+ WidgetSurfaceRules.ComputeClickThrough(_editMode, _safeInputMode, _session, _layout.ClickThrough));
var currentLayer = _layout.DisplayLayer;
var layerChanged = currentLayer != _lastDisplayLayer;
--
Gitblit v1.9.1