-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
2287 lines (2026 loc) · 91.2 KB
/
MainWindow.xaml.cs
File metadata and controls
2287 lines (2026 loc) · 91.2 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
/*
* Copyright (c) 2026 Erik Darling, Darling Data LLC
*
* This file is part of the SQL Server Performance Monitor Lite.
*
* Licensed under the MIT License. See LICENSE file in the project root for full license information.
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Xml.Linq;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using PerformanceMonitorLite.Controls;
using PerformanceMonitorLite.Database;
using PerformanceMonitorLite.Mcp;
using PerformanceMonitorLite.Models;
using PerformanceMonitorLite.Services;
using PerformanceMonitorLite.Windows;
namespace PerformanceMonitorLite;
public partial class MainWindow : Window
{
private readonly DuckDbInitializer _databaseInitializer;
private readonly ServerManager _serverManager;
private readonly ScheduleManager _scheduleManager;
private RemoteCollectorService? _collectorService;
private CollectionBackgroundService? _backgroundService;
private CancellationTokenSource? _backgroundCts;
private SystemTrayService? _trayService;
private readonly Dictionary<string, TabItem> _openServerTabs = new();
private readonly Dictionary<string, bool> _previousConnectionStates = new();
private readonly Dictionary<string, bool> _previousCollectorErrorStates = new();
private readonly Dictionary<string, DateTime> _lastCpuAlert = new();
private readonly Dictionary<string, DateTime> _lastBlockingAlert = new();
private readonly Dictionary<string, DateTime> _lastDeadlockAlert = new();
private readonly Dictionary<string, DateTime> _lastPoisonWaitAlert = new();
private readonly Dictionary<string, DateTime> _lastLongRunningQueryAlert = new();
private readonly Dictionary<string, DateTime> _lastTempDbSpaceAlert = new();
private readonly Dictionary<string, DateTime> _lastLongRunningJobAlert = new();
private readonly DispatcherTimer _statusTimer;
private LocalDataService? _dataService;
private McpHostService? _mcpService;
private readonly AlertStateService _alertStateService = new();
private readonly MuteRuleService _muteRuleService;
private EmailAlertService _emailAlertService;
/* Track active alert states for resolved notifications */
private readonly Dictionary<string, bool> _activeCpuAlert = new();
private readonly Dictionary<string, bool> _activeBlockingAlert = new();
private readonly Dictionary<string, bool> _activeDeadlockAlert = new();
private readonly Dictionary<string, bool> _activePoisonWaitAlert = new();
private readonly Dictionary<string, bool> _activeLongRunningQueryAlert = new();
private readonly Dictionary<string, bool> _activeTempDbSpaceAlert = new();
private readonly Dictionary<string, bool> _activeLongRunningJobAlert = new();
public MainWindow()
{
InitializeComponent();
// Initialize services (with loggers wired to AppLogger)
_databaseInitializer = new DuckDbInitializer(App.DatabasePath, new AppLoggerAdapter<DuckDbInitializer>());
_emailAlertService = new EmailAlertService(_databaseInitializer);
_muteRuleService = new MuteRuleService(_databaseInitializer);
_serverManager = new ServerManager(App.ConfigDirectory, logger: new AppLoggerAdapter<ServerManager>());
_scheduleManager = new ScheduleManager(App.ConfigDirectory);
// Status bar update timer
_statusTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
_statusTimer.Tick += async (s, e) =>
{
UpdateStatusBar();
await RefreshOverviewAsync();
CheckConnectionsAndNotify();
/* Auto-refresh alert history if the tab is active */
if (ServerTabControl.SelectedItem == AlertsTab)
AlertsHistoryContent.RefreshAlerts();
};
// Initialize database and UI
Loaded += MainWindow_Loaded;
Closing += MainWindow_Closing;
ServerTabControl.SelectionChanged += ServerTabControl_SelectionChanged;
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
StatusText.Text = "Initializing database...";
// Initialize the DuckDB database
await _databaseInitializer.InitializeAsync();
// Initialize the collection engine (with loggers wired to AppLogger)
_collectorService = new RemoteCollectorService(
_databaseInitializer,
_serverManager,
_scheduleManager,
new AppLoggerAdapter<RemoteCollectorService>());
var archiveService = new ArchiveService(_databaseInitializer, App.ArchiveDirectory, new AppLoggerAdapter<ArchiveService>());
var retentionService = new RetentionService(App.ArchiveDirectory, new AppLoggerAdapter<RetentionService>());
_backgroundService = new CollectionBackgroundService(
_collectorService, _databaseInitializer, archiveService, retentionService, _serverManager,
new AppLoggerAdapter<CollectionBackgroundService>());
// Start background collection
_backgroundCts = new CancellationTokenSource();
_ = _backgroundService.StartAsync(_backgroundCts.Token);
// Initialize system tray
_trayService = new SystemTrayService(this, _backgroundService);
_trayService.Initialize();
// Initialize data service for overview
_dataService = new LocalDataService(_databaseInitializer);
// Load mute rules from database
await _muteRuleService.LoadAsync();
// Initialize alerts history tab
AlertsHistoryContent.Initialize(_dataService);
AlertsHistoryContent.MuteRuleService = _muteRuleService;
// Initialize FinOps tab
FinOpsContent.Initialize(_dataService, _serverManager);
// Start MCP server if enabled
await StartMcpServerAsync();
// Load servers
RefreshServerList();
// Update status
UpdateStatusBar();
_statusTimer.Start();
await RefreshOverviewAsync();
StatusText.Text = "Ready - Collection active";
_ = CheckForUpdatesOnStartupAsync();
}
catch (Exception ex)
{
StatusText.Text = $"Error: {ex.Message}";
MessageBox.Show(
$"Failed to initialize the application:\n\n{ex.Message}",
"Initialization Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
private async Task CheckForUpdatesOnStartupAsync()
{
try
{
await Task.Delay(5000); // Don't slow down startup
if (!App.CheckForUpdatesOnStartup) return;
// Try Velopack first (supports download + apply)
try
{
var mgr = new Velopack.UpdateManager(
new Velopack.Sources.GithubSource(
"https://github.com/erikdarlingdata/PerformanceMonitor", null, false));
var newVersion = await mgr.CheckForUpdatesAsync();
if (newVersion != null)
{
Dispatcher.Invoke(() =>
{
Title = $"Performance Monitor Lite — Update v{newVersion.TargetFullRelease.Version} available (Help > About)";
});
return;
}
}
catch
{
// Velopack packages may not exist yet — fall through
}
// Fallback: GitHub Releases API check
var result = await UpdateCheckService.CheckForUpdateAsync();
if (result?.IsUpdateAvailable == true)
{
Dispatcher.Invoke(() =>
{
Title = $"Performance Monitor Lite — Update {result.LatestVersion} available (Help > About)";
});
}
}
catch
{
// Never crash on update check failure
}
}
private async void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
{
// Dispose system tray
_trayService?.Dispose();
// Stop background collection with timeout
_backgroundCts?.Cancel();
await StopMcpServerAsync();
if (_backgroundService != null)
{
try
{
using var shutdownCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await _backgroundService.StopAsync(shutdownCts.Token);
}
catch (OperationCanceledException)
{
/* Shutdown timed out, proceeding anyway */
}
}
// Stop all server tab refresh timers
foreach (var tab in _openServerTabs.Values)
{
if (tab.Content is ServerTab serverTab)
{
serverTab.StopRefresh();
}
}
_statusTimer.Stop();
}
private void ServerTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Only respond to tab selection changes, not child control selection events that bubble up
if (e.OriginalSource != ServerTabControl) return;
/* Restore the selected tab's UTC offset so charts use the correct server timezone */
if (ServerTabControl.SelectedItem is TabItem { Content: ServerTab serverTab })
{
ServerTimeHelper.UtcOffsetMinutes = serverTab.UtcOffsetMinutes;
StatusText.Text = $"Connected to {serverTab.Server.DisplayNameWithIntent}";
}
/* Refresh alerts tab when selected */
if (ServerTabControl.SelectedItem == AlertsTab)
{
AlertsHistoryContent.RefreshAlerts();
}
UpdateCollectorHealth();
}
private async Task StartMcpServerAsync()
{
var mcpSettings = McpSettings.Load(App.ConfigDirectory);
if (!mcpSettings.Enabled) return;
try
{
bool portInUse = await PortUtilityService.IsTcpPortListeningAsync(mcpSettings.Port, IPAddress.Loopback);
if (portInUse)
{
AppLogger.Error("MCP", $"Port {mcpSettings.Port} is already in use — MCP server not started");
return;
}
_mcpService = new McpHostService(_dataService!, _serverManager, _muteRuleService, _databaseInitializer, mcpSettings.Port);
_ = _mcpService.StartAsync(_backgroundCts!.Token);
}
catch (Exception ex)
{
AppLogger.Error("MCP", $"Failed to start MCP server: {ex.Message}");
}
}
private async Task StopMcpServerAsync()
{
if (_mcpService != null)
{
try
{
using var shutdownCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
await _mcpService.StopAsync(shutdownCts.Token);
}
catch (OperationCanceledException)
{
/* MCP shutdown timed out */
}
_mcpService = null;
}
}
private void RefreshServerList()
{
var servers = _serverManager.GetAllServers();
foreach (var server in servers)
{
server.IsOnline = _serverManager.GetConnectionStatus(server.Id).IsOnline;
server.HasCollectorErrors = _collectorService != null
&& server.IsOnline == true
&& _collectorService.GetHealthSummary(server).ErroringCollectors > 0;
}
ServerListView.ItemsSource = servers;
// Update UI based on server count
if (servers.Count == 0 && _openServerTabs.Count == 0)
{
EmptyStatePanel.Visibility = Visibility.Visible;
ServerTabControl.Visibility = Visibility.Collapsed;
}
else
{
EmptyStatePanel.Visibility = Visibility.Collapsed;
ServerTabControl.Visibility = Visibility.Visible;
}
ServerCountText.Text = $"Servers: {servers.Count}";
// Refresh FinOps server dropdown when server list changes
FinOpsContent.RefreshServerList();
// Refresh overview when server list changes
_ = RefreshOverviewAsync();
}
private void UpdateStatusBar()
{
// Update database size
var fileSizeMb = _databaseInitializer.GetDatabaseSizeMb();
var usedSizeMb = _databaseInitializer.GetUsedDataSizeMb();
if (fileSizeMb > 0)
{
DatabaseSizeText.Text = usedSizeMb.HasValue
? $"Database: {usedSizeMb.Value:F1} / {fileSizeMb:F1} MB"
: $"Database: {fileSizeMb:F1} MB";
}
else
{
DatabaseSizeText.Text = "Database: New";
}
// Update collection status
if (_backgroundService != null)
{
if (_backgroundService.IsCollecting)
{
CollectionStatusText.Text = "Collection: Running";
}
else if (_backgroundService.IsPaused)
{
CollectionStatusText.Text = "Collection: Paused";
}
else if (_backgroundService.LastCollectionTime.HasValue)
{
var ago = DateTime.UtcNow - _backgroundService.LastCollectionTime.Value;
CollectionStatusText.Text = $"Collection: {ago.TotalSeconds:F0}s ago";
}
else
{
CollectionStatusText.Text = "Collection: Starting...";
}
}
else
{
CollectionStatusText.Text = "Collection: Stopped";
}
// Update collector health
UpdateCollectorHealth();
}
private void UpdateCollectorHealth()
{
if (_collectorService == null)
{
CollectorHealthText.Text = "";
return;
}
int? selectedServerId = null;
if (ServerTabControl.SelectedItem is TabItem { Content: ServerTab serverTab })
{
selectedServerId = serverTab.ServerId;
}
var health = _collectorService.GetHealthSummary(selectedServerId);
if (health.TotalCollectors == 0)
{
CollectorHealthText.Text = "";
return;
}
if (health.LoggingFailures > 0)
{
CollectorHealthText.Text = $"Logging: BROKEN ({health.LoggingFailures} failures)";
CollectorHealthText.Foreground = System.Windows.Media.Brushes.Red;
CollectorHealthText.ToolTip = $"collection_log INSERT is failing.\nThis means collector errors are invisible.\nCheck the log file for details.";
}
else if (health.ErroringCollectors > 0)
{
var names = string.Join(", ", health.Errors.Select(e => e.CollectorName));
CollectorHealthText.Text = $"Collectors: {health.ErroringCollectors} erroring";
CollectorHealthText.Foreground = System.Windows.Media.Brushes.OrangeRed;
CollectorHealthText.ToolTip = $"Failing: {names}\n\n" +
string.Join("\n", health.Errors.Select(e =>
$"{e.CollectorName}: {e.ConsecutiveErrors}x consecutive - {e.LastErrorMessage}"));
}
else
{
CollectorHealthText.Text = $"Collectors: {health.TotalCollectors} OK";
CollectorHealthText.Foreground = (System.Windows.Media.Brush)FindResource("ForegroundBrush");
CollectorHealthText.ToolTip = null;
}
}
private async Task RefreshOverviewAsync()
{
if (_dataService == null) return;
var servers = _serverManager.GetAllServers();
if (servers.Count == 0) return;
try
{
var summaries = new List<ServerSummaryItem>();
foreach (var server in servers)
{
try
{
var serverId = RemoteCollectorService.GetDeterministicHashCode(RemoteCollectorService.GetServerNameForStorage(server));
var summary = await _dataService.GetServerSummaryAsync(serverId, server.DisplayNameWithIntent);
if (summary != null)
{
summary.ServerName = server.ServerName;
var connStatus = _serverManager.GetConnectionStatus(server.Id);
summary.IsOnline = connStatus.IsOnline;
if (_collectorService != null && connStatus.IsOnline == true)
summary.HasCollectorErrors = _collectorService.GetHealthSummary(server).ErroringCollectors > 0;
summaries.Add(summary);
}
}
catch (Exception ex)
{
AppLogger.Info("Overview", $"Failed to get summary for {server.DisplayName}: {ex.Message}");
}
}
OverviewItemsControl.ItemsSource = summaries;
foreach (var summary in summaries)
{
CheckPerformanceAlerts(summary);
}
}
catch (Exception ex)
{
AppLogger.Info("Overview", $"RefreshOverviewAsync failed: {ex.Message}");
}
}
private void ServerListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (ServerListView.SelectedItem is ServerConnection server)
{
ConnectToServer(server);
}
}
private void OverviewCard_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2 && sender is FrameworkElement fe && fe.DataContext is ServerSummaryItem summary)
{
var server = _serverManager.GetAllServers()
.FirstOrDefault(s => s.ServerName == summary.ServerName);
if (server != null)
{
ConnectToServer(server);
}
}
}
private async void ConnectToServer(ServerConnection server)
{
// Check if tab already open
if (_openServerTabs.TryGetValue(server.Id, out var existingTab))
{
ServerTabControl.SelectedItem = existingTab;
return;
}
// Clear MFA cancellation flag when user explicitly connects
// This gives them a fresh attempt at authentication
var currentStatus = _serverManager.GetConnectionStatus(server.Id);
if (server.AuthenticationType == AuthenticationTypes.EntraMFA && currentStatus.UserCancelledMfa)
{
currentStatus.UserCancelledMfa = false;
StatusText.Text = "Retrying MFA authentication...";
}
// Ensure connection status is populated with UTC offset before opening tab
// This is critical for timezone-correct chart display
var status = _serverManager.GetConnectionStatus(server.Id);
if (!status.UtcOffsetMinutes.HasValue)
{
StatusText.Text = "Checking server connection...";
// Allow interactive auth (MFA) when user explicitly opens a server
status = await _serverManager.CheckConnectionAsync(server.Id, allowInteractiveAuth: true);
}
var utcOffset = status.UtcOffsetMinutes ?? 0;
var serverTab = new ServerTab(server, _databaseInitializer, _serverManager.CredentialService, utcOffset, status.HasMsdbAccess);
var tabHeader = CreateTabHeader(server);
var tabItem = new TabItem
{
Header = tabHeader,
Content = serverTab
};
/* Subscribe to alert counts for badge updates */
var serverId = server.Id;
serverTab.AlertCountsChanged += (blockingCount, deadlockCount, latestEventTime) =>
{
Dispatcher.Invoke(() => UpdateTabBadge(tabHeader, serverId, blockingCount, deadlockCount, latestEventTime));
};
/* Subscribe to "Apply to All" time range propagation */
serverTab.ApplyTimeRangeRequested += (selectedIndex) =>
{
Dispatcher.Invoke(() =>
{
foreach (var tab in _openServerTabs.Values)
{
if (tab.Content is ServerTab st && st != serverTab)
{
st.SetTimeRangeIndex(selectedIndex);
}
}
});
};
/* Re-collect on-load data (config, trace flags) when refresh button is clicked */
serverTab.ManualRefreshRequested += async () =>
{
if (_collectorService != null)
{
var onLoadCollectors = _scheduleManager.GetOnLoadCollectors();
foreach (var collector in onLoadCollectors)
{
try
{
await _collectorService.RunCollectorAsync(server, collector.Name);
}
catch (Exception ex)
{
AppLogger.Info("MainWindow", $"Re-collection of {collector.Name} failed: {ex.Message}");
}
}
}
};
_openServerTabs[server.Id] = tabItem;
ServerTabControl.Items.Add(tabItem);
ServerTabControl.SelectedItem = tabItem;
// Show the tab control, hide empty state
EmptyStatePanel.Visibility = Visibility.Collapsed;
ServerTabControl.Visibility = Visibility.Visible;
_serverManager.UpdateLastConnected(server.Id);
// Show existing historical data immediately
serverTab.RefreshData();
// Then collect fresh data and refresh again
if (_collectorService != null)
{
StatusText.Text = $"Collecting data from {server.DisplayNameWithIntent}...";
try
{
await _collectorService.RunAllCollectorsForServerAsync(server);
StatusText.Text = $"Connected to {server.DisplayNameWithIntent} - Data loaded";
serverTab.RefreshData();
UpdateCollectorHealth();
_ = RefreshOverviewAsync();
}
catch (Exception ex)
{
StatusText.Text = $"Connected to {server.DisplayNameWithIntent} - Collection error: {ex.Message}";
}
}
else
{
StatusText.Text = $"Connected to {server.DisplayNameWithIntent}";
}
}
private StackPanel CreateTabHeader(ServerConnection server)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal };
var tabLabel = server.ReadOnlyIntent ? $"{server.DisplayName} (RO)" : server.DisplayName;
panel.Children.Add(new TextBlock
{
Text = tabLabel,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 4, 0)
});
/* Alert badge - hidden by default, shown when blocking/deadlocks detected */
var badge = new System.Windows.Controls.Border
{
Background = System.Windows.Media.Brushes.OrangeRed,
CornerRadius = new CornerRadius(7),
Padding = new Thickness(5, 1, 5, 1),
Margin = new Thickness(0, 0, 4, 0),
VerticalAlignment = VerticalAlignment.Center,
Visibility = Visibility.Collapsed,
Child = new TextBlock
{
FontSize = 10,
FontWeight = FontWeights.Bold,
Foreground = System.Windows.Media.Brushes.White,
VerticalAlignment = VerticalAlignment.Center
}
};
badge.Tag = "AlertBadge";
/* Add context menu to badge for acknowledge/silence functionality */
var serverId = server.Id;
var contextMenu = new ContextMenu();
var acknowledgeItem = new MenuItem
{
Header = "Acknowledge Alert",
Tag = serverId,
Icon = new TextBlock { Text = "✓", FontWeight = FontWeights.Bold }
};
acknowledgeItem.Click += AcknowledgeServerAlert_Click;
var silenceItem = new MenuItem
{
Header = "Silence This Server",
Tag = serverId,
Icon = new TextBlock { Text = "🔇" }
};
silenceItem.Click += SilenceServer_Click;
var unsilenceItem = new MenuItem
{
Header = "Unsilence",
Tag = serverId,
Icon = new TextBlock { Text = "🔔" }
};
unsilenceItem.Click += UnsilenceServer_Click;
contextMenu.Items.Add(acknowledgeItem);
contextMenu.Items.Add(silenceItem);
contextMenu.Items.Add(new Separator());
contextMenu.Items.Add(unsilenceItem);
/* Update menu items based on state when opened */
contextMenu.Opened += (s, args) =>
{
var isSilenced = _alertStateService.IsServerSilenced(serverId);
var hasAlert = badge.Visibility == Visibility.Visible;
acknowledgeItem.IsEnabled = hasAlert;
silenceItem.IsEnabled = !isSilenced;
unsilenceItem.IsEnabled = isSilenced;
};
badge.ContextMenu = contextMenu;
panel.Children.Add(badge);
var closeButton = new Button
{
Content = "x",
FontSize = 10,
Padding = new Thickness(4, 0, 4, 0),
VerticalAlignment = VerticalAlignment.Center,
Cursor = Cursors.Hand
};
closeButton.Click += (s, e) => CloseServerTab(server.Id);
panel.Children.Add(closeButton);
return panel;
}
private void UpdateTabBadge(StackPanel tabHeader, string serverId, int blockingCount, int deadlockCount, DateTime? latestEventTime)
{
var totalAlerts = blockingCount + deadlockCount;
/* Delegate count tracking and acknowledgement clearing to AlertStateService.
Uses latestEventTime to only clear ack when genuinely new events arrive,
not when the user just switches time ranges. */
bool shouldShow = _alertStateService.UpdateAlertCounts(serverId, blockingCount, deadlockCount, latestEventTime);
foreach (var child in tabHeader.Children)
{
if (child is System.Windows.Controls.Border border && border.Tag as string == "AlertBadge")
{
if (shouldShow)
{
border.Visibility = Visibility.Visible;
border.Background = deadlockCount > 0
? System.Windows.Media.Brushes.Red
: System.Windows.Media.Brushes.OrangeRed;
if (border.Child is TextBlock text)
{
text.Text = totalAlerts > 99 ? "99+" : totalAlerts.ToString();
text.ToolTip = $"Blocking: {blockingCount}, Deadlocks: {deadlockCount}\nRight-click to dismiss";
}
}
else
{
border.Visibility = Visibility.Collapsed;
}
break;
}
}
}
private void AcknowledgeServerAlert_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && menuItem.Tag is string serverId)
{
_alertStateService.AcknowledgeAlert(serverId);
/* Find and hide the badge for this server */
if (_openServerTabs.TryGetValue(serverId, out var tab) && tab.Header is StackPanel panel)
{
foreach (var child in panel.Children)
{
if (child is System.Windows.Controls.Border border && border.Tag as string == "AlertBadge")
{
border.Visibility = Visibility.Collapsed;
break;
}
}
}
}
}
private void SilenceServer_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && menuItem.Tag is string serverId)
{
_alertStateService.SilenceServer(serverId);
/* Find and hide the badge for this server */
if (_openServerTabs.TryGetValue(serverId, out var tab) && tab.Header is StackPanel panel)
{
foreach (var child in panel.Children)
{
if (child is System.Windows.Controls.Border border && border.Tag as string == "AlertBadge")
{
border.Visibility = Visibility.Collapsed;
break;
}
}
}
}
}
private void UnsilenceServer_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuItem menuItem && menuItem.Tag is string serverId)
{
_alertStateService.UnsilenceServer(serverId);
/* The next refresh cycle will show the badge if there are alerts */
}
}
private void CloseServerTab(string serverId)
{
if (_openServerTabs.TryGetValue(serverId, out var tab))
{
if (tab.Content is ServerTab serverTab)
{
serverTab.StopRefresh();
}
ServerTabControl.Items.Remove(tab);
_openServerTabs.Remove(serverId);
/* Clean up alert state for this server */
_alertStateService.RemoveServerState(serverId);
// Show empty state if no tabs open
if (_openServerTabs.Count == 0)
{
var servers = _serverManager.GetAllServers();
if (servers.Count == 0)
{
EmptyStatePanel.Visibility = Visibility.Visible;
ServerTabControl.Visibility = Visibility.Collapsed;
}
}
}
}
private void AddServerButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new AddServerDialog(_serverManager) { Owner = this };
if (dialog.ShowDialog() == true && dialog.AddedServer != null)
{
RefreshServerList();
StatusText.Text = $"Added server: {dialog.AddedServer.DisplayNameWithIntent}";
}
}
private void ManageServersButton_Click(object sender, RoutedEventArgs e)
{
var window = new ManageServersWindow(_serverManager) { Owner = this };
window.ShowDialog();
if (window.ServersChanged)
{
// Purge collector health for servers that were removed
if (_collectorService != null)
{
var currentServerIds = new HashSet<int>(
_serverManager.GetAllServers().Select(s =>
RemoteCollectorService.GetDeterministicHashCode(
RemoteCollectorService.GetServerNameForStorage(s))));
_collectorService.ClearHealthExcept(currentServerIds);
}
RefreshServerList();
}
}
private async void SettingsButton_Click(object sender, RoutedEventArgs e)
{
var window = new SettingsWindow(_scheduleManager, _backgroundService, _mcpService, _muteRuleService) { Owner = this };
window.ShowDialog();
UpdateStatusBar();
if (window.McpSettingsChanged)
{
await StopMcpServerAsync();
await StartMcpServerAsync();
}
}
private void AboutButton_Click(object sender, RoutedEventArgs e)
{
var window = new Windows.AboutWindow { Owner = this };
window.ShowDialog();
}
private void ImportSettingsButton_Click(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFolderDialog
{
Title = "Select Previous Lite Install Folder"
};
if (dialog.ShowDialog() != true) return;
var oldConfigDir = System.IO.Path.Combine(dialog.FolderName, "config");
var serversJsonPath = System.IO.Path.Combine(oldConfigDir, "servers.json");
if (!System.IO.File.Exists(serversJsonPath))
{
MessageBox.Show(
"No config\\servers.json found in the selected folder.\n\nSelect the root folder of a previous Lite installation.",
"Import Settings",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
try
{
// Import server connections (upsert by server name)
var (imported, skipped) = _serverManager.ImportServersFromFile(serversJsonPath);
// Copy config files that don't already exist in the current install
var settingsFiles = new[] { "settings.json", "collection_schedule.json", "ignored_wait_types.json" };
int settingsCopied = 0;
foreach (var fileName in settingsFiles)
{
var source = System.IO.Path.Combine(oldConfigDir, fileName);
var target = System.IO.Path.Combine(App.ConfigDirectory, fileName);
if (System.IO.File.Exists(source) && !System.IO.File.Exists(target))
{
System.IO.File.Copy(source, target);
settingsCopied++;
}
}
// Copy alert_state.json from old root directory
var oldAlertState = System.IO.Path.Combine(dialog.FolderName, "alert_state.json");
var currentAlertState = System.IO.Path.Combine(App.DataDirectory, "alert_state.json");
if (System.IO.File.Exists(oldAlertState) && !System.IO.File.Exists(currentAlertState))
{
System.IO.File.Copy(oldAlertState, currentAlertState);
settingsCopied++;
}
var message = $"Imported {imported} server connection(s).";
if (skipped > 0)
message += $"\nSkipped {skipped} duplicate(s) (already configured).";
if (settingsCopied > 0)
message += $"\nCopied {settingsCopied} settings file(s).";
if (imported > 0)
message += "\n\nCredentials from the previous install are preserved.\nIf any connections fail to authenticate, re-enter the password in Manage Servers.";
if (settingsCopied > 0)
message += "\n\nRestart the application to apply imported settings.";
MessageBox.Show(message, "Import Settings", MessageBoxButton.OK, MessageBoxImage.Information);
if (imported > 0)
RefreshServerList();
}
catch (Exception ex)
{
MessageBox.Show($"Failed to import settings: {ex.Message}", "Import Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async void ImportDataButton_Click(object sender, RoutedEventArgs e)
{
/* Open folder browser to select the old Lite install directory */
var dialog = new Microsoft.Win32.OpenFolderDialog
{
Title = "Select Previous Lite Install Folder",
Multiselect = false
};
if (dialog.ShowDialog(this) != true || string.IsNullOrWhiteSpace(dialog.FolderName))
{
return;
}
var sourceFolder = dialog.FolderName;
/* Validate that monitor.duckdb exists in the selected folder */
if (!DataImportService.ValidateSourceFolder(sourceFolder))
{
MessageBox.Show(
"The selected folder does not contain a monitor.duckdb file.\n\n" +
"Please select the folder where the previous Lite application was installed.",
"Invalid Folder",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
/* Prevent double-clicks */
ImportDataButton.IsEnabled = false;
ImportDataButtonText.Text = "Importing...";
StatusText.Text = "Importing data from previous install...";
try
{
var importService = new DataImportService(_databaseInitializer, App.ArchiveDirectory);
/* The tryLockOldDb callback runs on the UI thread to show the retry dialog */
var result = await Task.Run(async () =>
await importService.RunImportAsync(sourceFolder, async _ =>
{
var answer = MessageBoxResult.Cancel;
await Dispatcher.InvokeAsync(() =>
{
answer = MessageBox.Show(
"Could not lock the database to flush current data.\n\n" +
"Close the previous Lite application and click OK to try again.",
"Database Locked",
MessageBoxButton.OKCancel,
MessageBoxImage.Warning);
});
return answer == MessageBoxResult.OK;
}));
if (result.Success)
{
StatusText.Text = "Import complete — refreshing views...";
await _serverManager.CheckAllConnectionsAsync();
RefreshServerList();
UpdateStatusBar();
StatusText.Text = "Import complete";