基于WebView2实现的Win11桌面框架,利用插件自定义
编辑 | blame | 历史 | 原始文档

Detailed Design: Moli.Desktop MVP

Context

本文档基于 docs/product/desktop-enhancement-prd.md 和 docs/architecture/runtime-architecture.md,面向 Dev Agent 的一期 MVP 实现。详细设计以 C#、WPF、WebView2、Win32 互操作和本地 JSON 配置为主线,目标是把模块、接口、状态机和异常恢复规则定义到可编码粒度。

Design Scope

MVP 必须实现:

  • WPF 桌面宿主、托盘和管理窗口骨架。
  • WebView2 壁纸窗口和组件窗口。
  • 本地插件目录扫描、manifest 校验、插件状态机。
  • 组件拖拽、缩放、锁定、显示隐藏、透明度和点击穿透。
  • appsettings.json、plugins.json、layout.json 持久化。
  • 本地 HTTP API 和 WebSocket 事件通道。
  • 诊断日志、WebView2 Runtime 检测、损坏配置恢复。

MVP 不实现:

  • 插件市场、zip 插件导入、在线更新。
  • 插件沙箱隔离。
  • Postgres / Redis 同步或远程控制。
  • Windows 11 之前系统兼容承诺。

Project Structure

建议解决方案结构:

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 托盘图标和菜单命令

Application Composition

App Startup

App.xaml.cs 只做最薄启动,复杂逻辑交给 AppHost。

public sealed class AppHost
{
    public Task StartAsync(CancellationToken cancellationToken);
    public Task StopAsync(CancellationToken cancellationToken);
}

启动顺序:

  1. 创建全局互斥锁:Global\Moli.Desktop.SingleInstance。
  2. 初始化 DiagnosticsService 和日志目录。
  3. 创建配置目录和插件目录。
  4. 加载配置文件,损坏时执行备份恢复。
  5. 检测 WebView2 Runtime。
  6. 扫描插件并合并注册表状态。
  7. 创建托盘。
  8. 根据配置创建壁纸窗口和组件窗口。
  9. 启动 HTTP 和 WebSocket 服务。
  10. 进入 WPF 消息循环。

关闭顺序:

  1. 停止 API 服务,不再接收新命令。
  2. 通知插件 onBeforeUnload。
  3. 保存当前布局和运行配置。
  4. 关闭 WebView2 窗口。
  5. 销毁托盘图标。
  6. 释放互斥锁。

Dependency Container

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>();

Core Domain Models

Common Value Objects

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);

Enums

public enum PluginType
{
    Wallpaper,
    Widget,
    Utility
}

public enum PluginState
{
    Installed,
    Enabled,
    Loaded,
    Running,
    Paused,
    Disabled,
    Error,
    Removed
}

public enum DiagnosticSeverity
{
    Info,
    Warning,
    Error,
    Critical
}

App Runtime State

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; } = [];
}

Configuration Detailed Design

Interfaces

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);
}

Document Types

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; } = [];
}

File Operations

读流程:

  1. 如果文件不存在,返回默认文档并写入默认文件。
  2. 使用 System.Text.Json 读取,启用大小写不敏感。
  3. 校验 schemaVersion。
  4. 执行文档级校验。
  5. 失败时备份原文件并返回默认文档。

写流程:

  1. 写入 <name>.tmp。
  2. flush 到磁盘。
  3. 如果目标文件存在,复制为 <name>.bak。
  4. 用临时文件替换目标文件。
  5. 失败时保留 .tmp 和 .bak,写诊断日志。

文件名规范:

appsettings.json
appsettings.json.bak
appsettings.json.invalid.20260502-153000.json
appsettings.json.tmp

Validation Rules

文档 规则
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 缺失显示器时布局回收到主显示器

Plugin Detailed Design

Manifest Model

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; }
}

Plugin Manager Interface

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);
}

Manifest Validation

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。
  • 远程 URL 插件必须在诊断中标记来源风险。
  • defaultLayout.width 最小 80,最大 3840。
  • defaultLayout.height 最小 40,最大 2160。

Plugin State Transitions

状态转换由 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,不抛出未处理异常。

WebView Detailed Design

WebView Runtime Interface

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();
}

WebView Options

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; }
}

Bridge Injection

桥接脚本在导航前通过 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 是否在白名单。
  • 请求来源是否属于当前 WebViewHost。
  • setConfig patch 是否是对象且大小不超过限制。
  • requestResize 是否符合布局约束。

Navigation Failure

失败处理:

  1. WebView 导航失败时记录 WebViewNavigationFailed。
  2. 当前插件实例进入 Error。
  3. 组件窗口显示轻量错误占位。
  4. 托盘状态变为错误或警告。
  5. WebSocket 广播 diagnostic.error 和 plugin.stateChanged。

Window and Win32 Detailed Design

Window Manager Interface

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);
}

Window Types

窗口 类型 说明
WallpaperWindow WPF Window 无边框、无任务栏、覆盖目标显示器、承载壁纸 WebView2
WidgetWindow WPF Window 无边框、透明背景、承载组件 WebView2
WidgetEditAdorner WPF Adorner 或自定义 overlay 编辑模式边框、控制点、锁定状态
ManagementWindow WPF Window 普通工具窗口,不参与桌面层

Win32 Interop Interface

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();
}

Desktop Layer Strategy

public interface IDesktopLayerStrategy
{
    string Name { get; }
    bool IsSupported();
    bool TryAttachWallpaperWindow(IntPtr hwnd, MonitorInfo monitor, out string? error);
}

策略顺序:

  1. WorkerWDesktopLayerStrategy:尝试将壁纸窗口挂到 Explorer WorkerW。
  2. BottomDesktopLayerStrategy:降级为覆盖目标显示器的底层窗口,并开启点击穿透。

选择策略后写入诊断:

DesktopLayerStrategySelected: WorkerW
DesktopLayerStrategyFallback: BottomDesktopLayer, reason=WorkerWNotFound

Click Through Rules

场景 点击穿透
壁纸默认运行 按壁纸配置,默认 true
壁纸编辑或调试 false
组件非编辑模式 按组件配置
组件编辑模式 false
全局安全输入模式 全部 false
全局锁定 不改变点击穿透,只阻止拖拽缩放

实现使用扩展样式:

  • WS_EX_TRANSPARENT
  • WS_EX_LAYERED
  • WS_EX_TOOLWINDOW
  • 可选 WS_EX_NOACTIVATE

Layout Detailed Design

Layout Manager Interface

public 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);
}

Layout Constraints

默认约束:

字段 最小 最大
width 80 当前显示器宽度
height 40 当前显示器高度
scale 0.5 3.0
opacity 0.1 1.0
displayPriority desktopLayer appLayer

位置约束:

  • 组件至少保留 48x48 DIP 在可见工作区内。
  • 如果目标显示器不存在,迁移到主显示器中心。
  • 拖拽时实时约束,保存时再次约束。

Drag and Resize Flow

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

保存策略:

  • 拖动中不每帧写文件。
  • 拖动结束后立即保存。
  • 连续 API 更新使用 300ms debounce。
  • 退出应用时强制 flush。

Runtime Coordinator Detailed Design

Interface

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);
}

Command Rules

命令 行为
SetEditMode(true) 所有组件关闭点击穿透,显示编辑控制
SetEditMode(false) 保存布局,恢复组件点击穿透
SetSafeInputMode(true) 所有桌面窗口关闭点击穿透
SetGlobalLocked(true) 所有组件拒绝拖拽缩放
ReloadPlugins 重新扫描插件目录,保留同 id 组件布局
DisableWallpaper 关闭壁纸窗口,保留壁纸配置
UpdateWidgetLayout 校验、应用窗口、保存布局、广播事件,包含 displayPriority 更新

所有命令都通过 DesktopRuntimeCoordinator 进入,托盘、管理窗口、HTTP API 不直接调用底层服务。

Local API Detailed Design

Hosting

MVP 使用 ASP.NET Core Minimal API 内嵌于桌面进程。

默认监听:

http://127.0.0.1:8765
ws://127.0.0.1:8765/ws/events

如果端口被占用:

  1. 记录诊断 ApiPortInUse。
  2. API 服务不启动。
  3. 托盘和管理窗口继续可用。
  4. 管理窗口显示当前 API 不可用原因。

Endpoints

方法 路径 请求 响应
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

API DTO Rules

  • DTO 不直接复用内部 mutable model。
  • 错误响应包含 code、message、details。
  • 默认不做跨网段访问,绑定地址不可通过插件修改。
{
  "success": false,
  "code": "PluginNotFound",
  "message": "Plugin sample.clock was not found.",
  "details": {}
}

WebSocket Events

{
  "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);
}

Tray and Management Window Detailed Design

Tray Shell

托盘菜单结构:

Moli.Desktop
  打开管理窗口
  壁纸
    启用 / 禁用
    暂停 / 恢复
    静音 / 取消静音
  编辑模式
    进入 / 退出
    锁定全部 / 解锁全部
    安全输入模式
  插件
    重载插件
  诊断
    打开日志目录
    导出诊断
  开机启动
  退出

状态图标:

状态 图标语义
正常 默认图标
暂停 暂停标识
警告 黄色角标或提示文本
错误 红色角标或提示文本

Management Window MVP Tabs

Tab 内容
状态 当前运行状态、WebView2 Runtime、API 监听、显示器信息
壁纸 当前壁纸插件、启停、重载、静音、点击穿透、显示器选择、本地文件选择
组件 组件列表、显示隐藏、锁定、透明度、点击穿透、显示优先级、右键编辑位置/大小、打开 layout.json
插件 插件扫描结果、manifest 错误、启用禁用、右键打开 plugin.json / plugins.json
诊断 日志摘要、错误列表、打开日志目录、二次确认恢复默认

管理窗口不得作为桌面覆盖层,必须是普通 WPF 工具窗口。

Built-in Audio Visualizer

默认样例插件:

samples/plugins/sample.audio-visualizer/
  plugin.json
  index.html

默认布局由 DefaultContentInstaller 特判:

  • x = 0
  • width = SystemParameters.PrimaryScreenWidth
  • y = SystemParameters.PrimaryScreenHeight * 2 / 3
  • height = min(SystemParameters.PrimaryScreenHeight * 0.25, manifest.defaultLayout.height)
  • locked = true
  • clickThrough = true

MVP 插件端通过 Web Audio API 尝试捕获带音频的屏幕流。若系统或用户授权不允许,则使用占位律动,避免桌面视觉出现空白。真实无授权声卡输出采集作为后续 IAudioLoopbackService 扩展。

Diagnostics Detailed Design

Error Codes

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 显示器变化后布局回收

Diagnostic Entry

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; } = [];
}

Logging Rules

  • 启动、插件扫描、WebView2 初始化、Win32 样式变更、配置读写必须有日志。
  • 插件错误必须包含 pluginId 和入口来源。
  • 布局错误必须包含 instanceId 和显示器信息。
  • 诊断导出可生成一个 zip,包含日志和脱敏后的配置快照。

Security Design

MVP 是无沙箱插件模型,但实现必须保留基本防线:

  • 所有宿主能力通过白名单方法访问。
  • 不注入任意 C# 对象给插件页面。
  • 插件本地路径必须在插件目录内。
  • 本地 API 只监听 127.0.0.1。
  • 管理窗口明确显示远程 URL 插件来源。
  • setConfig 限制 payload 大小,建议 MVP 最大 64 KB。
  • 日志不记录敏感本地文件内容。

Testing Hooks

为 QA 和后续自动化预留:

  • IDesktopLayerStrategy 可替换为 fake,避免测试时操作真实桌面。
  • IWin32InteropService 可 mock。
  • IFileSystem 或封装文件操作,方便配置损坏恢复测试。
  • ILocalApiService 支持随机端口或测试端口。
  • IClock 统一时间戳,便于断言备份文件名和事件。

Implementation Order

推荐实现顺序:

  1. 创建解决方案、WPF 项目、测试项目和基础依赖。
  2. 实现配置模型、默认值、读写、恢复和单元测试。
  3. 实现插件 manifest 模型、扫描、校验和状态机测试。
  4. 实现诊断服务和事件总线。
  5. 实现 WPF 托盘和管理窗口骨架。
  6. 实现 WebView2 host 基类和本地 HTML 加载。
  7. 实现壁纸窗口,先用降级底层窗口策略跑通。
  8. 实现组件窗口和布局应用。
  9. 实现拖拽、缩放、锁定和编辑模式。
  10. 实现 Win32 WorkerW 策略、点击穿透和透明窗口。
  11. 实现 HTTP API 和 WebSocket 事件。
  12. 实现开机启动、zip 发布脚本和 MVP 验收样例插件。

Dev Task Breakdown

DD-01 Solution Skeleton

输出:

  • src/Moli.Desktop/Moli.Desktop.csproj
  • src/Moli.Desktop.Tests/Moli.Desktop.Tests.csproj
  • 基础目录和 DI 装配。

验收:

  • dotnet build 通过。
  • 空应用启动后托盘可见或主窗口可见。

DD-02 Configuration Service

输出:

  • 配置模型。
  • JSON 读写服务。
  • 默认配置生成。
  • 损坏文件备份恢复。

验收:

  • 缺失配置时生成默认文件。
  • 损坏 JSON 被备份并恢复默认值。
  • 配置文件包含 schemaVersion。

DD-03 Plugin Manager

输出:

  • PluginManifest。
  • manifest 校验器。
  • 插件目录扫描。
  • 状态机。

验收:

  • 有效插件可识别。
  • 缺少 plugin.json 或入口文件时产生可读诊断。
  • 非法状态转换被拒绝。

DD-04 WebView Host

输出:

  • WebView2 初始化服务。
  • 桥接脚本注入。
  • 导航失败诊断。

验收:

  • 本地 HTML 可加载。
  • 插件可调用 getRuntimeInfo。
  • 导航失败不会崩溃宿主。

DD-05 Desktop Windows and Interop

输出:

  • 壁纸窗口。
  • 组件窗口。
  • 点击穿透、透明、置底样式。
  • Desktop layer strategy。

验收:

  • 壁纸窗口覆盖目标显示器。
  • 点击穿透开启后桌面可点击。
  • 关闭安全输入模式后组件可恢复原规则。

DD-06 Layout and Edit Mode

输出:

  • 布局管理器。
  • 拖拽、缩放、锁定。
  • 显示器拓扑回收。

验收:

  • 拖拽和缩放后重启恢复。
  • 锁定组件不可拖拽。
  • 移除副屏后组件回主屏可见区域。

DD-07 Tray and Management

输出:

  • 托盘菜单。
  • 管理窗口 MVP tabs。
  • 日志目录和重置布局入口。

验收:

  • 托盘能切换壁纸、编辑模式、全局锁定和安全输入模式。
  • 管理窗口显示插件和诊断状态。

DD-08 Local API and Events

输出:

  • Minimal API。
  • WebSocket 事件通道。
  • DTO 和错误响应。

验收:

  • GET /api/status 返回当前状态。
  • POST /api/edit-mode 能切换编辑模式。
  • 布局变化广播 widget.layoutChanged。
  • API 只监听 127.0.0.1。

Open Decisions

问题 建议默认值 后续触发条件
目标 .NET 版本 .NET 8 如果部署环境缺运行时,再评估 self-contained 发布
托盘库 Hardcodet.NotifyIcon.Wpf 如果包兼容性有问题,降级 WinForms NotifyIcon
日志库 Microsoft.Extensions.Logging + 文件 provider 或 Serilog 如果需要结构化日志和滚动文件,优先 Serilog
WebView2 用户数据目录 %LocalAppData%\DesktopEnhancer\WebView2 多 profile 需求出现后再拆
默认 API 端口 8765 端口冲突时允许用户在配置中修改