From 8658db5acd2531755fb8a8dfa1f2f5463c3af9e7 Mon Sep 17 00:00:00 2001
From: HDG <121079795+oniemiddle@users.noreply.github.com>
Date: Fri, 2 Oct 2026 17:15:33 +0800
Subject: [PATCH 1/2] refactor platform and widget boundaries
---
Directory.Packages.props | 1 +
README.md | 25 +++++
docs/architecture.md | 101 ++++++++++++++++++
src/DeskKit.App/App.axaml.cs | 35 ++----
.../Diagnostics/DesktopLayerSelfTest.cs | 5 +-
src/DeskKit.App/Services/WidgetShell.cs | 5 +
.../Abstractions/IWidgetMessageBus.cs | 33 ++++++
src/DeskKit.Core/Models/IWidgetHost.cs | 8 ++
src/DeskKit.Core/Services/WidgetMessageBus.cs | 78 ++++++++++++++
src/DeskKit.Core/Services/WidgetRegistry.cs | 48 ++++++++-
src/DeskKit.Platform/DeskKit.Platform.csproj | 1 +
.../PlatformServiceCollectionExtensions.cs | 43 ++++++++
src/DeskKit.Widgets/BuiltInWidgets.cs | 27 +++--
src/DeskKit.Widgets/DeskKit.Widgets.csproj | 1 +
.../WidgetMessageBusTests.cs | 59 ++++++++++
.../DeskKit.Core.Tests/WidgetRegistryTests.cs | 33 +++++-
16 files changed, 459 insertions(+), 44 deletions(-)
create mode 100644 docs/architecture.md
create mode 100644 src/DeskKit.Core/Abstractions/IWidgetMessageBus.cs
create mode 100644 src/DeskKit.Core/Services/WidgetMessageBus.cs
create mode 100644 src/DeskKit.Platform/PlatformServiceCollectionExtensions.cs
create mode 100644 tests/DeskKit.Core.Tests/WidgetMessageBusTests.cs
diff --git a/Directory.Packages.props b/Directory.Packages.props
index e2a3d70..b743daa 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -16,6 +16,7 @@
+
diff --git a/README.md b/README.md
index 2beea25..1750005 100644
--- a/README.md
+++ b/README.md
@@ -18,6 +18,31 @@ Three widgets ship in the box:
The interface is available in **English and Simplified Chinese**, and follows the
system language until you pick one.
+## Widget extension model
+
+The shell depends only on `IWidgetProvider`. Providers are registered with
+Microsoft.Extensions.DependencyInjection, and `WidgetRegistry` turns that ordered
+set into the catalogue shown by the UI. Built-in widgets use
+`services.AddBuiltInWidgets()`; an extension can register its own
+`IWidgetProvider` in the same composition root. A duplicate widget ID now fails
+at startup instead of silently choosing one provider, which makes plugin
+configuration errors actionable.
+
+Widgets communicate through typed, in-process messages exposed by
+`IWidgetHost.Messages`; message contracts contain data only, and subscriptions
+are disposed with the widget view model. See [the architecture guide](docs/architecture.md)
+for module ownership, platform capability boundaries, persistence rules and the
+theme/UI model.
+
+This is intentionally **composition-time extensibility**, not yet arbitrary DLL
+loading. Loading assemblies from a plugin directory needs an explicit isolation,
+dependency-resolution, versioning, and trust policy; adding that before defining
+those policies would make the app less predictable. When that host is introduced,
+[`McMaster.NETCore.Plugins`](https://github.com/natemcmaster/DotNetCorePlugins)
+is a good candidate to replace custom `AssemblyLoadContext` and dependency-probing
+code. It should be isolated behind an `IWidgetProvider` discovery service, leaving
+the widget shell and registry unchanged.
+
## Status
The desktop-layer mechanism, the shell and all three widgets are implemented and
diff --git a/docs/architecture.md b/docs/architecture.md
new file mode 100644
index 0000000..bd484cf
--- /dev/null
+++ b/docs/architecture.md
@@ -0,0 +1,101 @@
+# DeskKit architecture
+
+## Design boundary
+
+DeskKit is a desktop host, not a collection of special-case windows. The host
+owns process lifetime, persistence, platform integration and desktop placement.
+Widgets own their own view, settings schema and widget-specific behaviour. The
+boundary between the two is `DeskKit.Core`'s provider and host contracts.
+
+```
+DeskKit.App (Avalonia composition, shell, settings/tray)
+ ├── DeskKit.Widgets (built-in widget modules)
+ ├── DeskKit.Platform (capability implementations per OS)
+ └── DeskKit.Core (widget contracts, state model, persistence and pure rules)
+```
+
+Dependencies always point down this diagram. In particular, `Core` cannot
+reference `App` or `Platform`; a widget cannot call Win32 or reach into another
+widget's view model.
+
+## Platform capabilities
+
+`DeskKit.Platform` expresses host integration as capabilities:
+
+| Capability | Contract | Windows implementation | Other platforms |
+| --- | --- | --- | --- |
+| Desktop placement and deliberate visibility | `IDesktopLayerService` | `WindowsDesktopLayerService` | `NullDesktopLayerService` |
+| Window material | `IWindowMaterialService` | `WindowsWindowMaterialService` | `NullWindowMaterialService` |
+| Login startup | `IAutoStartService` | `WindowsAutoStartService` | `NullAutoStartService` |
+| File icons | `IShellIconLoader` | `WindowsShellIconLoader` | `NullShellIconLoader` |
+
+`AddDeskKitPlatform()` is the only platform selection point used by the app.
+New OS support therefore means adding implementations and extending that method,
+not adding `OperatingSystem.Is…` branches in views or widgets. A null capability
+must be a safe fallback, never an exception for a feature the host can simply
+omit.
+
+## Widget SDK and lifecycle
+
+The SDK surface for a widget is deliberately small:
+
+* `IWidgetProvider` describes a stable widget type and creates a view model for
+ one placement.
+* `WidgetDescriptor` contains only identity, size and interaction policy; UI text
+ is a resource key so it can follow a runtime culture change.
+* `WidgetContext` supplies placement, versioned settings and `IWidgetHost`.
+* `WidgetViewModel` owns its Avalonia controls and is started after its window is
+ visible, then stopped and disposed before the window closes.
+
+Providers are contributed through DI. `WidgetRegistry` preserves registration
+order and rejects empty or duplicate IDs. This makes built-ins, test widgets and
+future plugins use one composition seam. Runtime DLL discovery is intentionally
+not part of this boundary until plugin versioning, isolation and trust policies
+are specified.
+
+## Widget communication
+
+Widgets must not retain each other's view models. `IWidgetMessageBus` provides
+typed, in-process publish/subscribe contracts through `IWidgetHost.Messages`.
+Message types should be immutable data records in a small shared contract
+assembly. Delivery is synchronous on the publisher's thread; UI subscribers must
+marshal to Avalonia's UI thread where necessary, and each widget must dispose its
+subscriptions with its view model. Persistent or cross-process workflows do not
+belong on this bus.
+
+For request/response, start with an explicit service contract owned by the host.
+Do not layer a generic request bus over widget messages: doing so obscures
+ownership, cancellation and failure handling.
+
+## State and settings
+
+`StateStore` is the single writer for `AppState` and SQLite is the source of
+truth. It owns EF migrations, the pre-migration backup, old JSON import and the
+read-only refusal rules for unavailable or newer schemas. Widget settings are
+stored as versioned JSON per placement and migrated by the widget provider. The
+shell debounces ordinary writes, but migrations and first-run seeding are saved
+immediately.
+
+New host-level data belongs in a typed `AppState`/EF entity migration. New
+widget-level data belongs in the widget's settings plus an
+`IWidgetSettingsMigrations` step. Neither should create an independent file.
+
+## UI, theme and desktop behaviour
+
+`ThemeService` owns application theme selection. Widgets consume semantic keys
+from `WidgetTheme.axaml`; they must not hard-code light or dark content colours.
+`IWindowMaterialService` resolves a requested platform material before widget
+window layout is calculated, while `WidgetWindow` owns window-only concerns such
+as card margins, drag/resize and snap glow. `WidgetShell` coordinates widgets;
+it should not accumulate view rendering or native API calls.
+
+## Library decisions
+
+The project already uses Avalonia, CommunityToolkit.Mvvm, EF Core and Microsoft
+DI where they reduce framework plumbing. Keep the message bus small and local:
+MediatR would add indirection without solving a current cross-process or pipeline
+need. If DLL plugins are introduced, evaluate `McMaster.NETCore.Plugins` to avoid
+hand-written `AssemblyLoadContext` dependency resolution. For richer settings
+validation, evaluate `FluentValidation` only once user-editable settings have
+rules that are shared by UI and persistence; annotations or view-only validation
+would otherwise split the rule source.
diff --git a/src/DeskKit.App/App.axaml.cs b/src/DeskKit.App/App.axaml.cs
index 4657211..8a07a8a 100644
--- a/src/DeskKit.App/App.axaml.cs
+++ b/src/DeskKit.App/App.axaml.cs
@@ -10,7 +10,6 @@
using DeskKit.Core.Abstractions;
using DeskKit.Core.Services;
using DeskKit.Platform;
-using DeskKit.Platform.Windows;
using DeskKit.Widgets;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
@@ -147,6 +146,7 @@ private static ServiceProvider BuildServices()
});
services.AddSingleton();
+ services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
services.AddSingleton();
@@ -155,36 +155,13 @@ private static ServiceProvider BuildServices()
// widgets' resource managers, and two of them would fight over the culture.
services.AddSingleton();
- services.AddSingleton(_ =>
- OperatingSystem.IsWindows()
- ? new WindowsDesktopLayerService()
- : new NullDesktopLayerService());
-
- services.AddSingleton(_ =>
- OperatingSystem.IsWindows()
- ? new WindowsWindowMaterialService()
- : new NullWindowMaterialService());
-
- services.AddSingleton(_ =>
- OperatingSystem.IsWindows()
- ? new WindowsAutoStartService()
- : new NullAutoStartService());
-
- services.AddSingleton(_ =>
- OperatingSystem.IsWindows()
- ? new WindowsShellIconLoader()
- : new NullShellIconLoader());
+ services.AddDeskKitPlatform();
+ // The shell only sees the contract. Built-ins and future plugins both add
+ // providers through DI, and the registry checks duplicate IDs at startup.
+ services.AddBuiltInWidgets();
services.AddSingleton(provider =>
- {
- var registry = new WidgetRegistry();
- var iconLoader = provider.GetRequiredService();
-
- foreach (var widgetProvider in BuiltInWidgets.CreateProviders(iconLoader))
- registry.Register(widgetProvider);
-
- return registry;
- });
+ new WidgetRegistry(provider.GetServices()));
services.AddSingleton();
diff --git a/src/DeskKit.App/Diagnostics/DesktopLayerSelfTest.cs b/src/DeskKit.App/Diagnostics/DesktopLayerSelfTest.cs
index 41d8c35..bff5728 100644
--- a/src/DeskKit.App/Diagnostics/DesktopLayerSelfTest.cs
+++ b/src/DeskKit.App/Diagnostics/DesktopLayerSelfTest.cs
@@ -9,6 +9,7 @@
using DeskKit.App.Services;
using DeskKit.App.Views;
using DeskKit.Core;
+using DeskKit.Core.Abstractions;
using DeskKit.Core.Data;
using DeskKit.Core.Services;
using DeskKit.Platform;
@@ -270,7 +271,8 @@ private static WidgetShell CreateShell(
WidgetRegistry? registry = null,
IDesktopLayerService? desktopLayer = null,
INoticePresenter? notices = null,
- LanguageService? language = null) =>
+ LanguageService? language = null,
+ IWidgetMessageBus? messages = null) =>
new(
store ?? new StateStore(Path.Combine(directory, AppPaths.DatabaseFileName), directory),
registry ?? BuiltInRegistry(),
@@ -281,6 +283,7 @@ private static WidgetShell CreateShell(
new NullWindowMaterialService(),
language ?? new LanguageService(),
notices ?? NullNoticePresenter.Instance,
+ messages ?? new WidgetMessageBus(),
NullLogger.Instance);
///
diff --git a/src/DeskKit.App/Services/WidgetShell.cs b/src/DeskKit.App/Services/WidgetShell.cs
index d5331ab..29d8e4b 100644
--- a/src/DeskKit.App/Services/WidgetShell.cs
+++ b/src/DeskKit.App/Services/WidgetShell.cs
@@ -40,6 +40,7 @@ public sealed class WidgetShell : IWidgetHost, IDisposable
private readonly IWindowMaterialService _materials;
private readonly ILogger _logger;
private readonly INoticePresenter _notices;
+ private readonly IWidgetMessageBus _messages;
private readonly List _widgets = [];
/// The material every widget window carries, already resolved.
@@ -63,6 +64,7 @@ public WidgetShell(
IWindowMaterialService materials,
LanguageService languageService,
INoticePresenter notices,
+ IWidgetMessageBus messages,
ILogger logger)
{
_stateStore = stateStore;
@@ -74,6 +76,7 @@ public WidgetShell(
_materials = materials;
Language = languageService;
_notices = notices;
+ _messages = messages;
_logger = logger;
// Resolved once, at construction, because the answer changes the layout of
@@ -115,6 +118,8 @@ .. _widgets
public IReadOnlyList Screens => ScreenProbe.GetScreens();
+ public IWidgetMessageBus Messages => _messages;
+
public void ShowSettings(WidgetViewModel widget)
{
OpenSettings(FindRuntime(widget));
diff --git a/src/DeskKit.Core/Abstractions/IWidgetMessageBus.cs b/src/DeskKit.Core/Abstractions/IWidgetMessageBus.cs
new file mode 100644
index 0000000..8cccbde
--- /dev/null
+++ b/src/DeskKit.Core/Abstractions/IWidgetMessageBus.cs
@@ -0,0 +1,33 @@
+namespace DeskKit.Core.Abstractions;
+
+///
+/// Marker interface for a message that may be exchanged by widget instances.
+///
+///
+/// A message contract belongs in a small shared package owned by the widgets
+/// that use it. It must contain data only: widgets must not pass controls, view
+/// models, or shell services through the bus.
+///
+public interface IWidgetMessage
+{
+}
+
+///
+/// In-process communication boundary between independently developed widgets.
+///
+///
+/// Delivery is synchronous and takes place on the publishing thread. This keeps
+/// the contract deterministic and avoids silently introducing a background UI
+/// thread. A widget that changes Avalonia state must publish from, or marshal to,
+/// the UI thread. Publishers do not need to know which widgets are listening.
+///
+public interface IWidgetMessageBus
+{
+ /// Subscribes to one message contract.
+ IDisposable Subscribe(Action handler)
+ where TMessage : IWidgetMessage;
+
+ /// Publishes a message to the current subscribers of its contract.
+ void Publish(TMessage message)
+ where TMessage : IWidgetMessage;
+}
diff --git a/src/DeskKit.Core/Models/IWidgetHost.cs b/src/DeskKit.Core/Models/IWidgetHost.cs
index f050517..7df6c5b 100644
--- a/src/DeskKit.Core/Models/IWidgetHost.cs
+++ b/src/DeskKit.Core/Models/IWidgetHost.cs
@@ -1,8 +1,16 @@
+using DeskKit.Core.Abstractions;
+
namespace DeskKit.Core.Models;
/// Services a widget may use without knowing anything about the shell.
public interface IWidgetHost
{
+ ///
+ /// Sends and receives explicit data contracts between widgets without giving
+ /// one widget a reference to another widget's implementation.
+ ///
+ IWidgetMessageBus Messages { get; }
+
/// Current monitor layout, in physical pixels.
IReadOnlyList Screens { get; }
diff --git a/src/DeskKit.Core/Services/WidgetMessageBus.cs b/src/DeskKit.Core/Services/WidgetMessageBus.cs
new file mode 100644
index 0000000..1aca941
--- /dev/null
+++ b/src/DeskKit.Core/Services/WidgetMessageBus.cs
@@ -0,0 +1,78 @@
+using DeskKit.Core.Abstractions;
+
+namespace DeskKit.Core.Services;
+
+///
+/// Process-wide implementation of .
+///
+///
+/// Handlers are invoked from a snapshot. A handler can therefore safely subscribe
+/// or dispose itself while a message is being delivered, and a subscription never
+/// keeps a widget alive after its view model disposes the returned handle.
+///
+public sealed class WidgetMessageBus : IWidgetMessageBus
+{
+ private readonly object _gate = new();
+ private readonly Dictionary> _handlers = [];
+
+ public IDisposable Subscribe(Action handler)
+ where TMessage : IWidgetMessage
+ {
+ ArgumentNullException.ThrowIfNull(handler);
+
+ lock (_gate)
+ {
+ if (!_handlers.TryGetValue(typeof(TMessage), out var handlers))
+ {
+ handlers = [];
+ _handlers.Add(typeof(TMessage), handlers);
+ }
+
+ handlers.Add(handler);
+ }
+
+ return new Subscription(this, typeof(TMessage), handler);
+ }
+
+ public void Publish(TMessage message)
+ where TMessage : IWidgetMessage
+ {
+ ArgumentNullException.ThrowIfNull(message);
+
+ Action[] handlers;
+ lock (_gate)
+ {
+ if (!_handlers.TryGetValue(typeof(TMessage), out var registered))
+ return;
+
+ handlers = registered.Cast>().ToArray();
+ }
+
+ foreach (var handler in handlers)
+ handler(message);
+ }
+
+ private void Unsubscribe(Type messageType, Delegate handler)
+ {
+ lock (_gate)
+ {
+ if (!_handlers.TryGetValue(messageType, out var handlers))
+ return;
+
+ handlers.Remove(handler);
+ if (handlers.Count == 0)
+ _handlers.Remove(messageType);
+ }
+ }
+
+ private sealed class Subscription(WidgetMessageBus owner, Type messageType, Delegate handler) : IDisposable
+ {
+ private WidgetMessageBus? _owner = owner;
+
+ public void Dispose()
+ {
+ var owner = Interlocked.Exchange(ref _owner, null);
+ owner?.Unsubscribe(messageType, handler);
+ }
+ }
+}
diff --git a/src/DeskKit.Core/Services/WidgetRegistry.cs b/src/DeskKit.Core/Services/WidgetRegistry.cs
index 580c3be..1c8a100 100644
--- a/src/DeskKit.Core/Services/WidgetRegistry.cs
+++ b/src/DeskKit.Core/Services/WidgetRegistry.cs
@@ -11,16 +11,56 @@ public sealed class WidgetRegistry
private readonly Dictionary _byId = new(StringComparer.OrdinalIgnoreCase);
private readonly List _ordered = [];
+ ///
+ /// Builds a catalogue from the providers registered by the composition root.
+ /// Keeping the catalogue in Core means the shell does not need to know whether
+ /// a provider is built in, supplied by an extension, or loaded by a future
+ /// plugin host.
+ ///
+ public WidgetRegistry(IEnumerable providers)
+ {
+ ArgumentNullException.ThrowIfNull(providers);
+
+ foreach (var provider in providers)
+ Register(provider);
+ }
+
+ /// Creates an empty catalogue for hosts that register providers later.
+ public WidgetRegistry()
+ {
+ }
+
public IReadOnlyList Providers => _ordered;
public void Register(IWidgetProvider provider)
{
ArgumentNullException.ThrowIfNull(provider);
- if (_byId.TryAdd(provider.Descriptor.Id, provider))
- {
- _ordered.Add(provider);
- }
+ if (!TryRegister(provider))
+ throw new ArgumentException(
+ $"A widget provider with ID '{provider.Descriptor.Id}' is already registered.",
+ nameof(provider));
+ }
+
+ ///
+ /// Registers a provider when its ID has not already been claimed.
+ /// Use this only for an optional provider whose absence is acceptable; normal
+ /// application composition should use so a plugin ID
+ /// collision fails at startup instead of silently hiding functionality.
+ ///
+ public bool TryRegister(IWidgetProvider provider)
+ {
+ ArgumentNullException.ThrowIfNull(provider);
+
+ var id = provider.Descriptor.Id;
+ if (string.IsNullOrWhiteSpace(id))
+ throw new ArgumentException("A widget provider must declare a non-empty ID.", nameof(provider));
+
+ if (!_byId.TryAdd(id, provider))
+ return false;
+
+ _ordered.Add(provider);
+ return true;
}
public IWidgetProvider? Find(string widgetId) =>
diff --git a/src/DeskKit.Platform/DeskKit.Platform.csproj b/src/DeskKit.Platform/DeskKit.Platform.csproj
index eb0264d..1709957 100644
--- a/src/DeskKit.Platform/DeskKit.Platform.csproj
+++ b/src/DeskKit.Platform/DeskKit.Platform.csproj
@@ -14,6 +14,7 @@
+
diff --git a/src/DeskKit.Platform/PlatformServiceCollectionExtensions.cs b/src/DeskKit.Platform/PlatformServiceCollectionExtensions.cs
new file mode 100644
index 0000000..404d1b4
--- /dev/null
+++ b/src/DeskKit.Platform/PlatformServiceCollectionExtensions.cs
@@ -0,0 +1,43 @@
+using DeskKit.Core.Abstractions;
+using DeskKit.Platform.Windows;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace DeskKit.Platform;
+
+///
+/// Registers the platform capabilities used by the application shell.
+///
+///
+/// The application deliberately calls one cross-platform composition method. OS
+/// selection stays beside the capability implementations, so adding macOS or
+/// Linux services does not leak conditional platform code into the shell.
+///
+public static class PlatformServiceCollectionExtensions
+{
+ public static IServiceCollection AddDeskKitPlatform(this IServiceCollection services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+
+ services.AddSingleton(_ =>
+ OperatingSystem.IsWindows()
+ ? new WindowsDesktopLayerService()
+ : new NullDesktopLayerService());
+
+ services.AddSingleton(_ =>
+ OperatingSystem.IsWindows()
+ ? new WindowsWindowMaterialService()
+ : new NullWindowMaterialService());
+
+ services.AddSingleton(_ =>
+ OperatingSystem.IsWindows()
+ ? new WindowsAutoStartService()
+ : new NullAutoStartService());
+
+ services.AddSingleton(_ =>
+ OperatingSystem.IsWindows()
+ ? new WindowsShellIconLoader()
+ : new NullShellIconLoader());
+
+ return services;
+ }
+}
diff --git a/src/DeskKit.Widgets/BuiltInWidgets.cs b/src/DeskKit.Widgets/BuiltInWidgets.cs
index a39c96d..d36add2 100644
--- a/src/DeskKit.Widgets/BuiltInWidgets.cs
+++ b/src/DeskKit.Widgets/BuiltInWidgets.cs
@@ -2,23 +2,34 @@
using DeskKit.Widgets.Clock;
using DeskKit.Widgets.QuickLaunch;
using DeskKit.Widgets.StickyNote;
+using Microsoft.Extensions.DependencyInjection;
namespace DeskKit.Widgets;
///
-/// The built-in widget catalogue.
+/// Dependency-injection registrations for the built-in widget catalogue.
///
/// Providers are registered here at compile time. The shell only depends on
/// , so a future plugin loader can add providers
/// from separate assemblies without any change to the shell.
///
///
-public static class BuiltInWidgets
+public static class WidgetServiceCollectionExtensions
{
- public static IReadOnlyList CreateProviders(IShellIconLoader iconLoader) =>
- [
- new ClockWidgetProvider(),
- new StickyNoteWidgetProvider(),
- new QuickLaunchWidgetProvider(iconLoader),
- ];
+ ///
+ /// Adds DeskKit's built-in providers to the host's composition root.
+ /// Extensions use the same registration seam, so the shell never needs a
+ /// catalogue of concrete widget types.
+ ///
+ public static IServiceCollection AddBuiltInWidgets(this IServiceCollection services)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+
+ services.AddSingleton();
+ services.AddSingleton();
+ services.AddSingleton(provider =>
+ new QuickLaunchWidgetProvider(provider.GetRequiredService()));
+
+ return services;
+ }
}
diff --git a/src/DeskKit.Widgets/DeskKit.Widgets.csproj b/src/DeskKit.Widgets/DeskKit.Widgets.csproj
index 2d5617e..0a847ee 100644
--- a/src/DeskKit.Widgets/DeskKit.Widgets.csproj
+++ b/src/DeskKit.Widgets/DeskKit.Widgets.csproj
@@ -8,6 +8,7 @@
+
diff --git a/tests/DeskKit.Core.Tests/WidgetMessageBusTests.cs b/tests/DeskKit.Core.Tests/WidgetMessageBusTests.cs
new file mode 100644
index 0000000..52144e2
--- /dev/null
+++ b/tests/DeskKit.Core.Tests/WidgetMessageBusTests.cs
@@ -0,0 +1,59 @@
+using DeskKit.Core.Abstractions;
+using DeskKit.Core.Services;
+
+namespace DeskKit.Core.Tests;
+
+public sealed class WidgetMessageBusTests
+{
+ [Fact]
+ public void Publish_DeliversOnlyTheMatchingMessageType()
+ {
+ var bus = new WidgetMessageBus();
+ var received = new List();
+
+ using var first = bus.Subscribe(message => received.Add(message.Value));
+ using var second = bus.Subscribe(message => received.Add(message.Value));
+
+ bus.Publish(new ClockChanged("10:00"));
+
+ Assert.Equal(["10:00"], received);
+ }
+
+ [Fact]
+ public void Subscription_DisposeStopsFutureDelivery()
+ {
+ var bus = new WidgetMessageBus();
+ var calls = 0;
+ var subscription = bus.Subscribe(_ => calls++);
+
+ subscription.Dispose();
+ bus.Publish(new ClockChanged("10:00"));
+
+ Assert.Equal(0, calls);
+ }
+
+ [Fact]
+ public void Publish_UsesASnapshotWhenAHandlerDisposesItself()
+ {
+ var bus = new WidgetMessageBus();
+ var calls = 0;
+ IDisposable? subscription = null;
+
+ subscription = bus.Subscribe(_ =>
+ {
+ calls++;
+ subscription!.Dispose();
+ });
+
+ using var second = bus.Subscribe(_ => calls++);
+
+ bus.Publish(new ClockChanged("10:00"));
+ bus.Publish(new ClockChanged("10:01"));
+
+ Assert.Equal(3, calls);
+ }
+
+ private sealed record ClockChanged(string Value) : IWidgetMessage;
+
+ private sealed record NoteChanged(string Value) : IWidgetMessage;
+}
diff --git a/tests/DeskKit.Core.Tests/WidgetRegistryTests.cs b/tests/DeskKit.Core.Tests/WidgetRegistryTests.cs
index c7d9d18..a6cfee9 100644
--- a/tests/DeskKit.Core.Tests/WidgetRegistryTests.cs
+++ b/tests/DeskKit.Core.Tests/WidgetRegistryTests.cs
@@ -28,17 +28,46 @@ public void Find_IsCaseInsensitiveAndReturnsNullForUnknownIds()
}
[Fact]
- public void Register_IgnoresADuplicateId()
+ public void Register_RejectsADuplicateId()
{
var registry = new WidgetRegistry();
var first = new StubProvider("clock");
var second = new StubProvider("clock");
registry.Register(first);
- registry.Register(second);
+ var exception = Assert.Throws(() => registry.Register(second));
Assert.Same(first, registry.Find("clock"));
Assert.Single(registry.Providers);
+ Assert.Contains("clock", exception.Message, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void Constructor_RegistersProvidersInCompositionOrder()
+ {
+ var registry = new WidgetRegistry([
+ new StubProvider("clock"),
+ new StubProvider("note"),
+ ]);
+
+ Assert.Equal(["clock", "note"], registry.Providers.Select(provider => provider.Descriptor.Id));
+ }
+
+ [Fact]
+ public void Register_RejectsAnEmptyId()
+ {
+ var registry = new WidgetRegistry();
+
+ Assert.Throws(() => registry.Register(new StubProvider(" ")));
+ }
+
+ [Fact]
+ public void TryRegister_ReturnsFalseForAnOptionalDuplicate()
+ {
+ var registry = new WidgetRegistry();
+
+ Assert.True(registry.TryRegister(new StubProvider("clock")));
+ Assert.False(registry.TryRegister(new StubProvider("clock")));
}
[Fact]
From 12867cff9c014430857acd1e0b34dc35dc629111 Mon Sep 17 00:00:00 2001
From: HDG <121079795+oniemiddle@users.noreply.github.com>
Date: Fri, 2 Oct 2026 17:19:41 +0800
Subject: [PATCH 2/2] fix restore self-test widget catalogue
---
src/DeskKit.Widgets/BuiltInWidgets.cs | 21 +++++++++++++++++++--
1 file changed, 19 insertions(+), 2 deletions(-)
diff --git a/src/DeskKit.Widgets/BuiltInWidgets.cs b/src/DeskKit.Widgets/BuiltInWidgets.cs
index d36add2..978a20b 100644
--- a/src/DeskKit.Widgets/BuiltInWidgets.cs
+++ b/src/DeskKit.Widgets/BuiltInWidgets.cs
@@ -7,15 +7,32 @@
namespace DeskKit.Widgets;
///
-/// Dependency-injection registrations for the built-in widget catalogue.
+/// Built-in widget catalogue and its dependency-injection registration.
///
/// Providers are registered here at compile time. The shell only depends on
/// , so a future plugin loader can add providers
/// from separate assemblies without any change to the shell.
///
///
-public static class WidgetServiceCollectionExtensions
+public static class BuiltInWidgets
{
+ ///
+ /// Creates the built-in catalogue for hosts that deliberately do not build a
+ /// full service provider, such as the desktop self-test. Application startup
+ /// should normally use instead.
+ ///
+ public static IReadOnlyList CreateProviders(IShellIconLoader iconLoader)
+ {
+ ArgumentNullException.ThrowIfNull(iconLoader);
+
+ return
+ [
+ new ClockWidgetProvider(),
+ new StickyNoteWidgetProvider(),
+ new QuickLaunchWidgetProvider(iconLoader),
+ ];
+ }
+
///
/// Adds DeskKit's built-in providers to the host's composition root.
/// Extensions use the same registration seam, so the shell never needs a