基于WebView2实现的Win11桌面框架,利用插件自定义
chunhualin1
2026-08-17 9b5711d3124622b1f1b18500d442c76492da877a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging.Abstractions;
using Moli.Desktop.Configuration;
using Moli.Desktop.Diagnostics;
using Moli.Desktop.Host;
using Moli.Desktop.Hotkeys;
using Moli.Desktop.Interop;
using Moli.Desktop.Layout;
using Moli.Desktop.Llm;
using Moli.Desktop.Plugins;
using Moli.Desktop.Runtime;
using Moli.Desktop.Tests.Interop;
 
namespace Moli.Desktop.Tests.Runtime;
 
public class DesktopRuntimeCoordinatorTests
{
    [Fact]
    public async Task SetEditModeAsync_PersistsSettingAndBroadcastsStatus()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        var events = new List<RuntimeEvent>();
        using var subscription = fixture.Events.Subscribe(runtimeEvent =>
        {
            events.Add(runtimeEvent);
            return Task.CompletedTask;
        });
        await fixture.Runtime.StartAsync();
 
        var result = await fixture.Runtime.SetEditModeAsync(true);
 
        Assert.True(result.Succeeded);
        Assert.True(result.Value!.IsEditMode);
        Assert.True(fixture.Surface.EditModeEnabled);
        var settings = await fixture.Configuration.LoadAppSettingsAsync();
        Assert.True(settings.Runtime.EditMode);
        Assert.Contains(events, runtimeEvent => runtimeEvent.Name == "app.editModeChanged");
        Assert.Contains(events, runtimeEvent => runtimeEvent.Name == "app.statusChanged");
    }
 
    [Fact]
    public async Task UpdateWidgetLayoutAsync_ConstrainsAppliesSavesAndBroadcasts()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        var events = new List<RuntimeEvent>();
        using var subscription = fixture.Events.Subscribe(runtimeEvent =>
        {
            events.Add(runtimeEvent);
            return Task.CompletedTask;
        });
        await fixture.Runtime.StartAsync();
 
        var result = await fixture.Runtime.UpdateWidgetLayoutAsync(
            fixture.WidgetId,
            new WidgetLayoutPatch { Bounds = new RectD(-5000, -5000, 10, 10), Opacity = 0 });
 
        Assert.True(result.Succeeded);
        Assert.NotNull(fixture.Surface.LastAppliedLayout);
        Assert.Equal(LayoutManager.MinWidth, fixture.Surface.LastAppliedLayout.Bounds.Width);
        Assert.Equal(LayoutManager.MinOpacity, fixture.Surface.LastAppliedLayout.Opacity);
        Assert.Contains(events, runtimeEvent => runtimeEvent.Name == "widget.layoutChanged");
 
        var saved = await fixture.Configuration.LoadLayoutAsync();
        var savedLayout = Assert.Single(saved.Instances);
        Assert.Equal(LayoutManager.MinWidth, savedLayout.Bounds.Width);
        Assert.Equal(LayoutManager.MinOpacity, savedLayout.Opacity);
    }
 
    [Fact]
    public async Task UpdateWidgetLayoutAsync_WhenGlobalLockedRejectsGeometryPatch()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        await fixture.Runtime.StartAsync();
        await fixture.Runtime.SetGlobalLockedAsync(true);
 
        var result = await fixture.Runtime.UpdateWidgetLayoutAsync(
            fixture.WidgetId,
            new WidgetLayoutPatch { Bounds = new RectD(20, 20, 320, 160) });
 
        Assert.False(result.Succeeded);
        Assert.Equal("WidgetLayoutLocked", result.ErrorCode);
        Assert.Equal(2, fixture.Surface.AppliedLayoutCount);
        Assert.True(fixture.Surface.LastAppliedLayout?.IsLocked);
        Assert.Equal(new RectD(100, 100, 320, 160), fixture.Surface.LastAppliedLayout?.Bounds);
    }
 
    [Fact]
    public async Task StartAsync_RestoresRuntimeFlagsBeforeCreatingWidgetSurfaces()
    {
        var fixture = await RuntimeFixture.CreateAsync(new RuntimeSettings
        {
            EditMode = true,
            SafeInputMode = true
        });
 
        var result = await fixture.Runtime.StartAsync();
 
        Assert.True(result.Succeeded);
        Assert.True(fixture.Surface.EditModeEnabled);
        Assert.True(fixture.Surface.SafeInputModeEnabled);
        Assert.Equal(1, fixture.Surface.AppliedLayoutCount);
    }
 
    [Fact]
    public async Task ToggleWidgetInteractableAsync_DoesNotWriteLayoutAndOverridesClickThrough()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        await fixture.Configuration.SaveLayoutAsync(new LayoutDocument
        {
            Monitors =
            [
                new MonitorSnapshot { Monitors = [RuntimeFixture.PrimaryMonitor()] }
            ],
            Instances =
            [
                new WidgetLayout
                {
                    InstanceId = fixture.WidgetId,
                    PluginId = new PluginId("sample.clock"),
                    MonitorId = new MonitorId("primary"),
                    Bounds = new RectD(100, 100, 320, 160),
                    ClickThrough = false,
                    IsVisible = true
                }
            ]
        });
        await fixture.Runtime.StartAsync();
        var before = await fixture.Configuration.LoadLayoutAsync();
 
        var result = await fixture.Runtime.ToggleWidgetInteractableAsync(fixture.WidgetId);
 
        Assert.True(result.Succeeded);
        Assert.True(result.Value!.IsInteractable);
        Assert.True(result.Value.HasSessionInteractable);
        Assert.False(result.Value.ClickThrough);
        Assert.False(result.Value.LayoutClickThrough);
        Assert.Equal(1, fixture.Surface.SessionOverlayCount);
        Assert.True(fixture.Surface.LastSessionOverlay?.Interactable);
 
        var idle = await fixture.Runtime.ToggleWidgetInteractableAsync(fixture.WidgetId);
        Assert.True(idle.Succeeded);
        Assert.False(idle.Value!.IsInteractable);
        Assert.True(idle.Value.ClickThrough);
 
        var after = await fixture.Configuration.LoadLayoutAsync();
        var saved = Assert.Single(after.Instances);
        Assert.Equal(before.Instances[0].ClickThrough, saved.ClickThrough);
        Assert.Equal(before.Instances[0].IsVisible, saved.IsVisible);
    }
 
    [Fact]
    public async Task SetEditModeAsync_ForcesClickableOverSessionIdleOverlay()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        await fixture.Runtime.StartAsync();
        await fixture.Runtime.SetWidgetInteractableAsync(fixture.WidgetId, false);
 
        var result = await fixture.Runtime.SetEditModeAsync(true);
 
        var widget = Assert.Single(result.Value!.Widgets);
        Assert.False(widget.IsInteractable);
        Assert.True(widget.HasSessionInteractable);
        Assert.False(widget.ClickThrough);
        Assert.True(widget.LayoutClickThrough);
    }
 
    [Fact]
    public async Task StartAsync_AppliesIdleClickThroughForEnabledToggleInteractableBinding()
    {
        var fixture = await CreateIdleToggleInteractableFixtureAsync();
 
        var result = await fixture.Runtime.StartAsync();
 
        var widget = Assert.Single(result.Value!.Widgets);
        Assert.False(widget.IsInteractable);
        Assert.True(widget.HasSessionInteractable);
        Assert.True(widget.ClickThrough);
        Assert.False(widget.LayoutClickThrough);
        var saved = Assert.Single((await fixture.Configuration.LoadLayoutAsync()).Instances);
        Assert.False(saved.ClickThrough);
    }
 
    [Fact]
    public async Task UpdateWidgetLayoutAsync_ClickThroughPatch_SyncsIdleOverlaySoOpenAndCloseBothTakeEffect()
    {
        var fixture = await CreateIdleToggleInteractableFixtureAsync();
        await fixture.Runtime.StartAsync();
 
        var opened = await fixture.Runtime.UpdateWidgetLayoutAsync(
            fixture.WidgetId,
            new WidgetLayoutPatch { ClickThrough = true });
 
        Assert.True(opened.Succeeded);
        Assert.True(opened.Value!.ClickThrough);
        Assert.True(opened.Value.LayoutClickThrough);
        Assert.False(opened.Value.IsInteractable);
        Assert.True(opened.Value.HasSessionInteractable);
        Assert.False(fixture.Surface.LastSessionOverlay?.Interactable);
 
        var closed = await fixture.Runtime.UpdateWidgetLayoutAsync(
            fixture.WidgetId,
            new WidgetLayoutPatch { ClickThrough = false });
 
        Assert.True(closed.Succeeded);
        Assert.False(closed.Value!.ClickThrough);
        Assert.False(closed.Value.LayoutClickThrough);
        Assert.True(closed.Value.IsInteractable);
        Assert.True(closed.Value.HasSessionInteractable);
        Assert.True(fixture.Surface.LastSessionOverlay?.Interactable);
 
        var saved = Assert.Single((await fixture.Configuration.LoadLayoutAsync()).Instances);
        Assert.False(saved.ClickThrough);
    }
 
    [Fact]
    public async Task HotkeyToggleInteractable_FlipsIdleSessionOverlay()
    {
        var fixture = await CreateIdleToggleInteractableFixtureAsync();
        await fixture.Runtime.StartAsync();
        Assert.True(Assert.Single((await fixture.Runtime.GetStateAsync()).Widgets).ClickThrough);
 
        await fixture.Hotkeys.RaiseAsync(HotkeysDocument.CreateBuiltinPaletteBinding() with
        {
            Target = new HotkeyTarget { PluginId = "sample.clock" }
        });
 
        var widget = Assert.Single((await fixture.Runtime.GetStateAsync()).Widgets);
        Assert.True(widget.IsInteractable);
        Assert.False(widget.ClickThrough);
    }
 
    [Fact]
    public async Task SaveHotkeysAsync_RejectsDuplicateChord()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        await fixture.Runtime.StartAsync();
        var document = HotkeysDocument.CreateDefault();
        document.Bindings.Add(new HotkeyBinding
        {
            Id = "user-dup",
            Keys = "Shift+Ctrl+K",
            Action = HotkeyActions.RuntimeToggleEditMode,
            Source = HotkeySource.User
        });
 
        var result = await fixture.Runtime.SaveHotkeysAsync(document);
 
        Assert.False(result.Succeeded);
        Assert.Equal("HotkeyDuplicateChord", result.ErrorCode);
    }
 
    private static async Task<RuntimeFixture> CreateIdleToggleInteractableFixtureAsync()
    {
        var fixture = await RuntimeFixture.CreateAsync();
        await fixture.Configuration.SaveLayoutAsync(new LayoutDocument
        {
            Monitors = [new MonitorSnapshot { Monitors = [RuntimeFixture.PrimaryMonitor()] }],
            Instances =
            [
                new WidgetLayout
                {
                    InstanceId = fixture.WidgetId,
                    PluginId = new PluginId("sample.clock"),
                    MonitorId = new MonitorId("primary"),
                    Bounds = new RectD(100, 100, 320, 160),
                    ClickThrough = false
                }
            ]
        });
        await fixture.Configuration.SaveHotkeysAsync(new HotkeysDocument
        {
            Bindings =
            [
                HotkeysDocument.CreateBuiltinPaletteBinding() with
                {
                    Target = new HotkeyTarget { PluginId = "sample.clock" }
                }
            ]
        });
        return fixture;
    }
 
    private sealed class RuntimeFixture
    {
        private RuntimeFixture(
            IDesktopRuntime runtime,
            JsonConfigurationService configuration,
            RuntimeEventBus events,
            FakeRuntimeSurfaceController surface,
            FakeHotkeyService hotkeys,
            WidgetInstanceId widgetId)
        {
            Runtime = runtime;
            Configuration = configuration;
            Events = events;
            Surface = surface;
            Hotkeys = hotkeys;
            WidgetId = widgetId;
        }
 
        public IDesktopRuntime Runtime { get; }
        public JsonConfigurationService Configuration { get; }
        public RuntimeEventBus Events { get; }
        public FakeRuntimeSurfaceController Surface { get; }
        public FakeHotkeyService Hotkeys { get; }
        public WidgetInstanceId WidgetId { get; }
 
        public static async Task<RuntimeFixture> CreateAsync(RuntimeSettings? runtimeSettings = null)
        {
            var root = Path.Combine(Path.GetTempPath(), "Moli.Desktop.Tests", Guid.NewGuid().ToString("N"));
            var paths = new DesktopPaths(Path.Combine(root, "app"), Path.Combine(root, "local"));
            var diagnostics = new DiagnosticsService(paths, NullLogger<DiagnosticsService>.Instance);
            var configuration = new JsonConfigurationService(paths, diagnostics);
            var events = new RuntimeEventBus();
            var surface = new FakeRuntimeSurfaceController();
            var pluginManager = new PluginManager(paths, configuration, new PluginManifestValidator(), diagnostics, new PluginStateMachine());
            var layoutManager = new LayoutManager(configuration, diagnostics);
            var widgetId = new WidgetInstanceId("widget-01");
 
            await CreatePluginAsync(paths);
            if (runtimeSettings is not null)
            {
                await configuration.SaveAppSettingsAsync(new AppSettingsDocument
                {
                    Runtime = runtimeSettings
                });
            }
 
            await configuration.SaveLayoutAsync(new LayoutDocument
            {
                Monitors =
                [
                    new MonitorSnapshot
                    {
                        Monitors = [PrimaryMonitor()]
                    }
                ],
                Instances =
                [
                    new WidgetLayout
                    {
                        InstanceId = widgetId,
                        PluginId = new PluginId("sample.clock"),
                        MonitorId = new MonitorId("primary"),
                        Bounds = new RectD(100, 100, 320, 160)
                    }
                ]
            });
 
            var hotkeys = new FakeHotkeyService();
            var runtime = new DesktopRuntimeCoordinator(
                configuration,
                pluginManager,
                layoutManager,
                new FakeWin32InteropService(),
                diagnostics,
                events,
                surface,
                new DisplayChangeMonitor(),
                new FakeLlmGateway(),
                hotkeys);
 
            return new RuntimeFixture(runtime, configuration, events, surface, hotkeys, widgetId);
        }
 
        private static async Task CreatePluginAsync(DesktopPaths paths)
        {
            var directory = Path.Combine(paths.PluginDirectory, "sample.clock");
            Directory.CreateDirectory(directory);
            await File.WriteAllTextAsync(Path.Combine(directory, "index.html"), "<!doctype html><title>Clock</title>");
            await File.WriteAllTextAsync(
                Path.Combine(directory, "plugin.json"),
                """
                {
                  "id": "sample.clock",
                  "name": "Clock",
                  "version": "1.0.0",
                  "type": "widget",
                  "entry": "index.html",
                  "defaultLayout": {
                    "width": 320,
                    "height": 160,
                    "opacity": 1.0
                  }
                }
                """);
        }
 
        public static MonitorInfo PrimaryMonitor() => new()
        {
            Id = new MonitorId("primary"),
            Bounds = new RectD(0, 0, 1920, 1080),
            WorkArea = new RectD(0, 0, 1920, 1040),
            IsPrimary = true
        };
    }
 
    private sealed class FakeRuntimeSurfaceController : IRuntimeSurfaceController
    {
        public bool EditModeEnabled { get; private set; }
        public bool SafeInputModeEnabled { get; private set; }
        public WidgetLayout? LastAppliedLayout { get; private set; }
        public int AppliedLayoutCount { get; private set; }
        public WidgetSessionOverlay? LastSessionOverlay { get; private set; }
        public int SessionOverlayCount { get; private set; }
 
        public Task ApplyEditModeAsync(bool enabled, CancellationToken cancellationToken = default)
        {
            EditModeEnabled = enabled;
            return Task.CompletedTask;
        }
 
        public Task ApplySafeInputModeAsync(bool enabled, CancellationToken cancellationToken = default)
        {
            SafeInputModeEnabled = enabled;
            return Task.CompletedTask;
        }
 
        public Task ApplyWidgetLayoutAsync(WidgetLayout layout, CancellationToken cancellationToken = default)
        {
            LastAppliedLayout = layout;
            AppliedLayoutCount++;
            return Task.CompletedTask;
        }
 
        public Task ApplyWidgetSessionOverlayAsync(WidgetLayout layout, WidgetSessionOverlay overlay, CancellationToken cancellationToken = default)
        {
            LastAppliedLayout = layout;
            LastSessionOverlay = overlay;
            SessionOverlayCount++;
            return Task.CompletedTask;
        }
 
        public Task EnableWallpaperAsync(WallpaperRuntimeState wallpaper, CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task DisableWallpaperAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task ShutdownAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task SyncAllLayoutsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task SyncWallpaperMonitorsAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task ReattachDesktopLayersAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
    }
 
    private sealed class FakeHotkeyService : IHotkeyService
    {
        public event Func<HotkeyBinding, Task>? HotkeyPressed;
        public IReadOnlyList<HotkeyRegistration> Registrations { get; private set; } = [];
        public IReadOnlyList<HotkeyBinding> Bindings { get; private set; } = [];
        public bool Paused { get; private set; }
 
        public Task ReplaceBindingsAsync(IReadOnlyList<HotkeyBinding> bindings, CancellationToken cancellationToken = default)
        {
            Bindings = bindings.ToArray();
            Registrations = bindings.Select(binding => new HotkeyRegistration
            {
                BindingId = binding.Id,
                Keys = binding.Keys,
                State = !binding.Enabled || Paused ? HotkeyRegistrationState.Disabled : HotkeyRegistrationState.Registered
            }).ToArray();
            return Task.CompletedTask;
        }
 
        public void Pause() => Paused = true;
 
        public void Resume() => Paused = false;
 
        public void UnregisterAll() => Registrations = [];
 
        public Task RaiseAsync(HotkeyBinding binding) => HotkeyPressed?.Invoke(binding) ?? Task.CompletedTask;
 
        public void Dispose()
        {
        }
    }
 
    private sealed class FakeLlmGateway : ILlmGatewayService
    {
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
 
        public Task<IReadOnlyList<LlmModelSummary>> GetModelsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult<IReadOnlyList<LlmModelSummary>>([]);
 
        public Task<AiChatProjectsResult> GetProjectsAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatProjectsResult
            {
                Status = AiChatProjectStatuses.NotConfigured,
                Projects = []
            });
 
        public Task<AiChatMemoryCapabilities> GetMemoryCapabilitiesAsync(LlmPluginRuntimeConfig runtimeConfig, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatMemoryCapabilities());
 
        public Task<AiChatJsonResult> GetMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatGetMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
 
        public Task<AiChatJsonResult> CreateMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatCreateMemoryRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
 
        public Task DeleteMemoryAsync(LlmPluginRuntimeConfig runtimeConfig, string memoryId, CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task<AiChatJsonResult> RecallMemoriesAsync(LlmPluginRuntimeConfig runtimeConfig, AiChatRecallMemoriesRequest request, CancellationToken cancellationToken = default)
            => Task.FromResult(new AiChatJsonResult());
 
        public async IAsyncEnumerable<LlmStreamEvent> StreamChatAsync(LlmChatRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default)
        {
            yield break;
        }
 
        public Task CancelAsync(string requestId, CancellationToken cancellationToken = default) => Task.CompletedTask;
 
        public Task CancelPluginRequestsAsync(string pluginId, CancellationToken cancellationToken = default) => Task.CompletedTask;
    }
}