基于WebView2实现的Win11桌面框架,利用插件自定义
编辑 | blame | 历史 | 原始文档

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

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

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

插件模型下拉只能拿到安全摘要:

[
  {
    "id": "gpt-5.4",
    "label": "GPT-5.4",
    "provider": "openai-compatible",
    "supportsStreaming": true,
    "enabled": true
  }
]

默认不返回 endpoint、authRef、API key 或其他敏感配置。管理窗口可以在受控 UI 中展示和编辑 endpoint,但插件前端不需要知道。

Stream Chat

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

建议新增独立配置文件:

%AppData%\DesktopEnhancer\config\llm-models.json

独立文件的好处:

  • 避免把供应商 endpoint 和模型配置塞入 layout.json 或普通插件 manifest。
  • 便于管理窗口单独做“模型配置”页。
  • 后续迁移到加密存储或服务端配置时边界更清晰。

示例:

{
  "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 不直接等于环境变量名,可以通过宿主映射:

{
  "authRef": "llm.openai.primary"
}

宿主解析顺序示例:

Windows Credential Manager: Moli.Desktop/llm.openai.primary
Environment variable: MOLI_LLM_OPENAI_PRIMARY

Interfaces

C# Service Contracts

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

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

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

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 历史 默认不保存 用户明确需要历史或调试审计时再评估