基于WebView2实现的Win11桌面框架,利用插件自定义
ddd6889459bccf5015cd0c9629cdf4f4ce8fb8e1..4df6165fa93c7caeea86385312415e312de4d11f
2026-05-05 Moli
暂存
4df616 对比 | 目录
2026-05-04 Moli
增加LLM对话插件
b3bde9 对比 | 目录
26个文件已添加
30个文件已修改
1 文件已重命名
6836 ■■■■■ 已修改文件
.ai/agents/dev-agent.md 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.ai/agents/product-agent.md 3 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.ai/agents/qa-agent.md 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.ai/workflows/dev-workflow.md 40 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/README.md 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/detailed-design.md 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/llm-command-palette-architecture.md 900 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/architecture/runtime-architecture.md 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/data/configuration-and-storage.md 6 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/development/llm-command-palette-aichat-mode-task-breakdown.md 156 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual.md 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/moli-desktop.md 49 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.audio-visualizer.md 77 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.clock.md 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.llm-command-palette.md 331 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.system-info.md 58 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.wallpaper.md 59 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/ops/user-manual/plugins/sample.webview-test.md 47 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/product/desktop-enhancement-prd.md 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/product/llm-command-palette-plugin-prd.md 292 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/qa/display-layer-acceptance-2026-05-03.md 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/qa/llm-command-palette-acceptance-2026-05-04.md 65 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/qa/llm-command-palette-aichat-mode-acceptance-2026-05-04.md 57 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/demo.html 491 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/index.html 687 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/plugin.json 104 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/publish-to-apps.ps1 80 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Layout/LayoutManagerTests.cs 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/AiChatClientTests.cs 165 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs 217 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs 87 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs 184 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs 79 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Diagnostics/DiagnosticsService.cs 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DefaultContentInstaller.cs 39 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DesktopHostBuilder.cs 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Host/DesktopPaths.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/NativeMethods.cs 5 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/Win32InteropService.cs 20 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs 54 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Layout/LayoutManager.cs 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/AiChatClient.cs 621 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/EnvironmentCredentialStore.cs 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/ILlmServices.cs 109 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmGatewayService.cs 356 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmModelRegistry.cs 205 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmModels.cs 223 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs 139 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml 16 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml.cs 127 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/RuntimeState.cs 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs 306 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/PluginBridgeScript.cs 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/WebViewHost.cs 40 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs 77 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WidgetWindow.cs 21 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.ai/agents/dev-agent.md
@@ -17,6 +17,7 @@
- 模块或插件实现
- 配置文件、接口定义和必要脚本
- 本地运行说明
- 功能或插件开发/调整后的用户操作手册更新,优先维护 `docs/product/user-manual.md` 与 `docs/product/user-manual/`
- 变更说明
- 已执行的验证命令和结果
@@ -26,7 +27,7 @@
- 当发现现有架构无法支撑需求或需要调整模块边界时,调用 `architect-agent`。
- 当涉及持久化结构、配置 schema 或数据迁移时,调用 `dba-agent`。
- 当需要测试用例、验收验证或缺陷复现时,调用 `qa-agent`。
- 当功能或插件变更影响安装、启动、配置、交互、故障排查或用户可见限制时,在提交给 QA 前补充或更新操作手册;如无用户可见变化,在实现说明中注明无需更新手册的原因。
- 当需要生成或修改代码时,使用 `codegen-skill`。
- 当开发插件、插件协议或插件配置能力时,使用 `plugin-skill`。
- 当定位运行错误、构建失败、WebView2 异常或窗口行为问题时,使用 `debug-skill`。
.ai/agents/product-agent.md
@@ -19,6 +19,7 @@
- 功能优先级
- 非功能需求
- 验收标准
- 用户操作手册影响范围,说明新增或调整的用户流程、配置项、限制和故障排查信息
- 待澄清问题清单
## decision
@@ -27,6 +28,6 @@
- 当需求需要拆解为开发任务、代码生成或接口定义时,调用 `dev-agent`。
- 当需求涉及配置持久化、插件数据结构、迁移或存储策略时,调用 `dba-agent`。
- 当需求需要验收标准、测试矩阵或回归策略时,调用 `qa-agent`。
- 当需求会改变用户可见的功能、插件操作、配置或限制时,要求后续开发完成后同步更新操作手册。
- 当需要整理 PRD 时,使用 `prd-skill`。
- 当需求与插件能力、插件规范或桌面挂件体验相关时,使用 `plugin-skill`。
.ai/agents/qa-agent.md
@@ -9,6 +9,7 @@
- Product Agent 输出的验收标准
- Architect Agent 输出的架构和风险点
- Dev Agent 输出的实现说明、运行方式和变更清单
- 功能或插件变更对应的用户操作手册更新,或无需更新手册的说明
- 缺陷报告、日志、截图、录屏或用户反馈
## output
@@ -18,6 +19,7 @@
- 验收结果
- 缺陷报告
- 回归测试清单
- 用户操作手册一致性检查结果
- 发布风险评估
## decision
@@ -25,7 +27,7 @@
- 当验收标准不明确或测试期望与需求冲突时,调用 `product-agent`。
- 当问题可能源于架构设计、模块边界或技术方案时,调用 `architect-agent`。
- 当需要修复缺陷、补充日志或增加可测试性代码时,调用 `dev-agent`。
- 当功能或插件已变更但操作手册缺失、过期或与实际行为不一致时,退回 `dev-agent` 或 `product-agent` 补充手册。
- 当问题涉及配置读写、迁移、历史数据兼容或默认值时,调用 `dba-agent`。
- 当设计测试矩阵、测试脚本或验收命令时,使用 `test-skill`。
- 当复现和定位缺陷时,使用 `debug-skill`。
.ai/workflows/dev-workflow.md
@@ -15,16 +15,19 @@
  Product["Product\nproduct-agent + prd-skill"]
  Architect["Architect\narchitect-agent + arch-skill + plugin-skill"]
  Dev["Dev\ndev-agent + codegen-skill + plugin-skill + debug-skill"]
  Docs["Manual Update\ndev-agent + product-agent"]
  QA["QA\nqa-agent + test-skill + debug-skill"]
  Review["Review\nall agents"]
  Product --> Architect
  Architect --> Dev
  Dev --> QA
  Dev --> Docs
  Docs --> QA
  QA --> Review
  Review --> Product
  Review --> Architect
  Review --> Dev
  Review --> Docs
```
## steps
@@ -44,6 +47,7 @@
  - PRD
  - user stories
  - acceptance criteria
  - user manual impact scope when the change affects user-visible flows
  - open questions
- next:
  - send PRD to `architect-agent`
@@ -84,9 +88,28 @@
  - local verification results
  - implementation notes
- next:
  - send completed implementation and verification notes to `qa-agent`
  - send completed implementation and verification notes to Manual Update
### 4. QA
### 4. Manual Update
- agent:
  - `dev-agent` for implementation-aligned operation steps
  - `product-agent` when the wording, user scenario, or product boundary needs clarification
- skills:
  - `plugin-skill` when updating plugin operation docs
  - `prd-skill` when user-facing behavior or positioning needs product confirmation
- input:
  - completed code, configuration, script, or plugin changes from `dev-agent`
  - PRD acceptance criteria and user scenarios from `product-agent`
  - existing user manual files under `docs/product/user-manual.md` and `docs/product/user-manual/`
- output:
  - updated user operation manual for new or changed functionality
  - updated plugin operation manual when plugin behavior, configuration, startup, interaction, or troubleshooting changes
  - documentation notes covering unchanged-manual decisions when no user-facing behavior changed
- next:
  - send implementation notes, verification notes, and manual changes to `qa-agent`
### 5. QA
- agent: `qa-agent`
- skills:
@@ -96,18 +119,21 @@
  - PRD acceptance criteria
  - architecture risk points
  - Dev Agent implementation notes
  - user operation manual changes or unchanged-manual rationale
  - changed files and build output
- output:
  - test plan
  - test cases
  - defect report
  - regression result
  - manual consistency result
  - release recommendation
- next:
  - send pass or fail result to Review
  - route defects back to `dev-agent`
  - route missing or inaccurate operation manual content back to Manual Update
### 5. Review
### 6. Review
- agent:
  - `product-agent`
@@ -126,6 +152,7 @@
  - PRD
  - architecture design
  - implementation summary
  - user operation manual changes
  - test results
  - known risks
- output:
@@ -139,6 +166,8 @@
- If the requirement is unclear, return to `product-agent`.
- If module boundaries, runtime model, or technical risks change, return to `architect-agent`.
- If implementation fails or defects are confirmed, return to `dev-agent`.
- If a completed feature or plugin change affects user-visible operation, configuration, startup, interaction, troubleshooting, or known limitations, update the operation manual before QA.
- If manual content is missing, outdated, or inconsistent with actual behavior, return to Manual Update.
- If persistence schema, migration, default values, or compatibility is involved, call `dba-agent`.
- If release confidence is low, return to `qa-agent` for expanded verification.
@@ -153,10 +182,11 @@
## Development Output
## Manual Update Output
## QA Output
## Review Decision
## Follow Up Tasks
```
docs/README.md
@@ -15,17 +15,19 @@
## 当前产品文档
- [Windows 11 桌面增强应用 PRD](product/desktop-enhancement-prd.md)
- [Moli.Desktop 用户操作手册](product/user-manual.md)
- [Moli.Desktop 用户手册索引](product/user-manual.md)
- [LLM 桌面输入插件 PRD](product/llm-command-palette-plugin-prd.md)
## 当前架构文档
- [Moli.Desktop Runtime 架构设计](architecture/runtime-architecture.md)
- [Moli.Desktop MVP 详细设计](architecture/detailed-design.md)
- [LLM 桌面输入插件架构设计](architecture/llm-command-palette-architecture.md)
## 当前开发文档
- [Moli.Desktop MVP 开发任务拆分](development/mvp-dev-task-breakdown.md)
- [LLM 桌面输入插件 AiChat 模式开发任务拆分](development/llm-command-palette-aichat-mode-task-breakdown.md)
## 当前 API 文档
@@ -39,6 +41,8 @@
- [Moli.Desktop MVP 集成移交记录](qa/mvp-integration-handoff.md)
- [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)
## 当前运维文档
docs/architecture/detailed-design.md
@@ -462,7 +462,7 @@
策略顺序:
1. `WorkerWDesktopLayerStrategy`:尝试将壁纸窗口和 `desktop` 层组件挂到 Explorer WorkerW,使桌面插件在 Win+D 后仍然显示。
1. `WorkerWDesktopLayerStrategy`:尝试将壁纸窗口和 `desktop` 层组件挂到 Explorer WorkerW;当当前 Explorer 没有独立 WorkerW 时回退到 Progman 桌面宿主。挂载时窗口必须切换为 `WS_CHILD` 并移除 `WS_POPUP`,使桌面插件在 Win+D 后仍然显示。
2. `BottomDesktopLayerStrategy`:降级为覆盖目标区域的底层窗口,并开启点击穿透。
选择策略后写入诊断:
docs/architecture/llm-command-palette-architecture.md
New file
@@ -0,0 +1,900 @@
# Architecture: LLM Command Palette Plugin
## Context
本文档基于 `docs/product/llm-command-palette-plugin-prd.md`,为 LLM 桌面输入插件设计运行时架构、模块边界、配置模型、流式调用链路和实现拆分。
Moli.Desktop 已具备 WebView2 小组件窗口、插件 manifest、布局持久化、本地 HTTP API、WebSocket 事件和 `window.moliDesktop` 桥接能力。LLM 插件应复用这些基础设施,并新增一层宿主侧 LLM 代理能力,用于按 `modelId` 路由到不同供应商和不同 endpoint。
核心架构决策:
- 插件前端只负责输入、模型选择和流式渲染。
- 插件前端只传 `mode`、`projectId`、`modelId`、`messages` 和请求参数,不直接传 provider、endpoint、API key、AiChat 密码或 Session Token。
- 宿主维护 LLM 模型注册表,每个模型可独立配置 `provider`、`endpoint`、`authRef` 和 `apiModel`。
- 宿主按 `modelId` 选择 provider adapter,并把不同供应商的流式响应统一转换成插件可消费的事件。
- API key 不进入插件前端资源、manifest 示例或普通日志。
- 插件运行模式由配置决定:
  - `provider-direct`:沿用当前供应商直连链路,并可调用 AiChat 记忆接口管理/召回记忆。
  - `aichat-api`:通过自有 AiChat API 登录、读取项目、发送聊天和订阅 SSE;插件侧不处理记忆。
- AiChat 统一 Host 默认固定为 `http://192.168.1.111:13000`,不从 AiChat 接口文档的环境表推导。
## Goals
- 支持一个顶部居中的 LLM 输入小组件,默认作为 `widget` 插件运行。
- 支持多供应商、多 endpoint、多模型共存。
- 支持通过配置切换供应商直连和 AiChat 自有 API 两种模式。
- 支持输入框左侧 AiChat 项目下拉。
- 支持供应商直连模式下复用 AiChat 记忆管理能力。
- 支持 OpenAI-compatible、DeepSeek、本地 OpenAI-compatible 服务,后续可扩展 Anthropic、Ollama 等适配器。
- 支持流式输出,并将供应商差异屏蔽在宿主侧。
- 保持插件系统边界:WebView 页面只访问白名单桥接 API。
- 配置和密钥边界清晰,便于后续管理窗口和数据迁移继续扩展。
## Non Goals
- 不实现完整聊天会话系统。
- 不实现云端同步、团队共享模型配置或计费系统。
- 不在插件前端直接保存或管理 API key。
- 不在插件前端保存 AiChat 密码或 Session Token。
- 不复制 AiChat 服务端的项目、审批、权限、配额和记忆策略。
- 不在 `aichat-api` 模式中额外调用记忆召回拼装 Prompt。
- 不在 MVP 中实现文件上传、多模态输入或长期历史记录。
- 不要求把 LLM 代理暴露成公网 API。
## Module Design
### Module Overview
```mermaid
flowchart TB
  Plugin["sample.llm-command-palette WebView"]
  Bridge["PluginBridgeScript / WebViewHost"]
  Runtime["DesktopRuntimeCoordinator"]
  LlmService["LlmGatewayService"]
  ModeRouter["LlmModeRouter"]
  AiChat["AiChatClient"]
  AiChatSession["AiChatSessionService"]
  AiChatMemory["AiChatMemoryService"]
  Registry["LlmModelRegistry"]
  SecretStore["CredentialStore"]
  AdapterFactory["LlmProviderAdapterFactory"]
  OpenAI["OpenAICompatibleAdapter"]
  DeepSeek["DeepSeekAdapter"]
  Local["LocalOpenAICompatibleAdapter"]
  Config["ConfigurationService"]
  Events["RuntimeEventBus"]
  Diagnostics["DiagnosticsService"]
  Plugin --> Bridge
  Bridge --> Runtime
  Runtime --> LlmService
  LlmService --> ModeRouter
  ModeRouter --> AiChat
  AiChat --> AiChatSession
  AiChat --> AiChatMemory
  LlmService --> Registry
  Registry --> Config
  LlmService --> SecretStore
  LlmService --> AdapterFactory
  AdapterFactory --> OpenAI
  AdapterFactory --> DeepSeek
  AdapterFactory --> Local
  LlmService --> Events
  LlmService --> Diagnostics
  Bridge --> Plugin
```
### Responsibilities
| 模块 | 职责 | 不负责 |
| --- | --- | --- |
| `sample.llm-command-palette` | 输入、模型下拉、Enter 提交、流式文本渲染、错误展示 | 供应商 API 适配、密钥读取 |
| `PluginBridgeScript` | 向 WebView 注入 `window.moliDesktop.llm` API,处理 Promise 与事件派发 | 直接发起外部 HTTP 请求 |
| `DesktopRuntimeCoordinator` | 统一接收插件桥接命令,校验插件实例和权限,调用 LLM 服务 | 解析供应商流式协议 |
| `LlmGatewayService` | LLM 请求入口、运行模式分发、模型路由、取消、超时、事件归一化 | 持久化布局或窗口状态 |
| `LlmModeRouter` | 按 `provider-direct` / `aichat-api` 选择供应商适配器或 AiChat 客户端 | 处理具体 SSE 协议 |
| `AiChatClient` | 封装 AiChat 登录、项目、模型、聊天、SSE 和错误码映射 | 保存用户密码明文 |
| `AiChatSessionService` | 解析密码环境变量、登录、缓存内存态 sessionToken、401 重登 | 暴露 sessionToken 给插件页面 |
| `AiChatMemoryService` | 供应商直连模式下封装记忆查询、创建、删除、召回 | 在自有 API 模式中重复处理记忆 |
| `LlmModelRegistry` | 加载和校验模型配置,按 `modelId` 查找模型 | 保存 API key 明文 |
| `CredentialStore` | 按 `authRef` 提供密钥,隐藏真实 key | 保存普通插件配置 |
| `LlmProviderAdapter` | 按 provider 适配请求和流式响应 | 决定插件 UI 行为 |
| `RuntimeEventBus` | 广播 `llm.delta`、`llm.completed`、`llm.error` 等事件 | 存储历史对话 |
| `DiagnosticsService` | 记录鉴权失败、endpoint 不可达、流解析失败、超时 | 记录完整 prompt 或 key |
### Dependency Direction
- 插件 UI 只能依赖 `window.moliDesktop.llm`。
- 桥接层只依赖运行时接口,不直接依赖具体 provider adapter。
- Provider adapter 只由 `LlmGatewayService` 通过工厂创建或取得。
- AiChat API 访问只由宿主侧 `AiChatClient` 执行,插件页面不能直接持有密码或 token。
- 配置读写仍经 `ConfigurationService`,不允许插件或 adapter 直接写 JSON。
## Runtime Flow
### Model List Load
```mermaid
sequenceDiagram
  participant Plugin
  participant Bridge
  participant Runtime
  participant Llm as LlmGatewayService
  participant Registry as LlmModelRegistry
  Plugin->>Bridge: window.moliDesktop.llm.getModels()
  Bridge->>Runtime: GetLlmModels(pluginId, instanceId)
  Runtime->>Llm: GetAvailableModels(pluginId)
  Llm->>Registry: Load enabled model summaries
  Registry-->>Llm: model id, label, provider, supportsStreaming
  Llm-->>Runtime: safe model summaries
  Runtime-->>Bridge: summaries without endpoint/authRef
  Bridge-->>Plugin: Promise resolve
```
插件模型下拉只能拿到安全摘要:
```json
[
  {
    "id": "gpt-5.4",
    "label": "GPT-5.4",
    "provider": "openai-compatible",
    "supportsStreaming": true,
    "enabled": true
  }
]
```
默认不返回 `endpoint`、`authRef`、API key 或其他敏感配置。管理窗口可以在受控 UI 中展示和编辑 endpoint,但插件前端不需要知道。
`aichat-api` 模式下模型列表来自 AiChat `GET /api/chat/models`,返回同样的安全摘要结构:
```json
[
  {
    "id": "deepseek-v4-flash",
    "label": "deepseek-v4-flash",
    "provider": "aichat",
    "supportsStreaming": true,
    "enabled": true
  }
]
```
### AiChat Login and Project Load
```mermaid
sequenceDiagram
  participant Plugin
  participant Bridge
  participant Runtime
  participant AiChat as AiChatClient
  participant Session as AiChatSessionService
  participant Api as AiChat API
  Plugin->>Bridge: getProjects()
  Bridge->>Runtime: GetAiChatProjects(pluginId, instanceId)
  Runtime->>AiChat: GetProjectsAsync()
  AiChat->>Session: EnsureSessionAsync()
  Session->>Session: Resolve passwordEnv before password
  Session->>Api: POST /api/auth/login
  Api-->>Session: sessionToken
  AiChat->>Api: GET /api/projects with x-session-token
  Api-->>AiChat: projects
  AiChat-->>Runtime: safe project summaries
  Runtime-->>Bridge: project summaries
  Bridge-->>Plugin: Promise resolve
```
项目摘要建议只返回插件 UI 需要的字段:
```json
[
  {
    "id": "project_id",
    "name": "产品问答",
    "projectType": "CHAT",
    "memoryMode": "ISOLATED"
  }
]
```
### Stream Chat
```mermaid
sequenceDiagram
  participant Plugin
  participant Bridge
  participant Runtime
  participant Llm as LlmGatewayService
  participant Registry as LlmModelRegistry
  participant Secret as CredentialStore
  participant Adapter as ProviderAdapter
  participant Upstream as LLM Provider
  Plugin->>Bridge: streamChat(mode, projectId, modelId, messages, options)
  Bridge->>Runtime: StreamLlmChat(request)
  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
  Llm->>Secret: Resolve authRef
  Secret-->>Llm: credential or null
  Llm->>Adapter: StreamAsync(normalized request)
  Adapter->>Upstream: HTTP streaming request
  Upstream-->>Adapter: provider stream chunks
  Adapter-->>Llm: normalized deltas
  Llm-->>Runtime: LlmStreamEvent
  Runtime-->>Bridge: llm.delta / completed / error
  Bridge-->>Plugin: DOM event or callback
```
### AiChat API Chat Flow
```mermaid
sequenceDiagram
  participant Plugin
  participant Bridge
  participant Runtime
  participant Llm as LlmGatewayService
  participant AiChat as AiChatClient
  participant Api as AiChat API
  Plugin->>Bridge: streamChat(mode=aichat-api, projectId, modelId, message)
  Bridge->>Runtime: StreamLlmChat(request)
  Runtime->>Runtime: Validate plugin permission llm.stream
  Runtime->>Llm: StreamChatAsync(request)
  Llm->>AiChat: SendChatAsync(projectId, modelName, message)
  AiChat->>Api: POST /api/chat/send
  Api-->>AiChat: generationId, streamToken, conversationId
  AiChat->>Api: GET /api/chat/generations/{id}/stream?token={streamToken}
  Api-->>AiChat: snapshot/chunk/processing/done/failed/aborted
  AiChat-->>Llm: normalized deltas/completed/error
  Llm-->>Runtime: LlmStreamEvent
  Runtime-->>Bridge: llm.delta / completed / error
  Bridge-->>Plugin: DOM event or callback
```
AiChat SSE 事件映射:
| AiChat event | 归一化事件 | 处理 |
| --- | --- | --- |
| `snapshot` | `llm.delta` 或忽略 | 如果 snapshot content 非空,作为当前内容快照渲染 |
| `chunk` | `llm.delta` | 使用 `delta` 追加 |
| `processing` | `llm.processing` | UI 可显示“处理中” |
| `done` | `llm.completed` | 结束请求 |
| `failed` | `llm.error` | 显示错误并结束请求 |
| `aborted` | `llm.error` 或 `llm.aborted` | 显示已终止并结束请求 |
### Provider Direct Memory Flow
供应商直连模式下,记忆管理走 AiChat API,但聊天生成仍走供应商适配器:
```mermaid
sequenceDiagram
  participant Plugin
  participant Bridge
  participant Runtime
  participant Memory as AiChatMemoryService
  participant Api as AiChat API
  participant Llm as LlmGatewayService
  participant Provider as ProviderAdapter
  Plugin->>Bridge: recallMemories(query, projectId, scope=ALL)
  Bridge->>Runtime: RecallMemories(request)
  Runtime->>Memory: RecallAsync(request)
  Memory->>Api: POST /api/memories/recall
  Api-->>Memory: memory items
  Memory-->>Plugin: safe memory summaries
  Plugin->>Bridge: streamChat(mode=provider-direct, messages with selected memory context)
  Bridge->>Llm: StreamChatAsync(request)
  Llm->>Provider: StreamAsync(normalized request)
```
权限规则:
- `GET /api/auth/me` 返回 `canUseMemory`、`canViewMemory`、`canManageMemory` 后,宿主应把可用能力摘要返回给插件。
- `canViewMemory=false` 时不展示记忆列表。
- `canManageMemory=false` 时不允许创建或删除。
- `canUseMemory=false` 时不允许召回并注入上下文。
### Cancellation
MVP 可先实现“请求中忽略重复 Enter”。架构上预留取消能力:
- 每次 `streamChat` 生成 `requestId`。
- `LlmGatewayService` 保存 `requestId -> CancellationTokenSource`。
- 插件后续可调用 `window.moliDesktop.llm.cancel(requestId)`。
- Escape 可在 UI 层先收起输出;若后续启用取消语义,则 Escape 二次触发 cancel。
## Data Model
### LLM Settings Document
建议新增独立配置文件:
```text
%AppData%\DesktopEnhancer\config\llm-models.json
```
独立文件的好处:
- 避免把供应商 endpoint 和模型配置塞入 `layout.json` 或普通插件 manifest。
- 便于管理窗口单独做“模型配置”页。
- 后续迁移到加密存储或服务端配置时边界更清晰。
示例:
```json
{
  "schemaVersion": 1,
  "defaultModel": "gpt-5.4",
  "models": [
    {
      "id": "gpt-5.4",
      "label": "GPT-5.4",
      "provider": "openai-compatible",
      "endpoint": "https://api.openai.example/v1/chat/completions",
      "authRef": "llm.openai.primary",
      "apiModel": "gpt-5.4",
      "supportsStreaming": true,
      "enabled": true,
      "requestDefaults": {
        "temperature": 0.7,
        "maxTokens": 2048,
        "timeoutMs": 60000
      }
    },
    {
      "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",
      "provider": "openai-compatible",
      "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
      "authRef": null,
      "apiModel": "qwen2.5:14b",
      "supportsStreaming": true,
      "enabled": false,
      "requestDefaults": {
        "temperature": 0.6,
        "maxTokens": 2048,
        "timeoutMs": 120000
      }
    }
  ]
}
```
### Plugin Runtime Mode Config
建议在插件配置或后续独立运行配置中增加 AiChat 对接配置。为了兼容现有 `plugin.json`,缺失字段时使用默认值。
```json
{
  "schemaVersion": 1,
  "mode": "provider-direct",
  "aichat": {
    "baseUrl": "http://192.168.1.111:13000",
    "account": {
      "email": "user@example.com",
      "password": null,
      "passwordEnv": "MOLI_AICHAT_PASSWORD"
    },
    "defaultProjectId": "",
    "memory": {
      "enabledInProviderDirect": true,
      "defaultScope": "PROJECT",
      "recallLimit": 8
    }
  }
}
```
校验规则:
| 字段 | 规则 |
| --- | --- |
| `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.passwordEnv` | 可为空;存在时优先读取环境变量 |
| `aichat.account.password` | 可为空;只作为本地测试 fallback |
| `aichat.defaultProjectId` | 可为空;不为空时应存在于项目列表 |
| `aichat.memory.recallLimit` | `1..20` |
密码解析顺序:
1. `passwordEnv` 指向的环境变量值。
2. `password` 明文字段。
3. 都不存在时返回 `AiChatCredentialMissing`。
Session Token 仅保存在 `AiChatSessionService` 内存态,不写入 JSON。
### Model Validation Rules
| 字段 | 规则 |
| --- | --- |
| `schemaVersion` | 必填,当前为 `1` |
| `defaultModel` | 必须为空或指向一个 enabled 模型 |
| `models[].id` | 全局唯一,推荐 `provider-name` 或用户可读 id |
| `models[].label` | 1 到 40 字符,供下拉展示 |
| `models[].provider` | 必须存在对应 adapter |
| `models[].endpoint` | 必须是 `http` 或 `https` 绝对 URL |
| `models[].authRef` | 可为空;不为空时不得包含明文 key |
| `models[].apiModel` | 必填,发送给上游供应商的真实模型名 |
| `models[].timeoutMs` | 建议 `5000..300000` |
### Credential Storage
MVP 建议优先顺序:
1. Windows Credential Manager:生产路径,按 `authRef` 存取密钥。
2. 用户环境变量:开发/调试路径,例如 `MOLI_LLM_OPENAI_PRIMARY_KEY`。
3. 明文 JSON:不推荐;如临时支持,必须仅用于本地测试并在管理窗口明确标注风险。
`authRef` 不直接等于环境变量名,可以通过宿主映射:
```json
{
  "authRef": "llm.openai.primary"
}
```
宿主解析顺序示例:
```text
Windows Credential Manager: Moli.Desktop/llm.openai.primary
Environment variable: MOLI_LLM_OPENAI_PRIMARY
```
## Interfaces
### C# Service Contracts
```csharp
public interface ILlmGatewayService
{
    Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken);
    IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        CancellationToken cancellationToken);
    Task CancelAsync(string requestId, CancellationToken cancellationToken);
}
public interface ILlmModelRegistry
{
    Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken);
    Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken);
}
public interface ILlmProviderAdapter
{
    string Provider { get; }
    IAsyncEnumerable<LlmProviderChunk> StreamAsync(
        LlmProviderRequest request,
        CancellationToken cancellationToken);
}
public interface ICredentialStore
{
    Task<string?> ResolveSecretAsync(string authRef, CancellationToken cancellationToken);
}
```
### Request DTOs
```csharp
public sealed record LlmChatRequest
{
    public required string RequestId { get; init; }
    public required string PluginId { get; init; }
    public required string InstanceId { get; init; }
    public string Mode { get; init; } = "provider-direct";
    public string? ProjectId { get; init; }
    public required string ModelId { get; init; }
    public required IReadOnlyList<LlmMessage> Messages { get; init; }
    public LlmRequestOptions Options { get; init; } = new();
}
public sealed record LlmMessage
{
    public required string Role { get; init; }
    public required string Content { get; init; }
}
public sealed record LlmRequestOptions
{
    public double? Temperature { get; init; }
    public int? MaxTokens { get; init; }
    public int? TimeoutMs { get; init; }
}
```
### Stream Events
```csharp
public abstract record LlmStreamEvent
{
    public required string RequestId { get; init; }
}
public sealed record LlmDeltaEvent : LlmStreamEvent
{
    public required string Delta { get; init; }
}
public sealed record LlmCompletedEvent : LlmStreamEvent
{
    public LlmUsage? Usage { get; init; }
}
public sealed record LlmErrorEvent : LlmStreamEvent
{
    public required string Code { get; init; }
    public required string Message { get; init; }
}
```
### Plugin Bridge API
```typescript
type LlmModelSummary = {
  id: string;
  label: string;
  provider: string;
  supportsStreaming: boolean;
  enabled: boolean;
};
type LlmStreamRequest = {
  mode?: "provider-direct" | "aichat-api";
  projectId?: string;
  modelId: string;
  messages: Array<{ role: "system" | "user" | "assistant"; content: string }>;
  options?: {
    temperature?: number;
    maxTokens?: number;
    timeoutMs?: number;
  };
};
window.moliDesktop.llm = {
  getConnectionMode(): Promise<"provider-direct" | "aichat-api">;
  setConnectionMode(mode: "provider-direct" | "aichat-api"): Promise<void>;
  getProjects(): Promise<Array<{
    id: string;
    name: string;
    projectType: "CHAT" | "REMOTE";
    memoryMode: "ISOLATED" | "SHARED";
  }>>;
  getModels(): Promise<LlmModelSummary[]>;
  streamChat(request: LlmStreamRequest): Promise<{ requestId: string }>;
  cancel(requestId: string): Promise<void>;
  getMemoryCapabilities(): Promise<{
    canUseMemory: boolean;
    canViewMemory: boolean;
    canManageMemory: boolean;
  }>;
  getMemories(options: { scope?: "GLOBAL" | "PROJECT"; projectId?: string }): Promise<object>;
  createMemory(input: { scope: "GLOBAL" | "PROJECT"; projectId?: string; content: string }): Promise<object>;
  deleteMemory(memoryId: string): Promise<void>;
  recallMemories(input: { query: string; scope?: "GLOBAL" | "PROJECT" | "ALL"; projectId?: string; limit?: number }): Promise<object>;
  onDelta(handler: (event: { requestId: string; delta: string }) => void): () => void;
  onCompleted(handler: (event: { requestId: string; usage?: object }) => void): () => void;
  onError(handler: (event: { requestId: string; code: string; message: string }) => void): () => void;
};
```
### Provider Adapter Contract
不同供应商的适配器必须统一输出:
- `delta`: 增量文本。
- `completed`: 正常结束和可选 usage。
- `error`: 供应商错误归一化。
OpenAI-compatible adapter 可作为第一优先级,它能覆盖 OpenAI、DeepSeek 的兼容模式、本地 Ollama/LM Studio 等多数 MVP 场景。DeepSeek 如使用非兼容字段,再单独派生 adapter。
## Plugin Layout and Window Behavior
LLM 插件仍是普通 widget 实例,布局由 `LayoutManager` 和 `WidgetWindow` 控制。
默认安装规则建议由 `DefaultContentInstaller` 特判 `sample.llm-command-palette`:
- `width = min(760, primaryWorkArea.Width * 0.72)`
- `height = 72`
- `x = primaryWorkArea.X + (primaryWorkArea.Width - width) / 2`
- `y = primaryWorkArea.Y + 32`
- `locked = true`
- `clickThrough = false`
- `displayLayer = desktop`
- `opacity = 0.96`
输出展开高度存在两层约束:
1. 插件前端 CSS 限制输出区域 `max-height: 50vh`。
2. 如插件请求 `requestResize`,宿主布局层限制组件总高度不超过当前显示器高度 `50% + inputBarHeight + margin`,避免窗口无限扩张。
## Error Handling
| 错误码 | 场景 | UI 行为 | 诊断 |
| --- | --- | --- | --- |
| `LlmModelNotFound` | `modelId` 不存在或 disabled | 输出区显示模型不可用 | Warning |
| `LlmProviderUnsupported` | provider 无 adapter | 输出区显示供应商不支持 | Error |
| `LlmCredentialMissing` | `authRef` 无法解析 | 输出区提示检查密钥 | Error,不记录 key |
| `LlmEndpointUnavailable` | 网络失败、DNS、连接拒绝 | 输出区提示 endpoint 不可达 | Error,记录 endpoint host |
| `LlmUnauthorized` | 401/403 | 输出区提示鉴权失败 | Error,不记录 key |
| `LlmRateLimited` | 429 | 输出区提示稍后重试 | Warning |
| `LlmTimeout` | 超时 | 输出区提示请求超时 | Warning |
| `LlmStreamParseFailed` | 供应商流格式异常 | 保留已输出内容并提示解析失败 | Error |
| `AiChatCredentialMissing` | 未配置 AiChat 账号或密码 | 提示检查账号和密码环境变量 | Error,不记录密码 |
| `AiChatLoginFailed` | 登录失败或账号状态异常 | 显示登录失败、待审批或权限错误 | Warning |
| `AiChatProjectLoadFailed` | 项目列表不可用 | 项目下拉显示不可用 | Warning |
| `AiChatQuotaExceeded` | Token 配额耗尽 | 输出区提示配额耗尽 | Warning |
| `AiChatMemoryPermissionDenied` | 记忆权限不足 | 禁用对应记忆操作 | Warning |
| `AiChatSseInterrupted` | AiChat SSE 中断 | 保留已输出内容并提示连接中断 | Warning |
日志规则:
- 可以记录 `requestId`、`modelId`、`provider`、endpoint host、HTTP status。
- 不记录完整 API key。
- 不记录 AiChat 密码、Session Token 或完整 `x-session-token` 请求头。
- 默认不记录完整 prompt;如后续需要调试开关,必须由用户显式启用。
## Security Boundaries
- `llm.stream` 必须作为插件权限声明,未声明时桥接层拒绝调用。
- 插件只能看到 enabled 模型摘要。
- 插件不能覆盖 endpoint、provider、authRef 或 apiModel。
- 插件不能读取 AiChat 明文密码和 Session Token。
- `setConfig` 不允许写入宿主级 LLM 模型注册表。
- 本地 HTTP API 如后续暴露 LLM 调用,也必须默认绑定 `127.0.0.1`,并复用同一 `ILlmGatewayService`。
- 远程 endpoint 必须经过 URL 校验,禁止 `file://`、相对路径和非 HTTP 协议。
## Alternatives
| 方案 | 结论 | 原因 |
| --- | --- | --- |
| 插件前端直接调用各供应商 API | 不采用 | 密钥暴露、跨供应商差异扩散到插件 UI、日志和错误边界难控 |
| 全局单 provider + 单 endpoint | 不采用 | 无法自然支持不同供应商和每模型独立 URL |
| 宿主统一代理,按 `modelId` 路由 | 采用 | 满足多供应商,密钥留在宿主,插件 UI 简洁 |
| 只实现 OpenAI-compatible adapter | MVP 可作为第一阶段 | 快速覆盖多数供应商,但保留 provider adapter 扩展点 |
| 把模型配置放进插件 manifest | 仅作为 fallback | manifest 属于插件包,不适合保存用户真实 endpoint 和密钥引用 |
| 把模型配置放进 `appsettings.json` | 可行但不推荐 | LLM 配置会增长,独立文件更利于管理和迁移 |
| 自有 API 模式直接让插件 fetch AiChat | 不采用 | 会把密码、token、错误处理和 SSE 兼容逻辑扩散到前端 |
| 宿主封装 AiChatClient | 采用 | 统一鉴权、Session、项目、模型、聊天和记忆错误映射 |
| 自有 API 模式也手动召回记忆 | 不采用 | AiChat 服务自身负责项目和记忆策略,插件重复处理会破坏一致性 |
## Implementation Tasks
### A01 LLM Configuration Model
输出:
- `LlmSettingsDocument`
- `LlmModelConfig`
- `LlmRequestDefaults`
- `llm-models.json` 默认生成和校验
验收:
- 缺失配置时生成空模型列表或样例 disabled 模型。
- 非法 provider、重复 id、非法 endpoint 会产生诊断。
- `defaultModel` 指向 disabled 或不存在模型时降级为空。
### A02 Credential Store
输出:
- `ICredentialStore`
- Windows Credential Manager 实现或环境变量 fallback
- 密钥脱敏日志工具
验收:
- `authRef = null` 支持本地无鉴权模型。
- 缺失密钥返回明确 `LlmCredentialMissing`。
- 日志和异常中不出现完整 key。
### A03 Provider Adapter Layer
输出:
- `ILlmProviderAdapter`
- `OpenAICompatibleAdapter`
- adapter factory
- 流式 SSE 解析器
验收:
- 能解析 `data: ...` 增量文本。
- 能识别 `[DONE]`。
- 上游 401、429、5xx 能映射为统一错误。
### A04 LLM Gateway Service
输出:
- `ILlmGatewayService`
- 模型路由、超时、取消、事件归一化
- 请求大小和消息角色校验
验收:
- 不同 `modelId` 路由到不同 endpoint。
- 请求超时返回 `LlmTimeout`。
- provider 不存在返回 `LlmProviderUnsupported`。
### A05 WebView Bridge Extension
输出:
- `window.moliDesktop.llm.getModels`
- `streamChat`
- `cancel`
- `onDelta` / `onCompleted` / `onError`
- 权限校验 `llm.stream`
验收:
- 未声明权限的插件调用 LLM API 被拒绝。
- 插件只收到安全模型摘要。
- 流式 delta 可以到达当前插件实例。
### A06 Sample Plugin
输出:
- `samples/plugins/sample.llm-command-palette/plugin.json`
- `index.html`
- 半透明顶部输入条、模型下拉、输出展开区域
验收:
- 默认顶部居中。
- Enter 提交,Shift+Enter 换行。
- 输出区最大高度不超过屏幕 `50%`。
- 错误展示在输出区,不弹系统模态框。
### A07 Management Window Extension
输出:
- 模型配置页或插件配置入口。
- 增删改模型:id、label、provider、endpoint、apiModel、authRef、enabled。
- 密钥配置入口,显示 `authRef` 状态但不显示明文 key。
验收:
- 保存模型配置后插件下拉刷新。
- 无效 endpoint 或 provider 显示可读错误。
- 管理窗口不泄露完整 key。
### A08 Verification and QA Handoff
输出:
- LLM 架构验证记录。
- mock adapter 测试。
- 本地 OpenAI-compatible endpoint 手工验证说明。
验收:
- `dotnet build` 通过。
- LLM 配置和 adapter 单元测试通过。
- 使用两个不同 endpoint 的模型可分别路由。
### A09 AiChat Client and Session
输出:
- `AiChatClient`
- `AiChatSessionService`
- 登录、重登、`x-session-token` 注入
- `GET /api/projects`、`GET /api/chat/models`
验收:
- `passwordEnv` 优先于明文密码。
- 登录成功后 token 只保存在内存态。
- 401 后自动重登一次。
- 项目列表失败时 UI 可降级而不影响供应商直连聊天。
### A10 AiChat API Chat Mode
输出:
- `mode=aichat-api` 的 `StreamChatAsync` 分支。
- `POST /api/chat/send` 调用。
- AiChat SSE 解析和事件归一化。
验收:
- 所选 `projectId` 会传给 AiChat。
- `chunk` 能转换为 `llm.delta`。
- `done` 能转换为 `llm.completed`。
- `failed` / `aborted` 能转换为可读错误。
### A11 Provider Direct Memory Management
输出:
- `AiChatMemoryService`
- 记忆能力查询。
- 查询、创建、删除、召回接口。
- 直连模式下可选把召回内容注入上下文。
验收:
- `canViewMemory`、`canManageMemory`、`canUseMemory` 分别控制 UI 能力。
- 项目记忆请求必须携带 `projectId`。
- 自有 API 模式下不调用记忆召回。
### A12 Sample Plugin UI Update
输出:
- 输入框左侧项目下拉。
- 运行模式配置读取。
- 模型列表按模式切换。
- 记忆管理入口和权限降级状态。
验收:
- 两种模式切换后,下拉和提交路径正确刷新。
- 项目下拉长名称不撑开输入条。
- AiChat 不可用时有短错误且不破坏直连模式。
## Verification Plan
### Unit Tests
- `LlmModelRegistry`:重复 id、disabled model、非法 endpoint、默认模型降级。
- `CredentialStore`:空 `authRef`、缺失密钥、环境变量 fallback。
- `OpenAICompatibleAdapter`:SSE delta、`[DONE]`、错误响应、异常流。
- `LlmGatewayService`:模型路由、超时、取消、错误映射。
### Integration Tests
- 使用 fake provider adapter 验证 `modelId -> endpoint` 路由。
- 使用 fake WebView bridge 验证 `llm.delta` 只派发给请求来源插件实例。
- 使用损坏 `llm-models.json` 验证备份恢复和诊断。
### Manual QA
- 配置两个模型,分别指向不同 endpoint,选择不同模型提交后检查路由日志。
- 配置 `mode=aichat-api`、AiChat 账号和 `MOLI_AICHAT_PASSWORD`,确认能登录 `http://192.168.1.111:13000` 并加载项目。
- 在自有 API 模式下选择项目并提交,确认 AiChat SSE 能流式输出。
- 在供应商直连模式下查询、创建、删除和召回 AiChat 项目记忆。
- 配置缺失 `authRef`,确认输出区显示鉴权配置错误。
- 配置本地 OpenAI-compatible 服务,确认无 key 模型可流式输出。
- 断网或关闭本地 endpoint,确认插件输出区显示 endpoint 不可达。
- 输出长文本,确认插件窗口和输出区不超过屏幕高度约束。
## Open Decisions
| 问题 | 建议默认值 | 后续触发条件 |
| --- | --- | --- |
| 密钥生产存储 | Windows Credential Manager | 管理窗口实现密钥编辑时落地 |
| 默认 adapter | OpenAI-compatible | 先覆盖 OpenAI、DeepSeek 兼容接口和本地服务 |
| DeepSeek 是否独立 adapter | 暂不强制 | 如果实际接口与 OpenAI-compatible 差异明显再拆 |
| 是否暴露本地 HTTP LLM API | 暂不暴露 | 插件桥接先满足需求;外部自动化需要时再设计 |
| 是否保存 prompt 历史 | 默认不保存 | 用户明确需要历史或调试审计时再评估 |
| AiChat 配置位置 | 先放插件配置,后续可迁移为独立 `llm-runtime.json` | 管理 UI 需要跨插件共享 AiChat 账号时 |
| AiChat 会话下拉 | MVP 不做 | 用户要求固定会话或查看历史时 |
| 直连模式召回内容注入方式 | 先作为系统上下文前缀注入 | 后续可做用户确认和引用开关 |
docs/architecture/runtime-architecture.md
@@ -404,7 +404,7 @@
- 数据契约统一使用 `displayLayer`,取值仅允许 `desktop`、`normal`、`app-top`、`global-top`。
- `LayoutManager` 只负责保存、校验和广播层级意图,不直接操作 Win32。
- `DesktopRuntimeCoordinator` 将更新后的布局通过 `IRuntimeSurfaceController` 下发,保证管理窗口、API 和托盘命令走同一运行时路径。
- `WidgetWindow` 是最终窗口行为执行点:`desktop` 优先挂载到 Explorer WorkerW 桌面层以避免 Win+D 最小化,失败时降级到底层普通窗口;`normal` 使用普通 WPF 窗口层级,`app-top` 保持本应用内的普通窗口提升语义,`global-top` 才设置全局 `Topmost`。
- `WidgetWindow` 是最终窗口行为执行点:`desktop` 优先挂载到 Explorer WorkerW/Progman 桌面宿主并切换为 child 窗口样式,以避免 Win+D 最小化,失败时降级到底层普通窗口;`normal` 使用普通 WPF 窗口层级,`app-top` 保持本应用内的普通窗口提升语义,`global-top` 才设置全局 `Topmost`。
- 如果某层级受 Windows 桌面环境限制无法完全精确表达,窗口控制器必须选择更安全的非全局置顶行为,并记录诊断。
约束规则:
@@ -415,7 +415,7 @@
- `locked = true` 时拒绝拖拽和缩放。
- `visible = false` 时窗口隐藏但布局保留。
- `clickThrough = true` 时由 Win32 扩展样式透传鼠标输入。
- `displayLayer` 支持 `desktop`、`normal`、`app-top`、`global-top`:`desktop` 挂到 WorkerW 桌面层并在 Win+D 后继续显示,`normal` 遵循普通窗口层级,`app-top` 只在本应用窗口范围内提升,`global-top` 使用全局置顶并要求托盘/管理窗口可快速撤销。
- `displayLayer` 支持 `desktop`、`normal`、`app-top`、`global-top`:`desktop` 挂到 WorkerW/Progman 桌面宿主并在 Win+D 后继续显示,`normal` 遵循普通窗口层级,`app-top` 只在本应用窗口范围内提升,`global-top` 使用全局置顶并要求托盘/管理窗口可快速撤销。
### Audio Visualizer Plugin
docs/data/configuration-and-storage.md
@@ -15,7 +15,7 @@
| 应用数据根目录 | `%AppData%\DesktopEnhancer` |
| 配置目录 | `%AppData%\DesktopEnhancer\config` |
| 插件目录 | `%AppData%\DesktopEnhancer\plugins` |
| 日志目录 | `%LocalAppData%\DesktopEnhancer\logs` |
| 日志目录 | 程序目录下的 `logs` |
| WebView2 数据目录 | `%LocalAppData%\DesktopEnhancer\WebView2` |
| 源码样例插件目录 | `samples\plugins` |
| 便携包样例插件目录 | `samples\plugins` |
@@ -92,7 +92,7 @@
| `plugins[].state` | enum | 插件持久状态,常用值为 `enabled` / `disabled` |
| `plugins[].updatedAt` | string | 状态更新时间,使用 `DateTimeOffset` JSON 表达 |
插件扫描时,`IPluginManager` 会将磁盘上的 `plugin.json` 与注册表状态合并。无效 manifest 不会让应用崩溃,会进入错误状态并写入诊断。
插件扫描时,`IPluginManager` 会将磁盘上的 `plugin.json` 与注册表状态合并。无效 manifest 不会让应用崩溃,会进入错误状态并写入诊断。默认样例插件安装和发布更新不会覆盖已有 `plugin.json`;当目标插件目录已经存在配置时,新版本 manifest 会写入 `plugin.template.json`,供用户对照迁移。
## layout.json
@@ -213,7 +213,7 @@
- 保存时使用临时文件和备份文件,避免直接覆盖导致配置损坏。
- 配置读写异常应记录诊断,不应静默吞掉。
QA 可通过手工破坏配置文件验证恢复路径,并检查 `%LocalAppData%\DesktopEnhancer\logs` 与运行时诊断列表。
QA 可通过手工破坏配置文件验证恢复路径,并检查程序目录下的 `logs` 与运行时诊断列表。
## 后续迁移预留
docs/development/llm-command-palette-aichat-mode-task-breakdown.md
New file
@@ -0,0 +1,156 @@
# LLM 桌面输入插件 AiChat 模式开发任务拆分
日期:2026-05-04
## 范围
本任务包承接 `docs/product/llm-command-palette-plugin-prd.md` 和 `docs/architecture/llm-command-palette-architecture.md`,目标是在现有 `sample.llm-command-palette` 与宿主 LLM 代理基础上完成两种模式增强:
- 供应商直连模式:保留当前能力,并接入 AiChat 记忆管理。
- 自有 API 模式:通过 AiChat 登录、项目、模型、聊天和 SSE 接口完成回复。
AiChat Host 默认使用:
```text
http://192.168.1.111:13000
```
## D01 配置模型与兼容迁移
交付:
- 插件配置支持 `mode`、`aichat.baseUrl`、`aichat.account`、`aichat.defaultProjectId`、`aichat.memory`。
- 缺失 `mode` 时按 `provider-direct` 处理。
- 缺失 `aichat` 时不影响原供应商直连聊天。
- JSON 读写保持 UTF-8。
验收:
- 旧版 `plugin.json` 只包含 `defaultModel` / `models` 时仍可加载。
- 新版样例 `plugin.json` 默认 `mode=provider-direct`。
- 密码环境变量优先于明文密码。
依赖:无。
## D02 AiChat Session 与基础客户端
交付:
- `AiChatSessionService`:登录、token 内存缓存、401 重登一次。
- `AiChatClient`:统一封装请求头、错误码、JSON 响应解析。
- 支持 `POST /api/auth/login`、`GET /api/auth/me`。
验收:
- 登录成功后只在内存保存 `sessionToken`。
- 日志不输出密码和 `x-session-token`。
- 登录失败、待审批、停用账号能映射为插件可读错误。
依赖:D01。
## D03 项目与模型列表
交付:
- `GET /api/projects` 项目列表加载。
- `GET /api/chat/models` 模型列表加载。
- 插件桥接新增 `getProjects()`。
- 模型下拉根据模式选择宿主模型注册表或 AiChat 模型接口。
验收:
- 输入框左侧显示 AiChat 项目下拉。
- 项目名称过长不撑开输入条。
- AiChat 不可用时项目下拉降级为 `No project`,供应商直连仍可用。
依赖:D02。
## D04 自有 API 模式聊天
交付:
- `mode=aichat-api` 分支。
- 调用 `POST /api/chat/send`。
- 使用 `generationId` 和 `streamToken` 订阅 SSE。
- 解析 `snapshot`、`chunk`、`processing`、`done`、`failed`、`aborted`。
验收:
- 选择项目后提交,请求携带 `projectId`。
- `chunk.delta` 能流式显示到输出区。
- `done` 后状态回到空闲。
- `USER_PENDING_APPROVAL`、`TOKEN_TOTAL_LIMIT_REACHED`、`INVALID_MODEL` 等错误显示短错误。
依赖:D02、D03。
## D05 供应商直连模式记忆管理
交付:
- `GET /api/memories` 查询全局/项目记忆。
- `POST /api/memories` 创建记忆。
- `DELETE /api/memories/{memoryId}` 删除记忆。
- `POST /api/memories/recall` 召回记忆。
- `GET /api/auth/me` 能力摘要驱动 UI:`canUseMemory`、`canViewMemory`、`canManageMemory`。
验收:
- 供应商直连模式下可按选中项目查询、创建、删除和召回记忆。
- 权限不足时对应操作禁用。
- 自有 API 模式下不执行插件侧记忆召回。
依赖:D02、D03。
## D06 插件 UI 更新
交付:
- 输入框左侧项目下拉。
- 右侧模型下拉按模式刷新。
- 记忆管理入口和权限降级状态。
- 模式切换后刷新项目、模型和提交链路。
验收:
- Enter 提交、Shift+Enter 换行、Escape 收起继续可用。
- 长项目名、长模型名不会导致输入条跳动。
- AiChat 项目/模型加载失败时显示短状态,不弹系统模态框。
依赖:D03、D04、D05。
## D07 管理窗口与手册同步
交付:
- 管理窗口或插件配置入口展示运行模式和 AiChat 配置。
- 密码字段支持环境变量说明,不显示明文 token。
- 同步更新 `docs/ops/user-manual/plugins/sample.llm-command-palette.md`。
验收:
- 用户能找到两种模式、AiChat Host、账号、密码环境变量、项目下拉、记忆限制和故障排查说明。
- 后续 QA 前操作手册保持最新。
依赖:D01、D06。
## D08 测试与验收
交付:
- 配置解析单元测试。
- AiChat 客户端 fake HTTP 测试。
- AiChat SSE 解析测试。
- 记忆权限控制测试。
- 样例插件静态渲染检查。
- QA 验收记录更新。
验收:
- `dotnet build .\Moli.Desktop.slnx` 通过。
- `dotnet test .\Moli.Desktop.slnx` 通过。
- 可用 AiChat 账号下完成一次 `aichat-api` 模式流式回复。
- `provider-direct` 模式原有供应商直连能力不回归。
- 供应商直连模式下记忆查询、创建、删除、召回至少完成一轮手工验收。
依赖:D01-D07。
docs/ops/user-manual.md
New file
@@ -0,0 +1,25 @@
# Moli.Desktop 用户手册索引
日期:2026-05-04
本文档是用户手册入口。主程序和每个插件的操作说明已拆分为独立文件,便于后续按模块维护。
## 主程序
- [Moli.Desktop 主程序操作手册](user-manual/moli-desktop.md)
## 插件
- [sample.wallpaper 动态壁纸插件](user-manual/plugins/sample.wallpaper.md)
- [sample.clock 时钟插件](user-manual/plugins/sample.clock.md)
- [sample.system-info 系统信息插件](user-manual/plugins/sample.system-info.md)
- [sample.audio-visualizer 音乐律动插件](user-manual/plugins/sample.audio-visualizer.md)
- [sample.llm-command-palette LLM 桌面输入插件](user-manual/plugins/sample.llm-command-palette.md)
- [sample.webview-test WebView 测试插件](user-manual/plugins/sample.webview-test.md)
## 通用参考
- 配置文件目录:`%AppData%\DesktopEnhancer\config`
- 插件目录:`%AppData%\DesktopEnhancer\plugins`
- 日志目录:程序目录下的 `logs`
- WebView2 数据目录:`%LocalAppData%\DesktopEnhancer\WebView2`
docs/ops/user-manual/moli-desktop.md
File was renamed from docs/product/user-manual.md
@@ -1,12 +1,21 @@
# Moli.Desktop 用户操作手册
# Moli.Desktop 主程序操作手册
日期:2026-05-02
日期:2026-05-04
## 适用范围
本文档面向 Moli.Desktop 的最终用户、试用用户和现场验证人员,说明如何安装、启动、管理动态壁纸、管理桌面小组件、查看诊断信息以及处理常见问题。
本文档面向 Moli.Desktop 的最终用户、试用用户和现场验证人员,说明如何安装、启动、使用托盘菜单、管理窗口、插件通用能力、本地 API、备份恢复以及处理主程序常见问题。
Moli.Desktop 是一款 Windows 11 桌面增强应用。它不会替代 Windows 桌面、Explorer、任务栏或开始菜单,而是在原生桌面之上增加 WebView2 驱动的 H5 动态壁纸和 HTML 小组件能力。
各插件的专门操作请查看:
- [sample.wallpaper 动态壁纸插件](plugins/sample.wallpaper.md)
- [sample.clock 时钟插件](plugins/sample.clock.md)
- [sample.system-info 系统信息插件](plugins/sample.system-info.md)
- [sample.audio-visualizer 音乐律动插件](plugins/sample.audio-visualizer.md)
- [sample.llm-command-palette LLM 桌面输入插件](plugins/sample.llm-command-palette.md)
- [sample.webview-test WebView 测试插件](plugins/sample.webview-test.md)
## 使用前准备
@@ -23,7 +32,7 @@
| --- | --- |
| 配置文件 | `%AppData%\DesktopEnhancer\config` |
| 插件目录 | `%AppData%\DesktopEnhancer\plugins` |
| 日志目录 | `%LocalAppData%\DesktopEnhancer\logs` |
| 日志目录 | 程序目录下的 `logs` |
| WebView2 数据 | `%LocalAppData%\DesktopEnhancer\WebView2` |
## 安装与启动
@@ -54,6 +63,10 @@
- `sample.wallpaper`:本地 H5 动态壁纸。
- `sample.clock`:桌面时钟小组件。
- `sample.system-info`:系统信息占位小组件。
- `sample.audio-visualizer`:音乐律动小组件。
- `sample.llm-command-palette`:顶部 LLM 输入插件。
`sample.webview-test` 主要用于开发验证,通常不会默认启用。
## 托盘菜单
@@ -101,28 +114,11 @@
| 组件 | 小组件实例列表,可选择组件并显示/隐藏或锁定/解锁 |
| 插件 | 已扫描插件的名称、类型、状态、入口和错误码 |
| 诊断 | 诊断记录和插件 manifest 错误摘要 |
| Log | 加载当天日志,并随管理窗口刷新周期显示新增日志 |
## 动态壁纸
## 通用组件操作
Moli.Desktop 使用 WebView2 加载 H5 壁纸。默认样例为 `sample.wallpaper`。
常用操作:
1. 打开托盘菜单或管理窗口。
2. 点击“启用壁纸”显示壁纸。
3. 点击“禁用壁纸”关闭壁纸。
4. 如果桌面鼠标操作受影响,打开“安全输入模式”恢复可操作状态。
壁纸层设计目标是位于桌面图标之后,与原生桌面融合。不同 Windows 桌面状态、显卡驱动和 WebView2 Runtime 状态可能影响实际表现;如显示异常,请先查看诊断页和日志目录。
## 桌面小组件
小组件来自本地 HTML 插件。默认样例包含:
| 插件 | 用途 |
| --- | --- |
| `sample.clock` | 时钟小组件 |
| `sample.system-info` | 系统信息占位小组件 |
小组件来自本地 HTML 插件。每个小组件都可以通过管理窗口进行显示、隐藏、锁定和解锁。
### 显示或隐藏组件
@@ -160,6 +156,8 @@
```text
%AppData%\DesktopEnhancer\plugins\<pluginId>
```
发布或默认样例更新时,如果插件目录中已经存在 `plugin.json`,应用会保留现有配置,并把新版本样例配置写入 `plugin.template.json`。首次不存在配置时才会初始化 `plugin.json`。
添加本地插件的一般流程:
@@ -280,7 +278,7 @@
- 检查 Windows 托盘隐藏区域。
- 确认 `Moli.Desktop.exe` 进程是否仍在运行。
- 查看 `%LocalAppData%\DesktopEnhancer\logs`。
- 查看程序目录下的 `logs`,或打开管理窗口的 “Log” 页面。
- 如果从源码运行,先确认 `dotnet build Moli.Desktop.slnx` 成功。
### 壁纸或组件没有显示
@@ -325,4 +323,3 @@
- 开机启动通过当前用户 HKCU Run 注册表实现。
- 管理窗口的“重置布局”是软重置,不会重新创建组件实例。
- WebView2 Runtime 缺失、桌面层级和点击穿透行为需要在真实 Windows 桌面环境中验证。
docs/ops/user-manual/plugins/sample.audio-visualizer.md
New file
@@ -0,0 +1,77 @@
# sample.audio-visualizer 音乐律动插件手册
日期:2026-05-04
## 插件用途
`sample.audio-visualizer` 是内置音乐律动小组件。它以透明背景显示一组横向铺开的竖线,根据音频频谱或占位动效进行律动,用于验证桌面音频可视化、透明渲染和桥接事件能力。
## 默认布局
默认安装时,宿主会按主屏尺寸生成布局:
| 字段 | 默认行为 |
| --- | --- |
| `x` | `0` |
| `width` | 主屏宽度 |
| `y` | 约为主屏高度的 `2/3` |
| `height` | 不超过主屏高度的 `25%` |
| `displayLayer` | `desktop` |
| `clickThrough` | 通常开启,避免影响桌面操作 |
## 使用方式
1. 启动 Moli.Desktop。
2. 确认 `sample.audio-visualizer` 已在“插件”页面启用。
3. 播放系统音频。
4. 在桌面上查看律动效果。
如果系统不允许音频采集,插件仍应显示低强度占位动效,避免桌面区域为空白。
## 移动与锁定
如果需要调整位置:
1. 打开管理窗口。
2. 进入“组件”页面。
3. 选择 `sample.audio-visualizer.default`。
4. 解锁组件。
5. 进入编辑模式调整位置或尺寸。
6. 退出编辑模式保存布局。
## 插件文件
默认插件目录:
```text
%AppData%\DesktopEnhancer\plugins\sample.audio-visualizer
```
源码样例目录:
```text
samples\plugins\sample.audio-visualizer
```
关键文件:
| 文件 | 说明 |
| --- | --- |
| `plugin.json` | 插件 manifest |
| `index.html` | 当前插件入口 |
| `demo.html` | 视觉参考或演示页面 |
## 常见问题
### 没有随音乐变化
- 确认系统正在播放音频。
- 检查插件是否有 `audio-capture` 权限。
- 如果音频采集不可用,插件可能显示占位动效。
- 查看日志目录和诊断页面是否存在音频采集错误。
### 律动条挡住桌面点击
- 在管理窗口检查该组件点击穿透状态。
- 从托盘菜单开启“安全输入模式”恢复控制。
docs/ops/user-manual/plugins/sample.clock.md
New file
@@ -0,0 +1,58 @@
# sample.clock 时钟插件手册
日期:2026-05-04
## 插件用途
`sample.clock` 是内置桌面时钟小组件,用于显示当前时间,并验证普通 widget 的加载、布局、锁定和显示隐藏能力。
## 显示与隐藏
1. 打开管理窗口。
2. 进入“组件”页面。
3. 选择 `sample.clock.default`。
4. 点击“显示/隐藏”。
## 移动与锁定
1. 在管理窗口选择 `sample.clock.default`。
2. 点击“锁定/解锁”解除锁定。
3. 进入编辑模式。
4. 在桌面上拖动时钟到目标位置。
5. 退出编辑模式,布局会保存到 `layout.json`。
## 插件文件
默认插件目录:
```text
%AppData%\DesktopEnhancer\plugins\sample.clock
```
源码样例目录:
```text
samples\plugins\sample.clock
```
关键文件:
| 文件 | 说明 |
| --- | --- |
| `plugin.json` | 插件 manifest |
| `index.html` | 时钟页面入口 |
## 常见问题
### 时钟不显示
- 确认组件没有被隐藏。
- 确认 `sample.clock` 插件状态为 enabled。
- 点击“重载插件”。
- 查看诊断页是否存在 manifest 或 entry 错误。
### 时钟位置不合适
- 解锁组件后进入编辑模式调整位置。
- 如果组件跑到屏幕外,可使用管理窗口“重置布局”。
docs/ops/user-manual/plugins/sample.llm-command-palette.md
New file
@@ -0,0 +1,331 @@
# sample.llm-command-palette LLM 桌面输入插件手册
日期:2026-05-04
## 插件用途
`sample.llm-command-palette` 是一个顶部居中的桌面输入条。它支持在输入框中直接输入问题,按 Enter 提交,右侧下拉选择模型,并在输入框下方展开流式输出。
## 使用前准备
使用该插件前,需要根据运行模式准备不同服务:
| 模式 | 需要准备 |
| --- | --- |
| 供应商直连模式 | 至少一个可访问的 LLM 接口,例如 OpenAI-compatible、DeepSeek、本地 Ollama/LM Studio 等兼容接口 |
| 自有 API 模式 | 可访问的 AiChat 服务、已审批账号、密码或密码环境变量 |
AiChat 默认服务地址:
```text
http://192.168.1.111:13000
```
## 默认行为
| 项目 | 默认行为 |
| --- | --- |
| 位置 | 主屏顶部居中,顶部保留约 `32px` 空隙 |
| 默认模式 | 供应商直连模式 |
| 左侧下拉 | AiChat 项目列表 |
| 显示层级 | `desktop` |
| 点击穿透 | 关闭,便于接收键盘和鼠标输入 |
| 锁定状态 | 锁定,避免误拖动 |
| 提交方式 | Enter 提交,不提供提交按钮 |
| 换行方式 | Shift+Enter |
| 输出区域 | 输入框底部展开,最大高度约为屏幕高度 `50%` |
## 选择运行模式
LLM 插件支持两种模式:
| 模式 | 配置值 | 行为 |
| --- | --- | --- |
| 供应商直连模式 | `provider-direct` | 使用 Moli.Desktop 宿主 LLM 代理调用供应商模型;可复用 AiChat 记忆接口 |
| 自有 API 模式 | `aichat-api` | 使用 AiChat 项目、模型和聊天 SSE;插件不单独处理记忆 |
插件配置示例:
```json
{
  "mode": "provider-direct",
  "aichat": {
    "baseUrl": "http://192.168.1.111:13000",
    "account": {
      "email": "user@example.com",
      "password": null,
      "passwordEnv": "MOLI_AICHAT_PASSWORD"
    },
    "defaultProjectId": "",
    "memory": {
      "enabledInProviderDirect": true,
      "defaultScope": "PROJECT",
      "recallLimit": 8
    }
  }
}
```
缺少 `mode` 时,插件按 `provider-direct` 处理,以兼容旧配置。
## 配置 AiChat 账号
AiChat 账号信息只用于插件与 AiChat 服务交互。
账号允许直接写在配置中:
```json
{
  "email": "user@example.com"
}
```
密码建议使用环境变量。配置中的 `passwordEnv` 优先于明文 `password`:
```powershell
[Environment]::SetEnvironmentVariable(
  "MOLI_AICHAT_PASSWORD",
  "你的 AiChat 密码",
  "User"
)
```
设置后请重启 Moli.Desktop,让新环境变量对桌面进程生效。登录成功后的 Session Token 只保存在宿主运行态,不写入插件配置。
## 配置模型
LLM 插件不会直接保存供应商密钥,也不会把 endpoint 暴露给插件前端。宿主会读取模型注册表,根据用户选择的 `modelId` 路由到对应供应商和 endpoint。
模型配置文件位于:
```text
%AppData%\DesktopEnhancer\config\llm-models.json
```
首次启动后,如果文件不存在,应用会生成默认文件。当前管理窗口尚未提供模型编辑页面,短期可手工编辑该文件。
示例配置:
```json
{
  "schemaVersion": 1,
  "defaultModel": "deepseek-chat",
  "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",
      "provider": "openai-compatible",
      "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
      "authRef": null,
      "apiModel": "qwen2.5:14b",
      "supportsStreaming": true,
      "enabled": true,
      "requestDefaults": {
        "temperature": 0.6,
        "maxTokens": 2048,
        "timeoutMs": 120000
      }
    }
  ]
}
```
字段说明:
| 字段 | 说明 |
| --- | --- |
| `id` | 插件下拉和请求使用的模型 ID,必须唯一 |
| `label` | 下拉中显示的名称,建议短一点 |
| `provider` | 供应商或协议适配器,例如 `openai-compatible`、`deepseek`、`ollama` |
| `endpoint` | 当前模型自己的请求 URL,可每个模型不同 |
| `authRef` | 密钥引用,不是明文密钥;本地无鉴权模型可填 `null` |
| `apiModel` | 发送给上游接口的真实模型名 |
| `supportsStreaming` | 是否支持流式输出 |
| `enabled` | 是否显示在插件模型下拉中 |
当前 `deepseek`、`ollama` 和 `local-openai-compatible` 会复用 OpenAI-compatible 适配器。如果某个供应商接口不兼容 OpenAI-compatible 流式格式,需要后续新增独立适配器。
自有 API 模式下,模型列表来自 AiChat:
```text
GET /api/chat/models
```
插件只展示 AiChat 返回的可用模型,并在提交时把所选模型作为 `modelName` 传给 AiChat。
## 配置密钥
当前版本使用环境变量作为密钥 fallback。`authRef` 会按以下方式解析:
1. 直接读取同名环境变量。
2. 如果不存在,把 `authRef` 转成 `MOLI_` 前缀的大写环境变量名。
例如:
```text
authRef = llm.deepseek.primary
```
可设置环境变量:
```powershell
[Environment]::SetEnvironmentVariable(
  "MOLI_LLM_DEEPSEEK_PRIMARY",
  "你的 API Key",
  "User"
)
```
设置后请重启 Moli.Desktop,让新环境变量对桌面进程生效。
如果使用本地无鉴权服务,例如本机 Ollama 或 LM Studio 的 OpenAI-compatible endpoint,可以将 `authRef` 设置为 `null`。
## 使用输入条
1. 启动 Moli.Desktop。
2. 确认 `sample.llm-command-palette` 已在“插件”页面中启用。
3. 在桌面顶部找到半透明输入条。
4. 在左侧项目下拉中选择 AiChat 项目。
5. 在右侧模型下拉中选择模型。
6. 输入问题。
7. 按 Enter 提交。
8. 在输入框下方查看流式输出。
项目下拉说明:
| 状态 | 含义 |
| --- | --- |
| 显示项目名称 | 已成功调用 AiChat `GET /api/projects` |
| `No project` | 未配置 AiChat、登录失败或项目列表为空 |
| 登录/权限错误 | 检查账号审批状态、密码环境变量和 AiChat 服务地址 |
在自有 API 模式下,提交会携带当前项目 ID。未选择项目时,AiChat 会按自身接口规则使用或创建默认项目,但建议明确选择项目。
项目和模型下拉使用插件自绘的圆角扁平控件。展开下拉时,输入条会临时请求宿主增高组件窗口,避免选项列表被原始组件高度裁剪;选择完成或点击外部后会恢复到默认高度。
## 记忆管理
供应商直连模式下,插件可以使用 AiChat 记忆接口:
| 操作 | AiChat 接口 |
| --- | --- |
| 查询记忆 | `GET /api/memories?scope={scope}&projectId={projectId}` |
| 创建记忆 | `POST /api/memories` |
| 删除记忆 | `DELETE /api/memories/{memoryId}` |
| 召回记忆 | `POST /api/memories/recall` |
权限来自 AiChat 当前用户:
- `canViewMemory` 控制是否能查看记忆。
- `canManageMemory` 控制是否能创建或删除记忆。
- `canUseMemory` 控制是否能召回记忆并用于直连模型上下文。
自有 API 模式下,插件不单独展示或执行记忆管理。聊天中的记忆使用由 AiChat 服务和项目设置处理。
快捷操作:
| 操作 | 效果 |
| --- | --- |
| Enter | 提交当前输入 |
| Shift+Enter | 在输入框内换行 |
| Escape | 收起已展开的输出区域 |
| Copy 按钮 | 复制当前输出文本 |
| Collapse 按钮 | 收起输出区域 |
如果请求正在进行,重复按 Enter 默认不会发起新的请求。请等待当前请求完成,或后续版本使用取消功能。
## 调整位置和层级
LLM 插件默认锁定并位于 `desktop` 层。如果需要移动:
1. 打开管理窗口。
2. 进入“组件”页面。
3. 选择 `sample.llm-command-palette.default`。
4. 解锁组件。
5. 进入编辑模式并调整位置。
6. 调整完成后退出编辑模式,并按需重新锁定。
如果希望输入条覆盖普通应用窗口,可在布局配置或后续管理 UI 中将显示层级改为 `app-top` 或 `global-top`。使用 `global-top` 时请确保托盘仍可访问,便于恢复控制。
## 备份
建议备份:
```text
%AppData%\DesktopEnhancer\config\llm-models.json
%AppData%\DesktopEnhancer\plugins\sample.llm-command-palette
```
## 常见问题
### 下拉中没有模型
- 检查 `%AppData%\DesktopEnhancer\config\llm-models.json` 是否存在。
- 确认至少有一个模型的 `enabled` 为 `true`。
- 确认模型的 `endpoint` 是 `http` 或 `https` 绝对 URL。
- 如果当前是自有 API 模式,检查 AiChat `GET /api/chat/models` 是否可用。
- 修正配置后重启应用,或在管理窗口中重载插件。
### 项目下拉为空
- 检查 AiChat 服务地址是否为 `http://192.168.1.111:13000` 或你的实际配置。
- 检查账号和密码环境变量是否正确。
- 调用 AiChat `GET /api/auth/me` 确认账号已审批。
- 调用 AiChat `GET /api/projects` 确认账号有项目。
### 自有 API 模式无法输出
- 检查 AiChat 登录是否成功。
- 检查所选模型是否在 AiChat `GET /api/chat/models` 返回列表中。
- 如果返回 `TOKEN_TOTAL_LIMIT_REACHED`,需要在 AiChat 中申请或调整 Token 配额。
- 如果返回 `INVALID_MODEL`,需要在 AiChat 服务端启用对应模型。
- 如果 SSE 中断,保留已输出内容后重试。
### 请求提示密钥缺失
- 检查模型配置中的 `authRef`。
- 确认已设置对应环境变量。
- 如果刚设置环境变量,请重启 Moli.Desktop。
- 本地无鉴权模型可将 `authRef` 设置为 `null`。
### 请求提示 endpoint 不可达
- 确认 `endpoint` 地址正确。
- 如果是本地模型服务,确认服务已启动并监听对应端口。
- 如果是远程供应商,确认当前网络可访问该供应商 API。
- 检查日志目录 `%LocalAppData%\DesktopEnhancer\logs`,日志只会记录 endpoint host,不会记录完整 API key。
### 记忆功能不可用
- 记忆管理只在供应商直连模式下由插件处理。
- 检查 AiChat 当前用户是否有 `canUseMemory`、`canViewMemory` 或 `canManageMemory` 权限。
- 项目记忆必须选择项目后使用。
### 没有流式输出
- 确认上游接口支持 OpenAI-compatible SSE 流式输出。
- 确认模型配置 `supportsStreaming` 为 `true`。
- 如果供应商不是 OpenAI-compatible,当前版本可能需要新增对应 provider adapter。
## 当前限制
- 模型配置当前主要通过手工编辑 `llm-models.json` 完成。
- 密钥当前使用环境变量 fallback,Windows Credential Manager 管理界面尚未实现。
- 当前已实现 OpenAI-compatible 流式协议;非兼容供应商需要后续新增适配器。
- 自有 API 模式暂不在插件中提供会话下拉,提交时使用所选项目的默认会话规则。
- 自有 API 模式不在插件中管理记忆。
docs/ops/user-manual/plugins/sample.system-info.md
New file
@@ -0,0 +1,58 @@
# sample.system-info 系统信息插件手册
日期:2026-05-04
## 插件用途
`sample.system-info` 是系统信息占位小组件,用于验证普通信息类 widget 的加载、透明背景、布局和显示隐藏能力。
当前样例以展示基本系统信息或占位内容为主,不代表完整性能监控能力。
## 显示与隐藏
1. 打开管理窗口。
2. 进入“组件”页面。
3. 选择 `sample.system-info.default`。
4. 点击“显示/隐藏”。
## 移动与锁定
1. 在管理窗口选择 `sample.system-info.default`。
2. 点击“锁定/解锁”。
3. 进入编辑模式。
4. 在桌面上调整位置和尺寸。
5. 退出编辑模式保存布局。
## 插件文件
默认插件目录:
```text
%AppData%\DesktopEnhancer\plugins\sample.system-info
```
源码样例目录:
```text
samples\plugins\sample.system-info
```
关键文件:
| 文件 | 说明 |
| --- | --- |
| `plugin.json` | 插件 manifest |
| `index.html` | 系统信息页面入口 |
## 常见问题
### 信息没有刷新
- 当前样例主要用于展示和验证宿主插件能力,实时系统采集能力有限。
- 点击“重载插件”可重新加载页面。
### 插件显示错误
- 检查 `plugin.json` 是否存在。
- 检查管理窗口“插件”和“诊断”页面。
docs/ops/user-manual/plugins/sample.wallpaper.md
New file
@@ -0,0 +1,59 @@
# sample.wallpaper 动态壁纸插件手册
日期:2026-05-04
## 插件用途
`sample.wallpaper` 是内置 H5 动态壁纸样例,用于验证 WebView2 壁纸加载、透明背景、点击穿透和桌面层级能力。
## 启用与禁用
1. 启动 Moli.Desktop。
2. 右键托盘图标,或打开管理窗口。
3. 点击“启用壁纸”显示壁纸。
4. 点击“禁用壁纸”关闭壁纸。
如果壁纸影响鼠标操作,请从托盘菜单开启“安全输入模式”。
## 插件文件
默认插件目录:
```text
%AppData%\DesktopEnhancer\plugins\sample.wallpaper
```
源码样例目录:
```text
samples\plugins\sample.wallpaper
```
关键文件:
| 文件 | 说明 |
| --- | --- |
| `plugin.json` | 插件 manifest |
| `index.html` | H5 壁纸入口 |
## 布局与显示
壁纸插件通常作为 `wallpaper` 类型运行,由宿主创建壁纸窗口并覆盖目标显示器。壁纸层目标是位于桌面图标之后,与原生桌面融合。
不同 Windows 桌面状态、显卡驱动和 WebView2 Runtime 状态可能影响实际表现;如显示异常,请先查看管理窗口“诊断”页和日志目录。
## 常见问题
### 壁纸没有显示
- 确认插件目录中存在 `plugin.json` 和 `index.html`。
- 在管理窗口“插件”页面查看 `sample.wallpaper` 状态。
- 点击“重载插件”。
- 确认 WebView2 Runtime 已安装。
### 壁纸挡住桌面点击
- 从托盘菜单开启“安全输入模式”。
- 在管理窗口检查壁纸点击穿透状态。
- 必要时禁用壁纸后重新启用。
docs/ops/user-manual/plugins/sample.webview-test.md
New file
@@ -0,0 +1,47 @@
# sample.webview-test WebView 测试插件手册
日期:2026-05-04
## 插件用途
`sample.webview-test` 是开发和手工验证用插件,用于检查 WebView2 加载、宿主桥接、插件 manifest、透明背景和基础运行时状态。
该插件不是面向普通用户的默认功能插件,通常用于开发、QA 或现场排障。
## 使用方式
1. 将插件目录复制到 `%AppData%\DesktopEnhancer\plugins\sample.webview-test`。
2. 打开管理窗口。
3. 点击“重载插件”。
4. 在“插件”页面确认 `sample.webview-test` 状态。
5. 如需显示为组件,确认 `plugins.json` 和 `layout.json` 中有对应启用状态和布局实例。
## 插件文件
源码样例目录:
```text
samples\plugins\sample.webview-test
```
关键文件:
| 文件 | 说明 |
| --- | --- |
| `plugin.json` | 插件 manifest |
| `index.html` | WebView 测试入口 |
## 常见问题
### 插件没有出现在列表中
- 确认插件目录名和 `plugin.json` 存在。
- 点击“重载插件”。
- 查看管理窗口“诊断”页面。
### 页面加载失败
- 检查 `plugin.json` 中的 `entry` 是否指向存在的入口文件。
- 确认 WebView2 Runtime 已安装。
- 查看日志目录 `%LocalAppData%\DesktopEnhancer\logs`。
docs/product/desktop-enhancement-prd.md
@@ -114,7 +114,7 @@
  - `global-top`:全局置顶,允许覆盖其他应用窗口。
- 壁纸类内容默认使用 `desktop`;普通信息类小组件默认使用 `desktop` 或 `normal`;需要跨应用提醒、悬浮控制或演示场景的组件才应使用 `app-top` 或 `global-top`。
- 用户必须能够按组件实例切换显示层级,且切换结果必须持久化。
- `desktop` 层组件必须在用户触发 Win+D 显示桌面后仍保持可见;系统不支持 WorkerW 挂载时允许降级,但必须记录诊断并在 QA 记录中标注该环境限制。
- `desktop` 层组件必须在用户触发 Win+D 显示桌面后仍保持可见;系统不支持 WorkerW/Progman 桌面宿主挂载时允许降级,但必须记录诊断并在 QA 记录中标注该环境限制。
- 组件必须支持在编辑模式下拖拽和缩放。
- 已锁定组件必须拒绝拖拽和缩放操作。
- 应用必须支持按组件维度的配置。
docs/product/llm-command-palette-plugin-prd.md
@@ -24,9 +24,15 @@
- 提供一个顶部居中的 LLM 输入插件,默认在屏幕顶部保留呼吸空隙。
- 支持用户输入文本后按回车提交,不提供独立提交按钮。
- 支持在输入框右侧嵌入模型下拉选择。
- 支持两种运行模式,并可通过插件配置选择:
  - 供应商直连模式:继续使用当前宿主 LLM 代理,按 `modelId` 直连 OpenAI-compatible、DeepSeek、本地模型等供应商。
  - 自有 API 模式:接入自有 `AiChat` 服务,统一 Host 默认为 `http://192.168.1.111:13000`。
- 支持在输入框左侧嵌入 AiChat 项目下拉;右侧保留模型下拉。
- 支持多个 LLM 模型,模型清单来自插件配置或宿主配置。
- 支持调用 LLM 接口并将结果流式展示在输入框下方。
- 支持在供应商直连模式下通过 AiChat API 进行记忆查询、创建、删除和召回管理。
- 支持在自有 API 模式下使用 AiChat 项目上下文发起聊天;该模式下不处理插件侧记忆管理。
- 支持在插件配置中维护 AiChat 服务交互所需的用户信息,账号允许明文配置,密码允许引用环境变量。
- 输出区域与输入框保持同宽、同视觉风格,最大高度不超过屏幕高度的 `50%`。
- 保持桌面浮层轻量、透明、可读、可恢复控制。
@@ -34,6 +40,8 @@
- 不做完整多会话聊天应用。
- 不在插件内实现账号体系、计费管理或复杂知识库。
- 不在 Moli.Desktop 内重新实现 AiChat 的项目、会话、审批、权限和配额系统。
- 不在自有 API 模式下重复实现记忆管理;记忆由 AiChat 自身聊天链路和项目设置处理。
- 不在 MVP 中支持文件上传、图片理解、语音输入或多模态输出。
- 不要求替代管理窗口或系统托盘入口。
- 不把 LLM API key 明文写入插件前端源码。
@@ -49,10 +57,14 @@
## 用户故事
- 作为用户,我可以在桌面顶部直接输入问题并按回车提交,这样我能快速得到 LLM 回复。
- 作为用户,我可以在插件配置中选择供应商直连或 AiChat 自有 API,这样同一个桌面输入条既能调用外部模型,也能进入自有服务的项目上下文。
- 作为用户,我可以在输入框左侧选择 AiChat 项目,这样每次提问都能进入对应项目和默认会话。
- 作为用户,我可以在输入框右侧切换模型,这样我能按任务选择更快或更强的模型。
- 作为用户,我可以在回复生成时看到逐步流式输出,这样我知道请求正在进行。
- 作为用户,我可以继续编辑输入内容、复制输出内容或按 Escape 收起结果,这样桌面不会被长文本长期占据。
- 作为用户,我可以通过管理窗口或配置切换 API endpoint、模型列表和默认模型,这样插件能适配不同 LLM 服务。
- 作为用户,我可以通过管理窗口或配置维护不同供应商的模型、endpoint 和默认模型,这样插件能同时接入 OpenAI-compatible、DeepSeek、本地模型或后续新增供应商。
- 作为用户,我可以在供应商直连模式下查看、手动添加、删除和召回 AiChat 记忆,这样直连供应商时也能复用我在 AiChat 中维护的长期记忆。
- 作为用户,我可以把 AiChat 密码放在环境变量里,这样配置文件不需要保存密码明文。
## 插件类型
@@ -100,7 +112,11 @@
- 输入条为单行优先,长文本可在达到宽度后轻微增高到最多 3 行。
- 占位文案:`What can I help you with today?` 或后续本地化为中文。
- 左侧展示状态图标:
- 输入框左侧展示项目下拉:
  - 自有 API 模式下必须从 AiChat `GET /api/projects` 获取项目列表。
  - 供应商直连模式下如果已配置 AiChat 账号,也应显示项目下拉,用于记忆查询、创建、删除和召回的项目上下文。
  - 未登录、未配置或接口不可用时显示明确降级状态,例如 `No project`,不阻塞无项目直连提问。
- 项目下拉左侧或输入条前缀位置展示状态图标:
  - 空闲:品牌或星芒图标。
  - 请求中:细小旋转状态。
  - 错误:低饱和警示状态。
@@ -139,9 +155,9 @@
### 错误状态
- API key 缺失、endpoint 不可达、模型不可用、请求超时和流式解析失败必须展示短错误。
- API key 缺失、模型 endpoint 不可达、模型不可用、请求超时和流式解析失败必须展示短错误。
- 错误信息显示在输出区域内,不弹出系统模态框。
- 错误文本应包含可操作方向,例如“请在插件配置中检查 endpoint 和密钥”。
- 错误文本应包含可操作方向,例如“请在模型配置中检查该模型的 endpoint 和密钥”。
## 视觉设计
@@ -172,23 +188,103 @@
## 模型配置
插件配置应支持:
插件配置必须显式区分运行模式。插件前端只需要知道可展示的项目、模型清单和默认模型。具体供应商、endpoint、鉴权方式、AiChat 登录态和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `mode`、`projectId`、`modelId` 和消息内容。
### 运行模式
| 模式 | 配置值 | 聊天入口 | 模型来源 | 记忆管理 |
| --- | --- | --- | --- | --- |
| 供应商直连模式 | `provider-direct` | `window.moliDesktop.llm.streamChat` -> 供应商适配器 | `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 应尽量选择明确项目。
- 两种模式都不得把密码、Session Token、供应商 API key 暴露给插件页面日志或可复制错误信息。
### AiChat 用户配置
AiChat 服务配置属于插件运行配置,但凭据解析由宿主执行。统一 Host 不参考 AiChat 接口文档,以用户给定值为准:
```json
{
  "provider": "openai-compatible",
  "endpoint": "https://api.example.com/v1/chat/completions",
  "mode": "provider-direct",
  "aichat": {
    "baseUrl": "http://192.168.1.111:13000",
    "account": {
      "email": "user@example.com",
      "password": null,
      "passwordEnv": "MOLI_AICHAT_PASSWORD"
    },
    "defaultProjectId": "",
    "memory": {
      "enabledInProviderDirect": true,
      "defaultScope": "PROJECT",
      "recallLimit": 8
    }
  }
}
```
字段说明:
| 字段 | 说明 |
| --- | --- |
| `mode` | `provider-direct` 或 `aichat-api`,默认 `provider-direct`。 |
| `aichat.baseUrl` | AiChat 服务 Host,默认 `http://192.168.1.111:13000`。 |
| `aichat.account.email` | AiChat 登录账号,允许明文配置。 |
| `aichat.account.password` | AiChat 登录密码明文,仅允许个人本地测试,不推荐。 |
| `aichat.account.passwordEnv` | 密码环境变量名,优先级高于 `password`。 |
| `aichat.defaultProjectId` | 默认选中的 AiChat 项目 ID,可为空。 |
| `aichat.memory.enabledInProviderDirect` | 供应商直连模式下是否启用 AiChat 记忆管理。 |
| `aichat.memory.defaultScope` | `GLOBAL`、`PROJECT` 或 `ALL`,用于召回和记忆管理默认范围。 |
| `aichat.memory.recallLimit` | 召回数量,建议 `1..20`。 |
AiChat 鉴权流程:
1. `POST /api/auth/login`,请求体包含 `email` 和解析后的密码。
2. 保存响应 `data.sessionToken` 到宿主内存态。
3. 后续请求携带 `x-session-token: <sessionToken>`。
4. 可选调用 `GET /api/auth/me` 校验审批状态、记忆权限和项目权限。
5. Session 过期或返回 `401` 时重新登录一次;仍失败则在插件输出区展示可操作错误。
推荐采用“按模型路由”的配置结构:每个模型都可以绑定独立 provider、URL、鉴权引用和请求适配参数。这样同一个插件可以同时接入不同供应商,也可以接入同一供应商的不同 base URL。
```json
{
  "defaultModel": "gpt-5.4",
  "models": [
    {
      "id": "gpt-5.4",
      "label": "GPT-5.4",
      "supportsStreaming": true
      "provider": "openai-compatible",
      "endpoint": "https://api.openai.example/v1/chat/completions",
      "authRef": "llm.openai.primary",
      "apiModel": "gpt-5.4",
      "supportsStreaming": true,
      "enabled": true
    },
    {
      "id": "deepseek-chat",
      "label": "DeepSeek",
      "supportsStreaming": true
      "provider": "deepseek",
      "endpoint": "https://api.deepseek.com/chat/completions",
      "authRef": "llm.deepseek.primary",
      "apiModel": "deepseek-chat",
      "supportsStreaming": true,
      "enabled": true
    },
    {
      "id": "local-qwen",
      "label": "Local Qwen",
      "provider": "openai-compatible",
      "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
      "authRef": null,
      "apiModel": "qwen2.5:14b",
      "supportsStreaming": true,
      "enabled": false
    }
  ],
  "request": {
@@ -199,7 +295,33 @@
}
```
API key 不应存放在前端 `index.html` 或公开配置中。MVP 建议由宿主提供本地 LLM 代理能力,插件只向宿主请求流式生成;如果短期直接从插件调用远程 OpenAI-compatible endpoint,则必须在文档和管理界面中明确提示密钥暴露风险,并仅用于本地个人测试。
字段说明:
| 字段 | 说明 |
| --- | --- |
| `id` | 插件 UI 和请求中使用的稳定模型 id。 |
| `label` | 下拉中展示的短名称。 |
| `provider` | 供应商或协议适配器,例如 `openai-compatible`、`deepseek`、`anthropic`、`ollama`。 |
| `endpoint` | 当前模型使用的完整请求 URL,允许每个模型不同。 |
| `authRef` | 宿主侧密钥引用,不是明文密钥;本地无鉴权模型可为 `null`。 |
| `apiModel` | 发送给上游 API 的真实模型名。 |
| `supportsStreaming` | 是否允许流式输出;不支持时宿主可降级为一次性返回。 |
| `enabled` | 是否在插件模型下拉中显示。 |
API key 不应存放在前端 `index.html` 或公开配置中。MVP 建议由宿主提供本地 LLM 代理能力,插件只向宿主请求流式生成;宿主再根据 `modelId` 找到 provider、endpoint、authRef 和 apiModel 并调用对应供应商。如果短期直接从插件调用远程 endpoint,则必须在文档和管理界面中明确提示密钥暴露风险,并仅用于本地个人测试。
### 路由策略
推荐路线:
1. 插件调用宿主:`modelId + messages + options`。
2. 宿主读取 LLM 模型注册表。
3. 宿主按 `modelId` 找到对应模型配置。
4. 宿主按 `provider` 选择适配器。
5. 适配器按该模型的 `endpoint`、`authRef`、`apiModel` 发起请求。
6. 宿主把供应商流式响应统一转换为 `llm.delta`、`llm.completed`、`llm.error` 事件。
这种设计比插件端直接按供应商写多套请求更稳:模型可独立配置 URL,密钥留在宿主侧,插件 UI 只关心“用户选了哪个模型”。
## 宿主与插件通信
@@ -207,7 +329,9 @@
```javascript
window.moliDesktop.llm.streamChat({
  model: "gpt-5.4",
  mode: "provider-direct",
  projectId: "aichat_project_id",
  modelId: "gpt-5.4",
  messages: [
    { role: "user", content: "..." }
  ],
@@ -217,6 +341,36 @@
  }
});
```
插件不应直接传 provider、endpoint 或密钥。宿主响应中可返回本次请求实际命中的供应商和模型,用于诊断和 UI tooltip,但不返回密钥。
新增 AiChat 相关桥接能力建议:
```typescript
window.moliDesktop.llm = {
  getConnectionMode(): Promise<"provider-direct" | "aichat-api">;
  setConnectionMode(mode: "provider-direct" | "aichat-api"): Promise<void>;
  getProjects(): Promise<Array<{ id: string; name: string; projectType: "CHAT" | "REMOTE"; memoryMode: string }>>;
  getMemories(options: { scope?: "GLOBAL" | "PROJECT"; projectId?: string }): Promise<object>;
  createMemory(input: { scope: "GLOBAL" | "PROJECT"; projectId?: string; content: string }): Promise<object>;
  deleteMemory(memoryId: string): Promise<void>;
  recallMemories(input: { query: string; scope?: "GLOBAL" | "PROJECT" | "ALL"; projectId?: string; limit?: number }): Promise<object>;
};
```
项目下拉数据来自 AiChat `GET /api/projects`。记忆管理接口来自 AiChat:
- `GET /api/memories?scope={scope}&projectId={projectId}`
- `POST /api/memories`
- `DELETE /api/memories/{memoryId}`
- `POST /api/memories/recall`
自有 API 模式聊天调用:
- `POST /api/chat/send`
- `GET /api/chat/generations/{generationId}/stream?token={streamToken}`
自有 API 模式可使用 AiChat 项目和会话规则;插件 MVP 不必提供会话下拉,只需以所选 `projectId` 提交,让 AiChat 使用或创建该项目默认会话。
流式事件建议:
@@ -278,9 +432,19 @@
    "displayLayer": "desktop"
  },
  "config": {
    "provider": "openai-compatible",
    "defaultModel": "gpt-5.4",
    "models": []
    "models": [
      {
        "id": "gpt-5.4",
        "label": "GPT-5.4",
        "provider": "openai-compatible",
        "endpoint": "",
        "authRef": "",
        "apiModel": "gpt-5.4",
        "supportsStreaming": true,
        "enabled": false
      }
    ]
  }
}
```
@@ -301,9 +465,71 @@
### FR-LLM-02 模型选择
- 插件必须在输入框右侧提供模型下拉。
- 模型下拉必须从配置读取模型清单。
- 供应商直连模式下,模型下拉必须从宿主 LLM 模型注册表读取模型清单。
- 自有 API 模式下,模型下拉必须优先从 AiChat `GET /api/chat/models` 读取模型清单。
- 模型切换必须影响下一次提交。
- 当前请求进行中时,模型切换不得影响已发出的请求。
优先级:P1
### FR-LLM-07 运行模式选择
- 插件必须支持 `provider-direct` 和 `aichat-api` 两种运行模式。
- 模式必须可通过插件配置选择,并能在后续管理 UI 中展示。
- 默认模式必须为 `provider-direct`,保证现有供应商直连行为兼容。
- 模式切换后,项目下拉、模型下拉、聊天提交路径和记忆入口必须按模式刷新。
优先级:P1
### FR-LLM-08 AiChat 项目下拉
- 输入框左侧必须提供 AiChat 项目下拉列表。
- 项目列表必须调用 AiChat `GET /api/projects` 获取。
- 登录失败、账号未审批、无权限或接口不可达时,项目下拉必须展示可理解降级状态。
- 自有 API 模式下提交聊天时必须使用当前选中项目;未选项目时允许按 AiChat 默认项目规则降级。
- 供应商直连模式下,项目选择用于记忆管理和召回上下文,不得强制阻塞直连聊天。
优先级:P1
### FR-LLM-09 AiChat 用户配置
- 插件配置必须包含 AiChat `baseUrl`、账号和密码引用。
- `baseUrl` 默认值为 `http://192.168.1.111:13000`。
- 账号允许明文配置。
- 密码必须支持环境变量引用,且环境变量值优先于明文字段。
- 登录成功后的 `sessionToken` 必须只保存在宿主运行态,不写入插件前端或普通配置文件。
- 日志不得输出密码、Session Token 或完整请求头。
优先级:P1
### FR-LLM-10 自有 API 模式聊天
- 自有 API 模式下,插件必须通过 AiChat `POST /api/chat/send` 发起聊天。
- 插件必须使用 AiChat 返回的 `generationId` 和 `streamToken` 订阅 SSE。
- 插件必须处理 `snapshot`、`chunk`、`processing`、`done`、`failed` 和 `aborted` 事件。
- 插件必须把 AiChat 错误码映射为可理解错误,例如未登录、待审批、模型不可用、配额耗尽和消息数超限。
- 自有 API 模式下无需插件侧记忆管理;不得重复调用记忆召回接口拼装 Prompt。
优先级:P1
### FR-LLM-11 供应商直连模式记忆管理
- 供应商直连模式下,如果配置了 AiChat 账号且用户具备权限,插件必须支持 AiChat 记忆管理。
- 插件必须支持查询全局记忆和项目记忆。
- 插件必须支持手动创建全局记忆和项目记忆。
- 插件必须支持删除记忆。
- 插件必须支持按当前输入和选中项目调用 `POST /api/memories/recall` 召回记忆。
- 召回结果可作为供应商直连请求的上下文注入,但必须遵守项目隔离和用户权限。
- 如果 AiChat 返回 `canUseMemory=false`、`canViewMemory=false` 或 `canManageMemory=false`,插件必须按权限隐藏或禁用对应操作。
优先级:P1
### FR-LLM-12 配置兼容与迁移
- 现有仅包含 `defaultModel` 和 `models` 的插件配置必须继续可用。
- 缺失 `mode` 时按 `provider-direct` 处理。
- 缺失 `aichat` 配置时,项目下拉和记忆功能降级为不可用,但供应商直连聊天仍可用。
- 配置文件必须以 UTF-8 读写。
优先级:P1
@@ -328,8 +554,11 @@
### FR-LLM-05 配置与密钥
- 插件必须支持配置 endpoint、模型列表、默认模型和请求参数。
- 插件必须支持配置模型列表、默认模型和请求参数。
- 每个模型必须能够配置独立的 provider、endpoint、真实上游模型名和启用状态。
- 宿主应根据 `modelId` 路由到对应 provider 适配器,并调用该模型自己的 endpoint。
- API key 不得写死在插件前端资源中。
- API key 应以 `authRef` 形式引用宿主侧密钥存储或用户环境配置。
- 如果宿主暂未提供密钥安全存储,MVP 必须将该能力标记为受限,并提供清晰风险提示。
优先级:P1
@@ -366,29 +595,54 @@
### 安全
- 首版插件无沙箱隔离,但 LLM 请求能力必须通过明确权限声明。
- 宿主代理 LLM 请求时,应限制插件只能使用被允许的 endpoint 和模型。
- 宿主代理 LLM 请求时,应限制插件只能使用已启用的模型 id,并由宿主解析对应 endpoint。
- 日志不得记录完整 API key。
- 日志不得记录 AiChat 密码、Session Token 或完整 `x-session-token` 请求头。
- 默认不把用户输入内容写入持久化配置。
- 供应商直连模式使用记忆召回时,应只把用户确认启用的召回内容加入上下文,并避免在诊断日志中记录完整记忆内容。
## 验收标准
- 当插件首次安装并启用时,输入条出现在主屏顶部居中,顶部留有约 `32px` 空隙。
- 当插件配置 `mode=provider-direct` 时,原有供应商直连流式输出链路仍可使用。
- 当插件配置 `mode=aichat-api` 时,插件通过 `http://192.168.1.111:13000` 登录 AiChat,并使用 AiChat 聊天接口完成一次流式回复。
- 当 AiChat 密码配置为环境变量时,插件能读取环境变量完成登录,配置文件中不需要保存密码明文。
- 当登录成功后,输入框左侧项目下拉显示 AiChat `GET /api/projects` 返回的项目。
- 当用户选择不同项目后提交时,自有 API 模式请求携带对应 `projectId`。
- 当用户输入文本并按 Enter 时,插件发起一次 LLM 请求,且没有提交按钮。
- 当用户选择不同模型后再提交时,请求使用新模型。
- 当不同模型配置了不同供应商和 endpoint 时,宿主应按所选 `modelId` 路由到对应 API。
- 当供应商直连模式启用 AiChat 记忆管理时,用户可以查询、创建、删除和召回当前项目记忆。
- 当自有 API 模式启用时,插件不展示或不执行插件侧记忆管理动作,聊天记忆由 AiChat 服务处理。
- 当 LLM 返回内容时,输出区域在输入框底部展开,并逐步显示流式文本。
- 当输出内容超过屏幕高度 `50%` 时,输出区域内部滚动,插件不会继续向下无限扩张。
- 当用户按 Escape 时,已展开输出区域可以收起。
- 当 endpoint 不可用或鉴权失败时,输出区域展示可理解错误,不导致宿主崩溃。
- 当应用重启后,插件位置、尺寸、默认模型和显示层级从配置恢复。
- 当插件处于默认 `desktop` 层时,它不应覆盖普通应用窗口;切换到 `global-top` 时必须可通过托盘或管理窗口恢复。
- 当 AiChat 返回 `USER_PENDING_APPROVAL`、`PERMISSION_DENIED`、`TOKEN_TOTAL_LIMIT_REACHED` 或 `INVALID_MODEL` 时,插件必须显示短错误并允许用户修改配置或重试。
## 用户操作手册影响范围
本需求会改变用户可见配置和插件操作,后续开发完成后必须同步更新操作手册,至少包括:
- LLM 插件的两种运行模式说明。
- AiChat Host、账号、密码环境变量配置方式。
- 项目下拉的来源、刷新、失败状态和默认项目行为。
- 供应商直连模式下的记忆查询、创建、删除和召回操作。
- 自有 API 模式下“不在插件中管理记忆”的限制说明。
- 常见故障排查:登录失败、账号未审批、项目列表为空、模型列表为空、配额耗尽、记忆权限不足、SSE 中断。
## 待澄清问题
| 问题 | 建议默认值 |
| --- | --- |
| MVP 是否由宿主代理 LLM 请求 | 是,避免 API key 暴露给插件前端 |
| 默认模型列表来源 | 插件配置,后续可由管理窗口编辑 |
| 默认模型列表来源 | 宿主侧 LLM 模型注册表,插件 manifest 只提供 fallback |
| 模型是否共用 endpoint | 不强制共用;每个模型可配置独立 endpoint,宿主统一按 `modelId` 路由 |
| 是否保留历史记录 | MVP 不保留,仅保留当前结果 |
| 是否支持停止生成 | MVP 可暂不支持,后续新增停止按钮或 Escape 二次行为 |
| 是否全局快捷键唤起 | 后续版本考虑,例如 `Alt+Space` 或用户自定义快捷键 |
| AiChat Host | 固定默认 `http://192.168.1.111:13000`,不从接口文档环境表推导 |
| AiChat 密码配置 | 优先使用环境变量,允许本地个人测试明文密码 |
| 自有 API 模式记忆 | 插件不处理记忆管理,由 AiChat 服务聊天链路处理 |
docs/qa/display-layer-acceptance-2026-05-03.md
@@ -32,6 +32,6 @@
- 在真实 Windows 11 桌面环境分别切换 `desktop`、`normal`、`app-top`、`global-top`,观察窗口遮挡行为。
- 验证 `desktop` 不覆盖普通应用窗口。
- 验证 `desktop` 组件在按下 Win+D 后仍显示在桌面上;若 WorkerW 挂载失败,应在诊断日志中看到降级原因。
- 验证 `desktop` 组件在按下 Win+D 后仍显示在桌面上;诊断日志应显示 `WorkerW` 策略选中,并记录实际宿主 `WorkerW` 或 `Progman`。若桌面宿主挂载失败,应在诊断日志中看到降级原因。
- 验证 `global-top` 可覆盖其他应用窗口,并可通过管理窗口或托盘恢复为安全层级。
- 验证多显示器和 DPI 缩放下层级语义保持一致。
docs/qa/llm-command-palette-acceptance-2026-05-04.md
New file
@@ -0,0 +1,65 @@
# LLM 桌面输入插件验收记录
日期:2026-05-04
## 范围
本次验收覆盖 `sample.llm-command-palette` 插件和宿主侧 LLM 代理最小闭环:
- LLM 模型配置文件 `llm-models.json`。
- 每模型独立 `provider`、`endpoint`、`authRef`、`apiModel` 的路由结构。
- `ILlmGatewayService`、`ILlmModelRegistry`、`ICredentialStore`、`ILlmProviderAdapter`。
- WebView bridge 的 `window.moliDesktop.llm` API。
- OpenAI-compatible 流式响应解析。
- 顶部半透明输入插件静态渲染。
## 验收结论
当前实现满足本轮需求的开发验收条件,可进入后续真实供应商联调。
已通过:
- 自动化构建。
- 自动化单元测试。
- 样例插件静态渲染非空检查。
未覆盖:
- 真实 OpenAI / DeepSeek / 本地模型服务的联网请求。
- Windows Credential Manager 生产密钥存储。
- 管理窗口里的模型配置编辑 UI。
## 执行结果
| 项目 | 命令或方法 | 结果 |
| --- | --- | --- |
| 构建 | `dotnet build .\Moli.Desktop.slnx` | 通过,0 warning,0 error |
| 自动化测试 | `dotnet test .\Moli.Desktop.slnx` | 通过,36/36 |
| 样例插件渲染 | Edge headless 打开 `samples/plugins/sample.llm-command-palette/index.html` | 通过,生成截图 |
| 像素检查 | 采样截图像素 | 通过,`Sampled=1620 NonWhite=1620 NonTransparent=1620` |
渲染截图:
- `artifacts/llm-command-palette-edge-render-check.png`
## 功能验收
| 验收点 | 结果 | 说明 |
| --- | --- | --- |
| 插件默认 manifest 合法 | 通过 | 新增 `sample.llm-command-palette/plugin.json`,声明 `llm.stream` 权限 |
| 插件样式为顶部半透明输入条 | 通过 | HTML/CSS 实现深色半透明输入条、模型下拉和输出区域 |
| Enter 提交、Shift+Enter 换行 | 通过 | 前端事件已实现 |
| 模型选择从宿主读取 | 通过 | `window.moliDesktop.llm.getModels()` 返回安全模型摘要 |
| 插件不接触 endpoint/key | 通过 | bridge 只返回 id、label、provider、supportsStreaming、enabled |
| 每模型独立路由 | 通过 | `LlmGatewayServiceTests` 验证所选 `modelId` 路由到对应 endpoint |
| 未声明权限拒绝流式调用 | 通过 | bridge 测试覆盖 `BridgePermissionDenied` |
| 流式事件派发到插件 | 通过 | bridge 测试覆盖 `llm.delta` 事件发布 |
| 配置损坏恢复 | 通过 | `llm-models.json` 损坏后备份并恢复默认值 |
| 非法模型过滤 | 通过 | 重复 id 和非法 endpoint 会被过滤并记录诊断 |
## 风险与后续
- 当前密钥存储实现为环境变量 fallback,`authRef` 的 Windows Credential Manager 实现仍需补齐。
- 当前 provider adapter 优先覆盖 OpenAI-compatible SSE 协议;如果 DeepSeek 实际接口存在差异,应新增独立 `DeepSeekAdapter`。
- 管理窗口尚未提供模型配置 UI;短期可手工编辑 `%AppData%\DesktopEnhancer\config\llm-models.json`。
- 真实供应商验收需要准备可用 endpoint 和 key,再执行端到端流式输出测试。
docs/qa/llm-command-palette-aichat-mode-acceptance-2026-05-04.md
New file
@@ -0,0 +1,57 @@
# LLM 桌面输入插件 AiChat 模式验收记录
日期:2026-05-04
## 范围
本次验收覆盖 `sample.llm-command-palette` 的两种模式增强:
- 供应商直连模式继续走宿主 LLM 模型注册表和 provider adapter。
- 自有 API 模式走 AiChat 登录、项目、模型、聊天发送和 SSE。
- 供应商直连模式下通过 AiChat 进行记忆查询、创建、删除和召回。
- 插件 UI 左侧项目下拉、右侧模型下拉和记忆入口。
- 用户操作手册同步。
## 验收结论
通过。
当前实现已满足本轮开发验收条件。真实 AiChat 账号、审批状态、模型配额和内网服务可用性仍需要在目标环境做一次人工端到端联调。
## 执行结果
| 项目 | 命令或方法 | 结果 |
| --- | --- | --- |
| 构建 | `dotnet build .\Moli.Desktop.slnx` | 通过,0 warning,0 error |
| 自动化测试 | `dotnet test .\Moli.Desktop.slnx` | 通过,43/43 |
| 样例插件渲染 | Edge headless 打开 `samples/plugins/sample.llm-command-palette/index.html` | 通过,生成截图 |
| 像素检查 | 采样截图像素 | 通过,`Sampled=2340 NonWhite=2340 NonTransparent=2340` |
渲染截图:
- `artifacts/llm-command-palette-aichat-mode-render-check.png`
## 功能验收
| 验收点 | 结果 | 说明 |
| --- | --- | --- |
| 默认保持供应商直连模式 | 通过 | `plugin.json` 默认 `mode=provider-direct` |
| AiChat Host 默认值 | 通过 | 配置默认 `http://192.168.1.111:13000` |
| 密码环境变量 | 通过 | `AiChatClientTests` 验证 `passwordEnv` 优先于明文密码 |
| Session Token 边界 | 通过 | token 仅由宿主 `AiChatClient` 注入请求头,桥接不返回 token |
| 项目下拉数据 | 通过 | 桥接新增 `llm.getProjects`,测试覆盖项目返回 |
| AiChat 模型列表 | 通过 | `mode=aichat-api` 时可从 `GET /api/chat/models` 生成安全模型摘要 |
| 自有 API 聊天 | 通过 | 测试覆盖 `POST /api/chat/send` 与生成 SSE 解析 |
| SSE 事件映射 | 通过 | `chunk` -> `llm.delta`,`done` -> `llm.completed` |
| 直连模式记忆召回 | 通过 | 桥接和客户端测试覆盖 `POST /api/memories/recall` |
| 记忆管理接口 | 通过 | 桥接支持查询、创建、删除和召回 |
| UI 渲染 | 通过 | 截图显示左侧 `No project`、输入框、记忆按钮和右侧模型下拉 |
| 操作手册同步 | 通过 | 已更新 `docs/ops/user-manual/plugins/sample.llm-command-palette.md` |
## 风险与后续
- 本次使用 fake HTTP 覆盖 AiChat API 合同,未使用真实账号访问 `http://192.168.1.111:13000`。
- 插件 UI 目前提供轻量记忆面板;后续如需要更完整的记忆编辑体验,应进入管理窗口实现。
- 自有 API 模式暂未提供会话下拉,按 AiChat 项目默认会话规则提交。
- Windows Credential Manager 仍未实现,密码生产路径当前为环境变量。
samples/plugins/sample.llm-command-palette/demo.html
New file
@@ -0,0 +1,491 @@
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>LLM Command Palette Demo</title>
  <style>
    :root {
      color-scheme: dark;
      font-family: "Segoe UI", system-ui, sans-serif;
      background: #11100f;
    }
    * {
      box-sizing: border-box;
    }
    html,
    body {
      width: 100%;
      min-height: 100%;
      margin: 0;
      background:
        radial-gradient(circle at 18% 18%, rgba(255, 130, 88, 0.16), transparent 28%),
        linear-gradient(135deg, #151312 0%, #23201f 52%, #11100f 100%);
      overflow: hidden;
    }
    body {
      padding: 8px;
    }
    .shell {
      width: 100%;
      color: rgba(255, 255, 255, 0.92);
    }
    .bar,
    .output,
    .memory {
      width: 100%;
      border: 1px solid rgba(255, 255, 255, 0.14);
      background: rgba(28, 26, 25, 0.72);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
      backdrop-filter: blur(18px);
    }
    .bar {
      display: grid;
      grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px);
      align-items: center;
      gap: 14px;
      min-height: 56px;
      padding: 0 20px;
      border-radius: 20px;
    }
    .mark {
      width: 18px;
      height: 18px;
      color: #ff8258;
      display: grid;
      place-items: center;
      font-size: 20px;
      line-height: 1;
      transform-origin: center;
    }
    .mark.busy {
      animation: spin 1.1s linear infinite;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    textarea {
      width: 100%;
      min-height: 24px;
      max-height: 78px;
      resize: none;
      border: 0;
      outline: none;
      color: rgba(255, 255, 255, 0.94);
      background: transparent;
      font: 600 16px/1.35 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      overflow-y: auto;
    }
    textarea::placeholder {
      color: rgba(255, 255, 255, 0.46);
    }
    input {
      width: 100%;
      height: 34px;
      border: 1px solid rgba(255, 255, 255, 0.13);
      outline: none;
      color: rgba(255, 255, 255, 0.88);
      background: rgba(255, 255, 255, 0.07);
      border-radius: 8px;
      padding: 0 30px 0 10px;
      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      transition: background 120ms ease;
    }
    .combo {
      position: relative;
      width: 100%;
      min-width: 0;
    }
    .combo-input {
      display: none;
    }
    .combo-trigger {
      width: 100%;
      height: 34px;
      border: 0;
      border-radius: 8px;
      color: rgba(255, 255, 255, 0.82);
      background: transparent;
      padding: 0 28px 0 10px;
      text-align: left;
      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      transition: background 120ms ease;
    }
    .combo-trigger::after {
      content: "";
      position: absolute;
      right: 11px;
      top: 13px;
      width: 7px;
      height: 7px;
      border-right: 2px solid rgba(255, 255, 255, 0.72);
      border-bottom: 2px solid rgba(255, 255, 255, 0.72);
      transform: rotate(45deg);
    }
    input:hover,
    input:focus,
    .combo.open .combo-trigger,
    .combo-trigger:hover,
    .combo-trigger:focus {
      background-color: rgba(255, 255, 255, 0.08);
      box-shadow: none;
    }
    .combo-menu {
      position: absolute;
      left: 0;
      right: 0;
      top: calc(100% + 6px);
      z-index: 10;
      display: none;
      max-height: 184px;
      overflow-y: auto;
      padding: 6px;
      border: 1px solid rgba(255, 255, 255, 0.13);
      border-radius: 10px;
      background: rgba(28, 26, 25, 0.92);
      box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26);
      backdrop-filter: blur(16px);
    }
    .combo.open .combo-menu {
      display: block;
    }
    .combo-option {
      min-height: 36px;
      display: flex;
      align-items: center;
      border-radius: 7px;
      padding: 0 10px;
      color: rgba(255, 255, 255, 0.86);
      font: 600 13px/1.2 "Segoe UI", system-ui, sans-serif;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .combo-option:hover,
    .combo-option.selected {
      background: rgba(255, 130, 88, 0.16);
      color: rgba(255, 255, 255, 0.96);
    }
    .output,
    .memory {
      display: none;
      margin-top: 8px;
      max-height: 50vh;
      overflow: auto;
      border-radius: 16px;
      padding: 16px 18px 14px;
      font-size: 14px;
      line-height: 1.55;
      white-space: pre-wrap;
    }
    .output.open,
    .memory.open {
      display: block;
      animation: panelIn 160ms ease-out;
    }
    @keyframes panelIn {
      from { opacity: 0; transform: translateY(-3px); }
      to { opacity: 1; transform: translateY(0); }
    }
    .actions,
    .memory-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 12px;
    }
    .memory-row {
      display: grid;
      grid-template-columns: minmax(0, 1fr) 32px;
      gap: 8px;
      align-items: start;
      padding: 8px 0;
      border-top: 1px solid rgba(255, 255, 255, 0.08);
      white-space: normal;
    }
    .memory-row:first-child {
      border-top: 0;
    }
    .memory-content {
      color: rgba(255, 255, 255, 0.86);
      overflow-wrap: anywhere;
    }
    button {
      width: 30px;
      height: 30px;
      border: 0;
      border-radius: 8px;
      color: rgba(255, 255, 255, 0.84);
      background: rgba(255, 255, 255, 0.08);
      cursor: pointer;
      font: 700 13px/1 "Segoe UI", system-ui, sans-serif;
    }
    button:disabled,
    input:disabled {
      cursor: not-allowed;
      opacity: 0.52;
    }
    .error {
      color: #ffad9b;
    }
  </style>
</head>
<body>
  <main class="shell">
    <section class="bar">
      <div class="combo" id="projectCombo">
        <input id="project" class="combo-input" aria-hidden="true">
        <button id="projectButton" class="combo-trigger" type="button" title="AiChat project">Project</button>
        <div id="projectMenu" class="combo-menu" role="listbox"></div>
      </div>
      <div id="mark" class="mark" aria-hidden="true">*</div>
      <textarea id="prompt" rows="1" placeholder="What can I help you with today?">Summarize today's desktop notes</textarea>
      <button id="memoryToggle" title="Memory">M</button>
      <div class="combo" id="modelCombo">
        <input id="model" class="combo-input" aria-hidden="true">
        <button id="modelButton" class="combo-trigger" type="button" title="Model">Model</button>
        <div id="modelMenu" class="combo-menu" role="listbox"></div>
      </div>
    </section>
    <section id="output" class="output open" aria-live="polite">
      <div id="text">Static preview response. This demo.html has no host bridge, no network calls, and no LLM dependency. Press Enter in the prompt to preview the loading and response states.</div>
      <div class="actions">
        <button id="copy" title="Copy">C</button>
        <button id="collapse" title="Collapse">-</button>
      </div>
    </section>
    <section id="memory" class="memory" aria-live="polite">
      <div id="memoryList"></div>
      <div class="memory-actions">
        <input id="memoryInput" placeholder="Save memory">
        <button id="saveMemory" title="Save memory">+</button>
        <button id="refreshMemory" title="Refresh memory">R</button>
      </div>
    </section>
  </main>
  <script>
    const demoProjects = [
      { value: "desktop", label: "Desktop", title: "CHAT / PROJECT" },
      { value: "design", label: "Design pass", title: "CHAT / PROJECT" },
      { value: "ops", label: "Ops notes", title: "CHAT / PROJECT" }
    ];
    const demoModels = [
      { value: "deepseek-v4-flash", label: "deepseek-v4-flash", title: "deepseek / deepseek-v4-flash" },
      { value: "kimi-k2.6", label: "kimi-k2.6", title: "kimi / kimi-k2.6" },
      { value: "glm-4.7-flash", label: "glm-4.7-flash", title: "bigmodel / glm-4.7-flash" },
      { value: "qwen3.6-plus", label: "qwen3.6-plus", title: "qwen / qwen3.6-plus" }
    ];
    let demoMemories = [
      { id: "m1", content: "Keep the command palette compact enough for a desktop widget." },
      { id: "m2", content: "Prefer plain static demo files for visual iteration." }
    ];
    const promptInput = document.getElementById("prompt");
    const projectSelect = document.getElementById("project");
    const projectCombo = document.getElementById("projectCombo");
    const projectButton = document.getElementById("projectButton");
    const projectMenu = document.getElementById("projectMenu");
    const modelSelect = document.getElementById("model");
    const modelCombo = document.getElementById("modelCombo");
    const modelButton = document.getElementById("modelButton");
    const modelMenu = document.getElementById("modelMenu");
    const output = document.getElementById("output");
    const text = document.getElementById("text");
    const mark = document.getElementById("mark");
    const copy = document.getElementById("copy");
    const collapse = document.getElementById("collapse");
    const memoryToggle = document.getElementById("memoryToggle");
    const memoryPanel = document.getElementById("memory");
    const memoryList = document.getElementById("memoryList");
    const memoryInput = document.getElementById("memoryInput");
    const saveMemory = document.getElementById("saveMemory");
    const refreshMemory = document.getElementById("refreshMemory");
    let currentText = text.textContent;
    const projectDropdown = { input: projectSelect, root: projectCombo, button: projectButton, menu: projectMenu };
    const modelDropdown = { input: modelSelect, root: modelCombo, button: modelButton, menu: modelMenu };
    function setupDropdown(dropdown) {
      dropdown.button.addEventListener("click", () => {
        const willOpen = !dropdown.root.classList.contains("open");
        closeDropdowns();
        dropdown.root.classList.toggle("open", willOpen);
      });
    }
    function closeDropdowns() {
      projectCombo.classList.remove("open");
      modelCombo.classList.remove("open");
    }
    function setDropdownOptions(dropdown, items, preferredValue) {
      dropdown.menu.innerHTML = "";
      const selected = items.find((item) => item.value === preferredValue) || items[0];
      for (const item of items) {
        const option = document.createElement("div");
        option.className = `combo-option${item.value === selected.value ? " selected" : ""}`;
        option.textContent = item.label;
        option.title = item.title || item.label;
        option.dataset.value = item.value;
        option.addEventListener("click", () => {
          setDropdownValue(dropdown, item);
          closeDropdowns();
        });
        dropdown.menu.appendChild(option);
      }
      setDropdownValue(dropdown, selected, false);
    }
    function setDropdownValue(dropdown, item, notify = true) {
      dropdown.input.value = item.value;
      dropdown.button.textContent = item.label;
      dropdown.button.title = item.title || item.label;
      for (const option of dropdown.menu.children) {
        option.classList.toggle("selected", option.dataset.value === item.value);
      }
      if (notify) {
        dropdown.input.dispatchEvent(new Event("change"));
      }
    }
    function setBusy(busy) {
      mark.classList.toggle("busy", busy);
    }
    function openOutput() {
      output.classList.add("open");
    }
    function submitPrompt() {
      const content = promptInput.value.trim();
      if (!content) return;
      currentText = "";
      text.className = "";
      text.textContent = "";
      openOutput();
      setBusy(true);
      setTimeout(() => {
        currentText = `Preview only\n\nProject: ${projectButton.textContent}\nModel: ${modelButton.textContent}\nPrompt: ${content}\n\nThis static demo mimics the result panel so the visual style can be edited without running Moli.Desktop.`;
        text.textContent = currentText;
        setBusy(false);
      }, 380);
    }
    function renderMemories() {
      memoryList.innerHTML = "";
      if (!demoMemories.length) {
        memoryList.textContent = "No memory";
        return;
      }
      for (const item of demoMemories) {
        const row = document.createElement("div");
        row.className = "memory-row";
        const content = document.createElement("div");
        content.className = "memory-content";
        content.textContent = item.content;
        row.appendChild(content);
        const remove = document.createElement("button");
        remove.textContent = "x";
        remove.title = "Delete memory";
        remove.addEventListener("click", () => {
          demoMemories = demoMemories.filter((memory) => memory.id !== item.id);
          renderMemories();
        });
        row.appendChild(remove);
        memoryList.appendChild(row);
      }
    }
    promptInput.addEventListener("keydown", (event) => {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        submitPrompt();
      }
      if (event.key === "Escape") {
        output.classList.remove("open");
        memoryPanel.classList.remove("open");
      }
    });
    promptInput.addEventListener("input", () => {
      promptInput.style.height = "0";
      promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`;
    });
    memoryToggle.addEventListener("click", () => {
      memoryPanel.classList.toggle("open");
      if (memoryPanel.classList.contains("open")) {
        renderMemories();
      }
    });
    refreshMemory.addEventListener("click", renderMemories);
    saveMemory.addEventListener("click", () => {
      const content = memoryInput.value.trim();
      if (!content) return;
      demoMemories.unshift({ id: `m${Date.now()}`, content });
      memoryInput.value = "";
      renderMemories();
    });
    collapse.addEventListener("click", () => output.classList.remove("open"));
    copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {}));
    document.addEventListener("click", (event) => {
      if (!projectCombo.contains(event.target) && !modelCombo.contains(event.target)) {
        closeDropdowns();
      }
    });
    setupDropdown(projectDropdown);
    setupDropdown(modelDropdown);
    setDropdownOptions(projectDropdown, demoProjects, "desktop");
    setDropdownOptions(modelDropdown, demoModels, "deepseek-v4-flash");
    renderMemories();
  </script>
</body>
</html>
samples/plugins/sample.llm-command-palette/index.html
New file
@@ -0,0 +1,687 @@
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>LLM Command Palette</title>
  <style>
    :root {
      color-scheme: dark;
      font-family: "Segoe UI", system-ui, sans-serif;
      background: transparent;
    }
    * {
      box-sizing: border-box;
    }
    html,
    body {
      width: 100%;
      min-height: 100%;
      margin: 0;
      background: transparent;
      overflow: hidden;
    }
    body {
      padding: 8px;
    }
    .shell {
      width: 100%;
      color: rgba(255, 255, 255, 0.92);
    }
    .bar,
    .output,
    .memory {
      width: 100%;
      border: 1px solid rgba(255, 255, 255, 0.14);
      background: rgba(28, 26, 25, 0.72);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
      backdrop-filter: blur(18px);
    }
    .bar {
      display: grid;
      grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px);
      align-items: center;
      gap: 14px;
      min-height: 56px;
      padding: 0 20px;
      border-radius: 20px;
    }
    .mark {
      width: 18px;
      height: 18px;
      color: #ff8258;
      display: grid;
      place-items: center;
      font-size: 20px;
      line-height: 1;
      transform-origin: center;
    }
    .mark.busy {
      animation: spin 1.1s linear infinite;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
    textarea {
      width: 100%;
      min-height: 24px;
      max-height: 78px;
      resize: none;
      border: 0;
      outline: none;
      color: rgba(255, 255, 255, 0.94);
      background: transparent;
      font: 600 16px/1.35 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      overflow-y: auto;
    }
    textarea::placeholder {
      color: rgba(255, 255, 255, 0.46);
    }
    input {
      width: 100%;
      height: 34px;
      border: 1px solid rgba(255, 255, 255, 0.13);
      outline: none;
      color: rgba(255, 255, 255, 0.88);
      background: rgba(255, 255, 255, 0.07);
      border-radius: 8px;
      padding: 0 30px 0 10px;
      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;
    }
    .combo {
      position: relative;
      width: 100%;
      min-width: 0;
    }
    .combo-input {
      display: none;
    }
    .combo-trigger {
      width: 100%;
      height: 34px;
      border: 0;
      border-radius: 8px;
      color: rgba(255, 255, 255, 0.82);
      background: transparent;
      padding: 0 28px 0 10px;
      text-align: left;
      font: 600 13px/1 "Segoe UI", system-ui, sans-serif;
      letter-spacing: 0;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      position: relative;
      transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease;
    }
    .combo-trigger::after {
      content: "";
      position: absolute;
      right: 11px;
      top: 13px;
      width: 7px;
      height: 7px;
      border-right: 2px solid rgba(255, 255, 255, 0.72);
      border-bottom: 2px solid rgba(255, 255, 255, 0.72);
      transform: rotate(45deg);
    }
    input:hover,
    input:focus,
    .combo.open .combo-trigger,
    .combo-trigger:hover,
    .combo-trigger:focus {
      background-color: rgba(255, 255, 255, 0.08);
      box-shadow: none;
    }
    .combo-menu {
      position: absolute;
      left: 0;
      right: 0;
      top: calc(100% + 6px);
      z-index: 10;
      display: none;
      max-height: 184px;
      overflow-y: auto;
      padding: 6px;
      border: 1px solid rgba(255, 255, 255, 0.13);
      border-radius: 10px;
      background: rgba(28, 26, 25, 0.92);
      box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26);
      backdrop-filter: blur(16px);
    }
    .combo.open .combo-menu {
      display: block;
    }
    .combo-option {
      min-height: 36px;
      display: flex;
      align-items: center;
      border-radius: 7px;
      padding: 0 10px;
      color: rgba(255, 255, 255, 0.86);
      font: 600 13px/1.2 "Segoe UI", system-ui, sans-serif;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .combo-option:hover,
    .combo-option.selected {
      background: rgba(255, 130, 88, 0.16);
      color: rgba(255, 255, 255, 0.96);
    }
    .output,
    .memory {
      display: none;
      margin-top: 8px;
      max-height: 50vh;
      overflow: auto;
      border-radius: 16px;
      padding: 16px 18px 14px;
      font-size: 14px;
      line-height: 1.55;
      white-space: pre-wrap;
    }
    .output.open,
    .memory.open {
      display: block;
      animation: panelIn 160ms ease-out;
    }
    @keyframes panelIn {
      from { opacity: 0; transform: translateY(-3px); }
      to { opacity: 1; transform: translateY(0); }
    }
    .actions,
    .memory-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      margin-top: 12px;
    }
    .memory-row {
      display: grid;
      grid-template-columns: minmax(0, 1fr) 32px;
      gap: 8px;
      align-items: start;
      padding: 8px 0;
      border-top: 1px solid rgba(255, 255, 255, 0.08);
      white-space: normal;
    }
    .memory-row:first-child {
      border-top: 0;
    }
    .memory-content {
      color: rgba(255, 255, 255, 0.86);
      overflow-wrap: anywhere;
    }
    button {
      width: 30px;
      height: 30px;
      border: 0;
      border-radius: 8px;
      color: rgba(255, 255, 255, 0.84);
      background: rgba(255, 255, 255, 0.08);
      cursor: pointer;
      font: 700 13px/1 "Segoe UI", system-ui, sans-serif;
    }
    button:disabled,
    input:disabled {
      cursor: not-allowed;
      opacity: 0.52;
    }
    .error {
      color: #ffad9b;
    }
  </style>
</head>
<body>
  <main class="shell">
    <section class="bar">
      <div class="combo" id="projectCombo">
        <input id="project" class="combo-input" aria-hidden="true">
        <button id="projectButton" class="combo-trigger" type="button" title="AiChat project">Project</button>
        <div id="projectMenu" class="combo-menu" role="listbox"></div>
      </div>
      <div id="mark" class="mark" aria-hidden="true">*</div>
      <textarea id="prompt" rows="1" placeholder="What can I help you with today?"></textarea>
      <button id="memoryToggle" title="Memory">M</button>
      <div class="combo" id="modelCombo">
        <input id="model" class="combo-input" aria-hidden="true">
        <button id="modelButton" class="combo-trigger" type="button" title="Model">Model</button>
        <div id="modelMenu" class="combo-menu" role="listbox"></div>
      </div>
    </section>
    <section id="output" class="output" aria-live="polite">
      <div id="text"></div>
      <div class="actions">
        <button id="copy" title="Copy">C</button>
        <button id="collapse" title="Collapse">-</button>
      </div>
    </section>
    <section id="memory" class="memory" aria-live="polite">
      <div id="memoryList"></div>
      <div class="memory-actions">
        <input id="memoryInput" placeholder="Save memory">
        <button id="saveMemory" title="Save memory">+</button>
        <button id="refreshMemory" title="Refresh memory">R</button>
      </div>
    </section>
  </main>
  <script>
    const promptInput = document.getElementById("prompt");
    const projectSelect = document.getElementById("project");
    const projectCombo = document.getElementById("projectCombo");
    const projectButton = document.getElementById("projectButton");
    const projectMenu = document.getElementById("projectMenu");
    const modelSelect = document.getElementById("model");
    const modelCombo = document.getElementById("modelCombo");
    const modelButton = document.getElementById("modelButton");
    const modelMenu = document.getElementById("modelMenu");
    const output = document.getElementById("output");
    const text = document.getElementById("text");
    const mark = document.getElementById("mark");
    const copy = document.getElementById("copy");
    const collapse = document.getElementById("collapse");
    const memoryToggle = document.getElementById("memoryToggle");
    const memoryPanel = document.getElementById("memory");
    const memoryList = document.getElementById("memoryList");
    const memoryInput = document.getElementById("memoryInput");
    const saveMemory = document.getElementById("saveMemory");
    const refreshMemory = document.getElementById("refreshMemory");
    if (!window.moliDesktop) {
      window.moliDesktop = {
        getConfig: async () => ({
          mode: "provider-direct",
          aichat: { memory: { enabledInProviderDirect: false, defaultScope: "PROJECT", recallLimit: 8 } }
        }),
        requestResize: async () => {},
        llm: {
          getProjects: async () => [],
          getModels: async () => [],
          getMemoryCapabilities: async () => ({ canUseMemory: false, canViewMemory: false, canManageMemory: false }),
          getMemories: async () => ({ items: [] }),
          createMemory: async () => ({}),
          deleteMemory: async () => {},
          recallMemories: async () => ({ items: [] }),
          streamChat: async () => ({ requestId: "preview" }),
          onDelta: () => () => {},
          onCompleted: () => () => {},
          onError: () => () => {}
        }
      };
    }
    let activeRequestId = null;
    let currentText = "";
    let config = { mode: "provider-direct", aichat: { memory: { enabledInProviderDirect: true, defaultScope: "PROJECT", recallLimit: 8 } } };
    let memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
    function mode() {
      return config.mode || "provider-direct";
    }
    function selectedProjectId() {
      return projectSelect.value || config.aichat?.defaultProjectId || "";
    }
    function setBusy(busy) {
      mark.classList.toggle("busy", busy);
      mark.textContent = busy ? "*" : "*";
    }
    function openOutput() {
      output.classList.add("open");
      requestResize();
    }
    function requestResize() {
      const openMenu = projectCombo.classList.contains("open")
        ? projectMenu
        : modelCombo.classList.contains("open") ? modelMenu : null;
      const menuBottom = openMenu ? openMenu.getBoundingClientRect().bottom + 8 : 72;
      window.moliDesktop?.requestResize?.({
        width: document.body.scrollWidth,
        height: Math.max(72, Math.ceil(menuBottom))
      }).catch(() => {});
    }
    function setError(message) {
      currentText = message;
      text.className = "error";
      text.textContent = message;
      openOutput();
    }
    const projectDropdown = { input: projectSelect, root: projectCombo, button: projectButton, menu: projectMenu };
    const modelDropdown = { input: modelSelect, root: modelCombo, button: modelButton, menu: modelMenu };
    function setupDropdown(dropdown) {
      dropdown.button.addEventListener("click", () => {
        const willOpen = !dropdown.root.classList.contains("open");
        closeDropdowns();
        dropdown.root.classList.toggle("open", willOpen);
        requestResize();
      });
    }
    function closeDropdowns() {
      projectCombo.classList.remove("open");
      modelCombo.classList.remove("open");
      requestResize();
    }
    function setDropdownFallback(dropdown, label, title) {
      dropdown.input.value = "";
      dropdown.button.textContent = label;
      dropdown.button.title = title || label;
      dropdown.menu.innerHTML = "";
      const option = document.createElement("div");
      option.className = "combo-option";
      option.textContent = label;
      option.title = title || label;
      dropdown.menu.appendChild(option);
    }
    function setDropdownOptions(dropdown, items, preferredValue, fallbackLabel) {
      dropdown.menu.innerHTML = "";
      if (!items.length) {
        setDropdownFallback(dropdown, fallbackLabel);
        return;
      }
      let selected = items.find((item) => item.value === preferredValue) || items[0];
      for (const item of items) {
        const option = document.createElement("div");
        option.className = `combo-option${item.value === selected.value ? " selected" : ""}`;
        option.textContent = item.label;
        option.title = item.title || item.label;
        option.dataset.value = item.value;
        option.addEventListener("click", () => {
          selected = item;
          setDropdownValue(dropdown, item);
          closeDropdowns();
        });
        dropdown.menu.appendChild(option);
      }
      setDropdownValue(dropdown, selected, false);
    }
    function setDropdownValue(dropdown, item, notify = true) {
      dropdown.input.value = item.value;
      dropdown.button.textContent = item.label;
      dropdown.button.title = item.title || item.label;
      for (const option of dropdown.menu.children) {
        option.classList.toggle("selected", option.dataset.value === item.value);
      }
      if (notify) {
        dropdown.input.dispatchEvent(new Event("change"));
      }
    }
    async function loadConfig() {
      try {
        config = { ...config, ...(await window.moliDesktop.getConfig() || {}) };
      } catch {
      }
    }
    async function loadProjects() {
      try {
        const projects = await window.moliDesktop.llm.getProjects();
        const items = projects.map((project) => ({
          value: project.id,
          label: project.name || project.id,
          title: `${project.projectType || "CHAT"} / ${project.memoryMode || "ISOLATED"}`
        }));
        setDropdownOptions(projectDropdown, items, config.aichat?.defaultProjectId || "", "No project");
      } catch (error) {
        setDropdownFallback(projectDropdown, "Project error", error?.message || "AiChat projects could not be loaded");
      }
    }
    async function loadModels() {
      try {
        const models = await window.moliDesktop.llm.getModels();
        const items = models.map((model) => ({
          value: model.id,
          label: model.label || model.id,
          title: `${model.provider} / ${model.id}`
        }));
        setDropdownOptions(modelDropdown, items, config.defaultModel || "", "No models");
      } catch {
        setDropdownFallback(modelDropdown, "Model error");
      }
    }
    async function loadMemoryCapabilities() {
      try {
        memoryCapabilities = await window.moliDesktop.llm.getMemoryCapabilities();
      } catch {
        memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false };
      }
      const memoryEnabled = mode() === "provider-direct" && config.aichat?.memory?.enabledInProviderDirect;
      memoryToggle.disabled = !memoryEnabled || !memoryCapabilities.canViewMemory;
      memoryInput.disabled = !memoryCapabilities.canManageMemory;
      saveMemory.disabled = !memoryCapabilities.canManageMemory;
      refreshMemory.disabled = !memoryCapabilities.canViewMemory;
    }
    async function recallMemory(content) {
      if (mode() !== "provider-direct" || !config.aichat?.memory?.enabledInProviderDirect || !memoryCapabilities.canUseMemory) {
        return [];
      }
      const projectId = selectedProjectId();
      try {
        const result = await window.moliDesktop.llm.recallMemories({
          query: content,
          scope: config.aichat.memory.defaultScope || "PROJECT",
          projectId,
          limit: config.aichat.memory.recallLimit || 8
        });
        return Array.isArray(result?.items) ? result.items : [];
      } catch {
        return [];
      }
    }
    async function submitPrompt() {
      const content = promptInput.value.trim();
      const modelId = modelSelect.value;
      if (!content || !modelId || activeRequestId) return;
      currentText = "";
      text.className = "";
      text.textContent = "";
      openOutput();
      setBusy(true);
      try {
        const memories = await recallMemory(content);
        const messages = [];
        if (memories.length > 0) {
          const memoryText = memories.map((item) => `- ${item.content || ""}`).filter(Boolean).join("\n");
          if (memoryText) {
            messages.push({ role: "system", content: `Relevant memory:\n${memoryText}` });
          }
        }
        messages.push({ role: "user", content });
        const response = await window.moliDesktop.llm.streamChat({
          mode: mode(),
          projectId: selectedProjectId(),
          modelId,
          messages,
          options: {}
        });
        activeRequestId = response.requestId;
      } catch (error) {
        activeRequestId = null;
        setBusy(false);
        setError(error?.message || "LLM request could not be started.");
      }
    }
    async function refreshMemories() {
      if (!memoryCapabilities.canViewMemory) return;
      const projectId = selectedProjectId();
      memoryList.textContent = "Loading...";
      try {
        const scope = config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT";
        const result = await window.moliDesktop.llm.getMemories({ scope, projectId });
        const items = Array.isArray(result) ? result : Array.isArray(result?.items) ? result.items : [];
        renderMemories(items);
      } catch (error) {
        memoryList.textContent = error?.message || "Memory unavailable.";
      }
    }
    function renderMemories(items) {
      memoryList.innerHTML = "";
      if (!items.length) {
        memoryList.textContent = "No memory";
        return;
      }
      for (const item of items) {
        const row = document.createElement("div");
        row.className = "memory-row";
        const content = document.createElement("div");
        content.className = "memory-content";
        content.textContent = item.content || item.id || "";
        row.appendChild(content);
        const remove = document.createElement("button");
        remove.textContent = "x";
        remove.title = "Delete memory";
        remove.disabled = !memoryCapabilities.canManageMemory;
        remove.addEventListener("click", async () => {
          if (!item.id) return;
          await window.moliDesktop.llm.deleteMemory(item.id);
          refreshMemories();
        });
        row.appendChild(remove);
        memoryList.appendChild(row);
      }
    }
    promptInput.addEventListener("keydown", (event) => {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        submitPrompt();
      }
      if (event.key === "Escape") {
        output.classList.remove("open");
        memoryPanel.classList.remove("open");
        requestResize();
      }
    });
    promptInput.addEventListener("input", () => {
      promptInput.style.height = "0";
      promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`;
    });
    projectSelect.addEventListener("change", () => {
      if (memoryPanel.classList.contains("open")) {
        refreshMemories();
      }
    });
    memoryToggle.addEventListener("click", () => {
      memoryPanel.classList.toggle("open");
      if (memoryPanel.classList.contains("open")) {
        refreshMemories();
      }
      requestResize();
    });
    refreshMemory.addEventListener("click", refreshMemories);
    saveMemory.addEventListener("click", async () => {
      const content = memoryInput.value.trim();
      if (!content || !memoryCapabilities.canManageMemory) return;
      await window.moliDesktop.llm.createMemory({
        scope: config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT",
        projectId: selectedProjectId(),
        content
      });
      memoryInput.value = "";
      refreshMemories();
    });
    collapse.addEventListener("click", () => {
      output.classList.remove("open");
      requestResize();
    });
    copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {}));
    document.addEventListener("click", (event) => {
      if (!projectCombo.contains(event.target) && !modelCombo.contains(event.target)) {
        closeDropdowns();
      }
    });
    window.addEventListener("DOMContentLoaded", async () => {
      setupDropdown(projectDropdown);
      setupDropdown(modelDropdown);
      await loadConfig();
      await Promise.all([loadProjects(), loadModels(), loadMemoryCapabilities()]);
    });
    window.moliDesktop?.llm?.onDelta?.((event) => {
      if (event.requestId !== activeRequestId) return;
      currentText += event.delta || "";
      text.textContent = currentText;
      output.scrollTop = output.scrollHeight;
    });
    window.moliDesktop?.llm?.onCompleted?.((event) => {
      if (event.requestId !== activeRequestId) return;
      activeRequestId = null;
      setBusy(false);
    });
    window.moliDesktop?.llm?.onError?.((event) => {
      if (event.requestId !== activeRequestId) return;
      activeRequestId = null;
      setBusy(false);
      setError(event.message || "LLM request failed.");
    });
  </script>
</body>
</html>
samples/plugins/sample.llm-command-palette/plugin.json
New file
@@ -0,0 +1,104 @@
{
  "id": "sample.llm-command-palette",
  "name": "LLM Command Palette",
  "version": "1.0.0",
  "type": "widget",
  "entry": "index.html",
  "description": "A translucent desktop prompt bar for streaming LLM responses.",
  "author": "Moli.Desktop",
  "permissions": [
    "llm.stream",
    "config.read"
  ],
  "defaultLayout": {
    "x": 580,
    "y": 32,
    "width": 760,
    "height": 72,
    "locked": true,
    "clickThrough": false,
    "opacity": 0.96,
    "scale": 1,
    "displayLayer": "desktop"
  },
  "config": {
    "mode": "provider-direct",
    "aichat": {
      "baseUrl": "http://192.168.1.111:13000",
      "account": {
        "email": "linmolilin@163.com",
        "password": null,
        "passwordEnv": "MOLI_AICHAT_PASSWORD"
      },
      "defaultProjectId": "cmnd8uzcl0002c9usch183a01",
      "memory": {
        "enabledInProviderDirect": true,
        "defaultScope": "PROJECT",
        "recallLimit": 8
      }
    },
    "defaultModel": "deepseek-v4-flash",
    "models": [
      {
        "id": "deepseek-v4-flash",
        "label": "deepseek-v4-flash",
        "provider": "deepseek",
        "endpoint": "https://api.deepseek.com/chat/completions",
        "authRef": "llm_deepseek_api_key",
        "apiModel": "deepseek-v4-flash",
        "supportsStreaming": true,
        "enabled": true,
        "requestDefaults": {
          "temperature": 0.9,
          "maxTokens": 2560000,
          "timeoutMs": 60000
        }
      },
      {
        "id": "kimi-k2.6",
        "label": "kimi-k2.6",
        "provider": "kimi",
        "endpoint": "https://api.moonshot.cn/v1/chat/completions",
        "authRef": "llm_kimi_api_key",
        "apiModel": "kimi-k2.6",
        "supportsStreaming": true,
        "enabled": true,
        "requestDefaults": {
          "temperature": 0.9,
          "maxTokens": 2560000,
          "timeoutMs": 60000
        }
      },
      {
        "id": "glm-4.7-flash",
        "label": "glm-4.7-flash",
        "provider": "bigmodel",
        "endpoint": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
        "authRef": "llm_bigmodel_api_key",
        "apiModel": "glm-4.7-flash",
        "supportsStreaming": true,
        "enabled": true,
        "requestDefaults": {
          "temperature": 0.9,
          "maxTokens": 2000000,
          "timeoutMs": 60000
        }
      },
      {
        "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": 2560000,
          "timeoutMs": 60000
        }
      }
    ]
  }
}
scripts/publish-to-apps.ps1
@@ -54,11 +54,84 @@
    }
}
function Get-RelativePathCompat {
    param(
        [Parameter(Mandatory = $true)]
        [string]$BasePath,
        [Parameter(Mandatory = $true)]
        [string]$TargetPath
    )
    $baseFullPath = [System.IO.Path]::GetFullPath($BasePath).TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar)
    $targetFullPath = [System.IO.Path]::GetFullPath($TargetPath).TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar)
    $baseUri = New-Object System.Uri(($baseFullPath + [System.IO.Path]::DirectorySeparatorChar))
    $targetUri = New-Object System.Uri($targetFullPath)
    $relativeUri = $baseUri.MakeRelativeUri($targetUri)
    return [System.Uri]::UnescapeDataString($relativeUri.ToString()).Replace('/', [System.IO.Path]::DirectorySeparatorChar)
}
function Backup-DeployedPluginConfigs {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ApplicationDirectory,
        [Parameter(Mandatory = $true)]
        [string]$BackupDirectory
    )
    $pluginsRoot = Join-Path $ApplicationDirectory "samples\plugins"
    if (-not (Test-Path -LiteralPath $pluginsRoot)) {
        return
    }
    Get-ChildItem -LiteralPath $pluginsRoot -Directory | ForEach-Object {
        $pluginJson = Join-Path $_.FullName "plugin.json"
        if (-not (Test-Path -LiteralPath $pluginJson)) {
            return
        }
        $relativeDirectory = Get-RelativePathCompat -BasePath $pluginsRoot -TargetPath $_.FullName
        $backupPluginDirectory = Join-Path $BackupDirectory $relativeDirectory
        New-Item -ItemType Directory -Force -Path $backupPluginDirectory | Out-Null
        Copy-Item -LiteralPath $pluginJson -Destination (Join-Path $backupPluginDirectory "plugin.json") -Force
    }
}
function Restore-DeployedPluginConfigs {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ApplicationDirectory,
        [Parameter(Mandatory = $true)]
        [string]$BackupDirectory
    )
    if (-not (Test-Path -LiteralPath $BackupDirectory)) {
        return
    }
    $pluginsRoot = Join-Path $ApplicationDirectory "samples\plugins"
    Get-ChildItem -LiteralPath $BackupDirectory -Directory | ForEach-Object {
        $relativeDirectory = Get-RelativePathCompat -BasePath $BackupDirectory -TargetPath $_.FullName
        $targetPluginDirectory = Join-Path $pluginsRoot $relativeDirectory
        $newPluginJson = Join-Path $targetPluginDirectory "plugin.json"
        $templateJson = Join-Path $targetPluginDirectory "plugin.template.json"
        $backupPluginJson = Join-Path $_.FullName "plugin.json"
        if ((Test-Path -LiteralPath $newPluginJson) -and -not (Test-Path -LiteralPath $templateJson)) {
            Copy-Item -LiteralPath $newPluginJson -Destination $templateJson -Force
        }
        if (Test-Path -LiteralPath $backupPluginJson) {
            Copy-Item -LiteralPath $backupPluginJson -Destination $newPluginJson -Force
        }
    }
}
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$solutionPath = Join-Path $repoRoot "Moli.Desktop.slnx"
$projectPath = Join-Path $repoRoot "src\Moli.Desktop\Moli.Desktop.csproj"
$stagingRoot = Join-Path $repoRoot "artifacts\release"
$publishDir = Join-Path $stagingRoot "publish\$AppName"
$configBackupDir = Join-Path $stagingRoot "preserved-plugin-configs"
$targetRootPath = Join-Path $TargetRoot ""
$targetDir = Join-Path $targetRootPath $AppName
$targetExePath = Join-Path $targetDir "$AppName.exe"
@@ -103,6 +176,12 @@
Stop-PublishedApplication -ProcessName $AppName -ExecutablePath $targetExePath
if (Test-Path -LiteralPath $configBackupDir) {
    Remove-Item -LiteralPath $configBackupDir -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $configBackupDir | Out-Null
Backup-DeployedPluginConfigs -ApplicationDirectory $targetDir -BackupDirectory $configBackupDir
if (Test-Path -LiteralPath $targetDir) {
    Write-Host "Removing old published files:"
    Write-Host $targetDir
@@ -111,6 +190,7 @@
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
Invoke-CheckedRobocopy -Source $publishDir -Destination $targetDir
Restore-DeployedPluginConfigs -ApplicationDirectory $targetDir -BackupDirectory $configBackupDir
if (-not $NoZip) {
    if (Test-Path -LiteralPath $zipPath) {
src/Moli.Desktop.Tests/Layout/LayoutManagerTests.cs
@@ -47,6 +47,19 @@
    }
    [Fact]
    public async Task Update_AllowsUnlockingLockedWidget()
    {
        var (manager, monitor, _) = await CreateLoadedManagerAsync();
        var plugin = CreatePlugin(locked: true);
        var layout = manager.CreateFromPlugin(plugin, monitor.Id);
        var result = manager.Update(layout.InstanceId, new WidgetLayoutPatch { IsLocked = false });
        Assert.True(result.Succeeded);
        Assert.False(result.Value?.IsLocked);
    }
    [Fact]
    public async Task ReconcileMonitors_MovesMissingSecondaryMonitorToPrimary()
    {
        var (manager, _, diagnostics) = await CreateLoadedManagerAsync();
src/Moli.Desktop.Tests/Llm/AiChatClientTests.cs
New file
@@ -0,0 +1,165 @@
using System.Net;
using System.Net.Http;
using System.Text;
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
namespace Moli.Desktop.Tests.Llm;
public class AiChatClientTests
{
    [Fact]
    public async Task GetProjectsAsync_LogsInWithPasswordEnvAndSendsSessionToken()
    {
        var envName = "MOLI_AICHAT_TEST_PASSWORD_" + Guid.NewGuid().ToString("N");
        Environment.SetEnvironmentVariable(envName, "secret-from-env");
        try
        {
            var handler = new QueueHttpMessageHandler(
                Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""),
                Json("""{"ok":true,"data":[{"id":"project-1","name":"产品问答","projectType":"CHAT","memoryMode":"ISOLATED"}]}"""));
            var client = CreateClient(handler);
            var projects = await client.GetProjectsAsync(CreateConfig(passwordEnv: envName));
            Assert.Single(projects);
            Assert.Equal("project-1", projects[0].Id);
            Assert.Equal("secret-from-env", handler.RequestBodies[0].Contains("secret-from-env") ? "secret-from-env" : "");
            Assert.True(handler.Requests[1].Headers.TryGetValues("x-session-token", out var tokens));
            Assert.Contains("session-1", tokens);
        }
        finally
        {
            Environment.SetEnvironmentVariable(envName, null);
        }
    }
    [Fact]
    public async Task GetModelsAsync_ReturnsAiChatSafeModelSummaries()
    {
        var handler = new QueueHttpMessageHandler(
            Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""),
            Json("""{"ok":true,"data":{"models":["deepseek-v4-flash"],"defaultModel":"deepseek-v4-flash"}}"""));
        var client = CreateClient(handler);
        var models = await client.GetModelsAsync(CreateConfig());
        var model = Assert.Single(models);
        Assert.Equal("deepseek-v4-flash", model.Id);
        Assert.Equal("aichat", model.Provider);
        Assert.True(model.SupportsStreaming);
    }
    [Fact]
    public async Task StreamChatAsync_UsesAiChatSendAndParsesSseChunks()
    {
        var handler = new QueueHttpMessageHandler(
            Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""),
            Json("""{"ok":true,"data":{"generationId":"gen-1","streamToken":"stream-1","projectId":"project-1","conversationId":"conv-1"}}"""),
            Sse("""
event: chunk
data: {"type":"chunk","delta":"Hello","sequence":1}
event: done
data: {"type":"done","generationId":"gen-1"}
"""));
        var client = CreateClient(handler);
        var events = await client.StreamChatAsync(
            new LlmChatRequest
            {
                RequestId = "req-1",
                PluginId = "sample.llm-command-palette",
                InstanceId = "host-1",
                Mode = LlmConnectionModes.AiChatApi,
                ProjectId = "project-1",
                ModelId = "deepseek-v4-flash",
                Messages = [new LlmMessage { Role = "user", Content = "hello" }]
            },
            CreateConfig()).ToListAsync();
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "Hello" });
        Assert.Contains(events, item => item is LlmCompletedEvent);
        Assert.Contains("/api/chat/send", handler.Requests[1].RequestUri?.PathAndQuery);
        Assert.Contains("/api/chat/generations/gen-1/stream?token=stream-1", handler.Requests[2].RequestUri?.PathAndQuery);
    }
    [Fact]
    public async Task RecallMemoriesAsync_PostsToAiChatMemoryRecall()
    {
        var handler = new QueueHttpMessageHandler(
            Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""),
            Json("""{"ok":true,"data":{"items":[{"id":"mem-1","content":"Keep replies short."}]}}"""));
        var client = CreateClient(handler);
        var result = await client.RecallMemoriesAsync(
            CreateConfig(),
            new AiChatRecallMemoriesRequest
            {
                Query = "hello",
                Scope = "PROJECT",
                ProjectId = "project-1",
                Limit = 8
            });
        Assert.NotNull(result.Data);
        Assert.Equal("/api/memories/recall", handler.Requests[1].RequestUri?.PathAndQuery);
        Assert.Contains("project-1", handler.RequestBodies[1]);
    }
    private static AiChatClient CreateClient(QueueHttpMessageHandler handler)
    {
        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 AiChatClient(new HttpClient(handler), diagnostics);
    }
    private static LlmPluginRuntimeConfig CreateConfig(string? passwordEnv = null) => new()
    {
        Mode = LlmConnectionModes.AiChatApi,
        AiChat = new AiChatRuntimeConfig
        {
            BaseUrl = "http://192.168.1.111:13000",
            Account = new AiChatAccountConfig
            {
                Email = "user@example.com",
                Password = passwordEnv is null ? "plain-secret" : null,
                PasswordEnv = passwordEnv
            }
        }
    };
    private static HttpResponseMessage Json(string content, HttpStatusCode statusCode = HttpStatusCode.OK) => new(statusCode)
    {
        Content = new StringContent(content, Encoding.UTF8, "application/json")
    };
    private static HttpResponseMessage Sse(string content) => new(HttpStatusCode.OK)
    {
        Content = new StringContent(content, Encoding.UTF8, "text/event-stream")
    };
    private sealed class QueueHttpMessageHandler : HttpMessageHandler
    {
        private readonly Queue<HttpResponseMessage> _responses;
        public QueueHttpMessageHandler(params HttpResponseMessage[] responses)
        {
            _responses = new Queue<HttpResponseMessage>(responses);
        }
        public List<HttpRequestMessage> Requests { get; } = [];
        public List<string> RequestBodies { get; } = [];
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            Requests.Add(request);
            RequestBodies.Add(request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken));
            return _responses.Dequeue();
        }
    }
}
src/Moli.Desktop.Tests/Llm/LlmGatewayServiceTests.cs
New file
@@ -0,0 +1,217 @@
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
using Microsoft.Extensions.Logging.Abstractions;
namespace Moli.Desktop.Tests.Llm;
public class LlmGatewayServiceTests
{
    [Fact]
    public async Task StreamChatAsync_RoutesSelectedModelToMatchingAdapter()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter, new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
            ApiModel = "actual-model",
            Enabled = true
        });
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-1",
            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.Endpoint);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
        Assert.Contains(events, item => item is LlmCompletedEvent);
    }
    [Fact]
    public async Task StreamChatAsync_ReturnsModelNotFoundForDisabledModel()
    {
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
            ApiModel = "actual-model",
            Enabled = false
        });
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-2",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "model-a",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
        var error = Assert.IsType<LlmErrorEvent>(Assert.Single(events));
        Assert.Equal(LlmErrorCodes.ModelNotFound, error.Code);
    }
    [Fact]
    public async Task StreamChatAsync_UsesOpenAICompatibleAdapterForDeepSeekAlias()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter, new LlmModelConfig
        {
            Id = "deepseek-chat",
            Label = "DeepSeek",
            Provider = "deepseek",
            Endpoint = "https://api.deepseek.com/chat/completions",
            ApiModel = "deepseek-chat",
            Enabled = true
        });
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-3",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "deepseek-chat",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
        Assert.Equal("deepseek", adapter.LastRequest?.Model.Provider);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
    }
    [Fact]
    public async Task StreamChatAsync_UsesAiChatClientWhenModeIsAiChatApi()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(
            new CapturingAdapter("openai-compatible"),
            aiChat,
            new LlmModelConfig
            {
                Id = "provider-model",
                Label = "Provider",
                Provider = "openai-compatible",
                Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
                ApiModel = "provider-model",
                Enabled = true
            });
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-aichat",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            Mode = LlmConnectionModes.AiChatApi,
            ProjectId = "project-1",
            ModelId = "deepseek-v4-flash",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }],
            RuntimeConfig = new LlmPluginRuntimeConfig { Mode = LlmConnectionModes.AiChatApi }
        }).ToListAsync();
        Assert.Equal("project-1", aiChat.LastRequest?.ProjectId);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "from-aichat" });
    }
    private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models)
        => CreateGateway(adapter, null, models);
    private static LlmGatewayService CreateGateway(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(
            new InMemoryRegistry(models),
            new EnvironmentCredentialStore(),
            new LlmProviderAdapterFactory([adapter]),
            diagnostics,
            aiChatClient);
    }
    private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry
    {
        private readonly List<LlmModelConfig> _models = [.. models];
        public Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default)
            => Task.FromResult(new LlmSettingsDocument { Models = _models });
        public Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default)
            => Task.FromResult(_models.FirstOrDefault(model => model.Enabled && model.Id == modelId));
    }
    private sealed class CapturingAdapter(string provider) : ILlmProviderAdapter
    {
        public string Provider { get; } = provider;
        public LlmProviderRequest? LastRequest { get; private set; }
        public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
            LlmProviderRequest request,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            LastRequest = request;
            yield return new LlmProviderChunk { Delta = "ok" };
            yield return new LlmProviderChunk { IsCompleted = true };
        }
    }
    private sealed class FakeAiChatClient : IAiChatClient
    {
        public LlmChatRequest? LastRequest { get; private set; }
        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 async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
            LlmChatRequest request,
            LlmPluginRuntimeConfig runtimeConfig,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            LastRequest = request;
            yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "from-aichat" };
            yield return new LlmCompletedEvent { RequestId = request.RequestId };
        }
        public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatMemoryCapabilities());
        public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
        public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
        public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
            => Task.CompletedTask;
        public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
    }
}
internal static class AsyncEnumerableTestExtensions
{
    public static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source)
    {
        var results = new List<T>();
        await foreach (var item in source)
        {
            results.Add(item);
        }
        return results;
    }
}
src/Moli.Desktop.Tests/Llm/LlmModelRegistryTests.cs
New file
@@ -0,0 +1,87 @@
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
namespace Moli.Desktop.Tests.Llm;
public class LlmModelRegistryTests
{
    [Fact]
    public async Task LoadAsync_CreatesDefaultLlmModelDocument()
    {
        var (registry, paths, _) = CreateRegistry();
        var document = await registry.LoadAsync();
        Assert.Equal(1, document.SchemaVersion);
        Assert.True(File.Exists(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName)));
    }
    [Fact]
    public async Task LoadAsync_FiltersInvalidAndDuplicateModels()
    {
        var (registry, paths, diagnostics) = CreateRegistry();
        Directory.CreateDirectory(paths.ConfigDirectory);
        await File.WriteAllTextAsync(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName), """
        {
          "schemaVersion": 1,
          "defaultModel": "valid",
          "models": [
            {
              "id": "valid",
              "label": "Valid",
              "provider": "openai-compatible",
              "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
              "apiModel": "qwen",
              "enabled": true
            },
            {
              "id": "valid",
              "label": "Duplicate",
              "provider": "openai-compatible",
              "endpoint": "http://127.0.0.1:11434/v1/chat/completions",
              "apiModel": "qwen",
              "enabled": true
            },
            {
              "id": "bad-url",
              "label": "Bad",
              "provider": "openai-compatible",
              "endpoint": "file:///tmp/model",
              "apiModel": "qwen",
              "enabled": true
            }
          ]
        }
        """);
        var document = await registry.LoadAsync();
        Assert.Single(document.Models);
        Assert.Equal("valid", document.DefaultModel);
        Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == "LlmModelInvalid");
    }
    [Fact]
    public async Task LoadAsync_BacksUpInvalidJsonAndRecovers()
    {
        var (registry, paths, diagnostics) = CreateRegistry();
        Directory.CreateDirectory(paths.ConfigDirectory);
        await File.WriteAllTextAsync(Path.Combine(paths.ConfigDirectory, LlmModelRegistry.FileName), "{ broken");
        var document = await registry.LoadAsync();
        Assert.Equal(1, document.SchemaVersion);
        Assert.NotEmpty(Directory.GetFiles(paths.ConfigDirectory, "llm-models.invalid.*.json"));
        Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == DiagnosticCodes.ConfigurationRecovered);
    }
    private static (LlmModelRegistry Registry, DesktopPaths Paths, DiagnosticsService Diagnostics) CreateRegistry()
    {
        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 LlmModelRegistry(paths, diagnostics), paths, diagnostics);
    }
}
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
@@ -2,6 +2,7 @@
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Moli.Desktop.WebView;
@@ -56,12 +57,123 @@
    }
    [Fact]
    public async Task DispatchAsync_ReturnsSafeLlmModelSummaries()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var response = await dispatcher.DispatchAsync("""{"id":"4","method":"llm.getModels"}""", CreateContext());
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("gpt-test", json);
        Assert.DoesNotContain("endpoint", json, StringComparison.OrdinalIgnoreCase);
    }
    [Fact]
    public async Task DispatchAsync_ReturnsLlmModelsFromPluginConfig()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var context = CreateContext(configJson: """
        {
          "mode": "provider-direct",
          "defaultModel": "configured-model",
          "models": [
            {
              "id": "configured-model",
              "label": "Configured Model",
              "provider": "test",
              "endpoint": "https://example.test/chat",
              "apiModel": "configured-model",
              "supportsStreaming": true,
              "enabled": true
            }
          ]
        }
        """);
        var response = await dispatcher.DispatchAsync("""{"id":"40","method":"llm.getModels"}""", context);
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("configured-model", json);
    }
    [Fact]
    public async Task DispatchAsync_ReturnsAiChatProjects()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var response = await dispatcher.DispatchAsync("""{"id":"41","method":"llm.getProjects"}""", CreateContext());
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("project-1", json);
    }
    [Fact]
    public async Task DispatchAsync_ReturnsMemoryRecallResult()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var response = await dispatcher.DispatchAsync(
            """{"id":"42","method":"llm.recallMemories","params":{"query":"hello","scope":"PROJECT","projectId":"project-1","limit":8}}""",
            CreateContext());
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("remember this", json);
    }
    [Fact]
    public async Task DispatchAsync_RejectsLlmStreamWithoutPermission()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var context = CreateContext(includeLlmPermission: false);
        var response = await dispatcher.DispatchAsync(
            """{"id":"5","method":"llm.streamChat","params":{"modelId":"gpt-test","messages":[{"role":"user","content":"hello"}]}}""",
            context);
        Assert.False(response.Success);
        Assert.Equal("BridgePermissionDenied", response.Error?.Code);
    }
    [Fact]
    public async Task DispatchAsync_StartsLlmStreamForPermittedPlugin()
    {
        var dispatcher = CreateDispatcher(out _, out var events);
        var seenDelta = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
        using var subscription = events.Subscribe(runtimeEvent =>
        {
            if (runtimeEvent.Name == "llm.delta")
            {
                seenDelta.TrySetResult(JsonSerializer.Serialize(runtimeEvent.Payload));
            }
            return Task.CompletedTask;
        });
        var response = await dispatcher.DispatchAsync(
            """{"id":"6","method":"llm.streamChat","params":{"modelId":"gpt-test","messages":[{"role":"user","content":"hello"}]}}""",
            CreateContext());
        Assert.True(response.Success);
        var completed = await Task.WhenAny(seenDelta.Task, Task.Delay(TimeSpan.FromSeconds(3)));
        Assert.Same(seenDelta.Task, completed);
        Assert.Contains("Hello", await seenDelta.Task);
    }
    [Fact]
    public void BridgeScript_ExposesExpectedPluginMethods()
    {
        var script = PluginBridgeScript.Build();
        Assert.Contains("getRuntimeInfo", script);
        Assert.Contains("requestResize", script);
        Assert.Contains("llm", script);
        Assert.Contains("getProjects", script);
        Assert.Contains("recallMemories", script);
        Assert.Contains("streamChat", script);
        Assert.Contains("moliDesktopResponse", script);
    }
@@ -71,10 +183,10 @@
        var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
        diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
        events = new RuntimeEventBus();
        return new PluginBridgeDispatcher(diagnostics, events);
        return new PluginBridgeDispatcher(diagnostics, events, new FakeLlmGateway());
    }
    private static PluginBridgeContext CreateContext()
    private static PluginBridgeContext CreateContext(bool includeLlmPermission = true, string configJson = """{"label":"clock"}""")
    {
        return new PluginBridgeContext
        {
@@ -85,7 +197,8 @@
                Name = "Clock",
                Version = "1.0.0",
                Type = PluginType.Widget,
                Entry = "index.html"
                Entry = "index.html",
                Permissions = includeLlmPermission ? ["llm.stream"] : []
            },
            RuntimeInfo = new PluginRuntimeBridgeInfo
            {
@@ -93,7 +206,70 @@
                PluginType = PluginType.Widget,
                HostId = "host-1"
            },
            Config = JsonDocument.Parse("""{"label":"clock"}""").RootElement.Clone()
            Config = JsonDocument.Parse(configJson).RootElement.Clone()
        };
    }
    private sealed class FakeLlmGateway : ILlmGatewayService
    {
        public Task CancelAsync(string requestId, CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>(
            [
                new LlmModelSummary
                {
                    Id = "gpt-test",
                    Label = "GPT Test",
                    Provider = "openai-compatible",
                    SupportsStreaming = true,
                    Enabled = true
                }
            ]);
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => runtimeConfig.Models.Count > 0
                ? Task.FromResult<IReadOnlyList<LlmModelSummary>>(runtimeConfig.Models
                    .Where(model => model.Enabled)
                    .Select(model => new LlmModelSummary
                    {
                        Id = model.Id,
                        Label = model.Label,
                        Provider = model.Provider,
                        SupportsStreaming = model.SupportsStreaming,
                        Enabled = model.Enabled
                    })
                    .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<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatMemoryCapabilities { CanUseMemory = true, CanViewMemory = true, CanManageMemory = true });
        public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult { Data = new[] { new { id = "mem-1", content = "remember this" } } });
        public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult { Data = new { id = "mem-2", content = request.Content } });
        public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
            => Task.CompletedTask;
        public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult { Data = new { items = new[] { new { id = "mem-1", content = "remember this" } } } });
        public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
            LlmChatRequest request,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "Hello" };
            yield return new LlmCompletedEvent { RequestId = request.RequestId };
        }
    }
}
src/Moli.Desktop/Diagnostics/DailyFileLoggerProvider.cs
New file
@@ -0,0 +1,79 @@
using System.IO;
using System.Text;
using Microsoft.Extensions.Logging;
namespace Moli.Desktop.Diagnostics;
public sealed class DailyFileLoggerProvider : ILoggerProvider
{
    private readonly string _logDirectory;
    private readonly object _gate = new();
    private bool _disposed;
    public DailyFileLoggerProvider(string logDirectory)
    {
        _logDirectory = logDirectory;
        Directory.CreateDirectory(_logDirectory);
    }
    public ILogger CreateLogger(string categoryName)
        => new DailyFileLogger(categoryName, _logDirectory, _gate, () => _disposed);
    public void Dispose()
    {
        _disposed = true;
    }
    private sealed class DailyFileLogger(
        string categoryName,
        string logDirectory,
        object gate,
        Func<bool> isDisposed) : ILogger
    {
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
        public bool IsEnabled(LogLevel logLevel)
            => logLevel != LogLevel.None && !isDisposed();
        public void Log<TState>(
            LogLevel logLevel,
            EventId eventId,
            TState state,
            Exception? exception,
            Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            var message = formatter(state, exception);
            if (string.IsNullOrWhiteSpace(message) && exception is null)
            {
                return;
            }
            var now = DateTimeOffset.Now;
            var line = $"{now:O} [{logLevel}] {categoryName} {message}";
            if (exception is not null)
            {
                line += $" {exception.GetType().Name}: {exception.Message}";
            }
            var path = Path.Combine(logDirectory, $"moli-desktop-{now:yyyyMMdd}.log");
            try
            {
                lock (gate)
                {
                    File.AppendAllText(path, line + Environment.NewLine, Encoding.UTF8);
                }
            }
            catch (IOException)
            {
            }
            catch (UnauthorizedAccessException)
            {
            }
        }
    }
}
src/Moli.Desktop/Diagnostics/DiagnosticsService.cs
@@ -10,13 +10,13 @@
    private readonly object _gate = new();
    private readonly List<DiagnosticEntry> _entries = [];
    private readonly ILogger<DiagnosticsService> _logger;
    private readonly string _logFile;
    private readonly string _logDirectory;
    public DiagnosticsService(DesktopPaths paths, ILogger<DiagnosticsService> logger)
    {
        _logger = logger;
        Directory.CreateDirectory(paths.LogDirectory);
        _logFile = Path.Combine(paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log");
        _logDirectory = paths.LogDirectory;
    }
    public DiagnosticEntry Record(
@@ -61,7 +61,10 @@
        try
        {
            File.AppendAllText(_logFile, line + Environment.NewLine, Encoding.UTF8);
            File.AppendAllText(
                Path.Combine(_logDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log"),
                line + Environment.NewLine,
                Encoding.UTF8);
        }
        catch (IOException)
        {
src/Moli.Desktop/Host/DefaultContentInstaller.cs
@@ -17,7 +17,8 @@
        "sample.wallpaper",
        "sample.clock",
        "sample.system-info",
        "sample.audio-visualizer"
        "sample.audio-visualizer",
        "sample.llm-command-palette"
    };
    private readonly DesktopPaths _paths;
@@ -73,7 +74,7 @@
            }
            var targetDirectory = Path.Combine(_paths.PluginDirectory, manifest.Id);
            CopyDirectoryReplacingFiles(sourceDirectory, targetDirectory);
            CopyDirectoryPreservingPluginConfig(sourceDirectory, targetDirectory);
            manifests.Add((manifest, manifest.Id));
        }
@@ -182,7 +183,7 @@
        }
    }
    private static void CopyDirectoryReplacingFiles(string sourceDirectory, string targetDirectory)
    private static void CopyDirectoryPreservingPluginConfig(string sourceDirectory, string targetDirectory)
    {
        Directory.CreateDirectory(targetDirectory);
@@ -191,6 +192,14 @@
            var relativePath = Path.GetRelativePath(sourceDirectory, sourceFile);
            var targetFile = Path.Combine(targetDirectory, relativePath);
            Directory.CreateDirectory(Path.GetDirectoryName(targetFile)!);
            if (string.Equals(relativePath, "plugin.json", StringComparison.OrdinalIgnoreCase) &&
                File.Exists(targetFile))
            {
                File.Copy(sourceFile, Path.Combine(targetDirectory, "plugin.template.json"), overwrite: true);
                continue;
            }
            File.Copy(sourceFile, targetFile, overwrite: true);
        }
    }
@@ -219,14 +228,34 @@
    private static bool IsAudioVisualizer(PluginManifest manifest)
        => string.Equals(manifest.Id, "sample.audio-visualizer", StringComparison.OrdinalIgnoreCase);
    private static bool IsLlmCommandPalette(PluginManifest manifest)
        => string.Equals(manifest.Id, "sample.llm-command-palette", StringComparison.OrdinalIgnoreCase);
    private static double ResolveDefaultX(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? 0 : manifest.DefaultLayout.X;
    {
        if (IsAudioVisualizer(manifest))
        {
            return 0;
        }
        if (IsLlmCommandPalette(manifest))
        {
            var width = ResolveDefaultWidth(manifest);
            return Math.Max(0, (SystemParameters.PrimaryScreenWidth - width) / 2);
        }
        return manifest.DefaultLayout.X;
    }
    private static double ResolveDefaultY(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? SystemParameters.PrimaryScreenHeight * 2 / 3 : manifest.DefaultLayout.Y;
    private static double ResolveDefaultWidth(PluginManifest manifest)
        => IsAudioVisualizer(manifest) ? SystemParameters.PrimaryScreenWidth : manifest.DefaultLayout.Width;
        => IsAudioVisualizer(manifest)
            ? SystemParameters.PrimaryScreenWidth
            : IsLlmCommandPalette(manifest)
                ? Math.Min(manifest.DefaultLayout.Width, SystemParameters.PrimaryScreenWidth * 0.72)
                : manifest.DefaultLayout.Width;
    private static double ResolveDefaultHeight(PluginManifest manifest)
        => IsAudioVisualizer(manifest)
src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -7,6 +7,7 @@
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Api;
using Moli.Desktop.Llm;
using Moli.Desktop.Management;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
@@ -24,8 +25,10 @@
        return Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
            {
                var paths = new DesktopPaths();
                logging.ClearProviders();
                logging.AddDebug();
                logging.AddProvider(new DailyFileLoggerProvider(paths.LogDirectory));
            })
            .ConfigureServices(services =>
            {
@@ -37,6 +40,14 @@
                services.AddSingleton<IRuntimeSurfaceController, RuntimeSurfaceController>();
                services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>();
                services.AddSingleton<IConfigurationService, JsonConfigurationService>();
                services.AddSingleton<ILlmModelRegistry, LlmModelRegistry>();
                services.AddSingleton<ICredentialStore, EnvironmentCredentialStore>();
                services.AddHttpClient<OpenAICompatibleAdapter>();
                services.AddHttpClient<AiChatClient>();
                services.AddSingleton<IAiChatClient>(sp => sp.GetRequiredService<AiChatClient>());
                services.AddSingleton<ILlmProviderAdapter>(sp => sp.GetRequiredService<OpenAICompatibleAdapter>());
                services.AddSingleton<ILlmProviderAdapterFactory, LlmProviderAdapterFactory>();
                services.AddSingleton<ILlmGatewayService, LlmGatewayService>();
                services.AddSingleton<IPluginManifestValidator, PluginManifestValidator>();
                services.AddSingleton<PluginStateMachine>();
                services.AddSingleton<IPluginManager, PluginManager>();
src/Moli.Desktop/Host/DesktopPaths.cs
@@ -18,7 +18,7 @@
        LocalAppDataRoot = localAppDataRoot;
        ConfigDirectory = Path.Combine(AppDataRoot, "config");
        PluginDirectory = Path.Combine(AppDataRoot, "plugins");
        LogDirectory = Path.Combine(LocalAppDataRoot, "logs");
        LogDirectory = Path.Combine(AppContext.BaseDirectory, "logs");
        WebViewDataDirectory = Path.Combine(LocalAppDataRoot, "WebView2");
    }
src/Moli.Desktop/Interop/NativeMethods.cs
@@ -6,7 +6,11 @@
internal static class NativeMethods
{
    internal const int GwlStyle = -16;
    internal const int GwlExStyle = -20;
    internal const uint WsChild = 0x40000000;
    internal const uint WsPopup = 0x80000000;
    internal const uint WsVisible = 0x10000000;
    internal const int WsExTransparent = 0x00000020;
    internal const int WsExLayered = 0x00080000;
    internal const int WsExToolWindow = 0x00000080;
@@ -16,6 +20,7 @@
    internal const uint SwpNoMove = 0x0002;
    internal const uint SwpNoZOrder = 0x0004;
    internal const uint SwpNoActivate = 0x0010;
    internal const uint SwpFrameChanged = 0x0020;
    internal const uint SwpShowWindow = 0x0040;
    internal const uint SmtoNormal = 0x0000;
    internal static readonly IntPtr HwndBottom = new(1);
src/Moli.Desktop/Interop/Win32InteropService.cs
@@ -79,6 +79,7 @@
    public void RestoreTopLevelWindow(IntPtr hwnd)
    {
        RestoreTopLevelStyle(hwnd);
        NativeMethods.SetParent(hwnd, IntPtr.Zero);
        var error = NativeMethods.GetLastError();
        if (error != 0)
@@ -88,6 +89,18 @@
                DiagnosticCodes.Win32InteropFailed,
                "RestoreTopLevelWindow failed.",
                new Dictionary<string, string> { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() });
        }
        if (!NativeMethods.SetWindowPos(
            hwnd,
            IntPtr.Zero,
            0,
            0,
            0,
            0,
            NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged))
        {
            RecordWin32Failure("RestoreTopLevelWindow.SetWindowPos", hwnd);
        }
    }
@@ -186,4 +199,11 @@
    {
        return new RectD(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
    }
    private static void RestoreTopLevelStyle(IntPtr hwnd)
    {
        var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64());
        var updated = (current | NativeMethods.WsPopup | NativeMethods.WsVisible) & ~NativeMethods.WsChild;
        NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated)));
    }
}
src/Moli.Desktop/Interop/WorkerWDesktopLayerStrategy.cs
@@ -3,7 +3,7 @@
namespace Moli.Desktop.Interop;
/// <summary>Attempts to attach wallpaper windows behind desktop icons through Explorer's WorkerW layer.</summary>
/// <summary>Attempts to attach desktop surfaces through Explorer's WorkerW or Progman desktop host.</summary>
public sealed class WorkerWDesktopLayerStrategy : IDesktopLayerStrategy
{
    private readonly IDiagnosticsService _diagnostics;
@@ -20,24 +20,27 @@
    public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error)
    {
        error = null;
        var workerW = FindWorkerW();
        if (workerW == IntPtr.Zero)
        var desktopHost = FindDesktopHostWindow(out var hostClass);
        if (desktopHost == IntPtr.Zero)
        {
            error = "WorkerW window was not found.";
            error = "Explorer desktop host window was not found.";
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.DesktopLayerAttachFailed,
                "WorkerW desktop layer was not found.",
                "Explorer desktop host window was not found.",
                new Dictionary<string, string> { ["strategy"] = Name });
            return false;
        }
        if (NativeMethods.SetParent(hwnd, workerW) == IntPtr.Zero)
        SetDesktopChildStyle(hwnd);
        if (NativeMethods.SetParent(hwnd, desktopHost) == IntPtr.Zero)
        {
            var lastError = NativeMethods.GetLastError();
            if (lastError != 0)
            {
                error = $"SetParent failed with {lastError}";
                RestoreTopLevelStyle(hwnd);
                return false;
            }
        }
@@ -49,9 +52,11 @@
            (int)bounds.Y,
            (int)bounds.Width,
            (int)bounds.Height,
            NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow))
            NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged | NativeMethods.SwpShowWindow))
        {
            error = $"SetWindowPos failed with {NativeMethods.GetLastError()}";
            NativeMethods.SetParent(hwnd, IntPtr.Zero);
            RestoreTopLevelStyle(hwnd);
            return false;
        }
@@ -59,15 +64,24 @@
            DiagnosticSeverity.Info,
            DiagnosticCodes.DesktopLayerStrategySelected,
            "Desktop layer strategy selected.",
            new Dictionary<string, string> { ["strategy"] = Name });
            new Dictionary<string, string> { ["strategy"] = Name, ["host"] = hostClass });
        return true;
    }
    private static IntPtr FindWorkerW()
    private static IntPtr FindDesktopHostWindow(out string hostClass)
    {
        hostClass = "WorkerW";
        var progman = NativeMethods.FindWindow("Progman", null);
        if (progman != IntPtr.Zero)
        {
            NativeMethods.SendMessageTimeout(
                progman,
                0x052C,
                new IntPtr(0xD),
                IntPtr.Zero,
                NativeMethods.SmtoNormal,
                1000,
                out _);
            NativeMethods.SendMessageTimeout(
                progman,
                0x052C,
@@ -91,6 +105,26 @@
            return workerW == IntPtr.Zero;
        }, IntPtr.Zero);
        return workerW;
        if (workerW != IntPtr.Zero)
        {
            return workerW;
        }
        hostClass = "Progman";
        return progman;
    }
    private static void SetDesktopChildStyle(IntPtr hwnd)
    {
        var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64());
        var updated = (current | NativeMethods.WsChild | NativeMethods.WsVisible) & ~NativeMethods.WsPopup;
        NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated)));
    }
    private static void RestoreTopLevelStyle(IntPtr hwnd)
    {
        var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64());
        var updated = (current | NativeMethods.WsPopup | NativeMethods.WsVisible) & ~NativeMethods.WsChild;
        NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated)));
    }
}
src/Moli.Desktop/Layout/LayoutManager.cs
@@ -122,7 +122,7 @@
            ClickThrough = patch.ClickThrough ?? layout.ClickThrough,
            Scale = patch.Scale ?? layout.Scale,
            DisplayLayer = patch.DisplayLayer ?? layout.DisplayLayer
        });
        }, allowLocked: IsUnlockPatch(patch));
    }
    public IReadOnlyList<WidgetLayout> ReconcileMonitors(IReadOnlyList<MonitorInfo> monitors)
@@ -168,7 +168,7 @@
        }
    }
    private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update)
    private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update, bool allowLocked = false)
    {
        lock (_gate)
        {
@@ -179,7 +179,7 @@
            }
            var current = _document.Instances[index];
            if (current.IsLocked)
            if (current.IsLocked && !allowLocked)
            {
                return OperationResult<WidgetLayout>.Failure("WidgetLayoutLocked", $"Widget layout {instanceId} is locked.");
            }
@@ -256,4 +256,14 @@
    private static double Clamp(double value, double min, double max)
        => Math.Min(Math.Max(value, min), max);
    private static bool IsUnlockPatch(WidgetLayoutPatch patch)
        => patch.IsLocked == false &&
           patch.Bounds is null &&
           patch.MonitorId is null &&
           patch.IsVisible is null &&
           patch.Opacity is null &&
           patch.ClickThrough is null &&
           patch.Scale is null &&
           patch.DisplayLayer is null;
}
src/Moli.Desktop/Llm/AiChatClient.cs
New file
@@ -0,0 +1,621 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.IO;
using Moli.Desktop.Diagnostics;
namespace Moli.Desktop.Llm;
public sealed class AiChatClient : IAiChatClient
{
    private readonly HttpClient _httpClient;
    private readonly IDiagnosticsService _diagnostics;
    private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
    private readonly ConcurrentDictionary<string, string> _sessionTokens = new(StringComparer.OrdinalIgnoreCase);
    public AiChatClient(HttpClient httpClient, IDiagnosticsService diagnostics)
    {
        _httpClient = httpClient;
        _diagnostics = diagnostics;
    }
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/chat/models", null, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data) ||
            !data.TryGetProperty("models", out var modelsElement) ||
            modelsElement.ValueKind != JsonValueKind.Array)
        {
            return [];
        }
        var defaultModel = data.TryGetProperty("defaultModel", out var defaultModelElement)
            ? defaultModelElement.GetString()
            : null;
        return modelsElement
            .EnumerateArray()
            .Where(item => item.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(item.GetString()))
            .Select(item =>
            {
                var id = item.GetString()!;
                return new LlmModelSummary
                {
                    Id = id,
                    Label = id == defaultModel ? $"{id} *" : id,
                    Provider = "aichat",
                    SupportsStreaming = true,
                    Enabled = true
                };
            })
            .ToList();
    }
    public async Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        try
        {
            using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/projects", null, cancellationToken).ConfigureAwait(false);
            if (!TryGetProjectsData(document.RootElement, out var data))
            {
                _diagnostics.Record(
                    DiagnosticSeverity.Warning,
                    LlmErrorCodes.AiChatProjectLoadFailed,
                    "AiChat project response did not contain a project array.",
                    new Dictionary<string, string> { ["baseUrl"] = runtimeConfig.AiChat.BaseUrl });
                return [];
            }
            return data.EnumerateArray()
                .Select(ParseProject)
                .Where(project => project is not null)
                .Select(project => project!)
                .ToList();
        }
        catch (AiChatClientException ex)
        {
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                ex.Code,
                "AiChat projects could not be loaded.",
                new Dictionary<string, string>
                {
                    ["baseUrl"] = runtimeConfig.AiChat.BaseUrl,
                    ["exception"] = ex.GetType().Name
                });
            throw;
        }
    }
    public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        LlmPluginRuntimeConfig runtimeConfig,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        JsonDocument? sendDocument = null;
        LlmErrorEvent? startError = null;
        try
        {
            var message = request.Messages.LastOrDefault(message => string.Equals(message.Role, "user", StringComparison.OrdinalIgnoreCase))?.Content
                ?? request.Messages.Last().Content;
            var payload = new
            {
                projectId = request.ProjectId,
                modelName = request.ModelId,
                message
            };
            sendDocument = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/chat/send", payload, cancellationToken).ConfigureAwait(false);
        }
        catch (AiChatClientException ex)
        {
            startError = new LlmErrorEvent { RequestId = request.RequestId, Code = ex.Code, Message = ex.Message };
        }
        if (startError is not null)
        {
            yield return startError;
            yield break;
        }
        var generationDocument = sendDocument;
        if (generationDocument is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.AiChatApiFailed,
                Message = "AiChat did not return a valid generation stream."
            };
            yield break;
        }
        using (generationDocument)
        {
            if (!TryGetData(generationDocument.RootElement, out var data) ||
                !data.TryGetProperty("generationId", out var generationIdElement) ||
                !data.TryGetProperty("streamToken", out var streamTokenElement) ||
                string.IsNullOrWhiteSpace(generationIdElement.GetString()) ||
                string.IsNullOrWhiteSpace(streamTokenElement.GetString()))
            {
                yield return new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.AiChatApiFailed,
                    Message = "AiChat did not return a valid generation stream."
                };
                yield break;
            }
            var path = $"/api/chat/generations/{Uri.EscapeDataString(generationIdElement.GetString()!)}/stream?token={Uri.EscapeDataString(streamTokenElement.GetString()!)}";
            await foreach (var streamEvent in StreamAiChatEventsAsync(runtimeConfig, request.RequestId, path, cancellationToken).ConfigureAwait(false))
            {
                yield return streamEvent;
            }
        }
    }
    public async Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/auth/me", null, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data))
        {
            return new AiChatMemoryCapabilities();
        }
        return new AiChatMemoryCapabilities
        {
            CanUseMemory = ReadBool(data, "canUseMemory"),
            CanViewMemory = ReadBool(data, "canViewMemory"),
            CanManageMemory = ReadBool(data, "canManageMemory")
        };
    }
    public async Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default)
    {
        var query = new List<string>();
        if (!string.IsNullOrWhiteSpace(request.Scope))
        {
            query.Add($"scope={Uri.EscapeDataString(request.Scope)}");
        }
        if (!string.IsNullOrWhiteSpace(request.ProjectId))
        {
            query.Add($"projectId={Uri.EscapeDataString(request.ProjectId)}");
        }
        var path = "/api/memories" + (query.Count > 0 ? "?" + string.Join("&", query) : "");
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
    public async Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories", request, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
    public async Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(memoryId))
        {
            throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "memoryId is required.");
        }
        using var _ = await SendJsonAsync(runtimeConfig, HttpMethod.Delete, $"/api/memories/{Uri.EscapeDataString(memoryId)}", null, cancellationToken).ConfigureAwait(false);
    }
    public async Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default)
    {
        using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories/recall", request, cancellationToken).ConfigureAwait(false);
        return CloneData(document);
    }
    private async IAsyncEnumerable<LlmStreamEvent> StreamAiChatEventsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string requestId,
        string path,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        using var request = await CreateRequestAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        if (!response.IsSuccessStatusCode)
        {
            yield return new LlmErrorEvent
            {
                RequestId = requestId,
                Code = MapStatusCode(response.StatusCode),
                Message = $"AiChat stream returned {(int)response.StatusCode}."
            };
            yield break;
        }
        await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
        using var reader = new StreamReader(stream, Encoding.UTF8);
        var eventName = "message";
        var dataLines = new List<string>();
        while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (line.StartsWith(":", StringComparison.Ordinal))
            {
                continue;
            }
            if (line.Length == 0)
            {
                foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines)))
                {
                    yield return streamEvent;
                    if (streamEvent is LlmCompletedEvent or LlmErrorEvent)
                    {
                        yield break;
                    }
                }
                eventName = "message";
                dataLines.Clear();
                continue;
            }
            if (line.StartsWith("event:", StringComparison.OrdinalIgnoreCase))
            {
                eventName = line["event:".Length..].Trim();
                continue;
            }
            if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                dataLines.Add(line["data:".Length..].TrimStart());
            }
        }
        if (dataLines.Count > 0)
        {
            foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines)))
            {
                yield return streamEvent;
                if (streamEvent is LlmCompletedEvent or LlmErrorEvent)
                {
                    yield break;
                }
            }
        }
        yield return new LlmErrorEvent
        {
            RequestId = requestId,
            Code = LlmErrorCodes.AiChatSseInterrupted,
            Message = "AiChat stream ended before completion."
        };
    }
    private IEnumerable<LlmStreamEvent> ParseSseEvent(string requestId, string eventName, string data)
    {
        if (string.IsNullOrWhiteSpace(data))
        {
            yield break;
        }
        JsonDocument document;
        try
        {
            document = JsonDocument.Parse(data);
        }
        catch (JsonException ex)
        {
            throw new AiChatClientException(LlmErrorCodes.StreamParseFailed, "Failed to parse AiChat stream chunk.", ex);
        }
        using (document)
        {
            var root = document.RootElement;
            if (eventName.Equals("chunk", StringComparison.OrdinalIgnoreCase) &&
                root.TryGetProperty("delta", out var delta) &&
                delta.ValueKind == JsonValueKind.String)
            {
                yield return new LlmDeltaEvent { RequestId = requestId, Delta = delta.GetString() ?? "" };
                yield break;
            }
            if (eventName.Equals("snapshot", StringComparison.OrdinalIgnoreCase) &&
                root.TryGetProperty("content", out var content) &&
                content.ValueKind == JsonValueKind.String &&
                !string.IsNullOrEmpty(content.GetString()))
            {
                yield return new LlmDeltaEvent { RequestId = requestId, Delta = content.GetString() ?? "" };
                yield break;
            }
            if (eventName.Equals("done", StringComparison.OrdinalIgnoreCase))
            {
                yield return new LlmCompletedEvent { RequestId = requestId };
                yield break;
            }
            if (eventName.Equals("failed", StringComparison.OrdinalIgnoreCase) ||
                eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase))
            {
                var message = root.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String
                    ? error.GetString() ?? "AiChat request failed."
                    : eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase) ? "AiChat request was aborted." : "AiChat request failed.";
                yield return new LlmErrorEvent { RequestId = requestId, Code = LlmErrorCodes.AiChatApiFailed, Message = message };
            }
        }
    }
    private async Task<JsonDocument> SendJsonAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        HttpMethod method,
        string path,
        object? payload,
        CancellationToken cancellationToken)
    {
        using var request = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false);
        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
        if (response.StatusCode == HttpStatusCode.Unauthorized)
        {
            ClearSession(runtimeConfig);
            using var retry = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false);
            using var retryResponse = await _httpClient.SendAsync(retry, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
            return await ReadJsonResponseAsync(retryResponse, cancellationToken).ConfigureAwait(false);
        }
        return await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false);
    }
    private async Task<HttpRequestMessage> CreateRequestAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        HttpMethod method,
        string path,
        object? payload,
        CancellationToken cancellationToken)
    {
        var uri = BuildUri(runtimeConfig, path);
        var request = new HttpRequestMessage(method, uri);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        if (!path.Equals("/api/auth/login", StringComparison.OrdinalIgnoreCase))
        {
            var sessionToken = await EnsureSessionAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
            request.Headers.Add("x-session-token", sessionToken);
        }
        if (payload is not null)
        {
            request.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json");
        }
        return request;
    }
    private async Task<string> EnsureSessionAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken)
    {
        var key = SessionKey(runtimeConfig);
        if (_sessionTokens.TryGetValue(key, out var existing) && !string.IsNullOrWhiteSpace(existing))
        {
            return existing;
        }
        var email = runtimeConfig.AiChat.Account.Email;
        var password = ResolvePassword(runtimeConfig);
        if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password))
        {
            throw new AiChatClientException(LlmErrorCodes.AiChatCredentialMissing, "AiChat account or password is missing.");
        }
        using var request = new HttpRequestMessage(HttpMethod.Post, BuildUri(runtimeConfig, "/api/auth/login"))
        {
            Content = new StringContent(
                JsonSerializer.Serialize(new { email, password }, _jsonOptions),
                Encoding.UTF8,
                "application/json")
        };
        using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);
        using var document = await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false);
        if (!TryGetData(document.RootElement, out var data) ||
            !data.TryGetProperty("sessionToken", out var token) ||
            token.ValueKind != JsonValueKind.String ||
            string.IsNullOrWhiteSpace(token.GetString()))
        {
            throw new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "AiChat login did not return a session token.");
        }
        _sessionTokens[key] = token.GetString()!;
        return token.GetString()!;
    }
    private async Task<JsonDocument> ReadJsonResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken)
    {
        await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
        JsonDocument document;
        try
        {
            document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
        }
        catch (JsonException) when (response.Content.Headers.ContentLength == 0)
        {
            document = JsonDocument.Parse("""{"ok":true}""");
        }
        if (!response.IsSuccessStatusCode)
        {
            var (code, message) = ExtractError(document.RootElement, response.StatusCode);
            document.Dispose();
            throw new AiChatClientException(code, message);
        }
        if (document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind == JsonValueKind.False)
        {
            var (code, message) = ExtractError(document.RootElement, response.StatusCode);
            document.Dispose();
            throw new AiChatClientException(code, message);
        }
        return document;
    }
    private static AiChatProjectSummary? ParseProject(JsonElement item)
    {
        if (!item.TryGetProperty("id", out var id) || id.ValueKind != JsonValueKind.String)
        {
            return null;
        }
        return new AiChatProjectSummary
        {
            Id = id.GetString()!,
            Name = item.TryGetProperty("name", out var name) && name.ValueKind == JsonValueKind.String ? name.GetString() ?? id.GetString()! : id.GetString()!,
            ProjectType = item.TryGetProperty("projectType", out var projectType) && projectType.ValueKind == JsonValueKind.String ? projectType.GetString() ?? "CHAT" : "CHAT",
            MemoryMode = item.TryGetProperty("memoryMode", out var memoryMode) && memoryMode.ValueKind == JsonValueKind.String ? memoryMode.GetString() ?? "ISOLATED" : "ISOLATED"
        };
    }
    private static AiChatJsonResult CloneData(JsonDocument document)
    {
        if (!TryGetData(document.RootElement, out var data))
        {
            return new AiChatJsonResult();
        }
        return new AiChatJsonResult { Data = JsonSerializer.Deserialize<object>(data.GetRawText()) };
    }
    private static bool TryGetData(JsonElement root, out JsonElement data)
    {
        if (root.TryGetProperty("data", out data))
        {
            return true;
        }
        data = default;
        return false;
    }
    private static bool TryGetProjectsData(JsonElement root, out JsonElement projects)
    {
        if (TryGetData(root, out var data))
        {
            if (data.ValueKind == JsonValueKind.Array)
            {
                projects = data;
                return true;
            }
            if (data.ValueKind == JsonValueKind.Object &&
                data.TryGetProperty("projects", out var nestedProjects) &&
                nestedProjects.ValueKind == JsonValueKind.Array)
            {
                projects = nestedProjects;
                return true;
            }
        }
        projects = default;
        return false;
    }
    private static bool ReadBool(JsonElement root, string property)
        => root.TryGetProperty(property, out var value) &&
           (value.ValueKind == JsonValueKind.True || (value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed));
    private static (string Code, string Message) ExtractError(JsonElement root, HttpStatusCode statusCode)
    {
        var apiCode = root.TryGetProperty("code", out var codeElement) && codeElement.ValueKind == JsonValueKind.String
            ? codeElement.GetString()
            : null;
        var message = root.TryGetProperty("error", out var errorElement) && errorElement.ValueKind == JsonValueKind.String
            ? errorElement.GetString() ?? $"AiChat returned {(int)statusCode}."
            : $"AiChat returned {(int)statusCode}.";
        return (MapApiCode(apiCode, statusCode), message);
    }
    private static string MapApiCode(string? apiCode, HttpStatusCode statusCode)
    {
        if (string.Equals(apiCode, "TOKEN_TOTAL_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase) ||
            string.Equals(apiCode, "TOKEN_PER_REQUEST_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase))
        {
            return LlmErrorCodes.AiChatQuotaExceeded;
        }
        if (string.Equals(apiCode, "PERMISSION_DENIED", StringComparison.OrdinalIgnoreCase))
        {
            return LlmErrorCodes.AiChatMemoryPermissionDenied;
        }
        if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
        {
            return LlmErrorCodes.AiChatLoginFailed;
        }
        return apiCode ?? LlmErrorCodes.AiChatApiFailed;
    }
    private static string MapStatusCode(HttpStatusCode statusCode)
        => statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden
            ? LlmErrorCodes.AiChatLoginFailed
            : LlmErrorCodes.AiChatApiFailed;
    private static Uri BuildUri(LlmPluginRuntimeConfig runtimeConfig, string path)
    {
        var baseUrl = string.IsNullOrWhiteSpace(runtimeConfig.AiChat.BaseUrl)
            ? "http://192.168.1.111:13000"
            : runtimeConfig.AiChat.BaseUrl;
        if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var baseUri) ||
            baseUri.Scheme is not ("http" or "https"))
        {
            throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "AiChat baseUrl must be an absolute HTTP or HTTPS URL.");
        }
        return new Uri(baseUri, path);
    }
    private static string? ResolvePassword(LlmPluginRuntimeConfig runtimeConfig)
    {
        var envName = runtimeConfig.AiChat.Account.PasswordEnv;
        if (!string.IsNullOrWhiteSpace(envName))
        {
            var envValue = Environment.GetEnvironmentVariable(envName)
                ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.User)
                ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.Machine);
            if (!string.IsNullOrWhiteSpace(envValue))
            {
                return envValue;
            }
        }
        return runtimeConfig.AiChat.Account.Password;
    }
    private void ClearSession(LlmPluginRuntimeConfig runtimeConfig)
    {
        _sessionTokens.TryRemove(SessionKey(runtimeConfig), out _);
    }
    private static string SessionKey(LlmPluginRuntimeConfig runtimeConfig)
        => $"{runtimeConfig.AiChat.BaseUrl}|{runtimeConfig.AiChat.Account.Email}";
}
src/Moli.Desktop/Llm/EnvironmentCredentialStore.cs
New file
@@ -0,0 +1,25 @@
namespace Moli.Desktop.Llm;
public sealed class EnvironmentCredentialStore : ICredentialStore
{
    public Task<string?> ResolveSecretAsync(string? authRef, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        if (string.IsNullOrWhiteSpace(authRef))
        {
            return Task.FromResult<string?>(null);
        }
        var direct = Environment.GetEnvironmentVariable(authRef);
        if (!string.IsNullOrWhiteSpace(direct))
        {
            return Task.FromResult<string?>(direct);
        }
        var normalized = "MOLI_" + new string(authRef
            .Select(ch => char.IsLetterOrDigit(ch) ? char.ToUpperInvariant(ch) : '_')
            .ToArray());
        return Task.FromResult(Environment.GetEnvironmentVariable(normalized));
    }
}
src/Moli.Desktop/Llm/ILlmServices.cs
New file
@@ -0,0 +1,109 @@
namespace Moli.Desktop.Llm;
public interface ILlmGatewayService
{
    Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default);
    Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default);
    Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default);
    IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        CancellationToken cancellationToken = default);
    Task CancelAsync(string requestId, CancellationToken cancellationToken = default);
}
public interface ILlmModelRegistry
{
    Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default);
    Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default);
}
public interface ILlmProviderAdapter
{
    string Provider { get; }
    IAsyncEnumerable<LlmProviderChunk> StreamAsync(
        LlmProviderRequest request,
        CancellationToken cancellationToken = default);
}
public interface ILlmProviderAdapterFactory
{
    ILlmProviderAdapter? Get(string provider);
}
public interface ICredentialStore
{
    Task<string?> ResolveSecretAsync(string? authRef, CancellationToken cancellationToken = default);
}
public interface IAiChatClient
{
    Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default);
    Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default);
    Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default);
}
src/Moli.Desktop/Llm/LlmGatewayService.cs
New file
@@ -0,0 +1,356 @@
using System.Collections.Concurrent;
using System.Net.Http;
using System.Runtime.CompilerServices;
using Moli.Desktop.Diagnostics;
namespace Moli.Desktop.Llm;
public sealed class LlmGatewayService : ILlmGatewayService
{
    private static readonly HashSet<string> AllowedRoles = new(StringComparer.OrdinalIgnoreCase)
    {
        "system",
        "user",
        "assistant"
    };
    private readonly ILlmModelRegistry _registry;
    private readonly ICredentialStore _credentialStore;
    private readonly ILlmProviderAdapterFactory _adapterFactory;
    private readonly IDiagnosticsService _diagnostics;
    private readonly IAiChatClient? _aiChatClient;
    private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase);
    public LlmGatewayService(
        ILlmModelRegistry registry,
        ICredentialStore credentialStore,
        ILlmProviderAdapterFactory adapterFactory,
        IDiagnosticsService diagnostics,
        IAiChatClient? aiChatClient = null)
    {
        _registry = registry;
        _credentialStore = credentialStore;
        _adapterFactory = adapterFactory;
        _diagnostics = diagnostics;
        _aiChatClient = aiChatClient;
    }
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
    {
        var document = await _registry.LoadAsync(cancellationToken).ConfigureAwait(false);
        return document.Models
            .Where(model => model.Enabled)
            .Select(model => new LlmModelSummary
            {
                Id = model.Id,
                Label = model.Label,
                Provider = model.Provider,
                SupportsStreaming = model.SupportsStreaming,
                Enabled = model.Enabled
            })
            .ToList();
    }
    public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
    {
        if (runtimeConfig.IsAiChatMode)
        {
            return _aiChatClient is null
                ? []
                : await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false);
        }
        var configuredModels = 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
            })
            .ToList();
        if (configuredModels.Count > 0)
        {
            return configuredModels;
        }
        return await GetModelsAsync(cancellationToken).ConfigureAwait(false);
    }
    public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([])
            : _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken);
    public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.FromResult(new AiChatMemoryCapabilities())
            : _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken);
    public Task<AiChatJsonResult> GetMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatGetMemoriesRequest request,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken);
    public Task<AiChatJsonResult> CreateMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatCreateMemoryRequest request,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken);
    public Task DeleteMemoryAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        string memoryId,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.CompletedTask
            : _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken);
    public Task<AiChatJsonResult> RecallMemoriesAsync(
        LlmPluginRuntimeConfig runtimeConfig,
        AiChatRecallMemoriesRequest request,
        CancellationToken cancellationToken = default)
        => _aiChatClient is null
            ? Task.FromResult(new AiChatJsonResult())
            : _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken);
    public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
        LlmChatRequest request,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        if (!IsValidRequest(request, out var validationError))
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.RequestInvalid,
                Message = validationError
            };
            yield break;
        }
        if (string.Equals(request.Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase))
        {
            if (_aiChatClient is null)
            {
                yield return new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.AiChatApiFailed,
                    Message = "AiChat client is not available."
                };
                yield break;
            }
            await foreach (var streamEvent in _aiChatClient.StreamChatAsync(request, request.RuntimeConfig, cancellationToken).ConfigureAwait(false))
            {
                yield return streamEvent;
            }
            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);
        if (model is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.ModelNotFound,
                Message = "Selected LLM model is unavailable."
            };
            yield break;
        }
        var adapter = _adapterFactory.Get(model.Provider);
        if (adapter is null)
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.ProviderUnsupported,
                Message = "Selected LLM provider is unsupported."
            };
            yield break;
        }
        var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        var timeoutMs = request.Options.TimeoutMs ?? model.RequestDefaults.TimeoutMs;
        linkedCts.CancelAfter(TimeSpan.FromMilliseconds(timeoutMs));
        _activeRequests[request.RequestId] = linkedCts;
        var secret = await _credentialStore.ResolveSecretAsync(model.AuthRef, linkedCts.Token).ConfigureAwait(false);
        if (!string.IsNullOrWhiteSpace(model.AuthRef) && string.IsNullOrWhiteSpace(secret))
        {
            yield return new LlmErrorEvent
            {
                RequestId = request.RequestId,
                Code = LlmErrorCodes.CredentialMissing,
                Message = "LLM credential is missing. Check the model authRef configuration."
            };
            yield break;
        }
        var providerRequest = new LlmProviderRequest
        {
            RequestId = request.RequestId,
            Model = model,
            Messages = request.Messages,
            Options = request.Options,
            ApiKey = secret
        };
        await using var enumerator = adapter.StreamAsync(providerRequest, linkedCts.Token).GetAsyncEnumerator(linkedCts.Token);
        while (true)
        {
            LlmStreamEvent? nextEvent = null;
            try
            {
                if (!await enumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                    yield break;
                }
                var chunk = enumerator.Current;
                if (!string.IsNullOrEmpty(chunk.Delta))
                {
                    nextEvent = new LlmDeltaEvent { RequestId = request.RequestId, Delta = chunk.Delta };
                }
                if (chunk.IsCompleted)
                {
                    nextEvent = new LlmCompletedEvent { RequestId = request.RequestId, Usage = chunk.Usage };
                }
            }
            catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
            {
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.Timeout,
                    Message = "LLM request timed out."
                };
            }
            catch (HttpRequestException ex)
            {
                RecordFailure(request, model, LlmErrorCodes.EndpointUnavailable, ex.GetType().Name);
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = LlmErrorCodes.EndpointUnavailable,
                    Message = "LLM endpoint is unavailable."
                };
            }
            catch (LlmProviderException ex)
            {
                RecordFailure(request, model, ex.Code, ex.GetType().Name);
                nextEvent = new LlmErrorEvent
                {
                    RequestId = request.RequestId,
                    Code = ex.Code,
                    Message = ex.Message
                };
            }
            finally
            {
                if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                }
            }
            if (nextEvent is null)
            {
                continue;
            }
            yield return nextEvent;
            if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
            {
                yield break;
            }
        }
    }
    public Task CancelAsync(string requestId, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        if (_activeRequests.TryRemove(requestId, out var cts))
        {
            cts.Cancel();
            cts.Dispose();
        }
        return Task.CompletedTask;
    }
    private static bool IsValidRequest(LlmChatRequest request, out string error)
    {
        if (string.IsNullOrWhiteSpace(request.RequestId) ||
            string.IsNullOrWhiteSpace(request.PluginId) ||
            string.IsNullOrWhiteSpace(request.InstanceId) ||
            string.IsNullOrWhiteSpace(request.ModelId))
        {
            error = "requestId, pluginId, instanceId and modelId are required.";
            return false;
        }
        if (request.Messages.Count == 0 || request.Messages.Any(message =>
                string.IsNullOrWhiteSpace(message.Content) ||
                !AllowedRoles.Contains(message.Role)))
        {
            error = "At least one valid message is required.";
            return false;
        }
        error = "";
        return true;
    }
    private static bool IsUsableRuntimeModel(LlmModelConfig model)
        => model.Enabled &&
           !string.IsNullOrWhiteSpace(model.Id) &&
           !string.IsNullOrWhiteSpace(model.Label) &&
           !string.IsNullOrWhiteSpace(model.Provider) &&
           !string.IsNullOrWhiteSpace(model.Endpoint) &&
           !string.IsNullOrWhiteSpace(model.ApiModel);
    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,
            "LLM request failed.",
            new Dictionary<string, string>
            {
                ["requestId"] = request.RequestId,
                ["modelId"] = request.ModelId,
                ["provider"] = model.Provider,
                ["endpointHost"] = host,
                ["exception"] = exception
            });
    }
}
src/Moli.Desktop/Llm/LlmModelRegistry.cs
New file
@@ -0,0 +1,205 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
namespace Moli.Desktop.Llm;
public sealed class LlmModelRegistry : ILlmModelRegistry
{
    public const string FileName = "llm-models.json";
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        PropertyNameCaseInsensitive = true,
        WriteIndented = true,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
    };
    public LlmModelRegistry(DesktopPaths paths, IDiagnosticsService diagnostics)
    {
        _paths = paths;
        _diagnostics = diagnostics;
    }
    public async Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, FileName);
        if (!File.Exists(path))
        {
            var created = CreateDefault();
            await SaveAsync(created, cancellationToken).ConfigureAwait(false);
            return created;
        }
        try
        {
            await using var stream = File.OpenRead(path);
            var document = await JsonSerializer.DeserializeAsync<LlmSettingsDocument>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false);
            if (document is null || document.SchemaVersion <= 0)
            {
                throw new JsonException("LLM settings document is empty or missing schemaVersion.");
            }
            return Normalize(document);
        }
        catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
        {
            BackupInvalidFile(path);
            var recovered = CreateDefault();
            await SaveAsync(recovered, cancellationToken).ConfigureAwait(false);
            _diagnostics.Record(
                DiagnosticSeverity.Warning,
                DiagnosticCodes.ConfigurationRecovered,
                "Recovered llm-models.json from invalid configuration.",
                new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
            return recovered;
        }
    }
    public async Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(modelId))
        {
            return null;
        }
        var document = await LoadAsync(cancellationToken).ConfigureAwait(false);
        return document.Models.FirstOrDefault(model =>
            model.Enabled &&
            string.Equals(model.Id, modelId, StringComparison.OrdinalIgnoreCase));
    }
    private async Task SaveAsync(LlmSettingsDocument document, CancellationToken cancellationToken)
    {
        Directory.CreateDirectory(_paths.ConfigDirectory);
        var path = Path.Combine(_paths.ConfigDirectory, FileName);
        var tempPath = path + ".tmp";
        var backupPath = path + ".bak";
        await using (var stream = File.Create(tempPath))
        {
            await JsonSerializer.SerializeAsync(stream, document, _jsonOptions, cancellationToken).ConfigureAwait(false);
        }
        if (File.Exists(path))
        {
            File.Copy(path, backupPath, overwrite: true);
        }
        File.Move(tempPath, path, overwrite: true);
    }
    private LlmSettingsDocument Normalize(LlmSettingsDocument document)
    {
        var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var normalized = new List<LlmModelConfig>();
        foreach (var model in document.Models)
        {
            if (!IsValidModel(model, seen))
            {
                continue;
            }
            seen.Add(model.Id);
            normalized.Add(model);
        }
        var defaultModel = normalized.Any(model =>
            model.Enabled &&
            string.Equals(model.Id, document.DefaultModel, StringComparison.OrdinalIgnoreCase))
                ? document.DefaultModel
                : normalized.FirstOrDefault(model => model.Enabled)?.Id;
        return document with
        {
            DefaultModel = defaultModel,
            Models = normalized
        };
    }
    private bool IsValidModel(LlmModelConfig model, HashSet<string> seen)
    {
        if (string.IsNullOrWhiteSpace(model.Id) || seen.Contains(model.Id))
        {
            RecordInvalid(model.Id, "Model id is empty or duplicated.");
            return false;
        }
        if (string.IsNullOrWhiteSpace(model.Label) || model.Label.Length > 40)
        {
            RecordInvalid(model.Id, "Model label is empty or too long.");
            return false;
        }
        if (string.IsNullOrWhiteSpace(model.Provider))
        {
            RecordInvalid(model.Id, "Model provider is required.");
            return false;
        }
        if (!Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint) ||
            endpoint.Scheme is not ("http" or "https"))
        {
            RecordInvalid(model.Id, "Model endpoint must be an absolute HTTP or HTTPS URL.");
            return false;
        }
        if (string.IsNullOrWhiteSpace(model.ApiModel))
        {
            RecordInvalid(model.Id, "apiModel is required.");
            return false;
        }
        return true;
    }
    private void RecordInvalid(string? modelId, string message)
    {
        _diagnostics.Record(
            DiagnosticSeverity.Warning,
            "LlmModelInvalid",
            message,
            new Dictionary<string, string> { ["modelId"] = modelId ?? "" });
    }
    private static LlmSettingsDocument CreateDefault() => new()
    {
        DefaultModel = null,
        Models =
        [
            new LlmModelConfig
            {
                Id = "local-openai-compatible",
                Label = "Local",
                Provider = "openai-compatible",
                Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
                AuthRef = null,
                ApiModel = "qwen2.5:14b",
                SupportsStreaming = true,
                Enabled = false
            }
        ]
    };
    private static void BackupInvalidFile(string path)
    {
        if (!File.Exists(path))
        {
            return;
        }
        var timestamp = DateTimeOffset.Now.ToString("yyyyMMddHHmmss");
        var invalidPath = Path.Combine(
            Path.GetDirectoryName(path)!,
            $"{Path.GetFileNameWithoutExtension(path)}.invalid.{timestamp}{Path.GetExtension(path)}");
        File.Move(path, invalidPath, overwrite: true);
    }
}
src/Moli.Desktop/Llm/LlmModels.cs
New file
@@ -0,0 +1,223 @@
using System.Text.Json.Serialization;
namespace Moli.Desktop.Llm;
public sealed record LlmSettingsDocument
{
    public int SchemaVersion { get; init; } = 1;
    public string? DefaultModel { get; init; }
    public List<LlmModelConfig> Models { get; init; } = [];
}
public sealed record LlmModelConfig
{
    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? 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 sealed record LlmRequestDefaults
{
    public double Temperature { get; init; } = 0.7;
    public int MaxTokens { get; init; } = 2048;
    public int TimeoutMs { get; init; } = 60000;
}
public sealed record LlmModelSummary
{
    public required string Id { get; init; }
    public required string Label { get; init; }
    public required string Provider { get; init; }
    public bool SupportsStreaming { get; init; }
    public bool Enabled { get; init; }
}
public sealed record LlmChatRequest
{
    public required string RequestId { get; init; }
    public required string PluginId { get; init; }
    public required string InstanceId { get; init; }
    public string Mode { get; init; } = LlmConnectionModes.ProviderDirect;
    public string? ProjectId { get; init; }
    public required string ModelId { get; init; }
    public required IReadOnlyList<LlmMessage> Messages { get; init; }
    public LlmRequestOptions Options { get; init; } = new();
    public LlmPluginRuntimeConfig RuntimeConfig { get; init; } = new();
}
public sealed record LlmMessage
{
    public required string Role { get; init; }
    public required string Content { get; init; }
}
public sealed record LlmRequestOptions
{
    public double? Temperature { get; init; }
    public int? MaxTokens { get; init; }
    public int? TimeoutMs { get; init; }
}
public sealed record LlmProviderRequest
{
    public required string RequestId { get; init; }
    public required LlmModelConfig Model { get; init; }
    public required IReadOnlyList<LlmMessage> Messages { get; init; }
    public required LlmRequestOptions Options { get; init; }
    public string? ApiKey { get; init; }
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(LlmDeltaEvent), "delta")]
[JsonDerivedType(typeof(LlmCompletedEvent), "completed")]
[JsonDerivedType(typeof(LlmErrorEvent), "error")]
public abstract record LlmStreamEvent
{
    public required string RequestId { get; init; }
}
public sealed record LlmDeltaEvent : LlmStreamEvent
{
    public required string Delta { get; init; }
}
public sealed record LlmCompletedEvent : LlmStreamEvent
{
    public LlmUsage? Usage { get; init; }
}
public sealed record LlmErrorEvent : LlmStreamEvent
{
    public required string Code { get; init; }
    public required string Message { get; init; }
}
public sealed record LlmUsage
{
    public int? InputTokens { get; init; }
    public int? OutputTokens { get; init; }
}
public sealed record LlmProviderChunk
{
    public string? Delta { get; init; }
    public bool IsCompleted { get; init; }
    public LlmUsage? Usage { get; init; }
}
public static class LlmErrorCodes
{
    public const string ModelNotFound = "LlmModelNotFound";
    public const string ProviderUnsupported = "LlmProviderUnsupported";
    public const string CredentialMissing = "LlmCredentialMissing";
    public const string EndpointUnavailable = "LlmEndpointUnavailable";
    public const string Unauthorized = "LlmUnauthorized";
    public const string RateLimited = "LlmRateLimited";
    public const string Timeout = "LlmTimeout";
    public const string StreamParseFailed = "LlmStreamParseFailed";
    public const string RequestInvalid = "LlmRequestInvalid";
    public const string AiChatCredentialMissing = "AiChatCredentialMissing";
    public const string AiChatLoginFailed = "AiChatLoginFailed";
    public const string AiChatProjectLoadFailed = "AiChatProjectLoadFailed";
    public const string AiChatQuotaExceeded = "AiChatQuotaExceeded";
    public const string AiChatMemoryPermissionDenied = "AiChatMemoryPermissionDenied";
    public const string AiChatSseInterrupted = "AiChatSseInterrupted";
    public const string AiChatApiFailed = "AiChatApiFailed";
}
public static class LlmConnectionModes
{
    public const string ProviderDirect = "provider-direct";
    public const string AiChatApi = "aichat-api";
}
public sealed record LlmPluginRuntimeConfig
{
    public string Mode { get; init; } = LlmConnectionModes.ProviderDirect;
    public AiChatRuntimeConfig AiChat { get; init; } = new();
    public string? DefaultModel { get; init; }
    public List<LlmModelConfig> Models { get; init; } = [];
    public bool IsAiChatMode => string.Equals(Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase);
}
public sealed record AiChatRuntimeConfig
{
    public string BaseUrl { get; init; } = "http://192.168.1.111:13000";
    public AiChatAccountConfig Account { get; init; } = new();
    public string? DefaultProjectId { get; init; }
    public AiChatMemoryConfig Memory { get; init; } = new();
}
public sealed record AiChatAccountConfig
{
    public string? Email { get; init; }
    public string? Password { get; init; }
    public string? PasswordEnv { get; init; } = "MOLI_AICHAT_PASSWORD";
}
public sealed record AiChatMemoryConfig
{
    public bool EnabledInProviderDirect { get; init; } = true;
    public string DefaultScope { get; init; } = "PROJECT";
    public int RecallLimit { get; init; } = 8;
}
public sealed record AiChatProjectSummary
{
    public required string Id { get; init; }
    public required string Name { get; init; }
    public string ProjectType { get; init; } = "CHAT";
    public string MemoryMode { get; init; } = "ISOLATED";
}
public sealed record AiChatMemoryCapabilities
{
    public bool CanUseMemory { get; init; }
    public bool CanViewMemory { get; init; }
    public bool CanManageMemory { get; init; }
}
public sealed record AiChatGetMemoriesRequest
{
    public string? Scope { get; init; }
    public string? ProjectId { get; init; }
}
public sealed record AiChatCreateMemoryRequest
{
    public required string Scope { get; init; }
    public string? ProjectId { get; init; }
    public required string Content { get; init; }
}
public sealed record AiChatRecallMemoriesRequest
{
    public required string Query { get; init; }
    public string? Scope { get; init; }
    public string? ProjectId { get; init; }
    public string? ConversationId { get; init; }
    public int? Limit { get; init; }
}
public sealed record AiChatJsonResult
{
    public object? Data { get; init; }
}
public sealed class AiChatClientException : Exception
{
    public AiChatClientException(string code, string message, Exception? innerException = null)
        : base(message, innerException)
    {
        Code = code;
    }
    public string Code { get; }
}
src/Moli.Desktop/Llm/LlmProviderAdapterFactory.cs
New file
@@ -0,0 +1,31 @@
namespace Moli.Desktop.Llm;
public sealed class LlmProviderAdapterFactory : ILlmProviderAdapterFactory
{
    private static readonly IReadOnlyDictionary<string, string> ProviderAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        ["deepseek"] = "openai-compatible",
        ["ollama"] = "openai-compatible",
        ["local-openai-compatible"] = "openai-compatible"
    };
    private readonly IReadOnlyDictionary<string, ILlmProviderAdapter> _adapters;
    public LlmProviderAdapterFactory(IEnumerable<ILlmProviderAdapter> adapters)
    {
        _adapters = adapters.ToDictionary(adapter => adapter.Provider, StringComparer.OrdinalIgnoreCase);
    }
    public ILlmProviderAdapter? Get(string provider)
    {
        if (_adapters.TryGetValue(provider, out var adapter))
        {
            return adapter;
        }
        return ProviderAliases.TryGetValue(provider, out var targetProvider) &&
            _adapters.TryGetValue(targetProvider, out adapter)
                ? adapter
                : null;
    }
}
src/Moli.Desktop/Llm/OpenAICompatibleAdapter.cs
New file
@@ -0,0 +1,139 @@
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.IO;
namespace Moli.Desktop.Llm;
public sealed class OpenAICompatibleAdapter : ILlmProviderAdapter
{
    private readonly HttpClient _httpClient;
    private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
    public OpenAICompatibleAdapter(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
    public string Provider => "openai-compatible";
    public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
        LlmProviderRequest request,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        using var httpRequest = new HttpRequestMessage(HttpMethod.Post, request.Model.Endpoint);
        if (!string.IsNullOrWhiteSpace(request.ApiKey))
        {
            httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", request.ApiKey);
        }
        var payload = new
        {
            model = request.Model.ApiModel,
            messages = request.Messages.Select(message => new { role = message.Role, content = message.Content }).ToArray(),
            temperature = request.Options.Temperature ?? request.Model.RequestDefaults.Temperature,
            max_tokens = request.Options.MaxTokens ?? request.Model.RequestDefaults.MaxTokens,
            stream = request.Model.SupportsStreaming
        };
        httpRequest.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json");
        using var response = await _httpClient.SendAsync(
            httpRequest,
            HttpCompletionOption.ResponseHeadersRead,
            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 reader = new StreamReader(stream, Encoding.UTF8);
        while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (string.IsNullOrWhiteSpace(line) || !line.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                continue;
            }
            var data = line["data:".Length..].Trim();
            if (data == "[DONE]")
            {
                yield return new LlmProviderChunk { IsCompleted = true };
                yield break;
            }
            LlmProviderChunk? chunk;
            try
            {
                chunk = ParseChunk(data);
            }
            catch (JsonException ex)
            {
                throw new LlmProviderException(LlmErrorCodes.StreamParseFailed, "Failed to parse LLM stream chunk.", ex);
            }
            if (chunk is not null)
            {
                yield return chunk;
            }
        }
        yield return new LlmProviderChunk { IsCompleted = true };
    }
    private LlmProviderChunk? ParseChunk(string data)
    {
        using var document = JsonDocument.Parse(data);
        var root = document.RootElement;
        if (!root.TryGetProperty("choices", out var choices) || choices.ValueKind != JsonValueKind.Array || choices.GetArrayLength() == 0)
        {
            return null;
        }
        var first = choices[0];
        if (first.TryGetProperty("delta", out var delta) &&
            delta.TryGetProperty("content", out var content) &&
            content.ValueKind == JsonValueKind.String)
        {
            return new LlmProviderChunk { Delta = content.GetString() ?? string.Empty };
        }
        if (first.TryGetProperty("message", out var message) &&
            message.TryGetProperty("content", out content) &&
            content.ValueKind == JsonValueKind.String)
        {
            return new LlmProviderChunk { Delta = content.GetString() ?? string.Empty, IsCompleted = true };
        }
        if (first.TryGetProperty("finish_reason", out var finishReason) && finishReason.ValueKind != JsonValueKind.Null)
        {
            return new LlmProviderChunk { IsCompleted = true };
        }
        return null;
    }
    private static string MapStatusCode(HttpStatusCode statusCode) => statusCode switch
    {
        HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => LlmErrorCodes.Unauthorized,
        (HttpStatusCode)429 => LlmErrorCodes.RateLimited,
        _ => LlmErrorCodes.EndpointUnavailable
    };
}
public sealed class LlmProviderException : Exception
{
    public LlmProviderException(string code, string message, Exception? innerException = null)
        : base(message, innerException)
    {
        Code = code;
    }
    public string Code { get; }
}
src/Moli.Desktop/Management/ManagementWindow.xaml
@@ -92,6 +92,22 @@
                    <DataGrid x:Name="DiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" />
                </DockPanel>
            </TabItem>
            <TabItem Header="Log">
                <DockPanel Margin="8">
                    <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8">
                        <TextBlock x:Name="LogPathText" VerticalAlignment="Center" Margin="0,0,12,0" />
                        <Button Content="打开日志目录" Width="112" Click="OpenLogDirectory_Click" />
                    </WrapPanel>
                    <TextBox x:Name="LogTextBox"
                             FontFamily="Consolas"
                             FontSize="12"
                             IsReadOnly="True"
                             TextWrapping="NoWrap"
                             AcceptsReturn="True"
                             VerticalScrollBarVisibility="Auto"
                             HorizontalScrollBarVisibility="Auto" />
                </DockPanel>
            </TabItem>
        </TabControl>
    </DockPanel>
</Window>
src/Moli.Desktop/Management/ManagementWindow.xaml.cs
@@ -30,6 +30,8 @@
    private readonly DesktopPaths _paths;
    private readonly DispatcherTimer _timer;
    private AppRuntimeState? _state;
    private string? _selectedWidgetForDisplayLayer;
    private bool _isRefreshing;
    public ManagementWindow(
        IDesktopRuntime runtime,
@@ -43,6 +45,7 @@
        _paths = paths;
        InitializeComponent();
        DisplayLayerSelector.ItemsSource = Enum.GetValues<DisplayLayer>();
        WidgetSelector.SelectionChanged += WidgetSelector_SelectionChanged;
        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
        _timer.Tick += async (_, _) => await RefreshAsync();
        Loaded += async (_, _) =>
@@ -55,33 +58,42 @@
    private async Task RefreshAsync()
    {
        _state = await _runtime.GetStateAsync();
        var api = _apiStatus.GetStatus();
        var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray();
        var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null
            ? "未检测到初始化记录"
            : "已初始化";
        _isRefreshing = true;
        try
        {
            _state = await _runtime.GetStateAsync();
            var api = _apiStatus.GetStatus();
            var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray();
            var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null
                ? "未检测到初始化记录"
                : "已初始化";
        StatusSummaryText.Text = $"插件 {_state.Plugins.Count} 个,组件 {_state.Widgets.Count} 个,诊断 {diagnostics.Length} 条";
        RuntimeText.Text = $"运行时:编辑={_state.IsEditMode},安全输入={_state.IsSafeInputMode},全局锁定={_state.IsGlobalLocked}";
        ApiText.Text = api.IsListening ? $"API:127.0.0.1:{api.Port}" : $"API:未监听 {api.ErrorCode ?? ""}";
        WallpaperText.Text = $"壁纸:启用={_state.Wallpaper.IsEnabled},插件={_state.Wallpaper.PluginId?.Value ?? "无"}";
        WebViewText.Text = $"WebView2:{webViewStatus}";
        WallpaperDetailText.Text = $"启用:{_state.Wallpaper.IsEnabled}\n暂停:{_state.Wallpaper.IsPaused}\n静音:{_state.Wallpaper.IsMuted}\n透明度:{_state.Wallpaper.Opacity}\n点击穿透:{_state.Wallpaper.ClickThrough}";
        EditModeButton.Content = _state.IsEditMode ? "退出编辑" : "进入编辑";
        SafeInputButton.Content = _state.IsSafeInputMode ? "退出安全" : "安全输入";
        GlobalLockButton.Content = _state.IsGlobalLocked ? "解锁全部" : "锁定全部";
            StatusSummaryText.Text = $"插件 {_state.Plugins.Count} 个,组件 {_state.Widgets.Count} 个,诊断 {diagnostics.Length} 条";
            RuntimeText.Text = $"运行时:编辑={_state.IsEditMode},安全输入={_state.IsSafeInputMode},全局锁定={_state.IsGlobalLocked}";
            ApiText.Text = api.IsListening ? $"API:127.0.0.1:{api.Port}" : $"API:未监听 {api.ErrorCode ?? ""}";
            WallpaperText.Text = $"壁纸:启用={_state.Wallpaper.IsEnabled},插件={_state.Wallpaper.PluginId?.Value ?? "无"}";
            WebViewText.Text = $"WebView2:{webViewStatus}";
            WallpaperDetailText.Text = $"启用:{_state.Wallpaper.IsEnabled}\n暂停:{_state.Wallpaper.IsPaused}\n静音:{_state.Wallpaper.IsMuted}\n透明度:{_state.Wallpaper.Opacity}\n点击穿透:{_state.Wallpaper.ClickThrough}";
            EditModeButton.Content = _state.IsEditMode ? "退出编辑" : "进入编辑";
            SafeInputButton.Content = _state.IsSafeInputMode ? "退出安全" : "安全输入";
            GlobalLockButton.Content = _state.IsGlobalLocked ? "解锁全部" : "锁定全部";
        var widgets = _state.Widgets.Select(WidgetRow.From).ToArray();
        var selected = (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId;
        WidgetSelector.ItemsSource = widgets;
        WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
        WidgetsGrid.ItemsSource = widgets;
        DisplayLayerSelector.SelectedItem = (WidgetSelector.SelectedItem as WidgetRow)?.DisplayLayer ?? DisplayLayer.Desktop;
        PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
        DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
        RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray();
        ManifestErrorsText.Text = BuildManifestErrorText(_state);
            var widgets = _state.Widgets.Select(WidgetRow.From).ToArray();
            var selected = (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId;
            WidgetSelector.ItemsSource = widgets;
            WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
            WidgetsGrid.ItemsSource = widgets;
            SyncDisplayLayerSelector(force: _selectedWidgetForDisplayLayer != (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId);
            PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
            DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
            RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray();
            ManifestErrorsText.Text = BuildManifestErrorText(_state);
            LoadTodayLog();
        }
        finally
        {
            _isRefreshing = false;
        }
    }
    private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync();
@@ -199,6 +211,12 @@
    private void OpenPluginsJson_Click(object sender, RoutedEventArgs e)
        => OpenJson(Path.Combine(_paths.ConfigDirectory, "plugins.json"));
    private void OpenLogDirectory_Click(object sender, RoutedEventArgs e)
    {
        Directory.CreateDirectory(_paths.LogDirectory);
        Process.Start(new ProcessStartInfo("explorer.exe", $"\"{_paths.LogDirectory}\"") { UseShellExecute = true });
    }
    private void OpenPluginJson_Click(object sender, RoutedEventArgs e)
    {
        if ((PluginsGrid.SelectedItem as PluginRow) is not { } plugin)
@@ -228,6 +246,65 @@
    private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow;
    private void WidgetSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (!_isRefreshing)
        {
            SyncDisplayLayerSelector(force: true);
        }
    }
    private void SyncDisplayLayerSelector(bool force)
    {
        if (SelectedWidget() is not { } widget)
        {
            DisplayLayerSelector.SelectedItem = DisplayLayer.Desktop;
            _selectedWidgetForDisplayLayer = null;
            return;
        }
        if (!force)
        {
            return;
        }
        DisplayLayerSelector.SelectedItem = widget.DisplayLayer;
        _selectedWidgetForDisplayLayer = widget.InstanceId;
    }
    private void LoadTodayLog()
    {
        var logPath = Path.Combine(_paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log");
        LogPathText.Text = logPath;
        if (!File.Exists(logPath))
        {
            LogTextBox.Text = "当天暂无日志。";
            return;
        }
        try
        {
            var text = File.ReadAllText(logPath, Encoding.UTF8);
            if (LogTextBox.Text == text)
            {
                return;
            }
            var wasNearBottom = LogTextBox.VerticalOffset >= LogTextBox.ExtentHeight - LogTextBox.ViewportHeight - 24;
            LogTextBox.Text = text;
            if (wasNearBottom)
            {
                LogTextBox.ScrollToEnd();
            }
        }
        catch (IOException)
        {
        }
        catch (UnauthorizedAccessException)
        {
        }
    }
    private async Task InstallWallpaperFilePluginAsync(string fileName)
    {
        Directory.CreateDirectory(_paths.PluginDirectory);
src/Moli.Desktop/Runtime/RuntimeState.cs
@@ -1,6 +1,8 @@
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Moli.Desktop.Runtime;
@@ -42,6 +44,12 @@
{
    private readonly object _gate = new();
    private readonly List<Func<RuntimeEvent, Task>> _handlers = [];
    private readonly ILogger<RuntimeEventBus> _logger;
    public RuntimeEventBus(ILogger<RuntimeEventBus>? logger = null)
    {
        _logger = logger ?? NullLogger<RuntimeEventBus>.Instance;
    }
    public IDisposable Subscribe(Func<RuntimeEvent, Task> handler)
    {
@@ -61,6 +69,7 @@
    public async Task PublishAsync(RuntimeEvent runtimeEvent, CancellationToken cancellationToken = default)
    {
        _logger.LogDebug("Runtime event published: {EventName}", runtimeEvent.Name);
        Func<RuntimeEvent, Task>[] handlers;
        lock (_gate)
        {
src/Moli.Desktop/WebView/PluginBridgeDispatcher.cs
@@ -1,5 +1,6 @@
using System.Text.Json;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Llm;
using Moli.Desktop.Runtime;
namespace Moli.Desktop.WebView;
@@ -18,17 +19,29 @@
        "requestReload",
        "requestShow",
        "requestHide",
        "requestResize"
        "requestResize",
        "llm.getConnectionMode",
        "llm.getModels",
        "llm.getProjects",
        "llm.getMemoryCapabilities",
        "llm.getMemories",
        "llm.createMemory",
        "llm.deleteMemory",
        "llm.recallMemories",
        "llm.streamChat",
        "llm.cancel"
    ];
    private readonly IDiagnosticsService _diagnostics;
    private readonly IRuntimeEventBus _events;
    private readonly ILlmGatewayService _llmGateway;
    private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web);
    public PluginBridgeDispatcher(IDiagnosticsService diagnostics, IRuntimeEventBus events)
    public PluginBridgeDispatcher(IDiagnosticsService diagnostics, IRuntimeEventBus events, ILlmGatewayService llmGateway)
    {
        _diagnostics = diagnostics;
        _events = events;
        _llmGateway = llmGateway;
    }
    public async Task<PluginBridgeResponse> DispatchAsync(
@@ -72,8 +85,236 @@
            "requestShow" => await HandleEventAsync(request, context, "plugin.showRequested", cancellationToken).ConfigureAwait(false),
            "requestHide" => await HandleEventAsync(request, context, "plugin.hideRequested", cancellationToken).ConfigureAwait(false),
            "requestResize" => await HandleEventAsync(request, context, "plugin.resizeRequested", cancellationToken).ConfigureAwait(false),
            "llm.getConnectionMode" => PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { mode = ReadRuntimeConfig(context).Mode }),
            "llm.getModels" => await HandleGetLlmModelsAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.getProjects" => await HandleGetAiChatProjectsAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.getMemoryCapabilities" => await HandleGetMemoryCapabilitiesAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.getMemories" => await HandleGetMemoriesAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.createMemory" => await HandleCreateMemoryAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.deleteMemory" => await HandleDeleteMemoryAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.recallMemories" => await HandleRecallMemoriesAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.streamChat" => await HandleStreamLlmChatAsync(request, context, cancellationToken).ConfigureAwait(false),
            "llm.cancel" => await HandleCancelLlmChatAsync(request, cancellationToken).ConfigureAwait(false),
            _ => PluginBridgeResponse.Failure(request.Id, "BridgeMethodNotAllowed", $"Bridge method {request.Method} is not allowed.")
        };
    }
    private async Task<PluginBridgeResponse> HandleGetLlmModelsAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        var models = await _llmGateway.GetModelsAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false);
        return PluginBridgeResponse.Ok(request.Id ?? string.Empty, models);
    }
    private async Task<PluginBridgeResponse> HandleGetAiChatProjectsAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        try
        {
            var projects = await _llmGateway.GetProjectsAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, projects);
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private async Task<PluginBridgeResponse> HandleGetMemoryCapabilitiesAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        try
        {
            var capabilities = await _llmGateway.GetMemoryCapabilitiesAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, capabilities);
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private async Task<PluginBridgeResponse> HandleGetMemoriesAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        var payload = DeserializePayload<AiChatGetMemoriesRequest>(request, out var error);
        if (error is not null)
        {
            return error;
        }
        try
        {
            var result = await _llmGateway.GetMemoriesAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data);
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private async Task<PluginBridgeResponse> HandleCreateMemoryAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        var payload = DeserializePayload<AiChatCreateMemoryRequest>(request, out var error);
        if (error is not null)
        {
            return error;
        }
        try
        {
            var result = await _llmGateway.CreateMemoryAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data);
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private async Task<PluginBridgeResponse> HandleDeleteMemoryAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        if (request.Params.ValueKind is not JsonValueKind.Object ||
            !request.Params.TryGetProperty("memoryId", out var memoryIdElement) ||
            memoryIdElement.ValueKind != JsonValueKind.String ||
            string.IsNullOrWhiteSpace(memoryIdElement.GetString()))
        {
            return PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "memoryId is required.");
        }
        try
        {
            await _llmGateway.DeleteMemoryAsync(ReadRuntimeConfig(context), memoryIdElement.GetString()!, cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { accepted = true });
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private async Task<PluginBridgeResponse> HandleRecallMemoriesAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        var payload = DeserializePayload<AiChatRecallMemoriesRequest>(request, out var error);
        if (error is not null)
        {
            return error;
        }
        try
        {
            var result = await _llmGateway.RecallMemoriesAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false);
            return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data);
        }
        catch (AiChatClientException ex)
        {
            return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message);
        }
    }
    private Task<PluginBridgeResponse> HandleStreamLlmChatAsync(
        BridgeRequest request,
        PluginBridgeContext context,
        CancellationToken cancellationToken)
    {
        if (!HasPermission(context, "llm.stream"))
        {
            return Task.FromResult(PluginBridgeResponse.Failure(request.Id, "BridgePermissionDenied", "Plugin does not declare llm.stream permission."));
        }
        if (request.Params.ValueKind is not JsonValueKind.Object)
        {
            return Task.FromResult(PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "llm.streamChat expects an object payload."));
        }
        LlmBridgeStreamRequest? payload;
        try
        {
            payload = request.Params.Deserialize<LlmBridgeStreamRequest>(_jsonOptions);
        }
        catch (JsonException)
        {
            return Task.FromResult(PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "llm.streamChat payload could not be parsed."));
        }
        if (payload is null || string.IsNullOrWhiteSpace(payload.ModelId))
        {
            return Task.FromResult(PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "modelId is required."));
        }
        var requestId = string.IsNullOrWhiteSpace(payload.RequestId) ? $"llm-{Guid.NewGuid():N}" : payload.RequestId!;
        var chatRequest = new LlmChatRequest
        {
            RequestId = requestId,
            PluginId = context.RuntimeInfo.PluginId,
            InstanceId = context.HostId,
            Mode = string.IsNullOrWhiteSpace(payload.Mode) ? ReadRuntimeConfig(context).Mode : payload.Mode!,
            ProjectId = payload.ProjectId,
            ModelId = payload.ModelId,
            Messages = payload.Messages,
            Options = payload.Options ?? new LlmRequestOptions(),
            RuntimeConfig = ReadRuntimeConfig(context)
        };
        _ = Task.Run(() => PumpLlmStreamAsync(chatRequest, context, CancellationToken.None));
        return Task.FromResult(PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { requestId }));
    }
    private async Task<PluginBridgeResponse> HandleCancelLlmChatAsync(BridgeRequest request, CancellationToken cancellationToken)
    {
        if (request.Params.ValueKind is not JsonValueKind.Object ||
            !request.Params.TryGetProperty("requestId", out var requestIdElement) ||
            requestIdElement.ValueKind != JsonValueKind.String ||
            string.IsNullOrWhiteSpace(requestIdElement.GetString()))
        {
            return PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "requestId is required.");
        }
        await _llmGateway.CancelAsync(requestIdElement.GetString()!, cancellationToken).ConfigureAwait(false);
        return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { accepted = true });
    }
    private async Task PumpLlmStreamAsync(LlmChatRequest chatRequest, PluginBridgeContext context, CancellationToken cancellationToken)
    {
        await foreach (var streamEvent in _llmGateway.StreamChatAsync(chatRequest, cancellationToken).ConfigureAwait(false))
        {
            var eventName = streamEvent switch
            {
                LlmDeltaEvent => "llm.delta",
                LlmCompletedEvent => "llm.completed",
                LlmErrorEvent => "llm.error",
                _ => "llm.event"
            };
            await _events.PublishAsync(new RuntimeEvent
            {
                Name = eventName,
                Payload = new
                {
                    context.HostId,
                    context.RuntimeInfo.PluginId,
                    Event = streamEvent
                }
            }, cancellationToken).ConfigureAwait(false);
        }
    }
    private async Task<PluginBridgeResponse> HandleEventAsync(
@@ -110,12 +351,73 @@
        return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { accepted = true });
    }
    private static bool HasPermission(PluginBridgeContext context, string permission)
        => context.Manifest.Permissions.Any(item => string.Equals(item, permission, StringComparison.OrdinalIgnoreCase));
    private T? DeserializePayload<T>(BridgeRequest request, out PluginBridgeResponse? error)
    {
        error = null;
        if (request.Params.ValueKind is not JsonValueKind.Object)
        {
            error = PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", $"{request.Method} expects an object payload.");
            return default;
        }
        try
        {
            return request.Params.Deserialize<T>(_jsonOptions);
        }
        catch (JsonException)
        {
            error = PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", $"{request.Method} payload could not be parsed.");
            return default;
        }
    }
    private LlmPluginRuntimeConfig ReadRuntimeConfig(PluginBridgeContext context)
    {
        if (context.Config.ValueKind is not JsonValueKind.Object)
        {
            return new LlmPluginRuntimeConfig();
        }
        try
        {
            var config = context.Config.Deserialize<LlmPluginRuntimeConfig>(_jsonOptions) ?? new LlmPluginRuntimeConfig();
            if (string.IsNullOrWhiteSpace(config.Mode))
            {
                config = config with { Mode = LlmConnectionModes.ProviderDirect };
            }
            if (config.AiChat is null)
            {
                config = config with { AiChat = new AiChatRuntimeConfig() };
            }
            return config;
        }
        catch (JsonException)
        {
            return new LlmPluginRuntimeConfig();
        }
    }
    private sealed record BridgeRequest
    {
        public string? Id { get; init; }
        public string? Method { get; init; }
        public JsonElement Params { get; init; }
    }
    private sealed record LlmBridgeStreamRequest
    {
        public string? RequestId { get; init; }
        public string? Mode { get; init; }
        public string? ProjectId { get; init; }
        public required string ModelId { get; init; }
        public IReadOnlyList<LlmMessage> Messages { get; init; } = [];
        public LlmRequestOptions? Options { get; init; }
    }
}
public sealed record PluginBridgeResponse
src/Moli.Desktop/WebView/PluginBridgeScript.cs
@@ -23,6 +23,11 @@
            pending.set(id, { resolve, reject });
            chrome.webview.postMessage({ id, method, params });
          });
          const on = (name, handler) => {
            const wrapped = (event) => handler(event.detail || {});
            window.addEventListener(name, wrapped);
            return () => window.removeEventListener(name, wrapped);
          };
          window.moliDesktop = Object.freeze({
            getManifest: () => call("getManifest"),
            getRuntimeInfo: () => call("getRuntimeInfo"),
@@ -32,7 +37,22 @@
            requestReload: () => call("requestReload"),
            requestShow: () => call("requestShow"),
            requestHide: () => call("requestHide"),
            requestResize: (size) => call("requestResize", size)
            requestResize: (size) => call("requestResize", size),
            llm: Object.freeze({
              getConnectionMode: () => call("llm.getConnectionMode"),
              getModels: () => call("llm.getModels"),
              getProjects: () => call("llm.getProjects"),
              getMemoryCapabilities: () => call("llm.getMemoryCapabilities"),
              getMemories: (options) => call("llm.getMemories", options || {}),
              createMemory: (input) => call("llm.createMemory", input),
              deleteMemory: (memoryId) => call("llm.deleteMemory", { memoryId }),
              recallMemories: (input) => call("llm.recallMemories", input),
              streamChat: (request) => call("llm.streamChat", request),
              cancel: (requestId) => call("llm.cancel", { requestId }),
              onDelta: (handler) => on("moli:llm-delta", handler),
              onCompleted: (handler) => on("moli:llm-completed", handler),
              onError: (handler) => on("moli:llm-error", handler)
            })
          });
        })();
        """;
src/Moli.Desktop/WebView/WebViewHost.cs
@@ -25,6 +25,7 @@
    private PluginBridgeContext? _bridgeContext;
    private WebViewHostOptions? _options;
    private IDisposable? _audioSubscription;
    private IDisposable? _llmSubscription;
    private bool _initialized;
    public WebViewHost(
@@ -67,6 +68,8 @@
        {
            _audioSubscription = _events.Subscribe(DispatchAudioSpectrumAsync);
        }
        _llmSubscription = _events.Subscribe(DispatchLlmEventAsync);
        if (!string.IsNullOrWhiteSpace(options.InitialScript))
        {
@@ -127,6 +130,8 @@
    {
        _audioSubscription?.Dispose();
        _audioSubscription = null;
        _llmSubscription?.Dispose();
        _llmSubscription = null;
        if (Control.CoreWebView2 is not null)
        {
@@ -157,6 +162,41 @@
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
    private Task DispatchLlmEventAsync(RuntimeEvent runtimeEvent)
    {
        if (_bridgeContext is null || runtimeEvent.Payload is null || !runtimeEvent.Name.StartsWith("llm.", StringComparison.OrdinalIgnoreCase))
        {
            return Task.CompletedTask;
        }
        var payloadJson = JsonSerializer.Serialize(runtimeEvent.Payload, _jsonOptions);
        using var document = JsonDocument.Parse(payloadJson);
        var root = document.RootElement;
        if (!root.TryGetProperty("hostId", out var hostId) ||
            !string.Equals(hostId.GetString(), HostId, StringComparison.OrdinalIgnoreCase) ||
            !root.TryGetProperty("event", out var llmEvent))
        {
            return Task.CompletedTask;
        }
        var domEventName = runtimeEvent.Name switch
        {
            "llm.delta" => "moli:llm-delta",
            "llm.completed" => "moli:llm-completed",
            "llm.error" => "moli:llm-error",
            _ => "moli:llm-event"
        };
        var detail = llmEvent.GetRawText();
        var script = $"window.dispatchEvent(new CustomEvent(\"{domEventName}\", {{ detail: {detail} }}));";
        var dispatcher = Control.Dispatcher;
        if (dispatcher.CheckAccess())
        {
            return ExecuteScriptSafelyAsync(script);
        }
        return dispatcher.InvokeAsync(() => ExecuteScriptSafelyAsync(script)).Task.Unwrap();
    }
    private async void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        if (_bridgeContext is null)
src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -1,4 +1,5 @@
using System.Windows;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
@@ -21,11 +22,13 @@
    private readonly DesktopPaths _paths;
    private readonly IDiagnosticsService _diagnostics;
    private readonly IServiceProvider _services;
    private readonly IRuntimeEventBus _events;
    private readonly Dictionary<WidgetInstanceId, WidgetWindow> _widgets = [];
    private WallpaperWindow? _wallpaper;
    private WallpaperRuntimeState _wallpaperState = new();
    private bool _editMode;
    private bool _safeInputMode;
    private IDisposable? _eventSubscription;
    public RuntimeSurfaceController(
        IPluginManager plugins,
@@ -33,7 +36,8 @@
        IWebViewHostFactory webViews,
        DesktopPaths paths,
        IDiagnosticsService diagnostics,
        IServiceProvider services)
        IServiceProvider services,
        IRuntimeEventBus events)
    {
        _plugins = plugins;
        _interop = interop;
@@ -41,6 +45,8 @@
        _paths = paths;
        _diagnostics = diagnostics;
        _services = services;
        _events = events;
        _eventSubscription = _events.Subscribe(HandleRuntimeEventAsync);
    }
    public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
@@ -127,6 +133,7 @@
            _wallpaper.Show();
            await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
            _wallpaper.ApplyState(wallpaper, _safeInputMode);
            ReapplyDesktopWidgetLayers();
        });
    public Task DisableWallpaperAsync(CancellationToken cancellationToken = default)
@@ -149,6 +156,8 @@
            _widgets.Clear();
            _wallpaper?.Close();
            _wallpaper = null;
            _eventSubscription?.Dispose();
            _eventSubscription = null;
            return Task.CompletedTask;
        });
@@ -161,6 +170,72 @@
        await runtime.UpdateWidgetLayoutAsync(instanceId, patch, cancellationToken).ConfigureAwait(true);
    }
    private void ReapplyDesktopWidgetLayers()
    {
        foreach (var widget in _widgets.Values.Where(widget => widget.CurrentLayout.DisplayLayer == DisplayLayer.Desktop))
        {
            widget.ApplyLayout(widget.CurrentLayout, _editMode, _safeInputMode);
        }
    }
    private Task HandleRuntimeEventAsync(RuntimeEvent runtimeEvent)
    {
        if (!string.Equals(runtimeEvent.Name, "plugin.resizeRequested", StringComparison.OrdinalIgnoreCase) ||
            runtimeEvent.Payload is null)
        {
            return Task.CompletedTask;
        }
        return OnUiThreadAsync(() =>
        {
            try
            {
                var json = JsonSerializer.Serialize(runtimeEvent.Payload, new JsonSerializerOptions(JsonSerializerDefaults.Web));
                using var document = JsonDocument.Parse(json);
                var root = document.RootElement;
                if (!root.TryGetProperty("hostId", out var hostIdElement))
                {
                    return Task.CompletedTask;
                }
                var hostId = hostIdElement.GetString();
                var widget = _widgets.Values.FirstOrDefault(item => string.Equals(item.HostId, hostId, StringComparison.OrdinalIgnoreCase));
                if (widget is null ||
                    !root.TryGetProperty("params", out var parameters) ||
                    parameters.ValueKind != JsonValueKind.Object)
                {
                    return Task.CompletedTask;
                }
                var width = TryReadPositiveDouble(parameters, "width");
                var height = TryReadPositiveDouble(parameters, "height");
                widget.ApplyRequestedSize(width, height);
            }
            catch (JsonException ex)
            {
                _diagnostics.Record(
                    DiagnosticSeverity.Warning,
                    "PluginResizeRequestInvalid",
                    "Plugin resize request payload could not be parsed.",
                    new Dictionary<string, string> { ["exception"] = ex.GetType().Name });
            }
            return Task.CompletedTask;
        });
    }
    private static double? TryReadPositiveDouble(JsonElement parameters, string propertyName)
    {
        if (!parameters.TryGetProperty(propertyName, out var value))
        {
            return null;
        }
        return value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && number > 0
            ? number
            : null;
    }
    private static async Task OnUiThreadAsync(Func<Task> action)
    {
        var dispatcher = Application.Current?.Dispatcher;
src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -33,6 +33,7 @@
    private readonly Border _editBorder;
    private readonly Border _resizeGrip;
    private WidgetLayout _layout;
    private double? _requestedHeight;
    private bool _editMode;
    private bool _safeInputMode;
    private Point? _dragStart;
@@ -98,6 +99,10 @@
    public WidgetInstanceId InstanceId => _layout.InstanceId;
    public WidgetLayout CurrentLayout => _layout;
    public string HostId => _webView.HostId;
    public async Task LoadAsync(CancellationToken cancellationToken = default)
    {
        ApplyLayout(_layout, _editMode, _safeInputMode);
@@ -123,7 +128,7 @@
        Left = layout.Bounds.X;
        Top = layout.Bounds.Y;
        Width = layout.Bounds.Width;
        Height = layout.Bounds.Height;
        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;
        Topmost = layout.DisplayLayer == DisplayLayer.GlobalTop;
@@ -132,6 +137,20 @@
        ApplyWin32Styles();
    }
    public void ApplyRequestedSize(double? width, double? height)
    {
        if (width is > 0)
        {
            Width = Math.Max(LayoutManager.MinWidth, width.Value);
        }
        _requestedHeight = height is > 0 && height.Value > _layout.Bounds.Height
            ? height.Value
            : null;
        Height = Math.Max(_layout.Bounds.Height, _requestedHeight ?? _layout.Bounds.Height);
        ApplyWin32Styles();
    }
    public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
    {
        ApplyLayout(_layout, enabled, _safeInputMode);