-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
2308 lines (2012 loc) · 82.3 KB
/
App.xaml.cs
File metadata and controls
2308 lines (2012 loc) · 82.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using OpenClaw.Shared;
using OpenClaw.Shared.Capabilities;
using OpenClawTray.Dialogs;
using OpenClawTray.Helpers;
using OpenClawTray.Services;
using OpenClawTray.Windows;
using System;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Updatum;
using WinUIEx;
namespace OpenClawTray;
public partial class App : Application
{
private const string PipeName = "OpenClawTray-DeepLink";
internal static readonly UpdatumManager AppUpdater = new("shanselman", "openclaw-windows-hub")
{
FetchOnlyLatestRelease = true,
InstallUpdateSingleFileExecutableName = "OpenClaw.Tray.WinUI",
};
private TrayIcon? _trayIcon;
private OpenClawGatewayClient? _gatewayClient;
private SettingsManager? _settings;
private SshTunnelService? _sshTunnelService;
private GlobalHotkeyService? _globalHotkey;
private System.Timers.Timer? _healthCheckTimer;
private System.Timers.Timer? _sessionPollTimer;
private Mutex? _mutex;
private Microsoft.UI.Dispatching.DispatcherQueue? _dispatcherQueue;
private CancellationTokenSource? _deepLinkCts;
private bool _isExiting;
private ConnectionStatus _currentStatus = ConnectionStatus.Disconnected;
private AgentActivity? _currentActivity;
private ChannelHealth[] _lastChannels = Array.Empty<ChannelHealth>();
private SessionInfo[] _lastSessions = Array.Empty<SessionInfo>();
private GatewayNodeInfo[] _lastNodes = Array.Empty<GatewayNodeInfo>();
private readonly Dictionary<string, SessionPreviewInfo> _sessionPreviews = new();
private readonly object _sessionPreviewsLock = new();
private DateTime _lastPreviewRequestUtc = DateTime.MinValue;
private GatewayUsageInfo? _lastUsage;
private GatewayUsageStatusInfo? _lastUsageStatus;
private GatewayCostUsageInfo? _lastUsageCost;
private DateTime _lastCheckTime = DateTime.Now;
private DateTime _lastUsageActivityLogUtc = DateTime.MinValue;
// FrozenDictionary for O(1) case-insensitive notification type → setting lookup — no per-call allocation.
private static readonly System.Collections.Frozen.FrozenDictionary<string, Func<SettingsManager, bool>> s_notifTypeMap =
new Dictionary<string, Func<SettingsManager, bool>>(StringComparer.OrdinalIgnoreCase)
{
["health"] = s => s.NotifyHealth,
["urgent"] = s => s.NotifyUrgent,
["reminder"] = s => s.NotifyReminder,
["email"] = s => s.NotifyEmail,
["calendar"] = s => s.NotifyCalendar,
["build"] = s => s.NotifyBuild,
["stock"] = s => s.NotifyStock,
["info"] = s => s.NotifyInfo,
["error"] = s => s.NotifyUrgent, // errors follow urgent setting
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
// Session-aware activity tracking
private readonly Dictionary<string, AgentActivity> _sessionActivities = new();
private string? _displayedSessionKey;
private DateTime _lastSessionSwitch = DateTime.MinValue;
private static readonly TimeSpan SessionSwitchDebounce = TimeSpan.FromSeconds(3);
// Windows (created on demand)
private SettingsWindow? _settingsWindow;
private WebChatWindow? _webChatWindow;
private StatusDetailWindow? _statusDetailWindow;
private NotificationHistoryWindow? _notificationHistoryWindow;
private ActivityStreamWindow? _activityStreamWindow;
private TrayMenuWindow? _trayMenuWindow;
private QuickSendDialog? _quickSendDialog;
// Node service (optional, enabled in settings)
private NodeService? _nodeService;
// Keep-alive window to anchor WinUI runtime (prevents GC/threading issues)
private Window? _keepAliveWindow;
private string[]? _startupArgs;
private string? _pendingProtocolUri;
private static readonly string DataPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"OpenClawTray");
private static readonly string CrashLogPath = Path.Combine(DataPath, "crash.log");
private static readonly string RunMarkerPath = Path.Combine(DataPath, "run.marker");
public App()
{
InitializeComponent();
CheckPreviousRun();
MarkRunStarted();
// Hook up crash handlers
this.UnhandledException += OnUnhandledException;
AppDomain.CurrentDomain.UnhandledException += OnDomainUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
private void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
LogCrash("UnhandledException", e.Exception);
e.Handled = true; // Try to prevent crash
}
private void OnDomainUnhandledException(object sender, System.UnhandledExceptionEventArgs e)
{
LogCrash("DomainUnhandledException", e.ExceptionObject as Exception);
}
private void OnUnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs e)
{
LogCrash("UnobservedTaskException", e.Exception);
e.SetObserved(); // Prevent crash
}
private void OnProcessExit(object? sender, EventArgs e)
{
MarkRunEnded();
try
{
Logger.Info($"Process exiting (ExitCode={Environment.ExitCode})");
}
catch { }
}
private static void LogCrash(string source, Exception? ex)
{
try
{
var dir = Path.GetDirectoryName(CrashLogPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
var message = $"\n[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {source}\n{ex}\n";
File.AppendAllText(CrashLogPath, message);
}
catch { /* Can't log the crash logger crash */ }
try
{
if (ex != null)
{
Logger.Error($"CRASH {source}: {ex}");
}
else
{
Logger.Error($"CRASH {source}");
}
}
catch { /* Ignore logging failures */ }
}
private static void CheckPreviousRun()
{
try
{
if (File.Exists(RunMarkerPath))
{
var startedAt = File.ReadAllText(RunMarkerPath);
Logger.Error($"Previous session did not exit cleanly (started {startedAt})");
File.Delete(RunMarkerPath);
}
}
catch { }
}
private static void MarkRunStarted()
{
try
{
var dir = Path.GetDirectoryName(RunMarkerPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllText(RunMarkerPath, DateTime.Now.ToString("O"));
}
catch { }
}
private static void MarkRunEnded()
{
try
{
if (File.Exists(RunMarkerPath))
File.Delete(RunMarkerPath);
}
catch { }
}
/// <summary>
/// Check if the app was launched via protocol activation (MSIX deep link).
/// In WinUI 3, protocol activation is retrieved via AppInstance, not OnActivated.
/// </summary>
private static string? GetProtocolActivationUri()
{
try
{
var activatedArgs = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
if (activatedArgs.Kind == Microsoft.Windows.AppLifecycle.ExtendedActivationKind.Protocol
&& activatedArgs.Data is global::Windows.ApplicationModel.Activation.IProtocolActivatedEventArgs protocolArgs)
{
return protocolArgs.Uri?.ToString();
}
}
catch { /* Not activated via protocol, or not packaged */ }
return null;
}
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
_startupArgs = Environment.GetCommandLineArgs();
_dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();
// Check for protocol activation (MSIX packaged apps receive deep links this way)
string? protocolUri = GetProtocolActivationUri();
// Single instance check - keep mutex alive for app lifetime
_mutex = new Mutex(true, "OpenClawTray", out bool createdNew);
if (!createdNew)
{
// Forward deep link args to running instance (command-line or protocol activation)
var deepLink = protocolUri
?? (_startupArgs.Length > 1 && _startupArgs[1].StartsWith("openclaw://", StringComparison.OrdinalIgnoreCase)
? _startupArgs[1] : null);
if (deepLink != null)
{
SendDeepLinkToRunningInstance(deepLink);
}
Exit();
return;
}
// Store protocol URI for processing after setup
_pendingProtocolUri = protocolUri;
// Initialize settings before update check so skip selections can be remembered.
_settings = new SettingsManager();
// Register URI scheme on first run
DeepLinkHandler.RegisterUriScheme();
// Check for updates before launching
var shouldLaunch = await CheckForUpdatesAsync();
if (!shouldLaunch)
{
Exit();
return;
}
// Register toast activation handler
ToastNotificationManagerCompat.OnActivated += OnToastActivated;
_sshTunnelService = new SshTunnelService(new AppLogger());
_sshTunnelService.TunnelExited += OnSshTunnelExited;
// First-run check
if (string.IsNullOrWhiteSpace(_settings.Token))
{
await ShowFirstRunWelcomeAsync();
}
// Initialize tray icon (window-less pattern from WinUIEx)
InitializeTrayIcon();
ShowSurfaceImprovementsTipIfNeeded();
// Initialize connections - only use operator if node mode is disabled
// (dual connections cause gateway conflicts)
if (_settings?.EnableNodeMode == true)
{
// Node mode: only use node connection (provides health events too)
InitializeNodeService();
}
else
{
// Operator mode: use operator connection
InitializeGatewayClient();
}
// Start health check timer
StartHealthCheckTimer();
// Start deep link server
StartDeepLinkServer();
// Register global hotkey if enabled
if (_settings.GlobalHotkeyEnabled)
{
_globalHotkey = new GlobalHotkeyService();
_globalHotkey.HotkeyPressed += OnGlobalHotkeyPressed;
_globalHotkey.Register();
}
// Process startup deep link (command-line or MSIX protocol activation)
var startupDeepLink = _pendingProtocolUri
?? (_startupArgs.Length > 1 && _startupArgs[1].StartsWith("openclaw://", StringComparison.OrdinalIgnoreCase)
? _startupArgs[1] : null);
if (startupDeepLink != null)
{
HandleDeepLink(startupDeepLink);
}
Logger.Info("Application started (WinUI 3)");
}
private void InitializeKeepAliveWindow()
{
// Create a hidden window to keep the WinUI runtime properly initialized
// This prevents GC/threading issues when creating windows after idle
_keepAliveWindow = new Window();
_keepAliveWindow.Content = new Microsoft.UI.Xaml.Controls.Grid();
_keepAliveWindow.AppWindow.IsShownInSwitchers = false;
// Move off-screen and set minimal size
_keepAliveWindow.AppWindow.MoveAndResize(new global::Windows.Graphics.RectInt32(-32000, -32000, 1, 1));
}
private void InitializeTrayIcon()
{
// Initialize keep-alive window first to anchor WinUI runtime
InitializeKeepAliveWindow();
// Pre-create tray menu window at startup to avoid creation crashes later
InitializeTrayMenuWindow();
var iconPath = IconHelper.GetStatusIconPath(ConnectionStatus.Disconnected);
_trayIcon = new TrayIcon(1, iconPath, "OpenClaw Tray — Disconnected");
_trayIcon.IsVisible = true;
_trayIcon.Selected += OnTrayIconSelected;
_trayIcon.ContextMenu += OnTrayContextMenu;
}
private void InitializeTrayMenuWindow()
{
// Pre-create menu window once - reuse to avoid crash on window creation after idle
_trayMenuWindow = new TrayMenuWindow();
_trayMenuWindow.MenuItemClicked += OnTrayMenuItemClicked;
// Don't close - just hide
}
private void OnTrayIconSelected(TrayIcon sender, TrayIconEventArgs e)
{
// Left-click: show custom popup menu
ShowTrayMenuPopup();
}
private void OnTrayContextMenu(TrayIcon sender, TrayIconEventArgs e)
{
// Right-click: show custom popup menu
ShowTrayMenuPopup();
}
private MenuFlyout BuildTrayMenuFlyout()
{
// Pre-fetch data (fire and forget - flyout will show with cached data)
if (_gatewayClient != null && _currentStatus == ConnectionStatus.Connected)
{
try
{
_ = _gatewayClient.CheckHealthAsync();
_ = _gatewayClient.RequestSessionsAsync();
_ = _gatewayClient.RequestUsageAsync();
}
catch { /* ignore */ }
}
var flyout = new MenuFlyout();
// Brand header
var header = new MenuFlyoutItem { Text = "🦞 Molty", IsEnabled = false };
header.FontWeight = Microsoft.UI.Text.FontWeights.Bold;
flyout.Items.Add(header);
flyout.Items.Add(new MenuFlyoutSeparator());
// Status
var statusIcon = MenuDisplayHelper.GetStatusIcon(_currentStatus);
var statusItem = new MenuFlyoutItem { Text = $"{statusIcon} Status: {_currentStatus}" };
statusItem.Click += (s, e) => ShowStatusDetail();
flyout.Items.Add(statusItem);
// Activity (if any)
if (_currentActivity != null && _currentActivity.Kind != OpenClaw.Shared.ActivityKind.Idle)
{
flyout.Items.Add(new MenuFlyoutItem
{
Text = $"{_currentActivity.Glyph} {_currentActivity.DisplayText}",
IsEnabled = false
});
}
// Usage
if (_lastUsage != null)
{
flyout.Items.Add(new MenuFlyoutItem
{
Text = $"📊 {_lastUsage.DisplayText}",
IsEnabled = false
});
}
flyout.Items.Add(new MenuFlyoutSeparator());
// Sessions
if (_lastSessions.Length > 0)
{
var sessionsMenu = new MenuFlyoutSubItem { Text = $"📋 {string.Format(LocalizationHelper.GetString("Menu_SessionsFormat"), _lastSessions.Length)}" };
foreach (var session in _lastSessions.Take(5))
{
var sessionItem = new MenuFlyoutItem { Text = session.DisplayText };
var sessionKey = session.Key;
sessionItem.Click += (s, e) => OpenDashboard($"sessions/{sessionKey}");
sessionsMenu.Items.Add(sessionItem);
}
flyout.Items.Add(sessionsMenu);
}
// Quick actions
var dashboardItem = new MenuFlyoutItem { Text = "🌐 Open Dashboard" };
dashboardItem.Click += (s, e) => OpenDashboard();
flyout.Items.Add(dashboardItem);
var chatItem = new MenuFlyoutItem { Text = "💬 Web Chat" };
chatItem.Click += (s, e) => ShowWebChat();
flyout.Items.Add(chatItem);
var quickSendItem = new MenuFlyoutItem { Text = "✉️ Quick Send" };
quickSendItem.Click += (s, e) => ShowQuickSend();
flyout.Items.Add(quickSendItem);
var historyItem = new MenuFlyoutItem { Text = "📜 Notification History" };
historyItem.Click += (s, e) => ShowNotificationHistory();
flyout.Items.Add(historyItem);
flyout.Items.Add(new MenuFlyoutSeparator());
// Settings & Exit
var settingsItem = new MenuFlyoutItem { Text = "⚙️ Settings" };
settingsItem.Click += (s, e) => ShowSettings();
flyout.Items.Add(settingsItem);
var logItem = new MenuFlyoutItem { Text = "📄 View Log" };
logItem.Click += (s, e) => OpenLogFile();
flyout.Items.Add(logItem);
flyout.Items.Add(new MenuFlyoutSeparator());
var exitItem = new MenuFlyoutItem { Text = "❌ Exit" };
exitItem.Click += (s, e) => ExitApplication();
flyout.Items.Add(exitItem);
return flyout;
}
private async void ShowTrayMenuPopup()
{
try
{
// Verify dispatcher is still valid
if (_dispatcherQueue == null)
{
Logger.Error("DispatcherQueue is null - cannot show menu");
return;
}
// Pre-fetch latest data before showing menu
if (_gatewayClient != null && _currentStatus == ConnectionStatus.Connected)
{
try
{
// Request fresh data
_ = _gatewayClient.CheckHealthAsync();
_ = _gatewayClient.RequestSessionsAsync();
_ = _gatewayClient.RequestUsageAsync();
// Only wait if we have NO cached session data
// Otherwise show instantly with cached data (feels snappier)
if (_lastSessions.Length == 0)
{
await Task.Delay(200); // Wait for first-time data
}
else
{
await Task.Delay(50); // Brief yield to let fresh data arrive if ready
}
Logger.Info($"Menu data: {_lastSessions.Length} sessions, {_lastChannels.Length} channels");
}
catch (Exception ex)
{
Logger.Warn($"Data fetch error: {ex.Message}");
}
}
// Reuse pre-created window - never create new ones after startup
if (_trayMenuWindow == null)
{
// This shouldn't happen, but recreate if needed
Logger.Warn("TrayMenuWindow was null, recreating");
InitializeTrayMenuWindow();
}
// Rebuild menu content
_trayMenuWindow!.ClearItems();
BuildTrayMenuPopup(_trayMenuWindow);
_trayMenuWindow.SizeToContent();
_trayMenuWindow.ShowAtCursor();
}
catch (Exception ex)
{
LogCrash("ShowTrayMenuPopup", ex);
Logger.Error($"Failed to show tray menu: {ex.Message}");
}
}
private void OnTrayMenuItemClicked(object? sender, string action)
{
switch (action)
{
case "status": ShowStatusDetail(); break;
case "dashboard": OpenDashboard(); break;
case "webchat": ShowWebChat(); break;
case "quicksend": ShowQuickSend(); break;
case "history": ShowNotificationHistory(); break;
case "activity": ShowActivityStream(); break;
case "healthcheck": _ = RunHealthCheckAsync(userInitiated: true); break;
case "settings": ShowSettings(); break;
case "autostart": ToggleAutoStart(); break;
case "log": OpenLogFile(); break;
case "copydeviceid": CopyDeviceIdToClipboard(); break;
case "copynodesummary": CopyNodeSummaryToClipboard(); break;
case "exit": ExitApplication(); break;
default:
if (action.StartsWith("session-reset|", StringComparison.Ordinal))
_ = ExecuteSessionActionAsync("reset", action["session-reset|".Length..]);
else if (action.StartsWith("session-compact|", StringComparison.Ordinal))
_ = ExecuteSessionActionAsync("compact", action["session-compact|".Length..]);
else if (action.StartsWith("session-delete|", StringComparison.Ordinal))
_ = ExecuteSessionActionAsync("delete", action["session-delete|".Length..]);
else if (action.StartsWith("session-thinking|", StringComparison.Ordinal))
{
var split = action.Split('|', 3);
if (split.Length == 3)
_ = ExecuteSessionActionAsync("thinking", split[2], split[1]);
}
else if (action.StartsWith("session-verbose|", StringComparison.Ordinal))
{
var split = action.Split('|', 3);
if (split.Length == 3)
_ = ExecuteSessionActionAsync("verbose", split[2], split[1]);
}
else if (action.StartsWith("session:", StringComparison.Ordinal))
OpenDashboard($"sessions/{action[8..]}");
else if (action.StartsWith("dashboard:", StringComparison.Ordinal))
OpenDashboard(action["dashboard:".Length..]);
else if (action.StartsWith("activity:", StringComparison.Ordinal))
ShowActivityStream(action["activity:".Length..]);
else if (action.StartsWith("channel:", StringComparison.Ordinal))
ToggleChannel(action[8..]);
break;
}
}
private void CopyDeviceIdToClipboard()
{
if (_nodeService?.FullDeviceId == null) return;
try
{
var dataPackage = new global::Windows.ApplicationModel.DataTransfer.DataPackage();
dataPackage.SetText(_nodeService.FullDeviceId);
global::Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
// Show toast confirming copy
ShowToast(new ToastContentBuilder()
.AddText(LocalizationHelper.GetString("Toast_DeviceIdCopied"))
.AddText(string.Format(LocalizationHelper.GetString("Toast_DeviceIdCopiedDetail"), _nodeService.ShortDeviceId)));
}
catch (Exception ex)
{
Logger.Warn($"Failed to copy device ID: {ex.Message}");
}
}
private void CopyNodeSummaryToClipboard()
{
if (_lastNodes.Length == 0) return;
try
{
var lines = _lastNodes.Select(node =>
{
var state = node.IsOnline ? "online" : "offline";
var name = string.IsNullOrWhiteSpace(node.DisplayName) ? node.ShortId : node.DisplayName;
return $"{state}: {name} ({node.ShortId}) · {node.DetailText}";
});
var summary = string.Join(Environment.NewLine, lines);
var dataPackage = new global::Windows.ApplicationModel.DataTransfer.DataPackage();
dataPackage.SetText(summary);
global::Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(dataPackage);
ShowToast(new ToastContentBuilder()
.AddText(LocalizationHelper.GetString("Toast_NodeSummaryCopied"))
.AddText(string.Format(LocalizationHelper.GetString("Toast_NodeSummaryCopiedDetail"), _lastNodes.Length)));
}
catch (Exception ex)
{
Logger.Warn($"Failed to copy node summary: {ex.Message}");
}
}
private async Task ExecuteSessionActionAsync(string action, string sessionKey, string? value = null)
{
if (_gatewayClient == null || string.IsNullOrWhiteSpace(sessionKey)) return;
try
{
if (action is "reset" or "compact" or "delete")
{
var title = action switch
{
"reset" => "Reset session?",
"compact" => "Compact session log?",
"delete" => "Delete session?",
_ => "Confirm session action"
};
var body = action switch
{
"reset" => $"Start a fresh session for '{sessionKey}'?",
"compact" => $"Keep the latest log lines for '{sessionKey}' and archive the rest?",
"delete" => $"Delete '{sessionKey}' and archive its transcript?",
_ => "Continue?"
};
var button = action switch
{
"reset" => "Reset",
"compact" => "Compact",
"delete" => "Delete",
_ => "Continue"
};
var confirmed = await ConfirmSessionActionAsync(title, body, button);
if (!confirmed) return;
}
var sent = action switch
{
"reset" => await _gatewayClient.ResetSessionAsync(sessionKey),
"compact" => await _gatewayClient.CompactSessionAsync(sessionKey, 400),
"delete" => await _gatewayClient.DeleteSessionAsync(sessionKey, deleteTranscript: true),
"thinking" => await _gatewayClient.PatchSessionAsync(sessionKey, thinkingLevel: value),
"verbose" => await _gatewayClient.PatchSessionAsync(sessionKey, verboseLevel: value),
_ => false
};
if (!sent)
{
ShowToast(new ToastContentBuilder()
.AddText(LocalizationHelper.GetString("Toast_SessionActionFailed"))
.AddText(LocalizationHelper.GetString("Toast_SessionActionFailedDetail")));
return;
}
if (action is "thinking" or "verbose")
{
_ = _gatewayClient.RequestSessionsAsync();
}
}
catch (Exception ex)
{
Logger.Warn($"Session action error ({action}): {ex.Message}");
try
{
ShowToast(new ToastContentBuilder()
.AddText(LocalizationHelper.GetString("Toast_SessionActionFailed"))
.AddText(ex.Message));
}
catch { }
}
}
private async Task<bool> ConfirmSessionActionAsync(string title, string body, string actionLabel)
{
var root = _keepAliveWindow?.Content as FrameworkElement;
if (root?.XamlRoot == null) return false;
var dialog = new ContentDialog
{
Title = title,
Content = body,
PrimaryButtonText = actionLabel,
CloseButtonText = "Cancel",
DefaultButton = ContentDialogButton.Close,
XamlRoot = root.XamlRoot
};
var result = await dialog.ShowAsync();
return result == ContentDialogResult.Primary;
}
private static string TruncateMenuText(string text, int maxLength = 96) =>
MenuDisplayHelper.TruncateText(text, maxLength);
private void AddRecentActivity(
string line,
string category = "general",
string? dashboardPath = null,
string? details = null,
string? sessionKey = null,
string? nodeId = null)
{
ActivityStreamService.Add(
category: category,
title: line,
details: details,
dashboardPath: dashboardPath,
sessionKey: sessionKey,
nodeId: nodeId);
}
private List<string> GetRecentActivity(int maxItems)
{
return ActivityStreamService.GetItems(Math.Max(0, maxItems))
.Select(item => $"{item.Timestamp:HH:mm:ss} {item.Title}")
.ToList();
}
private void BuildTrayMenuPopup(TrayMenuWindow menu)
{
// Brand header
menu.AddBrandHeader("🦞", "Molty");
menu.AddSeparator();
// Status
var statusIcon = MenuDisplayHelper.GetStatusIcon(_currentStatus);
menu.AddMenuItem(string.Format(LocalizationHelper.GetString("Menu_StatusFormat"), LocalizationHelper.GetConnectionStatusText(_currentStatus)), statusIcon, "status");
// Activity (if any)
if (_currentActivity != null && _currentActivity.Kind != OpenClaw.Shared.ActivityKind.Idle)
{
menu.AddMenuItem(_currentActivity.DisplayText, _currentActivity.Glyph, "", isEnabled: false);
}
// Usage
if (_lastUsage != null || _lastUsageStatus != null || _lastUsageCost != null)
{
var usageText = _lastUsage?.DisplayText;
if (string.IsNullOrWhiteSpace(usageText) || string.Equals(usageText, "No usage data", StringComparison.Ordinal) || string.Equals(usageText, LocalizationHelper.GetString("Menu_NoUsageData"), StringComparison.Ordinal))
{
usageText = _lastUsageStatus?.Providers.Count > 0
? MenuDisplayHelper.FormatProviderSummary(_lastUsageStatus.Providers.Count)
: LocalizationHelper.GetString("Menu_NoUsageData");
}
menu.AddMenuItem(usageText ?? LocalizationHelper.GetString("Menu_NoUsageData"), "📊", "activity:usage");
if (!string.IsNullOrWhiteSpace(_lastUsage?.ProviderSummary))
{
menu.AddMenuItem(
$"↳ {TruncateMenuText(_lastUsage.ProviderSummary!, 88)}",
"",
"",
isEnabled: false,
indent: true);
}
if (_lastUsageCost is { Days: > 0 } usageCost)
{
menu.AddMenuItem(
$"↳ {usageCost.Days}d cost: ${usageCost.Totals.TotalCost:F2}",
"",
"",
isEnabled: false,
indent: true);
var recent = usageCost.Daily.TakeLast(3).ToArray();
if (recent.Length > 0)
{
menu.AddMenuItem(
$"↳ Last {recent.Length}d: ${recent.Sum(d => d.TotalCost):F2}",
"",
"",
isEnabled: false,
indent: true);
}
}
}
// Node Mode status (if enabled)
if (_settings?.EnableNodeMode == true && _nodeService != null)
{
menu.AddSeparator();
menu.AddHeader("🔌 Node Mode");
if (_nodeService.IsPendingApproval)
{
menu.AddMenuItem(LocalizationHelper.GetString("Menu_NodeWaitingApproval"), "", "", isEnabled: false, indent: true);
menu.AddMenuItem($"ID: {_nodeService.ShortDeviceId}...", "", "copydeviceid", indent: true);
}
else if (_nodeService.IsPaired && _nodeService.IsConnected)
{
menu.AddMenuItem(LocalizationHelper.GetString("Menu_NodePairedConnected"), "", "", isEnabled: false, indent: true);
}
else if (_nodeService.IsConnected)
{
menu.AddMenuItem(LocalizationHelper.GetString("Menu_NodeConnecting"), "", "", isEnabled: false, indent: true);
}
else
{
menu.AddMenuItem(LocalizationHelper.GetString("Menu_NodeDisconnected"), "", "", isEnabled: false, indent: true);
}
}
// Sessions (if any) - show meaningful info like the WinForms version
if (_lastSessions.Length > 0)
{
menu.AddSeparator();
menu.AddMenuItem(string.Format(LocalizationHelper.GetString("Menu_SessionsFormat"), _lastSessions.Length), "💬", "activity:sessions");
var visibleSessions = _lastSessions.Take(3).ToArray();
foreach (var session in visibleSessions)
{
var displayName = session.RichDisplayText;
if (!string.IsNullOrWhiteSpace(session.AgeText))
displayName += $" · {session.AgeText}";
var icon = session.IsMain ? "⭐" : "•";
menu.AddMenuItem(displayName, icon, $"session:{session.Key}", indent: true);
SessionPreviewInfo? preview;
lock (_sessionPreviewsLock)
{
_sessionPreviews.TryGetValue(session.Key, out preview);
}
if (preview != null)
{
var previewText = preview.Items.FirstOrDefault(i => !string.IsNullOrWhiteSpace(i.Text))?.Text;
if (!string.IsNullOrWhiteSpace(previewText))
{
menu.AddMenuItem(
$"↳ {TruncateMenuText(previewText)}",
"",
"",
isEnabled: false,
indent: true);
}
}
var currentThinking = string.IsNullOrWhiteSpace(session.ThinkingLevel) ? "off" : session.ThinkingLevel;
var currentVerbose = string.IsNullOrWhiteSpace(session.VerboseLevel) ? "off" : session.VerboseLevel;
var nextVerbose = string.Equals(currentVerbose, "on", StringComparison.OrdinalIgnoreCase) ? "off" : "on";
menu.AddMenuItem(
$"↳ Thinking: {currentThinking} → high",
"🧠",
$"session-thinking|high|{session.Key}",
indent: true);
menu.AddMenuItem(
$"↳ Verbose: {currentVerbose} → {nextVerbose}",
"📝",
$"session-verbose|{nextVerbose}|{session.Key}",
indent: true);
menu.AddMenuItem(LocalizationHelper.GetString("Menu_ResetSession"), "♻️", $"session-reset|{session.Key}", indent: true);
menu.AddMenuItem(LocalizationHelper.GetString("Menu_CompactLog"), "🗜️", $"session-compact|{session.Key}", indent: true);
if (!session.IsMain && !string.Equals(session.Key, "global", StringComparison.OrdinalIgnoreCase))
menu.AddMenuItem(LocalizationHelper.GetString("Menu_DeleteSession"), "🗑️", $"session-delete|{session.Key}", indent: true);
}
if (_lastSessions.Length > visibleSessions.Length)
menu.AddMenuItem($"+{_lastSessions.Length - visibleSessions.Length} more...", "", "", isEnabled: false, indent: true);
}
// Channels (if any)
if (_lastChannels.Length > 0)
{
menu.AddSeparator();
menu.AddHeader("📡 Channels");
foreach (var channel in _lastChannels)
{
var channelIcon = MenuDisplayHelper.GetChannelStatusIcon(channel.Status);
var channelName = char.ToUpper(channel.Name[0]) + channel.Name[1..];
menu.AddMenuItem(channelName, channelIcon, $"channel:{channel.Name}", indent: true);
}
}
if (_lastNodes.Length > 0)
{
menu.AddSeparator();
menu.AddMenuItem(string.Format(LocalizationHelper.GetString("Menu_NodesFormat"), _lastNodes.Length), "🖥️", "activity:nodes");
var visibleNodes = _lastNodes.Take(3).ToArray();
foreach (var node in visibleNodes)
{
var icon = node.IsOnline ? "🟢" : "⚪";
menu.AddMenuItem(TruncateMenuText(node.DisplayText, 92), icon, "", isEnabled: false, indent: true);
menu.AddMenuItem($"↳ {TruncateMenuText(node.DetailText, 92)}", "", "", isEnabled: false, indent: true);
}
if (_lastNodes.Length > visibleNodes.Length)
menu.AddMenuItem($"+{_lastNodes.Length - visibleNodes.Length} more...", "", "", isEnabled: false, indent: true);
menu.AddMenuItem(LocalizationHelper.GetString("Menu_CopyNodeSummary"), "📋", "copynodesummary", indent: true);
}
var recentActivity = GetRecentActivity(maxItems: 4);
if (recentActivity.Count > 0)
{
menu.AddSeparator();
var totalActivity = ActivityStreamService.GetItems().Count;
menu.AddMenuItem(string.Format(LocalizationHelper.GetString("Menu_RecentActivityFormat"), totalActivity), "⚡", "activity");
foreach (var line in recentActivity)
{
menu.AddMenuItem(TruncateMenuText(line, 94), "", "", isEnabled: false, indent: true);
}
}
menu.AddSeparator();
// Actions
menu.AddMenuItem(LocalizationHelper.GetString("Menu_OpenDashboard"), "🌐", "dashboard");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_OpenWebChat"), "💬", "webchat");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_QuickSend"), "📤", "quicksend");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_ActivityStream"), "⚡", "activity");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_NotificationHistory"), "📋", "history");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_RunHealthCheck"), "🔄", "healthcheck");
menu.AddSeparator();
// Settings
menu.AddMenuItem(LocalizationHelper.GetString("Menu_Settings"), "⚙️", "settings");
var autoStartText = (_settings?.AutoStart ?? false)
? LocalizationHelper.GetString("Menu_AutoStartEnabled")
: LocalizationHelper.GetString("Menu_AutoStart");
menu.AddMenuItem(autoStartText, "🚀", "autostart");
menu.AddSeparator();
menu.AddMenuItem(LocalizationHelper.GetString("Menu_OpenLogFile"), "📄", "log");
menu.AddMenuItem(LocalizationHelper.GetString("Menu_Exit"), "❌", "exit");
}
// Keep the old MenuFlyout method for reference but it won't be used
private void BuildTrayMenu(MenuFlyout flyout)
{
// Brand header
var brandItem = new MenuFlyoutItem
{
Text = "🦞 OpenClaw Tray",
IsEnabled = false
};
flyout.Items.Add(brandItem);
flyout.Items.Add(new MenuFlyoutSeparator());
// Status
var statusIcon = MenuDisplayHelper.GetStatusIcon(_currentStatus);
var statusItem = new MenuFlyoutItem
{
Text = $"{statusIcon} Status: {_currentStatus}"
};
statusItem.Click += (s, e) => ShowStatusDetail();
flyout.Items.Add(statusItem);
// Activity (if any)
if (_currentActivity != null && _currentActivity.Kind != OpenClaw.Shared.ActivityKind.Idle)
{
var activityItem = new MenuFlyoutItem
{
Text = $"{_currentActivity.Glyph} {_currentActivity.DisplayText}",
IsEnabled = false
};
flyout.Items.Add(activityItem);
}
// Usage
if (_lastUsage != null)
{
var usageItem = new MenuFlyoutItem
{
Text = $"📊 {_lastUsage.DisplayText}",
IsEnabled = false
};
flyout.Items.Add(usageItem);
}