本文档基于 docs/product/desktop-enhancement-prd.md 和 docs/architecture/runtime-architecture.md,面向 Dev Agent 的一期 MVP 实现。详细设计以 C#、WPF、WebView2、Win32 互操作和本地 JSON 配置为主线,目标是把模块、接口、状态机和异常恢复规则定义到可编码粒度。
MVP 必须实现:
appsettings.json、plugins.json、layout.json 持久化。MVP 不实现:
建议解决方案结构:
src/
Moli.Desktop/
App.xaml
App.xaml.cs
Moli.Desktop.csproj
Api/
Configuration/
Diagnostics/
Host/
Interop/
Layout/
Plugins/
Runtime/
Tray/
WebView/
Windows/
Moli.Desktop.Tests/
Configuration/
Layout/
Plugins/
命名空间约定:
| 目录 | 命名空间 | 内容 |
|---|---|---|
Host |
Moli.Desktop.Host |
启动、依赖装配、应用生命周期 |
Runtime |
Moli.Desktop.Runtime |
运行时编排、命令入口、状态聚合 |
Windows |
Moli.Desktop.Windows |
WPF 窗口、编辑浮层、管理窗口 |
WebView |
Moli.Desktop.WebView |
WebView2 初始化、导航、脚本桥 |
Plugins |
Moli.Desktop.Plugins |
manifest、插件注册表、生命周期 |
Layout |
Moli.Desktop.Layout |
显示器、组件布局、拖拽缩放 |
Configuration |
Moli.Desktop.Configuration |
JSON schema、读写、迁移、恢复 |
Interop |
Moli.Desktop.Interop |
Win32 P/Invoke、窗口样式、WorkerW |
Api |
Moli.Desktop.Api |
HTTP API、WebSocket、DTO |
Diagnostics |
Moli.Desktop.Diagnostics |
日志、错误码、诊断快照 |
Tray |
Moli.Desktop.Tray |
托盘图标和菜单命令 |
App.xaml.cs 只做最薄启动,复杂逻辑交给 AppHost。
public sealed class AppHost
{
public Task StartAsync(CancellationToken cancellationToken);
public Task StopAsync(CancellationToken cancellationToken);
}
启动顺序:
Global\Moli.Desktop.SingleInstance。DiagnosticsService 和日志目录。关闭顺序:
onBeforeUnload。MVP 可使用 Microsoft.Extensions.DependencyInjection,并通过接口注册服务。
services.AddSingleton<IConfigurationService, JsonConfigurationService>();
services.AddSingleton<IDiagnosticsService, DiagnosticsService>();
services.AddSingleton<IPluginManager, PluginManager>();
services.AddSingleton<ILayoutManager, LayoutManager>();
services.AddSingleton<IWindowManager, WindowManager>();
services.AddSingleton<IWin32InteropService, Win32InteropService>();
services.AddSingleton<IDesktopRuntime, DesktopRuntimeCoordinator>();
services.AddSingleton<ILocalApiService, LocalApiService>();
services.AddSingleton<ITrayShell, TrayShell>();
public readonly record struct PluginId(string Value);
public readonly record struct WidgetInstanceId(string Value);
public readonly record struct MonitorId(string Value);
public sealed record RectD(double X, double Y, double Width, double Height);
public sealed record SizeD(double Width, double Height);
public sealed record PointD(double X, double Y);
public enum PluginType
{
Wallpaper,
Widget,
Utility
}
public enum PluginState
{
Installed,
Enabled,
Loaded,
Running,
Paused,
Disabled,
Error,
Removed
}
public enum DiagnosticSeverity
{
Info,
Warning,
Error,
Critical
}
public sealed record AppRuntimeState
{
public bool IsEditMode { get; init; }
public bool GlobalLocked { get; init; }
public bool SafeInputMode { get; init; }
public WallpaperRuntimeState Wallpaper { get; init; } = new();
public IReadOnlyList<WidgetRuntimeState> Widgets { get; init; } = [];
public IReadOnlyList<PluginRuntimeState> Plugins { get; init; } = [];
public IReadOnlyList<DiagnosticEntry> Diagnostics { get; init; } = [];
}
public interface IConfigurationService
{
Task<AppSettingsDocument> LoadAppSettingsAsync(CancellationToken cancellationToken);
Task<PluginRegistryDocument> LoadPluginRegistryAsync(CancellationToken cancellationToken);
Task<LayoutDocument> LoadLayoutAsync(CancellationToken cancellationToken);
Task SaveAppSettingsAsync(AppSettingsDocument document, CancellationToken cancellationToken);
Task SavePluginRegistryAsync(PluginRegistryDocument document, CancellationToken cancellationToken);
Task SaveLayoutAsync(LayoutDocument document, CancellationToken cancellationToken);
Task<ConfigurationSnapshot> LoadAllAsync(CancellationToken cancellationToken);
Task SaveAllAsync(ConfigurationSnapshot snapshot, CancellationToken cancellationToken);
}
public sealed record AppSettingsDocument
{
public int SchemaVersion { get; init; } = 1;
public StartupSettings Startup { get; init; } = new();
public RuntimeSettings Runtime { get; init; } = new();
public WallpaperSettings Wallpaper { get; init; } = new();
public ApiSettings Api { get; init; } = new();
}
public sealed record PluginRegistryDocument
{
public int SchemaVersion { get; init; } = 1;
public List<PluginRegistryItem> Plugins { get; init; } = [];
}
public sealed record LayoutDocument
{
public int SchemaVersion { get; init; } = 1;
public List<MonitorSnapshot> Monitors { get; init; } = [];
public List<WidgetLayout> Instances { get; init; } = [];
}
读流程:
System.Text.Json 读取,启用大小写不敏感。schemaVersion。写流程:
<name>.tmp。<name>.bak。.tmp 和 .bak,写诊断日志。文件名规范:
appsettings.json
appsettings.json.bak
appsettings.json.invalid.20260502-153000.json
appsettings.json.tmp
| 文档 | 规则 |
|---|---|
| appsettings | api.bindAddress 默认必须是 127.0.0.1;端口范围 1024..65535 |
| appsettings | wallpaper.monitorId 为空时使用 primary |
| plugins | id 唯一;path 不为空;state 不允许直接持久化为 Running |
| layout | instanceId 唯一;尺寸大于 0;opacity 在 0..1 |
| layout | 缺失显示器时布局回收到主显示器 |
public sealed record PluginManifest
{
public required string Id { get; init; }
public required string Name { get; init; }
public required string Version { get; init; }
public required PluginType Type { get; init; }
public required string Entry { get; init; }
public string Description { get; init; } = "";
public string Author { get; init; } = "Unknown";
public List<string> Permissions { get; init; } = [];
public PluginDefaultLayout DefaultLayout { get; init; } = new();
public JsonElement Config { get; init; }
}
public interface IPluginManager
{
Task<IReadOnlyList<PluginDescriptor>> ScanAsync(CancellationToken cancellationToken);
Task<PluginDescriptor?> GetAsync(PluginId pluginId, CancellationToken cancellationToken);
Task<PluginOperationResult> EnableAsync(PluginId pluginId, CancellationToken cancellationToken);
Task<PluginOperationResult> DisableAsync(PluginId pluginId, CancellationToken cancellationToken);
Task<PluginOperationResult> ReloadAsync(PluginId pluginId, CancellationToken cancellationToken);
Task<PluginOperationResult> RemoveAsync(PluginId pluginId, CancellationToken cancellationToken);
}
public interface IPluginManifestValidator
{
PluginManifestValidationResult Validate(string pluginDirectory, PluginManifest manifest);
}
校验细节:
id 使用正则:^[a-zA-Z0-9][a-zA-Z0-9._-]{2,63}$。name 长度 1..80。version 必须能解析为 SemVer 形态。entry 解析为完整路径后必须位于插件目录内。entry 支持本地相对文件,也支持 http:// 或 https:// 远程 URL。defaultLayout.width 最小 80,最大 3840。defaultLayout.height 最小 40,最大 2160。状态转换由 PluginStateMachine 集中控制,禁止业务代码直接改状态。
| From | Event | To |
|---|---|---|
Installed |
enable | Enabled |
Enabled |
load success | Loaded |
Loaded |
start success | Running |
Running |
pause | Paused |
Paused |
resume | Running |
Running |
disable | Disabled |
Paused |
disable | Disabled |
Loaded |
load failed | Error |
Running |
runtime failed | Error |
Error |
disable | Disabled |
Disabled |
enable | Enabled |
Disabled |
remove | Removed |
Error |
remove | Removed |
非法转换返回 PluginOperationResult,不抛出未处理异常。
public interface IWebViewHost
{
string HostId { get; }
PluginId PluginId { get; }
PluginType PluginType { get; }
Task InitializeAsync(WebViewHostOptions options, CancellationToken cancellationToken);
Task NavigateAsync(Uri entryUri, CancellationToken cancellationToken);
Task InjectBridgeAsync(PluginBridgeContext context, CancellationToken cancellationToken);
Task DispatchLifecycleEventAsync(string eventName, object? payload, CancellationToken cancellationToken);
Task ReloadAsync(CancellationToken cancellationToken);
Task DisposeAsync();
}
public sealed record WebViewHostOptions
{
public required string UserDataFolder { get; init; }
public bool IsTransparent { get; init; }
public bool AreDevToolsEnabled { get; init; }
public bool IsMuted { get; init; }
public string? InitialScript { get; init; }
}
桥接脚本在导航前通过 AddScriptToExecuteOnDocumentCreatedAsync 注入。
插件侧 API:
window.moliDesktop = {
getManifest: () => chrome.webview.postMessage({ id, method: "getManifest" }),
getRuntimeInfo: () => chrome.webview.postMessage({ id, method: "getRuntimeInfo" }),
getConfig: () => chrome.webview.postMessage({ id, method: "getConfig" }),
setConfig: (patch) => chrome.webview.postMessage({ id, method: "setConfig", params: patch }),
notify: (message) => chrome.webview.postMessage({ id, method: "notify", params: message }),
requestReload: () => chrome.webview.postMessage({ id, method: "requestReload" }),
requestShow: () => chrome.webview.postMessage({ id, method: "requestShow" }),
requestHide: () => chrome.webview.postMessage({ id, method: "requestHide" }),
requestResize: (size) => chrome.webview.postMessage({ id, method: "requestResize", params: size })
};
C# 侧必须校验:
id 是否存在,便于响应 Promise。method 是否在白名单。setConfig patch 是否是对象且大小不超过限制。requestResize 是否符合布局约束。失败处理:
WebViewNavigationFailed。Error。diagnostic.error 和 plugin.stateChanged。public interface IWindowManager
{
Task CreateWallpaperAsync(WallpaperRuntimeSpec spec, CancellationToken cancellationToken);
Task DestroyWallpaperAsync(CancellationToken cancellationToken);
Task CreateWidgetAsync(WidgetRuntimeSpec spec, CancellationToken cancellationToken);
Task DestroyWidgetAsync(WidgetInstanceId instanceId, CancellationToken cancellationToken);
Task ApplyLayoutAsync(WidgetInstanceId instanceId, WidgetLayout layout, CancellationToken cancellationToken);
Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken);
Task SetSafeInputModeAsync(bool enabled, CancellationToken cancellationToken);
}
| 窗口 | 类型 | 说明 |
|---|---|---|
WallpaperWindow |
WPF Window | 无边框、无任务栏、覆盖目标显示器、承载壁纸 WebView2 |
WidgetWindow |
WPF Window | 无边框、透明背景、承载组件 WebView2 |
WidgetEditAdorner |
WPF Adorner 或自定义 overlay | 编辑模式边框、控制点、锁定状态 |
ManagementWindow |
WPF Window | 普通工具窗口,不参与桌面层 |
public interface IWin32InteropService
{
IntPtr GetWindowHandle(Window window);
void SetClickThrough(IntPtr hwnd, bool enabled);
void SetToolWindow(IntPtr hwnd, bool enabled);
void SetNoActivate(IntPtr hwnd, bool enabled);
void SetLayered(IntPtr hwnd, bool enabled, byte opacity);
void MoveToDesktopLayer(IntPtr hwnd, DesktopLayerMode mode);
void SetBottomMost(IntPtr hwnd);
IReadOnlyList<MonitorInfo> GetMonitors();
}
public interface IDesktopLayerStrategy
{
string Name { get; }
bool IsSupported();
bool TryAttachWallpaperWindow(IntPtr hwnd, MonitorInfo monitor, out string? error);
}
策略顺序:
WorkerWDesktopLayerStrategy:尝试将壁纸窗口挂到 Explorer WorkerW。BottomDesktopLayerStrategy:降级为覆盖目标显示器的底层窗口,并开启点击穿透。选择策略后写入诊断:
DesktopLayerStrategySelected: WorkerW
DesktopLayerStrategyFallback: BottomDesktopLayer, reason=WorkerWNotFound
| 场景 | 点击穿透 |
|---|---|
| 壁纸默认运行 | 按壁纸配置,默认 true |
| 壁纸编辑或调试 | false |
| 组件非编辑模式 | 按组件配置 |
| 组件编辑模式 | false |
| 全局安全输入模式 | 全部 false |
| 全局锁定 | 不改变点击穿透,只阻止拖拽缩放 |
实现使用扩展样式:
WS_EX_TRANSPARENTWS_EX_LAYEREDWS_EX_TOOLWINDOWWS_EX_NOACTIVATEpublic interface ILayoutManager
{
IReadOnlyList<WidgetLayout> GetAll();
WidgetLayout? Get(WidgetInstanceId instanceId);
WidgetLayout CreateFromPlugin(PluginDescriptor plugin, MonitorId monitorId);
LayoutUpdateResult Move(WidgetInstanceId instanceId, PointD position);
LayoutUpdateResult Resize(WidgetInstanceId instanceId, SizeD size);
LayoutUpdateResult Update(WidgetInstanceId instanceId, WidgetLayoutPatch patch);
IReadOnlyList<WidgetLayout> ReconcileMonitors(IReadOnlyList<MonitorInfo> monitors);
}
默认约束:
| 字段 | 最小 | 最大 |
|---|---|---|
width |
80 |
当前显示器宽度 |
height |
40 |
当前显示器高度 |
scale |
0.5 |
3.0 |
opacity |
0.1 |
1.0 |
位置约束:
48x48 DIP 在可见工作区内。sequenceDiagram
participant User
participant WidgetWindow
participant LayoutManager
participant WindowManager
participant Config
User->>WidgetWindow: MouseDown
WidgetWindow->>WidgetWindow: Capture mouse
User->>WidgetWindow: MouseMove
WidgetWindow->>LayoutManager: Move or Resize preview
LayoutManager-->>WidgetWindow: constrained layout
WidgetWindow->>WindowManager: ApplyLayout preview
User->>WidgetWindow: MouseUp
WidgetWindow->>LayoutManager: Commit
LayoutManager->>Config: Save layout.json
保存策略:
public interface IDesktopRuntime
{
AppRuntimeState GetState();
Task StartAsync(CancellationToken cancellationToken);
Task StopAsync(CancellationToken cancellationToken);
Task SetEditModeAsync(bool enabled, CancellationToken cancellationToken);
Task SetGlobalLockedAsync(bool locked, CancellationToken cancellationToken);
Task SetSafeInputModeAsync(bool enabled, CancellationToken cancellationToken);
Task ReloadPluginsAsync(CancellationToken cancellationToken);
Task EnableWallpaperAsync(CancellationToken cancellationToken);
Task DisableWallpaperAsync(CancellationToken cancellationToken);
Task UpdateWidgetLayoutAsync(WidgetInstanceId instanceId, WidgetLayoutPatch patch, CancellationToken cancellationToken);
}
| 命令 | 行为 |
|---|---|
SetEditMode(true) |
所有组件关闭点击穿透,显示编辑控制 |
SetEditMode(false) |
保存布局,恢复组件点击穿透 |
SetSafeInputMode(true) |
所有桌面窗口关闭点击穿透 |
SetGlobalLocked(true) |
所有组件拒绝拖拽缩放 |
ReloadPlugins |
重新扫描插件目录,保留同 id 组件布局 |
DisableWallpaper |
关闭壁纸窗口,保留壁纸配置 |
UpdateWidgetLayout |
校验、应用窗口、保存布局、广播事件 |
所有命令都通过 DesktopRuntimeCoordinator 进入,托盘、管理窗口、HTTP API 不直接调用底层服务。
MVP 使用 ASP.NET Core Minimal API 内嵌于桌面进程。
默认监听:
http://127.0.0.1:8765
ws://127.0.0.1:8765/ws/events
如果端口被占用:
ApiPortInUse。| 方法 | 路径 | 请求 | 响应 |
|---|---|---|---|
GET |
/api/status |
无 | AppRuntimeStateDto |
GET |
/api/plugins |
无 | PluginDto[] |
POST |
/api/plugins/{id}/reload |
无 | OperationResultDto |
POST |
/api/wallpaper/enable |
无 | OperationResultDto |
POST |
/api/wallpaper/disable |
无 | OperationResultDto |
POST |
/api/edit-mode |
{ "enabled": true } |
OperationResultDto |
POST |
/api/safe-input-mode |
{ "enabled": true } |
OperationResultDto |
POST |
/api/widgets/{instanceId}/layout |
WidgetLayoutPatchDto |
WidgetLayoutDto |
code、message、details。{
"success": false,
"code": "PluginNotFound",
"message": "Plugin sample.clock was not found.",
"details": {}
}
{
"type": "widget.layoutChanged",
"timestamp": "2026-05-02T15:30:00+08:00",
"payload": {
"instanceId": "widget-01",
"x": 120,
"y": 140,
"width": 320,
"height": 160
}
}
事件广播由 IRuntimeEventBus 统一管理:
public interface IRuntimeEventBus
{
void Publish(RuntimeEvent runtimeEvent);
IDisposable Subscribe(Action<RuntimeEvent> handler);
}
托盘菜单结构:
Moli.Desktop
打开管理窗口
壁纸
启用 / 禁用
暂停 / 恢复
静音 / 取消静音
编辑模式
进入 / 退出
锁定全部 / 解锁全部
安全输入模式
插件
重载插件
诊断
打开日志目录
导出诊断
开机启动
退出
状态图标:
| 状态 | 图标语义 |
|---|---|
| 正常 | 默认图标 |
| 暂停 | 暂停标识 |
| 警告 | 黄色角标或提示文本 |
| 错误 | 红色角标或提示文本 |
| Tab | 内容 |
|---|---|
| 状态 | 当前运行状态、WebView2 Runtime、API 监听、显示器信息 |
| 壁纸 | 当前壁纸插件、启停、重载、静音、点击穿透、显示器选择 |
| 组件 | 组件列表、显示隐藏、锁定、透明度、点击穿透、重载 |
| 插件 | 插件扫描结果、manifest 错误、启用禁用 |
| 诊断 | 日志摘要、错误列表、打开日志目录、重置布局 |
管理窗口不得作为桌面覆盖层,必须是普通 WPF 工具窗口。
| Code | Severity | 场景 |
|---|---|---|
WebView2RuntimeMissing |
Critical | 缺失 WebView2 Runtime |
ConfigReadFailed |
Error | JSON 读取失败 |
ConfigRecovered |
Warning | 配置已从损坏文件恢复 |
PluginManifestInvalid |
Error | manifest 缺字段或格式错误 |
PluginEntryMissing |
Error | 入口文件不存在 |
WebViewNavigationFailed |
Error | WebView2 导航失败 |
DesktopLayerAttachFailed |
Warning | WorkerW 挂载失败并降级 |
ApiPortInUse |
Warning | 本地 API 端口占用 |
LayoutReconciled |
Info | 显示器变化后布局回收 |
public sealed record DiagnosticEntry
{
public required string Code { get; init; }
public required DiagnosticSeverity Severity { get; init; }
public required string Message { get; init; }
public DateTimeOffset Timestamp { get; init; }
public Dictionary<string, string> Data { get; init; } = [];
}
pluginId 和入口来源。instanceId 和显示器信息。MVP 是无沙箱插件模型,但实现必须保留基本防线:
127.0.0.1。setConfig 限制 payload 大小,建议 MVP 最大 64 KB。为 QA 和后续自动化预留:
IDesktopLayerStrategy 可替换为 fake,避免测试时操作真实桌面。IWin32InteropService 可 mock。IFileSystem 或封装文件操作,方便配置损坏恢复测试。ILocalApiService 支持随机端口或测试端口。IClock 统一时间戳,便于断言备份文件名和事件。推荐实现顺序:
输出:
src/Moli.Desktop/Moli.Desktop.csprojsrc/Moli.Desktop.Tests/Moli.Desktop.Tests.csproj验收:
dotnet build 通过。输出:
验收:
schemaVersion。输出:
PluginManifest。验收:
plugin.json 或入口文件时产生可读诊断。输出:
验收:
getRuntimeInfo。输出:
验收:
输出:
验收:
输出:
验收:
输出:
验收:
GET /api/status 返回当前状态。POST /api/edit-mode 能切换编辑模式。widget.layoutChanged。127.0.0.1。| 问题 | 建议默认值 | 后续触发条件 |
|---|---|---|
| 目标 .NET 版本 | .NET 8 |
如果部署环境缺运行时,再评估 self-contained 发布 |
| 托盘库 | Hardcodet.NotifyIcon.Wpf |
如果包兼容性有问题,降级 WinForms NotifyIcon |
| 日志库 | Microsoft.Extensions.Logging + 文件 provider 或 Serilog |
如果需要结构化日志和滚动文件,优先 Serilog |
| WebView2 用户数据目录 | %LocalAppData%\DesktopEnhancer\WebView2 |
多 profile 需求出现后再拆 |
| 默认 API 端口 | 8765 |
端口冲突时允许用户在配置中修改 |