Skip to content

Commit ffdec51

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 a7db861 commit ffdec51

7 files changed

Lines changed: 98 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
@@ -28,7 +28,7 @@ private void OnToastActivated(ToastNotificationActivatedEventArgsCompat args)
2828
},
2929
OpenDashboard = () => OpenDashboard(),
3030
OpenSettings = ShowSettings,
31-
OpenChat = ShowWebChat,
31+
OpenChat = sessionKey => ShowWebChat(sessionKey),
3232
OpenActivity = () => ShowHub("channels"),
3333
CopyPairingCommand = command =>
3434
{

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

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

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

6976
/// <summary>
@@ -2460,10 +2467,15 @@ private void OnGatewayNotificationReceived(object? sender, OpenClawNotification
24602467

24612468
if (notification.IsChat)
24622469
{
2463-
builder.AddArgument("action", "open_chat")
2464-
.AddButton(new ToastButton()
2465-
.SetContent("Open Chat")
2466-
.AddArgument("action", "open_chat"));
2470+
builder.AddArgument("action", "open_chat");
2471+
if (!string.IsNullOrEmpty(notification.SessionKey))
2472+
{
2473+
builder.AddArgument("sessionKey", notification.SessionKey);
2474+
}
2475+
builder.AddButton(new ToastButton()
2476+
.SetContent("Open Chat")
2477+
.AddArgument("action", "open_chat")
2478+
.AddArgument("sessionKey", notification.SessionKey ?? ""));
24672479
}
24682480

24692481
_toastService!.ShowToast(builder);
@@ -2869,7 +2881,7 @@ private void OnSettingsSaved(object? sender, EventArgs e)
28692881
}
28702882
}
28712883

2872-
private void ShowWebChat()
2884+
private void ShowWebChat(string? sessionKey = null)
28732885
{
28742886
if (_settings == null) return;
28752887
if (!TryResolveChatCredentials(out _, out _, out _, out var isBootstrapToken))
@@ -2888,6 +2900,17 @@ private void ShowWebChat()
28882900
return;
28892901
}
28902902

2903+
// Stash the session key on both App (fallback when HubWindow doesn't exist)
2904+
// and HubWindow (existing path) so ChatPage can pick it up after navigation.
2905+
if (!string.IsNullOrEmpty(sessionKey))
2906+
{
2907+
PendingChatSessionKey = sessionKey;
2908+
if (_hubWindow != null)
2909+
{
2910+
_hubWindow.PendingChatSessionKey = sessionKey;
2911+
}
2912+
}
2913+
28912914
ShowHub("chat");
28922915
}
28932916

@@ -3550,7 +3573,7 @@ private void HandleDeepLink(string uri)
35503573
CopyActivitySummary = _diagnosticsClipboard!.CopyActivitySummary,
35513574
CopyExtensibilitySummary = _diagnosticsClipboard!.CopyExtensibilitySummary,
35523575
RestartSshTunnel = RestartSshTunnel,
3553-
OpenChat = ShowWebChat,
3576+
OpenChat = () => ShowWebChat(),
35543577
OpenCommandCenter = ShowStatusDetail,
35553578
OpenTrayMenu = ShowTrayMenuPopup,
35563579
OpenActivityStream = ShowActivityStream,

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

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ public sealed partial class ChatPage : Page
3737
private IGatewayConnectionManager? _connectionManager;
3838
private IChatPagePanelHost? _panelHost;
3939
private IChatPagePanelHost PanelHost => _panelHost ??= new ChatPagePanelHost(this);
40+
private string? _pendingWebViewSessionKey;
4041
private static readonly HttpClient s_httpClient = new()
4142
{
4243
Timeout = TimeSpan.FromSeconds(3)
@@ -215,18 +216,20 @@ private void ShowFunctionalSurface()
215216
var provider = app?.ChatProvider;
216217
Func<string, Task>? readAloud = app is null ? null : app.SpeakChatTextAsync;
217218

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

231234
if (_functionalHost is not null
232235
&& ReferenceEquals(_mountedProvider, provider)
@@ -290,6 +293,20 @@ private void ShowFunctionalSurface()
290293

291294
private void ShowWebViewSurface(bool forceNavigate = false)
292295
{
296+
// Consume pending session key for WebView mode.
297+
var pendingSessionKey = _hub?.PendingChatSessionKey
298+
?? (App.Current as App)?.PendingChatSessionKey;
299+
if (!string.IsNullOrEmpty(pendingSessionKey))
300+
{
301+
if (_hub is not null) _hub.PendingChatSessionKey = null;
302+
if (App.Current is App currentApp) currentApp.PendingChatSessionKey = null;
303+
_pendingWebViewSessionKey = pendingSessionKey;
304+
}
305+
else
306+
{
307+
_pendingWebViewSessionKey = null;
308+
}
309+
293310
// Tear down native chat (so the WebView2 owns the row) and (re)init WebView2.
294311
_webViewMode = true;
295312
DisposeFunctionalHost();
@@ -328,7 +345,19 @@ private bool NavigateWebViewToCurrentChatUrl()
328345
return false;
329346

330347
ChatPagePanelStates.ApplyShowingWebView(PanelHost);
331-
WebView.CoreWebView2.Navigate(_chatUrl);
348+
349+
var url = _chatUrl;
350+
if (!string.IsNullOrEmpty(_pendingWebViewSessionKey))
351+
{
352+
var baseUrl = System.Text.RegularExpressions.Regex.Replace(_chatUrl, @"[&?]session=[^&]*", "");
353+
var separator = baseUrl.Contains('?') ? "&" : "?";
354+
url = $"{baseUrl}{separator}session={Uri.EscapeDataString(_pendingWebViewSessionKey)}";
355+
_pendingWebViewSessionKey = null;
356+
}
357+
358+
ErrorPanel.Visibility = Visibility.Collapsed;
359+
WebView.Visibility = Visibility.Visible;
360+
WebView.CoreWebView2.Navigate(url);
332361
return true;
333362
}
334363

@@ -394,7 +423,7 @@ private async Task InitializeWebViewAsync(SettingsManager settings)
394423
return;
395424
}
396425

397-
if (!GatewayChatHelper.TryBuildChatUrl(credential.GatewayUrl, credential.Token, out var chatUrl, out var errorMessage))
426+
if (!GatewayChatHelper.TryBuildChatUrl(credential.GatewayUrl, credential.Token, out var chatUrl, out var errorMessage, _pendingWebViewSessionKey))
398427
{
399428
PlaceholderPanel.Visibility = Visibility.Collapsed;
400429
ErrorPanel.Visibility = Visibility.Visible;
@@ -403,6 +432,7 @@ private async Task InitializeWebViewAsync(SettingsManager settings)
403432
}
404433

405434
_chatUrl = chatUrl;
435+
_pendingWebViewSessionKey = null;
406436

407437
PlaceholderPanel.Visibility = Visibility.Collapsed;
408438
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
@@ -243,6 +243,9 @@ private void OnOpenChat(object sender, RoutedEventArgs e)
243243
{
244244
if (sender is Button btn && btn.Tag is string key)
245245
{
246+
// Stash the target session on both App (fallback when the HubWindow
247+
// doesn't exist yet) and HubWindow (existing path consumed by ChatPage).
248+
CurrentApp.PendingChatSessionKey = key;
246249
if (CurrentApp.ActiveHubWindow is HubWindow hub)
247250
{
248251
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)