Skip to content

Commit 473e764

Browse files
shanselmanCopilot
andcommitted
Fix Start menu activation for running tray app
Co-authored-by: Copilot App <[email protected]>
1 parent 1955282 commit 473e764

4 files changed

Lines changed: 105 additions & 31 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ leading and trailing pipe. Columns, in order:
189189
| chat-content-formatting | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | content text formatting, truncation, content-block seam repair, and trace hashing | ChatContentFormatting | thin provider forwarders (TruncateForChatEntry, LooksLikeSystemControlNote, RepairContentBlockSeams, TruncateChatEvent) kept for existing test call sites; system-note, native tool, and flattened-history projection belongs to NativeToolProjector | content truncation and seam repair output is preserved byte-for-byte while tool identity/classification has one canonical owner | ContentBlockSeamRepairTests.RepairsKnownSeams | behavioral | when provider forwarders are removed and callers use focused owners directly |
190190
| chat-metadata-store | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | live tool/attachment metadata dictionaries, scoped native-tool identity upsert, save locks/timers/versions, atomic JSON persistence, session eviction, and attachment-marker build/escape/rehydration | ChatMetadataStore | ChatConversationState supplies a typed session/reset/correlation write plan; provider retains the public static image-preview cache | metadata persistence, identity-strength upgrade, normalization, bounded eviction, marker security, and generation-aware idempotent reset eviction are owned under the metadata lock without raw attachment bytes on disk | ToolMetaCacheTests.CacheToolMeta_SameToolCallId_UpgradesSpecificIdentityWithoutDuplicate | behavioral | - |
191191
| chat-state-persistence | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | persisted aborted-message IDs plus last-chat-state debounce/version/atomic save lifecycle | ChatStatePersistence | provider retains the nested LastChatState compatibility type and owns bridge history fetch orchestration | corrupted state fails closed, reset removes aborted IDs, stale reset generations cannot persist, and selected/snapshot state writes remain atomic | ChatStatePersistenceTests.ResetFence_RejectsStaleAbortedIds | behavioral | - |
192-
| 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 | - |
192+
| 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; a no-argument secondary launch retries the existing IPC boundary and forwards the default Hub route; current-user IPC, oversized-payload rejection, and confirmation/redaction semantics are preserved | ActivationRouterTests.ForwardLaunchToPrimaryAsync_ListenerStartsLate_RetriesAndDispatchesDefaultHub | behavioral | - |
193193
| 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 |
194194
| 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 | - |
195195
| 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 |

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

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -570,16 +570,11 @@ private async Task OnLaunchedAsync(LaunchActivatedEventArgs args)
570570

571571
if (!ownsMutex)
572572
{
573-
// Forward deep link args to running instance (command-line or protocol activation)
574-
var deepLink = _activationRouter.ResolveLaunchCandidate(new LaunchActivationInput(
573+
await _activationRouter.ForwardLaunchToPrimaryAsync(new LaunchActivationInput(
575574
protocolUri,
576575
_startupArgs,
577576
_postSetupLaunch,
578-
SetupShownDuringStartup: false));
579-
if (deepLink != null)
580-
{
581-
await _activationRouter.ForwardToPrimaryAsync(deepLink, CancellationToken.None);
582-
}
577+
SetupShownDuringStartup: false), CancellationToken.None);
583578
Exit();
584579
return;
585580
}

‎src/OpenClaw.Tray.WinUI/Services/ActivationRouter.cs‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ namespace OpenClawTray.Services;
1313

1414
internal sealed class ActivationRouter : IAsyncDisposable
1515
{
16+
private const int ForwardAttemptCount = 5;
17+
private static readonly TimeSpan ForwardRetryDelay = TimeSpan.FromMilliseconds(100);
1618
private readonly string _protocolScheme;
1719
private readonly string _pipeName;
1820
private readonly object _lifecycleGate = new();
@@ -41,11 +43,35 @@ public ActivationPlan PlanLaunch(LaunchActivationInput input)
4143
if (input.SetupShownDuringStartup)
4244
return new ActivationPlan.Ignore();
4345

44-
var candidate = ResolveLaunchCandidate(input);
46+
var candidate = ResolveExplicitLaunchCandidate(input);
4547
return candidate == null ? new ActivationPlan.Ignore() : PlanFromUri(candidate);
4648
}
4749

48-
public string? ResolveLaunchCandidate(LaunchActivationInput input)
50+
[SupportedOSPlatform("windows")]
51+
public async Task<bool> ForwardLaunchToPrimaryAsync(
52+
LaunchActivationInput input,
53+
CancellationToken cancellationToken)
54+
{
55+
var candidate = ResolveExplicitLaunchCandidate(input);
56+
if (candidate == null && IsNoArgumentLaunch(input))
57+
candidate = $"{_protocolScheme}://hub";
58+
59+
if (candidate == null)
60+
return false;
61+
62+
for (var attempt = 1; attempt <= ForwardAttemptCount; attempt++)
63+
{
64+
if (await ForwardToPrimaryAsync(candidate, cancellationToken).ConfigureAwait(false))
65+
return true;
66+
67+
if (attempt < ForwardAttemptCount)
68+
await Task.Delay(ForwardRetryDelay, cancellationToken).ConfigureAwait(false);
69+
}
70+
71+
return false;
72+
}
73+
74+
private string? ResolveExplicitLaunchCandidate(LaunchActivationInput input)
4975
{
5076
if (!string.IsNullOrEmpty(input.ProtocolUri))
5177
return input.ProtocolUri;
@@ -58,6 +84,11 @@ public ActivationPlan PlanLaunch(LaunchActivationInput input)
5884
: null;
5985
}
6086

87+
private static bool IsNoArgumentLaunch(LaunchActivationInput input) =>
88+
string.IsNullOrEmpty(input.ProtocolUri) &&
89+
input.CommandLineArguments.Count <= 1 &&
90+
string.IsNullOrEmpty(input.PostSetupLaunch);
91+
6192
public ActivationPlan PlanToast(string? argument)
6293
{
6394
var arguments = ToastArguments.Parse(argument);

‎tests/OpenClaw.Tray.Tests/ActivationRouterTests.cs‎

Lines changed: 69 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -158,27 +158,6 @@ public void PlanLaunch_StateChangingRoute_ReturnsConfirmWithRedactedPrompt()
158158
Assert.DoesNotContain("secret-value", confirm.Prompt.RedactedInput);
159159
}
160160

161-
[Fact]
162-
public void ResolveLaunchCandidate_MatchesPlanLaunchPrecedence()
163-
{
164-
var router = CreateRouter();
165-
var input = Input(
166-
args: new[] { "app.exe", $"{Scheme}://dashboard" },
167-
postSetupLaunch: "chat");
168-
169-
Assert.Equal($"{Scheme}://dashboard", router.ResolveLaunchCandidate(input));
170-
}
171-
172-
[Fact]
173-
public void ResolveLaunchCandidate_IgnoresSetupShownFlag()
174-
{
175-
// Unlike PlanLaunch, candidate resolution alone does not gate on setup-shown; the
176-
// secondary-instance forwarding path needs the raw candidate regardless.
177-
var router = CreateRouter();
178-
var input = Input(protocolUri: $"{Scheme}://settings", setupShown: true);
179-
Assert.Equal($"{Scheme}://settings", router.ResolveLaunchCandidate(input));
180-
}
181-
182161
#endregion
183162

184163
#region PlanToast
@@ -352,6 +331,75 @@ public async Task ForwardThenListen_DispatchesRouteFromForwardedDeepLink()
352331
Assert.Equal("settings", hub.Page);
353332
}
354333

334+
[Fact]
335+
public async Task ForwardLaunchToPrimaryAsync_NoArgumentLaunch_DispatchesDefaultHub()
336+
{
337+
var pipeName = UniquePipeName();
338+
await using var listener = new ActivationRouter(Scheme, pipeName);
339+
var forwarder = new ActivationRouter(Scheme, pipeName);
340+
var sink = new FakeSink();
341+
342+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
343+
await listener.StartForwardedActivationListenerAsync(sink, cts.Token);
344+
345+
Assert.True(await forwarder.ForwardLaunchToPrimaryAsync(
346+
Input(args: new[] { "app.exe" }),
347+
cts.Token));
348+
349+
var deadline = DateTime.UtcNow.AddSeconds(5);
350+
while (sink.Dispatched.Count == 0 && DateTime.UtcNow < deadline)
351+
await Task.Delay(25, cts.Token);
352+
353+
var route = Assert.Single(sink.Dispatched);
354+
var hub = Assert.IsType<ActivationRoute.OpenHub>(route);
355+
Assert.Null(hub.Page);
356+
}
357+
358+
[Fact]
359+
public async Task ForwardLaunchToPrimaryAsync_ListenerStartsLate_RetriesAndDispatchesDefaultHub()
360+
{
361+
var pipeName = UniquePipeName();
362+
await using var listener = new ActivationRouter(Scheme, pipeName);
363+
var forwarder = new ActivationRouter(Scheme, pipeName);
364+
var sink = new FakeSink();
365+
366+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
367+
var forwardTask = forwarder.ForwardLaunchToPrimaryAsync(
368+
Input(args: new[] { "app.exe" }),
369+
cts.Token);
370+
await Task.Delay(1200, cts.Token);
371+
await listener.StartForwardedActivationListenerAsync(sink, cts.Token);
372+
373+
Assert.True(await forwardTask);
374+
375+
var deadline = DateTime.UtcNow.AddSeconds(5);
376+
while (sink.Dispatched.Count == 0 && DateTime.UtcNow < deadline)
377+
await Task.Delay(25, cts.Token);
378+
379+
var route = Assert.Single(sink.Dispatched);
380+
var hub = Assert.IsType<ActivationRoute.OpenHub>(route);
381+
Assert.Null(hub.Page);
382+
}
383+
384+
[Fact]
385+
public async Task ForwardLaunchToPrimaryAsync_UnknownArgument_DoesNotDispatch()
386+
{
387+
var pipeName = UniquePipeName();
388+
await using var listener = new ActivationRouter(Scheme, pipeName);
389+
var forwarder = new ActivationRouter(Scheme, pipeName);
390+
var sink = new FakeSink();
391+
392+
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
393+
await listener.StartForwardedActivationListenerAsync(sink, cts.Token);
394+
395+
var sent = await forwarder.ForwardLaunchToPrimaryAsync(
396+
Input(args: new[] { "app.exe", "--unknown" }),
397+
cts.Token);
398+
399+
Assert.False(sent);
400+
Assert.Empty(sink.Dispatched);
401+
}
402+
355403
[Fact]
356404
public async Task ForwardToPrimaryAsync_RejectsInvalidUriBeforeConnecting()
357405
{

0 commit comments

Comments
 (0)