Skip to content

Commit c319382

Browse files
author
QQ
committed
Fix chat session routing from Sessions page and toast notifications
Previously, clicking a session in the Sessions tab or a chat toast notification always opened the default/main session instead of the specific session. Changes: - Add App.PendingChatSessionKey as a fallback when HubWindow does not exist (background notifications, closed HubWindow). - Thread sessionKey through ToastActivationRouter (Action<string?>). - Embed sessionKey in chat toast arguments and route it on activation. - ChatPage (functional): consume pending key from both HubWindow and App fallbacks; use !string.IsNullOrEmpty guard to treat empty string as null. - ChatPage (WebView): consume pending key and append &session={key} to the navigation URL, or pass it through GatewayChatHelper on initial WebView init. - SessionsPage: write key to CurrentApp.PendingChatSessionKey in addition to hub.PendingChatSessionKey. - Update tests for the new OpenChat Action<string?> contract. Fixes session routing for both native FunctionalUI and legacy WebView2 chat surfaces.
1 parent dd18d17 commit c319382

7 files changed

Lines changed: 95 additions & 23 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ private void OnToastActivated(ToastNotificationActivatedEventArgsCompat args)
2424
},
2525
OpenDashboard = () => OpenDashboard(),
2626
OpenSettings = ShowSettings,
27-
OpenChat = ShowWebChat,
27+
OpenChat = sessionKey => ShowWebChat(sessionKey),
2828
OpenActivity = () => ShowHub("channels"),
2929
CopyPairingCommand = command =>
3030
{

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,13 @@ public partial class App : Application, OpenClawTray.Services.IAppCommands
6363
/// <summary>The full device ID of the local node service (if running).</summary>
6464
internal string? NodeFullDeviceId => _nodeService?.FullDeviceId;
6565

66+
/// <summary>
67+
/// Session key that the chat surface should select on its next mount.
68+
/// Used when the user clicks a session from SessionsPage or a notification
69+
/// while the HubWindow may not yet exist. Consumed (cleared) by ChatPage.
70+
/// </summary>
71+
public string? PendingChatSessionKey { get; set; }
72+
6673
public OpenClawTray.Chat.OpenClawChatDataProvider? ChatProvider => _chatCoordinator?.Provider;
6774

6875
/// <summary>
@@ -2469,10 +2476,15 @@ private void OnGatewayNotificationReceived(object? sender, OpenClawNotification
24692476

24702477
if (notification.IsChat)
24712478
{
2472-
builder.AddArgument("action", "open_chat")
2473-
.AddButton(new ToastButton()
2474-
.SetContent("Open Chat")
2475-
.AddArgument("action", "open_chat"));
2479+
builder.AddArgument("action", "open_chat");
2480+
if (!string.IsNullOrEmpty(notification.SessionKey))
2481+
{
2482+
builder.AddArgument("sessionKey", notification.SessionKey);
2483+
}
2484+
builder.AddButton(new ToastButton()
2485+
.SetContent("Open Chat")
2486+
.AddArgument("action", "open_chat")
2487+
.AddArgument("sessionKey", notification.SessionKey ?? ""));
24762488
}
24772489

24782490
_toastService!.ShowToast(builder);
@@ -2874,7 +2886,7 @@ private void OnSettingsSaved(object? sender, EventArgs e)
28742886
}
28752887
}
28762888

2877-
private void ShowWebChat()
2889+
private void ShowWebChat(string? sessionKey = null)
28782890
{
28792891
if (_settings == null) return;
28802892
if (!TryResolveChatCredentials(out _, out _, out _, out var isBootstrapToken))
@@ -2893,6 +2905,17 @@ private void ShowWebChat()
28932905
return;
28942906
}
28952907

2908+
// Stash the session key on both App (fallback when HubWindow doesn't exist)
2909+
// and HubWindow (existing path) so ChatPage can pick it up after navigation.
2910+
if (!string.IsNullOrEmpty(sessionKey))
2911+
{
2912+
PendingChatSessionKey = sessionKey;
2913+
if (_hubWindow != null)
2914+
{
2915+
_hubWindow.PendingChatSessionKey = sessionKey;
2916+
}
2917+
}
2918+
28962919
ShowHub("chat");
28972920
}
28982921

@@ -4006,7 +4029,7 @@ private void HandleDeepLink(string uri)
40064029
CopyActivitySummary = _diagnosticsClipboard!.CopyActivitySummary,
40074030
CopyExtensibilitySummary = _diagnosticsClipboard!.CopyExtensibilitySummary,
40084031
RestartSshTunnel = RestartSshTunnel,
4009-
OpenChat = ShowWebChat,
4032+
OpenChat = () => ShowWebChat(),
40104033
OpenCommandCenter = ShowStatusDetail,
40114034
OpenTrayMenu = ShowTrayMenuPopup,
40124035
OpenActivityStream = ShowActivityStream,

‎src/OpenClaw.Tray.WinUI/Pages/ChatPage.xaml.cs‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ public sealed partial class ChatPage : Page
3535
private global::Windows.Foundation.TypedEventHandler<CoreWebView2, CoreWebView2NavigationCompletedEventArgs>? _navCompletedHandler;
3636
private global::Windows.Foundation.TypedEventHandler<CoreWebView2, CoreWebView2NavigationStartingEventArgs>? _navStartingHandler;
3737
private IGatewayConnectionManager? _connectionManager;
38+
private string? _pendingWebViewSessionKey;
3839
private static readonly HttpClient s_httpClient = new()
3940
{
4041
Timeout = TimeSpan.FromSeconds(3)
@@ -213,18 +214,20 @@ private void ShowFunctionalSurface()
213214
var provider = app?.ChatProvider;
214215
Func<string, Task>? readAloud = app is null ? null : app.SpeakChatTextAsync;
215216

216-
// Consume a pending session-key hand-off from SessionsPage so the
217-
// chat root mounts with that thread selected. Any pending key forces
218-
// a remount — _mountedThreadId only records what we asked for, not
219-
// what the user later picked inside the composer's dropdown, so we
220-
// cannot use it to detect "already on the right thread".
221-
var pendingSessionKey = _hub?.PendingChatSessionKey;
222-
if (pendingSessionKey is not null && _hub is not null)
217+
// Consume a pending session-key hand-off from SessionsPage or a
218+
// notification toast so the chat root mounts with that thread selected.
219+
// Any pending key forces a remount — _mountedThreadId only records what
220+
// we asked for, not what the user later picked inside the composer's
221+
// dropdown, so we cannot use it to detect "already on the right thread".
222+
var pendingSessionKey = _hub?.PendingChatSessionKey
223+
?? (App.Current as App)?.PendingChatSessionKey;
224+
if (!string.IsNullOrEmpty(pendingSessionKey))
223225
{
224-
_hub.PendingChatSessionKey = null;
226+
if (_hub is not null) _hub.PendingChatSessionKey = null;
227+
if (App.Current is App currentApp) currentApp.PendingChatSessionKey = null;
225228
}
226229
var threadIdToMount = pendingSessionKey ?? _mountedThreadId;
227-
var forceRemount = pendingSessionKey is not null;
230+
var forceRemount = !string.IsNullOrEmpty(pendingSessionKey);
228231

229232
if (_functionalHost is not null
230233
&& ReferenceEquals(_mountedProvider, provider)
@@ -288,6 +291,20 @@ private void ShowFunctionalSurface()
288291

289292
private void ShowWebViewSurface(bool forceNavigate = false)
290293
{
294+
// Consume pending session key for WebView mode.
295+
var pendingSessionKey = _hub?.PendingChatSessionKey
296+
?? (App.Current as App)?.PendingChatSessionKey;
297+
if (!string.IsNullOrEmpty(pendingSessionKey))
298+
{
299+
if (_hub is not null) _hub.PendingChatSessionKey = null;
300+
if (App.Current is App currentApp) currentApp.PendingChatSessionKey = null;
301+
_pendingWebViewSessionKey = pendingSessionKey;
302+
}
303+
else
304+
{
305+
_pendingWebViewSessionKey = null;
306+
}
307+
291308
// Tear down native chat (so the WebView2 owns the row) and (re)init WebView2.
292309
_webViewMode = true;
293310
DisposeFunctionalHost();
@@ -325,9 +342,18 @@ private bool NavigateWebViewToCurrentChatUrl()
325342
if (string.IsNullOrEmpty(_chatUrl) || WebView.CoreWebView2 is null)
326343
return false;
327344

345+
var url = _chatUrl;
346+
if (!string.IsNullOrEmpty(_pendingWebViewSessionKey))
347+
{
348+
var baseUrl = System.Text.RegularExpressions.Regex.Replace(_chatUrl, @"[&?]session=[^&]*", "");
349+
var separator = baseUrl.Contains('?') ? "&" : "?";
350+
url = $"{baseUrl}{separator}session={Uri.EscapeDataString(_pendingWebViewSessionKey)}";
351+
_pendingWebViewSessionKey = null;
352+
}
353+
328354
ErrorPanel.Visibility = Visibility.Collapsed;
329355
WebView.Visibility = Visibility.Visible;
330-
WebView.CoreWebView2.Navigate(_chatUrl);
356+
WebView.CoreWebView2.Navigate(url);
331357
return true;
332358
}
333359

@@ -392,7 +418,7 @@ private async Task InitializeWebViewAsync(SettingsManager settings)
392418
return;
393419
}
394420

395-
if (!GatewayChatHelper.TryBuildChatUrl(credential.GatewayUrl, credential.Token, out var chatUrl, out var errorMessage))
421+
if (!GatewayChatHelper.TryBuildChatUrl(credential.GatewayUrl, credential.Token, out var chatUrl, out var errorMessage, _pendingWebViewSessionKey))
396422
{
397423
PlaceholderPanel.Visibility = Visibility.Collapsed;
398424
ErrorPanel.Visibility = Visibility.Visible;
@@ -401,6 +427,7 @@ private async Task InitializeWebViewAsync(SettingsManager settings)
401427
}
402428

403429
_chatUrl = chatUrl;
430+
_pendingWebViewSessionKey = null;
404431

405432
PlaceholderPanel.Visibility = Visibility.Collapsed;
406433
ErrorPanel.Visibility = Visibility.Collapsed;

‎src/OpenClaw.Tray.WinUI/Pages/SessionsPage.xaml.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,9 @@ private void OnOpenChat(object sender, RoutedEventArgs e)
242242
{
243243
if (sender is Button btn && btn.Tag is string key)
244244
{
245+
// Stash the target session on both App (fallback when the HubWindow
246+
// doesn't exist yet) and HubWindow (existing path consumed by ChatPage).
247+
CurrentApp.PendingChatSessionKey = key;
245248
if (CurrentApp.ActiveHubWindow is HubWindow hub)
246249
{
247250
hub.PendingChatSessionKey = key;

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ public sealed class ToastActivationActions
55
public required Action<string> OpenUrl { get; init; }
66
public required Action OpenDashboard { get; init; }
77
public required Action OpenSettings { get; init; }
8-
public required Action OpenChat { get; init; }
8+
public required Action<string?> OpenChat { get; init; }
99
public required Action OpenActivity { get; init; }
1010
public required Action<string> CopyPairingCommand { get; init; }
1111
}
@@ -34,7 +34,8 @@ public static void Route(
3434
actions.OpenSettings();
3535
break;
3636
case "open_chat":
37-
actions.OpenChat();
37+
var sessionKey = getArgument("sessionKey");
38+
actions.OpenChat(sessionKey);
3839
break;
3940
case "open_activity":
4041
actions.OpenActivity();

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ public void ToastActivation_RoutesOnUiThread()
9595
Assert.Contains("ToastActivationRouter.Route", method);
9696
Assert.Contains("OpenDashboard = () => OpenDashboard()", method);
9797
Assert.Contains("OpenSettings = ShowSettings", method);
98-
Assert.Contains("OpenChat = ShowWebChat", method);
98+
Assert.Contains("OpenChat = sessionKey => ShowWebChat(sessionKey)", method);
9999
Assert.Contains("OpenActivity = () => ShowHub(\"channels\")", method);
100100
Assert.Contains("CopyPairingCommand = command =>", method);
101101
}

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

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ public sealed class ToastActivationRouterTests
77
[Theory]
88
[InlineData("open_dashboard", "dashboard")]
99
[InlineData("open_settings", "settings")]
10-
[InlineData("open_chat", "chat")]
10+
[InlineData("open_chat", "chat:(null)")]
1111
[InlineData("open_activity", "activity")]
1212
public void Route_DispatchesSimpleActions(string action, string expected)
1313
{
@@ -57,6 +57,24 @@ public void Route_CopyPairingCommand_RequiresCommandArgument()
5757
Assert.Equal(["copy:openclaw pair approve abc"], calls);
5858
}
5959

60+
[Fact]
61+
public void Route_OpenChat_PassesSessionKeyArgument()
62+
{
63+
var calls = new List<string>();
64+
65+
ToastActivationRouter.Route(
66+
"open_chat",
67+
key => key == "sessionKey" ? "agent:main:scratch" : null,
68+
BuildActions(calls));
69+
70+
ToastActivationRouter.Route(
71+
"open_chat",
72+
_ => null,
73+
BuildActions(calls));
74+
75+
Assert.Equal(["chat:agent:main:scratch", "chat:(null)"], calls);
76+
}
77+
6078
[Fact]
6179
public void Route_UnknownAction_NoOps()
6280
{
@@ -75,7 +93,7 @@ public void Route_UnknownAction_NoOps()
7593
OpenUrl = url => calls.Add($"url:{url}"),
7694
OpenDashboard = () => calls.Add("dashboard"),
7795
OpenSettings = () => calls.Add("settings"),
78-
OpenChat = () => calls.Add("chat"),
96+
OpenChat = key => calls.Add($"chat:{key ?? "(null)"}"),
7997
OpenActivity = () => calls.Add("activity"),
8098
CopyPairingCommand = command => calls.Add($"copy:{command}")
8199
};

0 commit comments

Comments
 (0)