基于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
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
using System.Text.Json;
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Llm;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Moli.Desktop.WebView;
 
namespace Moli.Desktop.Tests.WebView;
 
public class PluginBridgeDispatcherTests
{
    [Fact]
    public async Task DispatchAsync_ReturnsRuntimeInfoForBridgeRequest()
    {
        var dispatcher = CreateDispatcher(out _, out _);
        var context = CreateContext();
 
        var response = await dispatcher.DispatchAsync("""{"id":"1","method":"getRuntimeInfo"}""", context);
 
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("sample.clock", json);
        Assert.Contains(context.HostId, json);
    }
 
    [Fact]
    public async Task DispatchAsync_PublishesResizeRequestEvent()
    {
        var dispatcher = CreateDispatcher(out _, out var events);
        RuntimeEvent? captured = null;
        using var subscription = events.Subscribe(runtimeEvent =>
        {
            captured = runtimeEvent;
            return Task.CompletedTask;
        });
 
        var response = await dispatcher.DispatchAsync(
            """{"id":"2","method":"requestResize","params":{"width":320,"height":160}}""",
            CreateContext());
 
        Assert.True(response.Success);
        Assert.NotNull(captured);
        Assert.Equal("plugin.resizeRequested", captured.Name);
    }
 
    [Fact]
    public async Task DispatchAsync_RejectsInvalidSetConfigPayload()
    {
        var dispatcher = CreateDispatcher(out _, out _);
 
        var response = await dispatcher.DispatchAsync("""{"id":"3","method":"setConfig","params":true}""", CreateContext());
 
        Assert.False(response.Success);
        Assert.Equal("BridgePayloadInvalid", response.Error?.Code);
    }
 
    [Fact]
    public async Task DispatchAsync_ReturnsSafeLlmModelSummaries()
    {
        var dispatcher = CreateDispatcher(out _, out _);
 
        var response = await dispatcher.DispatchAsync("""{"id":"4","method":"llm.getModels"}""", CreateContext());
 
        Assert.True(response.Success);
        var json = JsonSerializer.Serialize(response.Result, new JsonSerializerOptions(JsonSerializerDefaults.Web));
        Assert.Contains("gpt-test", json);
        Assert.DoesNotContain("endpoint", json, StringComparison.OrdinalIgnoreCase);
    }
 
    [Fact]
    public async Task DispatchAsync_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 _);
        var context = CreateContext(includeLlmPermission: false);
 
        var response = await dispatcher.DispatchAsync(
            """{"id":"5","method":"llm.streamChat","params":{"modelId":"gpt-test","messages":[{"role":"user","content":"hello"}]}}""",
            context);
 
        Assert.False(response.Success);
        Assert.Equal("BridgePermissionDenied", response.Error?.Code);
    }
 
    [Fact]
    public async Task DispatchAsync_StartsLlmStreamForPermittedPlugin()
    {
        var dispatcher = CreateDispatcher(out _, out var events);
        var seenDelta = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
        using var subscription = events.Subscribe(runtimeEvent =>
        {
            if (runtimeEvent.Name == "llm.delta")
            {
                seenDelta.TrySetResult(JsonSerializer.Serialize(runtimeEvent.Payload));
            }
 
            return Task.CompletedTask;
        });
 
        var response = await dispatcher.DispatchAsync(
            """{"id":"6","method":"llm.streamChat","params":{"modelId":"gpt-test","messages":[{"role":"user","content":"hello"}]}}""",
            CreateContext());
 
        Assert.True(response.Success);
        var completed = await Task.WhenAny(seenDelta.Task, Task.Delay(TimeSpan.FromSeconds(3)));
        Assert.Same(seenDelta.Task, completed);
        Assert.Contains("Hello", await seenDelta.Task);
    }
 
    [Fact]
    public void BridgeScript_ExposesExpectedPluginMethods()
    {
        var script = PluginBridgeScript.Build();
 
        Assert.Contains("getRuntimeInfo", script);
        Assert.Contains("requestResize", script);
        Assert.Contains("llm", script);
        Assert.Contains("getProjects", script);
        Assert.Contains("recallMemories", script);
        Assert.Contains("streamChat", script);
        Assert.Contains("moliDesktopResponse", script);
    }
 
    private static PluginBridgeDispatcher CreateDispatcher(out DiagnosticsService diagnostics, out RuntimeEventBus events)
    {
        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"));
        diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
        events = new RuntimeEventBus();
        return new PluginBridgeDispatcher(diagnostics, events, new FakeLlmGateway());
    }
 
    private static PluginBridgeContext CreateContext(bool includeLlmPermission = true, string configJson = """{"label":"clock"}""")
    {
        return new PluginBridgeContext
        {
            HostId = "host-1",
            Manifest = new PluginManifest
            {
                Id = "sample.clock",
                Name = "Clock",
                Version = "1.0.0",
                Type = PluginType.Widget,
                Entry = "index.html",
                Permissions = includeLlmPermission ? ["llm.stream"] : []
            },
            RuntimeInfo = new PluginRuntimeBridgeInfo
            {
                PluginId = "sample.clock",
                PluginType = PluginType.Widget,
                HostId = "host-1"
            },
            Config = JsonDocument.Parse(configJson).RootElement.Clone()
        };
    }
 
    private sealed class FakeLlmGateway : ILlmGatewayService
    {
        public Task CancelAsync(string requestId, CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>(
            [
                new LlmModelSummary
                {
                    Id = "gpt-test",
                    Label = "GPT Test",
                    Provider = "openai-compatible",
                    SupportsStreaming = true,
                    Enabled = true
                }
            ]);
 
        public 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)
        {
            await Task.Yield();
            yield return new LlmDeltaEvent { RequestId = request.RequestId, Delta = "Hello" };
            yield return new LlmCompletedEvent { RequestId = request.RequestId };
        }
    }
}