Skip to content

Commit c5331f2

Browse files
committed
refactor(tray): reduce orchestration owner overhead
Remove unused coordinator interfaces and callback compatibility paths, keep settings application synchronous and serialized, and trim tests for deleted protocols. Co-authored-by: Copilot App <[email protected]> Copilot-Session: c9ce1f9c-5e46-4d33-bd1a-d670a04e36a6
1 parent 260f287 commit c5331f2

25 files changed

Lines changed: 350 additions & 1377 deletions

‎docs/ARCHITECTURE.md‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
7575
| Tray-menu semantic composition and connection-toggle state | `TrayMenuPresenter` + `ConnectionTogglePresenter` | authoritative |
7676
| App-owned non-tray window creation, reuse, focus, theme, and lifetime | `IWindowManager` + `WindowManager` | authoritative |
7777
| Tray icon, popup coordination, live status, and callback lifetime | `ITrayController` + `TrayController` | authoritative |
78-
| Deep-link/protocol/toast/forwarded activation normalization, current-user IPC, and semantic activation plans | `IActivationRouter` + `ActivationRouter` | authoritative |
79-
| Post-save settings change effect ordering, detached snapshot comparison, and reentrancy | `ISettingsChangeCoordinator` + `SettingsChangeCoordinator` | authoritative |
80-
| Exactly-once ordered app shutdown sequencing | `IAppShutdownCoordinator` + `AppShutdownCoordinator` | authoritative |
78+
| Deep-link/protocol/toast/forwarded activation normalization, current-user IPC, and semantic activation plans | `ActivationRouter` | authoritative |
79+
| Post-save settings change effect ordering, detached snapshot comparison, and concurrent save serialization | `SettingsChangeCoordinator` | authoritative |
80+
| Exactly-once ordered app shutdown sequencing | `AppShutdownCoordinator` | authoritative |
8181
| App composition-root startup sequencing | `AppBootstrapper` (planned) | planned |
8282
| Capability UI metadata | `NodeCapabilityUiCatalog` (planned) | planned |
8383
| Capability registration/gating | `NodeCapabilityRegistrationPolicy` (planned) | planned |
@@ -89,7 +89,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
8989

9090
| If you are editing… | Do not grow it. Extract toward… |
9191
| --- | --- |
92-
| `src/OpenClaw.Tray.WinUI/App.xaml.cs` | use the authoritative `IWindowManager`, `ITrayController`, `IActivationRouter`, `ISettingsChangeCoordinator`, and `IAppShutdownCoordinator`; the remaining A3 extraction target is startup sequencing into `AppBootstrapper` (planned/deferred) |
92+
| `src/OpenClaw.Tray.WinUI/App.xaml.cs` | use the authoritative `IWindowManager`, `ITrayController`, `ActivationRouter`, `SettingsChangeCoordinator`, and `AppShutdownCoordinator`; the remaining A3 extraction target is startup sequencing into `AppBootstrapper` (planned/deferred) |
9393
| `src/OpenClaw.Tray.WinUI/Windows/HubWindow.xaml.cs` | navigation/catalog policy → `HubPageRegistry`; notification banner projection → `AppNotificationInfoBarPresenter`; keep Frame, NavigationView, back-stack mutation, control application, and route side effects in the view |
9494
| `src/OpenClaw.Tray.WinUI/Services/TrayMenuRenderer.cs` | semantic composition → `TrayMenuPresenter`; connection toggle projection → `ConnectionTogglePresenter`; keep WinUI control construction and callback application in the renderer |
9595
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs` | `ChatSendQueue`, `ChatBridgeEventPump`, `ChatHistoryLoader`, `ChatSnapshotProjector`, `AttachmentMetadataStore`; pure native tool projection stays in `NativeToolProjector` |
@@ -152,12 +152,12 @@ leading and trailing pipe. Columns, in order:
152152
| app-tray-surface-ownership-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete tray icon, root menu, weak live-control state, event subscriptions, popup build coordination, and resource disposal | ITrayController + TrayController | immutable snapshot and action callbacks plus state-change triggers only | App cannot regain tray controls or popup lifetime and TrayController cannot duplicate A1 semantic projection or TrayMenuWindow native mechanics | AppSurfaceOwnershipContractTests.App_DelegatesConcreteTrayAndWindowOwnership | source-shape | when the WinUI tray surface is replaced |
153153
| native-tool-projector | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | pure native tool identity, allowlisted display arguments, payload extraction, and flattened-history detection/classification/summary | NativeToolProjector | provider calls the projector while retaining stateful live/history application and metadata cache behavior | unknown identities remain truthful Tool; title aliases are strict; display arguments are allowlisted, redacted, and bounded; live/history projection stays consistent | NativeToolProjectorTests.ExtractToolIdentity_TitleRequiresExactTrustedAlias | behavioral | - |
154154
| provider-native-tool-projection-closed | closed | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | private static copies of native tool identity, display argument, payload, and flattened-history projection | NativeToolProjector | provider owns run/session/legacy-generation correlation, metadata cache persistence/upsert/migration/matching, active run IDs, and timeline state | provider does not regain pure native tool projection or duplicate NativeToolProjector compatibility wrappers | review-only: the provider retains stateful orchestration and calls the focused projector directly | review-only | when OpenClawChatDataProvider no longer applies native tool events or history |
155-
| app-activation-router | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/protocol/toast/forwarded activation normalization, current-user IPC, input guards, and confirmation decisions | IActivationRouter + ActivationRouter | App.ActivationRouter.cs implements IActivationPlanSink only and applies exactly one typed semantic plan through existing A2 owners and services | launch, protocol, toast, and forwarded activation resolve to the same routes; current-user IPC, oversized-payload rejection, and confirmation/redaction semantics are preserved | ActivationRouterTests.ForwardThenListen_DispatchesRouteFromForwardedDeepLink | behavioral | - |
156-
| app-activation-router-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete deep-link IPC, toast argument routing, and single-instance forwarding production logic | IActivationRouter + ActivationRouter | App.ActivationRouter.cs implements IActivationPlanSink only, dispatching one typed plan per activation | App does not regain a parallel activation production path outside ActivationRouter | AppRefactorContractTests.ToastActivation_RoutesOnUiThread | source-shape | when App is replaced as the WinUI composition root |
157-
| app-settings-change-coordinator | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | detached snapshot comparison, SettingsChangeClassifier use, and the full post-save effect order | ISettingsChangeCoordinator + SettingsChangeCoordinator | App implements narrow connection/runtime/surface effect ports and triggers ApplyAsync from one explicit post-save call | browser proxy sync, reconnect, MCP, hotkey, autostart, telemetry, and surface notification order is preserved; MCP-only behavior and credential precedence are unaffected | SettingsChangeCoordinatorTests.ApplyAsync_GatewayUrlChange_RunsFullReconnectWithPrepare | behavioral | - |
158-
| app-settings-change-coordinator-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | OnSettingsSaved impact classification, reconnect switch, and inline effect ordering | ISettingsChangeCoordinator + SettingsChangeCoordinator | App.SettingsChangeCoordinator.cs implements effect-port adapters only; OnSettingsSaved forwards to ApplyAsync | App does not regain a parallel settings-change orchestration path outside SettingsChangeCoordinator | PresentationSeamContractTests.App_AppliesToolCallVisibilityFromPersistedSettings | source-shape | when App is replaced as the WinUI composition root |
159-
| app-shutdown-coordinator | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | first-wins shared shutdown task, ordered step execution, and per-step log/catch/continue | IAppShutdownCoordinator + AppShutdownCoordinator | App builds the immutable step plan from services it owns, including activation null-before-await and failure-safe captured-resource nulling, and constructs the BeginShutdown/ExitApplication actions | shutdown steps run in the same order exactly once even under concurrent callers; each step logs and continues past failure; Exit is called exactly once after all steps | AppShutdownCoordinatorTests.ShutdownAsync_RunsBeginStepsThenExit_InOrder | behavioral | - |
160-
| app-shutdown-coordinator-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | the _isExiting bool guard, SafeShutdownStep/SafeShutdownStepAsync helpers, and inline ExitApplicationAsync body | IAppShutdownCoordinator + AppShutdownCoordinator | App.AppShutdownCoordinator.cs builds the step plan only; ExitApplicationAsync forwards to ShutdownAsync | App does not regain a parallel exactly-once shutdown guard or step-execution loop outside AppShutdownCoordinator | AppRefactorContractTests.Shutdown_Order_PreservesAwaitedTeardownBeforeExit | source-shape | when App is replaced as the WinUI composition root |
155+
| app-activation-router | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/protocol/toast/forwarded activation normalization, current-user IPC, input guards, and confirmation decisions | ActivationRouter | App.ActivationRouter.cs implements IActivationPlanSink only and applies exactly one typed semantic plan through existing A2 owners and services | launch, protocol, toast, and forwarded activation resolve to the same routes; current-user IPC, oversized-payload rejection, and confirmation/redaction semantics are preserved | ActivationRouterTests.ForwardThenListen_DispatchesRouteFromForwardedDeepLink | behavioral | - |
156+
| app-activation-router-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete deep-link IPC, toast argument routing, and single-instance forwarding production logic | ActivationRouter | App.ActivationRouter.cs implements IActivationPlanSink only, dispatching one typed plan per activation | App does not regain a parallel activation production path outside ActivationRouter | AppRefactorContractTests.ToastActivation_RoutesOnUiThread | source-shape | when App is replaced as the WinUI composition root |
157+
| app-settings-change-coordinator | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | detached snapshot comparison, SettingsChangeClassifier use, concurrent save serialization, and the full post-save effect order | SettingsChangeCoordinator | App supplies the existing effects as delegates and triggers synchronous Apply from one explicit post-save call | browser proxy sync, reconnect, MCP, hotkey, autostart, telemetry, and surface notification order is preserved; MCP-only behavior and credential precedence are unaffected | SettingsChangeCoordinatorTests.Apply_GatewayUrlChange_PreparesBeforeReconnect | behavioral | - |
158+
| app-settings-change-coordinator-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | OnSettingsSaved impact classification, reconnect switch, and inline effect ordering | SettingsChangeCoordinator | App.SettingsChangeCoordinator.cs wires effect delegates only; OnSettingsSaved forwards to Apply | App does not regain a parallel settings-change orchestration path outside SettingsChangeCoordinator | PresentationSeamContractTests.App_AppliesToolCallVisibilityFromPersistedSettings | source-shape | when App is replaced as the WinUI composition root |
159+
| app-shutdown-coordinator | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | first-wins shared shutdown task, ordered step execution, and per-step log/catch/continue | AppShutdownCoordinator | App builds the immutable step plan from services it owns, including activation null-before-await and failure-safe captured-resource nulling, and constructs the BeginShutdown/ExitApplication actions | shutdown steps run in the same order exactly once even under concurrent callers; each step logs and continues past failure; Exit is called exactly once after all steps | AppShutdownCoordinatorTests.ShutdownAsync_RunsBeginStepsThenExit_InOrder | behavioral | - |
160+
| app-shutdown-coordinator-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | the _isExiting bool guard, SafeShutdownStep/SafeShutdownStepAsync helpers, and inline ExitApplicationAsync body | AppShutdownCoordinator | App.AppShutdownCoordinator.cs builds the step plan only; ExitApplicationAsync forwards to ShutdownAsync | App does not regain a parallel exactly-once shutdown guard or step-execution loop outside AppShutdownCoordinator | AppRefactorContractTests.Shutdown_Order_PreservesAwaitedTeardownBeforeExit | source-shape | when App is replaced as the WinUI composition root |
161161
| 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 |
162162
| 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 |
163163
| 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 |

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -182,13 +182,6 @@ private AppShutdownPlan BuildShutdownPlan()
182182
return ValueTask.CompletedTask;
183183
}));
184184

185-
steps.Add(new AppShutdownStep("settings coordinator", () =>
186-
{
187-
_settingsChangeCoordinator?.Dispose();
188-
_settingsChangeCoordinator = null;
189-
return ValueTask.CompletedTask;
190-
}));
191-
192185
// Dispose the DI composition root. The container only owns the presentation
193186
// infrastructure it created (navigation scope manager + any open page-view-model scope).
194187
// App-owned services were registered as pre-built instances, so this does not re-dispose
@@ -223,6 +216,7 @@ private AppShutdownPlan BuildShutdownPlan()
223216
return new AppShutdownPlan(
224217
BeginShutdown: () =>
225218
{
219+
_settingsChangeCoordinator = null;
226220
_windowManager?.BeginShutdown();
227221
_trayController?.BeginShutdown();
228222
Logger.Info("Application exiting");

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

Lines changed: 22 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,36 @@
11
using OpenClaw.Shared;
22
using OpenClawTray.Services;
33
using System;
4-
using System.Threading;
5-
using System.Threading.Tasks;
64

75
namespace OpenClawTray;
86

9-
/// <summary>
10-
/// App's <see cref="ISettingsConnectionEffects"/>/<see cref="ISettingsRuntimeEffects"/>/
11-
/// <see cref="ISettingsSurfaceEffects"/> implementations, and the single explicit post-save
12-
/// trigger (<see cref="OnSettingsSaved"/>) that hands a detached <see cref="SettingsData"/>
13-
/// snapshot to <see cref="SettingsChangeCoordinator"/>. App never classifies impact or orders
14-
/// effects itself; every step below is a thin adapter onto an existing App method or field.
15-
/// </summary>
16-
public partial class App : ISettingsConnectionEffects, ISettingsRuntimeEffects, ISettingsSurfaceEffects
7+
public partial class App
178
{
189
private SettingsChangeCoordinator? _settingsChangeCoordinator;
1910

2011
private void OnSettingsSaved(object? sender, EventArgs e)
2112
{
22-
var settings = _settings;
23-
var coordinator = _settingsChangeCoordinator;
24-
if (settings == null || coordinator == null)
13+
if (_settings == null)
2514
return;
2615

27-
ObserveBackgroundFault(
28-
coordinator.ApplyAsync(
29-
new SettingsChangeRequest(PersistedVersion: null, settings.ToSettingsData()),
30-
CancellationToken.None),
31-
"[App] Failed to apply saved settings");
16+
_settingsChangeCoordinator?.Apply(_settings.ToSettingsData());
3217
}
3318

34-
void ISettingsConnectionEffects.SyncActiveGatewayBrowserProxyForward(SettingsData settings) =>
35-
SyncActiveGatewayBrowserProxyForward();
36-
37-
void ISettingsConnectionEffects.PrepareFullReconnect(SettingsData settings)
19+
private SettingsChangeCoordinator CreateSettingsChangeCoordinator(SettingsData initialSettings) =>
20+
new(
21+
new SettingsChangeEffects(
22+
settings => OpenClawTray.Chat.OpenClawReactorChatRoot.SetToolCallsVisible(settings.ShowChatToolCalls),
23+
SyncActiveGatewayBrowserProxyForward,
24+
PublishSandboxRiskNotificationIfNeeded,
25+
PrepareFullReconnect,
26+
ReconnectWithSyncedBrowserProxyForward,
27+
ApplyMcpRuntime,
28+
ApplyGlobalHotkey,
29+
ApplyAutoStartAndTelemetry,
30+
ApplySettingsSurface),
31+
initialSettings);
32+
33+
private void PrepareFullReconnect(SettingsData settings)
3834
{
3935
_appState!.GatewaySelf = null;
4036
if (!settings.UseSshTunnel)
@@ -48,20 +44,11 @@ void ISettingsConnectionEffects.PrepareFullReconnect(SettingsData settings)
4844
_windowManager?.ResetChatForCredentialChange();
4945
}
5046

51-
void ISettingsConnectionEffects.ReconnectWithSyncedBrowserProxyForward() =>
52-
ReconnectWithSyncedBrowserProxyForward();
53-
54-
void ISettingsRuntimeEffects.ApplyChatToolCallVisibility(SettingsData settings) =>
55-
OpenClawTray.Chat.OpenClawReactorChatRoot.SetToolCallsVisible(settings.ShowChatToolCalls);
56-
57-
void ISettingsRuntimeEffects.PublishSandboxRiskNotification() =>
58-
PublishSandboxRiskNotificationIfNeeded();
59-
6047
// Handle the MCP server lifecycle separately from gateway reconnects because MCP-only mode
6148
// doesn't involve a gateway at all. SetMcpEnabled checks actual runtime state
6249
// (_mcpServer != null), so it's safe to call unconditionally. Only create NodeService when
6350
// MCP is being enabled or the service already exists.
64-
void ISettingsRuntimeEffects.ApplyMcpRuntime(SettingsData settings)
51+
private void ApplyMcpRuntime(SettingsData settings)
6552
{
6653
if (_settings == null || (_nodeService == null && !settings.EnableMcpServer))
6754
return;
@@ -79,7 +66,7 @@ void ISettingsRuntimeEffects.ApplyMcpRuntime(SettingsData settings)
7966
WireAppCapabilityHandlers();
8067
}
8168

82-
void ISettingsRuntimeEffects.ApplyGlobalHotkey(SettingsData settings)
69+
private void ApplyGlobalHotkey(SettingsData settings)
8370
{
8471
if (settings.GlobalHotkeyEnabled)
8572
{
@@ -96,7 +83,7 @@ void ISettingsRuntimeEffects.ApplyGlobalHotkey(SettingsData settings)
9683
}
9784
}
9885

99-
void ISettingsRuntimeEffects.ApplyAutoStartAndTelemetry(SettingsData settings)
86+
private void ApplyAutoStartAndTelemetry(SettingsData settings)
10087
{
10188
ObserveBackgroundFault(
10289
AutoStartManager.SetAutoStartAsync(settings.AutoStart),
@@ -106,7 +93,7 @@ void ISettingsRuntimeEffects.ApplyAutoStartAndTelemetry(SettingsData settings)
10693

10794
// Apply UI-only settings and notify ad-hoc listeners. This public entry point can be
10895
// invoked from background work, while existing listeners update UI directly.
109-
void ISettingsSurfaceEffects.ApplyOnUiThread(SettingsData settings)
96+
private void ApplySettingsSurface(SettingsData settings)
11097
{
11198
void ApplyUiSettingsAndNotify()
11299
{

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,7 @@ private async Task OnLaunchedAsync(LaunchActivatedEventArgs args)
602602
// Seed chat tool-call visibility from persisted settings so the timeline
603603
// honors the Settings > Chat "Show tool calls and usage" toggle on launch.
604604
OpenClawTray.Chat.OpenClawReactorChatRoot.SetToolCallsVisible(_settings.ShowChatToolCalls);
605-
_settingsChangeCoordinator = new SettingsChangeCoordinator(this, this, this, _settings.ToSettingsData());
605+
_settingsChangeCoordinator = CreateSettingsChangeCoordinator(_settings.ToSettingsData());
606606
_openTelemetryConnection = new OpenTelemetryEndpointConnection();
607607
await _openTelemetryConnection.ApplyAsync(
608608
OpenTelemetryEndpointOptions.FromSettings(_settings));

0 commit comments

Comments
 (0)