基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 da97410f48a1e94d7e1fe019c69a7c847fe67ddf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
using Microsoft.Extensions.Logging.Abstractions;
 
namespace Moli.Desktop.Tests.Llm;
 
public class LlmGatewayServiceTests
{
    [Fact]
    public async Task StreamChatAsync_RoutesSelectedModelToMatchingAdapter()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter, new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
            ApiModel = "actual-model",
            Enabled = true
        });
 
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-1",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "model-a",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
 
        Assert.Equal("http://127.0.0.1:11434/v1/chat/completions", adapter.LastRequest?.Model.Endpoint);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
        Assert.Contains(events, item => item is LlmCompletedEvent);
    }
 
    [Fact]
    public async Task StreamChatAsync_ReturnsModelNotFoundForDisabledModel()
    {
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
            ApiModel = "actual-model",
            Enabled = false
        });
 
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-2",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "model-a",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
 
        var error = Assert.IsType<LlmErrorEvent>(Assert.Single(events));
        Assert.Equal(LlmErrorCodes.ModelNotFound, error.Code);
    }
 
    [Fact]
    public async Task StreamChatAsync_UsesOpenAICompatibleAdapterForDeepSeekAlias()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter, new LlmModelConfig
        {
            Id = "deepseek-chat",
            Label = "DeepSeek",
            Provider = "deepseek",
            Endpoint = "https://api.deepseek.com/chat/completions",
            ApiModel = "deepseek-chat",
            Enabled = true
        });
 
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-3",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "deepseek-chat",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
 
        Assert.Equal("deepseek", adapter.LastRequest?.Model.Provider);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "ok" });
    }
 
    [Fact]
    public async Task StreamChatAsync_UsesAiChatClientWhenModeIsAiChatApi()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(
            new CapturingAdapter("openai-compatible"),
            aiChat,
            new LlmModelConfig
            {
                Id = "provider-model",
                Label = "Provider",
                Provider = "openai-compatible",
                Endpoint = "http://127.0.0.1:11434/v1/chat/completions",
                ApiModel = "provider-model",
                Enabled = true
            });
 
        var events = await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-aichat",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            Mode = LlmConnectionModes.AiChatApi,
            ProjectId = "project-1",
            ModelId = "deepseek-v4-flash",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }],
            RuntimeConfig = new LlmPluginRuntimeConfig { Mode = LlmConnectionModes.AiChatApi }
        }).ToListAsync();
 
        Assert.Equal("project-1", aiChat.LastRequest?.ProjectId);
        Assert.Contains(events, item => item is LlmDeltaEvent { Delta: "from-aichat" });
    }
 
    private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models)
        => CreateGateway(adapter, null, models);
 
    private static LlmGatewayService CreateGateway(CapturingAdapter adapter, IAiChatClient? aiChatClient, params LlmModelConfig[] models)
    {
        var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
        var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
        var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
        return new LlmGatewayService(
            new InMemoryRegistry(models),
            new EnvironmentCredentialStore(),
            new LlmProviderAdapterFactory([adapter]),
            diagnostics,
            aiChatClient);
    }
 
    private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry
    {
        private readonly List<LlmModelConfig> _models = [.. models];
 
        public Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default)
            => Task.FromResult(new LlmSettingsDocument { Models = _models });
 
        public Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default)
            => Task.FromResult(_models.FirstOrDefault(model => model.Enabled && model.Id == modelId));
    }
 
    private sealed class CapturingAdapter(string provider) : ILlmProviderAdapter
    {
        public string Provider { get; } = provider;
        public LlmProviderRequest? LastRequest { get; private set; }
 
        public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
            LlmProviderRequest request,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            LastRequest = request;
            yield return new LlmProviderChunk { Delta = "ok" };
            yield return new LlmProviderChunk { IsCompleted = true };
        }
    }
 
    private sealed class FakeAiChatClient : IAiChatClient
    {
        public LlmChatRequest? LastRequest { get; private set; }
 
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
 
        public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<AiChatProjectSummary>>([]);
 
        public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
            LlmChatRequest request,
            LlmPluginRuntimeConfig runtimeConfig,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            LastRequest = request;
            yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "from-aichat" };
            yield return new LlmCompletedEvent { RequestId = request.RequestId };
        }
 
        public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatMemoryCapabilities());
 
        public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
 
        public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
 
        public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
            => Task.CompletedTask;
 
        public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
    }
}
 
internal static class AsyncEnumerableTestExtensions
{
    public static async Task<List<T>> ToListAsync<T>(this IAsyncEnumerable<T> source)
    {
        var results = new List<T>();
        await foreach (var item in source)
        {
            results.Add(item);
        }
 
        return results;
    }
}