基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-12 97df0fb5ed49e37d1c8e0e62057bb72ba5c9eb6a
优化透明样式
12个文件已修改
153 ■■■■■ 已修改文件
samples/plugins/sample.llm-command-palette/index.html 12 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/publish-to-apps.ps1 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs 40 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/ILlmServices.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Llm/LlmGatewayService.cs 26 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Management/ManagementWindow.xaml.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Runtime/IDesktopRuntime.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/IWebViewHost.cs 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/WebView/WebViewHost.cs 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Windows/WidgetWindow.cs 22 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.llm-command-palette/index.html
@@ -529,6 +529,8 @@
      config: {}
    };
    let _resizeTimer;
    const els = {
      statusMark: document.getElementById("statusMark"),
      projectSelect: document.getElementById("projectSelect"),
@@ -653,7 +655,15 @@
      const screenHeight = window.screen && window.screen.availHeight ? window.screen.availHeight : 900;
      const heightLimit = Math.floor(screenHeight * 0.5) + 88;
      const height = explicitHeight || Math.min(Math.ceil(document.body.scrollHeight + 2), heightLimit);
      bridge.requestResize({ width: Math.ceil(document.body.scrollWidth), height }).catch(() => {});
      if (explicitHeight != null) {
        clearTimeout(_resizeTimer);
        bridge.requestResize({ width: Math.ceil(document.body.scrollWidth), height }).catch(() => {});
        return;
      }
      clearTimeout(_resizeTimer);
      _resizeTimer = setTimeout(function() {
        bridge.requestResize({ width: Math.ceil(document.body.scrollWidth), height }).catch(() => {});
      }, 50);
    }
    function updatePanelLimits() {
scripts/publish-to-apps.ps1
@@ -1,7 +1,7 @@
param(
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64",
    [string]$TargetRoot = "D:\lin\tools\Moli.Desktop\Moli.Desktop",
    [string]$TargetRoot = "D:\lin\tools\Moli.Desktop",
    [string]$AppName = "Moli.Desktop",
    [switch]$SelfContained,
    [switch]$SkipTests,
src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
@@ -1,9 +1,11 @@
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Llm;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Moli.Desktop.Tests.Interop;
@@ -170,7 +172,8 @@
                diagnostics,
                events,
                surface,
                new DisplayChangeMonitor());
                new DisplayChangeMonitor(),
                new FakeLlmGateway());
            return new RuntimeFixture(runtime, configuration, events, surface, widgetId);
        }
@@ -245,4 +248,39 @@
        public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
    }
    private sealed class FakeLlmGateway : ILlmGatewayService
    {
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
        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 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());
        public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(LlmChatRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            yield break;
        }
        public Task CancelAsync(string requestId, CancellationToken cancellationToken = default) => Task.CompletedTask;
        public Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default) => Task.CompletedTask;
    }
}
src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
@@ -214,6 +214,8 @@
    {
        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>>(
            [
src/Moli.Desktop/Llm/ILlmServices.cs
@@ -41,6 +41,7 @@
        CancellationToken cancellationToken = default);
    Task CancelAsync(string requestId, CancellationToken cancellationToken = default);
    Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default);
}
public interface ILlmModelRegistry
src/Moli.Desktop/Llm/LlmGatewayService.cs
@@ -20,6 +20,7 @@
    private readonly IDiagnosticsService _diagnostics;
    private readonly IAiChatClient? _aiChatClient;
    private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRequests = new(StringComparer.OrdinalIgnoreCase);
    private readonly ConcurrentDictionary<string, string> _requestPlugins = new(StringComparer.OrdinalIgnoreCase);
    public LlmGatewayService(
        ILlmModelRegistry registry,
@@ -196,6 +197,7 @@
        var timeoutMs = request.Options.TimeoutMs ?? model.RequestDefaults.TimeoutMs;
        linkedCts.CancelAfter(TimeSpan.FromMilliseconds(timeoutMs));
        _activeRequests[request.RequestId] = linkedCts;
        _requestPlugins[request.RequestId] = request.PluginId;
        var secret = await _credentialStore.ResolveSecretAsync(model.AuthRef, linkedCts.Token).ConfigureAwait(false);
        if (!string.IsNullOrWhiteSpace(model.AuthRef) && string.IsNullOrWhiteSpace(secret))
@@ -227,6 +229,7 @@
                if (!await enumerator.MoveNextAsync().ConfigureAwait(false))
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    _requestPlugins.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                    yield break;
                }
@@ -275,6 +278,7 @@
                if (nextEvent is LlmCompletedEvent or LlmErrorEvent)
                {
                    _activeRequests.TryRemove(request.RequestId, out _);
                    _requestPlugins.TryRemove(request.RequestId, out _);
                    linkedCts.Dispose();
                }
            }
@@ -297,6 +301,7 @@
        cancellationToken.ThrowIfCancellationRequested();
        if (_activeRequests.TryRemove(requestId, out var cts))
        {
            _requestPlugins.TryRemove(requestId, out _);
            cts.Cancel();
            cts.Dispose();
        }
@@ -304,6 +309,27 @@
        return Task.CompletedTask;
    }
    public Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default)
    {
        cancellationToken.ThrowIfCancellationRequested();
        var matchingIds = _requestPlugins
            .Where(kvp => string.Equals(kvp.Value, pluginId, StringComparison.OrdinalIgnoreCase))
            .Select(kvp => kvp.Key)
            .ToList();
        foreach (var requestId in matchingIds)
        {
            if (_activeRequests.TryRemove(requestId, out var cts))
            {
                _requestPlugins.TryRemove(requestId, out _);
                cts.Cancel();
                cts.Dispose();
            }
        }
        return Task.CompletedTask;
    }
    private static bool IsValidRequest(LlmChatRequest request, out string error)
    {
        if (string.IsNullOrWhiteSpace(request.RequestId) ||
src/Moli.Desktop/Management/ManagementWindow.xaml.cs
@@ -124,6 +124,7 @@
            }
        }
        await _runtime.CancelPluginRequestsAsync(new PluginId(widget.PluginId));
        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { DisplayLayer = layer });
    }
src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -2,6 +2,7 @@
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Llm;
using Moli.Desktop.Plugins;
namespace Moli.Desktop.Runtime;
@@ -16,6 +17,7 @@
    private readonly IRuntimeEventBus _events;
    private readonly IRuntimeSurfaceController _surfaces;
    private readonly DisplayChangeMonitor _displayMonitor;
    private readonly ILlmGatewayService _llmGateway;
    private readonly SemaphoreSlim _lock = new(1, 1);
    private AppSettingsDocument _settings = new();
    private IReadOnlyList<PluginDescriptor> _pluginSnapshot = [];
@@ -32,7 +34,8 @@
        IDiagnosticsService diagnostics,
        IRuntimeEventBus events,
        IRuntimeSurfaceController surfaces,
        DisplayChangeMonitor displayMonitor)
        DisplayChangeMonitor displayMonitor,
        ILlmGatewayService llmGateway)
    {
        _configuration = configuration;
        _plugins = plugins;
@@ -42,6 +45,7 @@
        _events = events;
        _surfaces = surfaces;
        _displayMonitor = displayMonitor;
        _llmGateway = llmGateway;
    }
    public async Task<OperationResult<AppRuntimeState>> StartAsync(CancellationToken cancellationToken = default)
@@ -261,6 +265,11 @@
        }
    }
    public async Task CancelPluginRequestsAsync(PluginId pluginId, CancellationToken cancellationToken = default)
    {
        await _llmGateway.CancelPluginRequestsAsync(pluginId.Value, cancellationToken).ConfigureAwait(false);
    }
    private async Task<OperationResult<AppRuntimeState>> UpdateRuntimeFlagAsync(
        string eventName,
        Action update,
src/Moli.Desktop/Runtime/IDesktopRuntime.cs
@@ -1,4 +1,5 @@
using Moli.Desktop.Layout;
using Moli.Desktop.Plugins;
namespace Moli.Desktop.Runtime;
@@ -19,4 +20,5 @@
        WidgetLayoutPatch patch,
        CancellationToken cancellationToken = default);
    Task OnDisplayTopologyChangedAsync(CancellationToken cancellationToken = default);
    Task CancelPluginRequestsAsync(PluginId pluginId, CancellationToken cancellationToken = default);
}
src/Moli.Desktop/WebView/IWebViewHost.cs
@@ -15,4 +15,5 @@
    Task InjectBridgeAsync(PluginBridgeContext context, CancellationToken cancellationToken = default);
    Task DispatchLifecycleEventAsync(string eventName, object? payload, CancellationToken cancellationToken = default);
    Task ReloadAsync(CancellationToken cancellationToken = default);
    Task NotifyParentWindowPositionChangedAsync(CancellationToken cancellationToken = default);
}
src/Moli.Desktop/WebView/WebViewHost.cs
@@ -126,6 +126,39 @@
        return Task.CompletedTask;
    }
    public Task NotifyParentWindowPositionChangedAsync(CancellationToken cancellationToken = default)
    {
        if (!_initialized || Control.CoreWebView2 is null)
        {
            return Task.CompletedTask;
        }
        cancellationToken.ThrowIfCancellationRequested();
        try
        {
            var controllerProperty = Control.GetType().GetProperty("CoreWebView2Controller");
            if (controllerProperty?.GetValue(Control) is { } controller)
            {
                var method = controller.GetType().GetMethod("NotifyParentWindowPositionChanged");
                method?.Invoke(controller, null);
                return Task.CompletedTask;
            }
        }
        catch
        {
        }
        Control.Dispatcher.InvokeAsync(() =>
        {
            Control.InvalidateMeasure();
            Control.InvalidateArrange();
            Control.UpdateLayout();
        }, System.Windows.Threading.DispatcherPriority.Render);
        return Task.CompletedTask;
    }
    public async ValueTask DisposeAsync()
    {
        _audioSubscription?.Dispose();
src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -40,6 +40,7 @@
    private Point? _dragStart;
    private RectD _startBounds;
    private bool _resizing;
    private DisplayLayer? _lastDisplayLayer;
    public WidgetWindow(
        PluginDescriptor plugin,
@@ -149,7 +150,6 @@
            ? height.Value
            : null;
        Height = Math.Max(_layout.Bounds.Height, _requestedHeight ?? _layout.Bounds.Height);
        ApplyWin32Styles();
    }
    public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
@@ -311,27 +311,45 @@
            _interop.SetToolWindow(hwnd, true);
            _interop.SetLayered(hwnd, true);
            _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
            switch (_layout.DisplayLayer)
            var currentLayer = _layout.DisplayLayer;
            if (currentLayer == _lastDisplayLayer)
            {
                return;
            }
            var parentChanged = false;
            switch (currentLayer)
            {
                case DisplayLayer.Desktop:
                    Topmost = false;
                    if (_monitorInfo is not null)
                    {
                        _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitorInfo, _layout.Bounds);
                        parentChanged = true;
                    }
                    break;
                case DisplayLayer.GlobalTop:
                    _interop.RestoreTopLevelWindow(hwnd);
                    Topmost = true;
                    parentChanged = true;
                    break;
                case DisplayLayer.AppTop:
                case DisplayLayer.Normal:
                default:
                    _interop.RestoreTopLevelWindow(hwnd);
                    Topmost = false;
                    parentChanged = true;
                    break;
            }
            _lastDisplayLayer = currentLayer;
            if (parentChanged)
            {
                _ = _webView.NotifyParentWindowPositionChangedAsync();
            }
        }
        catch (Exception ex)
        {