Skip to content

Commit 3ff1f43

Browse files
bkudiessCopilot
andcommitted
Add DI composition root and navigation/activation seam for tray view models
Introduce the dependency-injection and navigation plumbing that page view models will depend on: a root ServiceProvider owned by App, a navigation scope/activation seam, and a UI-thread dispatcher abstraction. This is additive infrastructure only -- no page is converted to MVVM and no existing App behavior is moved. Intended runtime behavior change: none. - Add Microsoft.Extensions.DependencyInjection (10.0.0). App builds one validated root ServiceProvider (ValidateScopes + ValidateOnBuild) after tray init, disposed via an ordered shutdown step. App-owned services (SettingsManager, IAppCommands) are registered as pre-built instances so the container never disposes them (no double-dispose). - Presentation/ WinUI-free core: IUiDispatcher, INavigationAware, INavigationService, IPageActivator, NavigationScopeManager, AppNavigationService, transient Settings/Permissions page-view-model placeholders. - Presentation/Adapters/ WinUI-bound: WinUIDispatcher, FramePageActivator. - HubWindow activation hook (empty page-to-view-model map => runtime no-op). - Ledger: three authoritative rows (ui-dispatcher, navigation-scope, composition-root) with behavioral guard tests; single-source-owner entries. - 20 presentation tests (unit + source-contract, incl. WinUI-free guard). Co-authored-by: Copilot App <[email protected]>
1 parent 4518dd8 commit 3ff1f43

24 files changed

Lines changed: 1780 additions & 0 deletions

‎docs/ARCHITECTURE.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
5454
| Settings test data | `OpenClaw.TestSupport.SettingsDataBuilder` | authoritative |
5555
| JSON `JsonElement` coercion (non-nullable fallback family) | `JsonReadHelpers` | authoritative |
5656
| WSL/POSIX shell quoting | `WslShellQuoting` | authoritative |
57+
| UI-thread marshaling for presentation code | `IUiDispatcher` | authoritative |
58+
| Page view-model activation/deactivation + disposal lifetime | `NavigationScopeManager` | authoritative |
59+
| Presentation-layer DI composition root | `AppServiceRegistration` (root `ServiceProvider`, owned by `App`) | authoritative |
5760
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
5861
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
5962
| Local MCP exposure policy | `McpCapabilityPolicy` (planned) | planned |
@@ -116,6 +119,9 @@ leading and trailing pipe. Columns, in order:
116119
| chat-send-queue | planned | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | send queue/admission/abort state | ChatSendQueue | - | queued send/abort/generation semantics preserved | none | review-only | extracted in Phase 4 |
117120
| gateway-pending-requests | planned | src/OpenClaw.Shared/OpenClawGatewayClient.cs | request-id -> method/completion tracking | PendingRequestRegistry | - | request ids never leak after disconnect; thread-safe | none | review-only | extracted in Phase 4 |
118121
| connect-envelope | planned | src/OpenClaw.Shared/OpenClawGatewayClient.cs + WindowsNodeClient.cs | connect message + auth precedence + signature version | ConnectEnvelopeBuilder | - | credential precedence never downgrades a device token; v3->v2 fallback preserved | none | review-only | extracted in Phase 4 |
122+
| ui-dispatcher | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | UI-thread marshaling abstraction for presentation code | IUiDispatcher | App and existing WinUI code may call DispatcherQueue directly until the view-model migration | presentation view models depend on IUiDispatcher not a concrete DispatcherQueue | UiDispatcherContractTests.PageViewModel_ReceivesRegisteredDispatcher | behavioral | - |
123+
| navigation-scope | authoritative | src/OpenClaw.Tray.WinUI/Windows/HubWindow.xaml.cs | page view-model activation/deactivation and disposal lifetime | NavigationScopeManager | HubWindow keeps frame navigation back-stack and rail selection | transient page view models are activated on navigation and deactivated then disposed on navigate-away | NavigationScopeManagerTests.NavigatingAway_DeactivatesAndDisposesPreviousViewModel | behavioral | - |
124+
| composition-root | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | presentation-layer service construction and wiring | AppServiceRegistration | App remains the composition root and owns non-DI service lifetimes | one validated root ServiceProvider; App-owned singletons registered as instances are never disposed by the container | AppServiceRegistrationTests.Dispose_DoesNotDisposeAppOwnedInstanceSingletons | behavioral | - |
119125
<!-- LEDGER:END -->
120126

121127
## Deferred test builders

‎src/OpenClaw.Tray.WinUI/App.xaml.cs‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
using OpenClawTray.Services;
1414
using OpenClawTray.Windows;
1515
using OpenClaw.Connection;
16+
using Microsoft.Extensions.DependencyInjection;
17+
using OpenClawTray.Presentation;
18+
using OpenClawTray.Presentation.Adapters;
1619
using System;
1720
using System.Collections.Frozen;
1821
using System.Collections.Generic;
@@ -49,6 +52,29 @@ public partial class App : Application, OpenClawTray.Services.IAppCommands
4952
private GatewayConnectionManager? _connectionManager;
5053
private GatewayRegistry? _gatewayRegistry;
5154
private OpenClawTray.Chat.OpenClawChatCoordinator? _chatCoordinator;
55+
56+
/// <summary>
57+
/// Root DI composition root, built once during startup and disposed during
58+
/// shutdown. The container only owns the presentation infrastructure it creates
59+
/// (navigation scope manager + any open page-view-model scope); App-owned
60+
/// services are registered as pre-built instances, so the container never
61+
/// disposes them and there is no double-dispose.
62+
/// </summary>
63+
private ServiceProvider? _services;
64+
65+
/// <summary>
66+
/// Page type → view-model type map used by the navigation activation hook.
67+
/// Currently empty: no page resolves a view model from DI yet, so the activation
68+
/// hook is a runtime no-op. Entries are added here as pages adopt view models.
69+
/// </summary>
70+
private static readonly IReadOnlyDictionary<Type, Type> PageViewModelMap =
71+
new Dictionary<Type, Type>();
72+
73+
/// <summary>The root service provider, or null before startup / after shutdown.</summary>
74+
internal IServiceProvider? Services => _services;
75+
76+
/// <summary>Resolves the page activator used by <c>HubWindow</c>'s navigation hook.</summary>
77+
internal IPageActivator? PageActivator => _services?.GetService<IPageActivator>();
5278
/// <summary>
5379
/// Cached reference to the most recently constructed local-setup engine. Used by
5480
/// <see cref="OnPairingStatusChanged"/> to suppress the "copy pairing command" toast
@@ -403,6 +429,70 @@ private void OnProcessExit(object? sender, EventArgs e)
403429
return null;
404430
}
405431

432+
/// <summary>
433+
/// Builds the root DI composition root exactly once. Registers the WinUI-free
434+
/// core (dispatcher/app-commands/settings as pre-built instances, the navigation
435+
/// scope manager, and transient page view models) plus the WinUI-bound adapters
436+
/// (navigation service + page activator). Built with scope and build-time
437+
/// validation so wiring errors surface at startup rather than first use. No
438+
/// registered service starts work in its constructor.
439+
/// </summary>
440+
private void InitializeServiceProvider()
441+
{
442+
if (_services is not null)
443+
{
444+
return;
445+
}
446+
447+
if (_dispatcherQueue is null || _settings is null)
448+
{
449+
Logger.Warn("Skipping service provider init: dispatcher or settings not ready.");
450+
return;
451+
}
452+
453+
var dispatcher = new WinUIDispatcher(_dispatcherQueue);
454+
var context = new AppServiceContext(dispatcher, this, _settings);
455+
456+
var services = new ServiceCollection();
457+
services.AddOpenClawTrayCore(context);
458+
459+
// WinUI-bound registrations are added here (not in the pure core) so the core
460+
// stays testable in a pure net10 project.
461+
services.AddSingleton<INavigationService>(new AppNavigationService(
462+
dispatcher,
463+
navigate: tag => ((IAppCommands)this).Navigate(tag),
464+
canGoBack: () => _hubWindow is { IsClosed: false } hub && hub.CanGoBack,
465+
goBack: () =>
466+
{
467+
if (_hubWindow is { IsClosed: false } hub)
468+
{
469+
hub.NavigateBack();
470+
}
471+
}));
472+
services.AddSingleton<IPageActivator>(sp => new FramePageActivator(
473+
sp.GetRequiredService<NavigationScopeManager>(),
474+
PageViewModelMap));
475+
476+
try
477+
{
478+
_services = services.BuildServiceProvider(new ServiceProviderOptions
479+
{
480+
ValidateScopes = true,
481+
ValidateOnBuild = true,
482+
});
483+
Logger.Info("Service provider initialized.");
484+
}
485+
catch (Exception ex)
486+
{
487+
// Additive plumbing must never take the tray down. A build/validation
488+
// failure is logged and leaves _services null, so the navigation
489+
// activation hook stays a no-op. Wiring regressions are caught by tests
490+
// (AppServiceRegistrationTests builds with ValidateOnBuild).
491+
_services = null;
492+
Logger.Error($"Service provider initialization failed: {ex}");
493+
}
494+
}
495+
406496
protected override void OnLaunched(LaunchActivatedEventArgs args) =>
407497
AsyncEventHandlerGuard.Run(
408498
() => OnLaunchedAsync(args),
@@ -607,6 +697,11 @@ _dispatcherQueue is null
607697
InitializeTrayIcon();
608698
ShowSurfaceImprovementsTipIfNeeded();
609699

700+
// Build the DI composition root AFTER the tray is up, so additive plumbing
701+
// can never delay or preempt tray initialization. It only needs the
702+
// dispatcher + settings (created above) and failures are non-fatal.
703+
InitializeServiceProvider();
704+
610705
// Initialize connection manager before setup flow.
611706
_gatewayRegistry = new GatewayRegistry(SettingsManager.SettingsDirectoryPath, logger: new AppLogger());
612707
_gatewayRegistry.Load();
@@ -3303,6 +3398,17 @@ internal void ShowHub(string? navigateTo = null, bool activate = true)
33033398
{
33043399
_hubWindow.SettingsSaved -= OnSettingsSaved;
33053400
_hubWindow = null;
3401+
3402+
// Deactivate + dispose the current navigation scope so a page view model
3403+
// (once pages are mapped) does not outlive the window it belonged to.
3404+
try
3405+
{
3406+
PageActivator?.Reset();
3407+
}
3408+
catch (Exception ex)
3409+
{
3410+
Logger.Warn($"[App] Navigation scope reset on hub close failed: {ex.Message}");
3411+
}
33063412
};
33073413

33083414
_hubWindow.BindToAppState();
@@ -4525,6 +4631,22 @@ await SafeShutdownStepAsync("standalone voice service", async () =>
45254631
SafeShutdownStep("keep alive window", () => CloseWindow(_keepAliveWindow));
45264632
_keepAliveWindow = null;
45274633

4634+
// Dispose the DI composition root. The container only owns the presentation
4635+
// infrastructure it created (navigation scope manager + any open page-view-model
4636+
// scope). App-owned services were registered as pre-built instances, so this
4637+
// does not re-dispose them (no double-dispose). Null the field BEFORE awaiting
4638+
// disposal so a queued Frame.Navigated callback during shutdown cannot resolve
4639+
// the page activator against a disposing/disposed provider.
4640+
var services = _services;
4641+
_services = null;
4642+
if (services is not null)
4643+
{
4644+
await SafeShutdownStepAsync("service provider", async () =>
4645+
{
4646+
await services.DisposeAsync();
4647+
});
4648+
}
4649+
45284650
// Dispose tray and mutex
45294651
SafeShutdownStep("tray icon", () =>
45304652
{

‎src/OpenClaw.Tray.WinUI/OpenClaw.Tray.WinUI.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
</ItemGroup>
7272

7373
<ItemGroup>
74+
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.0" />
7475
<PackageReference Include="Microsoft.WindowsAppSDK" Version="$(MicrosoftWindowsAppSDKVersion)" />
7576
<PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="$(MicrosoftWindowsSdkBuildToolsVersion)" />
7677
<PackageReference Include="OpenTelemetry" Version="1.16.0" />
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using Microsoft.UI.Xaml;
2+
3+
namespace OpenClawTray.Presentation.Adapters;
4+
5+
/// <summary>
6+
/// WinUI adapter that implements <see cref="IPageActivator"/>. It maps a navigated
7+
/// page's type to its view-model type, resolves + activates the view model through
8+
/// <see cref="NavigationScopeManager"/>, and assigns it as the page's data context.
9+
/// </summary>
10+
/// <remarks>
11+
/// The page→view-model map is currently empty, so every navigation takes the
12+
/// "no view model" path: the scope manager only deactivates and disposes any prior
13+
/// view model, and a page's <c>DataContext</c> is never touched. This makes the
14+
/// activation hook a runtime no-op until pages adopt view models, at which point their
15+
/// entries are added to the map.
16+
/// </remarks>
17+
internal sealed class FramePageActivator : IPageActivator
18+
{
19+
private readonly NavigationScopeManager _scopes;
20+
private readonly IReadOnlyDictionary<Type, Type> _pageToViewModel;
21+
22+
public FramePageActivator(NavigationScopeManager scopes, IReadOnlyDictionary<Type, Type> pageToViewModel)
23+
{
24+
_scopes = scopes ?? throw new ArgumentNullException(nameof(scopes));
25+
_pageToViewModel = pageToViewModel ?? throw new ArgumentNullException(nameof(pageToViewModel));
26+
}
27+
28+
public void OnNavigatedTo(object page, object? parameter)
29+
{
30+
if (page is null)
31+
{
32+
return;
33+
}
34+
35+
if (_pageToViewModel.TryGetValue(page.GetType(), out var viewModelType))
36+
{
37+
var viewModel = _scopes.Navigate(viewModelType, parameter);
38+
if (page is FrameworkElement element)
39+
{
40+
element.DataContext = viewModel;
41+
}
42+
}
43+
else
44+
{
45+
// No view model mapped for this page yet: advance the scope (deactivate +
46+
// dispose any prior view model) without touching the page's data context.
47+
_scopes.Navigate(null, parameter);
48+
}
49+
}
50+
51+
public void Reset() => _scopes.Reset();
52+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using Microsoft.UI.Dispatching;
2+
3+
namespace OpenClawTray.Presentation.Adapters;
4+
5+
/// <summary>
6+
/// WinUI adapter that implements <see cref="IUiDispatcher"/> over the real
7+
/// <see cref="DispatcherQueue"/>. WinUI-bound; not compiled into the pure test
8+
/// project. The contract itself is covered by <c>IUiDispatcher</c> unit tests via a
9+
/// test double, and this adapter is covered by source-contract tests.
10+
/// </summary>
11+
internal sealed class WinUIDispatcher : IUiDispatcher
12+
{
13+
private readonly DispatcherQueue _queue;
14+
15+
public WinUIDispatcher(DispatcherQueue queue)
16+
{
17+
_queue = queue ?? throw new ArgumentNullException(nameof(queue));
18+
}
19+
20+
public bool HasThreadAccess => _queue.HasThreadAccess;
21+
22+
public bool TryEnqueue(Action action)
23+
{
24+
ArgumentNullException.ThrowIfNull(action);
25+
return _queue.TryEnqueue(() => action());
26+
}
27+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
namespace OpenClawTray.Presentation;
2+
3+
/// <summary>
4+
/// Default <see cref="INavigationService"/> implementation. It forwards navigation
5+
/// requests to delegates supplied by <c>App</c>, which drive the existing
6+
/// <c>HubWindow</c> navigation path. This keeps HubWindow as the single owner of
7+
/// frame navigation, back-stack, and rail selection while giving future view models
8+
/// a WinUI-free navigation surface to depend on.
9+
/// </summary>
10+
/// <remarks>
11+
/// The documented UI-thread affinity is <b>enforced</b>, not just described: mutating
12+
/// operations (<see cref="Navigate"/>, <see cref="GoBack"/>) are marshaled onto the UI
13+
/// thread through <see cref="IUiDispatcher"/>, and the <see cref="CanGoBack"/> read fails
14+
/// fast when called off the UI thread. This prevents a future background view model from
15+
/// touching the WinUI frame off-thread.
16+
/// </remarks>
17+
internal sealed class AppNavigationService : INavigationService
18+
{
19+
private readonly IUiDispatcher _dispatcher;
20+
private readonly Action<string> _navigate;
21+
private readonly Func<bool> _canGoBack;
22+
private readonly Action _goBack;
23+
24+
public AppNavigationService(IUiDispatcher dispatcher, Action<string> navigate, Func<bool> canGoBack, Action goBack)
25+
{
26+
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
27+
_navigate = navigate ?? throw new ArgumentNullException(nameof(navigate));
28+
_canGoBack = canGoBack ?? throw new ArgumentNullException(nameof(canGoBack));
29+
_goBack = goBack ?? throw new ArgumentNullException(nameof(goBack));
30+
}
31+
32+
public void Navigate(string tag) => RunOnUiThread(() => _navigate(tag));
33+
34+
public bool CanGoBack
35+
{
36+
get
37+
{
38+
if (!_dispatcher.HasThreadAccess)
39+
{
40+
throw new InvalidOperationException(
41+
"INavigationService.CanGoBack reflects live WinUI frame state and must be read on the UI thread.");
42+
}
43+
44+
return _canGoBack();
45+
}
46+
}
47+
48+
public void GoBack() => RunOnUiThread(_goBack);
49+
50+
/// <summary>
51+
/// Runs frame-touching work on the UI thread: directly when already on it, otherwise
52+
/// marshaled through the dispatcher so the WinUI frame is never touched off-thread.
53+
/// </summary>
54+
private void RunOnUiThread(Action action)
55+
{
56+
if (_dispatcher.HasThreadAccess)
57+
{
58+
action();
59+
}
60+
else
61+
{
62+
_dispatcher.TryEnqueue(action);
63+
}
64+
}
65+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using OpenClawTray.Services;
2+
3+
namespace OpenClawTray.Presentation;
4+
5+
/// <summary>
6+
/// Carries the already-constructed, App-owned singletons that the composition root
7+
/// registers as pre-built instances. Registering them as instances (rather than
8+
/// letting the container construct them) means the DI container never disposes them,
9+
/// so App keeps sole ownership of their lifetime and there is no double-dispose.
10+
/// </summary>
11+
internal sealed class AppServiceContext
12+
{
13+
public AppServiceContext(IUiDispatcher dispatcher, IAppCommands appCommands, SettingsManager settings)
14+
{
15+
Dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
16+
AppCommands = appCommands ?? throw new ArgumentNullException(nameof(appCommands));
17+
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
18+
}
19+
20+
public IUiDispatcher Dispatcher { get; }
21+
public IAppCommands AppCommands { get; }
22+
public SettingsManager Settings { get; }
23+
}

0 commit comments

Comments
 (0)