基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-14 b84db8983d63a9a981083ebce1a139860c6bdf25
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
using System.Net.Http;
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.GetChatCompletionsUrl());
        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_UsesBaseUrlOnlyModel()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter, new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            BaseUrl = "http://127.0.0.1:11434/v1",
            ApiModel = "actual-model",
            Enabled = true
        });
 
        await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-base",
            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.GetChatCompletionsUrl());
    }
 
    [Fact]
    public async Task StreamChatAsync_ResolvesProviderModelId()
    {
        var adapter = new CapturingAdapter("openai-compatible");
        var gateway = CreateGateway(adapter);
 
        await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-provider",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "provider:deepseek:deepseek-v4-flash",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }],
            RuntimeConfig = new LlmPluginRuntimeConfig
            {
                Providers =
                [
                    new LlmProviderConfig
                    {
                        Id = "deepseek",
                        Label = "DeepSeek",
                        BaseUrl = "https://api.deepseek.com"
                    }
                ]
            }
        }).ToListAsync();
 
        Assert.Equal("deepseek-v4-flash", adapter.LastRequest?.Model.ApiModel);
        Assert.Equal("https://api.deepseek.com/chat/completions", adapter.LastRequest?.Model.GetChatCompletionsUrl());
    }
 
    [Fact]
    public async Task GetModelsAsync_MergesCustomThenProviderAndIsolatesFailures()
    {
        var adapter = new CapturingAdapter("openai-compatible")
        {
            ListModels = baseUrl => baseUrl.Contains("bad", StringComparison.Ordinal)
                ? throw new HttpRequestException("down")
                : ["deepseek-v4-flash"]
        };
        var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter);
        var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
        {
            DefaultModel = "local-qwen",
            Models =
            [
                new LlmModelConfig
                {
                    Id = "local-qwen",
                    Label = "qwen2.5:14b",
                    Provider = "openai-compatible",
                    BaseUrl = "http://127.0.0.1:11434/v1",
                    ApiModel = "qwen2.5:14b",
                    Enabled = true
                }
            ],
            Providers =
            [
                new LlmProviderConfig { Id = "bad", Label = "Bad", BaseUrl = "https://bad.example" },
                new LlmProviderConfig { Id = "deepseek", Label = "DeepSeek", BaseUrl = "https://api.deepseek.com" }
            ]
        });
 
        Assert.Equal("local-qwen", models[0].Id);
        Assert.Equal("qwen2.5:14b(Custom) *", models[0].Label);
        Assert.Equal("provider:deepseek:deepseek-v4-flash", models[1].Id);
        Assert.Equal("deepseek-v4-flash(DeepSeek)", models[1].Label);
        Assert.Equal(2, models.Count);
        Assert.Contains(diagnostics.Snapshot(), entry => entry.Code == LlmErrorCodes.EndpointUnavailable);
        Assert.All(diagnostics.Snapshot(), entry =>
        {
            Assert.DoesNotContain("sk-", string.Join(" ", entry.Properties.Values), StringComparison.OrdinalIgnoreCase);
        });
    }
 
    [Fact]
    public async Task GetModelsAsync_FormatsAiChatLabels()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
 
        var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
        {
            Mode = LlmConnectionModes.AiChatApi,
            AiChat = new AiChatRuntimeConfig
            {
                Account = new AiChatAccountConfig { Email = "user@example.com" }
            }
        });
 
        var model = Assert.Single(models);
        Assert.Equal("deepseek-v4-flash(AiChat)", model.Label);
        Assert.Equal(1, aiChat.Calls);
    }
 
    [Fact]
    public async Task GetProjectsAsync_ReturnsNotConfiguredWithoutCallingAiChat()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
 
        var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
        {
            AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
        });
 
        Assert.Equal(AiChatProjectStatuses.NotConfigured, result.Status);
        Assert.Empty(result.Projects);
        Assert.Equal(0, aiChat.Calls);
    }
 
    [Fact]
    public async Task GetProjectsAsync_ReturnsNotConnectedWhenLoginFails()
    {
        var aiChat = new FakeAiChatClient { ThrowOnProjects = new AiChatClientException(LlmErrorCodes.AiChatLoginFailed, "password rejected") };
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
 
        var result = await gateway.GetProjectsAsync(new LlmPluginRuntimeConfig
        {
            AiChat = new AiChatRuntimeConfig
            {
                Account = new AiChatAccountConfig { Email = "user@example.com" }
            }
        });
 
        Assert.Equal(AiChatProjectStatuses.NotConnected, result.Status);
        Assert.Equal("password rejected", result.Message);
        Assert.Empty(result.Projects);
    }
 
    [Fact]
    public async Task MemoryApis_DoNotCallAiChatWhenAccountMissing()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
        var config = new LlmPluginRuntimeConfig();
 
        var capabilities = await gateway.GetMemoryCapabilitiesAsync(config);
        await gateway.GetMemoriesAsync(config, new AiChatGetMemoriesRequest());
        await gateway.CreateMemoryAsync(config, new AiChatCreateMemoryRequest { Scope = "GLOBAL", Content = "x" });
        await gateway.DeleteMemoryAsync(config, "mem-1");
        await gateway.RecallMemoriesAsync(config, new AiChatRecallMemoriesRequest { Query = "hello" });
 
        Assert.False(capabilities.CanUseMemory);
        Assert.False(capabilities.CanViewMemory);
        Assert.False(capabilities.CanManageMemory);
        Assert.Equal(0, aiChat.Calls);
    }
 
    [Fact]
    public async Task StreamChatAsync_RecordsHostWithoutApiKey()
    {
        var adapter = new CapturingAdapter("openai-compatible") { ThrowOnStream = new HttpRequestException("boom") };
        var (gateway, diagnostics) = CreateGatewayWithDiagnostics(adapter, new LlmModelConfig
        {
            Id = "model-a",
            Label = "Model A",
            Provider = "openai-compatible",
            BaseUrl = "https://api.deepseek.com",
            ApiModel = "deepseek-v4-flash",
            Enabled = true
        });
 
        await gateway.StreamChatAsync(new LlmChatRequest
        {
            RequestId = "req-fail",
            PluginId = "sample.llm-command-palette",
            InstanceId = "host-1",
            ModelId = "model-a",
            Messages = [new LlmMessage { Role = "user", Content = "hello" }]
        }).ToListAsync();
 
        var entry = Assert.Single(diagnostics.Snapshot(), item => item.Code == LlmErrorCodes.EndpointUnavailable);
        Assert.Equal("api.deepseek.com", entry.Properties["endpointHost"]);
        Assert.DoesNotContain("test-key", string.Join(" ", entry.Properties.Select(pair => pair.Key + pair.Value)));
    }
 
    [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" });
    }
 
    [Fact]
    public async Task GetModelsAsync_AiChatModeWithoutAccountDoesNotCallClient()
    {
        var aiChat = new FakeAiChatClient();
        var gateway = CreateGateway(new CapturingAdapter("openai-compatible"), aiChat);
 
        var models = await gateway.GetModelsAsync(new LlmPluginRuntimeConfig
        {
            Mode = LlmConnectionModes.AiChatApi,
            AiChat = new AiChatRuntimeConfig { BaseUrl = "http://192.168.1.111:13000" }
        });
 
        Assert.Empty(models);
        Assert.Equal(0, aiChat.Calls);
    }
 
    private static LlmGatewayService CreateGateway(CapturingAdapter adapter, params LlmModelConfig[] models)
        => CreateGatewayWithDiagnostics(adapter, null, models).Gateway;
 
    private static LlmGatewayService CreateGateway(CapturingAdapter adapter, IAiChatClient? aiChatClient, params LlmModelConfig[] models)
        => CreateGatewayWithDiagnostics(adapter, aiChatClient, models).Gateway;
 
    private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
        CapturingAdapter adapter,
        params LlmModelConfig[] models)
        => CreateGatewayWithDiagnostics(adapter, null, models);
 
    private static (LlmGatewayService Gateway, DiagnosticsService Diagnostics) CreateGatewayWithDiagnostics(
        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), diagnostics);
    }
 
    private sealed class InMemoryRegistry(IEnumerable<LlmModelConfig> models) : ILlmModelRegistry
    {
        private readonly List<LlmModelConfig> _models = [.. models];
 
        public Task<LlmSettingsDocument> LoadAsync(CancellationToken cancellationToken = default)
            => Task.FromResult(new LlmSettingsDocument { Models = _models });
 
        public Task<LlmModelConfig?> GetEnabledModelAsync(string modelId, CancellationToken cancellationToken = default)
            => Task.FromResult(_models.FirstOrDefault(model => model.Enabled && model.Id == modelId));
    }
 
    private sealed class CapturingAdapter(string provider) : ILlmProviderAdapter
    {
        public string Provider { get; } = provider;
        public LlmProviderRequest? LastRequest { get; private set; }
        public Func<string, IReadOnlyList<string>>? ListModels { get; set; }
        public Exception? ThrowOnStream { get; set; }
 
        public async IAsyncEnumerable<LlmProviderChunk> StreamAsync(
            LlmProviderRequest request,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            await Task.Yield();
            LastRequest = request;
            if (ThrowOnStream is not null)
            {
                throw ThrowOnStream;
            }
 
            yield return new LlmProviderChunk { Delta = "ok" };
            yield return new LlmProviderChunk { IsCompleted = true };
        }
 
        public Task<IReadOnlyList<string>> ListModelIdsAsync(
            string baseUrl,
            string? apiKey,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            return Task.FromResult(ListModels?.Invoke(baseUrl) ?? (IReadOnlyList<string>)[]);
        }
    }
 
    private sealed class FakeAiChatClient : IAiChatClient
    {
        public LlmChatRequest? LastRequest { get; private set; }
        public int Calls { get; private set; }
        public Exception? ThrowOnProjects { get; set; }
 
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
        {
            Calls++;
            return Task.FromResult<IReadOnlyList<LlmModelSummary>>(
            [
                new LlmModelSummary
                {
                    Id = "deepseek-v4-flash",
                    Label = "deepseek-v4-flash",
                    Provider = "aichat",
                    SupportsStreaming = true,
                    Enabled = true
                }
            ]);
        }
 
        public Task<IReadOnlyList<AiChatProjectSummary>> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
        {
            Calls++;
            if (ThrowOnProjects is not null)
            {
                throw ThrowOnProjects;
            }
 
            return Task.FromResult<IReadOnlyList<AiChatProjectSummary>>(
            [
                new AiChatProjectSummary { Id = "project-1", Name = "Project 1" }
            ]);
        }
 
        public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(
            LlmChatRequest request,
            LlmPluginRuntimeConfig runtimeConfig,
            [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            Calls++;
            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)
        {
            Calls++;
            return Task.FromResult(new AiChatMemoryCapabilities());
        }
 
        public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
        {
            Calls++;
            return Task.FromResult(new AiChatJsonResult());
        }
 
        public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
        {
            Calls++;
            return Task.FromResult(new AiChatJsonResult());
        }
 
        public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default)
        {
            Calls++;
            return Task.CompletedTask;
        }
 
        public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
        {
            Calls++;
            return 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;
    }
}