基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-14 b84db8983d63a9a981083ebce1a139860c6bdf25
commit
13个文件已添加
35个文件已修改
4124 ■■■■■ 已修改文件
docs/README.md 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/global-hotkeys.md 70 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/llm-command-palette-architecture.md 93 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/data/configuration-and-storage.md 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/moli-desktop.md 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.llm-command-palette.md 126 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/product/llm-command-palette-plugin-prd.md 38 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/qa/global-hotkeys-acceptance.md 37 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/index.html 118 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/plugin.json 77 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Configuration/JsonConfigurationServiceTests.cs 56 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs 105 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs 169 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs 311 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs 51 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/OpenAICompatibleAdapterTests.cs 59 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs 241 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs 17 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Configuration/ConfigurationDocuments.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Configuration/IConfigurationService.cs 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Configuration/JsonConfigurationService.cs 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Diagnostics/DiagnosticModels.cs 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DesktopHostBuilder.cs 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Hotkeys/HotkeyChord.cs 189 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Hotkeys/HotkeysDocument.cs 74 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Hotkeys/HotkeysValidator.cs 74 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/NativeMethods.cs 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Layout/Geometry.cs 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/ILlmServices.cs 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmGatewayService.cs 240 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmModelRegistry.cs 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmModels.cs 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmOpenAiUrls.cs 90 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs 8 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml.cs 421 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs 509 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/HotkeyService.cs 421 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IDesktopRuntime.cs 30 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IHotkeyService.cs 42 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IRuntimeSurfaceController.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WidgetWindow.cs 43 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
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)
## 当前运维文档
docs/architecture/global-hotkeys.md
New file
@@ -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
```
- 快捷键命令与托盘、管理窗口、本地 API 一样,只进入 `IDesktopRuntime`。
- `IRuntimeEventBus` 只做事后通知,不当命令总线。
- `HotkeyService` 只负责 `RegisterHotKey` / `UnregisterHotKey` 和 `WM_HOTKEY` 消息窗口,不解析业务动作。
- 插件不开放 `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` 也会空闲穿透。管理窗口或本地 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
docs/architecture/llm-command-palette-architecture.md
@@ -10,13 +10,14 @@
- 插件前端只负责输入、模型选择和流式渲染。
- 插件前端只传 `mode`、`projectId`、`modelId`、`messages` 和请求参数,不直接传 provider、endpoint、API key、AiChat 密码或 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 不进入插件前端资源、manifest 示例或普通日志。
- 插件运行模式由配置决定:
  - `provider-direct`:沿用当前供应商直连链路,并可调用 AiChat 记忆接口管理/召回记忆。
  - `aichat-api`:通过自有 AiChat API 登录、读取项目、发送聊天和订阅 SSE;插件侧不处理记忆。
- AiChat 统一 Host 默认固定为 `http://192.168.1.111:13000`,不从 AiChat 接口文档的环境表推导。
  - `provider-direct`:沿用当前供应商直连链路;仅在已配置 AiChat 账号时调用记忆接口。
  - `aichat-api`:通过自有 AiChat API 登录、读取项目、发送聊天和订阅 SSE;插件侧不处理记忆。AiChat 账号与项目均为可选。
- 提供商可配置 `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`、API key 或其他敏感配置。管理窗口可以在受控 UI 中展示和编辑 endpoint,但插件前端不需要知道。
默认不返回 `baseUrl`、`endpoint`、`authRef`、API 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`,tooltip 为原因 | 已尝试登录但失败 |
| `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` |
密码解析顺序:
@@ -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` |
docs/data/configuration-and-storage.md
@@ -24,13 +24,14 @@
## 配置文件
MVP 本地配置包含 3 个 JSON 文件。
MVP 本地配置包含 4 个 JSON 文件。
| 文件 | 负责内容 | 默认行为 |
| --- | --- | --- |
| `appsettings.json` | 启动项、API 端口、运行模式持久状态 | 缺失时生成默认值 |
| `plugins.json` | 插件启用/禁用状态注册表 | 缺失时生成空列表,并由默认内容安装器补样例插件 |
| `layout.json` | 显示器快照和 widget 实例布局 | 缺失时生成空布局,并由默认内容安装器补样例 widget |
| `hotkeys.json` | 全局快捷键绑定 | 缺失时生成带默认 `Ctrl+Shift+K` 绑定的文档 |
所有配置文档包含 `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`。
docs/ops/user-manual/moli-desktop.md
@@ -111,11 +111,31 @@
| --- | --- |
| 状态 | 运行模式、API 状态、壁纸状态、WebView2 初始化状态和最近诊断 |
| 壁纸 | 当前壁纸启用状态、暂停状态、透明度、点击穿透状态 |
| 组件 | 小组件实例列表,可选择组件并显示/隐藏或锁定/解锁 |
| 组件 | 小组件实例列表,可选择组件并显示/隐藏或锁定/解锁。展示「本次会话可交互 / 有效穿透」;「点击穿透」按有效穿透切换,写入 `layout.json` 并同步会话覆盖 |
| 快捷键 | 管理全局快捷键:改键、启用、新增、删除用户绑定、恢复默认。录制时会暂时注销已注册热键 |
| 插件 | 已扫描插件的名称、类型、状态、入口和错误码 |
| 诊断 | 诊断记录和插件 manifest 错误摘要 |
| Log | 加载当天日志,并随管理窗口刷新周期显示新增日志 |
## 全局快捷键
默认绑定:
| 快捷键 | 动作 | 目标 |
| --- | --- | --- |
| `Ctrl+Shift+K` | 切换会话可交互 | `sample.llm-command-palette` |
规则:
- 空闲态:窗口常显,点击穿透,桌面图标可点。
- 再按一次同一快捷键才退出可交互;点击桌面失焦不会自动退出。
- 热键导致的可交互/会话显隐不写 `layout.json`,重启后回到空闲穿透。
- 绑定本身保存在 `%AppData%\DesktopEnhancer\config\hotkeys.json`。
- 管理窗口「组件」页的点击穿透按**有效穿透**切换:写入 `layout.json`,并同步本次会话覆盖,窗口会立刻可点或穿透。
- 系统已占用的组合键会在快捷键列表标为冲突;录制新键时先暂停全部热键,避免抢键。
- 内置绑定可改键或禁用,不能删除;「恢复默认快捷键」只重置内置绑定。
- 不要使用 `Alt+Space`。插件不能自己注册全局热键。
## 通用组件操作
小组件来自本地 HTML 插件。每个小组件都可以通过管理窗口进行显示、隐藏、锁定和解锁。
docs/ops/user-manual/plugins/sample.llm-command-palette.md
@@ -35,6 +35,19 @@
| 换行方式 | Shift+Enter |
| 输出区域 | 输入框底部展开,最大高度约为屏幕高度 `50%` |
## 全局快捷键与聚焦
宿主默认用 `Ctrl+Shift+K` 切换本插件的会话可交互,不写 `layout.json`。
| 状态 | 行为 |
| --- | --- |
| 空闲穿透 | 输入条常显,鼠标点击会穿过窗口,桌面图标可点 |
| 可交互 | 窗口可点,输入框自动获得焦点,可直接打字并 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 但登录或拉取项目失败,tooltip 含原因 |
| `No project` | 已连接但项目列表为空;可不选项目就提问 |
在自有 API 模式下,提交会携带当前项目 ID。未选择项目时,AiChat 会按自身接口规则使用或创建默认项目,但建议明确选择项目。
在自有 API 模式下,提交会携带当前项目 ID(可空)。未选择项目时,AiChat 会按自身接口规则处理。项目不是必填项。
项目和模型下拉使用插件自绘的圆角扁平控件。展开下拉时,输入条会临时请求宿主增高组件窗口,避免选项列表被原始组件高度裁剪;选择完成或点击外部后会恢复到默认高度。
## 记忆管理
供应商直连模式下,插件可以使用 AiChat 记忆接口:
供应商直连模式下,**仅在已配置 AiChat 账号**时可以使用记忆接口。未配置时记忆按钮不可用,宿主不会调用记忆查询/创建/删除/召回。
| 操作 | 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` 或你的实际配置。
- 检查账号和密码环境变量是否正确。
- 调用 AiChat `GET /api/auth/me` 确认账号已审批。
- 调用 AiChat `GET /api/projects` 确认账号有项目。
- `Not configured`:在插件配置中填写非空的 `aichat.account.email`。仅有默认 AiChat `baseUrl` 不会登录。
- `Not connected`:检查账号、密码环境变量和 AiChat 服务是否可达;tooltip 会显示失败原因。
- 这两种状态下都可以用提供商或自定义模型直连提问。
### 自有 API 模式无法输出
@@ -305,16 +346,17 @@
### 请求提示 endpoint 不可达
- 确认 `endpoint` 地址正确。
- 确认 `baseUrl` 正确,聊天实际请求 `{baseUrl}/chat/completions`。
- 如果是本地模型服务,确认服务已启动并监听对应端口。
- 如果是远程供应商,确认当前网络可访问该供应商 API。
- 检查日志目录 `%LocalAppData%\DesktopEnhancer\logs`,日志只会记录 endpoint host,不会记录完整 API key。
- 检查日志目录 `%LocalAppData%\DesktopEnhancer\logs`,日志只会记录 host,不会记录完整 API key。
### 记忆功能不可用
- 记忆管理只在供应商直连模式下由插件处理。
- 未配置 AiChat 账号时记忆入口不可用,这是预期行为。
- 记忆管理只在供应商直连模式且已配置 AiChat 时由插件处理。
- 检查 AiChat 当前用户是否有 `canUseMemory`、`canViewMemory` 或 `canManageMemory` 权限。
- 项目记忆必须选择项目后使用。
- 有项目时记忆走 PROJECT,无项目时走 GLOBAL。
### 没有流式输出
docs/product/llm-command-palette-plugin-prd.md
@@ -188,20 +188,20 @@
## 模型配置
插件配置必须显式区分运行模式。插件前端只需要知道可展示的项目、模型清单和默认模型。具体供应商、endpoint、鉴权方式、AiChat 登录态和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `mode`、`projectId`、`modelId` 和消息内容。
插件配置必须显式区分运行模式。插件前端只需要知道可展示的项目、模型清单和默认模型。具体供应商、`baseUrl`、鉴权方式、AiChat 登录态和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `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 按接口规则使用或创建默认项目,但 UI 应尽量选择明确项目。
- 切换到 `aichat-api` 后,若已配置账号则登录 AiChat 并获取项目列表;未配置则项目显示 `Not configured`,不登录。
- `aichat-api` 模式下提交消息时应传入当前 `projectId`(可空);项目不是必填项。
- 两种模式都不得把密码、Session Token、供应商 API key 暴露给插件页面日志或可复制错误信息。
### AiChat 用户配置
@@ -250,7 +250,7 @@
4. 可选调用 `GET /api/auth/me` 校验审批状态、记忆权限和项目权限。
5. Session 过期或返回 `401` 时重新登录一次;仍失败则在插件输出区展示可操作错误。
推荐采用“按模型路由”的配置结构:每个模型都可以绑定独立 provider、URL、鉴权引用和请求适配参数。这样同一个插件可以同时接入不同供应商,也可以接入同一供应商的不同 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` 或公开配置中。MVP 建议由宿主提供本地 LLM 代理能力,插件只向宿主请求流式生成;宿主再根据 `modelId` 找到 provider、endpoint、authRef 和 apiModel 并调用对应供应商。如果短期直接从插件调用远程 endpoint,则必须在文档和管理界面中明确提示密钥暴露风险,并仅用于本地个人测试。
API key 不应存放在前端 `index.html` 或公开配置中。MVP 建议由宿主提供本地 LLM 代理能力,插件只向宿主请求流式生成;宿主再根据 `modelId` 找到 provider、`baseUrl`、authRef 和 apiModel 并调用对应供应商。如果短期直接从插件调用远程接口,则必须在文档和管理界面中明确提示密钥暴露风险,并仅用于本地个人测试。
### 路由策略
@@ -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、endpoint 或密钥。宿主响应中可返回本次请求实际命中的供应商和模型,用于诊断和 UI tooltip,但不返回密钥。
插件不应直接传 provider、`baseUrl` 或密钥。宿主响应中可返回本次请求实际命中的供应商和模型,用于诊断和 UI tooltip,但不返回密钥。
新增 AiChat 相关桥接能力建议:
@@ -484,17 +484,17 @@
### FR-LLM-08 AiChat 项目下拉
- 输入框左侧必须提供 AiChat 项目下拉列表。
- 项目列表必须调用 AiChat `GET /api/projects` 获取。
- 登录失败、账号未审批、无权限或接口不可达时,项目下拉必须展示可理解降级状态。
- 自有 API 模式下提交聊天时必须使用当前选中项目;未选项目时允许按 AiChat 默认项目规则降级。
- 项目列表必须调用 AiChat `GET /api/projects` 获取;未配置账号时返回 `not-configured`,不得登录。
- 登录失败、账号未审批、无权限或接口不可达时,项目下拉必须展示 `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、endpoint、真实上游模型名和启用状态。
- 宿主应根据 `modelId` 路由到对应 provider 适配器,并调用该模型自己的 endpoint。
- 每个模型必须能够配置独立的 provider、`baseUrl`、真实上游模型名和启用状态。
- 宿主应根据 `modelId` 路由到对应 provider 适配器,并调用 `{baseUrl}/chat/completions`。
- API key 不得写死在插件前端资源中。
- API key 应以 `authRef` 形式引用宿主侧密钥存储或用户环境配置。
- 如果宿主暂未提供密钥安全存储,MVP 必须将该能力标记为受限,并提供清晰风险提示。
docs/qa/global-hotkeys-acceptance.md
New file
@@ -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、hotkeys.json 默认/损坏恢复/round-trip、校验(重复 chord、非法 keys、未知动作、空 target、builtin 不可删)、RegisterHotKey 冲突跳过、Pause/Resume。
## 非目标
- 插件自行注册全局热键
- `WH_KEYBOARD_LL` 键盘钩子
- 失焦自动退出
- 默认绑定使用 `Alt+Space`
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) {
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": []
  }
}
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"));
src/Moli.Desktop.Tests/Hotkeys/HotkeyChordTests.cs
New file
@@ -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");
    }
}
src/Moli.Desktop.Tests/Hotkeys/HotkeyServiceTests.cs
New file
@@ -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];
}
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());
        }
    }
}
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();
src/Moli.Desktop.Tests/Llm/LlmOpenAiUrlsTests.cs
New file
@@ -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 _));
}
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")
            });
        }
    }
}
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());
src/Moli.Desktop.Tests/Runtime/WidgetSurfaceRulesTests.cs
New file
@@ -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));
    }
}
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 });
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();
}
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);
}
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)
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
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>();
src/Moli.Desktop/Hotkeys/HotkeyChord.cs
New file
@@ -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();
    }
}
src/Moli.Desktop/Hotkeys/HotkeysDocument.cs
New file
@@ -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
    };
}
src/Moli.Desktop/Hotkeys/HotkeysValidator.cs
New file
@@ -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);
}
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);
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;
}
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
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
            });
    }
}
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,
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; }
src/Moli.Desktop/Llm/LlmOpenAiUrls.cs
New file
@@ -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";
}
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"
    };
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);
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="锁定/解锁" 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="锁定/解锁" 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>
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;
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();
    }
}
src/Moli.Desktop/Runtime/HotkeyService.cs
New file
@@ -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;
    }
}
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);
}
src/Moli.Desktop/Runtime/IHotkeyService.cs
New file
@@ -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();
}
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);
src/Moli.Desktop/Runtime/WidgetSessionOverlay.cs
New file
@@ -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;
}
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 = []
            });
        }
    }
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));
        }
    }
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;