20个文件已添加
12个文件已修改
1 文件已重命名
| | |
| | | - 模块或插件实现 |
| | | - 配置文件、接口定义和必要脚本 |
| | | - 本地运行说明 |
| | | - 功能或插件开发/调整后的用户操作手册更新,优先维护 `docs/product/user-manual.md` 与 `docs/product/user-manual/` |
| | | - 变更说明 |
| | | - 已执行的验证命令和结果 |
| | | |
| | |
| | | - 当发现现有架构无法支撑需求或需要调整模块边界时,调用 `architect-agent`。 |
| | | - 当涉及持久化结构、配置 schema 或数据迁移时,调用 `dba-agent`。 |
| | | - 当需要测试用例、验收验证或缺陷复现时,调用 `qa-agent`。 |
| | | - 当功能或插件变更影响安装、启动、配置、交互、故障排查或用户可见限制时,在提交给 QA 前补充或更新操作手册;如无用户可见变化,在实现说明中注明无需更新手册的原因。 |
| | | - 当需要生成或修改代码时,使用 `codegen-skill`。 |
| | | - 当开发插件、插件协议或插件配置能力时,使用 `plugin-skill`。 |
| | | - 当定位运行错误、构建失败、WebView2 异常或窗口行为问题时,使用 `debug-skill`。 |
| | | |
| | |
| | | - 功能优先级 |
| | | - 非功能需求 |
| | | - 验收标准 |
| | | - 用户操作手册影响范围,说明新增或调整的用户流程、配置项、限制和故障排查信息 |
| | | - 待澄清问题清单 |
| | | |
| | | ## decision |
| | |
| | | - 当需求需要拆解为开发任务、代码生成或接口定义时,调用 `dev-agent`。 |
| | | - 当需求涉及配置持久化、插件数据结构、迁移或存储策略时,调用 `dba-agent`。 |
| | | - 当需求需要验收标准、测试矩阵或回归策略时,调用 `qa-agent`。 |
| | | - 当需求会改变用户可见的功能、插件操作、配置或限制时,要求后续开发完成后同步更新操作手册。 |
| | | - 当需要整理 PRD 时,使用 `prd-skill`。 |
| | | - 当需求与插件能力、插件规范或桌面挂件体验相关时,使用 `plugin-skill`。 |
| | | |
| | |
| | | - Product Agent 输出的验收标准 |
| | | - Architect Agent 输出的架构和风险点 |
| | | - Dev Agent 输出的实现说明、运行方式和变更清单 |
| | | - 功能或插件变更对应的用户操作手册更新,或无需更新手册的说明 |
| | | - 缺陷报告、日志、截图、录屏或用户反馈 |
| | | |
| | | ## output |
| | |
| | | - 验收结果 |
| | | - 缺陷报告 |
| | | - 回归测试清单 |
| | | - 用户操作手册一致性检查结果 |
| | | - 发布风险评估 |
| | | |
| | | ## decision |
| | |
| | | - 当验收标准不明确或测试期望与需求冲突时,调用 `product-agent`。 |
| | | - 当问题可能源于架构设计、模块边界或技术方案时,调用 `architect-agent`。 |
| | | - 当需要修复缺陷、补充日志或增加可测试性代码时,调用 `dev-agent`。 |
| | | - 当功能或插件已变更但操作手册缺失、过期或与实际行为不一致时,退回 `dev-agent` 或 `product-agent` 补充手册。 |
| | | - 当问题涉及配置读写、迁移、历史数据兼容或默认值时,调用 `dba-agent`。 |
| | | - 当设计测试矩阵、测试脚本或验收命令时,使用 `test-skill`。 |
| | | - 当复现和定位缺陷时,使用 `debug-skill`。 |
| | | |
| | |
| | | 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 |
| | |
| | | - PRD |
| | | - user stories |
| | | - acceptance criteria |
| | | - user manual impact scope when the change affects user-visible flows |
| | | - open questions |
| | | - next: |
| | | - send PRD to `architect-agent` |
| | |
| | | - 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: |
| | |
| | | - 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` |
| | |
| | | - PRD |
| | | - architecture design |
| | | - implementation summary |
| | | - user operation manual changes |
| | | - test results |
| | | - known risks |
| | | - output: |
| | |
| | | - 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. |
| | | |
| | |
| | | |
| | | ## Development Output |
| | | |
| | | ## Manual Update Output |
| | | |
| | | ## QA Output |
| | | |
| | | ## Review Decision |
| | | |
| | | ## Follow Up Tasks |
| | | ``` |
| | | |
| | |
| | | ## 当前产品文档 |
| | | |
| | | - [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 集成移交记录](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) |
| | | |
| | | ## 当前运维文档 |
| | | |
| New file |
| | |
| | | # 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。 |
| | | |
| | | 核心架构决策: |
| | | |
| | | - 插件前端只负责输入、模型选择和流式渲染。 |
| | | - 插件前端只传 `modelId`、`messages` 和请求参数,不直接传 provider、endpoint 或 API key。 |
| | | - 宿主维护 LLM 模型注册表,每个模型可独立配置 `provider`、`endpoint`、`authRef` 和 `apiModel`。 |
| | | - 宿主按 `modelId` 选择 provider adapter,并把不同供应商的流式响应统一转换成插件可消费的事件。 |
| | | - API key 不进入插件前端资源、manifest 示例或普通日志。 |
| | | |
| | | ## Goals |
| | | |
| | | - 支持一个顶部居中的 LLM 输入小组件,默认作为 `widget` 插件运行。 |
| | | - 支持多供应商、多 endpoint、多模型共存。 |
| | | - 支持 OpenAI-compatible、DeepSeek、本地 OpenAI-compatible 服务,后续可扩展 Anthropic、Ollama 等适配器。 |
| | | - 支持流式输出,并将供应商差异屏蔽在宿主侧。 |
| | | - 保持插件系统边界:WebView 页面只访问白名单桥接 API。 |
| | | - 配置和密钥边界清晰,便于后续管理窗口和数据迁移继续扩展。 |
| | | |
| | | ## Non Goals |
| | | |
| | | - 不实现完整聊天会话系统。 |
| | | - 不实现云端同步、团队共享模型配置或计费系统。 |
| | | - 不在插件前端直接保存或管理 API key。 |
| | | - 不在 MVP 中实现文件上传、多模态输入或长期历史记录。 |
| | | - 不要求把 LLM 代理暴露成公网 API。 |
| | | |
| | | ## Module Design |
| | | |
| | | ### Module Overview |
| | | |
| | | ```mermaid |
| | | flowchart TB |
| | | Plugin["sample.llm-command-palette WebView"] |
| | | Bridge["PluginBridgeScript / WebViewHost"] |
| | | Runtime["DesktopRuntimeCoordinator"] |
| | | LlmService["LlmGatewayService"] |
| | | 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 --> 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 请求入口、模型路由、取消、超时、事件归一化 | 持久化布局或窗口状态 | |
| | | | `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` 通过工厂创建或取得。 |
| | | - 配置读写仍经 `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,但插件前端不需要知道。 |
| | | |
| | | ### 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(modelId, messages, options) |
| | | Bridge->>Runtime: StreamLlmChat(request) |
| | | Runtime->>Runtime: Validate plugin permission llm.stream |
| | | Runtime->>Llm: StreamChatAsync(request) |
| | | Llm->>Registry: Get model by modelId |
| | | 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 |
| | | ``` |
| | | |
| | | ### 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 |
| | | } |
| | | } |
| | | ] |
| | | } |
| | | ``` |
| | | |
| | | ### 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 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 = { |
| | | modelId: string; |
| | | messages: Array<{ role: "system" | "user" | "assistant"; content: string }>; |
| | | options?: { |
| | | temperature?: number; |
| | | maxTokens?: number; |
| | | timeoutMs?: number; |
| | | }; |
| | | }; |
| | | |
| | | window.moliDesktop.llm = { |
| | | getModels(): Promise<LlmModelSummary[]>; |
| | | streamChat(request: LlmStreamRequest): Promise<{ requestId: string }>; |
| | | cancel(requestId: string): Promise<void>; |
| | | 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 | |
| | | |
| | | 日志规则: |
| | | |
| | | - 可以记录 `requestId`、`modelId`、`provider`、endpoint host、HTTP status。 |
| | | - 不记录完整 API key。 |
| | | - 默认不记录完整 prompt;如后续需要调试开关,必须由用户显式启用。 |
| | | |
| | | ## Security Boundaries |
| | | |
| | | - `llm.stream` 必须作为插件权限声明,未声明时桥接层拒绝调用。 |
| | | - 插件只能看到 enabled 模型摘要。 |
| | | - 插件不能覆盖 endpoint、provider、authRef 或 apiModel。 |
| | | - `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 配置会增长,独立文件更利于管理和迁移 | |
| | | |
| | | ## 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 的模型可分别路由。 |
| | | |
| | | ## 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,选择不同模型提交后检查路由日志。 |
| | | - 配置缺失 `authRef`,确认输出区显示鉴权配置错误。 |
| | | - 配置本地 OpenAI-compatible 服务,确认无 key 模型可流式输出。 |
| | | - 断网或关闭本地 endpoint,确认插件输出区显示 endpoint 不可达。 |
| | | - 输出长文本,确认插件窗口和输出区不超过屏幕高度约束。 |
| | | |
| | | ## Open Decisions |
| | | |
| | | | 问题 | 建议默认值 | 后续触发条件 | |
| | | | --- | --- | --- | |
| | | | 密钥生产存储 | Windows Credential Manager | 管理窗口实现密钥编辑时落地 | |
| | | | 默认 adapter | OpenAI-compatible | 先覆盖 OpenAI、DeepSeek 兼容接口和本地服务 | |
| | | | DeepSeek 是否独立 adapter | 暂不强制 | 如果实际接口与 OpenAI-compatible 差异明显再拆 | |
| | | | 是否暴露本地 HTTP LLM API | 暂不暴露 | 插件桥接先满足需求;外部自动化需要时再设计 | |
| | | | 是否保存 prompt 历史 | 默认不保存 | 用户明确需要历史或调试审计时再评估 | |
| | | |
| New file |
| | |
| | | # 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` |
| | | - 日志目录:`%LocalAppData%\DesktopEnhancer\logs` |
| | | - WebView2 数据目录:`%LocalAppData%\DesktopEnhancer\WebView2` |
| | | |
| File was renamed from docs/product/user-manual.md |
| | |
| | | # 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) |
| | | |
| | | ## 使用前准备 |
| | | |
| | |
| | | - `sample.wallpaper`:本地 H5 动态壁纸。 |
| | | - `sample.clock`:桌面时钟小组件。 |
| | | - `sample.system-info`:系统信息占位小组件。 |
| | | - `sample.audio-visualizer`:音乐律动小组件。 |
| | | - `sample.llm-command-palette`:顶部 LLM 输入插件。 |
| | | |
| | | `sample.webview-test` 主要用于开发验证,通常不会默认启用。 |
| | | |
| | | ## 托盘菜单 |
| | | |
| | |
| | | | 插件 | 已扫描插件的名称、类型、状态、入口和错误码 | |
| | | | 诊断 | 诊断记录和插件 manifest 错误摘要 | |
| | | |
| | | ## 动态壁纸 |
| | | ## 通用组件操作 |
| | | |
| | | Moli.Desktop 使用 WebView2 加载 H5 壁纸。默认样例为 `sample.wallpaper`。 |
| | | |
| | | 常用操作: |
| | | |
| | | 1. 打开托盘菜单或管理窗口。 |
| | | 2. 点击“启用壁纸”显示壁纸。 |
| | | 3. 点击“禁用壁纸”关闭壁纸。 |
| | | 4. 如果桌面鼠标操作受影响,打开“安全输入模式”恢复可操作状态。 |
| | | |
| | | 壁纸层设计目标是位于桌面图标之后,与原生桌面融合。不同 Windows 桌面状态、显卡驱动和 WebView2 Runtime 状态可能影响实际表现;如显示异常,请先查看诊断页和日志目录。 |
| | | |
| | | ## 桌面小组件 |
| | | |
| | | 小组件来自本地 HTML 插件。默认样例包含: |
| | | |
| | | | 插件 | 用途 | |
| | | | --- | --- | |
| | | | `sample.clock` | 时钟小组件 | |
| | | | `sample.system-info` | 系统信息占位小组件 | |
| | | 小组件来自本地 HTML 插件。每个小组件都可以通过管理窗口进行显示、隐藏、锁定和解锁。 |
| | | |
| | | ### 显示或隐藏组件 |
| | | |
| New file |
| | |
| | | # 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` 权限。 |
| | | - 如果音频采集不可用,插件可能显示占位动效。 |
| | | - 查看日志目录和诊断页面是否存在音频采集错误。 |
| | | |
| | | ### 律动条挡住桌面点击 |
| | | |
| | | - 在管理窗口检查该组件点击穿透状态。 |
| | | - 从托盘菜单开启“安全输入模式”恢复控制。 |
| | | |
| New file |
| | |
| | | # 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 错误。 |
| | | |
| | | ### 时钟位置不合适 |
| | | |
| | | - 解锁组件后进入编辑模式调整位置。 |
| | | - 如果组件跑到屏幕外,可使用管理窗口“重置布局”。 |
| | | |
| New file |
| | |
| | | # sample.llm-command-palette LLM 桌面输入插件手册 |
| | | |
| | | 日期:2026-05-04 |
| | | |
| | | ## 插件用途 |
| | | |
| | | `sample.llm-command-palette` 是一个顶部居中的桌面输入条。它支持在输入框中直接输入问题,按 Enter 提交,右侧下拉选择模型,并在输入框下方展开流式输出。 |
| | | |
| | | ## 使用前准备 |
| | | |
| | | 使用该插件前,需要准备至少一个可访问的 LLM 接口。当前版本优先支持 OpenAI-compatible 流式接口,也可以配置 DeepSeek、本地 Ollama/LM Studio 等兼容接口。 |
| | | |
| | | ## 默认行为 |
| | | |
| | | | 项目 | 默认行为 | |
| | | | --- | --- | |
| | | | 位置 | 主屏顶部居中,顶部保留约 `32px` 空隙 | |
| | | | 显示层级 | `desktop` | |
| | | | 点击穿透 | 关闭,便于接收键盘和鼠标输入 | |
| | | | 锁定状态 | 锁定,避免误拖动 | |
| | | | 提交方式 | Enter 提交,不提供提交按钮 | |
| | | | 换行方式 | Shift+Enter | |
| | | | 输出区域 | 输入框底部展开,最大高度约为屏幕高度 `50%` | |
| | | |
| | | ## 配置模型 |
| | | |
| | | 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 流式格式,需要后续新增独立适配器。 |
| | | |
| | | ## 配置密钥 |
| | | |
| | | 当前版本使用环境变量作为密钥 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. 在右侧模型下拉中选择模型。 |
| | | 5. 输入问题。 |
| | | 6. 按 Enter 提交。 |
| | | 7. 在输入框下方查看流式输出。 |
| | | |
| | | 快捷操作: |
| | | |
| | | | 操作 | 效果 | |
| | | | --- | --- | |
| | | | 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。 |
| | | - 修正配置后重启应用,或在管理窗口中重载插件。 |
| | | |
| | | ### 请求提示密钥缺失 |
| | | |
| | | - 检查模型配置中的 `authRef`。 |
| | | - 确认已设置对应环境变量。 |
| | | - 如果刚设置环境变量,请重启 Moli.Desktop。 |
| | | - 本地无鉴权模型可将 `authRef` 设置为 `null`。 |
| | | |
| | | ### 请求提示 endpoint 不可达 |
| | | |
| | | - 确认 `endpoint` 地址正确。 |
| | | - 如果是本地模型服务,确认服务已启动并监听对应端口。 |
| | | - 如果是远程供应商,确认当前网络可访问该供应商 API。 |
| | | - 检查日志目录 `%LocalAppData%\DesktopEnhancer\logs`,日志只会记录 endpoint host,不会记录完整 API key。 |
| | | |
| | | ### 没有流式输出 |
| | | |
| | | - 确认上游接口支持 OpenAI-compatible SSE 流式输出。 |
| | | - 确认模型配置 `supportsStreaming` 为 `true`。 |
| | | - 如果供应商不是 OpenAI-compatible,当前版本可能需要新增对应 provider adapter。 |
| | | |
| | | ## 当前限制 |
| | | |
| | | - 模型配置当前主要通过手工编辑 `llm-models.json` 完成。 |
| | | - 密钥当前使用环境变量 fallback,Windows Credential Manager 管理界面尚未实现。 |
| | | - 当前已实现 OpenAI-compatible 流式协议;非兼容供应商需要后续新增适配器。 |
| | | |
| New file |
| | |
| | | # 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` 是否存在。 |
| | | - 检查管理窗口“插件”和“诊断”页面。 |
| | | |
| New file |
| | |
| | | # 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 已安装。 |
| | | |
| | | ### 壁纸挡住桌面点击 |
| | | |
| | | - 从托盘菜单开启“安全输入模式”。 |
| | | - 在管理窗口检查壁纸点击穿透状态。 |
| | | - 必要时禁用壁纸后重新启用。 |
| | | |
| New file |
| | |
| | | # 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`。 |
| | | |
| | |
| | | - 作为用户,我可以在输入框右侧切换模型,这样我能按任务选择更快或更强的模型。 |
| | | - 作为用户,我可以在回复生成时看到逐步流式输出,这样我知道请求正在进行。 |
| | | - 作为用户,我可以继续编辑输入内容、复制输出内容或按 Escape 收起结果,这样桌面不会被长文本长期占据。 |
| | | - 作为用户,我可以通过管理窗口或配置切换 API endpoint、模型列表和默认模型,这样插件能适配不同 LLM 服务。 |
| | | - 作为用户,我可以通过管理窗口或配置维护不同供应商的模型、endpoint 和默认模型,这样插件能同时接入 OpenAI-compatible、DeepSeek、本地模型或后续新增供应商。 |
| | | |
| | | ## 插件类型 |
| | | |
| | |
| | | |
| | | ### 错误状态 |
| | | |
| | | - API key 缺失、endpoint 不可达、模型不可用、请求超时和流式解析失败必须展示短错误。 |
| | | - API key 缺失、模型 endpoint 不可达、模型不可用、请求超时和流式解析失败必须展示短错误。 |
| | | - 错误信息显示在输出区域内,不弹出系统模态框。 |
| | | - 错误文本应包含可操作方向,例如“请在插件配置中检查 endpoint 和密钥”。 |
| | | - 错误文本应包含可操作方向,例如“请在模型配置中检查该模型的 endpoint 和密钥”。 |
| | | |
| | | ## 视觉设计 |
| | | |
| | |
| | | |
| | | ## 模型配置 |
| | | |
| | | 插件配置应支持: |
| | | 插件前端只需要知道可展示的模型清单和默认模型。具体供应商、endpoint、鉴权方式和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `modelId`。 |
| | | |
| | | 推荐采用“按模型路由”的配置结构:每个模型都可以绑定独立 provider、URL、鉴权引用和请求适配参数。这样同一个插件可以同时接入不同供应商,也可以接入同一供应商的不同 base URL。 |
| | | |
| | | ```json |
| | | { |
| | | "provider": "openai-compatible", |
| | | "endpoint": "https://api.example.com/v1/chat/completions", |
| | | "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": { |
| | |
| | | } |
| | | ``` |
| | | |
| | | 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 只关心“用户选了哪个模型”。 |
| | | |
| | | ## 宿主与插件通信 |
| | | |
| | |
| | | |
| | | ```javascript |
| | | window.moliDesktop.llm.streamChat({ |
| | | model: "gpt-5.4", |
| | | modelId: "gpt-5.4", |
| | | messages: [ |
| | | { role: "user", content: "..." } |
| | | ], |
| | |
| | | } |
| | | }); |
| | | ``` |
| | | |
| | | 插件不应直接传 provider、endpoint 或密钥。宿主响应中可返回本次请求实际命中的供应商和模型,用于诊断和 UI tooltip,但不返回密钥。 |
| | | |
| | | 流式事件建议: |
| | | |
| | |
| | | "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 |
| | | } |
| | | ] |
| | | } |
| | | } |
| | | ``` |
| | |
| | | |
| | | ### FR-LLM-05 配置与密钥 |
| | | |
| | | - 插件必须支持配置 endpoint、模型列表、默认模型和请求参数。 |
| | | - 插件必须支持配置模型列表、默认模型和请求参数。 |
| | | - 每个模型必须能够配置独立的 provider、endpoint、真实上游模型名和启用状态。 |
| | | - 宿主应根据 `modelId` 路由到对应 provider 适配器,并调用该模型自己的 endpoint。 |
| | | - API key 不得写死在插件前端资源中。 |
| | | - API key 应以 `authRef` 形式引用宿主侧密钥存储或用户环境配置。 |
| | | - 如果宿主暂未提供密钥安全存储,MVP 必须将该能力标记为受限,并提供清晰风险提示。 |
| | | |
| | | 优先级:P1 |
| | |
| | | ### 安全 |
| | | |
| | | - 首版插件无沙箱隔离,但 LLM 请求能力必须通过明确权限声明。 |
| | | - 宿主代理 LLM 请求时,应限制插件只能使用被允许的 endpoint 和模型。 |
| | | - 宿主代理 LLM 请求时,应限制插件只能使用已启用的模型 id,并由宿主解析对应 endpoint。 |
| | | - 日志不得记录完整 API key。 |
| | | - 默认不把用户输入内容写入持久化配置。 |
| | | |
| | |
| | | - 当插件首次安装并启用时,输入条出现在主屏顶部居中,顶部留有约 `32px` 空隙。 |
| | | - 当用户输入文本并按 Enter 时,插件发起一次 LLM 请求,且没有提交按钮。 |
| | | - 当用户选择不同模型后再提交时,请求使用新模型。 |
| | | - 当不同模型配置了不同供应商和 endpoint 时,宿主应按所选 `modelId` 路由到对应 API。 |
| | | - 当 LLM 返回内容时,输出区域在输入框底部展开,并逐步显示流式文本。 |
| | | - 当输出内容超过屏幕高度 `50%` 时,输出区域内部滚动,插件不会继续向下无限扩张。 |
| | | - 当用户按 Escape 时,已展开输出区域可以收起。 |
| | |
| | | | 问题 | 建议默认值 | |
| | | | --- | --- | |
| | | | MVP 是否由宿主代理 LLM 请求 | 是,避免 API key 暴露给插件前端 | |
| | | | 默认模型列表来源 | 插件配置,后续可由管理窗口编辑 | |
| | | | 默认模型列表来源 | 宿主侧 LLM 模型注册表,插件 manifest 只提供 fallback | |
| | | | 模型是否共用 endpoint | 不强制共用;每个模型可配置独立 endpoint,宿主统一按 `modelId` 路由 | |
| | | | 是否保留历史记录 | MVP 不保留,仅保留当前结果 | |
| | | | 是否支持停止生成 | MVP 可暂不支持,后续新增停止按钮或 Escape 二次行为 | |
| | | | 是否全局快捷键唤起 | 后续版本考虑,例如 `Alt+Space` 或用户自定义快捷键 | |
| | | |
| New file |
| | |
| | | # 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,再执行端到端流式输出测试。 |
| New file |
| | |
| | | <!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 { |
| | | width: 100%; |
| | | border: 1px solid rgba(255, 255, 255, 0.16); |
| | | background: rgba(30, 28, 27, 0.74); |
| | | box-shadow: 0 18px 42px rgba(0, 0, 0, 0.24); |
| | | backdrop-filter: blur(18px); |
| | | } |
| | | |
| | | .bar { |
| | | display: grid; |
| | | grid-template-columns: 24px minmax(0, 1fr) 128px; |
| | | align-items: center; |
| | | gap: 14px; |
| | | min-height: 56px; |
| | | padding: 0 18px; |
| | | 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); |
| | | } |
| | | |
| | | select { |
| | | width: 100%; |
| | | height: 34px; |
| | | border: 0; |
| | | outline: none; |
| | | color: rgba(255, 255, 255, 0.82); |
| | | background: rgba(255, 255, 255, 0.08); |
| | | border-radius: 8px; |
| | | padding: 0 8px; |
| | | font: 600 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | } |
| | | |
| | | .output { |
| | | 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 { |
| | | display: block; |
| | | } |
| | | |
| | | .actions { |
| | | display: flex; |
| | | justify-content: flex-end; |
| | | gap: 8px; |
| | | margin-top: 12px; |
| | | } |
| | | |
| | | 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; |
| | | } |
| | | |
| | | .error { |
| | | color: #ffad9b; |
| | | } |
| | | </style> |
| | | </head> |
| | | <body> |
| | | <main class="shell"> |
| | | <section class="bar"> |
| | | <div id="mark" class="mark" aria-hidden="true">*</div> |
| | | <textarea id="prompt" rows="1" placeholder="What can I help you with today?"></textarea> |
| | | <select id="model" title="Model"></select> |
| | | </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> |
| | | </main> |
| | | |
| | | <script> |
| | | const promptInput = document.getElementById("prompt"); |
| | | const modelSelect = document.getElementById("model"); |
| | | 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"); |
| | | let activeRequestId = null; |
| | | let currentText = ""; |
| | | |
| | | function setBusy(busy) { |
| | | mark.classList.toggle("busy", busy); |
| | | mark.textContent = busy ? "*" : "*"; |
| | | } |
| | | |
| | | function openOutput() { |
| | | output.classList.add("open"); |
| | | window.moliDesktop?.requestResize?.({ width: document.body.scrollWidth, height: Math.min(window.innerHeight, document.body.scrollHeight) }).catch(() => {}); |
| | | } |
| | | |
| | | function setError(message) { |
| | | currentText = message; |
| | | text.className = "error"; |
| | | text.textContent = message; |
| | | openOutput(); |
| | | } |
| | | |
| | | async function loadModels() { |
| | | try { |
| | | const models = await window.moliDesktop.llm.getModels(); |
| | | modelSelect.innerHTML = ""; |
| | | for (const model of models) { |
| | | const option = document.createElement("option"); |
| | | option.value = model.id; |
| | | option.textContent = model.label || model.id; |
| | | option.title = `${model.provider} / ${model.id}`; |
| | | modelSelect.appendChild(option); |
| | | } |
| | | |
| | | if (models.length === 0) { |
| | | const option = document.createElement("option"); |
| | | option.textContent = "No models"; |
| | | option.value = ""; |
| | | modelSelect.appendChild(option); |
| | | } |
| | | } catch { |
| | | modelSelect.innerHTML = "<option value=\"\">No models</option>"; |
| | | } |
| | | } |
| | | |
| | | 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 response = await window.moliDesktop.llm.streamChat({ |
| | | modelId, |
| | | messages: [{ role: "user", content }], |
| | | options: {} |
| | | }); |
| | | activeRequestId = response.requestId; |
| | | } catch (error) { |
| | | activeRequestId = null; |
| | | setBusy(false); |
| | | setError(error?.message || "LLM request could not be started."); |
| | | } |
| | | } |
| | | |
| | | promptInput.addEventListener("keydown", (event) => { |
| | | if (event.key === "Enter" && !event.shiftKey) { |
| | | event.preventDefault(); |
| | | submitPrompt(); |
| | | } |
| | | |
| | | if (event.key === "Escape") { |
| | | output.classList.remove("open"); |
| | | } |
| | | }); |
| | | |
| | | promptInput.addEventListener("input", () => { |
| | | promptInput.style.height = "0"; |
| | | promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`; |
| | | }); |
| | | |
| | | collapse.addEventListener("click", () => output.classList.remove("open")); |
| | | copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {})); |
| | | |
| | | window.addEventListener("DOMContentLoaded", loadModels); |
| | | 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> |
| New file |
| | |
| | | { |
| | | "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": { |
| | | "defaultModel": "", |
| | | "models": [] |
| | | } |
| | | } |
| New file |
| | |
| | | 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" }); |
| | | } |
| | | |
| | | private static LlmGatewayService CreateGateway(CapturingAdapter adapter, 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); |
| | | } |
| | | |
| | | 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 }; |
| | | } |
| | | } |
| | | } |
| | | |
| | | 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; |
| | | } |
| | | } |
| New file |
| | |
| | | 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); |
| | | } |
| | | } |
| | |
| | | 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; |
| | |
| | | } |
| | | |
| | | [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_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("streamChat", script); |
| | | Assert.Contains("moliDesktopResponse", script); |
| | | } |
| | | |
| | |
| | | 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) |
| | | { |
| | | return new PluginBridgeContext |
| | | { |
| | |
| | | Name = "Clock", |
| | | Version = "1.0.0", |
| | | Type = PluginType.Widget, |
| | | Entry = "index.html" |
| | | Entry = "index.html", |
| | | Permissions = includeLlmPermission ? ["llm.stream"] : [] |
| | | }, |
| | | RuntimeInfo = new PluginRuntimeBridgeInfo |
| | | { |
| | |
| | | Config = JsonDocument.Parse("""{"label":"clock"}""").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 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 }; |
| | | } |
| | | } |
| | | } |
| | |
| | | "sample.wallpaper", |
| | | "sample.clock", |
| | | "sample.system-info", |
| | | "sample.audio-visualizer" |
| | | "sample.audio-visualizer", |
| | | "sample.llm-command-palette" |
| | | }; |
| | | |
| | | private readonly DesktopPaths _paths; |
| | |
| | | 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) |
| | |
| | | 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; |
| | |
| | | services.AddSingleton<IRuntimeSurfaceController, RuntimeSurfaceController>(); |
| | | services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>(); |
| | | services.AddSingleton<IConfigurationService, JsonConfigurationService>(); |
| | | services.AddSingleton<ILlmModelRegistry, LlmModelRegistry>(); |
| | | services.AddSingleton<ICredentialStore, EnvironmentCredentialStore>(); |
| | | services.AddHttpClient<OpenAICompatibleAdapter>(); |
| | | 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>(); |
| New file |
| | |
| | | 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)); |
| | | } |
| | | } |
| New file |
| | |
| | | namespace Moli.Desktop.Llm; |
| | | |
| | | public interface ILlmGatewayService |
| | | { |
| | | Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(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); |
| | | } |
| New file |
| | |
| | | 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 ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase); |
| | | |
| | | public LlmGatewayService( |
| | | ILlmModelRegistry registry, |
| | | ICredentialStore credentialStore, |
| | | ILlmProviderAdapterFactory adapterFactory, |
| | | IDiagnosticsService diagnostics) |
| | | { |
| | | _registry = registry; |
| | | _credentialStore = credentialStore; |
| | | _adapterFactory = adapterFactory; |
| | | _diagnostics = diagnostics; |
| | | } |
| | | |
| | | 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 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; |
| | | } |
| | | |
| | | var 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 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 |
| | | }); |
| | | } |
| | | } |
| New file |
| | |
| | | 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); |
| | | } |
| | | } |
| New file |
| | |
| | | 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 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; } |
| | | } |
| | | |
| | | 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"; |
| | | } |
| New file |
| | |
| | | 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; |
| | | } |
| | | } |
| New file |
| | |
| | | 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; } |
| | | } |
| | |
| | | using System.Text.Json; |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Llm; |
| | | using Moli.Desktop.Runtime; |
| | | |
| | | namespace Moli.Desktop.WebView; |
| | |
| | | "requestReload", |
| | | "requestShow", |
| | | "requestHide", |
| | | "requestResize" |
| | | "requestResize", |
| | | "llm.getModels", |
| | | "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( |
| | |
| | | "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.getModels" => await HandleGetLlmModelsAsync(request, 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, CancellationToken cancellationToken) |
| | | { |
| | | var models = await _llmGateway.GetModelsAsync(cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, models); |
| | | } |
| | | |
| | | 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, |
| | | ModelId = payload.ModelId, |
| | | Messages = payload.Messages, |
| | | Options = payload.Options ?? new LlmRequestOptions() |
| | | }; |
| | | |
| | | _ = 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( |
| | |
| | | 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 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 required string ModelId { get; init; } |
| | | public IReadOnlyList<LlmMessage> Messages { get; init; } = []; |
| | | public LlmRequestOptions? Options { get; init; } |
| | | } |
| | | } |
| | | |
| | | public sealed record PluginBridgeResponse |
| | |
| | | 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"), |
| | |
| | | requestReload: () => call("requestReload"), |
| | | requestShow: () => call("requestShow"), |
| | | requestHide: () => call("requestHide"), |
| | | requestResize: (size) => call("requestResize", size) |
| | | requestResize: (size) => call("requestResize", size), |
| | | llm: Object.freeze({ |
| | | getModels: () => call("llm.getModels"), |
| | | 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) |
| | | }) |
| | | }); |
| | | })(); |
| | | """; |
| | |
| | | private PluginBridgeContext? _bridgeContext; |
| | | private WebViewHostOptions? _options; |
| | | private IDisposable? _audioSubscription; |
| | | private IDisposable? _llmSubscription; |
| | | private bool _initialized; |
| | | |
| | | public WebViewHost( |
| | |
| | | { |
| | | _audioSubscription = _events.Subscribe(DispatchAudioSpectrumAsync); |
| | | } |
| | | |
| | | _llmSubscription = _events.Subscribe(DispatchLlmEventAsync); |
| | | |
| | | if (!string.IsNullOrWhiteSpace(options.InitialScript)) |
| | | { |
| | |
| | | { |
| | | _audioSubscription?.Dispose(); |
| | | _audioSubscription = null; |
| | | _llmSubscription?.Dispose(); |
| | | _llmSubscription = null; |
| | | |
| | | if (Control.CoreWebView2 is not null) |
| | | { |
| | |
| | | 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) |