From 690cf73d6100e93d6ae7ca95dededbad4e40eeed Mon Sep 17 00:00:00 2001
From: Moli <13026959681@163.com>
Date: 星期六, 02 五月 2026 23:10:17 +0800
Subject: [PATCH] T12-T14、T16

---
 src/Moli.Desktop/Tray/TrayShell.cs                   |  160 ++++++++
 src/Moli.Desktop/Tray/ITrayShell.cs                  |    7 
 src/Moli.Desktop/Management/ManagementWindow.xaml    |   78 ++++
 src/Moli.Desktop/Windows/RuntimeSurfaceController.cs |    1 
 src/Moli.Desktop/Moli.Desktop.csproj                 |    5 
 src/Moli.Desktop/App.xaml.cs                         |   14 
 src/Moli.Desktop/Windows/WidgetWindow.cs             |    5 
 src/Moli.Desktop/Host/DesktopHostBuilder.cs          |   10 
 src/Moli.Desktop/Management/ManagementWindow.xaml.cs |  178 +++++++++
 scripts/api-smoke-test.ps1                           |   51 ++
 src/Moli.Desktop/Tray/RegistryStartupService.cs      |   41 ++
 src/Moli.Desktop/Windows/WallpaperWindow.cs          |    1 
 src/Moli.Desktop/Api/LocalApiService.cs              |  295 ++++++++++++++++
 src/Moli.Desktop/Tray/IStartupService.cs             |    7 
 src/Moli.Desktop/Api/LocalApiModels.cs               |  149 ++++++++
 docs/qa/mvp-integration-handoff.md                   |   38 ++
 16 files changed, 1,033 insertions(+), 7 deletions(-)

diff --git a/docs/qa/mvp-integration-handoff.md b/docs/qa/mvp-integration-handoff.md
new file mode 100644
index 0000000..777ca19
--- /dev/null
+++ b/docs/qa/mvp-integration-handoff.md
@@ -0,0 +1,38 @@
+# Moli.Desktop MVP 闆嗘垚绉讳氦璁板綍
+
+鏃ユ湡锛�2026-05-02
+
+## 鑼冨洿
+
+- T12 Tray Shell锛氭墭鐩樺浘鏍囥�佽彍鍗曞懡浠ゃ�佹棩蹇楃洰褰曘�佸紑鏈哄惎鍔ㄣ�侀��鍑烘祦绋嬨��
+- T13 Management Window锛氱姸鎬併�佸绾搞�佺粍浠躲�佹彃浠躲�佽瘖鏂� tabs 鍜屾牳蹇冨懡浠ゃ��
+- T14 Local API and WebSocket锛歚127.0.0.1:8765` Minimal API銆佷簨浠� WebSocket銆侀敊璇搷搴斻��
+- T16 Integration Hardening锛氭瀯寤烘祴璇曘�丄PI smoke test 鑴氭湰銆佹墜宸ラ獙鏀舵竻鍗曘��
+
+## 鑷姩鍖栭獙璇�
+
+```powershell
+dotnet build .\Moli.Desktop.slnx
+dotnet test .\Moli.Desktop.slnx
+.\scripts\api-smoke-test.ps1
+```
+
+`api-smoke-test.ps1` 闇�瑕佸厛鍚姩 `Moli.Desktop`锛岄粯璁よ闂� `http://127.0.0.1:8765`銆�
+
+## 鎵嬪伐楠屾敹娓呭崟
+
+- 鎵樼洏鑿滃崟鍙墦寮�锛屽弻鍑绘墭鐩樺浘鏍囧彲鎵撳紑绠$悊绐楀彛銆�
+- 鎵樼洏鍙垏鎹㈢紪杈戞ā寮忋�佸畨鍏ㄨ緭鍏ユā寮忋�侀攣瀹氬叏閮紝骞跺彲姝e父閫�鍑哄簲鐢ㄣ��
+- 绠$悊绐楀彛涓嶆槸妗岄潰瑕嗙洊灞傦紝tabs 鍙煡鐪嬬姸鎬併�佹彃浠躲�佺粍浠跺拰璇婃柇銆�
+- 绠$悊绐楀彛鍙墽琛屽绾稿惎鍋溿�佺粍浠舵樉绀洪殣钘忋�佺粍浠堕攣瀹氥�侀噸杞芥彃浠躲�侀噸缃竷灞�銆�
+- `GET /api/status` 杩斿洖杩愯鏃剁姸鎬佸拰 API 鐩戝惉鐘舵�併��
+- `POST /api/edit-mode` 鍙�氳繃 JSON body 鎴栨棤 body 鍒囨崲缂栬緫妯″紡銆�
+- `GET /ws/events` 鍙帴鏀� `widget.layoutChanged`銆乣app.statusChanged` 绛夎繍琛屾椂浜嬩欢銆�
+- API 鍙粦瀹� `127.0.0.1`锛涚鍙e崰鐢ㄦ椂搴旂敤缁х画鍚姩骞惰褰� `LocalApiStartFailed`銆�
+- 閰嶇疆鎹熷潖鎭㈠銆乄ebView2 Runtime 缂哄け鎻愮ず銆佹嫋鎷界缉鏀句繚瀛橀渶鍦ㄧ湡瀹炴闈㈢幆澧冨楠屻��
+
+## 宸茬煡闄愬埗
+
+- 寮�鏈哄惎鍔ㄥ綋鍓嶄娇鐢� HKCU Run 娉ㄥ唽琛ㄩ」锛屾湭瀹炵幇瀹夎鍣ㄧ骇鍚姩椤圭鐞嗐��
+- 绠$悊绐楀彛鐨勯噸缃竷灞�鏄� MVP 绾ц蒋閲嶇疆锛氭仮澶嶅彲瑙併�佽В閿併�侀�忔槑搴﹀拰鐐瑰嚮绌块�忥紝涓嶉噸寤虹粍浠跺疄渚嬨��
+- WebView2 Runtime 缂哄け鍙兘鍦ㄧ己澶辫繍琛屾椂鐨勬満鍣ㄤ笂瀹屾暣楠岃瘉銆�
diff --git a/scripts/api-smoke-test.ps1 b/scripts/api-smoke-test.ps1
new file mode 100644
index 0000000..f7f7773
--- /dev/null
+++ b/scripts/api-smoke-test.ps1
@@ -0,0 +1,51 @@
+param(
+    [string]$BaseUrl = "http://127.0.0.1:8765"
+)
+
+$ErrorActionPreference = "Stop"
+
+function Invoke-MoliApi {
+    param(
+        [string]$Method,
+        [string]$Path,
+        [object]$Body = $null
+    )
+
+    $uri = "$BaseUrl$Path"
+    if ($null -eq $Body) {
+        Invoke-RestMethod -Method $Method -Uri $uri
+    }
+    else {
+        Invoke-RestMethod -Method $Method -Uri $uri -ContentType "application/json" -Body ($Body | ConvertTo-Json -Depth 8)
+    }
+}
+
+$status = Invoke-MoliApi -Method Get -Path "/api/status"
+Write-Host "status: editMode=$($status.isEditMode), safeInput=$($status.isSafeInputMode), plugins=$($status.plugins.Count), widgets=$($status.widgets.Count)"
+
+try {
+    $edit = Invoke-MoliApi -Method Post -Path "/api/edit-mode" -Body @{ enabled = -not $status.isEditMode }
+    Write-Host "edit-mode toggled: $($edit.isEditMode)"
+
+    $safe = Invoke-MoliApi -Method Post -Path "/api/safe-input-mode" -Body @{ enabled = $status.isSafeInputMode }
+    Write-Host "safe-input confirmed: $($safe.isSafeInputMode)"
+
+    $plugins = Invoke-MoliApi -Method Get -Path "/api/plugins"
+    Write-Host "plugins endpoint returned $($plugins.Count) item(s)"
+
+    if ($status.widgets.Count -gt 0) {
+        $widget = $status.widgets[0]
+        $updated = Invoke-MoliApi -Method Post -Path "/api/widgets/$($widget.instanceId)/layout" -Body @{
+            isVisible = $widget.isVisible
+            isLocked = $widget.isLocked
+            opacity = $widget.opacity
+        }
+        Write-Host "widget layout accepted: $($updated.instanceId)"
+    }
+}
+finally {
+    Invoke-MoliApi -Method Post -Path "/api/edit-mode" -Body @{ enabled = $status.isEditMode } | Out-Null
+    Invoke-MoliApi -Method Post -Path "/api/safe-input-mode" -Body @{ enabled = $status.isSafeInputMode } | Out-Null
+}
+
+Write-Host "API smoke test completed."
diff --git a/src/Moli.Desktop/Api/LocalApiModels.cs b/src/Moli.Desktop/Api/LocalApiModels.cs
new file mode 100644
index 0000000..9ce3aa2
--- /dev/null
+++ b/src/Moli.Desktop/Api/LocalApiModels.cs
@@ -0,0 +1,149 @@
+using System.Text.Json.Serialization;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Api;
+
+public sealed record LocalApiStatusSnapshot
+{
+    public bool IsListening { get; init; }
+    public string Host { get; init; } = "127.0.0.1";
+    public int Port { get; init; } = 8765;
+    public string? ErrorCode { get; init; }
+    public string? Message { get; init; }
+}
+
+public interface ILocalApiStatus
+{
+    LocalApiStatusSnapshot GetStatus();
+}
+
+public sealed record ApiErrorResponse(string ErrorCode, string Message);
+
+public sealed record ModeRequest(bool? Enabled);
+
+public sealed record RectDto(double X, double Y, double Width, double Height)
+{
+    public RectD ToRect() => new(X, Y, Width, Height);
+    public static RectDto From(RectD rect) => new(rect.X, rect.Y, rect.Width, rect.Height);
+}
+
+public sealed record WidgetLayoutPatchRequest
+{
+    public RectDto? Bounds { get; init; }
+    public string? MonitorId { get; init; }
+    public bool? IsVisible { get; init; }
+    public bool? IsLocked { get; init; }
+    public double? Opacity { get; init; }
+    public bool? ClickThrough { get; init; }
+    public double? Scale { get; init; }
+
+    public WidgetLayoutPatch ToPatch() => new()
+    {
+        Bounds = Bounds?.ToRect(),
+        MonitorId = string.IsNullOrWhiteSpace(MonitorId) ? null : new MonitorId(MonitorId),
+        IsVisible = IsVisible,
+        IsLocked = IsLocked,
+        Opacity = Opacity,
+        ClickThrough = ClickThrough,
+        Scale = Scale
+    };
+}
+
+public sealed record ApiStatusResponse
+{
+    public bool IsEditMode { get; init; }
+    public bool IsGlobalLocked { get; init; }
+    public bool IsSafeInputMode { get; init; }
+    public LocalApiStatusSnapshot Api { get; init; } = new();
+    public WallpaperResponse Wallpaper { get; init; } = new();
+    public IReadOnlyList<PluginResponse> Plugins { get; init; } = [];
+    public IReadOnlyList<WidgetResponse> Widgets { get; init; } = [];
+    public IReadOnlyList<DiagnosticEntry> Diagnostics { get; init; } = [];
+
+    public static ApiStatusResponse From(AppRuntimeState state, LocalApiStatusSnapshot api) => new()
+    {
+        IsEditMode = state.IsEditMode,
+        IsGlobalLocked = state.IsGlobalLocked,
+        IsSafeInputMode = state.IsSafeInputMode,
+        Api = api,
+        Wallpaper = WallpaperResponse.From(state.Wallpaper),
+        Plugins = [.. state.Plugins.Select(PluginResponse.From)],
+        Widgets = [.. state.Widgets.Select(WidgetResponse.From)],
+        Diagnostics = state.Diagnostics
+    };
+}
+
+public sealed record WallpaperResponse
+{
+    public bool IsEnabled { get; init; }
+    public bool IsPaused { get; init; }
+    public bool IsMuted { get; init; }
+    public double Opacity { get; init; }
+    public bool ClickThrough { get; init; }
+    public string? PluginId { get; init; }
+
+    public static WallpaperResponse From(WallpaperRuntimeState state) => new()
+    {
+        IsEnabled = state.IsEnabled,
+        IsPaused = state.IsPaused,
+        IsMuted = state.IsMuted,
+        Opacity = state.Opacity,
+        ClickThrough = state.ClickThrough,
+        PluginId = state.PluginId?.Value
+    };
+}
+
+public sealed record PluginResponse
+{
+    public required string Id { get; init; }
+    public required string Name { get; init; }
+    [JsonConverter(typeof(JsonStringEnumConverter<PluginType>))]
+    public PluginType Type { get; init; }
+    [JsonConverter(typeof(JsonStringEnumConverter<PluginState>))]
+    public PluginState State { get; init; }
+    public string? ErrorCode { get; init; }
+    public string Entry { get; init; } = "";
+
+    public static PluginResponse From(PluginRuntimeState state) => new()
+    {
+        Id = state.Id.Value,
+        Name = state.Name,
+        Type = state.Type,
+        State = state.State,
+        ErrorCode = state.ErrorCode,
+        Entry = state.Entry ?? ""
+    };
+}
+
+public sealed record WidgetResponse
+{
+    public required string InstanceId { get; init; }
+    public required string PluginId { get; init; }
+    public required RectDto Bounds { get; init; }
+    public required string MonitorId { get; init; }
+    public bool IsVisible { get; init; }
+    public bool IsLocked { get; init; }
+    public double Opacity { get; init; }
+    public bool ClickThrough { get; init; }
+
+    public static WidgetResponse From(WidgetRuntimeState state) => new()
+    {
+        InstanceId = state.InstanceId.Value,
+        PluginId = state.PluginId.Value,
+        Bounds = RectDto.From(state.Bounds),
+        MonitorId = state.MonitorId.Value,
+        IsVisible = state.IsVisible,
+        IsLocked = state.IsLocked,
+        Opacity = state.Opacity,
+        ClickThrough = state.ClickThrough
+    };
+}
+
+public sealed record RuntimeEventResponse(string Name, DateTimeOffset Timestamp, object? Payload)
+{
+    public static RuntimeEventResponse From(RuntimeEvent runtimeEvent)
+        => new(runtimeEvent.Name, runtimeEvent.Timestamp, runtimeEvent.Payload);
+}
diff --git a/src/Moli.Desktop/Api/LocalApiService.cs b/src/Moli.Desktop/Api/LocalApiService.cs
new file mode 100644
index 0000000..386bd40
--- /dev/null
+++ b/src/Moli.Desktop/Api/LocalApiService.cs
@@ -0,0 +1,295 @@
+using System.Collections.Concurrent;
+using System.IO;
+using System.Net;
+using System.Net.WebSockets;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Json;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Moli.Desktop.Configuration;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+
+namespace Moli.Desktop.Api;
+
+public sealed class LocalApiService : BackgroundService, ILocalApiStatus
+{
+    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
+    {
+        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+    };
+
+    private readonly IDesktopRuntime _runtime;
+    private readonly IConfigurationService _configuration;
+    private readonly IPluginManager _plugins;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly IRuntimeEventBus _events;
+    private readonly ConcurrentDictionary<WebSocket, byte> _sockets = new();
+    private readonly object _statusGate = new();
+    private IDisposable? _eventSubscription;
+    private WebApplication? _app;
+    private LocalApiStatusSnapshot _status = new();
+
+    public LocalApiService(
+        IDesktopRuntime runtime,
+        IConfigurationService configuration,
+        IPluginManager plugins,
+        IDiagnosticsService diagnostics,
+        IRuntimeEventBus events)
+    {
+        _runtime = runtime;
+        _configuration = configuration;
+        _plugins = plugins;
+        _diagnostics = diagnostics;
+        _events = events;
+    }
+
+    public LocalApiStatusSnapshot GetStatus()
+    {
+        lock (_statusGate)
+        {
+            return _status;
+        }
+    }
+
+    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+    {
+        var settings = await _configuration.LoadAppSettingsAsync(stoppingToken).ConfigureAwait(false);
+        SetStatus(new LocalApiStatusSnapshot { Port = settings.Runtime.ApiPort });
+        _eventSubscription = _events.Subscribe(BroadcastAsync);
+
+        try
+        {
+            var builder = WebApplication.CreateBuilder(new WebApplicationOptions
+            {
+                ApplicationName = typeof(LocalApiService).Assembly.GetName().Name,
+                Args = []
+            });
+            builder.WebHost.UseUrls($"http://127.0.0.1:{settings.Runtime.ApiPort}");
+            builder.Services.Configure<JsonOptions>(options =>
+            {
+                options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
+                options.SerializerOptions.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
+            });
+
+            _app = builder.Build();
+            _app.UseWebSockets();
+            MapEndpoints(_app);
+
+            SetStatus(new LocalApiStatusSnapshot
+            {
+                IsListening = true,
+                Port = settings.Runtime.ApiPort,
+                Message = $"Listening on http://127.0.0.1:{settings.Runtime.ApiPort}"
+            });
+            _diagnostics.Record(
+                DiagnosticSeverity.Info,
+                "LocalApiStarted",
+                "Local API started.",
+                new Dictionary<string, string> { ["url"] = $"http://127.0.0.1:{settings.Runtime.ApiPort}" });
+
+            await _app.RunAsync(stoppingToken).ConfigureAwait(false);
+        }
+        catch (Exception ex) when (ex is IOException or InvalidOperationException or HttpListenerException)
+        {
+            SetStatus(new LocalApiStatusSnapshot
+            {
+                Port = settings.Runtime.ApiPort,
+                ErrorCode = "LocalApiStartFailed",
+                Message = ex.Message
+            });
+            _diagnostics.Record(
+                DiagnosticSeverity.Error,
+                "LocalApiStartFailed",
+                "Local API failed to start; desktop runtime will continue.",
+                new Dictionary<string, string>
+                {
+                    ["host"] = "127.0.0.1",
+                    ["port"] = settings.Runtime.ApiPort.ToString(),
+                    ["exception"] = ex.GetType().Name,
+                    ["message"] = ex.Message
+                });
+        }
+    }
+
+    public override async Task StopAsync(CancellationToken cancellationToken)
+    {
+        _eventSubscription?.Dispose();
+        foreach (var socket in _sockets.Keys)
+        {
+            if (socket.State == WebSocketState.Open)
+            {
+                await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Application stopping.", cancellationToken).ConfigureAwait(false);
+            }
+
+            socket.Dispose();
+        }
+
+        _sockets.Clear();
+        if (_app is not null)
+        {
+            await _app.StopAsync(cancellationToken).ConfigureAwait(false);
+            await _app.DisposeAsync().ConfigureAwait(false);
+        }
+
+        SetStatus(GetStatus() with { IsListening = false, Message = "Stopped." });
+        await base.StopAsync(cancellationToken).ConfigureAwait(false);
+    }
+
+    private void MapEndpoints(WebApplication app)
+    {
+        app.MapGet("/api/status", async () =>
+        {
+            var state = await _runtime.GetStateAsync().ConfigureAwait(false);
+            return Results.Json(ApiStatusResponse.From(state, GetStatus()), JsonOptions);
+        });
+
+        app.MapGet("/api/plugins", async () =>
+        {
+            var state = await _runtime.GetStateAsync().ConfigureAwait(false);
+            return Results.Json(state.Plugins.Select(PluginResponse.From), JsonOptions);
+        });
+
+        app.MapPost("/api/plugins/{id}/reload", async (string id) =>
+        {
+            var reload = await _plugins.ReloadAsync(new PluginId(id)).ConfigureAwait(false);
+            if (!reload.Succeeded)
+            {
+                return Error(reload.ErrorCode ?? "PluginReloadFailed", reload.Message ?? "Plugin reload failed.", StatusCodes.Status404NotFound);
+            }
+
+            var state = await _runtime.ReloadPluginsAsync().ConfigureAwait(false);
+            return ToResult(state);
+        });
+
+        app.MapPost("/api/wallpaper/enable", async () => ToResult(await _runtime.EnableWallpaperAsync().ConfigureAwait(false)));
+        app.MapPost("/api/wallpaper/disable", async () => ToResult(await _runtime.DisableWallpaperAsync().ConfigureAwait(false)));
+        app.MapPost("/api/edit-mode", async (HttpContext context) =>
+        {
+            var enabled = await ReadModeAsync(context).ConfigureAwait(false)
+                ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsEditMode;
+            return ToResult(await _runtime.SetEditModeAsync(enabled).ConfigureAwait(false));
+        });
+        app.MapPost("/api/safe-input-mode", async (HttpContext context) =>
+        {
+            var enabled = await ReadModeAsync(context).ConfigureAwait(false)
+                ?? !(await _runtime.GetStateAsync().ConfigureAwait(false)).IsSafeInputMode;
+            return ToResult(await _runtime.SetSafeInputModeAsync(enabled).ConfigureAwait(false));
+        });
+        app.MapPost("/api/widgets/{instanceId}/layout", async (string instanceId, WidgetLayoutPatchRequest request) =>
+        {
+            var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), request.ToPatch()).ConfigureAwait(false);
+            if (!result.Succeeded)
+            {
+                return Error(result.ErrorCode ?? "WidgetLayoutUpdateFailed", result.Message ?? "Widget layout update failed.", StatusCodes.Status400BadRequest);
+            }
+
+            return Results.Json(WidgetResponse.From(result.Value!), JsonOptions);
+        });
+        app.MapGet("/ws/events", AcceptWebSocketAsync);
+    }
+
+    private async Task AcceptWebSocketAsync(HttpContext context)
+    {
+        if (!context.WebSockets.IsWebSocketRequest)
+        {
+            context.Response.StatusCode = StatusCodes.Status400BadRequest;
+            await context.Response.WriteAsJsonAsync(new ApiErrorResponse("WebSocketRequired", "Use a WebSocket request."), JsonOptions).ConfigureAwait(false);
+            return;
+        }
+
+        using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
+        _sockets.TryAdd(socket, 0);
+        await SendAsync(socket, new RuntimeEventResponse("api.connected", DateTimeOffset.UtcNow, GetStatus()), context.RequestAborted).ConfigureAwait(false);
+
+        var buffer = new byte[1024];
+        try
+        {
+            while (!context.RequestAborted.IsCancellationRequested && socket.State == WebSocketState.Open)
+            {
+                var message = await socket.ReceiveAsync(buffer, context.RequestAborted).ConfigureAwait(false);
+                if (message.MessageType == WebSocketMessageType.Close)
+                {
+                    break;
+                }
+            }
+        }
+        finally
+        {
+            _sockets.TryRemove(socket, out _);
+        }
+    }
+
+    private async Task BroadcastAsync(RuntimeEvent runtimeEvent)
+    {
+        var payload = RuntimeEventResponse.From(runtimeEvent);
+        foreach (var socket in _sockets.Keys)
+        {
+            if (socket.State != WebSocketState.Open)
+            {
+                _sockets.TryRemove(socket, out _);
+                continue;
+            }
+
+            try
+            {
+                await SendAsync(socket, payload, CancellationToken.None).ConfigureAwait(false);
+            }
+            catch (WebSocketException)
+            {
+                _sockets.TryRemove(socket, out _);
+            }
+        }
+    }
+
+    private static async Task<bool?> ReadModeAsync(HttpContext context)
+    {
+        if (context.Request.Query.TryGetValue("enabled", out var values)
+            && bool.TryParse(values.FirstOrDefault(), out var queryValue))
+        {
+            return queryValue;
+        }
+
+        if (context.Request.ContentLength is null or 0)
+        {
+            return null;
+        }
+
+        var request = await context.Request.ReadFromJsonAsync<ModeRequest>(JsonOptions).ConfigureAwait(false);
+        return request?.Enabled;
+    }
+
+    private IResult ToResult(OperationResult<AppRuntimeState> result)
+    {
+        if (!result.Succeeded)
+        {
+            return Error(result.ErrorCode ?? "RuntimeCommandFailed", result.Message ?? "Runtime command failed.", StatusCodes.Status400BadRequest);
+        }
+
+        return Results.Json(ApiStatusResponse.From(result.Value!, GetStatus()), JsonOptions);
+    }
+
+    private static IResult Error(string code, string message, int statusCode)
+        => Results.Json(new ApiErrorResponse(code, message), JsonOptions, statusCode: statusCode);
+
+    private static Task SendAsync(WebSocket socket, object payload, CancellationToken cancellationToken)
+    {
+        var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload, JsonOptions));
+        return socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancellationToken);
+    }
+
+    private void SetStatus(LocalApiStatusSnapshot status)
+    {
+        lock (_statusGate)
+        {
+            _status = status;
+        }
+    }
+}
diff --git a/src/Moli.Desktop/App.xaml.cs b/src/Moli.Desktop/App.xaml.cs
index 111d1a0..f2c1ef5 100644
--- a/src/Moli.Desktop/App.xaml.cs
+++ b/src/Moli.Desktop/App.xaml.cs
@@ -1,13 +1,16 @@
 using System.Windows;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
+using Moli.Desktop.Configuration;
 using Moli.Desktop.Host;
+using Moli.Desktop.Management;
 using Moli.Desktop.Runtime;
+using Moli.Desktop.Tray;
 
 namespace Moli.Desktop;
 
 /// <summary>Application entry point and composition root.</summary>
-public partial class App : Application
+public partial class App : System.Windows.Application
 {
     private IHost? _host;
 
@@ -18,15 +21,20 @@
         _host = DesktopHostBuilder.Create(e.Args).Build();
         await _host.StartAsync();
         await _host.Services.GetRequiredService<IDesktopRuntime>().StartAsync();
+        await _host.Services.GetRequiredService<ITrayShell>().StartAsync();
 
-        var mainWindow = _host.Services.GetRequiredService<MainWindow>();
-        mainWindow.Show();
+        var settings = await _host.Services.GetRequiredService<IConfigurationService>().LoadAppSettingsAsync();
+        if (!settings.Startup.StartMinimized)
+        {
+            _host.Services.GetRequiredService<ManagementWindow>().Show();
+        }
     }
 
     protected override async void OnExit(ExitEventArgs e)
     {
         if (_host is not null)
         {
+            await _host.Services.GetRequiredService<ITrayShell>().StopAsync();
             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 9f4ec05..40733f6 100644
--- a/src/Moli.Desktop/Host/DesktopHostBuilder.cs
+++ b/src/Moli.Desktop/Host/DesktopHostBuilder.cs
@@ -5,8 +5,11 @@
 using Moli.Desktop.Diagnostics;
 using Moli.Desktop.Interop;
 using Moli.Desktop.Layout;
+using Moli.Desktop.Api;
+using Moli.Desktop.Management;
 using Moli.Desktop.Plugins;
 using Moli.Desktop.Runtime;
+using Moli.Desktop.Tray;
 using Moli.Desktop.WebView;
 using Moli.Desktop.Windows;
 
@@ -40,7 +43,12 @@
                 services.AddSingleton<IWin32InteropService, Win32InteropService>();
                 services.AddSingleton<PluginBridgeDispatcher>();
                 services.AddSingleton<IWebViewHostFactory, WebViewHostFactory>();
-                services.AddSingleton<MainWindow>();
+                services.AddSingleton<LocalApiService>();
+                services.AddSingleton<ILocalApiStatus>(sp => sp.GetRequiredService<LocalApiService>());
+                services.AddHostedService(sp => sp.GetRequiredService<LocalApiService>());
+                services.AddSingleton<IStartupService, RegistryStartupService>();
+                services.AddSingleton<ITrayShell, TrayShell>();
+                services.AddTransient<ManagementWindow>();
             });
     }
 }
diff --git a/src/Moli.Desktop/Management/ManagementWindow.xaml b/src/Moli.Desktop/Management/ManagementWindow.xaml
new file mode 100644
index 0000000..2aae04e
--- /dev/null
+++ b/src/Moli.Desktop/Management/ManagementWindow.xaml
@@ -0,0 +1,78 @@
+<Window x:Class="Moli.Desktop.Management.ManagementWindow"
+        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
+        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
+        Title="Moli Desktop 绠$悊"
+        Height="620"
+        Width="920"
+        MinHeight="520"
+        MinWidth="760"
+        WindowStartupLocation="CenterScreen">
+    <DockPanel>
+        <Border DockPanel.Dock="Top" Background="#20242C" Padding="16,12">
+            <DockPanel>
+                <StackPanel>
+                    <TextBlock Text="Moli Desktop" Foreground="White" FontSize="20" FontWeight="SemiBold" />
+                    <TextBlock x:Name="StatusSummaryText" Foreground="#BFC7D5" Margin="0,4,0,0" />
+                </StackPanel>
+                <Button Content="鍒锋柊" DockPanel.Dock="Right" Width="88" Height="32" Click="RefreshButton_Click" />
+            </DockPanel>
+        </Border>
+
+        <Grid DockPanel.Dock="Bottom" Background="#F4F6F8" MinHeight="56">
+            <WrapPanel Margin="12" VerticalAlignment="Center">
+                <Button Content="鍚敤澹佺焊" Width="92" Margin="0,0,8,0" Click="EnableWallpaper_Click" />
+                <Button Content="绂佺敤澹佺焊" Width="92" Margin="0,0,8,0" Click="DisableWallpaper_Click" />
+                <Button x:Name="EditModeButton" Content="鍒囨崲缂栬緫" Width="92" Margin="0,0,8,0" Click="ToggleEditMode_Click" />
+                <Button x:Name="SafeInputButton" Content="瀹夊叏杈撳叆" Width="92" Margin="0,0,8,0" Click="ToggleSafeInput_Click" />
+                <Button x:Name="GlobalLockButton" Content="閿佸畾鍏ㄩ儴" Width="92" Margin="0,0,8,0" Click="ToggleGlobalLock_Click" />
+                <Button Content="閲嶈浇鎻掍欢" Width="92" Margin="0,0,8,0" Click="ReloadPlugins_Click" />
+                <Button Content="閲嶇疆甯冨眬" Width="92" Margin="0,0,8,0" Click="ResetLayout_Click" />
+            </WrapPanel>
+        </Grid>
+
+        <TabControl Margin="12">
+            <TabItem Header="鐘舵��">
+                <Grid Margin="8">
+                    <Grid.RowDefinitions>
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="Auto" />
+                        <RowDefinition Height="*" />
+                    </Grid.RowDefinitions>
+                    <UniformGrid Columns="2">
+                        <TextBlock x:Name="RuntimeText" Margin="0,0,12,8" />
+                        <TextBlock x:Name="ApiText" Margin="0,0,12,8" />
+                        <TextBlock x:Name="WallpaperText" Margin="0,0,12,8" />
+                        <TextBlock x:Name="WebViewText" Margin="0,0,12,8" />
+                    </UniformGrid>
+                    <TextBlock Grid.Row="1" Text="鏈�杩戣瘖鏂�" FontWeight="SemiBold" Margin="0,12,0,6" />
+                    <DataGrid Grid.Row="2" x:Name="RecentDiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" />
+                </Grid>
+            </TabItem>
+            <TabItem Header="澹佺焊">
+                <StackPanel Margin="8">
+                    <TextBlock x:Name="WallpaperDetailText" Margin="0,0,0,12" />
+                    <TextBlock Text="澹佺焊鎺у埗閫氳繃搴曢儴鍛戒护鏍忔墽琛屻��" Foreground="#526070" />
+                </StackPanel>
+            </TabItem>
+            <TabItem Header="缁勪欢">
+                <DockPanel Margin="8">
+                    <WrapPanel DockPanel.Dock="Top" Margin="0,0,0,8">
+                        <ComboBox x:Name="WidgetSelector" Width="260" DisplayMemberPath="InstanceId" Margin="0,0,8,0" />
+                        <Button Content="鏄剧ず/闅愯棌" Width="96" Margin="0,0,8,0" Click="ToggleWidgetVisible_Click" />
+                        <Button Content="閿佸畾/瑙i攣" Width="96" Margin="0,0,8,0" Click="ToggleWidgetLocked_Click" />
+                    </WrapPanel>
+                    <DataGrid x:Name="WidgetsGrid" AutoGenerateColumns="True" IsReadOnly="True" />
+                </DockPanel>
+            </TabItem>
+            <TabItem Header="鎻掍欢">
+                <DataGrid x:Name="PluginsGrid" Margin="8" AutoGenerateColumns="True" IsReadOnly="True" />
+            </TabItem>
+            <TabItem Header="璇婃柇">
+                <DockPanel Margin="8">
+                    <TextBlock x:Name="ManifestErrorsText" DockPanel.Dock="Top" TextWrapping="Wrap" Margin="0,0,0,8" />
+                    <DataGrid x:Name="DiagnosticsGrid" AutoGenerateColumns="True" IsReadOnly="True" />
+                </DockPanel>
+            </TabItem>
+        </TabControl>
+    </DockPanel>
+</Window>
diff --git a/src/Moli.Desktop/Management/ManagementWindow.xaml.cs b/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
new file mode 100644
index 0000000..f22bbac
--- /dev/null
+++ b/src/Moli.Desktop/Management/ManagementWindow.xaml.cs
@@ -0,0 +1,178 @@
+using System.Windows;
+using System.Windows.Threading;
+using Moli.Desktop.Api;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Layout;
+using Moli.Desktop.Plugins;
+using Moli.Desktop.Runtime;
+using MessageBox = System.Windows.MessageBox;
+
+namespace Moli.Desktop.Management;
+
+public partial class ManagementWindow : Window
+{
+    private readonly IDesktopRuntime _runtime;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly ILocalApiStatus _apiStatus;
+    private readonly DispatcherTimer _timer;
+    private AppRuntimeState? _state;
+
+    public ManagementWindow(
+        IDesktopRuntime runtime,
+        IDiagnosticsService diagnostics,
+        ILocalApiStatus apiStatus)
+    {
+        _runtime = runtime;
+        _diagnostics = diagnostics;
+        _apiStatus = apiStatus;
+        InitializeComponent();
+        _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
+        _timer.Tick += async (_, _) => await RefreshAsync();
+        Loaded += async (_, _) =>
+        {
+            _timer.Start();
+            await RefreshAsync();
+        };
+        Closed += (_, _) => _timer.Stop();
+    }
+
+    private async Task RefreshAsync()
+    {
+        _state = await _runtime.GetStateAsync();
+        var api = _apiStatus.GetStatus();
+        var diagnostics = _diagnostics.Snapshot().OrderByDescending(entry => entry.Timestamp).ToArray();
+        var webViewStatus = diagnostics.FirstOrDefault(entry => entry.Code == DiagnosticCodes.WebViewHostInitialized) is null
+            ? "鏈娴嬪埌鍒濆鍖栬褰�"
+            : "宸插垵濮嬪寲";
+
+        StatusSummaryText.Text = $"鎻掍欢 {_state.Plugins.Count} 涓紝缁勪欢 {_state.Widgets.Count} 涓紝璇婃柇 {diagnostics.Length} 鏉�";
+        RuntimeText.Text = $"杩愯鏃讹細缂栬緫={_state.IsEditMode}锛屽畨鍏ㄨ緭鍏�={_state.IsSafeInputMode}锛屽叏灞�閿佸畾={_state.IsGlobalLocked}";
+        ApiText.Text = api.IsListening ? $"API锛�127.0.0.1:{api.Port}" : $"API锛氭湭鐩戝惉 {api.ErrorCode ?? ""}";
+        WallpaperText.Text = $"澹佺焊锛氬惎鐢�={_state.Wallpaper.IsEnabled}锛屾彃浠�={_state.Wallpaper.PluginId?.Value ?? "鏃�"}";
+        WebViewText.Text = $"WebView2锛歿webViewStatus}";
+        WallpaperDetailText.Text = $"鍚敤锛歿_state.Wallpaper.IsEnabled}\n鏆傚仠锛歿_state.Wallpaper.IsPaused}\n闈欓煶锛歿_state.Wallpaper.IsMuted}\n閫忔槑搴︼細{_state.Wallpaper.Opacity}\n鐐瑰嚮绌块�忥細{_state.Wallpaper.ClickThrough}";
+        EditModeButton.Content = _state.IsEditMode ? "閫�鍑虹紪杈�" : "杩涘叆缂栬緫";
+        SafeInputButton.Content = _state.IsSafeInputMode ? "閫�鍑哄畨鍏�" : "瀹夊叏杈撳叆";
+        GlobalLockButton.Content = _state.IsGlobalLocked ? "瑙i攣鍏ㄩ儴" : "閿佸畾鍏ㄩ儴";
+
+        var widgets = _state.Widgets.Select(WidgetRow.From).ToArray();
+        var selected = (WidgetSelector.SelectedItem as WidgetRow)?.InstanceId;
+        WidgetSelector.ItemsSource = widgets;
+        WidgetSelector.SelectedItem = widgets.FirstOrDefault(widget => widget.InstanceId == selected) ?? widgets.FirstOrDefault();
+        WidgetsGrid.ItemsSource = widgets;
+        PluginsGrid.ItemsSource = _state.Plugins.Select(PluginRow.From).ToArray();
+        DiagnosticsGrid.ItemsSource = diagnostics.Select(DiagnosticRow.From).ToArray();
+        RecentDiagnosticsGrid.ItemsSource = diagnostics.Take(8).Select(DiagnosticRow.From).ToArray();
+        ManifestErrorsText.Text = BuildManifestErrorText(_state);
+    }
+
+    private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync();
+    private async void EnableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.EnableWallpaperAsync());
+    private async void DisableWallpaper_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.DisableWallpaperAsync());
+    private async void ToggleEditMode_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetEditModeAsync(!(_state?.IsEditMode ?? false)));
+    private async void ToggleSafeInput_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetSafeInputModeAsync(!(_state?.IsSafeInputMode ?? false)));
+    private async void ToggleGlobalLock_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.SetGlobalLockedAsync(!(_state?.IsGlobalLocked ?? false)));
+    private async void ReloadPlugins_Click(object sender, RoutedEventArgs e) => await ExecuteAsync(() => _runtime.ReloadPluginsAsync());
+
+    private async void ToggleWidgetVisible_Click(object sender, RoutedEventArgs e)
+    {
+        if (SelectedWidget() is not { } widget)
+        {
+            return;
+        }
+
+        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsVisible = !widget.IsVisible });
+    }
+
+    private async void ToggleWidgetLocked_Click(object sender, RoutedEventArgs e)
+    {
+        if (SelectedWidget() is not { } widget)
+        {
+            return;
+        }
+
+        await ExecuteWidgetAsync(widget.InstanceId, new WidgetLayoutPatch { IsLocked = !widget.IsLocked });
+    }
+
+    private async void ResetLayout_Click(object sender, RoutedEventArgs e)
+    {
+        if (_state is null)
+        {
+            return;
+        }
+
+        foreach (var widget in _state.Widgets)
+        {
+            await _runtime.UpdateWidgetLayoutAsync(
+                widget.InstanceId,
+                new WidgetLayoutPatch
+                {
+                    IsVisible = true,
+                    IsLocked = false,
+                    Opacity = 1,
+                    ClickThrough = true
+                });
+        }
+
+        await RefreshAsync();
+    }
+
+    private WidgetRow? SelectedWidget() => WidgetSelector.SelectedItem as WidgetRow;
+
+    private async Task ExecuteAsync(Func<Task<OperationResult<AppRuntimeState>>> command)
+    {
+        var result = await command();
+        if (!result.Succeeded)
+        {
+            MessageBox.Show(this, result.Message ?? "鍛戒护鎵ц澶辫触銆�", result.ErrorCode ?? "RuntimeCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
+        }
+
+        await RefreshAsync();
+    }
+
+    private async Task ExecuteWidgetAsync(string instanceId, WidgetLayoutPatch patch)
+    {
+        var result = await _runtime.UpdateWidgetLayoutAsync(new WidgetInstanceId(instanceId), patch);
+        if (!result.Succeeded)
+        {
+            MessageBox.Show(this, result.Message ?? "缁勪欢鍛戒护鎵ц澶辫触銆�", result.ErrorCode ?? "WidgetCommandFailed", MessageBoxButton.OK, MessageBoxImage.Warning);
+        }
+
+        await RefreshAsync();
+    }
+
+    private static string BuildManifestErrorText(AppRuntimeState state)
+    {
+        var errors = state.Plugins
+            .Where(plugin => !string.IsNullOrWhiteSpace(plugin.ErrorCode))
+            .Select(plugin => $"{plugin.Id.Value}: {plugin.ErrorCode}")
+            .ToArray();
+        return errors.Length == 0 ? "鏈彂鐜版彃浠� manifest 閿欒銆�" : string.Join(Environment.NewLine, errors);
+    }
+
+    private sealed record WidgetRow(string InstanceId, string PluginId, string Bounds, string MonitorId, bool IsVisible, bool IsLocked, double Opacity, bool ClickThrough)
+    {
+        public static WidgetRow From(WidgetRuntimeState state)
+            => new(
+                state.InstanceId.Value,
+                state.PluginId.Value,
+                $"{state.Bounds.X:0},{state.Bounds.Y:0} {state.Bounds.Width:0}x{state.Bounds.Height:0}",
+                state.MonitorId.Value,
+                state.IsVisible,
+                state.IsLocked,
+                state.Opacity,
+                state.ClickThrough);
+    }
+
+    private sealed record PluginRow(string Id, string Name, string Type, string State, string? ErrorCode, string Entry)
+    {
+        public static PluginRow From(PluginRuntimeState state)
+            => new(state.Id.Value, state.Name, state.Type.ToString(), state.State.ToString(), state.ErrorCode, state.Entry ?? "");
+    }
+
+    private sealed record DiagnosticRow(DateTimeOffset Timestamp, string Severity, string Code, string Message)
+    {
+        public static DiagnosticRow From(DiagnosticEntry entry)
+            => new(entry.Timestamp, entry.Severity.ToString(), entry.Code, entry.Message);
+    }
+}
diff --git a/src/Moli.Desktop/Moli.Desktop.csproj b/src/Moli.Desktop/Moli.Desktop.csproj
index ce0107d..44e155b 100644
--- a/src/Moli.Desktop/Moli.Desktop.csproj
+++ b/src/Moli.Desktop/Moli.Desktop.csproj
@@ -6,12 +6,11 @@
     <Nullable>enable</Nullable>
     <ImplicitUsings>enable</ImplicitUsings>
     <UseWPF>true</UseWPF>
+    <UseWindowsForms>true</UseWindowsForms>
   </PropertyGroup>
 
   <ItemGroup>
-    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.7" />
-    <PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.7" />
-    <PackageReference Include="Microsoft.Extensions.Logging" Version="10.0.7" />
+    <FrameworkReference Include="Microsoft.AspNetCore.App" />
     <PackageReference Include="Microsoft.Web.WebView2" Version="1.0.3912.50" />
   </ItemGroup>
 
diff --git a/src/Moli.Desktop/Tray/IStartupService.cs b/src/Moli.Desktop/Tray/IStartupService.cs
new file mode 100644
index 0000000..c66acee
--- /dev/null
+++ b/src/Moli.Desktop/Tray/IStartupService.cs
@@ -0,0 +1,7 @@
+namespace Moli.Desktop.Tray;
+
+public interface IStartupService
+{
+    bool IsEnabled();
+    Task SetEnabledAsync(bool enabled, CancellationToken cancellationToken = default);
+}
diff --git a/src/Moli.Desktop/Tray/ITrayShell.cs b/src/Moli.Desktop/Tray/ITrayShell.cs
new file mode 100644
index 0000000..4e181aa
--- /dev/null
+++ b/src/Moli.Desktop/Tray/ITrayShell.cs
@@ -0,0 +1,7 @@
+namespace Moli.Desktop.Tray;
+
+public interface ITrayShell
+{
+    Task StartAsync(CancellationToken cancellationToken = default);
+    Task StopAsync(CancellationToken cancellationToken = default);
+}
diff --git a/src/Moli.Desktop/Tray/RegistryStartupService.cs b/src/Moli.Desktop/Tray/RegistryStartupService.cs
new file mode 100644
index 0000000..c7f6b8c
--- /dev/null
+++ b/src/Moli.Desktop/Tray/RegistryStartupService.cs
@@ -0,0 +1,41 @@
+using Microsoft.Win32;
+using Moli.Desktop.Configuration;
+
+namespace Moli.Desktop.Tray;
+
+public sealed class RegistryStartupService : IStartupService
+{
+    private const string RunKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
+    private const string ValueName = "Moli.Desktop";
+    private readonly IConfigurationService _configuration;
+
+    public RegistryStartupService(IConfigurationService configuration)
+    {
+        _configuration = configuration;
+    }
+
+    public bool IsEnabled()
+    {
+        using var key = Registry.CurrentUser.OpenSubKey(RunKeyPath, writable: false);
+        return key?.GetValue(ValueName) is string value && !string.IsNullOrWhiteSpace(value);
+    }
+
+    public async Task SetEnabledAsync(bool enabled, CancellationToken cancellationToken = default)
+    {
+        using var key = Registry.CurrentUser.CreateSubKey(RunKeyPath, writable: true);
+        if (enabled)
+        {
+            var executable = Environment.ProcessPath ?? AppContext.BaseDirectory;
+            key.SetValue(ValueName, $"\"{executable}\"", RegistryValueKind.String);
+        }
+        else
+        {
+            key.DeleteValue(ValueName, throwOnMissingValue: false);
+        }
+
+        var settings = await _configuration.LoadAppSettingsAsync(cancellationToken).ConfigureAwait(false);
+        await _configuration.SaveAppSettingsAsync(
+            settings with { Startup = settings.Startup with { StartWithWindows = enabled } },
+            cancellationToken).ConfigureAwait(false);
+    }
+}
diff --git a/src/Moli.Desktop/Tray/TrayShell.cs b/src/Moli.Desktop/Tray/TrayShell.cs
new file mode 100644
index 0000000..8590d6f
--- /dev/null
+++ b/src/Moli.Desktop/Tray/TrayShell.cs
@@ -0,0 +1,160 @@
+using System.Diagnostics;
+using System.IO;
+using System.Windows;
+using Microsoft.Extensions.DependencyInjection;
+using Moli.Desktop.Api;
+using Moli.Desktop.Diagnostics;
+using Moli.Desktop.Host;
+using Moli.Desktop.Management;
+using Moli.Desktop.Runtime;
+using Forms = System.Windows.Forms;
+using Drawing = System.Drawing;
+using Application = System.Windows.Application;
+
+namespace Moli.Desktop.Tray;
+
+public sealed class TrayShell : ITrayShell, IDisposable
+{
+    private readonly IServiceProvider _services;
+    private readonly IDesktopRuntime _runtime;
+    private readonly IDiagnosticsService _diagnostics;
+    private readonly ILocalApiStatus _apiStatus;
+    private readonly IStartupService _startup;
+    private readonly DesktopPaths _paths;
+    private Forms.NotifyIcon? _notifyIcon;
+    private ManagementWindow? _managementWindow;
+
+    public TrayShell(
+        IServiceProvider services,
+        IDesktopRuntime runtime,
+        IDiagnosticsService diagnostics,
+        ILocalApiStatus apiStatus,
+        IStartupService startup,
+        DesktopPaths paths)
+    {
+        _services = services;
+        _runtime = runtime;
+        _diagnostics = diagnostics;
+        _apiStatus = apiStatus;
+        _startup = startup;
+        _paths = paths;
+    }
+
+    public Task StartAsync(CancellationToken cancellationToken = default)
+    {
+        _notifyIcon = new Forms.NotifyIcon
+        {
+            Icon = Drawing.SystemIcons.Application,
+            Text = "Moli Desktop",
+            Visible = true,
+            ContextMenuStrip = BuildMenu()
+        };
+        _notifyIcon.DoubleClick += (_, _) => OpenManagementWindow();
+        _diagnostics.Record(DiagnosticSeverity.Info, "TrayShellStarted", "Tray shell started.");
+        return Task.CompletedTask;
+    }
+
+    public Task StopAsync(CancellationToken cancellationToken = default)
+    {
+        Dispose();
+        return Task.CompletedTask;
+    }
+
+    public void Dispose()
+    {
+        if (_notifyIcon is not null)
+        {
+            _notifyIcon.Visible = false;
+            _notifyIcon.Dispose();
+            _notifyIcon = null;
+        }
+    }
+
+    private Forms.ContextMenuStrip BuildMenu()
+    {
+        var menu = new Forms.ContextMenuStrip();
+        menu.Opening += async (_, _) => await RefreshMenuAsync(menu).ConfigureAwait(true);
+
+        menu.Items.Add(Command("鎵撳紑绠$悊绐楀彛", (_, _) => OpenManagementWindow()));
+        menu.Items.Add(new Forms.ToolStripSeparator());
+        menu.Items.Add(Command("鍚敤澹佺焊", async (_, _) => await _runtime.EnableWallpaperAsync().ConfigureAwait(true), "wallpaper.enable"));
+        menu.Items.Add(Command("绂佺敤澹佺焊", async (_, _) => await _runtime.DisableWallpaperAsync().ConfigureAwait(true), "wallpaper.disable"));
+        menu.Items.Add(CheckCommand("杩涘叆缂栬緫妯″紡", async item => await _runtime.SetEditModeAsync(item.Checked).ConfigureAwait(true), "edit"));
+        menu.Items.Add(CheckCommand("閿佸畾鍏ㄩ儴", async item => await _runtime.SetGlobalLockedAsync(item.Checked).ConfigureAwait(true), "lock"));
+        menu.Items.Add(CheckCommand("瀹夊叏杈撳叆妯″紡", async item => await _runtime.SetSafeInputModeAsync(item.Checked).ConfigureAwait(true), "safe"));
+        menu.Items.Add(new Forms.ToolStripSeparator());
+        menu.Items.Add(Command("閲嶈浇鎻掍欢", async (_, _) => await _runtime.ReloadPluginsAsync().ConfigureAwait(true)));
+        menu.Items.Add(Command("鎵撳紑鏃ュ織鐩綍", (_, _) => OpenDirectory(_paths.LogDirectory)));
+        menu.Items.Add(CheckCommand("璁剧疆寮�鏈哄惎鍔�", async item => await _startup.SetEnabledAsync(item.Checked).ConfigureAwait(true), "startup"));
+        menu.Items.Add(new Forms.ToolStripSeparator());
+        menu.Items.Add(Command("閫�鍑哄簲鐢�", async (_, _) => await ShutdownApplicationAsync().ConfigureAwait(true)));
+        return menu;
+    }
+
+    private async Task RefreshMenuAsync(Forms.ContextMenuStrip menu)
+    {
+        var state = await _runtime.GetStateAsync().ConfigureAwait(true);
+        SetChecked(menu, "edit", state.IsEditMode);
+        SetChecked(menu, "lock", state.IsGlobalLocked);
+        SetChecked(menu, "safe", state.IsSafeInputMode);
+        SetChecked(menu, "startup", _startup.IsEnabled());
+
+        var worst = state.Diagnostics.OrderByDescending(entry => entry.Severity).FirstOrDefault();
+        var api = _apiStatus.GetStatus();
+        var statusText = api.IsListening ? $"API 127.0.0.1:{api.Port}" : $"API 鏈洃鍚�: {api.ErrorCode ?? "Stopped"}";
+        _notifyIcon!.Text = TrimForTray(worst is null ? $"Moli Desktop - {statusText}" : $"Moli Desktop - {worst.Code}");
+    }
+
+    private void OpenManagementWindow()
+    {
+        Application.Current.Dispatcher.Invoke(() =>
+        {
+            if (_managementWindow is { IsVisible: true })
+            {
+                _managementWindow.Activate();
+                return;
+            }
+
+            _managementWindow = _services.GetRequiredService<ManagementWindow>();
+            _managementWindow.Closed += (_, _) => _managementWindow = null;
+            _managementWindow.Show();
+            _managementWindow.Activate();
+        });
+    }
+
+    private async Task ShutdownApplicationAsync()
+    {
+        await _runtime.ShutdownAsync().ConfigureAwait(true);
+        Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
+    }
+
+    private static Forms.ToolStripMenuItem Command(string text, EventHandler onClick, string? name = null)
+    {
+        var item = new Forms.ToolStripMenuItem(text) { Name = name ?? text };
+        item.Click += onClick;
+        return item;
+    }
+
+    private static Forms.ToolStripMenuItem CheckCommand(string text, Func<Forms.ToolStripMenuItem, Task> onClick, string name)
+    {
+        var item = new Forms.ToolStripMenuItem(text) { Name = name, CheckOnClick = true };
+        item.Click += async (_, _) => await onClick(item).ConfigureAwait(true);
+        return item;
+    }
+
+    private static void SetChecked(Forms.ContextMenuStrip menu, string name, bool value)
+    {
+        if (menu.Items[name] is Forms.ToolStripMenuItem item)
+        {
+            item.Checked = value;
+        }
+    }
+
+    private static void OpenDirectory(string path)
+    {
+        Directory.CreateDirectory(path);
+        Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
+    }
+
+    private static string TrimForTray(string text) => text.Length <= 63 ? text : text[..63];
+}
diff --git a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
index 44186f1..ca24bb8 100644
--- a/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
+++ b/src/Moli.Desktop/Windows/RuntimeSurfaceController.cs
@@ -8,6 +8,7 @@
 using Moli.Desktop.Plugins;
 using Moli.Desktop.Runtime;
 using Moli.Desktop.WebView;
+using Application = System.Windows.Application;
 
 namespace Moli.Desktop.Windows;
 
diff --git a/src/Moli.Desktop/Windows/WallpaperWindow.cs b/src/Moli.Desktop/Windows/WallpaperWindow.cs
index 5ffeba5..9cc0132 100644
--- a/src/Moli.Desktop/Windows/WallpaperWindow.cs
+++ b/src/Moli.Desktop/Windows/WallpaperWindow.cs
@@ -9,6 +9,7 @@
 using Moli.Desktop.Plugins;
 using Moli.Desktop.Runtime;
 using Moli.Desktop.WebView;
+using Brushes = System.Windows.Media.Brushes;
 
 namespace Moli.Desktop.Windows;
 
diff --git a/src/Moli.Desktop/Windows/WidgetWindow.cs b/src/Moli.Desktop/Windows/WidgetWindow.cs
index 64b1cb8..8fe0a6e 100644
--- a/src/Moli.Desktop/Windows/WidgetWindow.cs
+++ b/src/Moli.Desktop/Windows/WidgetWindow.cs
@@ -12,6 +12,11 @@
 using Moli.Desktop.Plugins;
 using Moli.Desktop.Runtime;
 using Moli.Desktop.WebView;
+using Brushes = System.Windows.Media.Brushes;
+using Cursors = System.Windows.Input.Cursors;
+using HorizontalAlignment = System.Windows.HorizontalAlignment;
+using MouseEventArgs = System.Windows.Input.MouseEventArgs;
+using Point = System.Windows.Point;
 
 namespace Moli.Desktop.Windows;
 

--
Gitblit v1.9.1