| | |
| | | ## 当前开发文档 |
| | | |
| | | - [Moli.Desktop MVP 开发任务拆分](development/mvp-dev-task-breakdown.md) |
| | | - [LLM 桌面输入插件 AiChat 模式开发任务拆分](development/llm-command-palette-aichat-mode-task-breakdown.md) |
| | | |
| | | ## 当前 API 文档 |
| | | |
| | |
| | | - [Moli.Desktop MVP 集成移交记录](qa/mvp-integration-handoff.md) |
| | | - [Moli.Desktop MVP QA 测试计划与报告](qa/mvp-qa-report-2026-05-02.md) |
| | | - [LLM 桌面输入插件验收记录](qa/llm-command-palette-acceptance-2026-05-04.md) |
| | | - [LLM 桌面输入插件 AiChat 模式验收记录](qa/llm-command-palette-aichat-mode-acceptance-2026-05-04.md) |
| | | |
| | | ## 当前运维文档 |
| | | |
| | |
| | | |
| | | 策略顺序: |
| | | |
| | | 1. `WorkerWDesktopLayerStrategy`:尝试将壁纸窗口和 `desktop` 层组件挂到 Explorer WorkerW,使桌面插件在 Win+D 后仍然显示。 |
| | | 1. `WorkerWDesktopLayerStrategy`:尝试将壁纸窗口和 `desktop` 层组件挂到 Explorer WorkerW;当当前 Explorer 没有独立 WorkerW 时回退到 Progman 桌面宿主。挂载时窗口必须切换为 `WS_CHILD` 并移除 `WS_POPUP`,使桌面插件在 Win+D 后仍然显示。 |
| | | 2. `BottomDesktopLayerStrategy`:降级为覆盖目标区域的底层窗口,并开启点击穿透。 |
| | | |
| | | 选择策略后写入诊断: |
| | |
| | | 核心架构决策: |
| | | |
| | | - 插件前端只负责输入、模型选择和流式渲染。 |
| | | - 插件前端只传 `modelId`、`messages` 和请求参数,不直接传 provider、endpoint 或 API key。 |
| | | - 插件前端只传 `mode`、`projectId`、`modelId`、`messages` 和请求参数,不直接传 provider、endpoint、API key、AiChat 密码或 Session Token。 |
| | | - 宿主维护 LLM 模型注册表,每个模型可独立配置 `provider`、`endpoint`、`authRef` 和 `apiModel`。 |
| | | - 宿主按 `modelId` 选择 provider adapter,并把不同供应商的流式响应统一转换成插件可消费的事件。 |
| | | - API key 不进入插件前端资源、manifest 示例或普通日志。 |
| | | - 插件运行模式由配置决定: |
| | | - `provider-direct`:沿用当前供应商直连链路,并可调用 AiChat 记忆接口管理/召回记忆。 |
| | | - `aichat-api`:通过自有 AiChat API 登录、读取项目、发送聊天和订阅 SSE;插件侧不处理记忆。 |
| | | - AiChat 统一 Host 默认固定为 `http://192.168.1.111:13000`,不从 AiChat 接口文档的环境表推导。 |
| | | |
| | | ## Goals |
| | | |
| | | - 支持一个顶部居中的 LLM 输入小组件,默认作为 `widget` 插件运行。 |
| | | - 支持多供应商、多 endpoint、多模型共存。 |
| | | - 支持通过配置切换供应商直连和 AiChat 自有 API 两种模式。 |
| | | - 支持输入框左侧 AiChat 项目下拉。 |
| | | - 支持供应商直连模式下复用 AiChat 记忆管理能力。 |
| | | - 支持 OpenAI-compatible、DeepSeek、本地 OpenAI-compatible 服务,后续可扩展 Anthropic、Ollama 等适配器。 |
| | | - 支持流式输出,并将供应商差异屏蔽在宿主侧。 |
| | | - 保持插件系统边界:WebView 页面只访问白名单桥接 API。 |
| | |
| | | - 不实现完整聊天会话系统。 |
| | | - 不实现云端同步、团队共享模型配置或计费系统。 |
| | | - 不在插件前端直接保存或管理 API key。 |
| | | - 不在插件前端保存 AiChat 密码或 Session Token。 |
| | | - 不复制 AiChat 服务端的项目、审批、权限、配额和记忆策略。 |
| | | - 不在 `aichat-api` 模式中额外调用记忆召回拼装 Prompt。 |
| | | - 不在 MVP 中实现文件上传、多模态输入或长期历史记录。 |
| | | - 不要求把 LLM 代理暴露成公网 API。 |
| | | |
| | |
| | | Bridge["PluginBridgeScript / WebViewHost"] |
| | | Runtime["DesktopRuntimeCoordinator"] |
| | | LlmService["LlmGatewayService"] |
| | | ModeRouter["LlmModeRouter"] |
| | | AiChat["AiChatClient"] |
| | | AiChatSession["AiChatSessionService"] |
| | | AiChatMemory["AiChatMemoryService"] |
| | | Registry["LlmModelRegistry"] |
| | | SecretStore["CredentialStore"] |
| | | AdapterFactory["LlmProviderAdapterFactory"] |
| | |
| | | Plugin --> Bridge |
| | | Bridge --> Runtime |
| | | Runtime --> LlmService |
| | | LlmService --> ModeRouter |
| | | ModeRouter --> AiChat |
| | | AiChat --> AiChatSession |
| | | AiChat --> AiChatMemory |
| | | LlmService --> Registry |
| | | Registry --> Config |
| | | LlmService --> SecretStore |
| | |
| | | | `sample.llm-command-palette` | 输入、模型下拉、Enter 提交、流式文本渲染、错误展示 | 供应商 API 适配、密钥读取 | |
| | | | `PluginBridgeScript` | 向 WebView 注入 `window.moliDesktop.llm` API,处理 Promise 与事件派发 | 直接发起外部 HTTP 请求 | |
| | | | `DesktopRuntimeCoordinator` | 统一接收插件桥接命令,校验插件实例和权限,调用 LLM 服务 | 解析供应商流式协议 | |
| | | | `LlmGatewayService` | LLM 请求入口、模型路由、取消、超时、事件归一化 | 持久化布局或窗口状态 | |
| | | | `LlmGatewayService` | LLM 请求入口、运行模式分发、模型路由、取消、超时、事件归一化 | 持久化布局或窗口状态 | |
| | | | `LlmModeRouter` | 按 `provider-direct` / `aichat-api` 选择供应商适配器或 AiChat 客户端 | 处理具体 SSE 协议 | |
| | | | `AiChatClient` | 封装 AiChat 登录、项目、模型、聊天、SSE 和错误码映射 | 保存用户密码明文 | |
| | | | `AiChatSessionService` | 解析密码环境变量、登录、缓存内存态 sessionToken、401 重登 | 暴露 sessionToken 给插件页面 | |
| | | | `AiChatMemoryService` | 供应商直连模式下封装记忆查询、创建、删除、召回 | 在自有 API 模式中重复处理记忆 | |
| | | | `LlmModelRegistry` | 加载和校验模型配置,按 `modelId` 查找模型 | 保存 API key 明文 | |
| | | | `CredentialStore` | 按 `authRef` 提供密钥,隐藏真实 key | 保存普通插件配置 | |
| | | | `LlmProviderAdapter` | 按 provider 适配请求和流式响应 | 决定插件 UI 行为 | |
| | |
| | | - 插件 UI 只能依赖 `window.moliDesktop.llm`。 |
| | | - 桥接层只依赖运行时接口,不直接依赖具体 provider adapter。 |
| | | - Provider adapter 只由 `LlmGatewayService` 通过工厂创建或取得。 |
| | | - AiChat API 访问只由宿主侧 `AiChatClient` 执行,插件页面不能直接持有密码或 token。 |
| | | - 配置读写仍经 `ConfigurationService`,不允许插件或 adapter 直接写 JSON。 |
| | | |
| | | ## Runtime Flow |
| | |
| | | |
| | | 默认不返回 `endpoint`、`authRef`、API key 或其他敏感配置。管理窗口可以在受控 UI 中展示和编辑 endpoint,但插件前端不需要知道。 |
| | | |
| | | `aichat-api` 模式下模型列表来自 AiChat `GET /api/chat/models`,返回同样的安全摘要结构: |
| | | |
| | | ```json |
| | | [ |
| | | { |
| | | "id": "deepseek-v4-flash", |
| | | "label": "deepseek-v4-flash", |
| | | "provider": "aichat", |
| | | "supportsStreaming": true, |
| | | "enabled": true |
| | | } |
| | | ] |
| | | ``` |
| | | |
| | | ### AiChat Login and Project Load |
| | | |
| | | ```mermaid |
| | | sequenceDiagram |
| | | participant Plugin |
| | | participant Bridge |
| | | participant Runtime |
| | | participant AiChat as AiChatClient |
| | | participant Session as AiChatSessionService |
| | | participant Api as AiChat API |
| | | |
| | | Plugin->>Bridge: getProjects() |
| | | Bridge->>Runtime: GetAiChatProjects(pluginId, instanceId) |
| | | Runtime->>AiChat: GetProjectsAsync() |
| | | AiChat->>Session: EnsureSessionAsync() |
| | | Session->>Session: Resolve passwordEnv before password |
| | | Session->>Api: POST /api/auth/login |
| | | Api-->>Session: sessionToken |
| | | AiChat->>Api: GET /api/projects with x-session-token |
| | | Api-->>AiChat: projects |
| | | AiChat-->>Runtime: safe project summaries |
| | | Runtime-->>Bridge: project summaries |
| | | Bridge-->>Plugin: Promise resolve |
| | | ``` |
| | | |
| | | 项目摘要建议只返回插件 UI 需要的字段: |
| | | |
| | | ```json |
| | | [ |
| | | { |
| | | "id": "project_id", |
| | | "name": "产品问答", |
| | | "projectType": "CHAT", |
| | | "memoryMode": "ISOLATED" |
| | | } |
| | | ] |
| | | ``` |
| | | |
| | | ### Stream Chat |
| | | |
| | | ```mermaid |
| | |
| | | participant Adapter as ProviderAdapter |
| | | participant Upstream as LLM Provider |
| | | |
| | | Plugin->>Bridge: streamChat(modelId, messages, options) |
| | | Plugin->>Bridge: streamChat(mode, projectId, modelId, messages, options) |
| | | Bridge->>Runtime: StreamLlmChat(request) |
| | | Runtime->>Runtime: Validate plugin permission llm.stream |
| | | Runtime->>Llm: StreamChatAsync(request) |
| | | Llm->>Registry: Get model by modelId |
| | | Llm->>Registry: Get model by modelId when provider-direct |
| | | Registry-->>Llm: provider, endpoint, authRef, apiModel |
| | | Llm->>Secret: Resolve authRef |
| | | Secret-->>Llm: credential or null |
| | |
| | | Runtime-->>Bridge: llm.delta / completed / error |
| | | Bridge-->>Plugin: DOM event or callback |
| | | ``` |
| | | |
| | | ### AiChat API Chat Flow |
| | | |
| | | ```mermaid |
| | | sequenceDiagram |
| | | participant Plugin |
| | | participant Bridge |
| | | participant Runtime |
| | | participant Llm as LlmGatewayService |
| | | participant AiChat as AiChatClient |
| | | participant Api as AiChat API |
| | | |
| | | Plugin->>Bridge: streamChat(mode=aichat-api, projectId, modelId, message) |
| | | Bridge->>Runtime: StreamLlmChat(request) |
| | | Runtime->>Runtime: Validate plugin permission llm.stream |
| | | Runtime->>Llm: StreamChatAsync(request) |
| | | Llm->>AiChat: SendChatAsync(projectId, modelName, message) |
| | | AiChat->>Api: POST /api/chat/send |
| | | Api-->>AiChat: generationId, streamToken, conversationId |
| | | AiChat->>Api: GET /api/chat/generations/{id}/stream?token={streamToken} |
| | | Api-->>AiChat: snapshot/chunk/processing/done/failed/aborted |
| | | AiChat-->>Llm: normalized deltas/completed/error |
| | | Llm-->>Runtime: LlmStreamEvent |
| | | Runtime-->>Bridge: llm.delta / completed / error |
| | | Bridge-->>Plugin: DOM event or callback |
| | | ``` |
| | | |
| | | AiChat SSE 事件映射: |
| | | |
| | | | AiChat event | 归一化事件 | 处理 | |
| | | | --- | --- | --- | |
| | | | `snapshot` | `llm.delta` 或忽略 | 如果 snapshot content 非空,作为当前内容快照渲染 | |
| | | | `chunk` | `llm.delta` | 使用 `delta` 追加 | |
| | | | `processing` | `llm.processing` | UI 可显示“处理中” | |
| | | | `done` | `llm.completed` | 结束请求 | |
| | | | `failed` | `llm.error` | 显示错误并结束请求 | |
| | | | `aborted` | `llm.error` 或 `llm.aborted` | 显示已终止并结束请求 | |
| | | |
| | | ### Provider Direct Memory Flow |
| | | |
| | | 供应商直连模式下,记忆管理走 AiChat API,但聊天生成仍走供应商适配器: |
| | | |
| | | ```mermaid |
| | | sequenceDiagram |
| | | participant Plugin |
| | | participant Bridge |
| | | participant Runtime |
| | | participant Memory as AiChatMemoryService |
| | | participant Api as AiChat API |
| | | participant Llm as LlmGatewayService |
| | | participant Provider as ProviderAdapter |
| | | |
| | | Plugin->>Bridge: recallMemories(query, projectId, scope=ALL) |
| | | Bridge->>Runtime: RecallMemories(request) |
| | | Runtime->>Memory: RecallAsync(request) |
| | | Memory->>Api: POST /api/memories/recall |
| | | Api-->>Memory: memory items |
| | | Memory-->>Plugin: safe memory summaries |
| | | Plugin->>Bridge: streamChat(mode=provider-direct, messages with selected memory context) |
| | | Bridge->>Llm: StreamChatAsync(request) |
| | | Llm->>Provider: StreamAsync(normalized request) |
| | | ``` |
| | | |
| | | 权限规则: |
| | | |
| | | - `GET /api/auth/me` 返回 `canUseMemory`、`canViewMemory`、`canManageMemory` 后,宿主应把可用能力摘要返回给插件。 |
| | | - `canViewMemory=false` 时不展示记忆列表。 |
| | | - `canManageMemory=false` 时不允许创建或删除。 |
| | | - `canUseMemory=false` 时不允许召回并注入上下文。 |
| | | |
| | | ### Cancellation |
| | | |
| | |
| | | } |
| | | ``` |
| | | |
| | | ### Plugin Runtime Mode Config |
| | | |
| | | 建议在插件配置或后续独立运行配置中增加 AiChat 对接配置。为了兼容现有 `plugin.json`,缺失字段时使用默认值。 |
| | | |
| | | ```json |
| | | { |
| | | "schemaVersion": 1, |
| | | "mode": "provider-direct", |
| | | "aichat": { |
| | | "baseUrl": "http://192.168.1.111:13000", |
| | | "account": { |
| | | "email": "user@example.com", |
| | | "password": null, |
| | | "passwordEnv": "MOLI_AICHAT_PASSWORD" |
| | | }, |
| | | "defaultProjectId": "", |
| | | "memory": { |
| | | "enabledInProviderDirect": true, |
| | | "defaultScope": "PROJECT", |
| | | "recallLimit": 8 |
| | | } |
| | | } |
| | | } |
| | | ``` |
| | | |
| | | 校验规则: |
| | | |
| | | | 字段 | 规则 | |
| | | | --- | --- | |
| | | | `mode` | `provider-direct` 或 `aichat-api`,缺失时默认为 `provider-direct` | |
| | | | `aichat.baseUrl` | `http` 或 `https` 绝对 URL,默认 `http://192.168.1.111:13000` | |
| | | | `aichat.account.email` | 可为空;调用 AiChat API 前必须存在 | |
| | | | `aichat.account.passwordEnv` | 可为空;存在时优先读取环境变量 | |
| | | | `aichat.account.password` | 可为空;只作为本地测试 fallback | |
| | | | `aichat.defaultProjectId` | 可为空;不为空时应存在于项目列表 | |
| | | | `aichat.memory.recallLimit` | `1..20` | |
| | | |
| | | 密码解析顺序: |
| | | |
| | | 1. `passwordEnv` 指向的环境变量值。 |
| | | 2. `password` 明文字段。 |
| | | 3. 都不存在时返回 `AiChatCredentialMissing`。 |
| | | |
| | | Session Token 仅保存在 `AiChatSessionService` 内存态,不写入 JSON。 |
| | | |
| | | ### Model Validation Rules |
| | | |
| | | | 字段 | 规则 | |
| | |
| | | public required string RequestId { get; init; } |
| | | public required string PluginId { get; init; } |
| | | public required string InstanceId { get; init; } |
| | | public string Mode { get; init; } = "provider-direct"; |
| | | public string? ProjectId { get; init; } |
| | | public required string ModelId { get; init; } |
| | | public required IReadOnlyList<LlmMessage> Messages { get; init; } |
| | | public LlmRequestOptions Options { get; init; } = new(); |
| | |
| | | }; |
| | | |
| | | type LlmStreamRequest = { |
| | | mode?: "provider-direct" | "aichat-api"; |
| | | projectId?: string; |
| | | modelId: string; |
| | | messages: Array<{ role: "system" | "user" | "assistant"; content: string }>; |
| | | options?: { |
| | |
| | | }; |
| | | |
| | | window.moliDesktop.llm = { |
| | | getConnectionMode(): Promise<"provider-direct" | "aichat-api">; |
| | | setConnectionMode(mode: "provider-direct" | "aichat-api"): Promise<void>; |
| | | getProjects(): Promise<Array<{ |
| | | id: string; |
| | | name: string; |
| | | projectType: "CHAT" | "REMOTE"; |
| | | memoryMode: "ISOLATED" | "SHARED"; |
| | | }>>; |
| | | getModels(): Promise<LlmModelSummary[]>; |
| | | streamChat(request: LlmStreamRequest): Promise<{ requestId: string }>; |
| | | cancel(requestId: string): Promise<void>; |
| | | getMemoryCapabilities(): Promise<{ |
| | | canUseMemory: boolean; |
| | | canViewMemory: boolean; |
| | | canManageMemory: boolean; |
| | | }>; |
| | | getMemories(options: { scope?: "GLOBAL" | "PROJECT"; projectId?: string }): Promise<object>; |
| | | createMemory(input: { scope: "GLOBAL" | "PROJECT"; projectId?: string; content: string }): Promise<object>; |
| | | deleteMemory(memoryId: string): Promise<void>; |
| | | recallMemories(input: { query: string; scope?: "GLOBAL" | "PROJECT" | "ALL"; projectId?: string; limit?: number }): Promise<object>; |
| | | onDelta(handler: (event: { requestId: string; delta: string }) => void): () => void; |
| | | onCompleted(handler: (event: { requestId: string; usage?: object }) => void): () => void; |
| | | onError(handler: (event: { requestId: string; code: string; message: string }) => void): () => void; |
| | |
| | | | `LlmRateLimited` | 429 | 输出区提示稍后重试 | Warning | |
| | | | `LlmTimeout` | 超时 | 输出区提示请求超时 | Warning | |
| | | | `LlmStreamParseFailed` | 供应商流格式异常 | 保留已输出内容并提示解析失败 | Error | |
| | | | `AiChatCredentialMissing` | 未配置 AiChat 账号或密码 | 提示检查账号和密码环境变量 | Error,不记录密码 | |
| | | | `AiChatLoginFailed` | 登录失败或账号状态异常 | 显示登录失败、待审批或权限错误 | Warning | |
| | | | `AiChatProjectLoadFailed` | 项目列表不可用 | 项目下拉显示不可用 | Warning | |
| | | | `AiChatQuotaExceeded` | Token 配额耗尽 | 输出区提示配额耗尽 | Warning | |
| | | | `AiChatMemoryPermissionDenied` | 记忆权限不足 | 禁用对应记忆操作 | Warning | |
| | | | `AiChatSseInterrupted` | AiChat SSE 中断 | 保留已输出内容并提示连接中断 | Warning | |
| | | |
| | | 日志规则: |
| | | |
| | | - 可以记录 `requestId`、`modelId`、`provider`、endpoint host、HTTP status。 |
| | | - 不记录完整 API key。 |
| | | - 不记录 AiChat 密码、Session Token 或完整 `x-session-token` 请求头。 |
| | | - 默认不记录完整 prompt;如后续需要调试开关,必须由用户显式启用。 |
| | | |
| | | ## Security Boundaries |
| | |
| | | - `llm.stream` 必须作为插件权限声明,未声明时桥接层拒绝调用。 |
| | | - 插件只能看到 enabled 模型摘要。 |
| | | - 插件不能覆盖 endpoint、provider、authRef 或 apiModel。 |
| | | - 插件不能读取 AiChat 明文密码和 Session Token。 |
| | | - `setConfig` 不允许写入宿主级 LLM 模型注册表。 |
| | | - 本地 HTTP API 如后续暴露 LLM 调用,也必须默认绑定 `127.0.0.1`,并复用同一 `ILlmGatewayService`。 |
| | | - 远程 endpoint 必须经过 URL 校验,禁止 `file://`、相对路径和非 HTTP 协议。 |
| | |
| | | | 只实现 OpenAI-compatible adapter | MVP 可作为第一阶段 | 快速覆盖多数供应商,但保留 provider adapter 扩展点 | |
| | | | 把模型配置放进插件 manifest | 仅作为 fallback | manifest 属于插件包,不适合保存用户真实 endpoint 和密钥引用 | |
| | | | 把模型配置放进 `appsettings.json` | 可行但不推荐 | LLM 配置会增长,独立文件更利于管理和迁移 | |
| | | | 自有 API 模式直接让插件 fetch AiChat | 不采用 | 会把密码、token、错误处理和 SSE 兼容逻辑扩散到前端 | |
| | | | 宿主封装 AiChatClient | 采用 | 统一鉴权、Session、项目、模型、聊天和记忆错误映射 | |
| | | | 自有 API 模式也手动召回记忆 | 不采用 | AiChat 服务自身负责项目和记忆策略,插件重复处理会破坏一致性 | |
| | | |
| | | ## Implementation Tasks |
| | | |
| | |
| | | - LLM 配置和 adapter 单元测试通过。 |
| | | - 使用两个不同 endpoint 的模型可分别路由。 |
| | | |
| | | ### A09 AiChat Client and Session |
| | | |
| | | 输出: |
| | | |
| | | - `AiChatClient` |
| | | - `AiChatSessionService` |
| | | - 登录、重登、`x-session-token` 注入 |
| | | - `GET /api/projects`、`GET /api/chat/models` |
| | | |
| | | 验收: |
| | | |
| | | - `passwordEnv` 优先于明文密码。 |
| | | - 登录成功后 token 只保存在内存态。 |
| | | - 401 后自动重登一次。 |
| | | - 项目列表失败时 UI 可降级而不影响供应商直连聊天。 |
| | | |
| | | ### A10 AiChat API Chat Mode |
| | | |
| | | 输出: |
| | | |
| | | - `mode=aichat-api` 的 `StreamChatAsync` 分支。 |
| | | - `POST /api/chat/send` 调用。 |
| | | - AiChat SSE 解析和事件归一化。 |
| | | |
| | | 验收: |
| | | |
| | | - 所选 `projectId` 会传给 AiChat。 |
| | | - `chunk` 能转换为 `llm.delta`。 |
| | | - `done` 能转换为 `llm.completed`。 |
| | | - `failed` / `aborted` 能转换为可读错误。 |
| | | |
| | | ### A11 Provider Direct Memory Management |
| | | |
| | | 输出: |
| | | |
| | | - `AiChatMemoryService` |
| | | - 记忆能力查询。 |
| | | - 查询、创建、删除、召回接口。 |
| | | - 直连模式下可选把召回内容注入上下文。 |
| | | |
| | | 验收: |
| | | |
| | | - `canViewMemory`、`canManageMemory`、`canUseMemory` 分别控制 UI 能力。 |
| | | - 项目记忆请求必须携带 `projectId`。 |
| | | - 自有 API 模式下不调用记忆召回。 |
| | | |
| | | ### A12 Sample Plugin UI Update |
| | | |
| | | 输出: |
| | | |
| | | - 输入框左侧项目下拉。 |
| | | - 运行模式配置读取。 |
| | | - 模型列表按模式切换。 |
| | | - 记忆管理入口和权限降级状态。 |
| | | |
| | | 验收: |
| | | |
| | | - 两种模式切换后,下拉和提交路径正确刷新。 |
| | | - 项目下拉长名称不撑开输入条。 |
| | | - AiChat 不可用时有短错误且不破坏直连模式。 |
| | | |
| | | ## Verification Plan |
| | | |
| | | ### Unit Tests |
| | |
| | | ### Manual QA |
| | | |
| | | - 配置两个模型,分别指向不同 endpoint,选择不同模型提交后检查路由日志。 |
| | | - 配置 `mode=aichat-api`、AiChat 账号和 `MOLI_AICHAT_PASSWORD`,确认能登录 `http://192.168.1.111:13000` 并加载项目。 |
| | | - 在自有 API 模式下选择项目并提交,确认 AiChat SSE 能流式输出。 |
| | | - 在供应商直连模式下查询、创建、删除和召回 AiChat 项目记忆。 |
| | | - 配置缺失 `authRef`,确认输出区显示鉴权配置错误。 |
| | | - 配置本地 OpenAI-compatible 服务,确认无 key 模型可流式输出。 |
| | | - 断网或关闭本地 endpoint,确认插件输出区显示 endpoint 不可达。 |
| | |
| | | | DeepSeek 是否独立 adapter | 暂不强制 | 如果实际接口与 OpenAI-compatible 差异明显再拆 | |
| | | | 是否暴露本地 HTTP LLM API | 暂不暴露 | 插件桥接先满足需求;外部自动化需要时再设计 | |
| | | | 是否保存 prompt 历史 | 默认不保存 | 用户明确需要历史或调试审计时再评估 | |
| | | |
| | | | AiChat 配置位置 | 先放插件配置,后续可迁移为独立 `llm-runtime.json` | 管理 UI 需要跨插件共享 AiChat 账号时 | |
| | | | AiChat 会话下拉 | MVP 不做 | 用户要求固定会话或查看历史时 | |
| | | | 直连模式召回内容注入方式 | 先作为系统上下文前缀注入 | 后续可做用户确认和引用开关 | |
| | |
| | | - 数据契约统一使用 `displayLayer`,取值仅允许 `desktop`、`normal`、`app-top`、`global-top`。 |
| | | - `LayoutManager` 只负责保存、校验和广播层级意图,不直接操作 Win32。 |
| | | - `DesktopRuntimeCoordinator` 将更新后的布局通过 `IRuntimeSurfaceController` 下发,保证管理窗口、API 和托盘命令走同一运行时路径。 |
| | | - `WidgetWindow` 是最终窗口行为执行点:`desktop` 优先挂载到 Explorer WorkerW 桌面层以避免 Win+D 最小化,失败时降级到底层普通窗口;`normal` 使用普通 WPF 窗口层级,`app-top` 保持本应用内的普通窗口提升语义,`global-top` 才设置全局 `Topmost`。 |
| | | - `WidgetWindow` 是最终窗口行为执行点:`desktop` 优先挂载到 Explorer WorkerW/Progman 桌面宿主并切换为 child 窗口样式,以避免 Win+D 最小化,失败时降级到底层普通窗口;`normal` 使用普通 WPF 窗口层级,`app-top` 保持本应用内的普通窗口提升语义,`global-top` 才设置全局 `Topmost`。 |
| | | - 如果某层级受 Windows 桌面环境限制无法完全精确表达,窗口控制器必须选择更安全的非全局置顶行为,并记录诊断。 |
| | | |
| | | 约束规则: |
| | |
| | | - `locked = true` 时拒绝拖拽和缩放。 |
| | | - `visible = false` 时窗口隐藏但布局保留。 |
| | | - `clickThrough = true` 时由 Win32 扩展样式透传鼠标输入。 |
| | | - `displayLayer` 支持 `desktop`、`normal`、`app-top`、`global-top`:`desktop` 挂到 WorkerW 桌面层并在 Win+D 后继续显示,`normal` 遵循普通窗口层级,`app-top` 只在本应用窗口范围内提升,`global-top` 使用全局置顶并要求托盘/管理窗口可快速撤销。 |
| | | - `displayLayer` 支持 `desktop`、`normal`、`app-top`、`global-top`:`desktop` 挂到 WorkerW/Progman 桌面宿主并在 Win+D 后继续显示,`normal` 遵循普通窗口层级,`app-top` 只在本应用窗口范围内提升,`global-top` 使用全局置顶并要求托盘/管理窗口可快速撤销。 |
| | | |
| | | ### Audio Visualizer Plugin |
| | | |
| | |
| | | | 应用数据根目录 | `%AppData%\DesktopEnhancer` | |
| | | | 配置目录 | `%AppData%\DesktopEnhancer\config` | |
| | | | 插件目录 | `%AppData%\DesktopEnhancer\plugins` | |
| | | | 日志目录 | `%LocalAppData%\DesktopEnhancer\logs` | |
| | | | 日志目录 | 程序目录下的 `logs` | |
| | | | WebView2 数据目录 | `%LocalAppData%\DesktopEnhancer\WebView2` | |
| | | | 源码样例插件目录 | `samples\plugins` | |
| | | | 便携包样例插件目录 | `samples\plugins` | |
| | |
| | | | `plugins[].state` | enum | 插件持久状态,常用值为 `enabled` / `disabled` | |
| | | | `plugins[].updatedAt` | string | 状态更新时间,使用 `DateTimeOffset` JSON 表达 | |
| | | |
| | | 插件扫描时,`IPluginManager` 会将磁盘上的 `plugin.json` 与注册表状态合并。无效 manifest 不会让应用崩溃,会进入错误状态并写入诊断。 |
| | | 插件扫描时,`IPluginManager` 会将磁盘上的 `plugin.json` 与注册表状态合并。无效 manifest 不会让应用崩溃,会进入错误状态并写入诊断。默认样例插件安装和发布更新不会覆盖已有 `plugin.json`;当目标插件目录已经存在配置时,新版本 manifest 会写入 `plugin.template.json`,供用户对照迁移。 |
| | | |
| | | ## layout.json |
| | | |
| | |
| | | - 保存时使用临时文件和备份文件,避免直接覆盖导致配置损坏。 |
| | | - 配置读写异常应记录诊断,不应静默吞掉。 |
| | | |
| | | QA 可通过手工破坏配置文件验证恢复路径,并检查 `%LocalAppData%\DesktopEnhancer\logs` 与运行时诊断列表。 |
| | | QA 可通过手工破坏配置文件验证恢复路径,并检查程序目录下的 `logs` 与运行时诊断列表。 |
| | | |
| | | ## 后续迁移预留 |
| | | |
| New file |
| | |
| | | # LLM 桌面输入插件 AiChat 模式开发任务拆分 |
| | | |
| | | 日期:2026-05-04 |
| | | |
| | | ## 范围 |
| | | |
| | | 本任务包承接 `docs/product/llm-command-palette-plugin-prd.md` 和 `docs/architecture/llm-command-palette-architecture.md`,目标是在现有 `sample.llm-command-palette` 与宿主 LLM 代理基础上完成两种模式增强: |
| | | |
| | | - 供应商直连模式:保留当前能力,并接入 AiChat 记忆管理。 |
| | | - 自有 API 模式:通过 AiChat 登录、项目、模型、聊天和 SSE 接口完成回复。 |
| | | |
| | | AiChat Host 默认使用: |
| | | |
| | | ```text |
| | | http://192.168.1.111:13000 |
| | | ``` |
| | | |
| | | ## D01 配置模型与兼容迁移 |
| | | |
| | | 交付: |
| | | |
| | | - 插件配置支持 `mode`、`aichat.baseUrl`、`aichat.account`、`aichat.defaultProjectId`、`aichat.memory`。 |
| | | - 缺失 `mode` 时按 `provider-direct` 处理。 |
| | | - 缺失 `aichat` 时不影响原供应商直连聊天。 |
| | | - JSON 读写保持 UTF-8。 |
| | | |
| | | 验收: |
| | | |
| | | - 旧版 `plugin.json` 只包含 `defaultModel` / `models` 时仍可加载。 |
| | | - 新版样例 `plugin.json` 默认 `mode=provider-direct`。 |
| | | - 密码环境变量优先于明文密码。 |
| | | |
| | | 依赖:无。 |
| | | |
| | | ## D02 AiChat Session 与基础客户端 |
| | | |
| | | 交付: |
| | | |
| | | - `AiChatSessionService`:登录、token 内存缓存、401 重登一次。 |
| | | - `AiChatClient`:统一封装请求头、错误码、JSON 响应解析。 |
| | | - 支持 `POST /api/auth/login`、`GET /api/auth/me`。 |
| | | |
| | | 验收: |
| | | |
| | | - 登录成功后只在内存保存 `sessionToken`。 |
| | | - 日志不输出密码和 `x-session-token`。 |
| | | - 登录失败、待审批、停用账号能映射为插件可读错误。 |
| | | |
| | | 依赖:D01。 |
| | | |
| | | ## D03 项目与模型列表 |
| | | |
| | | 交付: |
| | | |
| | | - `GET /api/projects` 项目列表加载。 |
| | | - `GET /api/chat/models` 模型列表加载。 |
| | | - 插件桥接新增 `getProjects()`。 |
| | | - 模型下拉根据模式选择宿主模型注册表或 AiChat 模型接口。 |
| | | |
| | | 验收: |
| | | |
| | | - 输入框左侧显示 AiChat 项目下拉。 |
| | | - 项目名称过长不撑开输入条。 |
| | | - AiChat 不可用时项目下拉降级为 `No project`,供应商直连仍可用。 |
| | | |
| | | 依赖:D02。 |
| | | |
| | | ## D04 自有 API 模式聊天 |
| | | |
| | | 交付: |
| | | |
| | | - `mode=aichat-api` 分支。 |
| | | - 调用 `POST /api/chat/send`。 |
| | | - 使用 `generationId` 和 `streamToken` 订阅 SSE。 |
| | | - 解析 `snapshot`、`chunk`、`processing`、`done`、`failed`、`aborted`。 |
| | | |
| | | 验收: |
| | | |
| | | - 选择项目后提交,请求携带 `projectId`。 |
| | | - `chunk.delta` 能流式显示到输出区。 |
| | | - `done` 后状态回到空闲。 |
| | | - `USER_PENDING_APPROVAL`、`TOKEN_TOTAL_LIMIT_REACHED`、`INVALID_MODEL` 等错误显示短错误。 |
| | | |
| | | 依赖:D02、D03。 |
| | | |
| | | ## D05 供应商直连模式记忆管理 |
| | | |
| | | 交付: |
| | | |
| | | - `GET /api/memories` 查询全局/项目记忆。 |
| | | - `POST /api/memories` 创建记忆。 |
| | | - `DELETE /api/memories/{memoryId}` 删除记忆。 |
| | | - `POST /api/memories/recall` 召回记忆。 |
| | | - `GET /api/auth/me` 能力摘要驱动 UI:`canUseMemory`、`canViewMemory`、`canManageMemory`。 |
| | | |
| | | 验收: |
| | | |
| | | - 供应商直连模式下可按选中项目查询、创建、删除和召回记忆。 |
| | | - 权限不足时对应操作禁用。 |
| | | - 自有 API 模式下不执行插件侧记忆召回。 |
| | | |
| | | 依赖:D02、D03。 |
| | | |
| | | ## D06 插件 UI 更新 |
| | | |
| | | 交付: |
| | | |
| | | - 输入框左侧项目下拉。 |
| | | - 右侧模型下拉按模式刷新。 |
| | | - 记忆管理入口和权限降级状态。 |
| | | - 模式切换后刷新项目、模型和提交链路。 |
| | | |
| | | 验收: |
| | | |
| | | - Enter 提交、Shift+Enter 换行、Escape 收起继续可用。 |
| | | - 长项目名、长模型名不会导致输入条跳动。 |
| | | - AiChat 项目/模型加载失败时显示短状态,不弹系统模态框。 |
| | | |
| | | 依赖:D03、D04、D05。 |
| | | |
| | | ## D07 管理窗口与手册同步 |
| | | |
| | | 交付: |
| | | |
| | | - 管理窗口或插件配置入口展示运行模式和 AiChat 配置。 |
| | | - 密码字段支持环境变量说明,不显示明文 token。 |
| | | - 同步更新 `docs/ops/user-manual/plugins/sample.llm-command-palette.md`。 |
| | | |
| | | 验收: |
| | | |
| | | - 用户能找到两种模式、AiChat Host、账号、密码环境变量、项目下拉、记忆限制和故障排查说明。 |
| | | - 后续 QA 前操作手册保持最新。 |
| | | |
| | | 依赖:D01、D06。 |
| | | |
| | | ## D08 测试与验收 |
| | | |
| | | 交付: |
| | | |
| | | - 配置解析单元测试。 |
| | | - AiChat 客户端 fake HTTP 测试。 |
| | | - AiChat SSE 解析测试。 |
| | | - 记忆权限控制测试。 |
| | | - 样例插件静态渲染检查。 |
| | | - QA 验收记录更新。 |
| | | |
| | | 验收: |
| | | |
| | | - `dotnet build .\Moli.Desktop.slnx` 通过。 |
| | | - `dotnet test .\Moli.Desktop.slnx` 通过。 |
| | | - 可用 AiChat 账号下完成一次 `aichat-api` 模式流式回复。 |
| | | - `provider-direct` 模式原有供应商直连能力不回归。 |
| | | - 供应商直连模式下记忆查询、创建、删除、召回至少完成一轮手工验收。 |
| | | |
| | | 依赖:D01-D07。 |
| | | |
| | |
| | | |
| | | - 配置文件目录:`%AppData%\DesktopEnhancer\config` |
| | | - 插件目录:`%AppData%\DesktopEnhancer\plugins` |
| | | - 日志目录:`%LocalAppData%\DesktopEnhancer\logs` |
| | | - 日志目录:程序目录下的 `logs` |
| | | - WebView2 数据目录:`%LocalAppData%\DesktopEnhancer\WebView2` |
| | | |
| | |
| | | | --- | --- | |
| | | | 配置文件 | `%AppData%\DesktopEnhancer\config` | |
| | | | 插件目录 | `%AppData%\DesktopEnhancer\plugins` | |
| | | | 日志目录 | `%LocalAppData%\DesktopEnhancer\logs` | |
| | | | 日志目录 | 程序目录下的 `logs` | |
| | | | WebView2 数据 | `%LocalAppData%\DesktopEnhancer\WebView2` | |
| | | |
| | | ## 安装与启动 |
| | |
| | | | 组件 | 小组件实例列表,可选择组件并显示/隐藏或锁定/解锁 | |
| | | | 插件 | 已扫描插件的名称、类型、状态、入口和错误码 | |
| | | | 诊断 | 诊断记录和插件 manifest 错误摘要 | |
| | | | Log | 加载当天日志,并随管理窗口刷新周期显示新增日志 | |
| | | |
| | | ## 通用组件操作 |
| | | |
| | |
| | | ```text |
| | | %AppData%\DesktopEnhancer\plugins\<pluginId> |
| | | ``` |
| | | |
| | | 发布或默认样例更新时,如果插件目录中已经存在 `plugin.json`,应用会保留现有配置,并把新版本样例配置写入 `plugin.template.json`。首次不存在配置时才会初始化 `plugin.json`。 |
| | | |
| | | 添加本地插件的一般流程: |
| | | |
| | |
| | | |
| | | - 检查 Windows 托盘隐藏区域。 |
| | | - 确认 `Moli.Desktop.exe` 进程是否仍在运行。 |
| | | - 查看 `%LocalAppData%\DesktopEnhancer\logs`。 |
| | | - 查看程序目录下的 `logs`,或打开管理窗口的 “Log” 页面。 |
| | | - 如果从源码运行,先确认 `dotnet build Moli.Desktop.slnx` 成功。 |
| | | |
| | | ### 壁纸或组件没有显示 |
| | |
| | | - 开机启动通过当前用户 HKCU Run 注册表实现。 |
| | | - 管理窗口的“重置布局”是软重置,不会重新创建组件实例。 |
| | | - WebView2 Runtime 缺失、桌面层级和点击穿透行为需要在真实 Windows 桌面环境中验证。 |
| | | |
| | |
| | | |
| | | ## 使用前准备 |
| | | |
| | | 使用该插件前,需要准备至少一个可访问的 LLM 接口。当前版本优先支持 OpenAI-compatible 流式接口,也可以配置 DeepSeek、本地 Ollama/LM Studio 等兼容接口。 |
| | | 使用该插件前,需要根据运行模式准备不同服务: |
| | | |
| | | | 模式 | 需要准备 | |
| | | | --- | --- | |
| | | | 供应商直连模式 | 至少一个可访问的 LLM 接口,例如 OpenAI-compatible、DeepSeek、本地 Ollama/LM Studio 等兼容接口 | |
| | | | 自有 API 模式 | 可访问的 AiChat 服务、已审批账号、密码或密码环境变量 | |
| | | |
| | | AiChat 默认服务地址: |
| | | |
| | | ```text |
| | | http://192.168.1.111:13000 |
| | | ``` |
| | | |
| | | ## 默认行为 |
| | | |
| | | | 项目 | 默认行为 | |
| | | | --- | --- | |
| | | | 位置 | 主屏顶部居中,顶部保留约 `32px` 空隙 | |
| | | | 默认模式 | 供应商直连模式 | |
| | | | 左侧下拉 | AiChat 项目列表 | |
| | | | 显示层级 | `desktop` | |
| | | | 点击穿透 | 关闭,便于接收键盘和鼠标输入 | |
| | | | 锁定状态 | 锁定,避免误拖动 | |
| | | | 提交方式 | Enter 提交,不提供提交按钮 | |
| | | | 换行方式 | Shift+Enter | |
| | | | 输出区域 | 输入框底部展开,最大高度约为屏幕高度 `50%` | |
| | | |
| | | ## 选择运行模式 |
| | | |
| | | LLM 插件支持两种模式: |
| | | |
| | | | 模式 | 配置值 | 行为 | |
| | | | --- | --- | --- | |
| | | | 供应商直连模式 | `provider-direct` | 使用 Moli.Desktop 宿主 LLM 代理调用供应商模型;可复用 AiChat 记忆接口 | |
| | | | 自有 API 模式 | `aichat-api` | 使用 AiChat 项目、模型和聊天 SSE;插件不单独处理记忆 | |
| | | |
| | | 插件配置示例: |
| | | |
| | | ```json |
| | | { |
| | | "mode": "provider-direct", |
| | | "aichat": { |
| | | "baseUrl": "http://192.168.1.111:13000", |
| | | "account": { |
| | | "email": "user@example.com", |
| | | "password": null, |
| | | "passwordEnv": "MOLI_AICHAT_PASSWORD" |
| | | }, |
| | | "defaultProjectId": "", |
| | | "memory": { |
| | | "enabledInProviderDirect": true, |
| | | "defaultScope": "PROJECT", |
| | | "recallLimit": 8 |
| | | } |
| | | } |
| | | } |
| | | ``` |
| | | |
| | | 缺少 `mode` 时,插件按 `provider-direct` 处理,以兼容旧配置。 |
| | | |
| | | ## 配置 AiChat 账号 |
| | | |
| | | AiChat 账号信息只用于插件与 AiChat 服务交互。 |
| | | |
| | | 账号允许直接写在配置中: |
| | | |
| | | ```json |
| | | { |
| | | "email": "user@example.com" |
| | | } |
| | | ``` |
| | | |
| | | 密码建议使用环境变量。配置中的 `passwordEnv` 优先于明文 `password`: |
| | | |
| | | ```powershell |
| | | [Environment]::SetEnvironmentVariable( |
| | | "MOLI_AICHAT_PASSWORD", |
| | | "你的 AiChat 密码", |
| | | "User" |
| | | ) |
| | | ``` |
| | | |
| | | 设置后请重启 Moli.Desktop,让新环境变量对桌面进程生效。登录成功后的 Session Token 只保存在宿主运行态,不写入插件配置。 |
| | | |
| | | ## 配置模型 |
| | | |
| | |
| | | |
| | | 当前 `deepseek`、`ollama` 和 `local-openai-compatible` 会复用 OpenAI-compatible 适配器。如果某个供应商接口不兼容 OpenAI-compatible 流式格式,需要后续新增独立适配器。 |
| | | |
| | | 自有 API 模式下,模型列表来自 AiChat: |
| | | |
| | | ```text |
| | | GET /api/chat/models |
| | | ``` |
| | | |
| | | 插件只展示 AiChat 返回的可用模型,并在提交时把所选模型作为 `modelName` 传给 AiChat。 |
| | | |
| | | ## 配置密钥 |
| | | |
| | | 当前版本使用环境变量作为密钥 fallback。`authRef` 会按以下方式解析: |
| | |
| | | 1. 启动 Moli.Desktop。 |
| | | 2. 确认 `sample.llm-command-palette` 已在“插件”页面中启用。 |
| | | 3. 在桌面顶部找到半透明输入条。 |
| | | 4. 在右侧模型下拉中选择模型。 |
| | | 5. 输入问题。 |
| | | 6. 按 Enter 提交。 |
| | | 7. 在输入框下方查看流式输出。 |
| | | 4. 在左侧项目下拉中选择 AiChat 项目。 |
| | | 5. 在右侧模型下拉中选择模型。 |
| | | 6. 输入问题。 |
| | | 7. 按 Enter 提交。 |
| | | 8. 在输入框下方查看流式输出。 |
| | | |
| | | 项目下拉说明: |
| | | |
| | | | 状态 | 含义 | |
| | | | --- | --- | |
| | | | 显示项目名称 | 已成功调用 AiChat `GET /api/projects` | |
| | | | `No project` | 未配置 AiChat、登录失败或项目列表为空 | |
| | | | 登录/权限错误 | 检查账号审批状态、密码环境变量和 AiChat 服务地址 | |
| | | |
| | | 在自有 API 模式下,提交会携带当前项目 ID。未选择项目时,AiChat 会按自身接口规则使用或创建默认项目,但建议明确选择项目。 |
| | | |
| | | 项目和模型下拉使用插件自绘的圆角扁平控件。展开下拉时,输入条会临时请求宿主增高组件窗口,避免选项列表被原始组件高度裁剪;选择完成或点击外部后会恢复到默认高度。 |
| | | |
| | | ## 记忆管理 |
| | | |
| | | 供应商直连模式下,插件可以使用 AiChat 记忆接口: |
| | | |
| | | | 操作 | AiChat 接口 | |
| | | | --- | --- | |
| | | | 查询记忆 | `GET /api/memories?scope={scope}&projectId={projectId}` | |
| | | | 创建记忆 | `POST /api/memories` | |
| | | | 删除记忆 | `DELETE /api/memories/{memoryId}` | |
| | | | 召回记忆 | `POST /api/memories/recall` | |
| | | |
| | | 权限来自 AiChat 当前用户: |
| | | |
| | | - `canViewMemory` 控制是否能查看记忆。 |
| | | - `canManageMemory` 控制是否能创建或删除记忆。 |
| | | - `canUseMemory` 控制是否能召回记忆并用于直连模型上下文。 |
| | | |
| | | 自有 API 模式下,插件不单独展示或执行记忆管理。聊天中的记忆使用由 AiChat 服务和项目设置处理。 |
| | | |
| | | 快捷操作: |
| | | |
| | |
| | | - 检查 `%AppData%\DesktopEnhancer\config\llm-models.json` 是否存在。 |
| | | - 确认至少有一个模型的 `enabled` 为 `true`。 |
| | | - 确认模型的 `endpoint` 是 `http` 或 `https` 绝对 URL。 |
| | | - 如果当前是自有 API 模式,检查 AiChat `GET /api/chat/models` 是否可用。 |
| | | - 修正配置后重启应用,或在管理窗口中重载插件。 |
| | | |
| | | ### 项目下拉为空 |
| | | |
| | | - 检查 AiChat 服务地址是否为 `http://192.168.1.111:13000` 或你的实际配置。 |
| | | - 检查账号和密码环境变量是否正确。 |
| | | - 调用 AiChat `GET /api/auth/me` 确认账号已审批。 |
| | | - 调用 AiChat `GET /api/projects` 确认账号有项目。 |
| | | |
| | | ### 自有 API 模式无法输出 |
| | | |
| | | - 检查 AiChat 登录是否成功。 |
| | | - 检查所选模型是否在 AiChat `GET /api/chat/models` 返回列表中。 |
| | | - 如果返回 `TOKEN_TOTAL_LIMIT_REACHED`,需要在 AiChat 中申请或调整 Token 配额。 |
| | | - 如果返回 `INVALID_MODEL`,需要在 AiChat 服务端启用对应模型。 |
| | | - 如果 SSE 中断,保留已输出内容后重试。 |
| | | |
| | | ### 请求提示密钥缺失 |
| | | |
| | |
| | | - 如果是远程供应商,确认当前网络可访问该供应商 API。 |
| | | - 检查日志目录 `%LocalAppData%\DesktopEnhancer\logs`,日志只会记录 endpoint host,不会记录完整 API key。 |
| | | |
| | | ### 记忆功能不可用 |
| | | |
| | | - 记忆管理只在供应商直连模式下由插件处理。 |
| | | - 检查 AiChat 当前用户是否有 `canUseMemory`、`canViewMemory` 或 `canManageMemory` 权限。 |
| | | - 项目记忆必须选择项目后使用。 |
| | | |
| | | ### 没有流式输出 |
| | | |
| | | - 确认上游接口支持 OpenAI-compatible SSE 流式输出。 |
| | |
| | | - 模型配置当前主要通过手工编辑 `llm-models.json` 完成。 |
| | | - 密钥当前使用环境变量 fallback,Windows Credential Manager 管理界面尚未实现。 |
| | | - 当前已实现 OpenAI-compatible 流式协议;非兼容供应商需要后续新增适配器。 |
| | | |
| | | - 自有 API 模式暂不在插件中提供会话下拉,提交时使用所选项目的默认会话规则。 |
| | | - 自有 API 模式不在插件中管理记忆。 |
| | |
| | | - `global-top`:全局置顶,允许覆盖其他应用窗口。 |
| | | - 壁纸类内容默认使用 `desktop`;普通信息类小组件默认使用 `desktop` 或 `normal`;需要跨应用提醒、悬浮控制或演示场景的组件才应使用 `app-top` 或 `global-top`。 |
| | | - 用户必须能够按组件实例切换显示层级,且切换结果必须持久化。 |
| | | - `desktop` 层组件必须在用户触发 Win+D 显示桌面后仍保持可见;系统不支持 WorkerW 挂载时允许降级,但必须记录诊断并在 QA 记录中标注该环境限制。 |
| | | - `desktop` 层组件必须在用户触发 Win+D 显示桌面后仍保持可见;系统不支持 WorkerW/Progman 桌面宿主挂载时允许降级,但必须记录诊断并在 QA 记录中标注该环境限制。 |
| | | - 组件必须支持在编辑模式下拖拽和缩放。 |
| | | - 已锁定组件必须拒绝拖拽和缩放操作。 |
| | | - 应用必须支持按组件维度的配置。 |
| | |
| | | |
| | | - 提供一个顶部居中的 LLM 输入插件,默认在屏幕顶部保留呼吸空隙。 |
| | | - 支持用户输入文本后按回车提交,不提供独立提交按钮。 |
| | | - 支持在输入框右侧嵌入模型下拉选择。 |
| | | - 支持两种运行模式,并可通过插件配置选择: |
| | | - 供应商直连模式:继续使用当前宿主 LLM 代理,按 `modelId` 直连 OpenAI-compatible、DeepSeek、本地模型等供应商。 |
| | | - 自有 API 模式:接入自有 `AiChat` 服务,统一 Host 默认为 `http://192.168.1.111:13000`。 |
| | | - 支持在输入框左侧嵌入 AiChat 项目下拉;右侧保留模型下拉。 |
| | | - 支持多个 LLM 模型,模型清单来自插件配置或宿主配置。 |
| | | - 支持调用 LLM 接口并将结果流式展示在输入框下方。 |
| | | - 支持在供应商直连模式下通过 AiChat API 进行记忆查询、创建、删除和召回管理。 |
| | | - 支持在自有 API 模式下使用 AiChat 项目上下文发起聊天;该模式下不处理插件侧记忆管理。 |
| | | - 支持在插件配置中维护 AiChat 服务交互所需的用户信息,账号允许明文配置,密码允许引用环境变量。 |
| | | - 输出区域与输入框保持同宽、同视觉风格,最大高度不超过屏幕高度的 `50%`。 |
| | | - 保持桌面浮层轻量、透明、可读、可恢复控制。 |
| | | |
| | |
| | | |
| | | - 不做完整多会话聊天应用。 |
| | | - 不在插件内实现账号体系、计费管理或复杂知识库。 |
| | | - 不在 Moli.Desktop 内重新实现 AiChat 的项目、会话、审批、权限和配额系统。 |
| | | - 不在自有 API 模式下重复实现记忆管理;记忆由 AiChat 自身聊天链路和项目设置处理。 |
| | | - 不在 MVP 中支持文件上传、图片理解、语音输入或多模态输出。 |
| | | - 不要求替代管理窗口或系统托盘入口。 |
| | | - 不把 LLM API key 明文写入插件前端源码。 |
| | |
| | | ## 用户故事 |
| | | |
| | | - 作为用户,我可以在桌面顶部直接输入问题并按回车提交,这样我能快速得到 LLM 回复。 |
| | | - 作为用户,我可以在插件配置中选择供应商直连或 AiChat 自有 API,这样同一个桌面输入条既能调用外部模型,也能进入自有服务的项目上下文。 |
| | | - 作为用户,我可以在输入框左侧选择 AiChat 项目,这样每次提问都能进入对应项目和默认会话。 |
| | | - 作为用户,我可以在输入框右侧切换模型,这样我能按任务选择更快或更强的模型。 |
| | | - 作为用户,我可以在回复生成时看到逐步流式输出,这样我知道请求正在进行。 |
| | | - 作为用户,我可以继续编辑输入内容、复制输出内容或按 Escape 收起结果,这样桌面不会被长文本长期占据。 |
| | | - 作为用户,我可以通过管理窗口或配置维护不同供应商的模型、endpoint 和默认模型,这样插件能同时接入 OpenAI-compatible、DeepSeek、本地模型或后续新增供应商。 |
| | | - 作为用户,我可以在供应商直连模式下查看、手动添加、删除和召回 AiChat 记忆,这样直连供应商时也能复用我在 AiChat 中维护的长期记忆。 |
| | | - 作为用户,我可以把 AiChat 密码放在环境变量里,这样配置文件不需要保存密码明文。 |
| | | |
| | | ## 插件类型 |
| | | |
| | |
| | | |
| | | - 输入条为单行优先,长文本可在达到宽度后轻微增高到最多 3 行。 |
| | | - 占位文案:`What can I help you with today?` 或后续本地化为中文。 |
| | | - 左侧展示状态图标: |
| | | - 输入框左侧展示项目下拉: |
| | | - 自有 API 模式下必须从 AiChat `GET /api/projects` 获取项目列表。 |
| | | - 供应商直连模式下如果已配置 AiChat 账号,也应显示项目下拉,用于记忆查询、创建、删除和召回的项目上下文。 |
| | | - 未登录、未配置或接口不可用时显示明确降级状态,例如 `No project`,不阻塞无项目直连提问。 |
| | | - 项目下拉左侧或输入条前缀位置展示状态图标: |
| | | - 空闲:品牌或星芒图标。 |
| | | - 请求中:细小旋转状态。 |
| | | - 错误:低饱和警示状态。 |
| | |
| | | |
| | | ## 模型配置 |
| | | |
| | | 插件前端只需要知道可展示的模型清单和默认模型。具体供应商、endpoint、鉴权方式和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `modelId`。 |
| | | 插件配置必须显式区分运行模式。插件前端只需要知道可展示的项目、模型清单和默认模型。具体供应商、endpoint、鉴权方式、AiChat 登录态和请求适配应优先由宿主侧 LLM 代理管理,插件提交时只传 `mode`、`projectId`、`modelId` 和消息内容。 |
| | | |
| | | ### 运行模式 |
| | | |
| | | | 模式 | 配置值 | 聊天入口 | 模型来源 | 记忆管理 | |
| | | | --- | --- | --- | --- | --- | |
| | | | 供应商直连模式 | `provider-direct` | `window.moliDesktop.llm.streamChat` -> 供应商适配器 | `llm-models.json` 或宿主模型注册表 | 通过 AiChat 记忆接口管理和召回 | |
| | | | 自有 API 模式 | `aichat-api` | AiChat `POST /api/chat/send` + SSE | AiChat `GET /api/chat/models` | 插件无需处理,交由 AiChat 聊天链路 | |
| | | |
| | | 模式切换规则: |
| | | |
| | | - 默认保持 `provider-direct`,保证现有行为不被破坏。 |
| | | - 切换到 `aichat-api` 后,插件必须先登录 AiChat 并获取项目列表。 |
| | | - `aichat-api` 模式下提交消息时应传入当前 `projectId`;如未选项目,可由 AiChat 按接口规则使用或创建默认项目,但 UI 应尽量选择明确项目。 |
| | | - 两种模式都不得把密码、Session Token、供应商 API key 暴露给插件页面日志或可复制错误信息。 |
| | | |
| | | ### AiChat 用户配置 |
| | | |
| | | AiChat 服务配置属于插件运行配置,但凭据解析由宿主执行。统一 Host 不参考 AiChat 接口文档,以用户给定值为准: |
| | | |
| | | ```json |
| | | { |
| | | "mode": "provider-direct", |
| | | "aichat": { |
| | | "baseUrl": "http://192.168.1.111:13000", |
| | | "account": { |
| | | "email": "user@example.com", |
| | | "password": null, |
| | | "passwordEnv": "MOLI_AICHAT_PASSWORD" |
| | | }, |
| | | "defaultProjectId": "", |
| | | "memory": { |
| | | "enabledInProviderDirect": true, |
| | | "defaultScope": "PROJECT", |
| | | "recallLimit": 8 |
| | | } |
| | | } |
| | | } |
| | | ``` |
| | | |
| | | 字段说明: |
| | | |
| | | | 字段 | 说明 | |
| | | | --- | --- | |
| | | | `mode` | `provider-direct` 或 `aichat-api`,默认 `provider-direct`。 | |
| | | | `aichat.baseUrl` | AiChat 服务 Host,默认 `http://192.168.1.111:13000`。 | |
| | | | `aichat.account.email` | AiChat 登录账号,允许明文配置。 | |
| | | | `aichat.account.password` | AiChat 登录密码明文,仅允许个人本地测试,不推荐。 | |
| | | | `aichat.account.passwordEnv` | 密码环境变量名,优先级高于 `password`。 | |
| | | | `aichat.defaultProjectId` | 默认选中的 AiChat 项目 ID,可为空。 | |
| | | | `aichat.memory.enabledInProviderDirect` | 供应商直连模式下是否启用 AiChat 记忆管理。 | |
| | | | `aichat.memory.defaultScope` | `GLOBAL`、`PROJECT` 或 `ALL`,用于召回和记忆管理默认范围。 | |
| | | | `aichat.memory.recallLimit` | 召回数量,建议 `1..20`。 | |
| | | |
| | | AiChat 鉴权流程: |
| | | |
| | | 1. `POST /api/auth/login`,请求体包含 `email` 和解析后的密码。 |
| | | 2. 保存响应 `data.sessionToken` 到宿主内存态。 |
| | | 3. 后续请求携带 `x-session-token: <sessionToken>`。 |
| | | 4. 可选调用 `GET /api/auth/me` 校验审批状态、记忆权限和项目权限。 |
| | | 5. Session 过期或返回 `401` 时重新登录一次;仍失败则在插件输出区展示可操作错误。 |
| | | |
| | | 推荐采用“按模型路由”的配置结构:每个模型都可以绑定独立 provider、URL、鉴权引用和请求适配参数。这样同一个插件可以同时接入不同供应商,也可以接入同一供应商的不同 base URL。 |
| | | |
| | |
| | | |
| | | ```javascript |
| | | window.moliDesktop.llm.streamChat({ |
| | | mode: "provider-direct", |
| | | projectId: "aichat_project_id", |
| | | modelId: "gpt-5.4", |
| | | messages: [ |
| | | { role: "user", content: "..." } |
| | |
| | | ``` |
| | | |
| | | 插件不应直接传 provider、endpoint 或密钥。宿主响应中可返回本次请求实际命中的供应商和模型,用于诊断和 UI tooltip,但不返回密钥。 |
| | | |
| | | 新增 AiChat 相关桥接能力建议: |
| | | |
| | | ```typescript |
| | | window.moliDesktop.llm = { |
| | | getConnectionMode(): Promise<"provider-direct" | "aichat-api">; |
| | | setConnectionMode(mode: "provider-direct" | "aichat-api"): Promise<void>; |
| | | getProjects(): Promise<Array<{ id: string; name: string; projectType: "CHAT" | "REMOTE"; memoryMode: string }>>; |
| | | getMemories(options: { scope?: "GLOBAL" | "PROJECT"; projectId?: string }): Promise<object>; |
| | | createMemory(input: { scope: "GLOBAL" | "PROJECT"; projectId?: string; content: string }): Promise<object>; |
| | | deleteMemory(memoryId: string): Promise<void>; |
| | | recallMemories(input: { query: string; scope?: "GLOBAL" | "PROJECT" | "ALL"; projectId?: string; limit?: number }): Promise<object>; |
| | | }; |
| | | ``` |
| | | |
| | | 项目下拉数据来自 AiChat `GET /api/projects`。记忆管理接口来自 AiChat: |
| | | |
| | | - `GET /api/memories?scope={scope}&projectId={projectId}` |
| | | - `POST /api/memories` |
| | | - `DELETE /api/memories/{memoryId}` |
| | | - `POST /api/memories/recall` |
| | | |
| | | 自有 API 模式聊天调用: |
| | | |
| | | - `POST /api/chat/send` |
| | | - `GET /api/chat/generations/{generationId}/stream?token={streamToken}` |
| | | |
| | | 自有 API 模式可使用 AiChat 项目和会话规则;插件 MVP 不必提供会话下拉,只需以所选 `projectId` 提交,让 AiChat 使用或创建该项目默认会话。 |
| | | |
| | | 流式事件建议: |
| | | |
| | |
| | | ### FR-LLM-02 模型选择 |
| | | |
| | | - 插件必须在输入框右侧提供模型下拉。 |
| | | - 模型下拉必须从配置读取模型清单。 |
| | | - 供应商直连模式下,模型下拉必须从宿主 LLM 模型注册表读取模型清单。 |
| | | - 自有 API 模式下,模型下拉必须优先从 AiChat `GET /api/chat/models` 读取模型清单。 |
| | | - 模型切换必须影响下一次提交。 |
| | | - 当前请求进行中时,模型切换不得影响已发出的请求。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-07 运行模式选择 |
| | | |
| | | - 插件必须支持 `provider-direct` 和 `aichat-api` 两种运行模式。 |
| | | - 模式必须可通过插件配置选择,并能在后续管理 UI 中展示。 |
| | | - 默认模式必须为 `provider-direct`,保证现有供应商直连行为兼容。 |
| | | - 模式切换后,项目下拉、模型下拉、聊天提交路径和记忆入口必须按模式刷新。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-08 AiChat 项目下拉 |
| | | |
| | | - 输入框左侧必须提供 AiChat 项目下拉列表。 |
| | | - 项目列表必须调用 AiChat `GET /api/projects` 获取。 |
| | | - 登录失败、账号未审批、无权限或接口不可达时,项目下拉必须展示可理解降级状态。 |
| | | - 自有 API 模式下提交聊天时必须使用当前选中项目;未选项目时允许按 AiChat 默认项目规则降级。 |
| | | - 供应商直连模式下,项目选择用于记忆管理和召回上下文,不得强制阻塞直连聊天。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-09 AiChat 用户配置 |
| | | |
| | | - 插件配置必须包含 AiChat `baseUrl`、账号和密码引用。 |
| | | - `baseUrl` 默认值为 `http://192.168.1.111:13000`。 |
| | | - 账号允许明文配置。 |
| | | - 密码必须支持环境变量引用,且环境变量值优先于明文字段。 |
| | | - 登录成功后的 `sessionToken` 必须只保存在宿主运行态,不写入插件前端或普通配置文件。 |
| | | - 日志不得输出密码、Session Token 或完整请求头。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-10 自有 API 模式聊天 |
| | | |
| | | - 自有 API 模式下,插件必须通过 AiChat `POST /api/chat/send` 发起聊天。 |
| | | - 插件必须使用 AiChat 返回的 `generationId` 和 `streamToken` 订阅 SSE。 |
| | | - 插件必须处理 `snapshot`、`chunk`、`processing`、`done`、`failed` 和 `aborted` 事件。 |
| | | - 插件必须把 AiChat 错误码映射为可理解错误,例如未登录、待审批、模型不可用、配额耗尽和消息数超限。 |
| | | - 自有 API 模式下无需插件侧记忆管理;不得重复调用记忆召回接口拼装 Prompt。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-11 供应商直连模式记忆管理 |
| | | |
| | | - 供应商直连模式下,如果配置了 AiChat 账号且用户具备权限,插件必须支持 AiChat 记忆管理。 |
| | | - 插件必须支持查询全局记忆和项目记忆。 |
| | | - 插件必须支持手动创建全局记忆和项目记忆。 |
| | | - 插件必须支持删除记忆。 |
| | | - 插件必须支持按当前输入和选中项目调用 `POST /api/memories/recall` 召回记忆。 |
| | | - 召回结果可作为供应商直连请求的上下文注入,但必须遵守项目隔离和用户权限。 |
| | | - 如果 AiChat 返回 `canUseMemory=false`、`canViewMemory=false` 或 `canManageMemory=false`,插件必须按权限隐藏或禁用对应操作。 |
| | | |
| | | 优先级:P1 |
| | | |
| | | ### FR-LLM-12 配置兼容与迁移 |
| | | |
| | | - 现有仅包含 `defaultModel` 和 `models` 的插件配置必须继续可用。 |
| | | - 缺失 `mode` 时按 `provider-direct` 处理。 |
| | | - 缺失 `aichat` 配置时,项目下拉和记忆功能降级为不可用,但供应商直连聊天仍可用。 |
| | | - 配置文件必须以 UTF-8 读写。 |
| | | |
| | | 优先级:P1 |
| | | |
| | |
| | | - 首版插件无沙箱隔离,但 LLM 请求能力必须通过明确权限声明。 |
| | | - 宿主代理 LLM 请求时,应限制插件只能使用已启用的模型 id,并由宿主解析对应 endpoint。 |
| | | - 日志不得记录完整 API key。 |
| | | - 日志不得记录 AiChat 密码、Session Token 或完整 `x-session-token` 请求头。 |
| | | - 默认不把用户输入内容写入持久化配置。 |
| | | - 供应商直连模式使用记忆召回时,应只把用户确认启用的召回内容加入上下文,并避免在诊断日志中记录完整记忆内容。 |
| | | |
| | | ## 验收标准 |
| | | |
| | | - 当插件首次安装并启用时,输入条出现在主屏顶部居中,顶部留有约 `32px` 空隙。 |
| | | - 当插件配置 `mode=provider-direct` 时,原有供应商直连流式输出链路仍可使用。 |
| | | - 当插件配置 `mode=aichat-api` 时,插件通过 `http://192.168.1.111:13000` 登录 AiChat,并使用 AiChat 聊天接口完成一次流式回复。 |
| | | - 当 AiChat 密码配置为环境变量时,插件能读取环境变量完成登录,配置文件中不需要保存密码明文。 |
| | | - 当登录成功后,输入框左侧项目下拉显示 AiChat `GET /api/projects` 返回的项目。 |
| | | - 当用户选择不同项目后提交时,自有 API 模式请求携带对应 `projectId`。 |
| | | - 当用户输入文本并按 Enter 时,插件发起一次 LLM 请求,且没有提交按钮。 |
| | | - 当用户选择不同模型后再提交时,请求使用新模型。 |
| | | - 当不同模型配置了不同供应商和 endpoint 时,宿主应按所选 `modelId` 路由到对应 API。 |
| | | - 当供应商直连模式启用 AiChat 记忆管理时,用户可以查询、创建、删除和召回当前项目记忆。 |
| | | - 当自有 API 模式启用时,插件不展示或不执行插件侧记忆管理动作,聊天记忆由 AiChat 服务处理。 |
| | | - 当 LLM 返回内容时,输出区域在输入框底部展开,并逐步显示流式文本。 |
| | | - 当输出内容超过屏幕高度 `50%` 时,输出区域内部滚动,插件不会继续向下无限扩张。 |
| | | - 当用户按 Escape 时,已展开输出区域可以收起。 |
| | | - 当 endpoint 不可用或鉴权失败时,输出区域展示可理解错误,不导致宿主崩溃。 |
| | | - 当应用重启后,插件位置、尺寸、默认模型和显示层级从配置恢复。 |
| | | - 当插件处于默认 `desktop` 层时,它不应覆盖普通应用窗口;切换到 `global-top` 时必须可通过托盘或管理窗口恢复。 |
| | | - 当 AiChat 返回 `USER_PENDING_APPROVAL`、`PERMISSION_DENIED`、`TOKEN_TOTAL_LIMIT_REACHED` 或 `INVALID_MODEL` 时,插件必须显示短错误并允许用户修改配置或重试。 |
| | | |
| | | ## 用户操作手册影响范围 |
| | | |
| | | 本需求会改变用户可见配置和插件操作,后续开发完成后必须同步更新操作手册,至少包括: |
| | | |
| | | - LLM 插件的两种运行模式说明。 |
| | | - AiChat Host、账号、密码环境变量配置方式。 |
| | | - 项目下拉的来源、刷新、失败状态和默认项目行为。 |
| | | - 供应商直连模式下的记忆查询、创建、删除和召回操作。 |
| | | - 自有 API 模式下“不在插件中管理记忆”的限制说明。 |
| | | - 常见故障排查:登录失败、账号未审批、项目列表为空、模型列表为空、配额耗尽、记忆权限不足、SSE 中断。 |
| | | |
| | | ## 待澄清问题 |
| | | |
| | |
| | | | 是否保留历史记录 | MVP 不保留,仅保留当前结果 | |
| | | | 是否支持停止生成 | MVP 可暂不支持,后续新增停止按钮或 Escape 二次行为 | |
| | | | 是否全局快捷键唤起 | 后续版本考虑,例如 `Alt+Space` 或用户自定义快捷键 | |
| | | | AiChat Host | 固定默认 `http://192.168.1.111:13000`,不从接口文档环境表推导 | |
| | | | AiChat 密码配置 | 优先使用环境变量,允许本地个人测试明文密码 | |
| | | | 自有 API 模式记忆 | 插件不处理记忆管理,由 AiChat 服务聊天链路处理 | |
| | |
| | | |
| | | - 在真实 Windows 11 桌面环境分别切换 `desktop`、`normal`、`app-top`、`global-top`,观察窗口遮挡行为。 |
| | | - 验证 `desktop` 不覆盖普通应用窗口。 |
| | | - 验证 `desktop` 组件在按下 Win+D 后仍显示在桌面上;若 WorkerW 挂载失败,应在诊断日志中看到降级原因。 |
| | | - 验证 `desktop` 组件在按下 Win+D 后仍显示在桌面上;诊断日志应显示 `WorkerW` 策略选中,并记录实际宿主 `WorkerW` 或 `Progman`。若桌面宿主挂载失败,应在诊断日志中看到降级原因。 |
| | | - 验证 `global-top` 可覆盖其他应用窗口,并可通过管理窗口或托盘恢复为安全层级。 |
| | | - 验证多显示器和 DPI 缩放下层级语义保持一致。 |
| New file |
| | |
| | | # LLM 桌面输入插件 AiChat 模式验收记录 |
| | | |
| | | 日期:2026-05-04 |
| | | |
| | | ## 范围 |
| | | |
| | | 本次验收覆盖 `sample.llm-command-palette` 的两种模式增强: |
| | | |
| | | - 供应商直连模式继续走宿主 LLM 模型注册表和 provider adapter。 |
| | | - 自有 API 模式走 AiChat 登录、项目、模型、聊天发送和 SSE。 |
| | | - 供应商直连模式下通过 AiChat 进行记忆查询、创建、删除和召回。 |
| | | - 插件 UI 左侧项目下拉、右侧模型下拉和记忆入口。 |
| | | - 用户操作手册同步。 |
| | | |
| | | ## 验收结论 |
| | | |
| | | 通过。 |
| | | |
| | | 当前实现已满足本轮开发验收条件。真实 AiChat 账号、审批状态、模型配额和内网服务可用性仍需要在目标环境做一次人工端到端联调。 |
| | | |
| | | ## 执行结果 |
| | | |
| | | | 项目 | 命令或方法 | 结果 | |
| | | | --- | --- | --- | |
| | | | 构建 | `dotnet build .\Moli.Desktop.slnx` | 通过,0 warning,0 error | |
| | | | 自动化测试 | `dotnet test .\Moli.Desktop.slnx` | 通过,43/43 | |
| | | | 样例插件渲染 | Edge headless 打开 `samples/plugins/sample.llm-command-palette/index.html` | 通过,生成截图 | |
| | | | 像素检查 | 采样截图像素 | 通过,`Sampled=2340 NonWhite=2340 NonTransparent=2340` | |
| | | |
| | | 渲染截图: |
| | | |
| | | - `artifacts/llm-command-palette-aichat-mode-render-check.png` |
| | | |
| | | ## 功能验收 |
| | | |
| | | | 验收点 | 结果 | 说明 | |
| | | | --- | --- | --- | |
| | | | 默认保持供应商直连模式 | 通过 | `plugin.json` 默认 `mode=provider-direct` | |
| | | | AiChat Host 默认值 | 通过 | 配置默认 `http://192.168.1.111:13000` | |
| | | | 密码环境变量 | 通过 | `AiChatClientTests` 验证 `passwordEnv` 优先于明文密码 | |
| | | | Session Token 边界 | 通过 | token 仅由宿主 `AiChatClient` 注入请求头,桥接不返回 token | |
| | | | 项目下拉数据 | 通过 | 桥接新增 `llm.getProjects`,测试覆盖项目返回 | |
| | | | AiChat 模型列表 | 通过 | `mode=aichat-api` 时可从 `GET /api/chat/models` 生成安全模型摘要 | |
| | | | 自有 API 聊天 | 通过 | 测试覆盖 `POST /api/chat/send` 与生成 SSE 解析 | |
| | | | SSE 事件映射 | 通过 | `chunk` -> `llm.delta`,`done` -> `llm.completed` | |
| | | | 直连模式记忆召回 | 通过 | 桥接和客户端测试覆盖 `POST /api/memories/recall` | |
| | | | 记忆管理接口 | 通过 | 桥接支持查询、创建、删除和召回 | |
| | | | UI 渲染 | 通过 | 截图显示左侧 `No project`、输入框、记忆按钮和右侧模型下拉 | |
| | | | 操作手册同步 | 通过 | 已更新 `docs/ops/user-manual/plugins/sample.llm-command-palette.md` | |
| | | |
| | | ## 风险与后续 |
| | | |
| | | - 本次使用 fake HTTP 覆盖 AiChat API 合同,未使用真实账号访问 `http://192.168.1.111:13000`。 |
| | | - 插件 UI 目前提供轻量记忆面板;后续如需要更完整的记忆编辑体验,应进入管理窗口实现。 |
| | | - 自有 API 模式暂未提供会话下拉,按 AiChat 项目默认会话规则提交。 |
| | | - Windows Credential Manager 仍未实现,密码生产路径当前为环境变量。 |
| | | |
| 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 Demo</title> |
| | | <style> |
| | | :root { |
| | | color-scheme: dark; |
| | | font-family: "Segoe UI", system-ui, sans-serif; |
| | | background: #11100f; |
| | | } |
| | | |
| | | * { |
| | | box-sizing: border-box; |
| | | } |
| | | |
| | | html, |
| | | body { |
| | | width: 100%; |
| | | min-height: 100%; |
| | | margin: 0; |
| | | background: |
| | | radial-gradient(circle at 18% 18%, rgba(255, 130, 88, 0.16), transparent 28%), |
| | | linear-gradient(135deg, #151312 0%, #23201f 52%, #11100f 100%); |
| | | overflow: hidden; |
| | | } |
| | | |
| | | body { |
| | | padding: 8px; |
| | | } |
| | | |
| | | .shell { |
| | | width: 100%; |
| | | color: rgba(255, 255, 255, 0.92); |
| | | } |
| | | |
| | | .bar, |
| | | .output, |
| | | .memory { |
| | | width: 100%; |
| | | border: 1px solid rgba(255, 255, 255, 0.14); |
| | | background: rgba(28, 26, 25, 0.72); |
| | | box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18); |
| | | backdrop-filter: blur(18px); |
| | | } |
| | | |
| | | .bar { |
| | | display: grid; |
| | | grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px); |
| | | align-items: center; |
| | | gap: 14px; |
| | | min-height: 56px; |
| | | padding: 0 20px; |
| | | border-radius: 20px; |
| | | } |
| | | |
| | | .mark { |
| | | width: 18px; |
| | | height: 18px; |
| | | color: #ff8258; |
| | | display: grid; |
| | | place-items: center; |
| | | font-size: 20px; |
| | | line-height: 1; |
| | | transform-origin: center; |
| | | } |
| | | |
| | | .mark.busy { |
| | | animation: spin 1.1s linear infinite; |
| | | } |
| | | |
| | | @keyframes spin { |
| | | to { transform: rotate(360deg); } |
| | | } |
| | | |
| | | textarea { |
| | | width: 100%; |
| | | min-height: 24px; |
| | | max-height: 78px; |
| | | resize: none; |
| | | border: 0; |
| | | outline: none; |
| | | color: rgba(255, 255, 255, 0.94); |
| | | background: transparent; |
| | | font: 600 16px/1.35 "Segoe UI", system-ui, sans-serif; |
| | | letter-spacing: 0; |
| | | overflow-y: auto; |
| | | } |
| | | |
| | | textarea::placeholder { |
| | | color: rgba(255, 255, 255, 0.46); |
| | | } |
| | | |
| | | input { |
| | | width: 100%; |
| | | height: 34px; |
| | | border: 1px solid rgba(255, 255, 255, 0.13); |
| | | outline: none; |
| | | color: rgba(255, 255, 255, 0.88); |
| | | background: rgba(255, 255, 255, 0.07); |
| | | border-radius: 8px; |
| | | padding: 0 30px 0 10px; |
| | | font: 600 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | letter-spacing: 0; |
| | | transition: background 120ms ease; |
| | | } |
| | | |
| | | .combo { |
| | | position: relative; |
| | | width: 100%; |
| | | min-width: 0; |
| | | } |
| | | |
| | | .combo-input { |
| | | display: none; |
| | | } |
| | | |
| | | .combo-trigger { |
| | | width: 100%; |
| | | height: 34px; |
| | | border: 0; |
| | | border-radius: 8px; |
| | | color: rgba(255, 255, 255, 0.82); |
| | | background: transparent; |
| | | padding: 0 28px 0 10px; |
| | | text-align: left; |
| | | font: 600 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | letter-spacing: 0; |
| | | cursor: pointer; |
| | | overflow: hidden; |
| | | text-overflow: ellipsis; |
| | | white-space: nowrap; |
| | | position: relative; |
| | | transition: background 120ms ease; |
| | | } |
| | | |
| | | .combo-trigger::after { |
| | | content: ""; |
| | | position: absolute; |
| | | right: 11px; |
| | | top: 13px; |
| | | width: 7px; |
| | | height: 7px; |
| | | border-right: 2px solid rgba(255, 255, 255, 0.72); |
| | | border-bottom: 2px solid rgba(255, 255, 255, 0.72); |
| | | transform: rotate(45deg); |
| | | } |
| | | |
| | | input:hover, |
| | | input:focus, |
| | | .combo.open .combo-trigger, |
| | | .combo-trigger:hover, |
| | | .combo-trigger:focus { |
| | | background-color: rgba(255, 255, 255, 0.08); |
| | | box-shadow: none; |
| | | } |
| | | |
| | | .combo-menu { |
| | | position: absolute; |
| | | left: 0; |
| | | right: 0; |
| | | top: calc(100% + 6px); |
| | | z-index: 10; |
| | | display: none; |
| | | max-height: 184px; |
| | | overflow-y: auto; |
| | | padding: 6px; |
| | | border: 1px solid rgba(255, 255, 255, 0.13); |
| | | border-radius: 10px; |
| | | background: rgba(28, 26, 25, 0.92); |
| | | box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26); |
| | | backdrop-filter: blur(16px); |
| | | } |
| | | |
| | | .combo.open .combo-menu { |
| | | display: block; |
| | | } |
| | | |
| | | .combo-option { |
| | | min-height: 36px; |
| | | display: flex; |
| | | align-items: center; |
| | | border-radius: 7px; |
| | | padding: 0 10px; |
| | | color: rgba(255, 255, 255, 0.86); |
| | | font: 600 13px/1.2 "Segoe UI", system-ui, sans-serif; |
| | | cursor: pointer; |
| | | overflow: hidden; |
| | | text-overflow: ellipsis; |
| | | white-space: nowrap; |
| | | } |
| | | |
| | | .combo-option:hover, |
| | | .combo-option.selected { |
| | | background: rgba(255, 130, 88, 0.16); |
| | | color: rgba(255, 255, 255, 0.96); |
| | | } |
| | | |
| | | .output, |
| | | .memory { |
| | | display: none; |
| | | margin-top: 8px; |
| | | max-height: 50vh; |
| | | overflow: auto; |
| | | border-radius: 16px; |
| | | padding: 16px 18px 14px; |
| | | font-size: 14px; |
| | | line-height: 1.55; |
| | | white-space: pre-wrap; |
| | | } |
| | | |
| | | .output.open, |
| | | .memory.open { |
| | | display: block; |
| | | animation: panelIn 160ms ease-out; |
| | | } |
| | | |
| | | @keyframes panelIn { |
| | | from { opacity: 0; transform: translateY(-3px); } |
| | | to { opacity: 1; transform: translateY(0); } |
| | | } |
| | | |
| | | .actions, |
| | | .memory-actions { |
| | | display: flex; |
| | | justify-content: flex-end; |
| | | gap: 8px; |
| | | margin-top: 12px; |
| | | } |
| | | |
| | | .memory-row { |
| | | display: grid; |
| | | grid-template-columns: minmax(0, 1fr) 32px; |
| | | gap: 8px; |
| | | align-items: start; |
| | | padding: 8px 0; |
| | | border-top: 1px solid rgba(255, 255, 255, 0.08); |
| | | white-space: normal; |
| | | } |
| | | |
| | | .memory-row:first-child { |
| | | border-top: 0; |
| | | } |
| | | |
| | | .memory-content { |
| | | color: rgba(255, 255, 255, 0.86); |
| | | overflow-wrap: anywhere; |
| | | } |
| | | |
| | | button { |
| | | width: 30px; |
| | | height: 30px; |
| | | border: 0; |
| | | border-radius: 8px; |
| | | color: rgba(255, 255, 255, 0.84); |
| | | background: rgba(255, 255, 255, 0.08); |
| | | cursor: pointer; |
| | | font: 700 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | } |
| | | |
| | | button:disabled, |
| | | input:disabled { |
| | | cursor: not-allowed; |
| | | opacity: 0.52; |
| | | } |
| | | |
| | | .error { |
| | | color: #ffad9b; |
| | | } |
| | | </style> |
| | | </head> |
| | | <body> |
| | | <main class="shell"> |
| | | <section class="bar"> |
| | | <div class="combo" id="projectCombo"> |
| | | <input id="project" class="combo-input" aria-hidden="true"> |
| | | <button id="projectButton" class="combo-trigger" type="button" title="AiChat project">Project</button> |
| | | <div id="projectMenu" class="combo-menu" role="listbox"></div> |
| | | </div> |
| | | <div id="mark" class="mark" aria-hidden="true">*</div> |
| | | <textarea id="prompt" rows="1" placeholder="What can I help you with today?">Summarize today's desktop notes</textarea> |
| | | <button id="memoryToggle" title="Memory">M</button> |
| | | <div class="combo" id="modelCombo"> |
| | | <input id="model" class="combo-input" aria-hidden="true"> |
| | | <button id="modelButton" class="combo-trigger" type="button" title="Model">Model</button> |
| | | <div id="modelMenu" class="combo-menu" role="listbox"></div> |
| | | </div> |
| | | </section> |
| | | <section id="output" class="output open" aria-live="polite"> |
| | | <div id="text">Static preview response. This demo.html has no host bridge, no network calls, and no LLM dependency. Press Enter in the prompt to preview the loading and response states.</div> |
| | | <div class="actions"> |
| | | <button id="copy" title="Copy">C</button> |
| | | <button id="collapse" title="Collapse">-</button> |
| | | </div> |
| | | </section> |
| | | <section id="memory" class="memory" aria-live="polite"> |
| | | <div id="memoryList"></div> |
| | | <div class="memory-actions"> |
| | | <input id="memoryInput" placeholder="Save memory"> |
| | | <button id="saveMemory" title="Save memory">+</button> |
| | | <button id="refreshMemory" title="Refresh memory">R</button> |
| | | </div> |
| | | </section> |
| | | </main> |
| | | |
| | | <script> |
| | | const demoProjects = [ |
| | | { value: "desktop", label: "Desktop", title: "CHAT / PROJECT" }, |
| | | { value: "design", label: "Design pass", title: "CHAT / PROJECT" }, |
| | | { value: "ops", label: "Ops notes", title: "CHAT / PROJECT" } |
| | | ]; |
| | | const demoModels = [ |
| | | { value: "deepseek-v4-flash", label: "deepseek-v4-flash", title: "deepseek / deepseek-v4-flash" }, |
| | | { value: "kimi-k2.6", label: "kimi-k2.6", title: "kimi / kimi-k2.6" }, |
| | | { value: "glm-4.7-flash", label: "glm-4.7-flash", title: "bigmodel / glm-4.7-flash" }, |
| | | { value: "qwen3.6-plus", label: "qwen3.6-plus", title: "qwen / qwen3.6-plus" } |
| | | ]; |
| | | let demoMemories = [ |
| | | { id: "m1", content: "Keep the command palette compact enough for a desktop widget." }, |
| | | { id: "m2", content: "Prefer plain static demo files for visual iteration." } |
| | | ]; |
| | | |
| | | const promptInput = document.getElementById("prompt"); |
| | | const projectSelect = document.getElementById("project"); |
| | | const projectCombo = document.getElementById("projectCombo"); |
| | | const projectButton = document.getElementById("projectButton"); |
| | | const projectMenu = document.getElementById("projectMenu"); |
| | | const modelSelect = document.getElementById("model"); |
| | | const modelCombo = document.getElementById("modelCombo"); |
| | | const modelButton = document.getElementById("modelButton"); |
| | | const modelMenu = document.getElementById("modelMenu"); |
| | | const output = document.getElementById("output"); |
| | | const text = document.getElementById("text"); |
| | | const mark = document.getElementById("mark"); |
| | | const copy = document.getElementById("copy"); |
| | | const collapse = document.getElementById("collapse"); |
| | | const memoryToggle = document.getElementById("memoryToggle"); |
| | | const memoryPanel = document.getElementById("memory"); |
| | | const memoryList = document.getElementById("memoryList"); |
| | | const memoryInput = document.getElementById("memoryInput"); |
| | | const saveMemory = document.getElementById("saveMemory"); |
| | | const refreshMemory = document.getElementById("refreshMemory"); |
| | | |
| | | let currentText = text.textContent; |
| | | const projectDropdown = { input: projectSelect, root: projectCombo, button: projectButton, menu: projectMenu }; |
| | | const modelDropdown = { input: modelSelect, root: modelCombo, button: modelButton, menu: modelMenu }; |
| | | |
| | | function setupDropdown(dropdown) { |
| | | dropdown.button.addEventListener("click", () => { |
| | | const willOpen = !dropdown.root.classList.contains("open"); |
| | | closeDropdowns(); |
| | | dropdown.root.classList.toggle("open", willOpen); |
| | | }); |
| | | } |
| | | |
| | | function closeDropdowns() { |
| | | projectCombo.classList.remove("open"); |
| | | modelCombo.classList.remove("open"); |
| | | } |
| | | |
| | | function setDropdownOptions(dropdown, items, preferredValue) { |
| | | dropdown.menu.innerHTML = ""; |
| | | const selected = items.find((item) => item.value === preferredValue) || items[0]; |
| | | for (const item of items) { |
| | | const option = document.createElement("div"); |
| | | option.className = `combo-option${item.value === selected.value ? " selected" : ""}`; |
| | | option.textContent = item.label; |
| | | option.title = item.title || item.label; |
| | | option.dataset.value = item.value; |
| | | option.addEventListener("click", () => { |
| | | setDropdownValue(dropdown, item); |
| | | closeDropdowns(); |
| | | }); |
| | | dropdown.menu.appendChild(option); |
| | | } |
| | | setDropdownValue(dropdown, selected, false); |
| | | } |
| | | |
| | | function setDropdownValue(dropdown, item, notify = true) { |
| | | dropdown.input.value = item.value; |
| | | dropdown.button.textContent = item.label; |
| | | dropdown.button.title = item.title || item.label; |
| | | for (const option of dropdown.menu.children) { |
| | | option.classList.toggle("selected", option.dataset.value === item.value); |
| | | } |
| | | if (notify) { |
| | | dropdown.input.dispatchEvent(new Event("change")); |
| | | } |
| | | } |
| | | |
| | | function setBusy(busy) { |
| | | mark.classList.toggle("busy", busy); |
| | | } |
| | | |
| | | function openOutput() { |
| | | output.classList.add("open"); |
| | | } |
| | | |
| | | function submitPrompt() { |
| | | const content = promptInput.value.trim(); |
| | | if (!content) return; |
| | | |
| | | currentText = ""; |
| | | text.className = ""; |
| | | text.textContent = ""; |
| | | openOutput(); |
| | | setBusy(true); |
| | | |
| | | setTimeout(() => { |
| | | currentText = `Preview only\n\nProject: ${projectButton.textContent}\nModel: ${modelButton.textContent}\nPrompt: ${content}\n\nThis static demo mimics the result panel so the visual style can be edited without running Moli.Desktop.`; |
| | | text.textContent = currentText; |
| | | setBusy(false); |
| | | }, 380); |
| | | } |
| | | |
| | | function renderMemories() { |
| | | memoryList.innerHTML = ""; |
| | | if (!demoMemories.length) { |
| | | memoryList.textContent = "No memory"; |
| | | return; |
| | | } |
| | | |
| | | for (const item of demoMemories) { |
| | | const row = document.createElement("div"); |
| | | row.className = "memory-row"; |
| | | const content = document.createElement("div"); |
| | | content.className = "memory-content"; |
| | | content.textContent = item.content; |
| | | row.appendChild(content); |
| | | const remove = document.createElement("button"); |
| | | remove.textContent = "x"; |
| | | remove.title = "Delete memory"; |
| | | remove.addEventListener("click", () => { |
| | | demoMemories = demoMemories.filter((memory) => memory.id !== item.id); |
| | | renderMemories(); |
| | | }); |
| | | row.appendChild(remove); |
| | | memoryList.appendChild(row); |
| | | } |
| | | } |
| | | |
| | | promptInput.addEventListener("keydown", (event) => { |
| | | if (event.key === "Enter" && !event.shiftKey) { |
| | | event.preventDefault(); |
| | | submitPrompt(); |
| | | } |
| | | |
| | | if (event.key === "Escape") { |
| | | output.classList.remove("open"); |
| | | memoryPanel.classList.remove("open"); |
| | | } |
| | | }); |
| | | |
| | | promptInput.addEventListener("input", () => { |
| | | promptInput.style.height = "0"; |
| | | promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`; |
| | | }); |
| | | |
| | | memoryToggle.addEventListener("click", () => { |
| | | memoryPanel.classList.toggle("open"); |
| | | if (memoryPanel.classList.contains("open")) { |
| | | renderMemories(); |
| | | } |
| | | }); |
| | | |
| | | refreshMemory.addEventListener("click", renderMemories); |
| | | saveMemory.addEventListener("click", () => { |
| | | const content = memoryInput.value.trim(); |
| | | if (!content) return; |
| | | demoMemories.unshift({ id: `m${Date.now()}`, content }); |
| | | memoryInput.value = ""; |
| | | renderMemories(); |
| | | }); |
| | | |
| | | collapse.addEventListener("click", () => output.classList.remove("open")); |
| | | copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {})); |
| | | document.addEventListener("click", (event) => { |
| | | if (!projectCombo.contains(event.target) && !modelCombo.contains(event.target)) { |
| | | closeDropdowns(); |
| | | } |
| | | }); |
| | | |
| | | setupDropdown(projectDropdown); |
| | | setupDropdown(modelDropdown); |
| | | setDropdownOptions(projectDropdown, demoProjects, "desktop"); |
| | | setDropdownOptions(modelDropdown, demoModels, "deepseek-v4-flash"); |
| | | renderMemories(); |
| | | </script> |
| | | </body> |
| | | </html> |
| | |
| | | } |
| | | |
| | | .bar, |
| | | .output { |
| | | .output, |
| | | .memory { |
| | | 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); |
| | | border: 1px solid rgba(255, 255, 255, 0.14); |
| | | background: rgba(28, 26, 25, 0.72); |
| | | box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18); |
| | | backdrop-filter: blur(18px); |
| | | } |
| | | |
| | | .bar { |
| | | display: grid; |
| | | grid-template-columns: 24px minmax(0, 1fr) 128px; |
| | | grid-template-columns: minmax(90px, 112px) 22px minmax(0, 1fr) 30px minmax(112px, 128px); |
| | | align-items: center; |
| | | gap: 14px; |
| | | min-height: 56px; |
| | | padding: 0 18px; |
| | | padding: 0 20px; |
| | | border-radius: 20px; |
| | | } |
| | | |
| | |
| | | color: rgba(255, 255, 255, 0.46); |
| | | } |
| | | |
| | | select { |
| | | input { |
| | | width: 100%; |
| | | height: 34px; |
| | | border: 1px solid rgba(255, 255, 255, 0.13); |
| | | outline: none; |
| | | color: rgba(255, 255, 255, 0.88); |
| | | background: rgba(255, 255, 255, 0.07); |
| | | border-radius: 8px; |
| | | padding: 0 30px 0 10px; |
| | | font: 600 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | letter-spacing: 0; |
| | | transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease; |
| | | } |
| | | |
| | | .combo { |
| | | position: relative; |
| | | width: 100%; |
| | | min-width: 0; |
| | | } |
| | | |
| | | .combo-input { |
| | | display: none; |
| | | } |
| | | |
| | | .combo-trigger { |
| | | width: 100%; |
| | | height: 34px; |
| | | border: 0; |
| | | outline: none; |
| | | color: rgba(255, 255, 255, 0.82); |
| | | background: rgba(255, 255, 255, 0.08); |
| | | border-radius: 8px; |
| | | padding: 0 8px; |
| | | color: rgba(255, 255, 255, 0.82); |
| | | background: transparent; |
| | | padding: 0 28px 0 10px; |
| | | text-align: left; |
| | | font: 600 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | letter-spacing: 0; |
| | | cursor: pointer; |
| | | overflow: hidden; |
| | | text-overflow: ellipsis; |
| | | white-space: nowrap; |
| | | position: relative; |
| | | transition: border-color 120ms ease, background 120ms ease, box-shadow 120ms ease; |
| | | } |
| | | |
| | | .output { |
| | | .combo-trigger::after { |
| | | content: ""; |
| | | position: absolute; |
| | | right: 11px; |
| | | top: 13px; |
| | | width: 7px; |
| | | height: 7px; |
| | | border-right: 2px solid rgba(255, 255, 255, 0.72); |
| | | border-bottom: 2px solid rgba(255, 255, 255, 0.72); |
| | | transform: rotate(45deg); |
| | | } |
| | | |
| | | input:hover, |
| | | input:focus, |
| | | .combo.open .combo-trigger, |
| | | .combo-trigger:hover, |
| | | .combo-trigger:focus { |
| | | background-color: rgba(255, 255, 255, 0.08); |
| | | box-shadow: none; |
| | | } |
| | | |
| | | .combo-menu { |
| | | position: absolute; |
| | | left: 0; |
| | | right: 0; |
| | | top: calc(100% + 6px); |
| | | z-index: 10; |
| | | display: none; |
| | | max-height: 184px; |
| | | overflow-y: auto; |
| | | padding: 6px; |
| | | border: 1px solid rgba(255, 255, 255, 0.13); |
| | | border-radius: 10px; |
| | | background: rgba(28, 26, 25, 0.92); |
| | | box-shadow: 0 12px 28px rgba(0, 0, 0, 0.26); |
| | | backdrop-filter: blur(16px); |
| | | } |
| | | |
| | | .combo.open .combo-menu { |
| | | display: block; |
| | | } |
| | | |
| | | .combo-option { |
| | | min-height: 36px; |
| | | display: flex; |
| | | align-items: center; |
| | | border-radius: 7px; |
| | | padding: 0 10px; |
| | | color: rgba(255, 255, 255, 0.86); |
| | | font: 600 13px/1.2 "Segoe UI", system-ui, sans-serif; |
| | | cursor: pointer; |
| | | overflow: hidden; |
| | | text-overflow: ellipsis; |
| | | white-space: nowrap; |
| | | } |
| | | |
| | | .combo-option:hover, |
| | | .combo-option.selected { |
| | | background: rgba(255, 130, 88, 0.16); |
| | | color: rgba(255, 255, 255, 0.96); |
| | | } |
| | | |
| | | .output, |
| | | .memory { |
| | | display: none; |
| | | margin-top: 8px; |
| | | max-height: 50vh; |
| | |
| | | white-space: pre-wrap; |
| | | } |
| | | |
| | | .output.open { |
| | | .output.open, |
| | | .memory.open { |
| | | display: block; |
| | | animation: panelIn 160ms ease-out; |
| | | } |
| | | |
| | | .actions { |
| | | @keyframes panelIn { |
| | | from { opacity: 0; transform: translateY(-3px); } |
| | | to { opacity: 1; transform: translateY(0); } |
| | | } |
| | | |
| | | .actions, |
| | | .memory-actions { |
| | | display: flex; |
| | | justify-content: flex-end; |
| | | gap: 8px; |
| | | margin-top: 12px; |
| | | } |
| | | |
| | | .memory-row { |
| | | display: grid; |
| | | grid-template-columns: minmax(0, 1fr) 32px; |
| | | gap: 8px; |
| | | align-items: start; |
| | | padding: 8px 0; |
| | | border-top: 1px solid rgba(255, 255, 255, 0.08); |
| | | white-space: normal; |
| | | } |
| | | |
| | | .memory-row:first-child { |
| | | border-top: 0; |
| | | } |
| | | |
| | | .memory-content { |
| | | color: rgba(255, 255, 255, 0.86); |
| | | overflow-wrap: anywhere; |
| | | } |
| | | |
| | | button { |
| | |
| | | color: rgba(255, 255, 255, 0.84); |
| | | background: rgba(255, 255, 255, 0.08); |
| | | cursor: pointer; |
| | | font: 700 13px/1 "Segoe UI", system-ui, sans-serif; |
| | | } |
| | | |
| | | button:disabled, |
| | | input:disabled { |
| | | cursor: not-allowed; |
| | | opacity: 0.52; |
| | | } |
| | | |
| | | .error { |
| | |
| | | <body> |
| | | <main class="shell"> |
| | | <section class="bar"> |
| | | <div class="combo" id="projectCombo"> |
| | | <input id="project" class="combo-input" aria-hidden="true"> |
| | | <button id="projectButton" class="combo-trigger" type="button" title="AiChat project">Project</button> |
| | | <div id="projectMenu" class="combo-menu" role="listbox"></div> |
| | | </div> |
| | | <div id="mark" class="mark" aria-hidden="true">*</div> |
| | | <textarea id="prompt" rows="1" placeholder="What can I help you with today?"></textarea> |
| | | <select id="model" title="Model"></select> |
| | | <button id="memoryToggle" title="Memory">M</button> |
| | | <div class="combo" id="modelCombo"> |
| | | <input id="model" class="combo-input" aria-hidden="true"> |
| | | <button id="modelButton" class="combo-trigger" type="button" title="Model">Model</button> |
| | | <div id="modelMenu" class="combo-menu" role="listbox"></div> |
| | | </div> |
| | | </section> |
| | | <section id="output" class="output" aria-live="polite"> |
| | | <div id="text"></div> |
| | |
| | | <button id="collapse" title="Collapse">-</button> |
| | | </div> |
| | | </section> |
| | | <section id="memory" class="memory" aria-live="polite"> |
| | | <div id="memoryList"></div> |
| | | <div class="memory-actions"> |
| | | <input id="memoryInput" placeholder="Save memory"> |
| | | <button id="saveMemory" title="Save memory">+</button> |
| | | <button id="refreshMemory" title="Refresh memory">R</button> |
| | | </div> |
| | | </section> |
| | | </main> |
| | | |
| | | <script> |
| | | const promptInput = document.getElementById("prompt"); |
| | | const projectSelect = document.getElementById("project"); |
| | | const projectCombo = document.getElementById("projectCombo"); |
| | | const projectButton = document.getElementById("projectButton"); |
| | | const projectMenu = document.getElementById("projectMenu"); |
| | | const modelSelect = document.getElementById("model"); |
| | | const modelCombo = document.getElementById("modelCombo"); |
| | | const modelButton = document.getElementById("modelButton"); |
| | | const modelMenu = document.getElementById("modelMenu"); |
| | | const output = document.getElementById("output"); |
| | | const text = document.getElementById("text"); |
| | | const mark = document.getElementById("mark"); |
| | | const copy = document.getElementById("copy"); |
| | | const collapse = document.getElementById("collapse"); |
| | | const memoryToggle = document.getElementById("memoryToggle"); |
| | | const memoryPanel = document.getElementById("memory"); |
| | | const memoryList = document.getElementById("memoryList"); |
| | | const memoryInput = document.getElementById("memoryInput"); |
| | | const saveMemory = document.getElementById("saveMemory"); |
| | | const refreshMemory = document.getElementById("refreshMemory"); |
| | | |
| | | if (!window.moliDesktop) { |
| | | window.moliDesktop = { |
| | | getConfig: async () => ({ |
| | | mode: "provider-direct", |
| | | aichat: { memory: { enabledInProviderDirect: false, defaultScope: "PROJECT", recallLimit: 8 } } |
| | | }), |
| | | requestResize: async () => {}, |
| | | llm: { |
| | | getProjects: async () => [], |
| | | getModels: async () => [], |
| | | getMemoryCapabilities: async () => ({ canUseMemory: false, canViewMemory: false, canManageMemory: false }), |
| | | getMemories: async () => ({ items: [] }), |
| | | createMemory: async () => ({}), |
| | | deleteMemory: async () => {}, |
| | | recallMemories: async () => ({ items: [] }), |
| | | streamChat: async () => ({ requestId: "preview" }), |
| | | onDelta: () => () => {}, |
| | | onCompleted: () => () => {}, |
| | | onError: () => () => {} |
| | | } |
| | | }; |
| | | } |
| | | |
| | | let activeRequestId = null; |
| | | let currentText = ""; |
| | | let config = { mode: "provider-direct", aichat: { memory: { enabledInProviderDirect: true, defaultScope: "PROJECT", recallLimit: 8 } } }; |
| | | let memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false }; |
| | | |
| | | function mode() { |
| | | return config.mode || "provider-direct"; |
| | | } |
| | | |
| | | function selectedProjectId() { |
| | | return projectSelect.value || config.aichat?.defaultProjectId || ""; |
| | | } |
| | | |
| | | function setBusy(busy) { |
| | | mark.classList.toggle("busy", busy); |
| | |
| | | |
| | | function openOutput() { |
| | | output.classList.add("open"); |
| | | window.moliDesktop?.requestResize?.({ width: document.body.scrollWidth, height: Math.min(window.innerHeight, document.body.scrollHeight) }).catch(() => {}); |
| | | requestResize(); |
| | | } |
| | | |
| | | function requestResize() { |
| | | const openMenu = projectCombo.classList.contains("open") |
| | | ? projectMenu |
| | | : modelCombo.classList.contains("open") ? modelMenu : null; |
| | | const menuBottom = openMenu ? openMenu.getBoundingClientRect().bottom + 8 : 72; |
| | | window.moliDesktop?.requestResize?.({ |
| | | width: document.body.scrollWidth, |
| | | height: Math.max(72, Math.ceil(menuBottom)) |
| | | }).catch(() => {}); |
| | | } |
| | | |
| | | function setError(message) { |
| | |
| | | openOutput(); |
| | | } |
| | | |
| | | const projectDropdown = { input: projectSelect, root: projectCombo, button: projectButton, menu: projectMenu }; |
| | | const modelDropdown = { input: modelSelect, root: modelCombo, button: modelButton, menu: modelMenu }; |
| | | |
| | | function setupDropdown(dropdown) { |
| | | dropdown.button.addEventListener("click", () => { |
| | | const willOpen = !dropdown.root.classList.contains("open"); |
| | | closeDropdowns(); |
| | | dropdown.root.classList.toggle("open", willOpen); |
| | | requestResize(); |
| | | }); |
| | | } |
| | | |
| | | function closeDropdowns() { |
| | | projectCombo.classList.remove("open"); |
| | | modelCombo.classList.remove("open"); |
| | | requestResize(); |
| | | } |
| | | |
| | | function setDropdownFallback(dropdown, label, title) { |
| | | dropdown.input.value = ""; |
| | | dropdown.button.textContent = label; |
| | | dropdown.button.title = title || label; |
| | | dropdown.menu.innerHTML = ""; |
| | | const option = document.createElement("div"); |
| | | option.className = "combo-option"; |
| | | option.textContent = label; |
| | | option.title = title || label; |
| | | dropdown.menu.appendChild(option); |
| | | } |
| | | |
| | | function setDropdownOptions(dropdown, items, preferredValue, fallbackLabel) { |
| | | dropdown.menu.innerHTML = ""; |
| | | if (!items.length) { |
| | | setDropdownFallback(dropdown, fallbackLabel); |
| | | return; |
| | | } |
| | | |
| | | let selected = items.find((item) => item.value === preferredValue) || items[0]; |
| | | for (const item of items) { |
| | | const option = document.createElement("div"); |
| | | option.className = `combo-option${item.value === selected.value ? " selected" : ""}`; |
| | | option.textContent = item.label; |
| | | option.title = item.title || item.label; |
| | | option.dataset.value = item.value; |
| | | option.addEventListener("click", () => { |
| | | selected = item; |
| | | setDropdownValue(dropdown, item); |
| | | closeDropdowns(); |
| | | }); |
| | | dropdown.menu.appendChild(option); |
| | | } |
| | | |
| | | setDropdownValue(dropdown, selected, false); |
| | | } |
| | | |
| | | function setDropdownValue(dropdown, item, notify = true) { |
| | | dropdown.input.value = item.value; |
| | | dropdown.button.textContent = item.label; |
| | | dropdown.button.title = item.title || item.label; |
| | | for (const option of dropdown.menu.children) { |
| | | option.classList.toggle("selected", option.dataset.value === item.value); |
| | | } |
| | | if (notify) { |
| | | dropdown.input.dispatchEvent(new Event("change")); |
| | | } |
| | | } |
| | | |
| | | async function loadConfig() { |
| | | try { |
| | | config = { ...config, ...(await window.moliDesktop.getConfig() || {}) }; |
| | | } catch { |
| | | } |
| | | } |
| | | |
| | | async function loadProjects() { |
| | | try { |
| | | const projects = await window.moliDesktop.llm.getProjects(); |
| | | const items = projects.map((project) => ({ |
| | | value: project.id, |
| | | label: project.name || project.id, |
| | | title: `${project.projectType || "CHAT"} / ${project.memoryMode || "ISOLATED"}` |
| | | })); |
| | | setDropdownOptions(projectDropdown, items, config.aichat?.defaultProjectId || "", "No project"); |
| | | } catch (error) { |
| | | setDropdownFallback(projectDropdown, "Project error", error?.message || "AiChat projects could not be loaded"); |
| | | } |
| | | } |
| | | |
| | | async function loadModels() { |
| | | try { |
| | | const models = await window.moliDesktop.llm.getModels(); |
| | | 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); |
| | | const items = models.map((model) => ({ |
| | | value: model.id, |
| | | label: model.label || model.id, |
| | | title: `${model.provider} / ${model.id}` |
| | | })); |
| | | setDropdownOptions(modelDropdown, items, config.defaultModel || "", "No models"); |
| | | } catch { |
| | | setDropdownFallback(modelDropdown, "Model error"); |
| | | } |
| | | } |
| | | |
| | | if (models.length === 0) { |
| | | const option = document.createElement("option"); |
| | | option.textContent = "No models"; |
| | | option.value = ""; |
| | | modelSelect.appendChild(option); |
| | | } |
| | | async function loadMemoryCapabilities() { |
| | | try { |
| | | memoryCapabilities = await window.moliDesktop.llm.getMemoryCapabilities(); |
| | | } catch { |
| | | modelSelect.innerHTML = "<option value=\"\">No models</option>"; |
| | | memoryCapabilities = { canUseMemory: false, canViewMemory: false, canManageMemory: false }; |
| | | } |
| | | |
| | | const memoryEnabled = mode() === "provider-direct" && config.aichat?.memory?.enabledInProviderDirect; |
| | | memoryToggle.disabled = !memoryEnabled || !memoryCapabilities.canViewMemory; |
| | | memoryInput.disabled = !memoryCapabilities.canManageMemory; |
| | | saveMemory.disabled = !memoryCapabilities.canManageMemory; |
| | | refreshMemory.disabled = !memoryCapabilities.canViewMemory; |
| | | } |
| | | |
| | | async function recallMemory(content) { |
| | | if (mode() !== "provider-direct" || !config.aichat?.memory?.enabledInProviderDirect || !memoryCapabilities.canUseMemory) { |
| | | return []; |
| | | } |
| | | |
| | | const projectId = selectedProjectId(); |
| | | try { |
| | | const result = await window.moliDesktop.llm.recallMemories({ |
| | | query: content, |
| | | scope: config.aichat.memory.defaultScope || "PROJECT", |
| | | projectId, |
| | | limit: config.aichat.memory.recallLimit || 8 |
| | | }); |
| | | return Array.isArray(result?.items) ? result.items : []; |
| | | } catch { |
| | | return []; |
| | | } |
| | | } |
| | | |
| | |
| | | setBusy(true); |
| | | |
| | | try { |
| | | const memories = await recallMemory(content); |
| | | const messages = []; |
| | | if (memories.length > 0) { |
| | | const memoryText = memories.map((item) => `- ${item.content || ""}`).filter(Boolean).join("\n"); |
| | | if (memoryText) { |
| | | messages.push({ role: "system", content: `Relevant memory:\n${memoryText}` }); |
| | | } |
| | | } |
| | | messages.push({ role: "user", content }); |
| | | |
| | | const response = await window.moliDesktop.llm.streamChat({ |
| | | mode: mode(), |
| | | projectId: selectedProjectId(), |
| | | modelId, |
| | | messages: [{ role: "user", content }], |
| | | messages, |
| | | options: {} |
| | | }); |
| | | activeRequestId = response.requestId; |
| | |
| | | activeRequestId = null; |
| | | setBusy(false); |
| | | setError(error?.message || "LLM request could not be started."); |
| | | } |
| | | } |
| | | |
| | | async function refreshMemories() { |
| | | if (!memoryCapabilities.canViewMemory) return; |
| | | const projectId = selectedProjectId(); |
| | | memoryList.textContent = "Loading..."; |
| | | try { |
| | | const scope = config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT"; |
| | | const result = await window.moliDesktop.llm.getMemories({ scope, projectId }); |
| | | const items = Array.isArray(result) ? result : Array.isArray(result?.items) ? result.items : []; |
| | | renderMemories(items); |
| | | } catch (error) { |
| | | memoryList.textContent = error?.message || "Memory unavailable."; |
| | | } |
| | | } |
| | | |
| | | function renderMemories(items) { |
| | | memoryList.innerHTML = ""; |
| | | if (!items.length) { |
| | | memoryList.textContent = "No memory"; |
| | | return; |
| | | } |
| | | |
| | | for (const item of items) { |
| | | const row = document.createElement("div"); |
| | | row.className = "memory-row"; |
| | | const content = document.createElement("div"); |
| | | content.className = "memory-content"; |
| | | content.textContent = item.content || item.id || ""; |
| | | row.appendChild(content); |
| | | const remove = document.createElement("button"); |
| | | remove.textContent = "x"; |
| | | remove.title = "Delete memory"; |
| | | remove.disabled = !memoryCapabilities.canManageMemory; |
| | | remove.addEventListener("click", async () => { |
| | | if (!item.id) return; |
| | | await window.moliDesktop.llm.deleteMemory(item.id); |
| | | refreshMemories(); |
| | | }); |
| | | row.appendChild(remove); |
| | | memoryList.appendChild(row); |
| | | } |
| | | } |
| | | |
| | |
| | | |
| | | if (event.key === "Escape") { |
| | | output.classList.remove("open"); |
| | | memoryPanel.classList.remove("open"); |
| | | requestResize(); |
| | | } |
| | | }); |
| | | |
| | |
| | | promptInput.style.height = `${Math.min(promptInput.scrollHeight, 78)}px`; |
| | | }); |
| | | |
| | | collapse.addEventListener("click", () => output.classList.remove("open")); |
| | | copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {})); |
| | | projectSelect.addEventListener("change", () => { |
| | | if (memoryPanel.classList.contains("open")) { |
| | | refreshMemories(); |
| | | } |
| | | }); |
| | | |
| | | window.addEventListener("DOMContentLoaded", loadModels); |
| | | memoryToggle.addEventListener("click", () => { |
| | | memoryPanel.classList.toggle("open"); |
| | | if (memoryPanel.classList.contains("open")) { |
| | | refreshMemories(); |
| | | } |
| | | requestResize(); |
| | | }); |
| | | |
| | | refreshMemory.addEventListener("click", refreshMemories); |
| | | saveMemory.addEventListener("click", async () => { |
| | | const content = memoryInput.value.trim(); |
| | | if (!content || !memoryCapabilities.canManageMemory) return; |
| | | await window.moliDesktop.llm.createMemory({ |
| | | scope: config.aichat?.memory?.defaultScope === "GLOBAL" ? "GLOBAL" : "PROJECT", |
| | | projectId: selectedProjectId(), |
| | | content |
| | | }); |
| | | memoryInput.value = ""; |
| | | refreshMemories(); |
| | | }); |
| | | |
| | | collapse.addEventListener("click", () => { |
| | | output.classList.remove("open"); |
| | | requestResize(); |
| | | }); |
| | | copy.addEventListener("click", () => navigator.clipboard?.writeText(currentText).catch(() => {})); |
| | | document.addEventListener("click", (event) => { |
| | | if (!projectCombo.contains(event.target) && !modelCombo.contains(event.target)) { |
| | | closeDropdowns(); |
| | | } |
| | | }); |
| | | |
| | | window.addEventListener("DOMContentLoaded", async () => { |
| | | setupDropdown(projectDropdown); |
| | | setupDropdown(modelDropdown); |
| | | await loadConfig(); |
| | | await Promise.all([loadProjects(), loadModels(), loadMemoryCapabilities()]); |
| | | }); |
| | | |
| | | window.moliDesktop?.llm?.onDelta?.((event) => { |
| | | if (event.requestId !== activeRequestId) return; |
| | | currentText += event.delta || ""; |
| | |
| | | "displayLayer": "desktop" |
| | | }, |
| | | "config": { |
| | | "defaultModel": "", |
| | | "models": [] |
| | | "mode": "provider-direct", |
| | | "aichat": { |
| | | "baseUrl": "http://192.168.1.111:13000", |
| | | "account": { |
| | | "email": "linmolilin@163.com", |
| | | "password": null, |
| | | "passwordEnv": "MOLI_AICHAT_PASSWORD" |
| | | }, |
| | | "defaultProjectId": "cmnd8uzcl0002c9usch183a01", |
| | | "memory": { |
| | | "enabledInProviderDirect": true, |
| | | "defaultScope": "PROJECT", |
| | | "recallLimit": 8 |
| | | } |
| | | }, |
| | | "defaultModel": "deepseek-v4-flash", |
| | | "models": [ |
| | | { |
| | | "id": "deepseek-v4-flash", |
| | | "label": "deepseek-v4-flash", |
| | | "provider": "deepseek", |
| | | "endpoint": "https://api.deepseek.com/chat/completions", |
| | | "authRef": "llm_deepseek_api_key", |
| | | "apiModel": "deepseek-v4-flash", |
| | | "supportsStreaming": true, |
| | | "enabled": true, |
| | | "requestDefaults": { |
| | | "temperature": 0.9, |
| | | "maxTokens": 2560000, |
| | | "timeoutMs": 60000 |
| | | } |
| | | }, |
| | | { |
| | | "id": "kimi-k2.6", |
| | | "label": "kimi-k2.6", |
| | | "provider": "kimi", |
| | | "endpoint": "https://api.moonshot.cn/v1/chat/completions", |
| | | "authRef": "llm_kimi_api_key", |
| | | "apiModel": "kimi-k2.6", |
| | | "supportsStreaming": true, |
| | | "enabled": true, |
| | | "requestDefaults": { |
| | | "temperature": 0.9, |
| | | "maxTokens": 2560000, |
| | | "timeoutMs": 60000 |
| | | } |
| | | }, |
| | | { |
| | | "id": "glm-4.7-flash", |
| | | "label": "glm-4.7-flash", |
| | | "provider": "bigmodel", |
| | | "endpoint": "https://open.bigmodel.cn/api/paas/v4/chat/completions", |
| | | "authRef": "llm_bigmodel_api_key", |
| | | "apiModel": "glm-4.7-flash", |
| | | "supportsStreaming": true, |
| | | "enabled": true, |
| | | "requestDefaults": { |
| | | "temperature": 0.9, |
| | | "maxTokens": 2000000, |
| | | "timeoutMs": 60000 |
| | | } |
| | | }, |
| | | { |
| | | "id": "qwen3.6-plus", |
| | | "label": "qwen3.6-plus", |
| | | "provider": "qwen", |
| | | "endpoint": "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", |
| | | "authRef": "llm_bigmodel_api_key", |
| | | "apiModel": "qwen3.6-plus", |
| | | "supportsStreaming": true, |
| | | "enabled": true, |
| | | "requestDefaults": { |
| | | "temperature": 0.9, |
| | | "maxTokens": 2560000, |
| | | "timeoutMs": 60000 |
| | | } |
| | | } |
| | | ] |
| | | } |
| | | } |
| | |
| | | } |
| | | } |
| | | |
| | | function Get-RelativePathCompat { |
| | | param( |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$BasePath, |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$TargetPath |
| | | ) |
| | | |
| | | $baseFullPath = [System.IO.Path]::GetFullPath($BasePath).TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) |
| | | $targetFullPath = [System.IO.Path]::GetFullPath($TargetPath).TrimEnd([System.IO.Path]::DirectorySeparatorChar, [System.IO.Path]::AltDirectorySeparatorChar) |
| | | $baseUri = New-Object System.Uri(($baseFullPath + [System.IO.Path]::DirectorySeparatorChar)) |
| | | $targetUri = New-Object System.Uri($targetFullPath) |
| | | $relativeUri = $baseUri.MakeRelativeUri($targetUri) |
| | | return [System.Uri]::UnescapeDataString($relativeUri.ToString()).Replace('/', [System.IO.Path]::DirectorySeparatorChar) |
| | | } |
| | | |
| | | function Backup-DeployedPluginConfigs { |
| | | param( |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$ApplicationDirectory, |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$BackupDirectory |
| | | ) |
| | | |
| | | $pluginsRoot = Join-Path $ApplicationDirectory "samples\plugins" |
| | | if (-not (Test-Path -LiteralPath $pluginsRoot)) { |
| | | return |
| | | } |
| | | |
| | | Get-ChildItem -LiteralPath $pluginsRoot -Directory | ForEach-Object { |
| | | $pluginJson = Join-Path $_.FullName "plugin.json" |
| | | if (-not (Test-Path -LiteralPath $pluginJson)) { |
| | | return |
| | | } |
| | | |
| | | $relativeDirectory = Get-RelativePathCompat -BasePath $pluginsRoot -TargetPath $_.FullName |
| | | $backupPluginDirectory = Join-Path $BackupDirectory $relativeDirectory |
| | | New-Item -ItemType Directory -Force -Path $backupPluginDirectory | Out-Null |
| | | Copy-Item -LiteralPath $pluginJson -Destination (Join-Path $backupPluginDirectory "plugin.json") -Force |
| | | } |
| | | } |
| | | |
| | | function Restore-DeployedPluginConfigs { |
| | | param( |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$ApplicationDirectory, |
| | | [Parameter(Mandatory = $true)] |
| | | [string]$BackupDirectory |
| | | ) |
| | | |
| | | if (-not (Test-Path -LiteralPath $BackupDirectory)) { |
| | | return |
| | | } |
| | | |
| | | $pluginsRoot = Join-Path $ApplicationDirectory "samples\plugins" |
| | | Get-ChildItem -LiteralPath $BackupDirectory -Directory | ForEach-Object { |
| | | $relativeDirectory = Get-RelativePathCompat -BasePath $BackupDirectory -TargetPath $_.FullName |
| | | $targetPluginDirectory = Join-Path $pluginsRoot $relativeDirectory |
| | | $newPluginJson = Join-Path $targetPluginDirectory "plugin.json" |
| | | $templateJson = Join-Path $targetPluginDirectory "plugin.template.json" |
| | | $backupPluginJson = Join-Path $_.FullName "plugin.json" |
| | | |
| | | if ((Test-Path -LiteralPath $newPluginJson) -and -not (Test-Path -LiteralPath $templateJson)) { |
| | | Copy-Item -LiteralPath $newPluginJson -Destination $templateJson -Force |
| | | } |
| | | |
| | | if (Test-Path -LiteralPath $backupPluginJson) { |
| | | Copy-Item -LiteralPath $backupPluginJson -Destination $newPluginJson -Force |
| | | } |
| | | } |
| | | } |
| | | |
| | | $repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..") |
| | | $solutionPath = Join-Path $repoRoot "Moli.Desktop.slnx" |
| | | $projectPath = Join-Path $repoRoot "src\Moli.Desktop\Moli.Desktop.csproj" |
| | | $stagingRoot = Join-Path $repoRoot "artifacts\release" |
| | | $publishDir = Join-Path $stagingRoot "publish\$AppName" |
| | | $configBackupDir = Join-Path $stagingRoot "preserved-plugin-configs" |
| | | $targetRootPath = Join-Path $TargetRoot "" |
| | | $targetDir = Join-Path $targetRootPath $AppName |
| | | $targetExePath = Join-Path $targetDir "$AppName.exe" |
| | |
| | | |
| | | Stop-PublishedApplication -ProcessName $AppName -ExecutablePath $targetExePath |
| | | |
| | | if (Test-Path -LiteralPath $configBackupDir) { |
| | | Remove-Item -LiteralPath $configBackupDir -Recurse -Force |
| | | } |
| | | New-Item -ItemType Directory -Force -Path $configBackupDir | Out-Null |
| | | Backup-DeployedPluginConfigs -ApplicationDirectory $targetDir -BackupDirectory $configBackupDir |
| | | |
| | | if (Test-Path -LiteralPath $targetDir) { |
| | | Write-Host "Removing old published files:" |
| | | Write-Host $targetDir |
| | |
| | | New-Item -ItemType Directory -Force -Path $targetDir | Out-Null |
| | | |
| | | Invoke-CheckedRobocopy -Source $publishDir -Destination $targetDir |
| | | Restore-DeployedPluginConfigs -ApplicationDirectory $targetDir -BackupDirectory $configBackupDir |
| | | |
| | | if (-not $NoZip) { |
| | | if (Test-Path -LiteralPath $zipPath) { |
| | |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task Update_AllowsUnlockingLockedWidget() |
| | | { |
| | | var (manager, monitor, _) = await CreateLoadedManagerAsync(); |
| | | var plugin = CreatePlugin(locked: true); |
| | | var layout = manager.CreateFromPlugin(plugin, monitor.Id); |
| | | |
| | | var result = manager.Update(layout.InstanceId, new WidgetLayoutPatch { IsLocked = false }); |
| | | |
| | | Assert.True(result.Succeeded); |
| | | Assert.False(result.Value?.IsLocked); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task ReconcileMonitors_MovesMissingSecondaryMonitorToPrimary() |
| | | { |
| | | var (manager, _, diagnostics) = await CreateLoadedManagerAsync(); |
| New file |
| | |
| | | using System.Net; |
| | | using System.Net.Http; |
| | | using System.Text; |
| | | using Microsoft.Extensions.Logging.Abstractions; |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Host; |
| | | using Moli.Desktop.Llm; |
| | | |
| | | namespace Moli.Desktop.Tests.Llm; |
| | | |
| | | public class AiChatClientTests |
| | | { |
| | | [Fact] |
| | | public async Task GetProjectsAsync_LogsInWithPasswordEnvAndSendsSessionToken() |
| | | { |
| | | var envName = "MOLI_AICHAT_TEST_PASSWORD_" + Guid.NewGuid().ToString("N"); |
| | | Environment.SetEnvironmentVariable(envName, "secret-from-env"); |
| | | try |
| | | { |
| | | var handler = new QueueHttpMessageHandler( |
| | | Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""), |
| | | Json("""{"ok":true,"data":[{"id":"project-1","name":"产品问答","projectType":"CHAT","memoryMode":"ISOLATED"}]}""")); |
| | | var client = CreateClient(handler); |
| | | |
| | | var projects = await client.GetProjectsAsync(CreateConfig(passwordEnv: envName)); |
| | | |
| | | Assert.Single(projects); |
| | | Assert.Equal("project-1", projects[0].Id); |
| | | Assert.Equal("secret-from-env", handler.RequestBodies[0].Contains("secret-from-env") ? "secret-from-env" : ""); |
| | | Assert.True(handler.Requests[1].Headers.TryGetValues("x-session-token", out var tokens)); |
| | | Assert.Contains("session-1", tokens); |
| | | } |
| | | finally |
| | | { |
| | | Environment.SetEnvironmentVariable(envName, null); |
| | | } |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task GetModelsAsync_ReturnsAiChatSafeModelSummaries() |
| | | { |
| | | var handler = new QueueHttpMessageHandler( |
| | | Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""), |
| | | Json("""{"ok":true,"data":{"models":["deepseek-v4-flash"],"defaultModel":"deepseek-v4-flash"}}""")); |
| | | var client = CreateClient(handler); |
| | | |
| | | var models = await client.GetModelsAsync(CreateConfig()); |
| | | |
| | | var model = Assert.Single(models); |
| | | Assert.Equal("deepseek-v4-flash", model.Id); |
| | | Assert.Equal("aichat", model.Provider); |
| | | Assert.True(model.SupportsStreaming); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task StreamChatAsync_UsesAiChatSendAndParsesSseChunks() |
| | | { |
| | | var handler = new QueueHttpMessageHandler( |
| | | Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""), |
| | | Json("""{"ok":true,"data":{"generationId":"gen-1","streamToken":"stream-1","projectId":"project-1","conversationId":"conv-1"}}"""), |
| | | Sse(""" |
| | | event: chunk |
| | | data: {"type":"chunk","delta":"Hello","sequence":1} |
| | | |
| | | event: done |
| | | data: {"type":"done","generationId":"gen-1"} |
| | | |
| | | """)); |
| | | var client = CreateClient(handler); |
| | | |
| | | var events = await client.StreamChatAsync( |
| | | new LlmChatRequest |
| | | { |
| | | RequestId = "req-1", |
| | | PluginId = "sample.llm-command-palette", |
| | | InstanceId = "host-1", |
| | | Mode = LlmConnectionModes.AiChatApi, |
| | | ProjectId = "project-1", |
| | | ModelId = "deepseek-v4-flash", |
| | | Messages = [new LlmMessage { Role = "user", Content = "hello" }] |
| | | }, |
| | | CreateConfig()).ToListAsync(); |
| | | |
| | | Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "Hello" }); |
| | | Assert.Contains(events, item => item is LlmCompletedEvent); |
| | | Assert.Contains("/api/chat/send", handler.Requests[1].RequestUri?.PathAndQuery); |
| | | Assert.Contains("/api/chat/generations/gen-1/stream?token=stream-1", handler.Requests[2].RequestUri?.PathAndQuery); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task RecallMemoriesAsync_PostsToAiChatMemoryRecall() |
| | | { |
| | | var handler = new QueueHttpMessageHandler( |
| | | Json("""{"ok":true,"data":{"sessionToken":"session-1"}}"""), |
| | | Json("""{"ok":true,"data":{"items":[{"id":"mem-1","content":"Keep replies short."}]}}""")); |
| | | var client = CreateClient(handler); |
| | | |
| | | var result = await client.RecallMemoriesAsync( |
| | | CreateConfig(), |
| | | new AiChatRecallMemoriesRequest |
| | | { |
| | | Query = "hello", |
| | | Scope = "PROJECT", |
| | | ProjectId = "project-1", |
| | | Limit = 8 |
| | | }); |
| | | |
| | | Assert.NotNull(result.Data); |
| | | Assert.Equal("/api/memories/recall", handler.Requests[1].RequestUri?.PathAndQuery); |
| | | Assert.Contains("project-1", handler.RequestBodies[1]); |
| | | } |
| | | |
| | | private static AiChatClient CreateClient(QueueHttpMessageHandler handler) |
| | | { |
| | | var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N")); |
| | | var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local")); |
| | | var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance); |
| | | return new AiChatClient(new HttpClient(handler), diagnostics); |
| | | } |
| | | |
| | | private static LlmPluginRuntimeConfig CreateConfig(string? passwordEnv = null) => new() |
| | | { |
| | | Mode = LlmConnectionModes.AiChatApi, |
| | | AiChat = new AiChatRuntimeConfig |
| | | { |
| | | BaseUrl = "http://192.168.1.111:13000", |
| | | Account = new AiChatAccountConfig |
| | | { |
| | | Email = "user@example.com", |
| | | Password = passwordEnv is null ? "plain-secret" : null, |
| | | PasswordEnv = passwordEnv |
| | | } |
| | | } |
| | | }; |
| | | |
| | | private static HttpResponseMessage Json(string content, HttpStatusCode statusCode = HttpStatusCode.OK) => new(statusCode) |
| | | { |
| | | Content = new StringContent(content, Encoding.UTF8, "application/json") |
| | | }; |
| | | |
| | | private static HttpResponseMessage Sse(string content) => new(HttpStatusCode.OK) |
| | | { |
| | | Content = new StringContent(content, Encoding.UTF8, "text/event-stream") |
| | | }; |
| | | |
| | | private sealed class QueueHttpMessageHandler : HttpMessageHandler |
| | | { |
| | | private readonly Queue<HttpResponseMessage> _responses; |
| | | |
| | | public QueueHttpMessageHandler(params HttpResponseMessage[] responses) |
| | | { |
| | | _responses = new Queue<HttpResponseMessage>(responses); |
| | | } |
| | | |
| | | public List<HttpRequestMessage> Requests { get; } = []; |
| | | public List<string> RequestBodies { get; } = []; |
| | | |
| | | protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| | | { |
| | | Requests.Add(request); |
| | | RequestBodies.Add(request.Content is null ? "" : await request.Content.ReadAsStringAsync(cancellationToken)); |
| | | return _responses.Dequeue(); |
| | | } |
| | | } |
| | | } |
| | |
| | | Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" }); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task StreamChatAsync_UsesAiChatClientWhenModeIsAiChatApi() |
| | | { |
| | | var aiChat = new FakeAiChatClient(); |
| | | var gateway = CreateGateway( |
| | | new CapturingAdapter("openai-compatible"), |
| | | aiChat, |
| | | new LlmModelConfig |
| | | { |
| | | Id = "provider-model", |
| | | Label = "Provider", |
| | | Provider = "openai-compatible", |
| | | Endpoint = "http://127.0.0.1:11434/v1/chat/completions", |
| | | ApiModel = "provider-model", |
| | | Enabled = true |
| | | }); |
| | | |
| | | var events = await gateway.StreamChatAsync(new LlmChatRequest |
| | | { |
| | | RequestId = "req-aichat", |
| | | PluginId = "sample.llm-command-palette", |
| | | InstanceId = "host-1", |
| | | Mode = LlmConnectionModes.AiChatApi, |
| | | ProjectId = "project-1", |
| | | ModelId = "deepseek-v4-flash", |
| | | Messages = [new LlmMessage { Role = "user", Content = "hello" }], |
| | | RuntimeConfig = new LlmPluginRuntimeConfig { Mode = LlmConnectionModes.AiChatApi } |
| | | }).ToListAsync(); |
| | | |
| | | Assert.Equal("project-1", aiChat.LastRequest?.ProjectId); |
| | | Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "from-aichat" }); |
| | | } |
| | | |
| | | private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models) |
| | | => CreateGateway(adapter, null, models); |
| | | |
| | | private static LlmGatewayService CreateGateway(CapturingAdapter adapter, IAiChatClient? aiChatClient, params LlmModelConfig[] models) |
| | | { |
| | | var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N")); |
| | | var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local")); |
| | |
| | | new InMemoryRegistry(models), |
| | | new EnvironmentCredentialStore(), |
| | | new LlmProviderAdapterFactory([adapter]), |
| | | diagnostics); |
| | | diagnostics, |
| | | aiChatClient); |
| | | } |
| | | |
| | | private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry |
| | |
| | | yield return new LlmProviderChunk { IsCompleted = true }; |
| | | } |
| | | } |
| | | |
| | | private sealed class FakeAiChatClient : IAiChatClient |
| | | { |
| | | public LlmChatRequest? LastRequest { get; private set; } |
| | | |
| | | public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]); |
| | | |
| | | public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([]); |
| | | |
| | | public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | { |
| | | await Task.Yield(); |
| | | LastRequest = request; |
| | | yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "from-aichat" }; |
| | | yield return new LlmCompletedEvent { RequestId = request.RequestId }; |
| | | } |
| | | |
| | | public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatMemoryCapabilities()); |
| | | |
| | | public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult()); |
| | | |
| | | public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult()); |
| | | |
| | | public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default) |
| | | => Task.CompletedTask; |
| | | |
| | | public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult()); |
| | | } |
| | | } |
| | | |
| | | internal static class AsyncEnumerableTestExtensions |
| | |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task DispatchAsync_ReturnsLlmModelsFromPluginConfig() |
| | | { |
| | | var dispatcher = CreateDispatcher(out _, out _); |
| | | var context = CreateContext(configJson: """ |
| | | { |
| | | "mode": "provider-direct", |
| | | "defaultModel": "configured-model", |
| | | "models": [ |
| | | { |
| | | "id": "configured-model", |
| | | "label": "Configured Model", |
| | | "provider": "test", |
| | | "endpoint": "https://example.test/chat", |
| | | "apiModel": "configured-model", |
| | | "supportsStreaming": true, |
| | | "enabled": true |
| | | } |
| | | ] |
| | | } |
| | | """); |
| | | |
| | | var response = await dispatcher.DispatchAsync("""{"id":"40","method":"llm.getModels"}""", context); |
| | | |
| | | Assert.True(response.Success); |
| | | var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web)); |
| | | Assert.Contains("configured-model", json); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task DispatchAsync_ReturnsAiChatProjects() |
| | | { |
| | | var dispatcher = CreateDispatcher(out _, out _); |
| | | |
| | | var response = await dispatcher.DispatchAsync("""{"id":"41","method":"llm.getProjects"}""", CreateContext()); |
| | | |
| | | Assert.True(response.Success); |
| | | var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web)); |
| | | Assert.Contains("project-1", json); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task DispatchAsync_ReturnsMemoryRecallResult() |
| | | { |
| | | var dispatcher = CreateDispatcher(out _, out _); |
| | | |
| | | var response = await dispatcher.DispatchAsync( |
| | | """{"id":"42","method":"llm.recallMemories","params":{"query":"hello","scope":"PROJECT","projectId":"project-1","limit":8}}""", |
| | | CreateContext()); |
| | | |
| | | Assert.True(response.Success); |
| | | var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web)); |
| | | Assert.Contains("remember this", json); |
| | | } |
| | | |
| | | [Fact] |
| | | public async Task DispatchAsync_RejectsLlmStreamWithoutPermission() |
| | | { |
| | | var dispatcher = CreateDispatcher(out _, out _); |
| | |
| | | Assert.Contains("getRuntimeInfo", script); |
| | | Assert.Contains("requestResize", script); |
| | | Assert.Contains("llm", script); |
| | | Assert.Contains("getProjects", script); |
| | | Assert.Contains("recallMemories", script); |
| | | Assert.Contains("streamChat", script); |
| | | Assert.Contains("moliDesktopResponse", script); |
| | | } |
| | |
| | | return new PluginBridgeDispatcher(diagnostics, events, new FakeLlmGateway()); |
| | | } |
| | | |
| | | private static PluginBridgeContext CreateContext(bool includeLlmPermission = true) |
| | | private static PluginBridgeContext CreateContext(bool includeLlmPermission = true, string configJson = """{"label":"clock"}""") |
| | | { |
| | | return new PluginBridgeContext |
| | | { |
| | |
| | | PluginType = PluginType.Widget, |
| | | HostId = "host-1" |
| | | }, |
| | | Config = JsonDocument.Parse("""{"label":"clock"}""").RootElement.Clone() |
| | | Config = JsonDocument.Parse(configJson).RootElement.Clone() |
| | | }; |
| | | } |
| | | |
| | |
| | | } |
| | | ]); |
| | | |
| | | public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => runtimeConfig.Models.Count > 0 |
| | | ? Task.FromResult<IReadOnlyList<LlmModelSummary>>(runtimeConfig.Models |
| | | .Where(model => model.Enabled) |
| | | .Select(model => new LlmModelSummary |
| | | { |
| | | Id = model.Id, |
| | | Label = model.Label, |
| | | Provider = model.Provider, |
| | | SupportsStreaming = model.SupportsStreaming, |
| | | Enabled = model.Enabled |
| | | }) |
| | | .ToList()) |
| | | : GetModelsAsync(cancellationToken); |
| | | |
| | | public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>( |
| | | [ |
| | | new AiChatProjectSummary { Id = "project-1", Name = "Project 1" } |
| | | ]); |
| | | |
| | | public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatMemoryCapabilities { CanUseMemory = true, CanViewMemory = true, CanManageMemory = true }); |
| | | |
| | | public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult { Data = new[] { new { id = "mem-1", content = "remember this" } } }); |
| | | |
| | | public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult { Data = new { id = "mem-2", content = request.Content } }); |
| | | |
| | | public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default) |
| | | => Task.CompletedTask; |
| | | |
| | | public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default) |
| | | => Task.FromResult(new AiChatJsonResult { Data = new { items = new[] { new { id = "mem-1", content = "remember this" } } } }); |
| | | |
| | | public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default) |
| New file |
| | |
| | | using System.IO; |
| | | using System.Text; |
| | | using Microsoft.Extensions.Logging; |
| | | |
| | | namespace Moli.Desktop.Diagnostics; |
| | | |
| | | public sealed class DailyFileLoggerProvider : ILoggerProvider |
| | | { |
| | | private readonly string _logDirectory; |
| | | private readonly object _gate = new(); |
| | | private bool _disposed; |
| | | |
| | | public DailyFileLoggerProvider(string logDirectory) |
| | | { |
| | | _logDirectory = logDirectory; |
| | | Directory.CreateDirectory(_logDirectory); |
| | | } |
| | | |
| | | public ILogger CreateLogger(string categoryName) |
| | | => new DailyFileLogger(categoryName, _logDirectory, _gate, () => _disposed); |
| | | |
| | | public void Dispose() |
| | | { |
| | | _disposed = true; |
| | | } |
| | | |
| | | private sealed class DailyFileLogger( |
| | | string categoryName, |
| | | string logDirectory, |
| | | object gate, |
| | | Func<bool> isDisposed) : ILogger |
| | | { |
| | | public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null; |
| | | |
| | | public bool IsEnabled(LogLevel logLevel) |
| | | => logLevel != LogLevel.None && !isDisposed(); |
| | | |
| | | public void Log<TState>( |
| | | LogLevel logLevel, |
| | | EventId eventId, |
| | | TState state, |
| | | Exception? exception, |
| | | Func<TState, Exception?, string> formatter) |
| | | { |
| | | if (!IsEnabled(logLevel)) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | var message = formatter(state, exception); |
| | | if (string.IsNullOrWhiteSpace(message) && exception is null) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | var now = DateTimeOffset.Now; |
| | | var line = $"{now:O} [{logLevel}] {categoryName} {message}"; |
| | | if (exception is not null) |
| | | { |
| | | line += $" {exception.GetType().Name}: {exception.Message}"; |
| | | } |
| | | |
| | | var path = Path.Combine(logDirectory, $"moli-desktop-{now:yyyyMMdd}.log"); |
| | | try |
| | | { |
| | | lock (gate) |
| | | { |
| | | File.AppendAllText(path, line + Environment.NewLine, Encoding.UTF8); |
| | | } |
| | | } |
| | | catch (IOException) |
| | | { |
| | | } |
| | | catch (UnauthorizedAccessException) |
| | | { |
| | | } |
| | | } |
| | | } |
| | | } |
| | |
| | | private readonly object _gate = new(); |
| | | private readonly List<DiagnosticEntry> _entries = []; |
| | | private readonly ILogger<DiagnosticsService> _logger; |
| | | private readonly string _logFile; |
| | | private readonly string _logDirectory; |
| | | |
| | | public DiagnosticsService(DesktopPaths paths, ILogger<DiagnosticsService> logger) |
| | | { |
| | | _logger = logger; |
| | | Directory.CreateDirectory(paths.LogDirectory); |
| | | _logFile = Path.Combine(paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log"); |
| | | _logDirectory = paths.LogDirectory; |
| | | } |
| | | |
| | | public DiagnosticEntry Record( |
| | |
| | | |
| | | try |
| | | { |
| | | File.AppendAllText(_logFile, line + Environment.NewLine, Encoding.UTF8); |
| | | File.AppendAllText( |
| | | Path.Combine(_logDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log"), |
| | | line + Environment.NewLine, |
| | | Encoding.UTF8); |
| | | } |
| | | catch (IOException) |
| | | { |
| | |
| | | } |
| | | |
| | | var targetDirectory = Path.Combine(_paths.PluginDirectory, manifest.Id); |
| | | CopyDirectoryReplacingFiles(sourceDirectory, targetDirectory); |
| | | CopyDirectoryPreservingPluginConfig(sourceDirectory, targetDirectory); |
| | | manifests.Add((manifest, manifest.Id)); |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | private static void CopyDirectoryReplacingFiles(string sourceDirectory, string targetDirectory) |
| | | private static void CopyDirectoryPreservingPluginConfig(string sourceDirectory, string targetDirectory) |
| | | { |
| | | Directory.CreateDirectory(targetDirectory); |
| | | |
| | |
| | | var relativePath = Path.GetRelativePath(sourceDirectory, sourceFile); |
| | | var targetFile = Path.Combine(targetDirectory, relativePath); |
| | | Directory.CreateDirectory(Path.GetDirectoryName(targetFile)!); |
| | | |
| | | if (string.Equals(relativePath, "plugin.json", StringComparison.OrdinalIgnoreCase) && |
| | | File.Exists(targetFile)) |
| | | { |
| | | File.Copy(sourceFile, Path.Combine(targetDirectory, "plugin.template.json"), overwrite: true); |
| | | continue; |
| | | } |
| | | |
| | | File.Copy(sourceFile, targetFile, overwrite: true); |
| | | } |
| | | } |
| | |
| | | return Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args) |
| | | .ConfigureLogging(logging => |
| | | { |
| | | var paths = new DesktopPaths(); |
| | | logging.ClearProviders(); |
| | | logging.AddDebug(); |
| | | logging.AddProvider(new DailyFileLoggerProvider(paths.LogDirectory)); |
| | | }) |
| | | .ConfigureServices(services => |
| | | { |
| | |
| | | services.AddSingleton<ILlmModelRegistry, LlmModelRegistry>(); |
| | | services.AddSingleton<ICredentialStore, EnvironmentCredentialStore>(); |
| | | services.AddHttpClient<OpenAICompatibleAdapter>(); |
| | | services.AddHttpClient<AiChatClient>(); |
| | | services.AddSingleton<IAiChatClient>(sp => sp.GetRequiredService<AiChatClient>()); |
| | | services.AddSingleton<ILlmProviderAdapter>(sp => sp.GetRequiredService<OpenAICompatibleAdapter>()); |
| | | services.AddSingleton<ILlmProviderAdapterFactory, LlmProviderAdapterFactory>(); |
| | | services.AddSingleton<ILlmGatewayService, LlmGatewayService>(); |
| | |
| | | LocalAppDataRoot = localAppDataRoot; |
| | | ConfigDirectory = Path.Combine(AppDataRoot, "config"); |
| | | PluginDirectory = Path.Combine(AppDataRoot, "plugins"); |
| | | LogDirectory = Path.Combine(LocalAppDataRoot, "logs"); |
| | | LogDirectory = Path.Combine(AppContext.BaseDirectory, "logs"); |
| | | WebViewDataDirectory = Path.Combine(LocalAppDataRoot, "WebView2"); |
| | | } |
| | | |
| | |
| | | |
| | | internal static class NativeMethods |
| | | { |
| | | internal const int GwlStyle = -16; |
| | | internal const int GwlExStyle = -20; |
| | | internal const uint WsChild = 0x40000000; |
| | | internal const uint WsPopup = 0x80000000; |
| | | internal const uint WsVisible = 0x10000000; |
| | | internal const int WsExTransparent = 0x00000020; |
| | | internal const int WsExLayered = 0x00080000; |
| | | internal const int WsExToolWindow = 0x00000080; |
| | |
| | | internal const uint SwpNoMove = 0x0002; |
| | | internal const uint SwpNoZOrder = 0x0004; |
| | | internal const uint SwpNoActivate = 0x0010; |
| | | internal const uint SwpFrameChanged = 0x0020; |
| | | internal const uint SwpShowWindow = 0x0040; |
| | | internal const uint SmtoNormal = 0x0000; |
| | | internal static readonly IntPtr HwndBottom = new(1); |
| | |
| | | |
| | | public void RestoreTopLevelWindow(IntPtr hwnd) |
| | | { |
| | | RestoreTopLevelStyle(hwnd); |
| | | NativeMethods.SetParent(hwnd, IntPtr.Zero); |
| | | var error = NativeMethods.GetLastError(); |
| | | if (error != 0) |
| | |
| | | DiagnosticCodes.Win32InteropFailed, |
| | | "RestoreTopLevelWindow failed.", |
| | | new Dictionary<string, string> { ["hwnd"] = hwnd.ToString("X"), ["error"] = error.ToString() }); |
| | | } |
| | | |
| | | if (!NativeMethods.SetWindowPos( |
| | | hwnd, |
| | | IntPtr.Zero, |
| | | 0, |
| | | 0, |
| | | 0, |
| | | 0, |
| | | NativeMethods.SwpNoMove | NativeMethods.SwpNoSize | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged)) |
| | | { |
| | | RecordWin32Failure("RestoreTopLevelWindow.SetWindowPos", hwnd); |
| | | } |
| | | } |
| | | |
| | |
| | | { |
| | | return new RectD(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top); |
| | | } |
| | | |
| | | private static void RestoreTopLevelStyle(IntPtr hwnd) |
| | | { |
| | | var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64()); |
| | | var updated = (current | NativeMethods.WsPopup | NativeMethods.WsVisible) & ~NativeMethods.WsChild; |
| | | NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated))); |
| | | } |
| | | } |
| | |
| | | |
| | | namespace Moli.Desktop.Interop; |
| | | |
| | | /// <summary>Attempts to attach wallpaper windows behind desktop icons through Explorer's WorkerW layer.</summary> |
| | | /// <summary>Attempts to attach desktop surfaces through Explorer's WorkerW or Progman desktop host.</summary> |
| | | public sealed class WorkerWDesktopLayerStrategy : IDesktopLayerStrategy |
| | | { |
| | | private readonly IDiagnosticsService _diagnostics; |
| | |
| | | public bool TryAttachDesktopWindow(IntPtr hwnd, RectD bounds, out string? error) |
| | | { |
| | | error = null; |
| | | var workerW = FindWorkerW(); |
| | | if (workerW == IntPtr.Zero) |
| | | var desktopHost = FindDesktopHostWindow(out var hostClass); |
| | | if (desktopHost == IntPtr.Zero) |
| | | { |
| | | error = "WorkerW window was not found."; |
| | | error = "Explorer desktop host window was not found."; |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Warning, |
| | | DiagnosticCodes.DesktopLayerAttachFailed, |
| | | "WorkerW desktop layer was not found.", |
| | | "Explorer desktop host window was not found.", |
| | | new Dictionary<string, string> { ["strategy"] = Name }); |
| | | return false; |
| | | } |
| | | |
| | | if (NativeMethods.SetParent(hwnd, workerW) == IntPtr.Zero) |
| | | SetDesktopChildStyle(hwnd); |
| | | |
| | | if (NativeMethods.SetParent(hwnd, desktopHost) == IntPtr.Zero) |
| | | { |
| | | var lastError = NativeMethods.GetLastError(); |
| | | if (lastError != 0) |
| | | { |
| | | error = $"SetParent failed with {lastError}"; |
| | | RestoreTopLevelStyle(hwnd); |
| | | return false; |
| | | } |
| | | } |
| | |
| | | (int)bounds.Y, |
| | | (int)bounds.Width, |
| | | (int)bounds.Height, |
| | | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpShowWindow)) |
| | | NativeMethods.SwpNoZOrder | NativeMethods.SwpNoActivate | NativeMethods.SwpFrameChanged | NativeMethods.SwpShowWindow)) |
| | | { |
| | | error = $"SetWindowPos failed with {NativeMethods.GetLastError()}"; |
| | | NativeMethods.SetParent(hwnd, IntPtr.Zero); |
| | | RestoreTopLevelStyle(hwnd); |
| | | return false; |
| | | } |
| | | |
| | |
| | | DiagnosticSeverity.Info, |
| | | DiagnosticCodes.DesktopLayerStrategySelected, |
| | | "Desktop layer strategy selected.", |
| | | new Dictionary<string, string> { ["strategy"] = Name }); |
| | | new Dictionary<string, string> { ["strategy"] = Name, ["host"] = hostClass }); |
| | | return true; |
| | | } |
| | | |
| | | private static IntPtr FindWorkerW() |
| | | private static IntPtr FindDesktopHostWindow(out string hostClass) |
| | | { |
| | | hostClass = "WorkerW"; |
| | | var progman = NativeMethods.FindWindow("Progman", null); |
| | | if (progman != IntPtr.Zero) |
| | | { |
| | | NativeMethods.SendMessageTimeout( |
| | | progman, |
| | | 0x052C, |
| | | new IntPtr(0xD), |
| | | IntPtr.Zero, |
| | | NativeMethods.SmtoNormal, |
| | | 1000, |
| | | out _); |
| | | NativeMethods.SendMessageTimeout( |
| | | progman, |
| | | 0x052C, |
| | |
| | | return workerW == IntPtr.Zero; |
| | | }, IntPtr.Zero); |
| | | |
| | | if (workerW != IntPtr.Zero) |
| | | { |
| | | return workerW; |
| | | } |
| | | |
| | | hostClass = "Progman"; |
| | | return progman; |
| | | } |
| | | |
| | | private static void SetDesktopChildStyle(IntPtr hwnd) |
| | | { |
| | | var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64()); |
| | | var updated = (current | NativeMethods.WsChild | NativeMethods.WsVisible) & ~NativeMethods.WsPopup; |
| | | NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated))); |
| | | } |
| | | |
| | | private static void RestoreTopLevelStyle(IntPtr hwnd) |
| | | { |
| | | var current = unchecked((uint)NativeMethods.GetWindowLongPtr(hwnd, NativeMethods.GwlStyle).ToInt64()); |
| | | var updated = (current | NativeMethods.WsPopup | NativeMethods.WsVisible) & ~NativeMethods.WsChild; |
| | | NativeMethods.SetWindowLongPtr(hwnd, NativeMethods.GwlStyle, new IntPtr(unchecked((int)updated))); |
| | | } |
| | | } |
| | |
| | | ClickThrough = patch.ClickThrough ?? layout.ClickThrough, |
| | | Scale = patch.Scale ?? layout.Scale, |
| | | DisplayLayer = patch.DisplayLayer ?? layout.DisplayLayer |
| | | }); |
| | | }, allowLocked: IsUnlockPatch(patch)); |
| | | } |
| | | |
| | | public IReadOnlyList<WidgetLayout> ReconcileMonitors(IReadOnlyList<MonitorInfo> monitors) |
| | |
| | | } |
| | | } |
| | | |
| | | private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update) |
| | | private OperationResult<WidgetLayout> Mutate(WidgetInstanceId instanceId, Func<WidgetLayout, WidgetLayout> update, bool allowLocked = false) |
| | | { |
| | | lock (_gate) |
| | | { |
| | |
| | | } |
| | | |
| | | var current = _document.Instances[index]; |
| | | if (current.IsLocked) |
| | | if (current.IsLocked && !allowLocked) |
| | | { |
| | | return OperationResult<WidgetLayout>.Failure("WidgetLayoutLocked", $"Widget layout {instanceId} is locked."); |
| | | } |
| | |
| | | |
| | | private static double Clamp(double value, double min, double max) |
| | | => Math.Min(Math.Max(value, min), max); |
| | | |
| | | private static bool IsUnlockPatch(WidgetLayoutPatch patch) |
| | | => patch.IsLocked == false && |
| | | patch.Bounds is null && |
| | | patch.MonitorId is null && |
| | | patch.IsVisible is null && |
| | | patch.Opacity is null && |
| | | patch.ClickThrough is null && |
| | | patch.Scale is null && |
| | | patch.DisplayLayer is null; |
| | | } |
| New file |
| | |
| | | using System.Collections.Concurrent; |
| | | using System.Net; |
| | | using System.Net.Http; |
| | | using System.Net.Http.Headers; |
| | | using System.Runtime.CompilerServices; |
| | | using System.Text; |
| | | using System.Text.Json; |
| | | using System.IO; |
| | | using Moli.Desktop.Diagnostics; |
| | | |
| | | namespace Moli.Desktop.Llm; |
| | | |
| | | public sealed class AiChatClient : IAiChatClient |
| | | { |
| | | private readonly HttpClient _httpClient; |
| | | private readonly IDiagnosticsService _diagnostics; |
| | | private readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); |
| | | private readonly ConcurrentDictionary<string, string> _sessionTokens = new(StringComparer.OrdinalIgnoreCase); |
| | | |
| | | public AiChatClient(HttpClient httpClient, IDiagnosticsService diagnostics) |
| | | { |
| | | _httpClient = httpClient; |
| | | _diagnostics = diagnostics; |
| | | } |
| | | |
| | | public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/chat/models", null, cancellationToken).ConfigureAwait(false); |
| | | if (!TryGetData(document.RootElement, out var data) || |
| | | !data.TryGetProperty("models", out var modelsElement) || |
| | | modelsElement.ValueKind != JsonValueKind.Array) |
| | | { |
| | | return []; |
| | | } |
| | | |
| | | var defaultModel = data.TryGetProperty("defaultModel", out var defaultModelElement) |
| | | ? defaultModelElement.GetString() |
| | | : null; |
| | | |
| | | return modelsElement |
| | | .EnumerateArray() |
| | | .Where(item => item.ValueKind == JsonValueKind.String && !string.IsNullOrWhiteSpace(item.GetString())) |
| | | .Select(item => |
| | | { |
| | | var id = item.GetString()!; |
| | | return new LlmModelSummary |
| | | { |
| | | Id = id, |
| | | Label = id == defaultModel ? $"{id} *" : id, |
| | | Provider = "aichat", |
| | | SupportsStreaming = true, |
| | | Enabled = true |
| | | }; |
| | | }) |
| | | .ToList(); |
| | | } |
| | | |
| | | public async Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | try |
| | | { |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/projects", null, cancellationToken).ConfigureAwait(false); |
| | | if (!TryGetProjectsData(document.RootElement, out var data)) |
| | | { |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Warning, |
| | | LlmErrorCodes.AiChatProjectLoadFailed, |
| | | "AiChat project response did not contain a project array.", |
| | | new Dictionary<string, string> { ["baseUrl"] = runtimeConfig.AiChat.BaseUrl }); |
| | | return []; |
| | | } |
| | | |
| | | return data.EnumerateArray() |
| | | .Select(ParseProject) |
| | | .Where(project => project is not null) |
| | | .Select(project => project!) |
| | | .ToList(); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Warning, |
| | | ex.Code, |
| | | "AiChat projects could not be loaded.", |
| | | new Dictionary<string, string> |
| | | { |
| | | ["baseUrl"] = runtimeConfig.AiChat.BaseUrl, |
| | | ["exception"] = ex.GetType().Name |
| | | }); |
| | | throw; |
| | | } |
| | | } |
| | | |
| | | public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | | { |
| | | JsonDocument? sendDocument = null; |
| | | LlmErrorEvent? startError = null; |
| | | try |
| | | { |
| | | var message = request.Messages.LastOrDefault(message => string.Equals(message.Role, "user", StringComparison.OrdinalIgnoreCase))?.Content |
| | | ?? request.Messages.Last().Content; |
| | | var payload = new |
| | | { |
| | | projectId = request.ProjectId, |
| | | modelName = request.ModelId, |
| | | message |
| | | }; |
| | | sendDocument = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/chat/send", payload, cancellationToken).ConfigureAwait(false); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | startError = new LlmErrorEvent { RequestId = request.RequestId, Code = ex.Code, Message = ex.Message }; |
| | | } |
| | | |
| | | if (startError is not null) |
| | | { |
| | | yield return startError; |
| | | yield break; |
| | | } |
| | | |
| | | var generationDocument = sendDocument; |
| | | if (generationDocument is null) |
| | | { |
| | | yield return new LlmErrorEvent |
| | | { |
| | | RequestId = request.RequestId, |
| | | Code = LlmErrorCodes.AiChatApiFailed, |
| | | Message = "AiChat did not return a valid generation stream." |
| | | }; |
| | | yield break; |
| | | } |
| | | |
| | | using (generationDocument) |
| | | { |
| | | if (!TryGetData(generationDocument.RootElement, out var data) || |
| | | !data.TryGetProperty("generationId", out var generationIdElement) || |
| | | !data.TryGetProperty("streamToken", out var streamTokenElement) || |
| | | string.IsNullOrWhiteSpace(generationIdElement.GetString()) || |
| | | string.IsNullOrWhiteSpace(streamTokenElement.GetString())) |
| | | { |
| | | yield return new LlmErrorEvent |
| | | { |
| | | RequestId = request.RequestId, |
| | | Code = LlmErrorCodes.AiChatApiFailed, |
| | | Message = "AiChat did not return a valid generation stream." |
| | | }; |
| | | yield break; |
| | | } |
| | | |
| | | var path = $"/api/chat/generations/{Uri.EscapeDataString(generationIdElement.GetString()!)}/stream?token={Uri.EscapeDataString(streamTokenElement.GetString()!)}"; |
| | | await foreach (var streamEvent in StreamAiChatEventsAsync(runtimeConfig, request.RequestId, path, cancellationToken).ConfigureAwait(false)) |
| | | { |
| | | yield return streamEvent; |
| | | } |
| | | } |
| | | } |
| | | |
| | | public async Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, "/api/auth/me", null, cancellationToken).ConfigureAwait(false); |
| | | if (!TryGetData(document.RootElement, out var data)) |
| | | { |
| | | return new AiChatMemoryCapabilities(); |
| | | } |
| | | |
| | | return new AiChatMemoryCapabilities |
| | | { |
| | | CanUseMemory = ReadBool(data, "canUseMemory"), |
| | | CanViewMemory = ReadBool(data, "canViewMemory"), |
| | | CanManageMemory = ReadBool(data, "canManageMemory") |
| | | }; |
| | | } |
| | | |
| | | public async Task<AiChatJsonResult> GetMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatGetMemoriesRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | var query = new List<string>(); |
| | | if (!string.IsNullOrWhiteSpace(request.Scope)) |
| | | { |
| | | query.Add($"scope={Uri.EscapeDataString(request.Scope)}"); |
| | | } |
| | | |
| | | if (!string.IsNullOrWhiteSpace(request.ProjectId)) |
| | | { |
| | | query.Add($"projectId={Uri.EscapeDataString(request.ProjectId)}"); |
| | | } |
| | | |
| | | var path = "/api/memories" + (query.Count > 0 ? "?" + string.Join("&", query) : ""); |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); |
| | | return CloneData(document); |
| | | } |
| | | |
| | | public async Task<AiChatJsonResult> CreateMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatCreateMemoryRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories", request, cancellationToken).ConfigureAwait(false); |
| | | return CloneData(document); |
| | | } |
| | | |
| | | public async Task DeleteMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | string memoryId, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | if (string.IsNullOrWhiteSpace(memoryId)) |
| | | { |
| | | throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "memoryId is required."); |
| | | } |
| | | |
| | | using var _ = await SendJsonAsync(runtimeConfig, HttpMethod.Delete, $"/api/memories/{Uri.EscapeDataString(memoryId)}", null, cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | public async Task<AiChatJsonResult> RecallMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatRecallMemoriesRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | using var document = await SendJsonAsync(runtimeConfig, HttpMethod.Post, "/api/memories/recall", request, cancellationToken).ConfigureAwait(false); |
| | | return CloneData(document); |
| | | } |
| | | |
| | | private async IAsyncEnumerable<LlmStreamEvent> StreamAiChatEventsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | string requestId, |
| | | string path, |
| | | [EnumeratorCancellation] CancellationToken cancellationToken) |
| | | { |
| | | using var request = await CreateRequestAsync(runtimeConfig, HttpMethod.Get, path, null, cancellationToken).ConfigureAwait(false); |
| | | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); |
| | | using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); |
| | | if (!response.IsSuccessStatusCode) |
| | | { |
| | | yield return new LlmErrorEvent |
| | | { |
| | | RequestId = requestId, |
| | | Code = MapStatusCode(response.StatusCode), |
| | | Message = $"AiChat stream returned {(int)response.StatusCode}." |
| | | }; |
| | | yield break; |
| | | } |
| | | |
| | | await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | | using var reader = new StreamReader(stream, Encoding.UTF8); |
| | | var eventName = "message"; |
| | | var dataLines = new List<string>(); |
| | | |
| | | while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line) |
| | | { |
| | | cancellationToken.ThrowIfCancellationRequested(); |
| | | if (line.StartsWith(":", StringComparison.Ordinal)) |
| | | { |
| | | continue; |
| | | } |
| | | |
| | | if (line.Length == 0) |
| | | { |
| | | foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines))) |
| | | { |
| | | yield return streamEvent; |
| | | if (streamEvent is LlmCompletedEvent or LlmErrorEvent) |
| | | { |
| | | yield break; |
| | | } |
| | | } |
| | | |
| | | eventName = "message"; |
| | | dataLines.Clear(); |
| | | continue; |
| | | } |
| | | |
| | | if (line.StartsWith("event:", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | eventName = line["event:".Length..].Trim(); |
| | | continue; |
| | | } |
| | | |
| | | if (line.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | dataLines.Add(line["data:".Length..].TrimStart()); |
| | | } |
| | | } |
| | | |
| | | if (dataLines.Count > 0) |
| | | { |
| | | foreach (var streamEvent in ParseSseEvent(requestId, eventName, string.Join('\n', dataLines))) |
| | | { |
| | | yield return streamEvent; |
| | | if (streamEvent is LlmCompletedEvent or LlmErrorEvent) |
| | | { |
| | | yield break; |
| | | } |
| | | } |
| | | } |
| | | |
| | | yield return new LlmErrorEvent |
| | | { |
| | | RequestId = requestId, |
| | | Code = LlmErrorCodes.AiChatSseInterrupted, |
| | | Message = "AiChat stream ended before completion." |
| | | }; |
| | | } |
| | | |
| | | private IEnumerable<LlmStreamEvent> ParseSseEvent(string requestId, string eventName, string data) |
| | | { |
| | | if (string.IsNullOrWhiteSpace(data)) |
| | | { |
| | | yield break; |
| | | } |
| | | |
| | | JsonDocument document; |
| | | try |
| | | { |
| | | document = JsonDocument.Parse(data); |
| | | } |
| | | catch (JsonException ex) |
| | | { |
| | | throw new AiChatClientException(LlmErrorCodes.StreamParseFailed, "Failed to parse AiChat stream chunk.", ex); |
| | | } |
| | | |
| | | using (document) |
| | | { |
| | | var root = document.RootElement; |
| | | if (eventName.Equals("chunk", StringComparison.OrdinalIgnoreCase) && |
| | | root.TryGetProperty("delta", out var delta) && |
| | | delta.ValueKind == JsonValueKind.String) |
| | | { |
| | | yield return new LlmDeltaEvent { RequestId = requestId, Delta = delta.GetString() ?? "" }; |
| | | yield break; |
| | | } |
| | | |
| | | if (eventName.Equals("snapshot", StringComparison.OrdinalIgnoreCase) && |
| | | root.TryGetProperty("content", out var content) && |
| | | content.ValueKind == JsonValueKind.String && |
| | | !string.IsNullOrEmpty(content.GetString())) |
| | | { |
| | | yield return new LlmDeltaEvent { RequestId = requestId, Delta = content.GetString() ?? "" }; |
| | | yield break; |
| | | } |
| | | |
| | | if (eventName.Equals("done", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | yield return new LlmCompletedEvent { RequestId = requestId }; |
| | | yield break; |
| | | } |
| | | |
| | | if (eventName.Equals("failed", StringComparison.OrdinalIgnoreCase) || |
| | | eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | var message = root.TryGetProperty("error", out var error) && error.ValueKind == JsonValueKind.String |
| | | ? error.GetString() ?? "AiChat request failed." |
| | | : eventName.Equals("aborted", StringComparison.OrdinalIgnoreCase) ? "AiChat request was aborted." : "AiChat request failed."; |
| | | yield return new LlmErrorEvent { RequestId = requestId, Code = LlmErrorCodes.AiChatApiFailed, Message = message }; |
| | | } |
| | | } |
| | | } |
| | | |
| | | private async Task<JsonDocument> SendJsonAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | HttpMethod method, |
| | | string path, |
| | | object? payload, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | using var request = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false); |
| | | using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); |
| | | if (response.StatusCode == HttpStatusCode.Unauthorized) |
| | | { |
| | | ClearSession(runtimeConfig); |
| | | using var retry = await CreateRequestAsync(runtimeConfig, method, path, payload, cancellationToken).ConfigureAwait(false); |
| | | using var retryResponse = await _httpClient.SendAsync(retry, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); |
| | | return await ReadJsonResponseAsync(retryResponse, cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | return await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | private async Task<HttpRequestMessage> CreateRequestAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | HttpMethod method, |
| | | string path, |
| | | object? payload, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | var uri = BuildUri(runtimeConfig, path); |
| | | var request = new HttpRequestMessage(method, uri); |
| | | request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); |
| | | |
| | | if (!path.Equals("/api/auth/login", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | var sessionToken = await EnsureSessionAsync(runtimeConfig, cancellationToken).ConfigureAwait(false); |
| | | request.Headers.Add("x-session-token", sessionToken); |
| | | } |
| | | |
| | | if (payload is not null) |
| | | { |
| | | request.Content = new StringContent(JsonSerializer.Serialize(payload, _jsonOptions), Encoding.UTF8, "application/json"); |
| | | } |
| | | |
| | | return request; |
| | | } |
| | | |
| | | private async Task<string> EnsureSessionAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken) |
| | | { |
| | | var key = SessionKey(runtimeConfig); |
| | | if (_sessionTokens.TryGetValue(key, out var existing) && !string.IsNullOrWhiteSpace(existing)) |
| | | { |
| | | return existing; |
| | | } |
| | | |
| | | var email = runtimeConfig.AiChat.Account.Email; |
| | | var password = ResolvePassword(runtimeConfig); |
| | | if (string.IsNullOrWhiteSpace(email) || string.IsNullOrWhiteSpace(password)) |
| | | { |
| | | throw new AiChatClientException(LlmErrorCodes.AiChatCredentialMissing, "AiChat account or password is missing."); |
| | | } |
| | | |
| | | using var request = new HttpRequestMessage(HttpMethod.Post, BuildUri(runtimeConfig, "/api/auth/login")) |
| | | { |
| | | Content = new StringContent( |
| | | JsonSerializer.Serialize(new { email, password }, _jsonOptions), |
| | | Encoding.UTF8, |
| | | "application/json") |
| | | }; |
| | | using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| | | using var document = await ReadJsonResponseAsync(response, cancellationToken).ConfigureAwait(false); |
| | | if (!TryGetData(document.RootElement, out var data) || |
| | | !data.TryGetProperty("sessionToken", out var token) || |
| | | token.ValueKind != JsonValueKind.String || |
| | | string.IsNullOrWhiteSpace(token.GetString())) |
| | | { |
| | | throw new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "AiChat login did not return a session token."); |
| | | } |
| | | |
| | | _sessionTokens[key] = token.GetString()!; |
| | | return token.GetString()!; |
| | | } |
| | | |
| | | private async Task<JsonDocument> ReadJsonResponseAsync(HttpResponseMessage response, CancellationToken cancellationToken) |
| | | { |
| | | await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); |
| | | JsonDocument document; |
| | | try |
| | | { |
| | | document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); |
| | | } |
| | | catch (JsonException) when (response.Content.Headers.ContentLength == 0) |
| | | { |
| | | document = JsonDocument.Parse("""{"ok":true}"""); |
| | | } |
| | | |
| | | if (!response.IsSuccessStatusCode) |
| | | { |
| | | var (code, message) = ExtractError(document.RootElement, response.StatusCode); |
| | | document.Dispose(); |
| | | throw new AiChatClientException(code, message); |
| | | } |
| | | |
| | | if (document.RootElement.TryGetProperty("ok", out var ok) && ok.ValueKind == JsonValueKind.False) |
| | | { |
| | | var (code, message) = ExtractError(document.RootElement, response.StatusCode); |
| | | document.Dispose(); |
| | | throw new AiChatClientException(code, message); |
| | | } |
| | | |
| | | return document; |
| | | } |
| | | |
| | | private static AiChatProjectSummary? ParseProject(JsonElement item) |
| | | { |
| | | if (!item.TryGetProperty("id", out var id) || id.ValueKind != JsonValueKind.String) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | return new AiChatProjectSummary |
| | | { |
| | | Id = id.GetString()!, |
| | | Name = item.TryGetProperty("name", out var name) && name.ValueKind == JsonValueKind.String ? name.GetString() ?? id.GetString()! : id.GetString()!, |
| | | ProjectType = item.TryGetProperty("projectType", out var projectType) && projectType.ValueKind == JsonValueKind.String ? projectType.GetString() ?? "CHAT" : "CHAT", |
| | | MemoryMode = item.TryGetProperty("memoryMode", out var memoryMode) && memoryMode.ValueKind == JsonValueKind.String ? memoryMode.GetString() ?? "ISOLATED" : "ISOLATED" |
| | | }; |
| | | } |
| | | |
| | | private static AiChatJsonResult CloneData(JsonDocument document) |
| | | { |
| | | if (!TryGetData(document.RootElement, out var data)) |
| | | { |
| | | return new AiChatJsonResult(); |
| | | } |
| | | |
| | | return new AiChatJsonResult { Data = JsonSerializer.Deserialize<object>(data.GetRawText()) }; |
| | | } |
| | | |
| | | private static bool TryGetData(JsonElement root, out JsonElement data) |
| | | { |
| | | if (root.TryGetProperty("data", out data)) |
| | | { |
| | | return true; |
| | | } |
| | | |
| | | data = default; |
| | | return false; |
| | | } |
| | | |
| | | private static bool TryGetProjectsData(JsonElement root, out JsonElement projects) |
| | | { |
| | | if (TryGetData(root, out var data)) |
| | | { |
| | | if (data.ValueKind == JsonValueKind.Array) |
| | | { |
| | | projects = data; |
| | | return true; |
| | | } |
| | | |
| | | if (data.ValueKind == JsonValueKind.Object && |
| | | data.TryGetProperty("projects", out var nestedProjects) && |
| | | nestedProjects.ValueKind == JsonValueKind.Array) |
| | | { |
| | | projects = nestedProjects; |
| | | return true; |
| | | } |
| | | } |
| | | |
| | | projects = default; |
| | | return false; |
| | | } |
| | | |
| | | private static bool ReadBool(JsonElement root, string property) |
| | | => root.TryGetProperty(property, out var value) && |
| | | (value.ValueKind == JsonValueKind.True || (value.ValueKind == JsonValueKind.String && bool.TryParse(value.GetString(), out var parsed) && parsed)); |
| | | |
| | | private static (string Code, string Message) ExtractError(JsonElement root, HttpStatusCode statusCode) |
| | | { |
| | | var apiCode = root.TryGetProperty("code", out var codeElement) && codeElement.ValueKind == JsonValueKind.String |
| | | ? codeElement.GetString() |
| | | : null; |
| | | var message = root.TryGetProperty("error", out var errorElement) && errorElement.ValueKind == JsonValueKind.String |
| | | ? errorElement.GetString() ?? $"AiChat returned {(int)statusCode}." |
| | | : $"AiChat returned {(int)statusCode}."; |
| | | |
| | | return (MapApiCode(apiCode, statusCode), message); |
| | | } |
| | | |
| | | private static string MapApiCode(string? apiCode, HttpStatusCode statusCode) |
| | | { |
| | | if (string.Equals(apiCode, "TOKEN_TOTAL_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase) || |
| | | string.Equals(apiCode, "TOKEN_PER_REQUEST_LIMIT_REACHED", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | return LlmErrorCodes.AiChatQuotaExceeded; |
| | | } |
| | | |
| | | if (string.Equals(apiCode, "PERMISSION_DENIED", StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | return LlmErrorCodes.AiChatMemoryPermissionDenied; |
| | | } |
| | | |
| | | if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden) |
| | | { |
| | | return LlmErrorCodes.AiChatLoginFailed; |
| | | } |
| | | |
| | | return apiCode ?? LlmErrorCodes.AiChatApiFailed; |
| | | } |
| | | |
| | | private static string MapStatusCode(HttpStatusCode statusCode) |
| | | => statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden |
| | | ? LlmErrorCodes.AiChatLoginFailed |
| | | : LlmErrorCodes.AiChatApiFailed; |
| | | |
| | | private static Uri BuildUri(LlmPluginRuntimeConfig runtimeConfig, string path) |
| | | { |
| | | var baseUrl = string.IsNullOrWhiteSpace(runtimeConfig.AiChat.BaseUrl) |
| | | ? "http://192.168.1.111:13000" |
| | | : runtimeConfig.AiChat.BaseUrl; |
| | | if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out var baseUri) || |
| | | baseUri.Scheme is not ("http" or "https")) |
| | | { |
| | | throw new AiChatClientException(LlmErrorCodes.RequestInvalid, "AiChat baseUrl must be an absolute HTTP or HTTPS URL."); |
| | | } |
| | | |
| | | return new Uri(baseUri, path); |
| | | } |
| | | |
| | | private static string? ResolvePassword(LlmPluginRuntimeConfig runtimeConfig) |
| | | { |
| | | var envName = runtimeConfig.AiChat.Account.PasswordEnv; |
| | | if (!string.IsNullOrWhiteSpace(envName)) |
| | | { |
| | | var envValue = Environment.GetEnvironmentVariable(envName) |
| | | ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.User) |
| | | ?? Environment.GetEnvironmentVariable(envName, EnvironmentVariableTarget.Machine); |
| | | if (!string.IsNullOrWhiteSpace(envValue)) |
| | | { |
| | | return envValue; |
| | | } |
| | | } |
| | | |
| | | return runtimeConfig.AiChat.Account.Password; |
| | | } |
| | | |
| | | private void ClearSession(LlmPluginRuntimeConfig runtimeConfig) |
| | | { |
| | | _sessionTokens.TryRemove(SessionKey(runtimeConfig), out _); |
| | | } |
| | | |
| | | private static string SessionKey(LlmPluginRuntimeConfig runtimeConfig) |
| | | => $"{runtimeConfig.AiChat.BaseUrl}|{runtimeConfig.AiChat.Account.Email}"; |
| | | } |
| | |
| | | { |
| | | Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default); |
| | | |
| | | Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> GetMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatGetMemoriesRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> CreateMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatCreateMemoryRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task DeleteMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | string memoryId, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> RecallMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatRecallMemoriesRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | CancellationToken cancellationToken = default); |
| | |
| | | { |
| | | Task<string?> ResolveSecretAsync(string? authRef, CancellationToken cancellationToken = default); |
| | | } |
| | | |
| | | public interface IAiChatClient |
| | | { |
| | | Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> GetMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatGetMemoriesRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> CreateMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatCreateMemoryRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task DeleteMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | string memoryId, |
| | | CancellationToken cancellationToken = default); |
| | | |
| | | Task<AiChatJsonResult> RecallMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatRecallMemoriesRequest request, |
| | | CancellationToken cancellationToken = default); |
| | | } |
| | |
| | | private readonly ICredentialStore _credentialStore; |
| | | private readonly ILlmProviderAdapterFactory _adapterFactory; |
| | | private readonly IDiagnosticsService _diagnostics; |
| | | private readonly IAiChatClient? _aiChatClient; |
| | | private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase); |
| | | |
| | | public LlmGatewayService( |
| | | ILlmModelRegistry registry, |
| | | ICredentialStore credentialStore, |
| | | ILlmProviderAdapterFactory adapterFactory, |
| | | IDiagnosticsService diagnostics) |
| | | IDiagnosticsService diagnostics, |
| | | IAiChatClient? aiChatClient = null) |
| | | { |
| | | _registry = registry; |
| | | _credentialStore = credentialStore; |
| | | _adapterFactory = adapterFactory; |
| | | _diagnostics = diagnostics; |
| | | _aiChatClient = aiChatClient; |
| | | } |
| | | |
| | | public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default) |
| | |
| | | .ToList(); |
| | | } |
| | | |
| | | public async Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | { |
| | | if (runtimeConfig.IsAiChatMode) |
| | | { |
| | | return _aiChatClient is null |
| | | ? [] |
| | | : await _aiChatClient.GetModelsAsync(runtimeConfig, cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | var configuredModels = runtimeConfig.Models |
| | | .Where(IsUsableRuntimeModel) |
| | | .Select(model => new LlmModelSummary |
| | | { |
| | | Id = model.Id, |
| | | Label = string.Equals(model.Id, runtimeConfig.DefaultModel, StringComparison.OrdinalIgnoreCase) |
| | | ? $"{model.Label} *" |
| | | : model.Label, |
| | | Provider = model.Provider, |
| | | SupportsStreaming = model.SupportsStreaming, |
| | | Enabled = model.Enabled |
| | | }) |
| | | .ToList(); |
| | | if (configuredModels.Count > 0) |
| | | { |
| | | return configuredModels; |
| | | } |
| | | |
| | | return await GetModelsAsync(cancellationToken).ConfigureAwait(false); |
| | | } |
| | | |
| | | public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([]) |
| | | : _aiChatClient.GetProjectsAsync(runtimeConfig, cancellationToken); |
| | | |
| | | public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.FromResult(new AiChatMemoryCapabilities()) |
| | | : _aiChatClient.GetMemoryCapabilitiesAsync(runtimeConfig, cancellationToken); |
| | | |
| | | public Task<AiChatJsonResult> GetMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatGetMemoriesRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.FromResult(new AiChatJsonResult()) |
| | | : _aiChatClient.GetMemoriesAsync(runtimeConfig, request, cancellationToken); |
| | | |
| | | public Task<AiChatJsonResult> CreateMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatCreateMemoryRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.FromResult(new AiChatJsonResult()) |
| | | : _aiChatClient.CreateMemoryAsync(runtimeConfig, request, cancellationToken); |
| | | |
| | | public Task DeleteMemoryAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | string memoryId, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.CompletedTask |
| | | : _aiChatClient.DeleteMemoryAsync(runtimeConfig, memoryId, cancellationToken); |
| | | |
| | | public Task<AiChatJsonResult> RecallMemoriesAsync( |
| | | LlmPluginRuntimeConfig runtimeConfig, |
| | | AiChatRecallMemoriesRequest request, |
| | | CancellationToken cancellationToken = default) |
| | | => _aiChatClient is null |
| | | ? Task.FromResult(new AiChatJsonResult()) |
| | | : _aiChatClient.RecallMemoriesAsync(runtimeConfig, request, cancellationToken); |
| | | |
| | | public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync( |
| | | LlmChatRequest request, |
| | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | |
| | | yield break; |
| | | } |
| | | |
| | | var model = await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false); |
| | | if (string.Equals(request.Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase)) |
| | | { |
| | | if (_aiChatClient is null) |
| | | { |
| | | yield return new LlmErrorEvent |
| | | { |
| | | RequestId = request.RequestId, |
| | | Code = LlmErrorCodes.AiChatApiFailed, |
| | | Message = "AiChat client is not available." |
| | | }; |
| | | yield break; |
| | | } |
| | | |
| | | await foreach (var streamEvent in _aiChatClient.StreamChatAsync(request, request.RuntimeConfig, cancellationToken).ConfigureAwait(false)) |
| | | { |
| | | yield return streamEvent; |
| | | } |
| | | |
| | | yield break; |
| | | } |
| | | |
| | | var model = request.RuntimeConfig.Models.FirstOrDefault(model => |
| | | IsUsableRuntimeModel(model) && |
| | | string.Equals(model.Id, request.ModelId, StringComparison.OrdinalIgnoreCase)); |
| | | model ??= await _registry.GetEnabledModelAsync(request.ModelId, cancellationToken).ConfigureAwait(false); |
| | | if (model is null) |
| | | { |
| | | yield return new LlmErrorEvent |
| | |
| | | return true; |
| | | } |
| | | |
| | | private static bool IsUsableRuntimeModel(LlmModelConfig model) |
| | | => model.Enabled && |
| | | !string.IsNullOrWhiteSpace(model.Id) && |
| | | !string.IsNullOrWhiteSpace(model.Label) && |
| | | !string.IsNullOrWhiteSpace(model.Provider) && |
| | | !string.IsNullOrWhiteSpace(model.Endpoint) && |
| | | !string.IsNullOrWhiteSpace(model.ApiModel); |
| | | |
| | | private void RecordFailure(LlmChatRequest request, LlmModelConfig model, string code, string exception) |
| | | { |
| | | var host = Uri.TryCreate(model.Endpoint, UriKind.Absolute, out var endpoint) |
| | |
| | | public required string RequestId { get; init; } |
| | | public required string PluginId { get; init; } |
| | | public required string InstanceId { get; init; } |
| | | public string Mode { get; init; } = LlmConnectionModes.ProviderDirect; |
| | | public string? ProjectId { get; init; } |
| | | public required string ModelId { get; init; } |
| | | public required IReadOnlyList<LlmMessage> Messages { get; init; } |
| | | public LlmRequestOptions Options { get; init; } = new(); |
| | | public LlmPluginRuntimeConfig RuntimeConfig { get; init; } = new(); |
| | | } |
| | | |
| | | public sealed record LlmMessage |
| | |
| | | public const string Timeout = "LlmTimeout"; |
| | | public const string StreamParseFailed = "LlmStreamParseFailed"; |
| | | public const string RequestInvalid = "LlmRequestInvalid"; |
| | | public const string AiChatCredentialMissing = "AiChatCredentialMissing"; |
| | | public const string AiChatLoginFailed = "AiChatLoginFailed"; |
| | | public const string AiChatProjectLoadFailed = "AiChatProjectLoadFailed"; |
| | | public const string AiChatQuotaExceeded = "AiChatQuotaExceeded"; |
| | | public const string AiChatMemoryPermissionDenied = "AiChatMemoryPermissionDenied"; |
| | | public const string AiChatSseInterrupted = "AiChatSseInterrupted"; |
| | | public const string AiChatApiFailed = "AiChatApiFailed"; |
| | | } |
| | | |
| | | public static class LlmConnectionModes |
| | | { |
| | | public const string ProviderDirect = "provider-direct"; |
| | | public const string AiChatApi = "aichat-api"; |
| | | } |
| | | |
| | | public sealed record LlmPluginRuntimeConfig |
| | | { |
| | | public string Mode { get; init; } = LlmConnectionModes.ProviderDirect; |
| | | public AiChatRuntimeConfig AiChat { get; init; } = new(); |
| | | public string? DefaultModel { get; init; } |
| | | public List<LlmModelConfig> Models { get; init; } = []; |
| | | |
| | | public bool IsAiChatMode => string.Equals(Mode, LlmConnectionModes.AiChatApi, StringComparison.OrdinalIgnoreCase); |
| | | } |
| | | |
| | | public sealed record AiChatRuntimeConfig |
| | | { |
| | | public string BaseUrl { get; init; } = "http://192.168.1.111:13000"; |
| | | public AiChatAccountConfig Account { get; init; } = new(); |
| | | public string? DefaultProjectId { get; init; } |
| | | public AiChatMemoryConfig Memory { get; init; } = new(); |
| | | } |
| | | |
| | | public sealed record AiChatAccountConfig |
| | | { |
| | | public string? Email { get; init; } |
| | | public string? Password { get; init; } |
| | | public string? PasswordEnv { get; init; } = "MOLI_AICHAT_PASSWORD"; |
| | | } |
| | | |
| | | public sealed record AiChatMemoryConfig |
| | | { |
| | | public bool EnabledInProviderDirect { get; init; } = true; |
| | | public string DefaultScope { get; init; } = "PROJECT"; |
| | | public int RecallLimit { get; init; } = 8; |
| | | } |
| | | |
| | | public sealed record AiChatProjectSummary |
| | | { |
| | | public required string Id { get; init; } |
| | | public required string Name { get; init; } |
| | | public string ProjectType { get; init; } = "CHAT"; |
| | | public string MemoryMode { get; init; } = "ISOLATED"; |
| | | } |
| | | |
| | | public sealed record AiChatMemoryCapabilities |
| | | { |
| | | public bool CanUseMemory { get; init; } |
| | | public bool CanViewMemory { get; init; } |
| | | public bool CanManageMemory { get; init; } |
| | | } |
| | | |
| | | public sealed record AiChatGetMemoriesRequest |
| | | { |
| | | public string? Scope { get; init; } |
| | | public string? ProjectId { get; init; } |
| | | } |
| | | |
| | | public sealed record AiChatCreateMemoryRequest |
| | | { |
| | | public required string Scope { get; init; } |
| | | public string? ProjectId { get; init; } |
| | | public required string Content { get; init; } |
| | | } |
| | | |
| | | public sealed record AiChatRecallMemoriesRequest |
| | | { |
| | | public required string Query { get; init; } |
| | | public string? Scope { get; init; } |
| | | public string? ProjectId { get; init; } |
| | | public string? ConversationId { get; init; } |
| | | public int? Limit { get; init; } |
| | | } |
| | | |
| | | public sealed record AiChatJsonResult |
| | | { |
| | | public object? Data { get; init; } |
| | | } |
| | | |
| | | public sealed class AiChatClientException : Exception |
| | | { |
| | | public AiChatClientException(string code, string message, Exception? innerException = null) |
| | | : base(message, innerException) |
| | | { |
| | | Code = code; |
| | | } |
| | | |
| | | public string Code { get; } |
| | | } |
| | |
| | | <DataGrid x:Name="DiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" /> |
| | | </DockPanel> |
| | | </TabItem> |
| | | <TabItem Header="Log"> |
| | | <DockPanel Margin="8"> |
| | | <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8"> |
| | | <TextBlock x:Name="LogPathText" VerticalAlignment="Center" Margin="0,0,12,0" /> |
| | | <Button Content="打开日志目录" Width="112" Click="OpenLogDirectory_Click" /> |
| | | </WrapPanel> |
| | | <TextBox x:Name="LogTextBox" |
| | | FontFamily="Consolas" |
| | | FontSize="12" |
| | | IsReadOnly="True" |
| | | TextWrapping="NoWrap" |
| | | AcceptsReturn="True" |
| | | VerticalScrollBarVisibility="Auto" |
| | | HorizontalScrollBarVisibility="Auto" /> |
| | | </DockPanel> |
| | | </TabItem> |
| | | </TabControl> |
| | | </DockPanel> |
| | | </Window> |
| | |
| | | private readonly DesktopPaths _paths; |
| | | private readonly DispatcherTimer _timer; |
| | | private AppRuntimeState? _state; |
| | | private string? _selectedWidgetForDisplayLayer; |
| | | private bool _isRefreshing; |
| | | |
| | | public ManagementWindow( |
| | | IDesktopRuntime runtime, |
| | |
| | | _paths = paths; |
| | | InitializeComponent(); |
| | | DisplayLayerSelector.ItemsSource = Enum.GetValues<DisplayLayer>(); |
| | | WidgetSelector.SelectionChanged += WidgetSelector_SelectionChanged; |
| | | _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) }; |
| | | _timer.Tick += async (_, _) => await RefreshAsync(); |
| | | Loaded += async (_, _) => |
| | |
| | | } |
| | | |
| | | private async Task RefreshAsync() |
| | | { |
| | | _isRefreshing = true; |
| | | try |
| | | { |
| | | _state = await _runtime.GetStateAsync(); |
| | | var api = _apiStatus.GetStatus(); |
| | |
| | | WidgetSelector.ItemsSource = widgets; |
| | | WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault(); |
| | | WidgetsGrid.ItemsSource = widgets; |
| | | DisplayLayerSelector.SelectedItem = (WidgetSelector.SelectedItem as WidgetRow)?.DisplayLayer ?? DisplayLayer.Desktop; |
| | | SyncDisplayLayerSelector(force: _selectedWidgetForDisplayLayer != (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId); |
| | | PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray(); |
| | | DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray(); |
| | | RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray(); |
| | | ManifestErrorsText.Text = BuildManifestErrorText(_state); |
| | | LoadTodayLog(); |
| | | } |
| | | finally |
| | | { |
| | | _isRefreshing = false; |
| | | } |
| | | } |
| | | |
| | | private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync(); |
| | |
| | | private void OpenPluginsJson_Click(object sender, RoutedEventArgs e) |
| | | => OpenJson(Path.Combine(_paths.ConfigDirectory, "plugins.json")); |
| | | |
| | | private void OpenLogDirectory_Click(object sender, RoutedEventArgs e) |
| | | { |
| | | Directory.CreateDirectory(_paths.LogDirectory); |
| | | Process.Start(new ProcessStartInfo("explorer.exe", $"\"{_paths.LogDirectory}\"") { UseShellExecute = true }); |
| | | } |
| | | |
| | | private void OpenPluginJson_Click(object sender, RoutedEventArgs e) |
| | | { |
| | | if ((PluginsGrid.SelectedItem as PluginRow) is not { } plugin) |
| | |
| | | |
| | | private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow; |
| | | |
| | | private void WidgetSelector_SelectionChanged(object sender, SelectionChangedEventArgs e) |
| | | { |
| | | if (!_isRefreshing) |
| | | { |
| | | SyncDisplayLayerSelector(force: true); |
| | | } |
| | | } |
| | | |
| | | private void SyncDisplayLayerSelector(bool force) |
| | | { |
| | | if (SelectedWidget() is not { } widget) |
| | | { |
| | | DisplayLayerSelector.SelectedItem = DisplayLayer.Desktop; |
| | | _selectedWidgetForDisplayLayer = null; |
| | | return; |
| | | } |
| | | |
| | | if (!force) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | DisplayLayerSelector.SelectedItem = widget.DisplayLayer; |
| | | _selectedWidgetForDisplayLayer = widget.InstanceId; |
| | | } |
| | | |
| | | private void LoadTodayLog() |
| | | { |
| | | var logPath = Path.Combine(_paths.LogDirectory, $"moli-desktop-{DateTimeOffset.Now:yyyyMMdd}.log"); |
| | | LogPathText.Text = logPath; |
| | | if (!File.Exists(logPath)) |
| | | { |
| | | LogTextBox.Text = "当天暂无日志。"; |
| | | return; |
| | | } |
| | | |
| | | try |
| | | { |
| | | var text = File.ReadAllText(logPath, Encoding.UTF8); |
| | | if (LogTextBox.Text == text) |
| | | { |
| | | return; |
| | | } |
| | | |
| | | var wasNearBottom = LogTextBox.VerticalOffset >= LogTextBox.ExtentHeight - LogTextBox.ViewportHeight - 24; |
| | | LogTextBox.Text = text; |
| | | if (wasNearBottom) |
| | | { |
| | | LogTextBox.ScrollToEnd(); |
| | | } |
| | | } |
| | | catch (IOException) |
| | | { |
| | | } |
| | | catch (UnauthorizedAccessException) |
| | | { |
| | | } |
| | | } |
| | | |
| | | private async Task InstallWallpaperFilePluginAsync(string fileName) |
| | | { |
| | | Directory.CreateDirectory(_paths.PluginDirectory); |
| | |
| | | using Moli.Desktop.Diagnostics; |
| | | using Moli.Desktop.Layout; |
| | | using Moli.Desktop.Plugins; |
| | | using Microsoft.Extensions.Logging; |
| | | using Microsoft.Extensions.Logging.Abstractions; |
| | | |
| | | namespace Moli.Desktop.Runtime; |
| | | |
| | |
| | | { |
| | | private readonly object _gate = new(); |
| | | private readonly List<Func<RuntimeEvent, Task>> _handlers = []; |
| | | private readonly ILogger<RuntimeEventBus> _logger; |
| | | |
| | | public RuntimeEventBus(ILogger<RuntimeEventBus>? logger = null) |
| | | { |
| | | _logger = logger ?? NullLogger<RuntimeEventBus>.Instance; |
| | | } |
| | | |
| | | public IDisposable Subscribe(Func<RuntimeEvent, Task> handler) |
| | | { |
| | |
| | | |
| | | public async Task PublishAsync(RuntimeEvent runtimeEvent, CancellationToken cancellationToken = default) |
| | | { |
| | | _logger.LogDebug("Runtime event published: {EventName}", runtimeEvent.Name); |
| | | Func<RuntimeEvent, Task>[] handlers; |
| | | lock (_gate) |
| | | { |
| | |
| | | "requestShow", |
| | | "requestHide", |
| | | "requestResize", |
| | | "llm.getConnectionMode", |
| | | "llm.getModels", |
| | | "llm.getProjects", |
| | | "llm.getMemoryCapabilities", |
| | | "llm.getMemories", |
| | | "llm.createMemory", |
| | | "llm.deleteMemory", |
| | | "llm.recallMemories", |
| | | "llm.streamChat", |
| | | "llm.cancel" |
| | | ]; |
| | |
| | | "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.getConnectionMode" => PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { mode = ReadRuntimeConfig(context).Mode }), |
| | | "llm.getModels" => await HandleGetLlmModelsAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.getProjects" => await HandleGetAiChatProjectsAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.getMemoryCapabilities" => await HandleGetMemoryCapabilitiesAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.getMemories" => await HandleGetMemoriesAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.createMemory" => await HandleCreateMemoryAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.deleteMemory" => await HandleDeleteMemoryAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.recallMemories" => await HandleRecallMemoriesAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.streamChat" => await HandleStreamLlmChatAsync(request, context, cancellationToken).ConfigureAwait(false), |
| | | "llm.cancel" => await HandleCancelLlmChatAsync(request, cancellationToken).ConfigureAwait(false), |
| | | _ => PluginBridgeResponse.Failure(request.Id, "BridgeMethodNotAllowed", $"Bridge method {request.Method} is not allowed.") |
| | | }; |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleGetLlmModelsAsync(BridgeRequest request, CancellationToken cancellationToken) |
| | | private async Task<PluginBridgeResponse> HandleGetLlmModelsAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | var models = await _llmGateway.GetModelsAsync(cancellationToken).ConfigureAwait(false); |
| | | var models = await _llmGateway.GetModelsAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, models); |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleGetAiChatProjectsAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | try |
| | | { |
| | | var projects = await _llmGateway.GetProjectsAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, projects); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleGetMemoryCapabilitiesAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | try |
| | | { |
| | | var capabilities = await _llmGateway.GetMemoryCapabilitiesAsync(ReadRuntimeConfig(context), cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, capabilities); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleGetMemoriesAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | var payload = DeserializePayload<AiChatGetMemoriesRequest>(request, out var error); |
| | | if (error is not null) |
| | | { |
| | | return error; |
| | | } |
| | | |
| | | try |
| | | { |
| | | var result = await _llmGateway.GetMemoriesAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleCreateMemoryAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | var payload = DeserializePayload<AiChatCreateMemoryRequest>(request, out var error); |
| | | if (error is not null) |
| | | { |
| | | return error; |
| | | } |
| | | |
| | | try |
| | | { |
| | | var result = await _llmGateway.CreateMemoryAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleDeleteMemoryAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | if (request.Params.ValueKind is not JsonValueKind.Object || |
| | | !request.Params.TryGetProperty("memoryId", out var memoryIdElement) || |
| | | memoryIdElement.ValueKind != JsonValueKind.String || |
| | | string.IsNullOrWhiteSpace(memoryIdElement.GetString())) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", "memoryId is required."); |
| | | } |
| | | |
| | | try |
| | | { |
| | | await _llmGateway.DeleteMemoryAsync(ReadRuntimeConfig(context), memoryIdElement.GetString()!, cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, new { accepted = true }); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private async Task<PluginBridgeResponse> HandleRecallMemoriesAsync( |
| | | BridgeRequest request, |
| | | PluginBridgeContext context, |
| | | CancellationToken cancellationToken) |
| | | { |
| | | var payload = DeserializePayload<AiChatRecallMemoriesRequest>(request, out var error); |
| | | if (error is not null) |
| | | { |
| | | return error; |
| | | } |
| | | |
| | | try |
| | | { |
| | | var result = await _llmGateway.RecallMemoriesAsync(ReadRuntimeConfig(context), payload!, cancellationToken).ConfigureAwait(false); |
| | | return PluginBridgeResponse.Ok(request.Id ?? string.Empty, result.Data); |
| | | } |
| | | catch (AiChatClientException ex) |
| | | { |
| | | return PluginBridgeResponse.Failure(request.Id, ex.Code, ex.Message); |
| | | } |
| | | } |
| | | |
| | | private Task<PluginBridgeResponse> HandleStreamLlmChatAsync( |
| | |
| | | RequestId = requestId, |
| | | PluginId = context.RuntimeInfo.PluginId, |
| | | InstanceId = context.HostId, |
| | | Mode = string.IsNullOrWhiteSpace(payload.Mode) ? ReadRuntimeConfig(context).Mode : payload.Mode!, |
| | | ProjectId = payload.ProjectId, |
| | | ModelId = payload.ModelId, |
| | | Messages = payload.Messages, |
| | | Options = payload.Options ?? new LlmRequestOptions() |
| | | Options = payload.Options ?? new LlmRequestOptions(), |
| | | RuntimeConfig = ReadRuntimeConfig(context) |
| | | }; |
| | | |
| | | _ = Task.Run(() => PumpLlmStreamAsync(chatRequest, context, CancellationToken.None)); |
| | |
| | | private static bool HasPermission(PluginBridgeContext context, string permission) |
| | | => context.Manifest.Permissions.Any(item => string.Equals(item, permission, StringComparison.OrdinalIgnoreCase)); |
| | | |
| | | private T? DeserializePayload<T>(BridgeRequest request, out PluginBridgeResponse? error) |
| | | { |
| | | error = null; |
| | | if (request.Params.ValueKind is not JsonValueKind.Object) |
| | | { |
| | | error = PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", $"{request.Method} expects an object payload."); |
| | | return default; |
| | | } |
| | | |
| | | try |
| | | { |
| | | return request.Params.Deserialize<T>(_jsonOptions); |
| | | } |
| | | catch (JsonException) |
| | | { |
| | | error = PluginBridgeResponse.Failure(request.Id, "BridgePayloadInvalid", $"{request.Method} payload could not be parsed."); |
| | | return default; |
| | | } |
| | | } |
| | | |
| | | private LlmPluginRuntimeConfig ReadRuntimeConfig(PluginBridgeContext context) |
| | | { |
| | | if (context.Config.ValueKind is not JsonValueKind.Object) |
| | | { |
| | | return new LlmPluginRuntimeConfig(); |
| | | } |
| | | |
| | | try |
| | | { |
| | | var config = context.Config.Deserialize<LlmPluginRuntimeConfig>(_jsonOptions) ?? new LlmPluginRuntimeConfig(); |
| | | if (string.IsNullOrWhiteSpace(config.Mode)) |
| | | { |
| | | config = config with { Mode = LlmConnectionModes.ProviderDirect }; |
| | | } |
| | | |
| | | if (config.AiChat is null) |
| | | { |
| | | config = config with { AiChat = new AiChatRuntimeConfig() }; |
| | | } |
| | | |
| | | return config; |
| | | } |
| | | catch (JsonException) |
| | | { |
| | | return new LlmPluginRuntimeConfig(); |
| | | } |
| | | } |
| | | |
| | | private sealed record BridgeRequest |
| | | { |
| | | public string? Id { get; init; } |
| | |
| | | private sealed record LlmBridgeStreamRequest |
| | | { |
| | | public string? RequestId { get; init; } |
| | | public string? Mode { get; init; } |
| | | public string? ProjectId { get; init; } |
| | | public required string ModelId { get; init; } |
| | | public IReadOnlyList<LlmMessage> Messages { get; init; } = []; |
| | | public LlmRequestOptions? Options { get; init; } |
| | |
| | | requestHide: () => call("requestHide"), |
| | | requestResize: (size) => call("requestResize", size), |
| | | llm: Object.freeze({ |
| | | getConnectionMode: () => call("llm.getConnectionMode"), |
| | | getModels: () => call("llm.getModels"), |
| | | getProjects: () => call("llm.getProjects"), |
| | | getMemoryCapabilities: () => call("llm.getMemoryCapabilities"), |
| | | getMemories: (options) => call("llm.getMemories", options || {}), |
| | | createMemory: (input) => call("llm.createMemory", input), |
| | | deleteMemory: (memoryId) => call("llm.deleteMemory", { memoryId }), |
| | | recallMemories: (input) => call("llm.recallMemories", input), |
| | | streamChat: (request) => call("llm.streamChat", request), |
| | | cancel: (requestId) => call("llm.cancel", { requestId }), |
| | | onDelta: (handler) => on("moli:llm-delta", handler), |
| | |
| | | using System.Windows; |
| | | using System.Text.Json; |
| | | using Microsoft.Extensions.DependencyInjection; |
| | | using Moli.Desktop.Configuration; |
| | | using Moli.Desktop.Diagnostics; |
| | |
| | | private readonly DesktopPaths _paths; |
| | | private readonly IDiagnosticsService _diagnostics; |
| | | private readonly IServiceProvider _services; |
| | | private readonly IRuntimeEventBus _events; |
| | | private readonly Dictionary<WidgetInstanceId, WidgetWindow> _widgets = []; |
| | | private WallpaperWindow? _wallpaper; |
| | | private WallpaperRuntimeState _wallpaperState = new(); |
| | | private bool _editMode; |
| | | private bool _safeInputMode; |
| | | private IDisposable? _eventSubscription; |
| | | |
| | | public RuntimeSurfaceController( |
| | | IPluginManager plugins, |
| | |
| | | IWebViewHostFactory webViews, |
| | | DesktopPaths paths, |
| | | IDiagnosticsService diagnostics, |
| | | IServiceProvider services) |
| | | IServiceProvider services, |
| | | IRuntimeEventBus events) |
| | | { |
| | | _plugins = plugins; |
| | | _interop = interop; |
| | |
| | | _paths = paths; |
| | | _diagnostics = diagnostics; |
| | | _services = services; |
| | | _events = events; |
| | | _eventSubscription = _events.Subscribe(HandleRuntimeEventAsync); |
| | | } |
| | | |
| | | public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default) |
| | |
| | | _wallpaper.Show(); |
| | | await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true); |
| | | _wallpaper.ApplyState(wallpaper, _safeInputMode); |
| | | ReapplyDesktopWidgetLayers(); |
| | | }); |
| | | |
| | | public Task DisableWallpaperAsync(CancellationToken cancellationToken = default) |
| | |
| | | _widgets.Clear(); |
| | | _wallpaper?.Close(); |
| | | _wallpaper = null; |
| | | _eventSubscription?.Dispose(); |
| | | _eventSubscription = null; |
| | | return Task.CompletedTask; |
| | | }); |
| | | |
| | |
| | | await runtime.UpdateWidgetLayoutAsync(instanceId, patch, cancellationToken).ConfigureAwait(true); |
| | | } |
| | | |
| | | private void ReapplyDesktopWidgetLayers() |
| | | { |
| | | foreach (var widget in _widgets.Values.Where(widget => widget.CurrentLayout.DisplayLayer == DisplayLayer.Desktop)) |
| | | { |
| | | widget.ApplyLayout(widget.CurrentLayout, _editMode, _safeInputMode); |
| | | } |
| | | } |
| | | |
| | | private Task HandleRuntimeEventAsync(RuntimeEvent runtimeEvent) |
| | | { |
| | | if (!string.Equals(runtimeEvent.Name, "plugin.resizeRequested", StringComparison.OrdinalIgnoreCase) || |
| | | runtimeEvent.Payload is null) |
| | | { |
| | | return Task.CompletedTask; |
| | | } |
| | | |
| | | return OnUiThreadAsync(() => |
| | | { |
| | | try |
| | | { |
| | | var json = JsonSerializer.Serialize(runtimeEvent.Payload, new JsonSerializerOptions(JsonSerializerDefaults.Web)); |
| | | using var document = JsonDocument.Parse(json); |
| | | var root = document.RootElement; |
| | | if (!root.TryGetProperty("hostId", out var hostIdElement)) |
| | | { |
| | | return Task.CompletedTask; |
| | | } |
| | | |
| | | var hostId = hostIdElement.GetString(); |
| | | var widget = _widgets.Values.FirstOrDefault(item => string.Equals(item.HostId, hostId, StringComparison.OrdinalIgnoreCase)); |
| | | if (widget is null || |
| | | !root.TryGetProperty("params", out var parameters) || |
| | | parameters.ValueKind != JsonValueKind.Object) |
| | | { |
| | | return Task.CompletedTask; |
| | | } |
| | | |
| | | var width = TryReadPositiveDouble(parameters, "width"); |
| | | var height = TryReadPositiveDouble(parameters, "height"); |
| | | widget.ApplyRequestedSize(width, height); |
| | | } |
| | | catch (JsonException ex) |
| | | { |
| | | _diagnostics.Record( |
| | | DiagnosticSeverity.Warning, |
| | | "PluginResizeRequestInvalid", |
| | | "Plugin resize request payload could not be parsed.", |
| | | new Dictionary<string, string> { ["exception"] = ex.GetType().Name }); |
| | | } |
| | | |
| | | return Task.CompletedTask; |
| | | }); |
| | | } |
| | | |
| | | private static double? TryReadPositiveDouble(JsonElement parameters, string propertyName) |
| | | { |
| | | if (!parameters.TryGetProperty(propertyName, out var value)) |
| | | { |
| | | return null; |
| | | } |
| | | |
| | | return value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number) && number > 0 |
| | | ? number |
| | | : null; |
| | | } |
| | | |
| | | private static async Task OnUiThreadAsync(Func<Task> action) |
| | | { |
| | | var dispatcher = Application.Current?.Dispatcher; |
| | |
| | | private readonly Border _editBorder; |
| | | private readonly Border _resizeGrip; |
| | | private WidgetLayout _layout; |
| | | private double? _requestedHeight; |
| | | private bool _editMode; |
| | | private bool _safeInputMode; |
| | | private Point? _dragStart; |
| | |
| | | |
| | | public WidgetInstanceId InstanceId => _layout.InstanceId; |
| | | |
| | | public WidgetLayout CurrentLayout => _layout; |
| | | |
| | | public string HostId => _webView.HostId; |
| | | |
| | | public async Task LoadAsync(CancellationToken cancellationToken = default) |
| | | { |
| | | ApplyLayout(_layout, _editMode, _safeInputMode); |
| | |
| | | Left = layout.Bounds.X; |
| | | Top = layout.Bounds.Y; |
| | | Width = layout.Bounds.Width; |
| | | Height = layout.Bounds.Height; |
| | | Height = Math.Max(layout.Bounds.Height, _requestedHeight ?? layout.Bounds.Height); |
| | | Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0); |
| | | Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden; |
| | | Topmost = layout.DisplayLayer == DisplayLayer.GlobalTop; |
| | |
| | | ApplyWin32Styles(); |
| | | } |
| | | |
| | | public void ApplyRequestedSize(double? width, double? height) |
| | | { |
| | | if (width is > 0) |
| | | { |
| | | Width = Math.Max(LayoutManager.MinWidth, width.Value); |
| | | } |
| | | |
| | | _requestedHeight = height is > 0 && height.Value > _layout.Bounds.Height |
| | | ? height.Value |
| | | : null; |
| | | Height = Math.Max(_layout.Bounds.Height, _requestedHeight ?? _layout.Bounds.Height); |
| | | ApplyWin32Styles(); |
| | | } |
| | | |
| | | public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default) |
| | | { |
| | | ApplyLayout(_layout, enabled, _safeInputMode); |