基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-04 b3bde921167ee0a7dc21cf7e3d642840a0fcc11e
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
@@ -2,6 +2,7 @@
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;
@@ -56,12 +57,66 @@
    }
    [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_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("streamChat", script);
        Assert.Contains("moliDesktopResponse", script);
    }
@@ -71,10 +126,10 @@
        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);
        return new PluginBridgeDispatcher(diagnostics, events, new FakeLlmGateway());
    }
    private static PluginBridgeContext CreateContext()
    private static PluginBridgeContext CreateContext(bool includeLlmPermission = true)
    {
        return new PluginBridgeContext
        {
@@ -85,7 +140,8 @@
                Name = "Clock",
                Version = "1.0.0",
                Type = PluginType.Widget,
                Entry = "index.html"
                Entry = "index.html",
                Permissions = includeLlmPermission ? ["llm.stream"] : []
            },
            RuntimeInfo = new PluginRuntimeBridgeInfo
            {
@@ -96,4 +152,31 @@
            Config = JsonDocument.Parse("""{"label":"clock"}""").RootElement.Clone()
        };
    }
    private sealed class FakeLlmGateway : ILlmGatewayService
    {
        public Task CancelAsync(string requestId, 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 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 };
        }
    }
}