From 97df0fb5ed49e37d1c8e0e62057bb72ba5c9eb6a Mon Sep 17 00:00:00 2001
From: chunhualin1 <chunhualin1@lenovo.com>
Date: 星期三, 12 八月 2026 17:24:49 +0800
Subject: [PATCH] 优化透明样式

---
 src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs |   40 +++++++++++++
 src/Moli.Desktop/Runtime/IDesktopRuntime.cs                      |    2 
 src/Moli.Desktop/WebView/IWebViewHost.cs                         |    1 
 src/Moli.Desktop/Management/ManagementWindow.xaml.cs             |    1 
 src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs            |   11 +++
 scripts/publish-to-apps.ps1                                      |    2 
 src/Moli.Desktop/Llm/ILlmServices.cs                             |    1 
 samples/plugins/sample.llm-command-palette/index.html            |   12 +++
 src/Moli.Desktop/Llm/LlmGatewayService.cs                        |   26 ++++++++
 src/Moli.Desktop/Windows/WidgetWindow.cs                         |   22 ++++++
 src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs    |    2 
 src/Moli.Desktop/WebView/WebViewHost.cs                          |   33 +++++++++++
 12 files changed, 147 insertions(+), 6 deletions(-)

diff --git a/samples/plugins/sample.llm-command-palette/index.html b/samples/plugins/sample.llm-command-palette/index.html
index 569f80b..6057f32 100644
--- a/samples/plugins/sample.llm-command-palette/index.html
+++ b/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() {
diff --git a/scripts/publish-to-apps.ps1 b/scripts/publish-to-apps.ps1
index a82d274..f248843 100644
--- a/scripts/publish-to-apps.ps1
+++ b/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,
diff --git a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
index 3b3ebde..00e8102 100644
--- a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
+++ b/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;
+    }
 }
diff --git a/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs b/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
index b50c648..0502097 100644
--- a/src/Moli.Desktop.Tests/WebView/PluginBridgeDispatcherTests.cs
+++ b/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>>(
             [
diff --git a/src/Moli.Desktop/Llm/ILlmServices.cs b/src/Moli.Desktop/Llm/ILlmServices.cs
index 2258be5..c4552f0 100644
--- a/src/Moli.Desktop/Llm/ILlmServices.cs
+++ b/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
diff --git a/src/Moli.Desktop/Llm/LlmGatewayService.cs b/src/Moli.Desktop/Llm/LlmGatewayService.cs
index 472ecda..e068be6 100644
--- a/src/Moli.Desktop/Llm/LlmGatewayService.cs
+++ b/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) ||
diff --git a/src/Moli.Desktop/Management/ManagementWindow.xaml.cs b/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
index 19185ed..b2aef4b 100644
--- a/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
+++ b/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 });
     }
 
diff --git a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
index 76e3087..13f1d1d 100644
--- a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
+++ b/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,
diff --git a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs b/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
index 9304d8d..47ba35f 100644
--- a/src/Moli.Desktop/Runtime/IDesktopRuntime.cs
+++ b/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);
 }
diff --git a/src/Moli.Desktop/WebView/IWebViewHost.cs b/src/Moli.Desktop/WebView/IWebViewHost.cs
index 2dd06bb..e12dde5 100644
--- a/src/Moli.Desktop/WebView/IWebViewHost.cs
+++ b/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);
 }
diff --git a/src/Moli.Desktop/WebView/WebViewHost.cs b/src/Moli.Desktop/WebView/WebViewHost.cs
index dd39b80..95c87c6 100644
--- a/src/Moli.Desktop/WebView/WebViewHost.cs
+++ b/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();
diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
index 94ecba0..23a87cf 100644
--- a/src/Moli.Desktop/Windows/WidgetWindow.cs
+++ b/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)
         {

--
Gitblit v1.9.1