From 93676d91a7c734cf6b2ace496142e69ccb037775 Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期六, 02 五月 2026 16:41:54 +0800
Subject: [PATCH] T10, T11

---
 samples/plugins/sample.clock/index.html                          |   54 ++++
 src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs |    5 
 src/Moli.Desktop/WebView/IWebViewHost.cs                         |    2 
 samples/plugins/sample.wallpaper/plugin.json                     |   18 +
 src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs            |    5 
 src/Moli.Desktop/Windows/RuntimeSurfaceController.cs             |  174 +++++++++++++
 src/Moli.Desktop/App.xaml.cs                                     |    3 
 src/Moli.Desktop/Windows/WidgetWindow.cs                         |  266 ++++++++++++++++++++
 src/Moli.Desktop/WebView/WebViewHost.cs                          |    2 
 src/Moli.Desktop/Host/DesktopHostBuilder.cs                      |    3 
 samples/plugins/sample.clock/plugin.json                         |   22 +
 src/Moli.Desktop/Windows/WallpaperWindow.cs                      |  141 ++++++++++
 samples/plugins/sample.wallpaper/index.html                      |   39 +++
 13 files changed, 732 insertions(+), 2 deletions(-)

diff --git a/samples/plugins/sample.clock/index.html b/samples/plugins/sample.clock/index.html
new file mode 100644
index 0000000..c0073d0
--- /dev/null
+++ b/samples/plugins/sample.clock/index.html
@@ -0,0 +1,54 @@
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>Sample Clock</title>
+  <style>
+    html, body {
+      margin: 0;
+      width: 100%;
+      height: 100%;
+      background: transparent;
+      color: #f7fbff;
+      font-family: "Segoe UI", sans-serif;
+    }
+
+    body {
+      display: grid;
+      place-items: center;
+      background: rgba(18, 24, 32, 0.76);
+      border-radius: 8px;
+    }
+
+    .time {
+      font-size: 34px;
+      font-weight: 650;
+      letter-spacing: 0;
+    }
+
+    .date {
+      margin-top: 4px;
+      color: rgba(247, 251, 255, 0.72);
+      font-size: 13px;
+      text-align: center;
+    }
+  </style>
+</head>
+<body>
+  <main>
+    <div class="time" id="time">--:--:--</div>
+    <div class="date" id="date"></div>
+  </main>
+  <script>
+    const time = document.getElementById("time");
+    const date = document.getElementById("date");
+    const render = () => {
+      const now = new Date();
+      time.textContent = now.toLocaleTimeString([], { hour12: false });
+      date.textContent = now.toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" });
+    };
+    render();
+    setInterval(render, 1000);
+  </script>
+</body>
+</html>
diff --git a/samples/plugins/sample.clock/plugin.json b/samples/plugins/sample.clock/plugin.json
new file mode 100644
index 0000000..2b33bf0
--- /dev/null
+++ b/samples/plugins/sample.clock/plugin.json
@@ -0,0 +1,22 @@
+{
+  "id": "sample.clock",
+  "name": "Sample Clock",
+  "version": "1.0.0",
+  "type": "widget",
+  "entry": "index.html",
+  "description": "Local clock widget sample for Moli.Desktop.",
+  "author": "Moli.Desktop",
+  "defaultLayout": {
+    "x": 120,
+    "y": 120,
+    "width": 280,
+    "height": 120,
+    "locked": false,
+    "clickThrough": false,
+    "opacity": 0.92,
+    "scale": 1.0
+  },
+  "config": {
+    "hour12": false
+  }
+}
diff --git a/samples/plugins/sample.wallpaper/index.html b/samples/plugins/sample.wallpaper/index.html
new file mode 100644
index 0000000..3f99f5a
--- /dev/null
+++ b/samples/plugins/sample.wallpaper/index.html
@@ -0,0 +1,39 @@
+<!doctype html>
+<html lang="en">
+<head>
+  <meta charset="utf-8">
+  <title>Sample Wallpaper</title>
+  <style>
+    html, body {
+      margin: 0;
+      width: 100%;
+      height: 100%;
+      overflow: hidden;
+      background: #101820;
+    }
+
+    body::before {
+      content: "";
+      position: fixed;
+      inset: -20%;
+      background:
+        radial-gradient(circle at 20% 20%, rgba(40, 178, 170, 0.55), transparent 28%),
+        radial-gradient(circle at 78% 32%, rgba(255, 183, 77, 0.38), transparent 30%),
+        radial-gradient(circle at 45% 80%, rgba(126, 217, 87, 0.35), transparent 34%),
+        linear-gradient(135deg, #101820, #1a2633 52%, #0e151c);
+      animation: drift 18s ease-in-out infinite alternate;
+    }
+
+    @keyframes drift {
+      from { transform: translate3d(-2%, -1%, 0) scale(1); }
+      to { transform: translate3d(2%, 1%, 0) scale(1.04); }
+    }
+  </style>
+</head>
+<body>
+  <script>
+    window.addEventListener("moli:pause", () => document.body.style.animationPlayState = "paused");
+    window.addEventListener("moli:resume", () => document.body.style.animationPlayState = "running");
+  </script>
+</body>
+</html>
diff --git a/samples/plugins/sample.wallpaper/plugin.json b/samples/plugins/sample.wallpaper/plugin.json
new file mode 100644
index 0000000..24b79f0
--- /dev/null
+++ b/samples/plugins/sample.wallpaper/plugin.json
@@ -0,0 +1,18 @@
+{
+  "id": "sample.wallpaper",
+  "name": "Sample Wallpaper",
+  "version": "1.0.0",
+  "type": "wallpaper",
+  "entry": "index.html",
+  "description": "Local animated wallpaper sample for Moli.Desktop.",
+  "author": "Moli.Desktop",
+  "defaultLayout": {
+    "width": 1920,
+    "height": 1080,
+    "opacity": 1.0,
+    "clickThrough": true
+  },
+  "config": {
+    "theme": "aurora"
+  }
+}
diff --git a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
index 60e959c..b350e77 100644
--- a/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
+++ b/src/Moli.Desktop.Tests/Runtime/DesktopRuntimeCoordinatorTests.cs
@@ -76,7 +76,8 @@
 
         Assert.False(result.Succeeded);
         Assert.Equal("WidgetLayoutLocked", result.ErrorCode);
-        Assert.Null(fixture.Surface.LastAppliedLayout);
+        Assert.Equal(1, fixture.Surface.AppliedLayoutCount);
+        Assert.Equal(new RectD(100, 100, 320, 160), fixture.Surface.LastAppliedLayout?.Bounds);
     }
 
     private sealed class RuntimeFixture
@@ -183,6 +184,7 @@
     {
         public bool EditModeEnabled { get; private set; }
         public WidgetLayout? LastAppliedLayout { get; private set; }
+        public int AppliedLayoutCount { get; private set; }
 
         public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
         {
@@ -195,6 +197,7 @@
         public Task ApplyWidgetLayoutAsync(WidgetLayout layout, CancellationToken cancellationToken = default)
         {
             LastAppliedLayout = layout;
+            AppliedLayoutCount++;
             return Task.CompletedTask;
         }
 
diff --git a/src/Moli.Desktop/App.xaml.cs b/src/Moli.Desktop/App.xaml.cs
index 9063de7..111d1a0 100644
--- a/src/Moli.Desktop/App.xaml.cs
+++ b/src/Moli.Desktop/App.xaml.cs
@@ -2,6 +2,7 @@
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Moli.Desktop.Host;
+using Moli.Desktop.Runtime;
 
 namespace Moli.Desktop;
 
@@ -16,6 +17,7 @@
 
         _host = DesktopHostBuilder.Create(e.Args).Build();
         await _host.StartAsync();
+        await _host.Services.GetRequiredService<IDesktopRuntime>().StartAsync();
 
         var mainWindow = _host.Services.GetRequiredService<MainWindow>();
         mainWindow.Show();
@@ -25,6 +27,7 @@
     {
         if (_host is not null)
         {
+            await _host.Services.GetRequiredService<IDesktopRuntime>().ShutdownAsync();
             await _host.StopAsync(TimeSpan.FromSeconds(5));
             _host.Dispose();
         }
diff --git a/src/Moli.Desktop/Host/DesktopHostBuilder.cs b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
index 0082136..9f4ec05 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -8,6 +8,7 @@
 using Moli.Desktop.Plugins;
 using Moli.Desktop.Runtime;
 using Moli.Desktop.WebView;
+using Moli.Desktop.Windows;
 
 namespace Moli.Desktop.Host;
 
@@ -27,7 +28,7 @@
                 services.AddSingleton<DesktopPaths>();
                 services.AddSingleton<IDiagnosticsService, DiagnosticsService>();
                 services.AddSingleton<IRuntimeEventBus, RuntimeEventBus>();
-                services.AddSingleton<IRuntimeSurfaceController, NullRuntimeSurfaceController>();
+                services.AddSingleton<IRuntimeSurfaceController, RuntimeSurfaceController>();
                 services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>();
                 services.AddSingleton<IConfigurationService, JsonConfigurationService>();
                 services.AddSingleton<IPluginManifestValidator, PluginManifestValidator>();
diff --git a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
index 8f9d094..fc537cd 100644
--- a/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
+++ b/src/Moli.Desktop/Runtime/DesktopRuntimeCoordinator.cs
@@ -55,6 +55,11 @@
             await _layout.SaveAsync(cancellationToken).ConfigureAwait(false);
 
             _pluginSnapshot = await _plugins.ScanAsync(cancellationToken).ConfigureAwait(false);
+            foreach (var layout in _layout.GetAll().Where(layout => layout.IsVisible))
+            {
+                await _surfaces.ApplyWidgetLayoutAsync(layout, cancellationToken).ConfigureAwait(false);
+            }
+
             _diagnostics.Record(DiagnosticSeverity.Info, DiagnosticCodes.ApplicationStarted, "Desktop runtime started.");
             var state = BuildState();
             await PublishStatusAsync(state, cancellationToken).ConfigureAwait(false);
diff --git a/src/Moli.Desktop/WebView/IWebViewHost.cs b/src/Moli.Desktop/WebView/IWebViewHost.cs
index ff31e42..2dd06bb 100644
--- a/src/Moli.Desktop/WebView/IWebViewHost.cs
+++ b/src/Moli.Desktop/WebView/IWebViewHost.cs
@@ -1,4 +1,5 @@
 using Moli.Desktop.Plugins;
+using System.Windows;
 
 namespace Moli.Desktop.WebView;
 
@@ -8,6 +9,7 @@
     string HostId { get; }
     PluginId PluginId { get; }
     PluginType PluginType { get; }
+    FrameworkElement View { get; }
     Task InitializeAsync(WebViewHostOptions options, CancellationToken cancellationToken = default);
     Task NavigateAsync(Uri entryUri, CancellationToken cancellationToken = default);
     Task InjectBridgeAsync(PluginBridgeContext context, CancellationToken cancellationToken = default);
diff --git a/src/Moli.Desktop/WebView/WebViewHost.cs b/src/Moli.Desktop/WebView/WebViewHost.cs
index 357eb59..33b0284 100644
--- a/src/Moli.Desktop/WebView/WebViewHost.cs
+++ b/src/Moli.Desktop/WebView/WebViewHost.cs
@@ -1,6 +1,7 @@
 using System.IO;
 using System.Text.Encodings.Web;
 using System.Text.Json;
+using System.Windows;
 using Microsoft.Web.WebView2.Core;
 using Microsoft.Web.WebView2.Wpf;
 using Moli.Desktop.Diagnostics;
@@ -38,6 +39,7 @@
     }
 
     public WebView2 Control { get; }
+    public FrameworkElement View => Control;
     public string HostId { get; } = $"webview-{Guid.NewGuid():N}";
     public PluginId PluginId => _plugin.Id;
     public PluginType PluginType => _plugin.Type;
diff --git a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
new file mode 100644
index 0000000..44186f1
--- /dev/null
+++ b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -0,0 +1,174 @@
+using System.Windows;
+using Microsoft.Extensions.DependencyInjection;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Interop;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+using Moli.Desktop.WebView;
+
+namespace Moli.Desktop.Windows;
+
+/// <summary>Creates and updates real WPF desktop surfaces for runtime commands.</summary>
+public sealed class RuntimeSurfaceController : IRuntimeSurfaceController
+{
+    private readonly IPluginManager _plugins;
+    private readonly IWin32InteropService _interop;
+    private readonly IWebViewHostFactory _webViews;
+    private readonly DesktopPaths _paths;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly IServiceProvider _services;
+    private readonly Dictionary<WidgetInstanceId, WidgetWindow> _widgets = [];
+    private WallpaperWindow? _wallpaper;
+    private WallpaperRuntimeState _wallpaperState = new();
+    private bool _editMode;
+    private bool _safeInputMode;
+
+    public RuntimeSurfaceController(
+        IPluginManager plugins,
+        IWin32InteropService interop,
+        IWebViewHostFactory webViews,
+        DesktopPaths paths,
+        IDiagnosticsService diagnostics,
+        IServiceProvider services)
+    {
+        _plugins = plugins;
+        _interop = interop;
+        _webViews = webViews;
+        _paths = paths;
+        _diagnostics = diagnostics;
+        _services = services;
+    }
+
+    public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(async () =>
+        {
+            _editMode = enabled;
+            foreach (var widget in _widgets.Values)
+            {
+                cancellationToken.ThrowIfCancellationRequested();
+                await widget.SetEditModeAsync(enabled, cancellationToken).ConfigureAwait(true);
+            }
+        });
+
+    public Task ApplySafeInputModeAsync(bool enabled, CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(() =>
+        {
+            _safeInputMode = enabled;
+            _wallpaper?.ApplyState(_wallpaperState, _safeInputMode);
+            foreach (var widget in _widgets.Values)
+            {
+                widget.SetSafeInputMode(enabled);
+            }
+
+            return Task.CompletedTask;
+        });
+
+    public Task ApplyWidgetLayoutAsync(WidgetLayout layout, CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(async () =>
+        {
+            if (!_widgets.TryGetValue(layout.InstanceId, out var window))
+            {
+                var plugin = await _plugins.GetAsync(layout.PluginId, cancellationToken).ConfigureAwait(true);
+                if (plugin is null || plugin.State == PluginState.Invalid)
+                {
+                    _diagnostics.Record(
+                        DiagnosticSeverity.Warning,
+                        "WidgetPluginNotFound",
+                        "Widget plugin was not available for layout surface.",
+                        new Dictionary<string, string> { ["instanceId"] = layout.InstanceId.Value, ["pluginId"] = layout.PluginId.Value });
+                    return;
+                }
+
+                window = new WidgetWindow(
+                    plugin,
+                    layout,
+                    _webViews.Create(plugin),
+                    _interop,
+                    _paths,
+                    _diagnostics,
+                    CommitWidgetLayoutAsync);
+                _widgets[layout.InstanceId] = window;
+                window.Closed += (_, _) => _widgets.Remove(layout.InstanceId);
+                window.Show();
+                await window.LoadAsync(cancellationToken).ConfigureAwait(true);
+            }
+
+            window.ApplyLayout(layout, _editMode, _safeInputMode);
+        });
+
+    public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(async () =>
+        {
+            if (wallpaper.PluginId is null)
+            {
+                return;
+            }
+
+            var plugin = await _plugins.GetAsync(wallpaper.PluginId.Value, cancellationToken).ConfigureAwait(true);
+            if (plugin is null)
+            {
+                _diagnostics.Record(
+                    DiagnosticSeverity.Warning,
+                    "WallpaperPluginNotFound",
+                    "Wallpaper plugin was not available for surface creation.",
+                    new Dictionary<string, string> { ["pluginId"] = wallpaper.PluginId.Value.Value });
+                return;
+            }
+
+            _wallpaper?.Close();
+            _wallpaperState = wallpaper;
+            var monitor = _interop.GetMonitors().FirstOrDefault(monitor => monitor.IsPrimary) ?? _interop.GetMonitors().First();
+            _wallpaper = new WallpaperWindow(plugin, monitor, _webViews.Create(plugin), _interop, _paths, _diagnostics);
+            _wallpaper.Closed += (_, _) => _wallpaper = null;
+            _wallpaper.Show();
+            await _wallpaper.LoadAsync(wallpaper, cancellationToken).ConfigureAwait(true);
+            _wallpaper.ApplyState(wallpaper, _safeInputMode);
+        });
+
+    public Task DisableWallpaperAsync(CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(() =>
+        {
+            _wallpaperState = _wallpaperState with { IsEnabled = false };
+            _wallpaper?.Close();
+            _wallpaper = null;
+            return Task.CompletedTask;
+        });
+
+    public Task ShutdownAsync(CancellationToken cancellationToken = default)
+        => OnUiThreadAsync(() =>
+        {
+            foreach (var widget in _widgets.Values.ToArray())
+            {
+                widget.Close();
+            }
+
+            _widgets.Clear();
+            _wallpaper?.Close();
+            _wallpaper = null;
+            return Task.CompletedTask;
+        });
+
+    private async Task CommitWidgetLayoutAsync(
+        WidgetInstanceId instanceId,
+        WidgetLayoutPatch patch,
+        CancellationToken cancellationToken)
+    {
+        var runtime = _services.GetRequiredService<IDesktopRuntime>();
+        await runtime.UpdateWidgetLayoutAsync(instanceId, patch, cancellationToken).ConfigureAwait(true);
+    }
+
+    private static async Task OnUiThreadAsync(Func<Task> action)
+    {
+        var dispatcher = Application.Current?.Dispatcher;
+        if (dispatcher is null || dispatcher.CheckAccess())
+        {
+            await action().ConfigureAwait(true);
+            return;
+        }
+
+        await await dispatcher.InvokeAsync(action).Task.ConfigureAwait(false);
+    }
+}
diff --git a/src/Moli.Desktop/Windows/WallpaperWindow.cs b/src/Moli.Desktop/Windows/WallpaperWindow.cs
new file mode 100644
index 0000000..5ffeba5
--- /dev/null
+++ b/src/Moli.Desktop/Windows/WallpaperWindow.cs
@@ -0,0 +1,141 @@
+using System.IO;
+using System.Text.Json;
+using System.Windows;
+using System.Windows.Media;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Interop;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+using Moli.Desktop.WebView;
+
+namespace Moli.Desktop.Windows;
+
+/// <summary>Borderless desktop wallpaper surface backed by one WebView host.</summary>
+public sealed class WallpaperWindow : Window
+{
+    private readonly PluginDescriptor _plugin;
+    private readonly MonitorInfo _monitor;
+    private readonly IWebViewHost _webView;
+    private readonly IWin32InteropService _interop;
+    private readonly DesktopPaths _paths;
+    private readonly IDiagnosticsService _diagnostics;
+    private bool _clickThrough = true;
+    private double _opacity = 1;
+
+    public WallpaperWindow(
+        PluginDescriptor plugin,
+        MonitorInfo monitor,
+        IWebViewHost webView,
+        IWin32InteropService interop,
+        DesktopPaths paths,
+        IDiagnosticsService diagnostics)
+    {
+        _plugin = plugin;
+        _monitor = monitor;
+        _webView = webView;
+        _interop = interop;
+        _paths = paths;
+        _diagnostics = diagnostics;
+
+        Title = $"Moli Wallpaper - {plugin.Manifest.Name}";
+        WindowStyle = WindowStyle.None;
+        ResizeMode = ResizeMode.NoResize;
+        AllowsTransparency = true;
+        Background = Brushes.Transparent;
+        ShowInTaskbar = false;
+        Topmost = false;
+        Left = monitor.Bounds.X;
+        Top = monitor.Bounds.Y;
+        Width = monitor.Bounds.Width;
+        Height = monitor.Bounds.Height;
+        Content = webView.View;
+
+        Loaded += (_, _) => ApplyWin32Styles();
+    }
+
+    public async Task LoadAsync(WallpaperRuntimeState state, CancellationToken cancellationToken = default)
+    {
+        _clickThrough = state.ClickThrough;
+        _opacity = state.Opacity;
+        await _webView.InitializeAsync(new WebViewHostOptions
+        {
+            UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "wallpaper", _plugin.Id.Value),
+            IsTransparent = true,
+            AreDevToolsEnabled = true,
+            IsMuted = state.IsMuted,
+            InitialScript = PluginBridgeScript.Build()
+        }, cancellationToken).ConfigureAwait(true);
+
+        await _webView.InjectBridgeAsync(CreateBridgeContext(), cancellationToken).ConfigureAwait(true);
+        await _webView.NavigateAsync(_plugin.EntryUri, cancellationToken).ConfigureAwait(true);
+        await _webView.DispatchLifecycleEventAsync("moli:wallpaper-enabled", state, cancellationToken).ConfigureAwait(true);
+    }
+
+    public void ApplyState(WallpaperRuntimeState state, bool safeInputMode)
+    {
+        _clickThrough = !safeInputMode && state.ClickThrough;
+        _opacity = state.Opacity;
+        Opacity = Math.Clamp(state.Opacity, 0.1, 1.0);
+        ApplyWin32Styles();
+    }
+
+    public Task PauseAsync(CancellationToken cancellationToken = default)
+        => _webView.DispatchLifecycleEventAsync("moli:pause", null, cancellationToken);
+
+    public Task ResumeAsync(CancellationToken cancellationToken = default)
+        => _webView.DispatchLifecycleEventAsync("moli:resume", null, cancellationToken);
+
+    public Task ReloadAsync(CancellationToken cancellationToken = default) => _webView.ReloadAsync(cancellationToken);
+
+    protected override async void OnClosed(EventArgs e)
+    {
+        await _webView.DisposeAsync();
+        base.OnClosed(e);
+    }
+
+    private PluginBridgeContext CreateBridgeContext() => new()
+    {
+        HostId = _webView.HostId,
+        Manifest = _plugin.Manifest,
+        RuntimeInfo = new PluginRuntimeBridgeInfo
+        {
+            HostId = _webView.HostId,
+            PluginId = _plugin.Id.Value,
+            PluginType = _plugin.Type,
+            IsVisible = true
+        },
+        Config = _plugin.Manifest.Config.ValueKind == JsonValueKind.Undefined
+            ? default
+            : _plugin.Manifest.Config.Clone()
+    };
+
+    private void ApplyWin32Styles()
+    {
+        var hwnd = _interop.GetWindowHandle(this);
+        if (hwnd == IntPtr.Zero)
+        {
+            return;
+        }
+
+        try
+        {
+            _interop.SetToolWindow(hwnd, true);
+            _interop.SetNoActivate(hwnd, true);
+            _interop.SetLayered(hwnd, true, ToAlpha(_opacity));
+            _interop.SetClickThrough(hwnd, _clickThrough);
+            _interop.MoveToDesktopLayer(hwnd, DesktopLayerMode.WorkerW, _monitor);
+        }
+        catch (Exception ex)
+        {
+            _diagnostics.Record(
+                DiagnosticSeverity.Warning,
+                DiagnosticCodes.DesktopLayerAttachFailed,
+                "Failed to apply wallpaper window styles.",
+                new Dictionary<string, string> { ["pluginId"] = _plugin.Id.Value, ["exception"] = ex.GetType().Name });
+        }
+    }
+
+    private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
+}
diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
new file mode 100644
index 0000000..64b1cb8
--- /dev/null
+++ b/src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -0,0 +1,266 @@
+using System.IO;
+using System.Text.Json;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Interop;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+using Moli.Desktop.WebView;
+
+namespace Moli.Desktop.Windows;
+
+/// <summary>Desktop widget surface with edit-mode drag and resize behavior.</summary>
+public sealed class WidgetWindow : Window
+{
+    private const double ResizeGripSize = 18;
+    private readonly PluginDescriptor _plugin;
+    private readonly IWebViewHost _webView;
+    private readonly IWin32InteropService _interop;
+    private readonly DesktopPaths _paths;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly Func<WidgetInstanceId, WidgetLayoutPatch, CancellationToken, Task> _commitLayoutAsync;
+    private readonly Border _editBorder;
+    private readonly Border _resizeGrip;
+    private WidgetLayout _layout;
+    private bool _editMode;
+    private bool _safeInputMode;
+    private Point? _dragStart;
+    private RectD _startBounds;
+    private bool _resizing;
+
+    public WidgetWindow(
+        PluginDescriptor plugin,
+        WidgetLayout layout,
+        IWebViewHost webView,
+        IWin32InteropService interop,
+        DesktopPaths paths,
+        IDiagnosticsService diagnostics,
+        Func<WidgetInstanceId, WidgetLayoutPatch, CancellationToken, Task> commitLayoutAsync)
+    {
+        _plugin = plugin;
+        _layout = layout;
+        _webView = webView;
+        _interop = interop;
+        _paths = paths;
+        _diagnostics = diagnostics;
+        _commitLayoutAsync = commitLayoutAsync;
+
+        Title = $"Moli Widget - {plugin.Manifest.Name}";
+        WindowStyle = WindowStyle.None;
+        ResizeMode = ResizeMode.NoResize;
+        AllowsTransparency = true;
+        Background = Brushes.Transparent;
+        ShowInTaskbar = false;
+        Topmost = true;
+        SizeToContent = SizeToContent.Manual;
+
+        var root = new Grid { Background = Brushes.Transparent };
+        root.Children.Add(webView.View);
+        _editBorder = new Border
+        {
+            BorderBrush = Brushes.DeepSkyBlue,
+            BorderThickness = new Thickness(2),
+            Visibility = Visibility.Collapsed,
+            IsHitTestVisible = false
+        };
+        _resizeGrip = new Border
+        {
+            Width = ResizeGripSize,
+            Height = ResizeGripSize,
+            HorizontalAlignment = HorizontalAlignment.Right,
+            VerticalAlignment = VerticalAlignment.Bottom,
+            Background = Brushes.DeepSkyBlue,
+            Opacity = 0.85,
+            Cursor = Cursors.SizeNWSE,
+            Visibility = Visibility.Collapsed
+        };
+        root.Children.Add(_editBorder);
+        root.Children.Add(_resizeGrip);
+        Content = root;
+
+        Loaded += (_, _) => ApplyWin32Styles();
+        MouseLeftButtonDown += OnMouseLeftButtonDown;
+        MouseMove += OnMouseMove;
+        MouseLeftButtonUp += OnMouseLeftButtonUp;
+        _resizeGrip.MouseLeftButtonDown += OnResizeGripMouseLeftButtonDown;
+    }
+
+    public WidgetInstanceId InstanceId => _layout.InstanceId;
+
+    public async Task LoadAsync(CancellationToken cancellationToken = default)
+    {
+        ApplyLayout(_layout, _editMode, _safeInputMode);
+        await _webView.InitializeAsync(new WebViewHostOptions
+        {
+            UserDataFolder = Path.Combine(_paths.WebViewDataDirectory, "widgets", _layout.InstanceId.Value),
+            IsTransparent = true,
+            AreDevToolsEnabled = true,
+            IsMuted = false,
+            InitialScript = PluginBridgeScript.Build()
+        }, cancellationToken).ConfigureAwait(true);
+
+        await _webView.InjectBridgeAsync(CreateBridgeContext(), cancellationToken).ConfigureAwait(true);
+        await _webView.NavigateAsync(_plugin.EntryUri, cancellationToken).ConfigureAwait(true);
+        await _webView.DispatchLifecycleEventAsync("moli:widget-loaded", ToRuntimeState(), cancellationToken).ConfigureAwait(true);
+    }
+
+    public void ApplyLayout(WidgetLayout layout, bool editMode, bool safeInputMode)
+    {
+        _layout = layout;
+        _editMode = editMode;
+        _safeInputMode = safeInputMode;
+        Left = layout.Bounds.X;
+        Top = layout.Bounds.Y;
+        Width = layout.Bounds.Width;
+        Height = layout.Bounds.Height;
+        Opacity = Math.Clamp(layout.Opacity, 0.1, 1.0);
+        Visibility = layout.IsVisible ? Visibility.Visible : Visibility.Hidden;
+        _editBorder.Visibility = editMode ? Visibility.Visible : Visibility.Collapsed;
+        _resizeGrip.Visibility = editMode && !layout.IsLocked ? Visibility.Visible : Visibility.Collapsed;
+        ApplyWin32Styles();
+    }
+
+    public Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
+    {
+        ApplyLayout(_layout, enabled, _safeInputMode);
+        return _webView.DispatchLifecycleEventAsync("moli:edit-mode-changed", new { enabled }, cancellationToken);
+    }
+
+    public void SetSafeInputMode(bool enabled)
+    {
+        _safeInputMode = enabled;
+        ApplyWin32Styles();
+    }
+
+    protected override async void OnClosed(EventArgs e)
+    {
+        await _webView.DisposeAsync();
+        base.OnClosed(e);
+    }
+
+    private void OnResizeGripMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+    {
+        if (!_editMode || _layout.IsLocked)
+        {
+            return;
+        }
+
+        _resizing = true;
+        BeginPointerOperation(e);
+        e.Handled = true;
+    }
+
+    private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
+    {
+        if (!_editMode || _layout.IsLocked || _resizing)
+        {
+            return;
+        }
+
+        BeginPointerOperation(e);
+    }
+
+    private void OnMouseMove(object sender, MouseEventArgs e)
+    {
+        if (_dragStart is null || e.LeftButton != MouseButtonState.Pressed)
+        {
+            return;
+        }
+
+        var current = PointToScreen(e.GetPosition(this));
+        var deltaX = current.X - _dragStart.Value.X;
+        var deltaY = current.Y - _dragStart.Value.Y;
+        if (_resizing)
+        {
+            Width = Math.Max(LayoutManager.MinWidth, _startBounds.Width + deltaX);
+            Height = Math.Max(LayoutManager.MinHeight, _startBounds.Height + deltaY);
+        }
+        else
+        {
+            Left = _startBounds.X + deltaX;
+            Top = _startBounds.Y + deltaY;
+        }
+    }
+
+    private async void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
+    {
+        if (_dragStart is null)
+        {
+            return;
+        }
+
+        ReleaseMouseCapture();
+        var bounds = new RectD(Left, Top, Width, Height);
+        _dragStart = null;
+        _resizing = false;
+        await _commitLayoutAsync(_layout.InstanceId, new WidgetLayoutPatch { Bounds = bounds }, CancellationToken.None);
+    }
+
+    private void BeginPointerOperation(MouseButtonEventArgs e)
+    {
+        _dragStart = PointToScreen(e.GetPosition(this));
+        _startBounds = new RectD(Left, Top, Width, Height);
+        CaptureMouse();
+    }
+
+    private PluginBridgeContext CreateBridgeContext() => new()
+    {
+        HostId = _webView.HostId,
+        Manifest = _plugin.Manifest,
+        RuntimeInfo = new PluginRuntimeBridgeInfo
+        {
+            HostId = _webView.HostId,
+            PluginId = _plugin.Id.Value,
+            PluginType = _plugin.Type,
+            IsVisible = _layout.IsVisible,
+            IsEditMode = _editMode
+        },
+        Config = _plugin.Manifest.Config.ValueKind == JsonValueKind.Undefined
+            ? default
+            : _plugin.Manifest.Config.Clone()
+    };
+
+    private WidgetRuntimeState ToRuntimeState() => new()
+    {
+        InstanceId = _layout.InstanceId,
+        PluginId = _layout.PluginId,
+        Bounds = _layout.Bounds,
+        MonitorId = _layout.MonitorId,
+        IsVisible = _layout.IsVisible,
+        IsLocked = _layout.IsLocked,
+        Opacity = _layout.Opacity,
+        ClickThrough = _layout.ClickThrough
+    };
+
+    private void ApplyWin32Styles()
+    {
+        var hwnd = _interop.GetWindowHandle(this);
+        if (hwnd == IntPtr.Zero)
+        {
+            return;
+        }
+
+        try
+        {
+            _interop.SetToolWindow(hwnd, true);
+            _interop.SetLayered(hwnd, true, ToAlpha(_layout.Opacity));
+            _interop.SetClickThrough(hwnd, !_editMode && !_safeInputMode && _layout.ClickThrough);
+        }
+        catch (Exception ex)
+        {
+            _diagnostics.Record(
+                DiagnosticSeverity.Warning,
+                DiagnosticCodes.Win32InteropFailed,
+                "Failed to apply widget window styles.",
+                new Dictionary<string, string> { ["instanceId"] = _layout.InstanceId.Value, ["exception"] = ex.GetType().Name });
+        }
+    }
+
+    private static byte ToAlpha(double opacity) => (byte)Math.Round(Math.Clamp(opacity, 0.1, 1.0) * 255);
+}

--
Gitblit v1.9.1