diff --git a/App.xaml.cs b/App.xaml.cs index 7f759661..faeea710 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -180,8 +180,13 @@ protected override void OnStartup(StartupEventArgs e) if (!settings.HasUserThemePreference && settings.UseDarkTheme != useDarkTheme) { - settings.UseDarkTheme = useDarkTheme; - Task.Run(async () => await settingsService.UpdateSettingsAsync(settings)).GetAwaiter().GetResult(); + Task.Run(() => settingsService.EditSettingsAsync(draft => + { + if (!draft.HasUserThemePreference) + { + draft.UseDarkTheme = useDarkTheme; + } + })).GetAwaiter().GetResult(); } themeService.ApplyTheme(useDarkTheme); @@ -498,14 +503,10 @@ private void ReportUnhandledException(Exception exception, string source, LogLev return; } - var errorCode = exception is ThreadPilotException typedException - ? typedException.ErrorCode.ToString() - : ErrorCode.Unhandled.ToString(); - var context = new Dictionary { ["Source"] = source, - [LogProperties.ErrorCode] = errorCode, + [LogProperties.ErrorCode] = "Unhandled", [LogProperties.CorrelationId] = enhancedLogger.GetCurrentCorrelationId() ?? "N/A", ["IsTerminatingLevel"] = level == LogLevel.Critical, }; diff --git a/Converters/ItemIndexConverter.cs b/Converters/ItemIndexConverter.cs deleted file mode 100644 index 8982551d..00000000 --- a/Converters/ItemIndexConverter.cs +++ /dev/null @@ -1,32 +0,0 @@ -namespace ThreadPilot.Converters -{ - using System; - using System.Globalization; - using System.Windows; - using System.Windows.Controls; - using System.Windows.Data; - - public class ItemIndexConverter : IValueConverter - { - public object Convert(object value, Type targetType, object parameter, CultureInfo culture) - { - if (value is DependencyObject item) - { - var itemsControl = ItemsControl.ItemsControlFromItemContainer(item); - if (itemsControl != null) - { - int index = itemsControl.ItemContainerGenerator.IndexFromContainer(item); - return index; - } - } - - return -1; - } - - public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) - { - throw new NotImplementedException(); - } - } -} - diff --git a/Helpers/AffinityHelper.cs b/Helpers/AffinityHelper.cs deleted file mode 100644 index 8024f4ab..00000000 --- a/Helpers/AffinityHelper.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace ThreadPilot.Helpers -{ - using System.Collections.Generic; - using System.Linq; - using System.Windows.Controls; - - public static class AffinityHelper - { - public static long CalculateAffinityMask(IEnumerable cpuCheckboxes) - { - return cpuCheckboxes - .Where(cb => cb.IsChecked == true) - .Sum(cb => (long)cb.Tag); - } - - public static void UpdateCheckboxesFromMask(IEnumerable cpuCheckboxes, long affinityMask) - { - foreach (var checkbox in cpuCheckboxes) - { - var cpuBit = (long)checkbox.Tag; - checkbox.IsChecked = (affinityMask & cpuBit) != 0; - } - } - } -} diff --git a/Installer/setup.iss b/Installer/setup.iss index c190df41..e612544f 100644 --- a/Installer/setup.iss +++ b/Installer/setup.iss @@ -11,7 +11,7 @@ #endif #ifndef MyAppVersion - #define MyAppVersion "1.7.9" + #define MyAppVersion "1.7.10" #endif #ifndef MyAppSourceDir diff --git a/Locales/de-DE.xaml b/Locales/de-DE.xaml index f0cc9eee..e0e21172 100644 --- a/Locales/de-DE.xaml +++ b/Locales/de-DE.xaml @@ -399,9 +399,6 @@ Minimiert starten Prozessänderungen beim Beenden zurücksetzen Stellt von ThreadPilot geänderte CPU-Zuweisungen und Prioritäten beim Beenden der App wieder her. - Ausstehende Einstellungen aktivieren, die aus dem Fach übernommen werden - Aktivieren Sie die Steuerelemente für die Automatisierungsüberwachung in der Taskleiste - Detaillierte Tooltips anzeigen Grundeinstellungen Beginnen Sie mit Windows @@ -436,8 +433,6 @@ Fortgeschritten Benachrichtigungsverlauf aktivieren Max. Verlaufselemente: - Benachrichtigungen automatisch ausblenden - Benachrichtigungston aktivieren Aktivieren Sie die Debug-Protokollierung Leistungsindikatoren aktivieren diff --git a/Locales/en-US.xaml b/Locales/en-US.xaml index 029aab96..a7891f7b 100644 --- a/Locales/en-US.xaml +++ b/Locales/en-US.xaml @@ -399,9 +399,6 @@ Start minimized Reset process changes on exit Restores CPU assignments and priorities changed by ThreadPilot when the app exits. - Enable pending settings apply from tray - Enable automation monitoring controls from tray - Show detailed tooltips Basic Preferences Start with Windows @@ -436,8 +433,6 @@ Advanced Enable notification history Max history items: - Auto-hide notifications - Enable notification sound Enable debug logging Enable performance counters diff --git a/Locales/es-ES.xaml b/Locales/es-ES.xaml index 9bd09626..574107d8 100644 --- a/Locales/es-ES.xaml +++ b/Locales/es-ES.xaml @@ -399,9 +399,6 @@ Empezar minimizado Restablecer cambios de procesos al salir Restaura las asignaciones de CPU y prioridades modificadas por ThreadPilot al cerrar la aplicación. - Habilitar configuración pendiente aplicar desde la bandeja - Habilite los controles de monitoreo de automatización desde la bandeja - Mostrar información sobre herramientas detallada Preferencias básicas Comience con Windows @@ -436,8 +433,6 @@ Avanzado Habilitar el historial de notificaciones Elementos máximos del historial: - Ocultar notificaciones automáticamente - Habilitar sonido de notificación Habilitar el registro de depuración Habilitar contadores de rendimiento diff --git a/Locales/fr-FR.xaml b/Locales/fr-FR.xaml index 35d158b8..da8f5f93 100644 --- a/Locales/fr-FR.xaml +++ b/Locales/fr-FR.xaml @@ -399,9 +399,6 @@ Démarrer réduit Réinitialiser les modifications des processus à la fermeture Restaure les affectations CPU et les priorités modifiées par ThreadPilot à la fermeture de l'application. - Activer l'application des paramètres en attente à partir du bac - Activer les contrôles de surveillance de l'automatisation à partir du bac - Afficher des info-bulles détaillées Préférences de base Commencez par Windows @@ -436,8 +433,6 @@ Avancé Activer l'historique des notifications Nombre maximum d'éléments d'historique : - Masquer automatiquement les notifications - Activer le son des notifications Activer la journalisation du débogage Activer les compteurs de performances diff --git a/Locales/it-IT.xaml b/Locales/it-IT.xaml index 97a2d19c..7f109375 100644 --- a/Locales/it-IT.xaml +++ b/Locales/it-IT.xaml @@ -399,9 +399,6 @@ Inizia minimizzato Ripristina le modifiche ai processi all'uscita Ripristina le assegnazioni CPU e le priorità modificate da ThreadPilot quando l'app viene chiusa. - Abilita le impostazioni in sospeso applicate dal vassoio - Abilita i controlli di monitoraggio dell'automazione dal vassoio - Mostra descrizioni comandi dettagliate Preferenze di base Inizia con Windows @@ -436,8 +433,6 @@ Avanzato Abilita la cronologia delle notifiche Elementi massimi della cronologia: - Notifiche nascoste automaticamente - Abilita il suono delle notifiche Abilita la registrazione del debug Abilita i contatori delle prestazioni diff --git a/Locales/ru-RU.xaml b/Locales/ru-RU.xaml index 24d2564c..e2ec400c 100644 --- a/Locales/ru-RU.xaml +++ b/Locales/ru-RU.xaml @@ -399,9 +399,6 @@ Начать сворачивать Сбрасывать изменения процессов при выходе Восстанавливает назначения ЦП и приоритеты, изменённые ThreadPilot, при закрытии приложения. - Включить ожидающие настройки, применимые из трея - Включить элементы управления мониторингом автоматизации из трея - Показать подробные подсказки Основные настройки Начните с Windows @@ -436,8 +433,6 @@ Расширенный Включить историю уведомлений Максимальное количество элементов истории: - Автоматическое скрытие уведомлений - Включить звук уведомлений Включить ведение журнала отладки Включить счетчики производительности diff --git a/Locales/zh-CN.xaml b/Locales/zh-CN.xaml index b6265ba4..f698dc0a 100644 --- a/Locales/zh-CN.xaml +++ b/Locales/zh-CN.xaml @@ -399,9 +399,6 @@ 开机启动时最小化 退出时重置进程更改 退出应用时恢复 ThreadPilot 更改的 CPU 分配和优先级。 - 允许从托盘菜单应用待处理设置 - 允许从托盘菜单控制自动化监控 - 托盘图标显示详细鼠标提示 基本偏好设置 随 Windows 开机启动 @@ -436,8 +433,6 @@ 高级与调试设置 启用通知历史记录 最大历史条目数: - 自动渐隐通知气泡 - 播放提示音 开启调试诊断日志记录 启用内部性能计数器 diff --git a/MainWindow.Behaviors.partial.cs b/MainWindow.Behaviors.partial.cs index 8f5d5c9e..262fb1ac 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -534,8 +534,13 @@ private async Task InitializeSettingsAsync() if (!settings.HasUserThemePreference && settings.UseDarkTheme != useDarkTheme) { - settings.UseDarkTheme = useDarkTheme; - await this.settingsService.UpdateSettingsAsync(settings); + await this.settingsService.EditSettingsAsync(draft => + { + if (!draft.HasUserThemePreference) + { + draft.UseDarkTheme = useDarkTheme; + } + }); } this.themeService.ApplyTheme(useDarkTheme); @@ -575,21 +580,29 @@ private async Task MigratePersistentRuleCpuAssignmentModesAsync() return; } - var rules = await ruleStore.LoadAsync(); - var migrated = CpuAssignmentModeMigrationPolicy.ApplyToRules(rules); - if (migrated != null) + var movedCount = await ruleStore.EditAsync(rules => { - await ruleStore.SaveAsync(migrated); - var movedCount = rules + var migrated = CpuAssignmentModeMigrationPolicy.ApplyToRules(rules); + if (migrated == null) + { + return Task.FromResult(0); + } + + var count = rules .Zip(migrated, (before, after) => before.CpuAssignmentMode != after.CpuAssignmentMode) .Count(moved => moved); + rules.Clear(); + rules.AddRange(migrated); + return Task.FromResult(count); + }); + if (movedCount > 0) + { this.LogDebug($"Migrated {movedCount} saved rule(s) from Automatic to Affinity Mask"); } // Only after the rules have reached disk: a failed write has to be retried on the // next launch, not recorded as done. - settings.HasMigratedPersistentRuleCpuAssignmentModes = true; - await this.settingsService.UpdateSettingsAsync(settings); + await this.settingsService.EditSettingsAsync(draft => draft.HasMigratedPersistentRuleCpuAssignmentModes = true); } catch (Exception ex) { @@ -1287,7 +1300,7 @@ private async Task StartProcessMonitoringManagerAsync() this.LogDebug("Starting process monitoring manager service..."); // Start the process monitoring manager service with internal timeout - var startTask = this.processMonitorManagerService.SetAutomationMonitoringEnabledAsync(true); + var startTask = this.processMonitorManagerService.StartAsync(); var timeoutTask = Task.Delay(6000); // 6 second internal timeout var completedTask = await Task.WhenAny(startTask, timeoutTask); @@ -1741,8 +1754,7 @@ private async Task PersistCpuAssignmentModeNoticeSeenAsync() return; } - settings.HasSeenCpuAssignmentModeChangeNotice = true; - await this.settingsService.UpdateSettingsAsync(settings); + await this.settingsService.EditSettingsAsync(draft => draft.HasSeenCpuAssignmentModeChangeNotice = true); } catch (Exception ex) { @@ -1805,8 +1817,7 @@ private async Task PersistStartupMinimizedSuggestionSeenAsync() return; } - settings.HasSeenStartupMinimizedSuggestion = true; - await this.settingsService.UpdateSettingsAsync(settings); + await this.settingsService.EditSettingsAsync(draft => draft.HasSeenStartupMinimizedSuggestion = true); } catch (Exception ex) { @@ -1894,8 +1905,7 @@ private async void PerformanceIntroContinue_Click(object sender, RoutedEventArgs var settings = this.settingsService.Settings; if (!settings.HasSeenPerformanceIntro) { - settings.HasSeenPerformanceIntro = true; - await this.settingsService.UpdateSettingsAsync(settings); + await this.settingsService.EditSettingsAsync(draft => draft.HasSeenPerformanceIntro = true); } } catch (Exception ex) @@ -1985,8 +1995,7 @@ private void ElevationWarningDismiss_Click(object sender, RoutedEventArgs e) var settings = this.settingsService.Settings; if (!settings.HasSeenElevationWarning) { - settings.HasSeenElevationWarning = true; - _ = this.settingsService.UpdateSettingsAsync(settings); + _ = this.settingsService.EditSettingsAsync(draft => draft.HasSeenElevationWarning = true); } } catch (Exception ex) diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index 20ad3f39..59ee0446 100644 --- a/Models/ApplicationSettingsModel.cs +++ b/Models/ApplicationSettingsModel.cs @@ -8,7 +8,7 @@ namespace ThreadPilot.Models using ThreadPilot.Models.Core; using ThreadPilot.Services; - public partial class ApplicationSettingsModel : ObservableObject, IModel + public partial class ApplicationSettingsModel : ObservableObject { private static readonly JsonSerializerOptions UserSettingsComparisonJsonOptions = new() { @@ -60,45 +60,18 @@ public partial class ApplicationSettingsModel : ObservableObject, IModel [ObservableProperty] private bool showTrayIcon = true; - [ObservableProperty] - private bool enableQuickApplyFromTray = true; - - [ObservableProperty] - private bool enableMonitoringControlFromTray = true; - [ObservableProperty] private int notificationDisplayDurationMs = 3000; [ObservableProperty] private int balloonNotificationTimeoutMs = 5000; - [ObservableProperty] - private NotificationPosition notificationPosition = NotificationPosition.BottomRight; - - [ObservableProperty] - private NotificationSound notificationSound = NotificationSound.Default; - - [ObservableProperty] - private bool enableNotificationSound = false; - [ObservableProperty] private string customTrayIconPath = string.Empty; [ObservableProperty] private bool useCustomTrayIcon = false; - [ObservableProperty] - private TrayIconStyle trayIconStyle = TrayIconStyle.Default; - - [ObservableProperty] - private bool showDetailedTooltips = true; - - [ObservableProperty] - private bool enableContextMenuAnimations = true; - - [ObservableProperty] - private bool autoHideNotifications = true; - [ObservableProperty] private bool enableNotificationHistory = true; @@ -156,24 +129,24 @@ public partial class ApplicationSettingsModel : ObservableObject, IModel [ObservableProperty] private bool applyPersistentRulesOnProcessStart = true; - [ObservableProperty] - private bool enableAutomationMonitoring = true; - - [ObservableProperty] - private CpuAssignmentMode defaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask; - - // Set on a profile that has been through CpuAssignmentModeMigrationPolicy, so the one-time - // move off Automatic never runs twice and never overrides a later deliberate choice. - [ObservableProperty] - private bool hasMigratedCpuAssignmentModeDefault; - - [ObservableProperty] - private bool hasSeenCpuAssignmentModeChangeNotice; - - // Separate from the profile flag above: profiles were migrated in 1.7.2, saved rules - // were not, so a shared flag would skip the rules of everyone already on 1.7.2. - [ObservableProperty] - private bool hasMigratedPersistentRuleCpuAssignmentModes; + [ObservableProperty] + private bool enableAutomationMonitoring = true; + + [ObservableProperty] + private CpuAssignmentMode defaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask; + + // Set on a profile that has been through CpuAssignmentModeMigrationPolicy, so the one-time + // move off Automatic never runs twice and never overrides a later deliberate choice. + [ObservableProperty] + private bool hasMigratedCpuAssignmentModeDefault; + + [ObservableProperty] + private bool hasSeenCpuAssignmentModeChangeNotice; + + // Separate from the profile flag above: profiles were migrated in 1.7.2, saved rules + // were not, so a shared flag would skip the rules of everyone already on 1.7.2. + [ObservableProperty] + private bool hasMigratedPersistentRuleCpuAssignmentModes; // Advanced Settings [ObservableProperty] @@ -244,19 +217,10 @@ public void CopyFrom(ApplicationSettingsModel other) this.CloseToTray = other.CloseToTray; this.StartMinimized = other.StartMinimized; this.ShowTrayIcon = other.ShowTrayIcon; - this.EnableQuickApplyFromTray = other.EnableQuickApplyFromTray; - this.EnableMonitoringControlFromTray = other.EnableMonitoringControlFromTray; this.NotificationDisplayDurationMs = other.NotificationDisplayDurationMs; this.BalloonNotificationTimeoutMs = other.BalloonNotificationTimeoutMs; - this.NotificationPosition = other.NotificationPosition; - this.NotificationSound = other.NotificationSound; - this.EnableNotificationSound = other.EnableNotificationSound; this.CustomTrayIconPath = other.CustomTrayIconPath; this.UseCustomTrayIcon = other.UseCustomTrayIcon; - this.TrayIconStyle = other.TrayIconStyle; - this.ShowDetailedTooltips = other.ShowDetailedTooltips; - this.EnableContextMenuAnimations = other.EnableContextMenuAnimations; - this.AutoHideNotifications = other.AutoHideNotifications; this.EnableNotificationHistory = other.EnableNotificationHistory; this.MaxNotificationHistoryItems = other.MaxNotificationHistoryItems; @@ -281,20 +245,20 @@ public void CopyFrom(ApplicationSettingsModel other) this.EnableWmiMonitoring = other.EnableWmiMonitoring; this.EnableFallbackPolling = other.EnableFallbackPolling; this.ApplyPersistentRulesOnProcessStart = other.ApplyPersistentRulesOnProcessStart; - this.EnableAutomationMonitoring = other.EnableAutomationMonitoring; - // Repair to the shipped default, not to Automatic: a corrupt value is not a choice the - // user made, and treating it as one would tell them their Automatic setting was changed. - this.DefaultCpuAssignmentMode = Enum.IsDefined(other.DefaultCpuAssignmentMode) - ? other.DefaultCpuAssignmentMode - : CpuAssignmentMode.AffinityMask; + this.EnableAutomationMonitoring = other.EnableAutomationMonitoring; + // Repair to the shipped default, not to Automatic: a corrupt value is not a choice the + // user made, and treating it as one would tell them their Automatic setting was changed. + this.DefaultCpuAssignmentMode = Enum.IsDefined(other.DefaultCpuAssignmentMode) + ? other.DefaultCpuAssignmentMode + : CpuAssignmentMode.AffinityMask; // Advanced Settings this.EnableDebugLogging = other.EnableDebugLogging; this.EnablePerformanceCounters = other.EnablePerformanceCounters; this.HasSeenPerformanceIntro = other.HasSeenPerformanceIntro; this.HasSeenElevationWarning = other.HasSeenElevationWarning; - this.HasSeenStartupMinimizedSuggestion = other.HasSeenStartupMinimizedSuggestion; - this.HasMigratedCpuAssignmentModeDefault = other.HasMigratedCpuAssignmentModeDefault; + this.HasSeenStartupMinimizedSuggestion = other.HasSeenStartupMinimizedSuggestion; + this.HasMigratedCpuAssignmentModeDefault = other.HasMigratedCpuAssignmentModeDefault; this.HasSeenCpuAssignmentModeChangeNotice = other.HasSeenCpuAssignmentModeChangeNotice; this.HasMigratedPersistentRuleCpuAssignmentModes = other.HasMigratedPersistentRuleCpuAssignmentModes; this.EnableSelfLowImpactMode = other.EnableSelfLowImpactMode; @@ -303,9 +267,10 @@ public void CopyFrom(ApplicationSettingsModel other) this.LogRetentionDays = other.LogRetentionDays; // Keyboard Shortcuts - this.KeyboardShortcuts = other.KeyboardShortcuts != null - ? new List(other.KeyboardShortcuts) - : new List(); + this.KeyboardShortcuts = other.KeyboardShortcuts? + .Where(shortcut => shortcut != null) + .Select(shortcut => shortcut.Clone()) + .ToList() ?? []; // Game Boost this.GameBoostEnabled = other.GameBoostEnabled; @@ -316,7 +281,6 @@ public void CopyFrom(ApplicationSettingsModel other) this.GameBoostBackgroundProcesses = new List(other.GameBoostBackgroundProcesses ?? new()); } - // IModel implementation - properties are auto-generated by ObservableProperty public ValidationResult Validate() { var errors = new List(); @@ -331,20 +295,20 @@ public ValidationResult Validate() errors.Add("Process polling interval must be between 1 and 60 seconds"); } - if (this.FallbackPollingIntervalMs < 1000 || this.FallbackPollingIntervalMs > 60000) - { - errors.Add("Fallback polling interval must be between 1 and 60 seconds"); - } - - if (!Enum.IsDefined(this.DefaultCpuAssignmentMode)) - { - errors.Add("Default CPU assignment mode is invalid"); - } + if (this.FallbackPollingIntervalMs < 1000 || this.FallbackPollingIntervalMs > 60000) + { + errors.Add("Fallback polling interval must be between 1 and 60 seconds"); + } + + if (!Enum.IsDefined(this.DefaultCpuAssignmentMode)) + { + errors.Add("Default CPU assignment mode is invalid"); + } return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); } - public IModel Clone() + public ApplicationSettingsModel Clone() { var clone = new ApplicationSettingsModel(); clone.CopyFrom(this); @@ -361,8 +325,8 @@ public bool HasSameUserSettingsAs(ApplicationSettingsModel? other) return false; } - var currentSnapshot = (ApplicationSettingsModel)this.Clone(); - var otherSnapshot = (ApplicationSettingsModel)other.Clone(); + var currentSnapshot = this.Clone(); + var otherSnapshot = other.Clone(); currentSnapshot.Id = otherSnapshot.Id; currentSnapshot.CreatedAt = otherSnapshot.CreatedAt; @@ -380,31 +344,4 @@ public enum NotificationLevelProfile WarningsAndErrorsOnly, Silent, } - - public enum NotificationPosition - { - TopLeft, - TopRight, - BottomLeft, - BottomRight, - Center, - } - - public enum NotificationSound - { - None, - Default, - Information, - Warning, - Error, - Custom, - } - - public enum TrayIconStyle - { - Default, - Monochrome, - Colored, - Custom, - } } diff --git a/Models/ConditionalProcessProfile.cs b/Models/ConditionalProcessProfile.cs deleted file mode 100644 index 21e2ead9..00000000 --- a/Models/ConditionalProcessProfile.cs +++ /dev/null @@ -1,273 +0,0 @@ -namespace ThreadPilot.Models -{ - using System; - using System.Collections.Generic; - using System.Linq; - using CommunityToolkit.Mvvm.ComponentModel; - - public enum ProfileConditionType - { - SystemLoad, - TimeOfDay, - PowerState, - ProcessCount, - MemoryUsage, - CpuTemperature, - BatteryLevel, - NetworkActivity, - UserIdle, - Custom, - } - - public enum ComparisonOperator - { - Equals, - NotEquals, - GreaterThan, - LessThan, - GreaterThanOrEqual, - LessThanOrEqual, - Contains, - NotContains, - Between, - NotBetween, - } - - public enum LogicalOperator - { - And, - Or, - Not, - } - - public class SystemState - { - public double CpuUsage { get; set; } - - public double MemoryUsage { get; set; } - - public int ProcessCount { get; set; } - - public DateTime CurrentTime { get; set; } = DateTime.Now; - - public bool IsOnBattery { get; set; } - - public int BatteryLevel { get; set; } - - public double CpuTemperature { get; set; } - - public bool IsUserIdle { get; set; } - - public TimeSpan UserIdleTime { get; set; } - - public double NetworkActivity { get; set; } - - public Dictionary CustomProperties { get; set; } = new(); - } - - public partial class ProfileCondition : ObservableObject - { - [ObservableProperty] - private string name = string.Empty; - - [ObservableProperty] - private ProfileConditionType conditionType; - - [ObservableProperty] - private ComparisonOperator comparisonOperator; - - [ObservableProperty] - private object? value; - - [ObservableProperty] - private object? secondaryValue; // For Between/NotBetween operations - - [ObservableProperty] - private bool isEnabled = true; - - [ObservableProperty] - private string description = string.Empty; - - public bool Evaluate(ProcessModel process, SystemState systemState) - { - if (!this.IsEnabled) - { - return true; // Disabled conditions are considered true - } - - try - { - var actualValue = this.GetActualValue(process, systemState); - return CompareValues(actualValue, this.Value, this.SecondaryValue, this.ComparisonOperator); - } - catch (Exception) - { - return false; // Failed conditions are considered false - } - } - - private object? GetActualValue(ProcessModel process, SystemState systemState) - { - return this.ConditionType switch - { - ProfileConditionType.SystemLoad => systemState.CpuUsage, - ProfileConditionType.TimeOfDay => systemState.CurrentTime.TimeOfDay.TotalHours, - ProfileConditionType.PowerState => systemState.IsOnBattery, - ProfileConditionType.ProcessCount => systemState.ProcessCount, - ProfileConditionType.MemoryUsage => systemState.MemoryUsage, - ProfileConditionType.CpuTemperature => systemState.CpuTemperature, - ProfileConditionType.BatteryLevel => systemState.BatteryLevel, - ProfileConditionType.NetworkActivity => systemState.NetworkActivity, - ProfileConditionType.UserIdle => systemState.IsUserIdle, - ProfileConditionType.Custom => systemState.CustomProperties.GetValueOrDefault(this.Name), - _ => null, - }; - } - - private static bool CompareValues(object? actual, object? expected, object? secondary, ComparisonOperator op) - { - if (actual == null || expected == null) - { - return false; - } - - return op switch - { - ComparisonOperator.Equals => actual.Equals(expected), - ComparisonOperator.NotEquals => !actual.Equals(expected), - ComparisonOperator.GreaterThan => Comparer.Default.Compare(actual, expected) > 0, - ComparisonOperator.LessThan => Comparer.Default.Compare(actual, expected) < 0, - ComparisonOperator.GreaterThanOrEqual => Comparer.Default.Compare(actual, expected) >= 0, - ComparisonOperator.LessThanOrEqual => Comparer.Default.Compare(actual, expected) <= 0, - ComparisonOperator.Contains => actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false, - ComparisonOperator.NotContains => !(actual.ToString()?.Contains(expected.ToString() ?? string.Empty) ?? false), - ComparisonOperator.Between => secondary != null && - Comparer.Default.Compare(actual, expected) >= 0 && - Comparer.Default.Compare(actual, secondary) <= 0, - ComparisonOperator.NotBetween => secondary != null && - !(Comparer.Default.Compare(actual, expected) >= 0 && - Comparer.Default.Compare(actual, secondary) <= 0), - _ => false, - }; - } - } - - public partial class ConditionGroup : ObservableObject - { - [ObservableProperty] - private string name = string.Empty; - - [ObservableProperty] - private LogicalOperator logicalOperator = LogicalOperator.And; - - [ObservableProperty] - private List conditions = new(); - - [ObservableProperty] - private List subGroups = new(); - - [ObservableProperty] - private bool isEnabled = true; - - public bool Evaluate(ProcessModel process, SystemState systemState) - { - if (!this.IsEnabled) - { - return true; - } - - var conditionResults = this.Conditions.Select(c => c.Evaluate(process, systemState)).ToList(); - var subGroupResults = this.SubGroups.Select(g => g.Evaluate(process, systemState)).ToList(); - var allResults = conditionResults.Concat(subGroupResults).ToList(); - - if (!allResults.Any()) - { - return true; // No conditions means always true - } - - return this.LogicalOperator switch - { - LogicalOperator.And => allResults.All(r => r), - LogicalOperator.Or => allResults.Any(r => r), - LogicalOperator.Not => !allResults.All(r => r), - _ => false, - }; - } - } - - public partial class ConditionalProcessProfile : ProfileModel - { - [ObservableProperty] - private List conditionGroups = new(); - - [ObservableProperty] - private TimeSpan autoApplyDelay = TimeSpan.FromSeconds(5); - - [ObservableProperty] - private int priority = 0; // Higher priority profiles are applied first - - [ObservableProperty] - private bool isAutoApplyEnabled = true; - - [ObservableProperty] - private DateTime lastEvaluated = DateTime.MinValue; - - [ObservableProperty] - private DateTime lastApplied = DateTime.MinValue; - - [ObservableProperty] - private bool wasLastEvaluationTrue = false; - - [ObservableProperty] - private string lastEvaluationReason = string.Empty; - - public bool ShouldApply(ProcessModel process, SystemState systemState) - { - if (!this.IsAutoApplyEnabled) - { - return false; - } - - this.LastEvaluated = DateTime.UtcNow; - - try - { - // If no condition groups, always apply (like regular profile) - if (!this.ConditionGroups.Any()) - { - this.WasLastEvaluationTrue = true; - this.LastEvaluationReason = "No conditions defined"; - return true; - } - - // Evaluate all condition groups (AND logic between groups) - var results = this.ConditionGroups.Select(g => g.Evaluate(process, systemState)).ToList(); - var shouldApply = results.All(r => r); - - this.WasLastEvaluationTrue = shouldApply; - this.LastEvaluationReason = shouldApply - ? "All condition groups satisfied" - : $"Failed conditions: {string.Join(", ", this.ConditionGroups.Where((g, i) => !results[i]).Select(g => g.Name))}"; - - return shouldApply; - } - catch (Exception ex) - { - this.WasLastEvaluationTrue = false; - this.LastEvaluationReason = $"Evaluation error: {ex.Message}"; - return false; - } - } - - public bool CanApplyNow() - { - return DateTime.UtcNow - this.LastApplied >= this.AutoApplyDelay; - } - - public void MarkAsApplied() - { - this.LastApplied = DateTime.UtcNow; - } - } -} - diff --git a/Models/Core/IModel.cs b/Models/Core/ValidationResult.cs similarity index 67% rename from Models/Core/IModel.cs rename to Models/Core/ValidationResult.cs index 5055004d..eb9a6a48 100644 --- a/Models/Core/IModel.cs +++ b/Models/Core/ValidationResult.cs @@ -3,19 +3,6 @@ namespace ThreadPilot.Models.Core using System; using System.ComponentModel; - public interface IModel : INotifyPropertyChanged - { - string Id { get; } - - DateTime CreatedAt { get; } - - DateTime UpdatedAt { get; } - - ValidationResult Validate(); - - IModel Clone(); - } - public class ValidationResult { public bool IsValid { get; } diff --git a/Models/LogEventTypes.cs b/Models/LogEventTypes.cs index 87e2b751..4d1897a6 100644 --- a/Models/LogEventTypes.cs +++ b/Models/LogEventTypes.cs @@ -26,21 +26,6 @@ public static class ProcessMonitoring public const string AssociationTriggered = "AssociationTriggered"; } - public static class UserActions - { - public const string SettingsChanged = "SettingsChanged"; - public const string ProcessAffinityChanged = "ProcessAffinityChanged"; - public const string ProcessPriorityChanged = "ProcessPriorityChanged"; - public const string AssociationAdded = "AssociationAdded"; - public const string AssociationRemoved = "AssociationRemoved"; - public const string MonitoringToggled = "MonitoringToggled"; - public const string GameBoostToggled = "GameBoostToggled"; - public const string AutostartToggled = "AutostartToggled"; - public const string NotificationSettingsChanged = "NotificationSettingsChanged"; - public const string LogsExported = "LogsExported"; - public const string LogsCleared = "LogsCleared"; - } - public static class System { public const string ApplicationStarted = "ApplicationStarted"; @@ -79,19 +64,6 @@ public static class Performance } } - public static class LogCategories - { - public const string PowerPlan = "PowerPlan"; - public const string ProcessMonitoring = "ProcessMonitoring"; - public const string UserAction = "UserAction"; - public const string System = "System"; - public const string Error = "Error"; - public const string Performance = "Performance"; - public const string Security = "Security"; - public const string Configuration = "Configuration"; - public const string Lifecycle = "Lifecycle"; - } - public static class LogProperties { public const string ProcessName = "ProcessName"; @@ -111,77 +83,4 @@ public static class LogProperties public const string Version = "Version"; public const string Environment = "Environment"; } - - public static class LogDataBuilder - { - public static Dictionary CreateProcessData(string processName, int processId) - { - return new Dictionary - { - [LogProperties.ProcessName] = processName, - [LogProperties.ProcessId] = processId, - }; - } - - public static Dictionary CreatePowerPlanData(string planId, string planName) - { - return new Dictionary - { - [LogProperties.PowerPlanId] = planId, - [LogProperties.PowerPlanName] = planName, - }; - } - - public static Dictionary CreateGameData(string gameName) - { - return new Dictionary - { - [LogProperties.GameName] = gameName, - }; - } - - public static Dictionary CreatePerformanceData(long memoryUsage, double cpuUsage) - { - return new Dictionary - { - [LogProperties.MemoryUsage] = memoryUsage, - [LogProperties.CpuUsage] = cpuUsage, - }; - } - - public static Dictionary CreateErrorData(Exception exception) - { - var stackTrace = exception.StackTrace ?? "N/A"; - stackTrace = stackTrace[..Math.Min(2000, stackTrace.Length)]; - - return new Dictionary - { - [LogProperties.ErrorCode] = exception.HResult, - [LogProperties.StackTrace] = stackTrace, - ["ExceptionType"] = exception.GetType().Name, - ["InnerException"] = exception.InnerException?.Message ?? "N/A", - }; - } - - public static Dictionary CreateTimingData(TimeSpan duration) - { - return new Dictionary - { - [LogProperties.Duration] = duration.TotalMilliseconds, - }; - } - - public static Dictionary CreateSystemData() - { - return new Dictionary - { - [LogProperties.Version] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "Unknown", - [LogProperties.Environment] = Environment.OSVersion.ToString(), - [LogProperties.ThreadId] = Thread.CurrentThread.ManagedThreadId, - ["MachineName"] = Environment.MachineName, - ["UserName"] = Environment.UserName, - }; - } - } } - diff --git a/Models/ProcessModel.cs b/Models/ProcessModel.cs index 3b54b211..cbe6c25f 100644 --- a/Models/ProcessModel.cs +++ b/Models/ProcessModel.cs @@ -59,6 +59,14 @@ public partial class ProcessModel : ObservableObject [ObservableProperty] private bool isRegistryPriorityEnabled; + internal DateTime? StartTimeUtc { get; set; } + + internal bool IsSameInstance(ProcessModel other) => + this.ProcessId == other.ProcessId + && (this.StartTimeUtc.HasValue && other.StartTimeUtc.HasValue + ? this.StartTimeUtc == other.StartTimeUtc + : string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase)); + public void ForceNotifyProcessorAffinityChanged() { this.OnPropertyChanged(nameof(this.ProcessorAffinity)); diff --git a/Models/ProcessPowerPlanAssociation.cs b/Models/ProcessPowerPlanAssociation.cs index 7f22da40..ec60f7c9 100644 --- a/Models/ProcessPowerPlanAssociation.cs +++ b/Models/ProcessPowerPlanAssociation.cs @@ -7,7 +7,7 @@ namespace ThreadPilot.Models using ThreadPilot.Helpers; using ThreadPilot.Models.Core; - public partial class ProcessPowerPlanAssociation : ObservableObject, IModel + public partial class ProcessPowerPlanAssociation : ObservableObject { [ObservableProperty] private string id = Guid.NewGuid().ToString(); @@ -42,8 +42,6 @@ public partial class ProcessPowerPlanAssociation : ObservableObject, IModel [ObservableProperty] private DateTime updatedAt = DateTime.UtcNow; - // IModel implementation - properties are auto-generated by ObservableProperty - [ObservableProperty] private string description = string.Empty; @@ -129,11 +127,11 @@ public ValidationResult Validate() return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); } - public IModel Clone() + internal ProcessPowerPlanAssociation CreateSnapshot() { return new ProcessPowerPlanAssociation { - id = Guid.NewGuid().ToString(), // New ID for clone + Id = this.Id, ExecutableName = this.ExecutableName, ExecutablePath = this.ExecutablePath, PowerPlanGuid = this.PowerPlanGuid, @@ -144,8 +142,9 @@ public IModel Clone() IsEnabled = this.IsEnabled, Description = this.Description, MatchByPath = this.MatchByPath, - createdAt = DateTime.UtcNow, - updatedAt = DateTime.UtcNow, + Priority = this.Priority, + CreatedAt = this.CreatedAt, + UpdatedAt = this.UpdatedAt, }; } } diff --git a/Models/ProfileModel.cs b/Models/ProfileModel.cs deleted file mode 100644 index 8bc73d06..00000000 --- a/Models/ProfileModel.cs +++ /dev/null @@ -1,91 +0,0 @@ -namespace ThreadPilot.Models -{ - using System; - using System.Collections.Generic; - using System.ComponentModel; - using System.Diagnostics; - using CommunityToolkit.Mvvm.ComponentModel; - using ThreadPilot.Models.Core; - - public partial class ProfileModel : ObservableObject, IModel - { - [ObservableProperty] - private string id = Guid.NewGuid().ToString(); - - [ObservableProperty] - private DateTime createdAt = DateTime.UtcNow; - - [ObservableProperty] - private DateTime updatedAt = DateTime.UtcNow; - - [ObservableProperty] - private string name = string.Empty; - - [ObservableProperty] - private string processName = string.Empty; - - [ObservableProperty] - private ProcessPriorityClass priority = ProcessPriorityClass.Normal; - - [ObservableProperty] - private long processorAffinity = -1; // All cores - - [ObservableProperty] - private int profileSchemaVersion = CpuAffinityProfileSchemaVersions.Legacy; - - [ObservableProperty] - private CpuSelection? cpuSelection = null; - - [ObservableProperty] - private CpuSelectionMigrationMetadata? cpuSelectionMigration = null; - - [ObservableProperty] - private string description = string.Empty; - - [ObservableProperty] - private bool isEnabled = true; - - // IModel implementation - properties are auto-generated by ObservableProperty - - public ValidationResult Validate() - { - var errors = new List(); - - if (string.IsNullOrWhiteSpace(this.Name)) - { - errors.Add("Profile name is required"); - } - - if (string.IsNullOrWhiteSpace(this.ProcessName)) - { - errors.Add("Process name is required"); - } - - return errors.Count == 0 ? ValidationResult.Success() : ValidationResult.Failure(errors.ToArray()); - } - - public IModel Clone() - { - return new ProfileModel - { - id = Guid.NewGuid().ToString(), // New ID for clone - Name = this.Name, - ProcessName = this.ProcessName, - Priority = this.Priority, - ProcessorAffinity = this.ProcessorAffinity, - ProfileSchemaVersion = this.ProfileSchemaVersion, - CpuSelection = this.CpuSelection, - CpuSelectionMigration = this.CpuSelectionMigration, - Description = this.Description, - IsEnabled = this.IsEnabled, - createdAt = DateTime.UtcNow, - updatedAt = DateTime.UtcNow, - }; - } - - partial void OnUpdatedAtChanged(DateTime value) - { - updatedAt = DateTime.UtcNow; - } - } -} diff --git a/Models/ThreadPilotException.cs b/Models/ThreadPilotException.cs deleted file mode 100644 index 9ff88cb2..00000000 --- a/Models/ThreadPilotException.cs +++ /dev/null @@ -1,115 +0,0 @@ -/* - * ThreadPilot - exception hierarchy and error code registry. - */ -namespace ThreadPilot.Models -{ - using System; - - public enum ErrorCode - { - Unknown = 0, - ProcessManagement = 1000, - Privilege = 2000, - RuleEngine = 3000, - ResourceOptimization = 4000, - Persistence = 5000, - Unhandled = 9000, - } - - public class ThreadPilotException : Exception - { - public ThreadPilotException() - : this("A ThreadPilot error has occurred.", ErrorCode.Unknown) - { - } - - public ThreadPilotException(string message) - : this(message, ErrorCode.Unknown) - { - } - - public ThreadPilotException(string message, Exception innerException) - : this(message, ErrorCode.Unknown, innerException) - { - } - - public ThreadPilotException(string message, ErrorCode errorCode) - : base(message) - { - this.ErrorCode = errorCode; - } - - public ThreadPilotException(string message, ErrorCode errorCode, Exception innerException) - : base(message, innerException) - { - this.ErrorCode = errorCode; - } - - public ErrorCode ErrorCode { get; } - } - - public sealed class ProcessManagementException : ThreadPilotException - { - public ProcessManagementException(string message) - : base(message, ErrorCode.ProcessManagement) - { - } - - public ProcessManagementException(string message, Exception innerException) - : base(message, ErrorCode.ProcessManagement, innerException) - { - } - } - - public sealed class PrivilegeException : ThreadPilotException - { - public PrivilegeException(string message) - : base(message, ErrorCode.Privilege) - { - } - - public PrivilegeException(string message, Exception innerException) - : base(message, ErrorCode.Privilege, innerException) - { - } - } - - public sealed class RuleEngineException : ThreadPilotException - { - public RuleEngineException(string message) - : base(message, ErrorCode.RuleEngine) - { - } - - public RuleEngineException(string message, Exception innerException) - : base(message, ErrorCode.RuleEngine, innerException) - { - } - } - - public sealed class ResourceOptimizationException : ThreadPilotException - { - public ResourceOptimizationException(string message) - : base(message, ErrorCode.ResourceOptimization) - { - } - - public ResourceOptimizationException(string message, Exception innerException) - : base(message, ErrorCode.ResourceOptimization, innerException) - { - } - } - - public sealed class PersistenceException : ThreadPilotException - { - public PersistenceException(string message) - : base(message, ErrorCode.Persistence) - { - } - - public PersistenceException(string message, Exception innerException) - : base(message, ErrorCode.Persistence, innerException) - { - } - } -} diff --git a/Services/Abstractions/IGitHubReleaseClient.cs b/Services/Abstractions/IGitHubReleaseClient.cs index b6ba850c..e0ce122f 100644 --- a/Services/Abstractions/IGitHubReleaseClient.cs +++ b/Services/Abstractions/IGitHubReleaseClient.cs @@ -5,8 +5,6 @@ namespace ThreadPilot.Services.Abstractions public interface IGitHubReleaseClient { - Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default); - Task GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default); } } diff --git a/Services/ApplicationSettingsService.cs b/Services/ApplicationSettingsService.cs index 8320c37f..06ef9431 100644 --- a/Services/ApplicationSettingsService.cs +++ b/Services/ApplicationSettingsService.cs @@ -5,6 +5,7 @@ namespace ThreadPilot.Services using System.IO; using System.Text; using System.Text.Json; + using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using ThreadPilot.Helpers; @@ -18,7 +19,8 @@ public class ApplicationSettingsService : IApplicationSettingsService private readonly string settingsFilePath; private readonly string? legacySettingsPath; private readonly Func systemUiCultureProvider; - private ApplicationSettingsModel settings; + private readonly SemaphoreSlim settingsGate = new(1, 1); + private volatile ApplicationSettingsModel settings; private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true, @@ -30,7 +32,7 @@ public class ApplicationSettingsService : IApplicationSettingsService public event EventHandler? SettingsChanged; - public ApplicationSettingsModel Settings => (ApplicationSettingsModel)this.settings.Clone(); + public ApplicationSettingsModel Settings => this.settings.Clone(); public ApplicationSettingsService(ILogger logger) : this( @@ -61,6 +63,19 @@ public ApplicationSettingsService( } public async Task LoadSettingsAsync() + { + await this.settingsGate.WaitAsync(); + try + { + await this.LoadSettingsCoreAsync(); + } + finally + { + this.settingsGate.Release(); + } + } + + private async Task LoadSettingsCoreAsync() { try { @@ -69,8 +84,9 @@ public async Task LoadSettingsAsync() if (!this.settingsStorage.Exists(this.settingsFilePath)) { this.logger.LogInformation("Settings file not found, using defaults"); - this.settings = this.CreateDefaultSettings(); - await this.SaveSettingsAsync(); + var defaults = this.CreateDefaultSettings(); + await this.PersistAsync(defaults); + this.settings = defaults; return; } @@ -78,8 +94,9 @@ public async Task LoadSettingsAsync() if (string.IsNullOrWhiteSpace(json)) { this.logger.LogWarning("Settings file was empty, using defaults"); - this.settings = this.CreateDefaultSettings(); - await this.SaveSettingsAsync(); + var defaults = this.CreateDefaultSettings(); + await this.PersistAsync(defaults); + this.settings = defaults; return; } @@ -127,12 +144,11 @@ public async Task LoadSettingsAsync() loadedSettings.Language, this.systemUiCultureProvider()); - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); - this.settings.CopyFrom(loadedSettings); - this.ValidateAndFixSettings(); + var oldSettings = this.settings; + this.ValidateAndFixSettings(loadedSettings); - var migrationChangedSettings = CpuAssignmentModeMigrationPolicy.Apply(this.settings); - if (CpuAssignmentModeMigrationPolicy.ShouldShowNotice(this.settings)) + var migrationChangedSettings = CpuAssignmentModeMigrationPolicy.Apply(loadedSettings); + if (CpuAssignmentModeMigrationPolicy.ShouldShowNotice(loadedSettings)) { this.logger.LogInformation( "Migrated the default CPU assignment mode from Automatic to AffinityMask. Automatic applies CPU Sets only, which does not change the affinity mask Windows enforces."); @@ -142,7 +158,7 @@ public async Task LoadSettingsAsync() { try { - await this.SaveSettingsAsync(); + await this.PersistAsync(loadedSettings); } catch (Exception ex) { @@ -153,14 +169,16 @@ public async Task LoadSettingsAsync() } } + this.settings = loadedSettings; this.logger.LogInformation("Settings loaded successfully"); - this.OnSettingsChanged(oldSettings, this.settings); + this.OnSettingsChanged(oldSettings, loadedSettings); } else { this.logger.LogWarning("Failed to deserialize settings, using defaults"); - this.settings = this.CreateDefaultSettings(); - await this.SaveSettingsAsync(); + var defaults = this.CreateDefaultSettings(); + await this.PersistAsync(defaults); + this.settings = defaults; } } catch (Exception ex) @@ -170,73 +188,64 @@ public async Task LoadSettingsAsync() } } - public async Task SaveSettingsAsync() - { - try - { - this.logger.LogDebug("Saving application settings to {FilePath}", this.settingsFilePath); - - this.ValidateAndFixSettings(); - - var json = JsonSerializer.Serialize(this.settings, JsonOptions); - await this.settingsStorage.WriteAsync(this.settingsFilePath, json); + public Task SaveSettingsAsync() => + this.CommitAsync(current => current.Clone(), notify: false); - this.logger.LogDebug("Settings saved successfully"); - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error saving settings"); - throw; - } + public Task UpdateSettingsAsync(ApplicationSettingsModel newSettings) + { + ArgumentNullException.ThrowIfNull(newSettings); + var replacement = newSettings.Clone(); + replacement.Language = LocalizationService.ResolveLanguagePreference(newSettings.Language, this.systemUiCultureProvider()); + return this.CommitAsync(_ => replacement); } - public async Task UpdateSettingsAsync(ApplicationSettingsModel newSettings) + public Task EditSettingsAsync(Action edit) { - if (newSettings == null) + ArgumentNullException.ThrowIfNull(edit); + return this.CommitAsync(current => { - throw new ArgumentNullException(nameof(newSettings)); - } + var draft = current.Clone(); + edit(draft); + return draft.Clone(); + }); + } + public Task ResetToDefaultsAsync() => + this.CommitAsync(_ => this.CreateDefaultSettings()); + + private async Task CommitAsync( + Func createDraft, + bool notify = true) + { + await this.settingsGate.WaitAsync(); try { - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); - var resolvedLanguage = LocalizationService.ResolveLanguagePreference( - newSettings.Language, - this.systemUiCultureProvider()); - this.settings.CopyFrom(newSettings); - this.settings.Language = resolvedLanguage; - - await this.SaveSettingsAsync(); + var previous = this.settings; + var draft = createDraft(previous); + this.ValidateAndFixSettings(draft); + await this.PersistAsync(draft); + this.settings = draft; - this.OnSettingsChanged(oldSettings, this.settings); - this.logger.LogInformation("Settings updated successfully"); + if (notify) + { + this.OnSettingsChanged(previous, draft); + } } catch (Exception ex) { - this.logger.LogError(ex, "Error updating settings"); + this.logger.LogError(ex, "Error saving application settings"); throw; } + finally + { + this.settingsGate.Release(); + } } - public async Task ResetToDefaultsAsync() + private Task PersistAsync(ApplicationSettingsModel draft) { - try - { - this.logger.LogInformation("Resetting settings to defaults"); - - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); - this.settings = this.CreateDefaultSettings(); - - await this.SaveSettingsAsync(); - - this.OnSettingsChanged(oldSettings, this.settings); - this.logger.LogInformation("Settings reset to defaults"); - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error resetting settings to defaults"); - throw; - } + var json = JsonSerializer.Serialize(draft, JsonOptions); + return this.settingsStorage.WriteAsync(this.settingsFilePath, json); } public string GetSettingsFilePath() @@ -244,59 +253,59 @@ public string GetSettingsFilePath() return this.settingsFilePath; } - public void ValidateAndFixSettings() + private void ValidateAndFixSettings(ApplicationSettingsModel draft) { // Validate and fix notification durations - if (this.settings.NotificationDisplayDurationMs < 1000) + if (draft.NotificationDisplayDurationMs < 1000) { - this.settings.NotificationDisplayDurationMs = 1000; + draft.NotificationDisplayDurationMs = 1000; } - if (this.settings.NotificationDisplayDurationMs > 30000) + if (draft.NotificationDisplayDurationMs > 30000) { - this.settings.NotificationDisplayDurationMs = 30000; + draft.NotificationDisplayDurationMs = 30000; } - if (this.settings.BalloonNotificationTimeoutMs < 1000) + if (draft.BalloonNotificationTimeoutMs < 1000) { - this.settings.BalloonNotificationTimeoutMs = 1000; + draft.BalloonNotificationTimeoutMs = 1000; } - if (this.settings.BalloonNotificationTimeoutMs > 60000) + if (draft.BalloonNotificationTimeoutMs > 60000) { - this.settings.BalloonNotificationTimeoutMs = 60000; + draft.BalloonNotificationTimeoutMs = 60000; } // Validate notification history - if (this.settings.MaxNotificationHistoryItems < 10) + if (draft.MaxNotificationHistoryItems < 10) { - this.settings.MaxNotificationHistoryItems = 10; + draft.MaxNotificationHistoryItems = 10; } - if (this.settings.MaxNotificationHistoryItems > 1000) + if (draft.MaxNotificationHistoryItems > 1000) { - this.settings.MaxNotificationHistoryItems = 1000; + draft.MaxNotificationHistoryItems = 1000; } // Validate custom icon path - if (this.settings.UseCustomTrayIcon && !string.IsNullOrEmpty(this.settings.CustomTrayIconPath)) + if (draft.UseCustomTrayIcon && !string.IsNullOrEmpty(draft.CustomTrayIconPath)) { - if (!File.Exists(this.settings.CustomTrayIconPath)) + if (!File.Exists(draft.CustomTrayIconPath)) { - this.logger.LogWarning("Custom tray icon file not found: {Path}", this.settings.CustomTrayIconPath); - this.settings.UseCustomTrayIcon = false; + this.logger.LogWarning("Custom tray icon file not found: {Path}", draft.CustomTrayIconPath); + draft.UseCustomTrayIcon = false; } } - this.settings.Language = LocalizationService.ResolveLanguagePreference( - this.settings.Language, - this.systemUiCultureProvider()); - - if (!Enum.IsDefined(this.settings.DefaultCpuAssignmentMode)) - { - // Repair to the shipped default rather than Automatic; see CopyFrom. - this.settings.DefaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask; - } + draft.Language = LocalizationService.ResolveLanguagePreference( + draft.Language, + this.systemUiCultureProvider()); + + if (!Enum.IsDefined(draft.DefaultCpuAssignmentMode)) + { + // Repair to the shipped default rather than Automatic; see CopyFrom. + draft.DefaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask; + } } public async Task ExportSettingsAsync(string filePath) @@ -359,8 +368,8 @@ private void OnSettingsChanged(ApplicationSettingsModel oldSettings, Application // In a more sophisticated implementation, we could track specific property changes var changedProperties = new[] { "Settings" }; - var oldSnapshot = (ApplicationSettingsModel)oldSettings.Clone(); - var newSnapshot = (ApplicationSettingsModel)newSettings.Clone(); + var oldSnapshot = oldSettings.Clone(); + var newSnapshot = newSettings.Clone(); this.SettingsChanged?.Invoke(this, new ApplicationSettingsChangedEventArgs( oldSnapshot, newSnapshot, changedProperties)); diff --git a/Services/ConditionalProfileService.cs b/Services/ConditionalProfileService.cs deleted file mode 100644 index 677ed3da..00000000 --- a/Services/ConditionalProfileService.cs +++ /dev/null @@ -1,570 +0,0 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Linq; - using System.Text.Json; - using System.Threading; - using System.Threading.Tasks; - using System.Windows.Forms; - using Microsoft.Extensions.Logging; - using ThreadPilot.Models; - - public class ConditionalProfileService : IConditionalProfileService, IDisposable - { - private readonly ILogger logger; - private readonly IProcessService processService; - private readonly List profiles = new(); - private readonly System.Threading.Timer monitoringTimer; - private readonly SemaphoreSlim profileLock = new(1, 1); - - private SystemState lastSystemState = new(); - private bool isMonitoring; - private bool disposed; - - public bool IsMonitoring => this.isMonitoring; - - public event EventHandler? ProfileApplied; - - public event EventHandler? ProfileConflictResolved; - - public event EventHandler? SystemStateChanged; - - public ConditionalProfileService( - ILogger logger, - IProcessService processService) - { - this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); - this.processService = processService ?? throw new ArgumentNullException(nameof(processService)); - - // Set up monitoring timer (check every 10 seconds) - this.monitoringTimer = new System.Threading.Timer(this.MonitoringCallback, null, Timeout.Infinite, Timeout.Infinite); - } - - public async Task InitializeAsync() - { - this.logger.LogInformation("Initializing ConditionalProfileService"); - - // Load initial system state - this.lastSystemState = await this.GetSystemStateAsync().ConfigureAwait(false); - - // Create some default profiles for demonstration - await this.CreateDefaultProfilesAsync().ConfigureAwait(false); - } - - public async Task AddProfileAsync(ConditionalProcessProfile profile) - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - var (isValid, errors) = await this.ValidateProfileAsync(profile).ConfigureAwait(false); - if (!isValid) - { - throw new ArgumentException($"Invalid profile: {string.Join(", ", errors)}"); - } - - this.profiles.Add(profile); - this.logger.LogInformation( - "Added conditional profile: {ProfileName} for process {ProcessName}", - profile.Name, profile.ProcessName); - } - finally - { - this.profileLock.Release(); - } - } - - public async Task RemoveProfileAsync(string profileId) - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - var profile = this.profiles.FirstOrDefault(p => p.Id == profileId); - if (profile != null) - { - this.profiles.Remove(profile); - this.logger.LogInformation("Removed conditional profile: {ProfileName}", profile.Name); - } - } - finally - { - this.profileLock.Release(); - } - } - - public async Task UpdateProfileAsync(ConditionalProcessProfile profile) - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - var existingProfile = this.profiles.FirstOrDefault(p => p.Id == profile.Id); - if (existingProfile != null) - { - var index = this.profiles.IndexOf(existingProfile); - this.profiles[index] = profile; - this.logger.LogInformation("Updated conditional profile: {ProfileName}", profile.Name); - } - } - finally - { - this.profileLock.Release(); - } - } - - public async Task> GetAllProfilesAsync() - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - return this.profiles.ToList(); - } - finally - { - this.profileLock.Release(); - } - } - - public async Task> GetProfilesForProcessAsync(string processName) - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - return this.profiles - .Where(p => p.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)) - .ToList(); - } - finally - { - this.profileLock.Release(); - } - } - - public async Task> EvaluateProfilesAsync(ProcessModel process) - { - var systemState = await this.GetSystemStateAsync().ConfigureAwait(false); - var applicableProfiles = new List(); - - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - var processProfiles = this.profiles - .Where(p => p.ProcessName.Equals(process.Name, StringComparison.OrdinalIgnoreCase)) - .ToList(); - - foreach (var profile in processProfiles) - { - if (profile.ShouldApply(process, systemState) && profile.CanApplyNow()) - { - applicableProfiles.Add(profile); - } - } - - // Sort by priority (higher priority first) - applicableProfiles.Sort((a, b) => b.Priority.CompareTo(a.Priority)); - } - finally - { - this.profileLock.Release(); - } - - return applicableProfiles; - } - - public async Task ApplyBestProfileAsync(ProcessModel process) - { - try - { - var applicableProfiles = await this.EvaluateProfilesAsync(process).ConfigureAwait(false); - - if (!applicableProfiles.Any()) - { - return false; - } - - ConditionalProcessProfile selectedProfile; - - if (applicableProfiles.Count == 1) - { - selectedProfile = applicableProfiles[0]; - } - else - { - // Handle conflicts - selectedProfile = this.ResolveProfileConflict(applicableProfiles, process); - - this.ProfileConflictResolved?.Invoke(this, new ProfileConflictEventArgs - { - ConflictingProfiles = applicableProfiles, - Process = process, - SelectedProfile = selectedProfile, - Resolution = "Priority-based selection", - }); - } - - // Apply the profile (simplified - would use actual process service) - var success = await this.ApplyProfileToProcessAsync(process, selectedProfile).ConfigureAwait(false); - - if (success) - { - selectedProfile.MarkAsApplied(); - - this.ProfileApplied?.Invoke(this, new ProfileApplicationEventArgs - { - Profile = selectedProfile, - Process = process, - SystemState = await this.GetSystemStateAsync().ConfigureAwait(false), - WasApplied = true, - Reason = "Conditions satisfied", - }); - } - - return success; - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error applying profile for process {ProcessName}", process.Name); - return false; - } - } - - public async Task GetSystemStateAsync() - { - var systemState = new SystemState - { - CurrentTime = DateTime.Now, - CpuUsage = await this.GetCpuUsageAsync().ConfigureAwait(false), - MemoryUsage = await this.GetMemoryUsageAsync().ConfigureAwait(false), - ProcessCount = await this.GetProcessCountAsync().ConfigureAwait(false), - IsOnBattery = this.GetBatteryStatus(), - BatteryLevel = this.GetBatteryLevel(), - IsUserIdle = this.GetUserIdleStatus(), - UserIdleTime = this.GetUserIdleTime(), - NetworkActivity = await this.GetNetworkActivityAsync().ConfigureAwait(false), - }; - - if (this.HasSystemStateChangedSignificantly(systemState, this.lastSystemState)) - { - this.SystemStateChanged?.Invoke(this, systemState); - this.lastSystemState = systemState; - } - - return systemState; - } - - public async Task StartMonitoringAsync() - { - if (this.isMonitoring) - { - return; - } - - this.logger.LogInformation("Starting conditional profile monitoring"); - this.isMonitoring = true; - - // Start monitoring timer (check every 10 seconds) - this.monitoringTimer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(10)); - } - - public async Task StopMonitoringAsync() - { - if (!this.isMonitoring) - { - return; - } - - this.logger.LogInformation("Stopping conditional profile monitoring"); - this.isMonitoring = false; - - this.monitoringTimer.Change(Timeout.Infinite, Timeout.Infinite); - } - - public ConditionalProcessProfile ResolveProfileConflict(List conflictingProfiles, ProcessModel process) - { - // Simple resolution: highest priority wins - return conflictingProfiles.OrderByDescending(p => p.Priority).First(); - } - - public ConditionalProcessProfile CreateDefaultProfile(string processName) - { - return new ConditionalProcessProfile - { - Id = Guid.NewGuid().ToString(), - Name = $"Default Profile for {processName}", - ProcessName = processName, - Priority = 0, - AutoApplyDelay = TimeSpan.FromSeconds(5), - IsAutoApplyEnabled = true, - ConditionGroups = new List - { - new ConditionGroup - { - Name = "Default Conditions", - LogicalOperator = LogicalOperator.And, - Conditions = new List - { - new ProfileCondition - { - Name = "High CPU Usage", - ConditionType = ProfileConditionType.SystemLoad, - ComparisonOperator = ComparisonOperator.GreaterThan, - Value = 50.0, - Description = "Apply when system CPU usage is above 50%" - } - } - } - }, - }; - } - - public async Task<(bool IsValid, List Errors)> ValidateProfileAsync(ConditionalProcessProfile profile) - { - var errors = new List(); - - if (string.IsNullOrWhiteSpace(profile.Name)) - { - errors.Add("Profile name is required"); - } - - if (string.IsNullOrWhiteSpace(profile.ProcessName)) - { - errors.Add("Process name is required"); - } - - if (profile.AutoApplyDelay < TimeSpan.Zero) - { - errors.Add("Auto-apply delay cannot be negative"); - } - - // Validate condition groups - foreach (var group in profile.ConditionGroups) - { - if (!group.Conditions.Any() && !group.SubGroups.Any()) - { - errors.Add($"Condition group '{group.Name}' must have at least one condition or sub-group"); - } - } - - return (errors.Count == 0, errors); - } - - public async Task ExportProfilesToJsonAsync() - { - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - return JsonSerializer.Serialize(this.profiles, new JsonSerializerOptions { WriteIndented = true }); - } - finally - { - this.profileLock.Release(); - } - } - - public async Task ImportProfilesFromJsonAsync(string json) - { - try - { - var importedProfiles = JsonSerializer.Deserialize>(json); - if (importedProfiles == null) - { - return 0; - } - - await this.profileLock.WaitAsync().ConfigureAwait(false); - try - { - var validProfiles = 0; - foreach (var profile in importedProfiles) - { - var (isValid, _) = await this.ValidateProfileAsync(profile).ConfigureAwait(false); - if (isValid) - { - this.profiles.Add(profile); - validProfiles++; - } - } - - this.logger.LogInformation( - "Imported {ValidProfiles} valid profiles out of {TotalProfiles}", - validProfiles, importedProfiles.Count); - - return validProfiles; - } - finally - { - this.profileLock.Release(); - } - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error importing profiles from JSON"); - return 0; - } - } - - private void MonitoringCallback(object? state) - { - TaskSafety.FireAndForget(this.MonitoringCallbackAsync(), ex => - { - this.logger.LogWarning(ex, "Error during profile monitoring cycle"); - }); - } - - private async Task MonitoringCallbackAsync() - { - if (!this.isMonitoring) - { - return; - } - - try - { - var processes = await this.processService.GetProcessesAsync().ConfigureAwait(false); - foreach (var process in processes) - { - await this.ApplyBestProfileAsync(process).ConfigureAwait(false); - } - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Error during profile monitoring cycle"); - } - } - - private async Task ApplyProfileToProcessAsync(ProcessModel process, ConditionalProcessProfile profile) - { - try - { - // Simplified profile application - would use actual process service methods - this.logger.LogInformation( - "Applying profile {ProfileName} to process {ProcessName}", - profile.Name, process.Name); - return true; - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error applying profile {ProfileName} to process {ProcessName}", - profile.Name, process.Name); - return false; - } - } - - private async Task CreateDefaultProfilesAsync() - { - // Create some example conditional profiles - var gameProfile = new ConditionalProcessProfile - { - Id = Guid.NewGuid().ToString(), - Name = "High Performance Gaming", - ProcessName = "*", // Wildcard for any process - Priority = 10, - AutoApplyDelay = TimeSpan.FromSeconds(3), - ConditionGroups = new List - { - new ConditionGroup - { - Name = "Gaming Conditions", - LogicalOperator = LogicalOperator.And, - Conditions = new List - { - new ProfileCondition - { - Name = "High CPU Usage", - ConditionType = ProfileConditionType.SystemLoad, - ComparisonOperator = ComparisonOperator.GreaterThan, - Value = 70.0 - }, - new ProfileCondition - { - Name = "Evening Hours", - ConditionType = ProfileConditionType.TimeOfDay, - ComparisonOperator = ComparisonOperator.Between, - Value = 18.0, // 6 PM - SecondaryValue = 23.0 // 11 PM - } - } - } - }, - }; - - await this.AddProfileAsync(gameProfile).ConfigureAwait(false); - } - - private Task GetCpuUsageAsync() - { - // Simplified CPU usage calculation - return Task.FromResult(Environment.ProcessorCount * 10.0); // Placeholder - } - - private Task GetMemoryUsageAsync() - { - var totalMemory = GC.GetTotalMemory(false); - return Task.FromResult(totalMemory / (1024.0 * 1024.0)); // MB - } - - private async Task GetProcessCountAsync() - { - var processes = await this.processService.GetProcessesAsync().ConfigureAwait(false); - return processes.Count; - } - - private bool GetBatteryStatus() - { - return SystemInformation.PowerStatus.PowerLineStatus == PowerLineStatus.Offline; - } - - private int GetBatteryLevel() - { - return (int)(SystemInformation.PowerStatus.BatteryLifePercent * 100); - } - - private bool GetUserIdleStatus() - { - return this.GetUserIdleTime() > TimeSpan.FromMinutes(5); - } - - private TimeSpan GetUserIdleTime() - { - // Simplified - would use Windows API to get actual idle time - return TimeSpan.FromMinutes(1); - } - - private async Task GetNetworkActivityAsync() - { - // Simplified network activity measurement - return 0.0; // Placeholder - } - - private bool HasSystemStateChangedSignificantly(SystemState current, SystemState previous) - { - const double cpuThreshold = 10.0; - const double memoryThreshold = 100.0; // MB - - return Math.Abs(current.CpuUsage - previous.CpuUsage) > cpuThreshold || - Math.Abs(current.MemoryUsage - previous.MemoryUsage) > memoryThreshold || - current.IsOnBattery != previous.IsOnBattery; - } - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - this.monitoringTimer?.Dispose(); - this.profileLock?.Dispose(); - this.logger.LogInformation("ConditionalProfileService disposed"); - } - this.disposed = true; - } - } - - public void Dispose() - { - this.Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } -} - diff --git a/Services/ConfigurationBackupService.cs b/Services/ConfigurationBackupService.cs index 71d06a2f..a4700069 100644 --- a/Services/ConfigurationBackupService.cs +++ b/Services/ConfigurationBackupService.cs @@ -86,61 +86,36 @@ public static void Validate(ConfigurationBackup backup) public async Task ApplyAsync(ConfigurationBackup backup) { Validate(backup); - var previous = await this.CaptureAsync(settings.Settings); - try + await rules.ReplaceForImportAsync(backup.PersistentProcessRules, async () => { - if (backup.PersistentProcessRules != null) - { - await rules.SaveAsync(backup.PersistentProcessRules); - } - + var previousAssociations = Clone(associations.Configuration); if (!await associations.ReplaceConfigurationAsync(backup.ProcessMonitorConfiguration!)) { throw new IOException("Could not save power plan associations."); } - await settings.UpdateSettingsAsync(backup.Settings!); - } - catch (Exception importError) - { - var errors = new List { importError }; try { - await rules.SaveAsync(previous.PersistentProcessRules!); - } - catch (Exception ex) - { - errors.Add(ex); + // Settings commit last and publish only after persistence succeeds. + await settings.UpdateSettingsAsync(backup.Settings!); } - - try + catch (Exception importError) { - if (!await associations.ReplaceConfigurationAsync(previous.ProcessMonitorConfiguration!)) + try { - throw new IOException("Could not restore power plan associations."); + if (!await associations.ReplaceConfigurationAsync(previousAssociations)) + { + throw new IOException("Could not restore power plan associations."); + } + } + catch (Exception rollbackError) + { + throw new AggregateException("Import failed and power plan associations could not be restored.", importError, rollbackError); } - } - catch (Exception ex) - { - errors.Add(ex); - } - - try - { - await settings.UpdateSettingsAsync(previous.Settings!); - } - catch (Exception ex) - { - errors.Add(ex); - } - if (errors.Count > 1) - { - throw new AggregateException("Import failed and restoration was incomplete.", errors); + throw; } - - throw; - } + }); } private static T Clone(T source) => JsonSerializer.Deserialize(JsonSerializer.Serialize(source, JsonOptions), JsonOptions)!; diff --git a/Services/CoreMaskService.cs b/Services/CoreMaskService.cs index 156ede25..fb5c5ba5 100644 --- a/Services/CoreMaskService.cs +++ b/Services/CoreMaskService.cs @@ -485,8 +485,14 @@ public async Task UpdateProfilesToDefaultMaskAsync(string maskId) { association.CoreMaskId = allCoresMask.Id; association.CoreMaskName = allCoresMask.Name; - await associationService.UpdateAssociationAsync(association); - this.logger.LogInformation("Updated association '{Name}' to use 'All Cores' mask", association.ExecutableName); + if (await associationService.UpdateAssociationAsync(association)) + { + this.logger.LogInformation("Updated association '{Name}' to use 'All Cores' mask", association.ExecutableName); + } + else + { + this.logger.LogWarning("Could not update association '{Name}' to use 'All Cores' mask", association.ExecutableName); + } } } } diff --git a/Services/EnhancedLoggingService.cs b/Services/EnhancedLoggingService.cs index 206132e5..ece224b9 100644 --- a/Services/EnhancedLoggingService.cs +++ b/Services/EnhancedLoggingService.cs @@ -5,6 +5,7 @@ namespace ThreadPilot.Services using System.Collections.Generic; using System.IO; using System.Linq; + using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -12,17 +13,21 @@ namespace ThreadPilot.Services public class EnhancedLoggingService : IEnhancedLoggingService, IDisposable { + private const int MaxQueuedEntries = 4096; private readonly ILogger logger; private readonly IApplicationSettingsService settingsService; private readonly SemaphoreSlim fileLock = new(1, 1); - private readonly ConcurrentQueue logQueue = new(); + private readonly Queue logQueue = new(); private readonly System.Threading.Timer flushTimer; private readonly string logDirectory; private string currentLogFilePath; private int flushScheduled; private bool isInitialized; - private bool disposed; + private volatile bool disposed; private volatile bool isDebugLoggingEnabled; + private List? pendingBatch; + private long? pendingWriteOffset; + private int droppedEntries; // PERFORMANCE IMPROVEMENT: Correlation tracking for better debugging internal readonly AsyncLocal CorrelationId = new(); @@ -37,12 +42,18 @@ public class EnhancedLoggingService : IEnhancedLoggingService, IDisposable public event EventHandler? CriticalErrorOccurred; public EnhancedLoggingService(ILogger logger, IApplicationSettingsService settingsService) + : this(logger, settingsService, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ThreadPilot", "Logs")) + { + } + + internal EnhancedLoggingService( + ILogger logger, IApplicationSettingsService settingsService, string logDirectory) { this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); // Set up log directory - this.logDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ThreadPilot", "Logs"); + this.logDirectory = logDirectory; this.currentLogFilePath = this.GetCurrentLogFilePath(); this.isDebugLoggingEnabled = settingsService.Settings.EnableDebugLogging; @@ -235,18 +246,41 @@ private async Task LogStructuredEventAsync(string category, string message, LogL CorrelationId = Thread.CurrentThread.ManagedThreadId.ToString(), }; - this.logQueue.Enqueue(logEntry); + lock (this.logQueue) + { + if (this.disposed) + { + return; + } + + if (this.logQueue.Count == MaxQueuedEntries) + { + this.logQueue.Dequeue(); + this.droppedEntries++; + } + + this.logQueue.Enqueue(logEntry); + } // Force immediate flush for errors and critical events. if (level >= LogLevel.Error) { - this.flushTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); - Interlocked.Exchange(ref this.flushScheduled, 0); await this.FlushLogsAsync(); } - else if (Interlocked.Exchange(ref this.flushScheduled, 1) == 0) + else { - this.flushTimer.Change(TimeSpan.FromSeconds(5), Timeout.InfiniteTimeSpan); + this.ScheduleFlush(); + } + } + + private void ScheduleFlush() + { + lock (this.logQueue) + { + if (!this.disposed && Interlocked.Exchange(ref this.flushScheduled, 1) == 0) + { + this.flushTimer.Change(TimeSpan.FromSeconds(5), Timeout.InfiniteTimeSpan); + } } } @@ -261,34 +295,46 @@ private void FlushLogs(object? state) private async Task FlushLogsAsync() { - if (this.logQueue.IsEmpty) - { - return; - } - await this.fileLock.WaitAsync(); try { - // Check if we need to rotate the log file - await this.CheckLogRotationAsync(); + if (this.pendingBatch != null) + { + await this.WritePendingBatchAsync(); + } - var logEntries = new List(); - while (this.logQueue.TryDequeue(out var entry)) + lock (this.logQueue) { - logEntries.Add(entry); + if (this.logQueue.Count == 0) + { + return; + } } - if (logEntries.Count == 0) + await this.CheckLogRotationAsync(); + lock (this.logQueue) { - return; + this.pendingBatch = new List(this.logQueue); + this.logQueue.Clear(); } - // Write entries to file - await this.WriteLogEntriesToFileAsync(logEntries); + await this.WritePendingBatchAsync(); + var dropped = 0; + lock (this.logQueue) + { + dropped = this.droppedEntries; + this.droppedEntries = 0; + } + + if (dropped > 0) + { + this.logger.LogWarning("Dropped {Count} queued diagnostic events while logging was backed up", dropped); + } } catch (Exception ex) { this.logger.LogError(ex, "Failed to flush logs to file"); + this.ScheduleFlush(); } finally { @@ -296,10 +342,25 @@ private async Task FlushLogsAsync() } } - private async Task WriteLogEntriesToFileAsync(List entries) + private async Task WritePendingBatchAsync() { - var logLines = entries.Select(this.FormatLogEntry); - await File.AppendAllLinesAsync(this.currentLogFilePath, logLines); + var content = string.Join(Environment.NewLine, this.pendingBatch!.Select(this.FormatLogEntry)) + Environment.NewLine; + await using (var file = new FileStream(this.currentLogFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, 4096, useAsync: true)) + { + if (this.pendingWriteOffset is long offset && file.Length > offset) + { + // A failed append can leave part of this batch in the file. + file.SetLength(offset); + } + + file.Position = file.Length; + this.pendingWriteOffset = file.Position; + await file.WriteAsync(Encoding.UTF8.GetBytes(content)); + await file.FlushAsync(); + } + + this.pendingWriteOffset = null; + this.pendingBatch = null; } private string FormatLogEntry(LogEntry entry) @@ -510,27 +571,31 @@ public async Task ExportLogsAsync(DateTime fromDate, DateTime toDate, st public async Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileSizeMb, int retentionDays) { - var updatedSettings = this.settingsService.Settings; - updatedSettings.EnableDebugLogging = enableDebugLogging; - updatedSettings.MaxLogFileSizeMb = maxFileSizeMb; - updatedSettings.LogRetentionDays = retentionDays; - - await this.settingsService.UpdateSettingsAsync(updatedSettings); + await this.settingsService.EditSettingsAsync(draft => + { + draft.EnableDebugLogging = enableDebugLogging; + draft.MaxLogFileSizeMb = maxFileSizeMb; + draft.LogRetentionDays = retentionDays; + }); await this.LogSystemEventAsync("Configuration", $"Logging configuration updated: Debug={enableDebugLogging}, MaxSize={maxFileSizeMb}MB, Retention={retentionDays}days"); } public void Dispose() { - if (this.disposed) + lock (this.logQueue) { - return; + if (this.disposed) + { + return; + } + + this.disposed = true; + this.flushTimer.Dispose(); } this.settingsService.SettingsChanged -= this.OnSettingsChanged; - this.flushTimer?.Dispose(); - this.FlushLogsAsync().Wait(TimeSpan.FromSeconds(5)); - this.fileLock?.Dispose(); - this.disposed = true; + Task.Run(this.FlushLogsAsync).Wait(TimeSpan.FromSeconds(5)); + // Timer callbacks may already be waiting on the managed gate. } } diff --git a/Services/GameSessionService.cs b/Services/GameSessionService.cs index bde19406..731a8b6b 100644 --- a/Services/GameSessionService.cs +++ b/Services/GameSessionService.cs @@ -235,6 +235,7 @@ public sealed class GameSessionService : IGameSessionService private readonly object timerGate = new(); private List journal = new(); + private volatile JournalRecoveryState startupRecovery; private Timer? timer; private bool started; @@ -328,17 +329,13 @@ public async Task StartAsync() await this.stateLock.WaitAsync().ConfigureAwait(false); try { - this.journal = await this.LoadJournalAsync().ConfigureAwait(false); - if (this.journal.Count > 0) + if (this.started) { - this.logger.LogInformation("Game Boost: restoring {Count} change(s) left by a previous run", this.journal.Count); - var (restored, left, failed) = await this.RestoreAllAsync().ConfigureAwait(false); - await this.AuditAsync( - failed.Count > 0 ? ActivityAuditSeverity.Warning : ActivityAuditSeverity.Success, - $"Restored {restored} change(s) left by an unexpected close", - DescribeRestore(restored, left, failed)).ConfigureAwait(false); + return; } + this.startupRecovery = JournalRecoveryState.ReadPending; + await this.RecoverStartupJournalAsync(logReadFailure: true).ConfigureAwait(false); this.started = true; this.stopped = false; this.SyncTimer(); @@ -361,7 +358,14 @@ public async Task StopAsync() await this.stateLock.WaitAsync().ConfigureAwait(false); try { - await this.EndSessionAsync("ThreadPilot is closing").ConfigureAwait(false); + if (this.startupRecovery != JournalRecoveryState.Complete) + { + await this.RecoverStartupJournalAsync().ConfigureAwait(false); + } + else + { + await this.EndSessionAsync("ThreadPilot is closing").ConfigureAwait(false); + } } finally { @@ -382,12 +386,13 @@ public void Dispose() this.gameHandle?.Dispose(); } - // Ticks only while Game Boost is on (it is off by default); turning it off restores through ReapplyAsync. + // Startup recovery needs a timer even when Game Boost is disabled. private void SyncTimer() { lock (this.timerGate) { - if (this.started && !this.disposed && this.Settings.GameBoostEnabled) + if (this.started && !this.disposed + && (this.Settings.GameBoostEnabled || this.startupRecovery != JournalRecoveryState.Complete)) { this.timer ??= new Timer(_ => TaskSafety.FireAndForget(this.TickAsync(), ex => this.logger.LogWarning(ex, "Game Boost tick failed")), null, TickInterval, TickInterval); return; @@ -412,6 +417,16 @@ internal async Task TickAsync() return; } + if (this.startupRecovery != JournalRecoveryState.Complete) + { + await this.RecoverStartupJournalAsync().ConfigureAwait(false); + this.SyncTimer(); + if (this.startupRecovery != JournalRecoveryState.Complete) + { + return; + } + } + if (!this.Settings.GameBoostEnabled) { await this.EndSessionAsync("Game Boost turned off").ConfigureAwait(false); @@ -420,6 +435,12 @@ internal async Task TickAsync() if (this.session == null) { + if (this.journal.Count > 0 && (++this.tickCount % BackgroundRescanTicks != 0 || + (await this.RestoreAllAsync().ConfigureAwait(false)).Failed.Count > 0)) + { + return; + } + await this.TryBeginSessionAsync().ConfigureAwait(false); return; } @@ -809,7 +830,10 @@ private bool IsBackgroundCandidate(ProcessModel process, GameSession currentSess Setting = GameBoostSetting.CpuSets, AppliedCpuIndexes = selection.GlobalLogicalProcessorIndexes.ToList(), }; - await this.AddJournalEntryAsync(entry).ConfigureAwait(false); + if (!await this.TryAddJournalEntryAsync(entry).ConfigureAwait(false)) + { + return (ApplyOutcome.Failed, "could not save recovery data"); + } var result = await this.affinityApplyService.ApplyAsync(process, selection, CpuAssignmentMode.CpuSets).ConfigureAwait(false); if (result.Success) @@ -871,7 +895,10 @@ private bool IsBackgroundCandidate(ProcessModel process, GameSession currentSess Setting = GameBoostSetting.EfficiencyMode, AppliedEfficiencyMode = mode, }; - await this.AddJournalEntryAsync(entry).ConfigureAwait(false); + if (!await this.TryAddJournalEntryAsync(entry).ConfigureAwait(false)) + { + return (ApplyOutcome.Failed, "could not save recovery data"); + } var result = await this.efficiencyService.SetEfficiencyModeAsync(process, mode).ConfigureAwait(false); if (!result.Success) @@ -912,7 +939,11 @@ private async Task TryApplyAboveNormalAsync(ProcessModel game, long startTicks, OriginalPriority = ProcessPriorityClass.Normal, AppliedPriority = ProcessPriorityClass.AboveNormal, }; - await this.AddJournalEntryAsync(entry).ConfigureAwait(false); + if (!await this.TryAddJournalEntryAsync(entry).ConfigureAwait(false)) + { + await this.AuditAsync(ActivityAuditSeverity.Warning, $"{game.Name}: priority not changed", "Could not save recovery data").ConfigureAwait(false); + return; + } try { @@ -994,7 +1025,10 @@ await this.AuditAsync( break; } - this.journal.Remove(entry); + if (outcome != RestoreOutcome.Failed) + { + this.journal.Remove(entry); + } } await this.SaveJournalAsync().ConfigureAwait(false); @@ -1011,7 +1045,14 @@ private async Task RestoreAsync(GameBoostJournalEntry entry, IRe } var process = await this.processService.GetProcessByIdAsync(entry.ProcessId).ConfigureAwait(false); - if (process == null || this.HasUserRule(rules, process, entry.Setting)) + if (process == null) + { + return this.IsSameProcessAlive(entry.ProcessId, entry.StartTimeUtcTicks) + ? RestoreOutcome.Failed + : RestoreOutcome.LeftAlone; + } + + if (this.HasUserRule(rules, process, entry.Setting)) { return RestoreOutcome.LeftAlone; } @@ -1019,7 +1060,12 @@ private async Task RestoreAsync(GameBoostJournalEntry entry, IRe if (entry.Setting == GameBoostSetting.CpuSets) { var current = await this.processService.GetCpuAssignmentLogicalProcessorIndexesAsync(process, CpuAssignmentMode.CpuSets).ConfigureAwait(false); - if (current == null || !current.SequenceEqual(entry.AppliedCpuIndexes.OrderBy(index => index))) + if (current == null) + { + return RestoreOutcome.Failed; + } + + if (!current.SequenceEqual(entry.AppliedCpuIndexes.OrderBy(index => index))) { return RestoreOutcome.LeftAlone; } @@ -1035,8 +1081,13 @@ private async Task RestoreAsync(GameBoostJournalEntry entry, IRe if (entry.Setting == GameBoostSetting.EfficiencyMode) { - if (entry.AppliedEfficiencyMode == null - || await this.efficiencyService.GetEfficiencyModeAsync(process).ConfigureAwait(false) != entry.AppliedEfficiencyMode) + var current = await this.efficiencyService.GetEfficiencyModeAsync(process).ConfigureAwait(false); + if (current == null) + { + return RestoreOutcome.Failed; + } + + if (entry.AppliedEfficiencyMode == null || current != entry.AppliedEfficiencyMode) { return RestoreOutcome.LeftAlone; } @@ -1132,6 +1183,7 @@ internal async Task ReapplyAsync() var previous = this.session; await this.EndSessionAsync("Game Boost settings changed").ConfigureAwait(false); if (previous == null + || this.journal.Count > 0 || !this.Settings.GameBoostEnabled || !this.IsSameProcessAlive(previous.Game.ProcessId, previous.GameStartTimeUtcTicks) || !GameBoostProcessLists.IsGame(previous.Game.Name, previous.Game.ExecutablePath, this.Settings.GameBoostManualGames, this.Settings.GameBoostExcludedGames)) @@ -1152,10 +1204,16 @@ internal async Task ReapplyAsync() } } - private async Task AddJournalEntryAsync(GameBoostJournalEntry entry) + private async Task TryAddJournalEntryAsync(GameBoostJournalEntry entry) { this.journal.Add(entry); - await this.SaveJournalAsync().ConfigureAwait(false); + if (await this.SaveJournalAsync().ConfigureAwait(false)) + { + return true; + } + + this.journal.Remove(entry); + return false; } private async Task ConfirmJournalEntryAsync(GameBoostJournalEntry entry) @@ -1168,40 +1226,79 @@ private async Task ConfirmJournalEntryAsync(GameBoostJournalEntry entry) } } - private async Task> LoadJournalAsync() + private async Task RecoverStartupJournalAsync(bool logReadFailure = false) { - try + var firstRestoreAttempt = this.startupRecovery == JournalRecoveryState.ReadPending; + if (firstRestoreAttempt) { - if (!File.Exists(this.journalPath)) + var persisted = await this.LoadJournalAsync(logReadFailure).ConfigureAwait(false); + if (persisted == null) { - return new(); + return; } + this.journal = persisted; + this.startupRecovery = JournalRecoveryState.RestorePending; + } + + if (this.journal.Count > 0) + { + var (restored, left, failed) = await this.RestoreAllAsync().ConfigureAwait(false); + if (firstRestoreAttempt || restored > 0 || left > 0) + { + await this.AuditAsync( + failed.Count > 0 ? ActivityAuditSeverity.Warning : ActivityAuditSeverity.Success, + $"Restored {restored} change(s) left by an unexpected close", + DescribeRestore(restored, left, failed)).ConfigureAwait(false); + } + } + + if (this.journal.Count == 0) + { + this.startupRecovery = JournalRecoveryState.Complete; + } + } + + private async Task?> LoadJournalAsync(bool logReadFailure) + { + try + { var json = await File.ReadAllTextAsync(this.journalPath).ConfigureAwait(false); - return JsonSerializer.Deserialize>(json) ?? new(); + return JsonSerializer.Deserialize>(json) + ?? throw new JsonException("Expected a list of Game Boost recovery entries."); } - catch (Exception ex) + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) { - this.logger.LogWarning(ex, "Game Boost journal at {Path} is unreadable; nothing to restore", this.journalPath); return new(); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + if (logReadFailure) + { + this.logger.LogWarning(ex, "Game Boost recovery is pending because its journal at {Path} could not be read", this.journalPath); + } + + return null; + } } - private async Task SaveJournalAsync() + private async Task SaveJournalAsync() { try { if (this.journal.Count == 0) { File.Delete(this.journalPath); - return; + return true; } await AtomicFileWriter.WriteAllTextAsync(this.journalPath, JsonSerializer.Serialize(this.journal, JournalJsonOptions)).ConfigureAwait(false); + return true; } catch (Exception ex) { this.logger.LogWarning(ex, "Game Boost could not write its journal at {Path}", this.journalPath); + return false; } } @@ -1221,6 +1318,13 @@ private static void LogAmdVCacheDriver(ILogger logger) } } + private enum JournalRecoveryState + { + Complete, + ReadPending, + RestorePending, + } + private enum ApplyOutcome { AlreadyAttempted, diff --git a/Services/GitHubReleaseClient.cs b/Services/GitHubReleaseClient.cs index 370d1d28..f051b9bc 100644 --- a/Services/GitHubReleaseClient.cs +++ b/Services/GitHubReleaseClient.cs @@ -15,12 +15,6 @@ public GitHubReleaseClient(HttpClient httpClient) this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } - public Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) - { - var url = $"https://api.github.com/repos/{owner}/{repo}/releases/latest"; - return this.httpClient.GetStringAsync(url, cancellationToken); - } - public Task GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) { var url = $"https://api.github.com/repos/{owner}/{repo}/releases"; diff --git a/Services/GitHubUpdateChecker.cs b/Services/GitHubUpdateChecker.cs index 3a6d4b0b..77b235a6 100644 --- a/Services/GitHubUpdateChecker.cs +++ b/Services/GitHubUpdateChecker.cs @@ -26,45 +26,6 @@ public GitHubUpdateChecker(IGitHubReleaseClient gitHubReleaseClient) this.gitHubReleaseClient = gitHubReleaseClient ?? throw new ArgumentNullException(nameof(gitHubReleaseClient)); } - public async Task<(Version? latest, string? releaseUrl)> GetLatestVersionAsync( - string owner, - string repo, - CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(owner)) - { - throw new ArgumentException("Owner is required", nameof(owner)); - } - - if (string.IsNullOrWhiteSpace(repo)) - { - throw new ArgumentException("Repository is required", nameof(repo)); - } - - var json = await this.gitHubReleaseClient.GetLatestReleaseJsonAsync(owner, repo, cancellationToken); - var release = JsonSerializer.Deserialize(json, new JsonSerializerOptions - { - PropertyNameCaseInsensitive = true, - }); - - if (release is null || release.Draft || release.Prerelease || string.IsNullOrWhiteSpace(release.Tag_name)) - { - return (null, null); - } - - var tag = release.Tag_name.Trim(); - if (tag.StartsWith("v", StringComparison.OrdinalIgnoreCase)) - { - tag = tag[1..]; - } - - var sanitized = tag.Split('-', '+')[0]; - - return Version.TryParse(sanitized, out var version) - ? (version, release.Html_url) - : (null, release.Html_url); - } - public async Task GetLatestReleaseInfoAsync( string owner, string repo, diff --git a/Services/IApplicationSettingsService.cs b/Services/IApplicationSettingsService.cs index fb159daa..b4cb2205 100644 --- a/Services/IApplicationSettingsService.cs +++ b/Services/IApplicationSettingsService.cs @@ -14,14 +14,18 @@ public interface IApplicationSettingsService Task SaveSettingsAsync(); + // Replaces the full profile for import and backup restore. Task UpdateSettingsAsync(ApplicationSettingsModel newSettings); + /// Applies an edit to the latest committed profile and publishes it after persistence succeeds. + /// A synchronous edit that receives a detached draft. + /// A task that finishes when the edit has been persisted and published. + Task EditSettingsAsync(Action edit); + Task ResetToDefaultsAsync(); string GetSettingsFilePath(); - void ValidateAndFixSettings(); - Task ExportSettingsAsync(string filePath); Task ImportSettingsAsync(string filePath); diff --git a/Services/IConditionalProfileService.cs b/Services/IConditionalProfileService.cs deleted file mode 100644 index b7176cab..00000000 --- a/Services/IConditionalProfileService.cs +++ /dev/null @@ -1,77 +0,0 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using ThreadPilot.Models; - - public class ProfileApplicationEventArgs : EventArgs - { - public ConditionalProcessProfile Profile { get; set; } = new(); - - public ProcessModel Process { get; set; } = new(); - - public SystemState SystemState { get; set; } = new(); - - public bool WasApplied { get; set; } - - public string Reason { get; set; } = string.Empty; - - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - } - - public class ProfileConflictEventArgs : EventArgs - { - public List ConflictingProfiles { get; set; } = new(); - - public ProcessModel Process { get; set; } = new(); - - public ConditionalProcessProfile SelectedProfile { get; set; } = new(); - - public string Resolution { get; set; } = string.Empty; - } - - public interface IConditionalProfileService - { - Task InitializeAsync(); - - Task AddProfileAsync(ConditionalProcessProfile profile); - - Task RemoveProfileAsync(string profileId); - - Task UpdateProfileAsync(ConditionalProcessProfile profile); - - Task> GetAllProfilesAsync(); - - Task> GetProfilesForProcessAsync(string processName); - - Task> EvaluateProfilesAsync(ProcessModel process); - - Task ApplyBestProfileAsync(ProcessModel process); - - Task GetSystemStateAsync(); - - Task StartMonitoringAsync(); - - Task StopMonitoringAsync(); - - bool IsMonitoring { get; } - - ConditionalProcessProfile ResolveProfileConflict(List conflictingProfiles, ProcessModel process); - - ConditionalProcessProfile CreateDefaultProfile(string processName); - - Task<(bool IsValid, List Errors)> ValidateProfileAsync(ConditionalProcessProfile profile); - - Task ExportProfilesToJsonAsync(); - - Task ImportProfilesFromJsonAsync(string json); - - event EventHandler? ProfileApplied; - - event EventHandler? ProfileConflictResolved; - - event EventHandler? SystemStateChanged; - } -} - diff --git a/Services/IKeyboardShortcutService.cs b/Services/IKeyboardShortcutService.cs index fa1f151d..b0db4fb1 100644 --- a/Services/IKeyboardShortcutService.cs +++ b/Services/IKeyboardShortcutService.cs @@ -42,6 +42,8 @@ public class KeyboardShortcut public bool IsGlobal { get; set; } = true; + internal KeyboardShortcut Clone() => (KeyboardShortcut)this.MemberwiseClone(); + public override string ToString() { var parts = new List(); diff --git a/Services/IPersistentProcessRuleStore.cs b/Services/IPersistentProcessRuleStore.cs index 713b9c5d..4f56a17d 100644 --- a/Services/IPersistentProcessRuleStore.cs +++ b/Services/IPersistentProcessRuleStore.cs @@ -3,12 +3,84 @@ */ namespace ThreadPilot.Services { + using System.Runtime.CompilerServices; using ThreadPilot.Models; public interface IPersistentProcessRuleStore { + private static readonly ConditionalWeakTable EditLocks = new(); + Task> LoadAsync(); Task SaveAsync(IReadOnlyList rules); + + /// Edits the current rules atomically. An unavailable rule set aborts the edit. + Task EditAsync( + Func, Task> edit, + CancellationToken cancellationToken = default) => + this.RunTransactionAsync( + async () => + { + var previous = await this.LoadForEditAsync(); + var draft = previous.ToList(); + var result = await edit(draft); + cancellationToken.ThrowIfCancellationRequested(); + if (!previous.SequenceEqual(draft)) + { + await this.SaveAsync(draft); + } + + return result; + }, + cancellationToken); + + /// Replaces rules during an import and restores them if the remaining import fails. + Task ReplaceForImportAsync(IReadOnlyList? replacement, Func completeImport) => + this.RunTransactionAsync( + async () => + { + var previous = replacement == null ? null : await this.LoadForEditAsync(); + if (replacement != null) + { + await this.SaveAsync(replacement); + } + + try + { + await completeImport(); + } + catch (Exception importError) when (previous != null) + { + try + { + await this.SaveAsync(previous); + } + catch (Exception rollbackError) + { + throw new AggregateException("Import failed and the rule set could not be restored.", importError, rollbackError); + } + + throw; + } + + return true; + }, + CancellationToken.None); + + protected Task> LoadForEditAsync() => this.LoadAsync(); + + private async Task RunTransactionAsync(Func> operation, CancellationToken cancellationToken) + { + var gate = EditLocks.GetValue(this, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(cancellationToken); + try + { + return await operation(); + } + finally + { + gate.Release(); + } + } } } diff --git a/Services/IProcessPowerPlanAssociationService.cs b/Services/IProcessPowerPlanAssociationService.cs index 4e2ec65b..271d6216 100644 --- a/Services/IProcessPowerPlanAssociationService.cs +++ b/Services/IProcessPowerPlanAssociationService.cs @@ -13,7 +13,11 @@ public interface IProcessPowerPlanAssociationService Task LoadConfigurationAsync(); - Task SaveConfigurationAsync(); + /// Saves the power plan monitoring options. + /// Whether to suppress repeated power plan changes. + /// The delay before reevaluating the active power plan, in milliseconds. + /// Whether the options were saved. + Task SaveMonitoringSettingsAsync(bool preventDuplicateChanges, int delayMs); Task> GetAssociationsAsync(); @@ -35,7 +39,7 @@ public interface IProcessPowerPlanAssociationService Task> ValidateConfigurationAsync(); - Task ResetConfigurationAsync(); + Task ResetConfigurationAsync(); Task ExportConfigurationAsync(string filePath); diff --git a/Services/ISmartNotificationService.cs b/Services/ISmartNotificationService.cs deleted file mode 100644 index 656565ce..00000000 --- a/Services/ISmartNotificationService.cs +++ /dev/null @@ -1,137 +0,0 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using ThreadPilot.Models; - - public enum NotificationCategory - { - System, - Process, - Performance, - PowerPlan, - Error, - Warning, - Information, - UserAction, - } - - public class SmartNotification - { - public string Id { get; set; } = Guid.NewGuid().ToString(); - - public string Title { get; set; } = string.Empty; - - public string Message { get; set; } = string.Empty; - - public NotificationPriority Priority { get; set; } = NotificationPriority.Normal; - - public NotificationCategory Category { get; set; } = NotificationCategory.Information; - - public DateTime CreatedAt { get; set; } = DateTime.UtcNow; - - public DateTime? ScheduledFor { get; set; } - - public TimeSpan? ExpiresAfter { get; set; } - - public Dictionary Metadata { get; set; } = new(); - - public string DeduplicationKey { get; set; } = string.Empty; - - public bool IsPersistent { get; set; } = false; - - public int RetryCount { get; set; } = 0; - - public int MaxRetries { get; set; } = 3; - } - - public class NotificationThrottleConfig - { - public NotificationCategory Category { get; set; } - - public TimeSpan MinInterval { get; set; } = TimeSpan.FromSeconds(30); - - public int MaxPerHour { get; set; } = 10; - - public int MaxPerDay { get; set; } = 50; - - public bool EnableDeduplication { get; set; } = true; - - public TimeSpan DeduplicationWindow { get; set; } = TimeSpan.FromMinutes(5); - } - - public class NotificationPreferences - { - public bool IsEnabled { get; set; } = true; - - public bool DoNotDisturbMode { get; set; } = false; - - public TimeSpan DoNotDisturbStart { get; set; } = TimeSpan.FromHours(22); // 10 PM - - public TimeSpan DoNotDisturbEnd { get; set; } = TimeSpan.FromHours(8); // 8 AM - - public NotificationPriority MinimumPriority { get; set; } = NotificationPriority.Normal; - - public Dictionary CategoryEnabled { get; set; } = new(); - - public Dictionary ThrottleConfigs { get; set; } = new(); - - public bool ShowOnlyWhenMinimized { get; set; } = false; - - public bool PlaySounds { get; set; } = true; - - public int DefaultDisplayDuration { get; set; } = 5000; // milliseconds - } - - public class SmartNotificationEventArgs : EventArgs - { - public SmartNotification Notification { get; set; } = new(); - - public string Reason { get; set; } = string.Empty; - - public DateTime Timestamp { get; set; } = DateTime.UtcNow; - } - - public interface ISmartNotificationService - { - Task InitializeAsync(); - - Task SendNotificationAsync(SmartNotification notification); - - Task SendNotificationAsync(string title, string message, - NotificationPriority priority = NotificationPriority.Normal, - NotificationCategory category = NotificationCategory.Information); - - Task ScheduleNotificationAsync(SmartNotification notification, DateTime deliveryTime); - - Task CancelNotificationAsync(string notificationId); - - Task> GetPendingNotificationsAsync(); - - Task> GetNotificationHistoryAsync(TimeSpan? period = null); - - Task ClearHistoryAsync(); - - Task UpdatePreferencesAsync(NotificationPreferences preferences); - - Task GetPreferencesAsync(); - - Task SetDoNotDisturbAsync(bool enabled, TimeSpan? duration = null); - - bool IsDoNotDisturbActive(); - - Task> GetStatisticsAsync(); - - Task TestNotificationAsync(); - - event EventHandler? NotificationSent; - - event EventHandler? NotificationThrottled; - - event EventHandler? NotificationDeduplicated; - - event EventHandler? DoNotDisturbChanged; - } -} - diff --git a/Services/IVirtualizedProcessService.cs b/Services/IVirtualizedProcessService.cs index 583fc3af..f593340f 100644 --- a/Services/IVirtualizedProcessService.cs +++ b/Services/IVirtualizedProcessService.cs @@ -9,8 +9,6 @@ public class VirtualizedProcessConfig { public int BatchSize { get; set; } = 50; - public int PreloadBatches { get; set; } = 2; - public bool EnableBackgroundLoading { get; set; } = true; public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromSeconds(5); @@ -31,21 +29,6 @@ public class ProcessBatchResult public TimeSpan LoadTime { get; set; } } - public class BatchLoadProgressEventArgs : EventArgs - { - public int LoadedBatches { get; set; } - - public int TotalBatches { get; set; } - - public int LoadedProcesses { get; set; } - - public int TotalProcesses { get; set; } - - public double ProgressPercentage => this.TotalBatches > 0 ? (double)this.LoadedBatches / this.TotalBatches * 100 : 0; - - public string StatusMessage { get; set; } = string.Empty; - } - public interface IVirtualizedProcessService { VirtualizedProcessConfig Configuration { get; set; } @@ -56,18 +39,8 @@ public interface IVirtualizedProcessService Task LoadProcessBatchAsync(int batchIndex, bool activeApplicationsOnly = false); - Task> LoadProcessBatchesAsync(int startBatchIndex, int batchCount, bool activeApplicationsOnly = false); - Task PreloadNextBatchAsync(int currentBatchIndex, bool activeApplicationsOnly = false); - Task> SearchProcessesAsync(string searchTerm, bool activeApplicationsOnly = false); - - Task RefreshBatchAsync(int batchIndex, bool activeApplicationsOnly = false); - - void ClearCache(); - - event EventHandler? BatchLoadProgress; - event EventHandler? BackgroundBatchLoaded; } } diff --git a/Services/KeyboardShortcutService.cs b/Services/KeyboardShortcutService.cs index 711a62c9..b6872327 100644 --- a/Services/KeyboardShortcutService.cs +++ b/Services/KeyboardShortcutService.cs @@ -210,9 +210,8 @@ public async Task SaveShortcutsToSettingsAsync() { try { - var settings = this.settingsService.Settings; - settings.KeyboardShortcuts = this.registeredShortcuts.Values.ToList(); - await this.settingsService.UpdateSettingsAsync(settings); + var shortcuts = this.registeredShortcuts.Values.ToList(); + await this.settingsService.EditSettingsAsync(draft => draft.KeyboardShortcuts = shortcuts); this.logger.LogInformation("Saved {Count} keyboard shortcuts to settings", this.registeredShortcuts.Count); } diff --git a/Services/LogFileManager.cs b/Services/LogFileManager.cs deleted file mode 100644 index d6c7de4a..00000000 --- a/Services/LogFileManager.cs +++ /dev/null @@ -1,412 +0,0 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Extensions.Logging; - - public class LogFileManager : IDisposable - { - private readonly ILogger logger; - private readonly string logDirectory; - private readonly SemaphoreSlim fileLock = new(1, 1); - private readonly ReaderWriterLockSlim configLock = new(); - private bool disposed; - - // Configuration - private int maxFileSizeMb = 10; - private int retentionDays = 7; - private int maxLogFiles = 50; - - public string LogDirectory => this.logDirectory; - - public string CurrentLogFilePath { get; private set; } - - public LogFileManager(ILogger logger, string? logDirectory = null) - { - this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); - - this.logDirectory = logDirectory ?? Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - "ThreadPilot", - "Logs"); - - this.CurrentLogFilePath = Path.Combine(this.logDirectory, "ThreadPilot.log"); - } - - public async Task InitializeAsync() - { - await this.fileLock.WaitAsync(); - try - { - // Ensure log directory exists - Directory.CreateDirectory(this.logDirectory); - - // Create current log file if it doesn't exist - if (!File.Exists(this.CurrentLogFilePath)) - { - await this.CreateNewLogFileAsync(); - } - - this.logger.LogInformation("Log file manager initialized. Directory: {LogDirectory}", this.logDirectory); - } - finally - { - this.fileLock.Release(); - } - } - - public async Task WriteLogEntriesAsync(IEnumerable logLines) - { - await this.fileLock.WaitAsync(); - try - { - // Check if rotation is needed - await this.CheckAndRotateLogFileAsync(); - - // Write entries - await File.AppendAllLinesAsync(this.CurrentLogFilePath, logLines); - } - finally - { - this.fileLock.Release(); - } - } - - public async Task WriteLogEntryAsync(string logLine) - { - await this.WriteLogEntriesAsync(new[] { logLine }); - } - - public async Task> ReadLogEntriesAsync(DateTime fromDate, DateTime toDate, int maxEntries = 1000) - { - await this.fileLock.WaitAsync(); - try - { - var allEntries = new List<(DateTime timestamp, string line)>(); - var logFiles = this.GetLogFiles(); - - foreach (var logFile in logFiles) - { - var entries = await this.ReadLogEntriesFromFileAsync(logFile, fromDate, toDate); - allEntries.AddRange(entries); - } - - return allEntries - .OrderByDescending(e => e.timestamp) - .Take(maxEntries) - .Select(e => e.line) - .ToList(); - } - finally - { - this.fileLock.Release(); - } - } - - public async Task GetStatisticsAsync() - { - var stats = new LogFileStatistics(); - await this.fileLock.WaitAsync(); - try - { - var logFiles = this.GetLogFiles(); - stats.TotalLogFiles = logFiles.Count; - - foreach (var logFile in logFiles) - { - var fileInfo = new FileInfo(logFile); - stats.TotalLogSizeBytes += fileInfo.Length; - - if (Path.GetFileName(logFile) == "ThreadPilot.log") - { - stats.CurrentFileSizeBytes = fileInfo.Length; - } - - if (stats.OldestLogDate == default || fileInfo.CreationTime < stats.OldestLogDate) - { - stats.OldestLogDate = fileInfo.CreationTime; - } - - if (fileInfo.CreationTime > stats.NewestLogDate) - { - stats.NewestLogDate = fileInfo.CreationTime; - } - } - } - finally - { - this.fileLock.Release(); - } - - await this.CountLogLevelsAsync(stats); - return stats; - } - - public async Task CleanupOldLogsAsync() - { - await this.fileLock.WaitAsync(); - try - { - this.configLock.EnterReadLock(); - var retentionDate = DateTime.UtcNow.AddDays(-this.retentionDays); - var maxFiles = this.maxLogFiles; - this.configLock.ExitReadLock(); - - var logFiles = this.GetLogFiles() - .Where(f => Path.GetFileName(f) != "ThreadPilot.log") // Don't delete current log - .OrderBy(f => new FileInfo(f).CreationTime) - .ToList(); - - var deletedCount = 0; - - // Delete files older than retention period - foreach (var logFile in logFiles.ToList()) - { - var fileInfo = new FileInfo(logFile); - if (fileInfo.CreationTime < retentionDate) - { - try - { - File.Delete(logFile); - logFiles.Remove(logFile); - deletedCount++; - this.logger.LogDebug("Deleted old log file: {LogFile}", logFile); - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Failed to delete old log file: {LogFile}", logFile); - } - } - } - - // Delete excess files if we have too many - if (logFiles.Count > maxFiles) - { - var excessFiles = logFiles.Take(logFiles.Count - maxFiles); - foreach (var logFile in excessFiles) - { - try - { - File.Delete(logFile); - deletedCount++; - this.logger.LogDebug("Deleted excess log file: {LogFile}", logFile); - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Failed to delete excess log file: {LogFile}", logFile); - } - } - } - - if (deletedCount > 0) - { - this.logger.LogInformation("Cleaned up {DeletedCount} old log files", deletedCount); - } - } - finally - { - this.fileLock.Release(); - } - } - - public async Task ExportLogsAsync(DateTime fromDate, DateTime toDate, string? exportPath = null) - { - exportPath ??= Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.Desktop), - $"ThreadPilot_Logs_{DateTime.Now:yyyyMMdd_HHmmss}.txt"); - - var logEntries = await this.ReadLogEntriesAsync(fromDate, toDate, int.MaxValue); - - var exportContent = new List - { - $"# ThreadPilot Log Export", - $"# Export Date: {DateTime.Now:yyyy-MM-dd HH:mm:ss}", - $"# Date Range: {fromDate:yyyy-MM-dd} to {toDate:yyyy-MM-dd}", - $"# Total Entries: {logEntries.Count}", - string.Empty, - }; - - exportContent.AddRange(logEntries); - - await File.WriteAllLinesAsync(exportPath, exportContent); - return exportPath; - } - - public void UpdateConfiguration(int maxFileSizeMb, int retentionDays, int maxLogFiles = 50) - { - this.configLock.EnterWriteLock(); - try - { - this.maxFileSizeMb = maxFileSizeMb; - this.retentionDays = retentionDays; - this.maxLogFiles = maxLogFiles; - } - finally - { - this.configLock.ExitWriteLock(); - } - } - - private async Task CheckAndRotateLogFileAsync() - { - var fileInfo = new FileInfo(this.CurrentLogFilePath); - - this.configLock.EnterReadLock(); - var maxSizeBytes = this.maxFileSizeMb * 1024 * 1024; - this.configLock.ExitReadLock(); - - if (fileInfo.Exists && fileInfo.Length > maxSizeBytes) - { - await this.RotateLogFileAsync(); - } - } - - private async Task RotateLogFileAsync() - { - var timestamp = DateTime.UtcNow.ToString("yyyyMMdd_HHmmss"); - var rotatedPath = Path.Combine(this.logDirectory, $"ThreadPilot_{timestamp}.log"); - - try - { - // Move current log to rotated name - File.Move(this.CurrentLogFilePath, rotatedPath); - - // Create new current log file - await this.CreateNewLogFileAsync(); - - this.logger.LogInformation("Log file rotated: {RotatedPath}", rotatedPath); - } - catch (Exception ex) - { - this.logger.LogError(ex, "Failed to rotate log file"); - throw; - } - } - - private async Task CreateNewLogFileAsync() - { - var header = new[] - { - $"# ThreadPilot Log File", - $"# Created: {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC", - $"# Version: {System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}", - $"# Machine: {Environment.MachineName}", - string.Empty, - }; - - await File.WriteAllLinesAsync(this.CurrentLogFilePath, header); - } - - private List GetLogFiles() - { - return Directory.GetFiles(this.logDirectory, "*.log") - .OrderByDescending(f => new FileInfo(f).CreationTime) - .ToList(); - } - - private async Task> ReadLogEntriesFromFileAsync(string filePath, DateTime fromDate, DateTime toDate) - { - var entries = new List<(DateTime timestamp, string line)>(); - - try - { - var lines = await File.ReadAllLinesAsync(filePath); - foreach (var line in lines) - { - if (line.StartsWith("#") || string.IsNullOrWhiteSpace(line)) - { - continue; - } - - // Try to extract timestamp from JSON log entry - if (this.TryExtractTimestamp(line, out var timestamp)) - { - if (timestamp >= fromDate && timestamp <= toDate) - { - entries.Add((timestamp, line)); - } - } - } - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Failed to read log entries from file: {FilePath}", filePath); - } - - return entries; - } - - private bool TryExtractTimestamp(string logLine, out DateTime timestamp) - { - timestamp = default; - - try - { - // Look for timestamp in JSON format: "timestamp":"2024-01-01 12:00:00.000" - var timestampStart = logLine.IndexOf("\"timestamp\":\""); - if (timestampStart >= 0) - { - timestampStart += 13; // Length of "timestamp":"" - var timestampEnd = logLine.IndexOf("\"", timestampStart); - if (timestampEnd > timestampStart) - { - var timestampStr = logLine.Substring(timestampStart, timestampEnd - timestampStart); - return DateTime.TryParse(timestampStr, out timestamp); - } - } - } - catch - { - // Ignore parsing errors - } - - return false; - } - - private async Task CountLogLevelsAsync(LogFileStatistics stats) - { - try - { - // Read recent entries to count log levels - var recentEntries = await this.ReadLogEntriesAsync(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, 1000); - - foreach (var entry in recentEntries) - { - if (entry.Contains("\"level\":\"Error\"")) - { - stats.ErrorCount++; - } - else if (entry.Contains("\"level\":\"Warning\"")) - { - stats.WarningCount++; - } - else if (entry.Contains("\"level\":\"Information\"")) - { - stats.InfoCount++; - } - } - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Failed to count log levels"); - } - } - - public void Dispose() - { - if (this.disposed) - { - return; - } - - this.fileLock?.Dispose(); - this.configLock?.Dispose(); - this.disposed = true; - } - } -} - diff --git a/Services/PersistentProcessRuleJsonStore.cs b/Services/PersistentProcessRuleJsonStore.cs index 6cc51a21..e5537b0a 100644 --- a/Services/PersistentProcessRuleJsonStore.cs +++ b/Services/PersistentProcessRuleJsonStore.cs @@ -38,7 +38,12 @@ internal PersistentProcessRuleJsonStore( this.copyFile = copyFile ?? ((source, destination) => File.Copy(source, destination, overwrite: false)); } - public async Task> LoadAsync() + public Task> LoadAsync() => this.LoadAsync(failOnUnreadable: false); + + Task> IPersistentProcessRuleStore.LoadForEditAsync() => + this.LoadAsync(failOnUnreadable: true); + + private async Task> LoadAsync(bool failOnUnreadable) { if (this.cachedRules != null) { @@ -55,14 +60,6 @@ public async Task> LoadAsync() var filePath = this.filePathProvider(); this.logger?.LogDebug("Loading persistent process rules from {FilePath}", filePath); - if (!File.Exists(filePath)) - { - this.logger?.LogDebug("Persistent process rules file does not exist at {FilePath}", filePath); - this.loadFailed = false; - this.preservationRequired = false; - return this.cachedRules = []; - } - try { var json = await File.ReadAllTextAsync(filePath).ConfigureAwait(false); @@ -72,11 +69,23 @@ public async Task> LoadAsync() this.preservationRequired = false; return this.cachedRules = rules.ToArray(); } + catch (Exception ex) when (ex is FileNotFoundException or DirectoryNotFoundException) + { + this.logger?.LogDebug("Persistent process rules file does not exist at {FilePath}", filePath); + this.loadFailed = false; + this.preservationRequired = false; + return this.cachedRules = []; + } catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) { this.loadFailed = true; this.preservationRequired = !this.TryPreserveUnreadableFile(filePath, ex); this.logger?.LogWarning(ex, "Could not load persistent process rules from {FilePath}. The rule set will be re-read on the next access.", filePath); + if (failOnUnreadable) + { + throw new IOException("The saved process rules could not be read. Retry after the file becomes available.", ex); + } + return []; } } diff --git a/Services/PersistentRuleAutoApplyService.cs b/Services/PersistentRuleAutoApplyService.cs index b2239990..9392d805 100644 --- a/Services/PersistentRuleAutoApplyService.cs +++ b/Services/PersistentRuleAutoApplyService.cs @@ -13,10 +13,12 @@ public interface IPersistentRuleAutoApplyService { Task> ApplyForDiscoveredProcessesAsync( IEnumerable processes, + Func? getOptions = null, CancellationToken cancellationToken = default); Task> ApplyForProcessStartAsync( ProcessModel process, + Func? getOptions = null, CancellationToken cancellationToken = default); void MarkProcessExited(int processId); @@ -138,6 +140,7 @@ public PersistentRuleAutoApplyService( public async Task> ApplyForDiscoveredProcessesAsync( IEnumerable processes, + Func? getOptions = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(processes); @@ -164,7 +167,7 @@ public async Task> ApplyForDiscover foreach (var process in snapshot) { cancellationToken.ThrowIfCancellationRequested(); - results.AddRange(await this.ApplyForProcessAsync(process, rules, "DiscoveredSnapshot", cancellationToken).ConfigureAwait(false)); + results.AddRange(await this.ApplyForProcessAsync(process, rules, "DiscoveredSnapshot", getOptions, cancellationToken).ConfigureAwait(false)); } return results; @@ -172,6 +175,7 @@ public async Task> ApplyForDiscover public async Task> ApplyForProcessStartAsync( ProcessModel process, + Func? getOptions = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(process); @@ -182,7 +186,7 @@ public async Task> ApplyForProcessS } var rules = await this.ruleStore.LoadAsync().ConfigureAwait(false); - return await this.ApplyForProcessAsync(process, rules, "ProcessStarted", cancellationToken).ConfigureAwait(false); + return await this.ApplyForProcessAsync(process, rules, "ProcessStarted", getOptions, cancellationToken).ConfigureAwait(false); } public void MarkProcessExited(int processId) @@ -207,6 +211,7 @@ private async Task> ApplyForProcess ProcessModel process, IReadOnlyList rules, string source, + Func? getOptions, CancellationToken cancellationToken) { using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); @@ -220,7 +225,7 @@ private async Task> ApplyForProcess try { - return await this.ApplyForProcessCoreAsync(process, rules, source, lifetime.Token).ConfigureAwait(false); + return await this.ApplyForProcessCoreAsync(process, rules, source, getOptions, lifetime.Token).ConfigureAwait(false); } finally { @@ -238,6 +243,7 @@ private async Task> ApplyForProcess ProcessModel process, IReadOnlyList rules, string source, + Func? getOptions, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); @@ -353,18 +359,21 @@ await this.LogPathRetryAsync(process, string.IsNullOrWhiteSpace(process.Executab { // Runtime auto-apply only runs while ThreadPilot is open; it does not use registry, // IFEO, services, or protected-process bypass techniques. - var applyResults = await this.rulesEngine - .ApplyMatchingRulesAsync( - process, - rule => selectedSignatures.Contains(PersistentRuleRuntimeKeys.GetRuleSignature(rule)), - cancellationToken) - .ConfigureAwait(false); + var options = getOptions?.Invoke(process) ?? PersistentRuleApplyOptions.None; + var preserved = options & (PersistentRuleApplyOptions.PreserveAffinity | PersistentRuleApplyOptions.PreservePriority); + bool Filter(PersistentProcessRule rule) => selectedSignatures.Contains(PersistentRuleRuntimeKeys.GetRuleSignature(rule)); + var applyResults = preserved == PersistentRuleApplyOptions.None + ? await this.rulesEngine.ApplyMatchingRulesAsync(process, Filter, cancellationToken).ConfigureAwait(false) + : await this.rulesEngine.ApplyMatchingRulesAsync(process, Filter, preserved, cancellationToken).ConfigureAwait(false); var results = applyResults.Select(PersistentRuleAutoApplyResult.FromApplyResult).ToList(); foreach (var result in results) { await this.LogResultAsync(result, process, source).ConfigureAwait(false); - this.priorityVerificationService?.ScheduleDelayedVerification(result, process, source); + if (!options.HasFlag(PersistentRuleApplyOptions.SkipDelayedPriorityVerification)) + { + this.priorityVerificationService?.ScheduleDelayedVerification(result, process, source); + } } if (source.EndsWith("/PathRetry", StringComparison.Ordinal)) diff --git a/Services/PersistentRulesEngine.cs b/Services/PersistentRulesEngine.cs index 228936ea..6fb16672 100644 --- a/Services/PersistentRulesEngine.cs +++ b/Services/PersistentRulesEngine.cs @@ -7,12 +7,28 @@ namespace ThreadPilot.Services using Microsoft.Extensions.Logging; using ThreadPilot.Models; + [Flags] + public enum PersistentRuleApplyOptions + { + None = 0, + PreserveAffinity = 1, + PreservePriority = 2, + SkipDelayedPriorityVerification = 4, + } + public interface IPersistentRulesEngine { Task> ApplyMatchingRulesAsync( ProcessModel process, Predicate? ruleFilter = null, CancellationToken cancellationToken = default); + + /// Applies matching rules while preserving the process settings owned by another policy. + Task> ApplyMatchingRulesAsync( + ProcessModel process, + Predicate? ruleFilter, + PersistentRuleApplyOptions options, + CancellationToken cancellationToken); } public sealed class PersistentRulesEngine : IPersistentRulesEngine @@ -60,10 +76,17 @@ public PersistentRulesEngine( this.securityService = securityService; } - public async Task> ApplyMatchingRulesAsync( + public Task> ApplyMatchingRulesAsync( ProcessModel process, Predicate? ruleFilter = null, - CancellationToken cancellationToken = default) + CancellationToken cancellationToken = default) => + this.ApplyMatchingRulesAsync(process, ruleFilter, PersistentRuleApplyOptions.None, cancellationToken); + + public async Task> ApplyMatchingRulesAsync( + ProcessModel process, + Predicate? ruleFilter, + PersistentRuleApplyOptions options, + CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(process); @@ -75,12 +98,32 @@ public async Task> ApplyMatchingRulesAs .Where(rule => ruleFilter == null || ruleFilter(rule))) { cancellationToken.ThrowIfCancellationRequested(); - results.Add(await this.ApplyRuleAsync(rule, process, cancellationToken).ConfigureAwait(false)); + var preserveAffinity = options.HasFlag(PersistentRuleApplyOptions.PreserveAffinity) && rule.ApplyAffinityOnStart; + var preservePriority = options.HasFlag(PersistentRuleApplyOptions.PreservePriority) && rule.ApplyPriorityOnStart; + var remaining = rule; + if (preserveAffinity || preservePriority) + { + remaining = rule with + { + ApplyAffinityOnStart = rule.ApplyAffinityOnStart && !preserveAffinity, + ApplyPriorityOnStart = rule.ApplyPriorityOnStart && !preservePriority, + }; + if (!HasActions(remaining)) + { + continue; + } + } + + results.Add(await this.ApplyRuleAsync(remaining, process, cancellationToken).ConfigureAwait(false)); } return results; } + private static bool HasActions(PersistentProcessRule rule) => + rule.ApplyAffinityOnStart || rule.ApplyPriorityOnStart || rule.ApplyMemoryPriorityOnStart + || rule.ApplyIoPriorityOnStart || rule.ApplyEfficiencyModeOnStart || rule.PreventSystemSleepWhileRunning; + private async Task ApplyRuleAsync( PersistentProcessRule rule, ProcessModel process, @@ -89,12 +132,7 @@ private async Task ApplyRuleAsync( var result = CreateSuccessResult(rule, process); var success = true; - if (!rule.ApplyAffinityOnStart && - !rule.ApplyPriorityOnStart && - !rule.ApplyMemoryPriorityOnStart && - !rule.ApplyIoPriorityOnStart && - !rule.ApplyEfficiencyModeOnStart && - !rule.PreventSystemSleepWhileRunning) + if (!HasActions(rule)) { return MarkRuleConfigurationFailure( result, diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs index 96df0216..29b4f594 100644 --- a/Services/ProcessMonitorManagerService.cs +++ b/Services/ProcessMonitorManagerService.cs @@ -26,13 +26,13 @@ public class ProcessMonitorManagerService : IProcessMonitorManagerService private readonly IEnhancedLoggingService enhancedLogger; private readonly object lockObject = new(); - private readonly ConcurrentDictionary runningAssociatedProcesses = new(); + private readonly ConcurrentDictionary runningAssociatedProcesses = new(); private readonly System.Threading.Timer delayTimer; private readonly SemaphoreSlim powerPlanChangeSemaphore = new(1, 1); private readonly SemaphoreSlim stateMutationSemaphore = new(1, 1); private CancellationTokenSource automationLifetime = new(); - private bool isRunning; + private volatile bool isRunning; private string status = "Stopped"; private bool disposed; private ProcessMonitorConfiguration? configuration; @@ -46,7 +46,7 @@ public class ProcessMonitorManagerService : IProcessMonitorManagerService public string Status => this.status; - public IEnumerable RunningAssociatedProcesses => this.runningAssociatedProcesses.Values.ToList(); + public IEnumerable RunningAssociatedProcesses => this.runningAssociatedProcesses.Values.Select(tracked => tracked.Process); public ProcessMonitorManagerService( IProcessMonitorService processMonitorService, @@ -187,13 +187,15 @@ public async Task StopAsync() await this.processMonitorService.StopMonitoringAsync(); // Clear running processes - foreach (var processId in this.runningAssociatedProcesses.Keys) + lock (this.lockObject) { - this.coreMaskService.UnregisterMaskApplication(processId); - this.processService.UntrackProcess(processId); - this.persistentRuleAutoApplyService.MarkProcessExited(processId); + foreach (var processId in this.runningAssociatedProcesses.Keys) + { + this.ClearProcessTracking(processId); + } + + this.runningAssociatedProcesses.Clear(); } - this.runningAssociatedProcesses.Clear(); // Restore default power plan if configured if (this.configuration?.DefaultPowerPlanGuid != null) @@ -225,9 +227,18 @@ public async Task SetAutomationMonitoringEnabledAsync(bool enabled) await this.StopAsync(); } - var settings = this.settingsService.Settings; - settings.EnableAutomationMonitoring = enabled; - await this.settingsService.UpdateSettingsAsync(settings); + if (enabled != this.isRunning) + { + return; + } + + await this.settingsService.EditSettingsAsync(draft => + { + if (enabled == this.isRunning) + { + draft.EnableAutomationMonitoring = enabled; + } + }); } public Task EvaluateCurrentProcessesAsync() => this.EvaluateCurrentProcessesAsync(resetRuleAttempts: false); @@ -241,114 +252,64 @@ private async Task EvaluateCurrentProcessesAsync(bool resetRuleAttempts) try { + var lifetime = this.automationLifetime.Token; + var trackedBeforeScan = this.runningAssociatedProcesses.ToDictionary(); var currentProcesses = (await this.processMonitorService.GetRunningProcessesAsync()).ToList(); - if (resetRuleAttempts) + if (lifetime.IsCancellationRequested) { - // A fresh monitoring lifetime or resume must also reapply rules after a short sleep, - // even if the last application is still inside the normal duplicate-event cooldown. - foreach (var process in currentProcesses) - { - this.persistentRuleAutoApplyService.MarkProcessExited(process.ProcessId); - } + return; } - await this.ApplyPersistentRulesForDiscoveredProcessesAsync(currentProcesses); - var associatedProcesses = new List(); - var currentProcessIds = new HashSet(currentProcesses.Select(p => p.ProcessId)); - - // Remove stale tracked processes that are no longer running - foreach (var trackedPid in this.runningAssociatedProcesses.Keys) + var currentById = currentProcesses.DistinctBy(process => process.ProcessId) + .ToDictionary(process => process.ProcessId); + lock (this.lockObject) { - if (!currentProcessIds.Contains(trackedPid) && this.runningAssociatedProcesses.TryRemove(trackedPid, out _)) + // Keep processes reported by events while the snapshot was being read. + foreach (var tracked in trackedBeforeScan) { - this.coreMaskService.UnregisterMaskApplication(trackedPid); - this.processService.UntrackProcess(trackedPid); - this.persistentRuleAutoApplyService.MarkProcessExited(trackedPid); + if ((!currentById.TryGetValue(tracked.Key, out var current) || !tracked.Value.Process.IsSameInstance(current)) + && this.runningAssociatedProcesses.TryRemove(tracked)) + { + this.ClearProcessTracking(tracked.Key); + if (current != null) + { + trackedBeforeScan.Remove(tracked.Key); + } + } } } - // Find all currently running processes that have associations - foreach (var process in currentProcesses) + if (resetRuleAttempts) { - var association = this.configuration.FindMatchingAssociation(process); - if (association != null) + // A fresh monitoring lifetime or resume must also reapply rules after a short sleep, + // even if the last application is still inside the normal duplicate-event cooldown. + foreach (var process in currentProcesses) { - associatedProcesses.Add(process); - this.runningAssociatedProcesses[process.ProcessId] = process; + this.persistentRuleAutoApplyService.MarkProcessExited(process.ProcessId); } } - // Determine which power plan should be active - await this.DeterminePowerPlanAsync(associatedProcesses); - } - catch (Exception ex) - { - this.SetStatus(this.isRunning, "Error evaluating processes", $"Error: {ex.Message}", ex); - } - } - - public async Task ForceDefaultPowerPlanAsync() - { - if (this.configuration?.DefaultPowerPlanGuid == null) - { - return; - } - - try - { - await this.powerPlanChangeSemaphore.WaitAsync(); - - var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); - var decision = this.powerPlanTransitionGate.ShouldApply( - this.configuration.DefaultPowerPlanGuid, - currentPowerPlan?.Guid); - if (!decision.ShouldApply) + await this.ApplyPersistentRulesForDiscoveredProcessesAsync(currentById.Values, resetRuleAttempts, lifetime); + if (lifetime.IsCancellationRequested) { - this.logger.LogDebug( - "Default power plan restore suppressed for {PowerPlanGuid}: {Reason}", - this.configuration.DefaultPowerPlanGuid, - decision.SuppressionReason); return; } - this.powerPlanTransitionGate.RecordAttempt(this.configuration.DefaultPowerPlanGuid); - var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync( - this.configuration.DefaultPowerPlanGuid, - this.configuration.PreventDuplicatePowerPlanChanges); - - if (success) + foreach (var process in currentById.Values) { - var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(this.configuration.DefaultPowerPlanGuid); - // Note: We don't have a specific process for this event, so we'll use a dummy one - var dummyProcess = new ProcessModel { Name = "System", ProcessId = -1 }; - var dummyAssociation = new ProcessPowerPlanAssociation("System", this.configuration.DefaultPowerPlanGuid, this.configuration.DefaultPowerPlanName); - - this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( - dummyProcess, dummyAssociation, currentPowerPlan, newPowerPlan, "DefaultRestored")); - - // Show notification for default power plan restoration - await this.notificationService.ShowPowerPlanChangeNotificationAsync( - currentPowerPlan?.Name ?? "Unknown", - newPowerPlan?.Name ?? this.configuration.DefaultPowerPlanName, - string.Empty); - } - else - { - this.logger.LogWarning( - "Failed to restore default power plan {PowerPlanGuid}", - this.configuration.DefaultPowerPlanGuid); + await this.ReconcileAssociationAsync(process, applyProcessSettings: resetRuleAttempts, lifetime, trackedBeforeScan); } + + await this.ReevaluatePowerPlanAsync(lifetime); } catch (Exception ex) { - this.SetStatus(this.isRunning, "Error setting default power plan", $"Error: {ex.Message}", ex); - } - finally - { - this.powerPlanChangeSemaphore.Release(); + this.SetStatus(this.isRunning, "Error evaluating processes", $"Error: {ex.Message}", ex); } } + public Task ForceDefaultPowerPlanAsync() => this.ReevaluatePowerPlanAsync(CancellationToken.None, forceDefault: true); + public async Task GetCurrentActivePowerPlanAsync() { return await this.powerPlanService.GetActivePowerPlan(); @@ -393,41 +354,22 @@ private async Task OnProcessStartedAsync(ProcessEventArgs e) e.Process.Name, e.Process.ProcessId); - await this.ApplyPersistentRulesForProcessStartAsync(e.Process); - - var associationCandidates = this.configuration - .GetEnabledAssociations() - .Where(association => association.MatchesExecutable(e.Process.Name)) - .ToList(); - if (associationCandidates.Count > 0) + var lifetime = this.automationLifetime.Token; + lock (this.lockObject) { - try - { - await this.processService.RefreshProcessInfo(e.Process); - } - catch (Exception ex) + if (this.runningAssociatedProcesses.TryGetValue(e.Process.ProcessId, out var previous) + && !previous.Process.IsSameInstance(e.Process)) { - this.logger.LogDebug( - ex, - "Could not enrich process {ProcessName} (PID: {ProcessId}) for association matching", - e.Process.Name, - e.Process.ProcessId); + this.runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _); + this.ClearProcessTracking(e.Process.ProcessId); } } - var association = associationCandidates.FirstOrDefault(candidate => candidate.MatchesProcess(e.Process)); - if (association != null) - { - this.runningAssociatedProcesses[e.Process.ProcessId] = e.Process; - - await this.enhancedLogger.LogProcessMonitoringEventAsync( - LogEventTypes.ProcessMonitoring.AssociationTriggered, - e.Process.Name, e.Process.ProcessId, - $"Process matched association for power plan: {association.PowerPlanName}"); - - // Apply CPU affinity mask if configured - await this.ApplyCoreMaskAndPriorityAsync(e.Process, association); + await this.ApplyPersistentRulesForProcessStartAsync(e.Process, lifetime); + var association = await this.ReconcileAssociationAsync(e.Process, applyProcessSettings: true, lifetime); + if (association != null && !lifetime.IsCancellationRequested) + { // Schedule power plan change with delay if configured if (this.configuration.PowerPlanChangeDelayMs > 0) { @@ -440,7 +382,7 @@ await this.enhancedLogger.LogSystemEventAsync( } else { - await this.ChangePowerPlanForProcess(e.Process, association, "ProcessStarted"); + await this.ReevaluatePowerPlanAsync(lifetime); } } } @@ -456,6 +398,97 @@ await this.enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.OnProc } } + private async Task ReconcileAssociationAsync( + ProcessModel process, + bool applyProcessSettings, + CancellationToken lifetime, + IReadOnlyDictionary? trackedBeforeScan = null) + { + if (this.configuration == null || lifetime.IsCancellationRequested) + { + return null; + } + + var candidates = this.configuration.GetEnabledAssociations() + .Where(association => association.MatchesExecutable(process.Name)) + .ToList(); + if (candidates.Count == 0) + { + return null; + } + + var needsPath = string.IsNullOrWhiteSpace(process.ExecutablePath) && candidates.Any(candidate => candidate.MatchByPath); + var needsPriority = applyProcessSettings && candidates.Any(candidate => !string.IsNullOrEmpty(candidate.ProcessPriority)); + if (needsPath || needsPriority) + { + try + { + await this.processService.RefreshProcessInfo(process); + } + catch (Exception ex) + { + this.logger.LogDebug(ex, "Could not enrich process {ProcessName} (PID: {ProcessId}) for association matching", process.Name, process.ProcessId); + } + } + + var association = candidates.FirstOrDefault(candidate => candidate.MatchesProcess(process)); + if (association == null || lifetime.IsCancellationRequested) + { + return null; + } + + AssociatedProcess tracked; + bool applyEffects; + lock (this.lockObject) + { + this.runningAssociatedProcesses.TryGetValue(process.ProcessId, out var current); + if (lifetime.IsCancellationRequested) + { + return null; + } + + if (trackedBeforeScan != null) + { + trackedBeforeScan.TryGetValue(process.ProcessId, out var previous); + if (!ReferenceEquals(previous, current) && (current == null || !current.Process.IsSameInstance(process))) + { + // A later event stopped or replaced this process while we were scanning. + return null; + } + } + + tracked = current ?? new AssociatedProcess(process); + if (current == null) + { + this.runningAssociatedProcesses[process.ProcessId] = tracked; + } + else + { + process.StartTimeUtc ??= tracked.Process.StartTimeUtc; + tracked.Process = process; + } + + applyEffects = applyProcessSettings && !tracked.EffectsAttempted; + tracked.EffectsAttempted |= applyEffects; + } + + if (applyEffects) + { + var effects = await this.ApplyCoreMaskAndPriorityAsync(process, association); + lock (this.lockObject) + { + tracked.PreservedSettings = effects; + } + + await this.enhancedLogger.LogProcessMonitoringEventAsync( + LogEventTypes.ProcessMonitoring.AssociationTriggered, + process.Name, process.ProcessId, + $"Process matched association for power plan: {association.PowerPlanName}"); + } + + return association; + } + private void OnProcessStopped(object? sender, ProcessEventArgs e) { TaskSafety.FireAndForget(this.OnProcessStoppedAsync(e), ex => @@ -473,15 +506,23 @@ private async Task OnProcessStoppedAsync(ProcessEventArgs e) try { - this.persistentRuleAutoApplyService.MarkProcessExited(e.Process.ProcessId); - this.coreMaskService.UnregisterMaskApplication(e.Process.ProcessId); - this.processService.UntrackProcess(e.Process.ProcessId); + bool associated; + lock (this.lockObject) + { + var pid = e.Process.ProcessId; + associated = this.runningAssociatedProcesses.TryGetValue(pid, out var tracked); + if (tracked != null && !tracked.Process.IsSameInstance(e.Process)) + { + return; + } - if (this.runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _)) + this.runningAssociatedProcesses.TryRemove(pid, out _); + this.ClearProcessTracking(pid); + } + + if (associated) { - // Check if there are any other associated processes still running - var remainingProcesses = this.runningAssociatedProcesses.Values.ToList(); - await this.DeterminePowerPlanAsync(remainingProcesses); + await this.ReevaluatePowerPlanAsync(this.automationLifetime.Token); } } catch (Exception ex) @@ -490,6 +531,13 @@ private async Task OnProcessStoppedAsync(ProcessEventArgs e) } } + private void ClearProcessTracking(int processId) + { + this.persistentRuleAutoApplyService.MarkProcessExited(processId); + this.coreMaskService.UnregisterMaskApplication(processId); + this.processService.UntrackProcess(processId); + } + private void OnMonitoringStatusChanged(object? sender, MonitoringStatusEventArgs e) { if (e.StatusMessage != null) @@ -546,94 +594,66 @@ private async Task DelayedPowerPlanChangeCallbackAsync() return; } - var runningProcesses = this.runningAssociatedProcesses.Values.ToList(); - await this.DeterminePowerPlanAsync(runningProcesses); + await this.ReevaluatePowerPlanAsync(this.automationLifetime.Token); } - private async Task DeterminePowerPlanAsync(IList associatedProcesses) + private async Task ReevaluatePowerPlanAsync(CancellationToken lifetime, bool forceDefault = false) { - if (this.configuration == null) - { - return; - } - + await this.powerPlanChangeSemaphore.WaitAsync(); try { - if (associatedProcesses.Any()) + var configuration = this.configuration; + if (lifetime.IsCancellationRequested || configuration == null) { - // Find the highest priority association among running processes - var associations = associatedProcesses - .Select(p => this.configuration.FindMatchingAssociation(p)) - .Where(a => a != null) - .OrderByDescending(a => a!.Priority) - .ToList(); - - if (associations.Any()) - { - var topAssociation = associations.First()!; - var matchingProcess = associatedProcesses.First(p => topAssociation.MatchesProcess(p)); - await this.ChangePowerPlanForProcess(matchingProcess, topAssociation, "ProcessStarted"); - } + return; } - else + + (ProcessModel? Process, ProcessPowerPlanAssociation? Association) selected = default; + if (!forceDefault) { - // No associated processes running, revert to default - if (!string.IsNullOrEmpty(this.configuration.DefaultPowerPlanGuid)) - { - await this.ForceDefaultPowerPlanAsync(); - } + selected = this.RunningAssociatedProcesses + .Select(process => (Process: process, Association: configuration.FindMatchingAssociation(process))) + .Where(match => match.Association != null) + .OrderByDescending(match => match.Association!.Priority) + .FirstOrDefault(); } - } - catch (Exception ex) - { - this.SetStatus(this.isRunning, "Error determining power plan", $"Error: {ex.Message}", ex); - } - } - private async Task ChangePowerPlanForProcess(ProcessModel process, ProcessPowerPlanAssociation association, string action) - { - try - { - await this.powerPlanChangeSemaphore.WaitAsync(); + var process = selected.Process; + var association = selected.Association; + var planGuid = association?.PowerPlanGuid ?? configuration.DefaultPowerPlanGuid; + if (string.IsNullOrEmpty(planGuid)) + { + return; + } var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); - var decision = this.powerPlanTransitionGate.ShouldApply( - association.PowerPlanGuid, - currentPowerPlan?.Guid); - if (!decision.ShouldApply) + var decision = this.powerPlanTransitionGate.ShouldApply(planGuid, currentPowerPlan?.Guid); + if (!decision.ShouldApply || lifetime.IsCancellationRequested) { this.logger.LogDebug( - "Power plan change suppressed for {PowerPlanGuid}: {Reason}", - association.PowerPlanGuid, - decision.SuppressionReason); + "Power plan change suppressed for {PowerPlanGuid}: {Reason}", planGuid, decision.SuppressionReason); return; } - this.powerPlanTransitionGate.RecordAttempt(association.PowerPlanGuid); - var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync( - association.PowerPlanGuid, - this.configuration?.PreventDuplicatePowerPlanChanges ?? true); - - if (success) - { - var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(association.PowerPlanGuid); - this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( - process, association, currentPowerPlan, newPowerPlan, action)); - - // Show notification for power plan change - await this.notificationService.ShowPowerPlanChangeNotificationAsync( - currentPowerPlan?.Name ?? "Unknown", - newPowerPlan?.Name ?? association.PowerPlanName, - process.Name); - } - else + this.powerPlanTransitionGate.RecordAttempt(planGuid); + if (!await this.powerPlanService.SetActivePowerPlanByGuidAsync(planGuid, configuration.PreventDuplicatePowerPlanChanges)) { - this.logger.LogWarning( - "Failed to change power plan to {PowerPlanGuid} for process {ProcessName} (PID: {ProcessId})", - association.PowerPlanGuid, - process.Name, - process.ProcessId); + this.logger.LogWarning("Failed to change power plan to {PowerPlanGuid}", planGuid); + return; } + + var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(planGuid); + this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( + process ?? new ProcessModel { Name = "System", ProcessId = -1 }, + association ?? new ProcessPowerPlanAssociation("System", planGuid, configuration.DefaultPowerPlanName), + currentPowerPlan, + newPowerPlan, + association == null ? "DefaultRestored" : "ProcessStarted")); + + await this.notificationService.ShowPowerPlanChangeNotificationAsync( + currentPowerPlan?.Name ?? "Unknown", + newPowerPlan?.Name ?? association?.PowerPlanName ?? configuration.DefaultPowerPlanName, + process?.Name ?? string.Empty); } catch (Exception ex) { @@ -669,11 +689,13 @@ private void SetStatus(bool isRunning, string status, string? details = null, Ex } } - private async Task ApplyPersistentRulesForDiscoveredProcessesAsync(IEnumerable processes) + private async Task ApplyPersistentRulesForDiscoveredProcessesAsync( + IEnumerable processes, bool applyAssociationSettings, CancellationToken lifetime) { try { - var results = await this.persistentRuleAutoApplyService.ApplyForDiscoveredProcessesAsync(processes, this.automationLifetime.Token); + var results = await this.persistentRuleAutoApplyService.ApplyForDiscoveredProcessesAsync( + processes, process => this.GetPersistentRuleOptions(process, applyAssociationSettings), lifetime); await this.LogPersistentRuleResultsAsync(results); } catch (OperationCanceledException) @@ -685,11 +707,12 @@ private async Task ApplyPersistentRulesForDiscoveredProcessesAsync(IEnumerable

this.GetPersistentRuleOptions(target, applyAssociationSettings: true), lifetime); await this.LogPersistentRuleResultsAsync(results); } catch (OperationCanceledException) @@ -705,6 +728,33 @@ private async Task ApplyPersistentRulesForProcessStartAsync(ProcessModel process } } + private PersistentRuleApplyOptions GetPersistentRuleOptions(ProcessModel process, bool applyAssociationSettings) + { + var options = PersistentRuleApplyOptions.None; + lock (this.lockObject) + { + if (this.runningAssociatedProcesses.TryGetValue(process.ProcessId, out var tracked) + && tracked.Process.IsSameInstance(process)) + { + options = tracked.PreservedSettings; + } + } + + if (applyAssociationSettings + && this.configuration?.GetEnabledAssociations().Any(association => + Enum.TryParse(association.ProcessPriority, out var priority) + && Enum.IsDefined(priority) && !ProcessPriorityGuardrails.IsBlocked(priority) + && (association.MatchesProcess(process) + || (association.MatchByPath && string.IsNullOrWhiteSpace(process.ExecutablePath) + && association.MatchesExecutable(process.Name)))) == true) + { + // A delayed retry from the saved rule would undo the association's priority. + options |= PersistentRuleApplyOptions.SkipDelayedPriorityVerification; + } + + return options; + } + private async Task LogPersistentRuleResultsAsync(IReadOnlyList results) { foreach (var result in results) @@ -737,8 +787,10 @@ public void UpdateSettings() this.logger.LogDebug("ProcessMonitorManagerService settings updated"); } - private async Task ApplyCoreMaskAndPriorityAsync(ProcessModel process, ProcessPowerPlanAssociation association) + private async Task ApplyCoreMaskAndPriorityAsync( + ProcessModel process, ProcessPowerPlanAssociation association) { + var applied = PersistentRuleApplyOptions.None; try { // Apply CPU affinity mask if configured @@ -764,6 +816,7 @@ private async Task ApplyCoreMaskAndPriorityAsync(ProcessModel process, ProcessPo } else { + applied |= PersistentRuleApplyOptions.PreserveAffinity; this.processService.TrackAppliedMask(process.ProcessId, coreMask.Id); this.coreMaskService.RegisterMaskApplication(process.ProcessId, coreMask.Id); @@ -842,6 +895,7 @@ await this.enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyC } await this.processService.SetProcessPriority(process, priority, ProcessPriorityWriteSource.PowerPlanAssociation); + applied |= PersistentRuleApplyOptions.PreservePriority; this.logger.LogInformation( "Applied priority '{Priority}' to process {ProcessName} (PID: {ProcessId})", @@ -900,6 +954,15 @@ await this.enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.ApplyC ["AssociationId"] = association.Id, }); } + + return applied; + } + + private sealed class AssociatedProcess(ProcessModel process) + { + public ProcessModel Process { get; set; } = process; + public bool EffectsAttempted { get; set; } + public PersistentRuleApplyOptions PreservedSettings { get; set; } } private static string BuildAffinityOrPriorityBlockedMessage(Exception ex, string processName, string operation) diff --git a/Services/ProcessMonitorService.cs b/Services/ProcessMonitorService.cs index 38f03aae..87588f56 100644 --- a/Services/ProcessMonitorService.cs +++ b/Services/ProcessMonitorService.cs @@ -431,13 +431,14 @@ private void HandleProcessStarted(int processId, string processName) { ProcessId = processId, Name = NormalizeProcessName(processName), + StartTimeUtc = ProcessService.TryGetProcessStartTimeUtc(processId), Classification = ProcessClassification.Unknown, } : null; if (process != null) { - this.runningProcesses.TryAdd(processId, process); + this.UpdateRunningProcess(process); this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); } } @@ -520,9 +521,8 @@ private async Task RunFallbackPollingAsync(CancellationToken cancellationToken) return; } - if (!this.runningProcesses.ContainsKey(process.ProcessId)) + if (this.UpdateRunningProcess(process)) { - this.runningProcesses.TryAdd(process.ProcessId, process); this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); detectedChanges++; } @@ -560,6 +560,17 @@ private async Task RunFallbackPollingAsync(CancellationToken cancellationToken) } } + private bool UpdateRunningProcess(ProcessModel process) + { + var pid = process.ProcessId; + if (this.runningProcesses.TryGetValue(pid, out var existing) && !existing.IsSameInstance(process)) + { + return this.runningProcesses.TryUpdate(pid, process, existing); + } + + return this.runningProcesses.TryAdd(pid, process); + } + private void UpdateAdaptivePollingInterval(int detectedChanges) { if (!this.isFallbackPollingActive || this.fallbackTimer == null) diff --git a/Services/ProcessPowerPlanAssociationService.cs b/Services/ProcessPowerPlanAssociationService.cs index c827309f..d5571789 100644 --- a/Services/ProcessPowerPlanAssociationService.cs +++ b/Services/ProcessPowerPlanAssociationService.cs @@ -6,6 +6,7 @@ namespace ThreadPilot.Services using System.Linq; using System.Text; using System.Text.Json; + using System.Threading; using System.Threading.Tasks; using ThreadPilot.Models; @@ -26,271 +27,145 @@ public class ProcessPowerPlanAssociationService : IProcessPowerPlanAssociationSe private readonly string configurationDirectory; private readonly string configurationFilePath; - private readonly object lockObject = new(); + private readonly SemaphoreSlim mutationGate = new(1, 1); - private ProcessMonitorConfiguration configuration; + private volatile ProcessMonitorConfiguration configuration = new(); public event EventHandler? ConfigurationChanged; public ProcessMonitorConfiguration Configuration => this.configuration; public ProcessPowerPlanAssociationService() + : this(StoragePaths.ConfigurationDirectory) { StoragePaths.EnsureAppDataDirectories(); - - this.configurationDirectory = StoragePaths.ConfigurationDirectory; - this.configurationFilePath = Path.Combine(this.configurationDirectory, "ProcessPowerPlanAssociations.json"); - this.configuration = new ProcessMonitorConfiguration(); - - this.EnsureConfigurationDirectoryExists(); this.MigrateLegacyConfigurationIfNeeded(); } + internal ProcessPowerPlanAssociationService(string configurationDirectory) + { + this.configurationDirectory = configurationDirectory; + this.configurationFilePath = Path.Combine(configurationDirectory, "ProcessPowerPlanAssociations.json"); + } + public async Task LoadConfigurationAsync() { + await this.mutationGate.WaitAsync().ConfigureAwait(false); try { - if (!File.Exists(this.configurationFilePath)) - { - // Create default configuration - this.configuration = new ProcessMonitorConfiguration(); - await this.SaveConfigurationAsync().ConfigureAwait(false); - return true; - } - - var json = await File.ReadAllTextAsync(this.configurationFilePath).ConfigureAwait(false); - var loadedConfig = JsonSerializer.Deserialize(json, JsonOptions); - - if (loadedConfig != null) + if (File.Exists(this.configurationFilePath)) { - lock (this.lockObject) + var json = await File.ReadAllTextAsync(this.configurationFilePath).ConfigureAwait(false); + var loaded = JsonSerializer.Deserialize(json, JsonOptions); + if (loaded == null) { - loadedConfig.Associations ??= new List(); - this.configuration = loadedConfig; + return false; } - this.OnConfigurationChanged("Loaded", null, "Configuration loaded from file"); - return true; + loaded.Associations ??= new List(); + this.configuration = loaded; } - - return false; - } - catch (Exception ex) - { - this.OnConfigurationChanged("LoadError", null, $"Failed to load configuration: {ex.Message}"); - return false; - } - } - - public async Task SaveConfigurationAsync() - { - try - { - ProcessMonitorConfiguration configToSave; - lock (this.lockObject) + else { - configToSave = this.configuration; - configToSave.LastSavedDate = DateTime.Now; + await this.PersistAsync(new ProcessMonitorConfiguration()).ConfigureAwait(false); } - - var json = JsonSerializer.Serialize(configToSave, JsonOptions); - await AtomicFileWriter.WriteAllTextAsync(this.configurationFilePath, json, Encoding.UTF8).ConfigureAwait(false); - - this.OnConfigurationChanged("Saved", null, "Configuration saved to file"); - return true; } catch (Exception ex) { - this.OnConfigurationChanged("SaveError", null, $"Failed to save configuration: {ex.Message}"); + this.OnConfigurationChanged("LoadError", null, $"Failed to load configuration: {ex.Message}"); return false; } - } - - public async Task> GetAssociationsAsync() - { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) + finally { - return this.configuration.Associations.ToList(); + this.mutationGate.Release(); } - } - public async Task> GetEnabledAssociationsAsync() - { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) - { - return this.configuration.GetEnabledAssociations().ToList(); - } + this.OnConfigurationChanged("Loaded", null, "Configuration loaded"); + return true; } - public async Task AddAssociationAsync(ProcessPowerPlanAssociation association) - { - try - { - if (association == null) + public Task SaveMonitoringSettingsAsync(bool preventDuplicateChanges, int delayMs) => + this.CommitAsync( + config => { - return false; - } + config.PreventDuplicatePowerPlanChanges = preventDuplicateChanges; + config.PowerPlanChangeDelayMs = delayMs; + return config; + }, + "Saved"); - lock (this.lockObject) - { - // Check for duplicates - var existing = this.configuration.Associations - .FirstOrDefault(a => AreAssociationsConflicting(a, association)); + public Task> GetAssociationsAsync() => + Task.FromResult>(this.configuration.Associations.Select(association => association.CreateSnapshot()).ToList()); - if (existing != null) - { - return false; // Duplicate found - } + public Task> GetEnabledAssociationsAsync() => + Task.FromResult>(this.configuration.GetEnabledAssociations().Select(association => association.CreateSnapshot()).ToList()); - this.configuration.AddOrUpdateAssociation(association); - } - - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("Added", association, $"Association added for {association.ExecutableName}"); - return true; - } - catch (Exception ex) - { - this.OnConfigurationChanged("AddError", association, $"Failed to add association: {ex.Message}"); - return false; - } - } - - public async Task UpdateAssociationAsync(ProcessPowerPlanAssociation association) - { - try - { - if (association == null) - { - return false; - } - - lock (this.lockObject) + public Task AddAssociationAsync(ProcessPowerPlanAssociation association) => + this.CommitAsync( + config => { - this.configuration.AddOrUpdateAssociation(association); - } - - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("Updated", association, $"Association updated for {association.ExecutableName}"); - return true; - } - catch (Exception ex) - { - this.OnConfigurationChanged("UpdateError", association, $"Failed to update association: {ex.Message}"); - return false; - } - } + if (association == null || config.Associations.Any(existing => AreAssociationsConflicting(existing, association))) + { + return null; + } - public async Task RemoveAssociationAsync(string associationId) - { - try - { - ProcessPowerPlanAssociation? removedAssociation = null; - bool removed; + config.AddOrUpdateAssociation(association.CreateSnapshot()); + return config; + }, + "Added", + association); - lock (this.lockObject) + public Task UpdateAssociationAsync(ProcessPowerPlanAssociation association) => + this.CommitAsync( + config => { - removedAssociation = this.configuration.Associations.FirstOrDefault(a => a.Id == associationId); - removed = this.configuration.RemoveAssociation(associationId); - } + if (association == null) + { + return null; + } - if (removed) - { - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("Removed", removedAssociation, - $"Association removed for {removedAssociation?.ExecutableName}"); - } + config.AddOrUpdateAssociation(association.CreateSnapshot()); + return config; + }, + "Updated", + association); - return removed; - } - catch (Exception ex) - { - this.OnConfigurationChanged("RemoveError", null, $"Failed to remove association: {ex.Message}"); - return false; - } - } + public Task RemoveAssociationAsync(string associationId) => + this.CommitAsync(config => config.RemoveAssociation(associationId) ? config : null, "Removed"); - public async Task FindMatchingAssociationAsync(ProcessModel process) - { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) - { - return this.configuration.FindMatchingAssociation(process); - } - } + public Task FindMatchingAssociationAsync(ProcessModel process) => + Task.FromResult(this.configuration.FindMatchingAssociation(process)?.CreateSnapshot()); - public async Task FindAssociationByExecutableAsync(string executableName) - { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) - { - return this.configuration.FindAssociationByExecutable(executableName); - } - } + public Task FindAssociationByExecutableAsync(string executableName) => + Task.FromResult(this.configuration.FindAssociationByExecutable(executableName)?.CreateSnapshot()); - public async Task SetDefaultPowerPlanAsync(string powerPlanGuid, string powerPlanName) - { - try - { - lock (this.lockObject) + public Task SetDefaultPowerPlanAsync(string powerPlanGuid, string powerPlanName) => + this.CommitAsync( + config => { - this.configuration.DefaultPowerPlanGuid = powerPlanGuid; - this.configuration.DefaultPowerPlanName = powerPlanName; - } - - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("DefaultPowerPlanChanged", null, $"Default power plan set to {powerPlanName}"); - return true; - } - catch (Exception ex) - { - this.OnConfigurationChanged("DefaultPowerPlanError", null, $"Failed to set default power plan: {ex.Message}"); - return false; - } - } + config.DefaultPowerPlanGuid = powerPlanGuid; + config.DefaultPowerPlanName = powerPlanName; + return config; + }, + "DefaultPowerPlanChanged"); - public async Task<(string Guid, string Name)> GetDefaultPowerPlanAsync() + public Task<(string Guid, string Name)> GetDefaultPowerPlanAsync() { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) - { - return (this.configuration.DefaultPowerPlanGuid, this.configuration.DefaultPowerPlanName); - } + var config = this.configuration; + return Task.FromResult((config.DefaultPowerPlanGuid, config.DefaultPowerPlanName)); } - public async Task> ValidateConfigurationAsync() - { - await Task.CompletedTask.ConfigureAwait(false); - lock (this.lockObject) - { - return this.configuration.Validate(); - } - } - - public async Task ResetConfigurationAsync() - { - lock (this.lockObject) - { - this.configuration = new ProcessMonitorConfiguration(); - } + public Task> ValidateConfigurationAsync() => + Task.FromResult>(this.configuration.Validate()); - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("Reset", null, "Configuration reset to defaults"); - } + public Task ResetConfigurationAsync() => + this.CommitAsync(_ => new ProcessMonitorConfiguration(), "Reset"); public async Task ExportConfigurationAsync(string filePath) { try { - ProcessMonitorConfiguration configToExport; - lock (this.lockObject) - { - configToExport = this.configuration; - } - - var json = JsonSerializer.Serialize(configToExport, JsonOptions); + var json = JsonSerializer.Serialize(this.configuration, JsonOptions); await AtomicFileWriter.WriteAllTextAsync(filePath, json, Encoding.UTF8).ConfigureAwait(false); this.OnConfigurationChanged("Exported", null, $"Configuration exported to {filePath}"); @@ -335,39 +210,45 @@ public async Task ImportConfigurationAsync(string filePath) } } - public async Task ReplaceConfigurationAsync(ProcessMonitorConfiguration configuration) - { - if (configuration == null) - { - return false; - } + public Task ReplaceConfigurationAsync(ProcessMonitorConfiguration configuration) => + this.CommitAsync(_ => configuration == null ? null : CloneConfiguration(configuration), "Replaced"); + private async Task CommitAsync( + Func change, + string changeType, + ProcessPowerPlanAssociation? association = null) + { + await this.mutationGate.WaitAsync().ConfigureAwait(false); try { - var cloned = CloneConfiguration(configuration); - - lock (this.lockObject) + var proposed = change(CloneConfiguration(this.configuration)); + if (proposed == null) { - this.configuration = cloned; + return false; } - await this.SaveConfigurationAsync().ConfigureAwait(false); - this.OnConfigurationChanged("Replaced", null, "Configuration replaced from imported bundle"); - return true; + await this.PersistAsync(proposed).ConfigureAwait(false); } catch (Exception ex) { - this.OnConfigurationChanged("ReplaceError", null, $"Failed to replace configuration: {ex.Message}"); + this.OnConfigurationChanged("SaveError", association, $"Failed to save configuration: {ex.Message}"); return false; } + finally + { + this.mutationGate.Release(); + } + + this.OnConfigurationChanged(changeType, association); + return true; } - private void EnsureConfigurationDirectoryExists() + private async Task PersistAsync(ProcessMonitorConfiguration configuration) { - if (!Directory.Exists(this.configurationDirectory)) - { - Directory.CreateDirectory(this.configurationDirectory); - } + configuration.LastSavedDate = DateTime.Now; + var json = JsonSerializer.Serialize(configuration, JsonOptions); + await AtomicFileWriter.WriteAllTextAsync(this.configurationFilePath, json, Encoding.UTF8).ConfigureAwait(false); + this.configuration = configuration; } private void MigrateLegacyConfigurationIfNeeded() diff --git a/Services/ProcessRuleCreationService.cs b/Services/ProcessRuleCreationService.cs index ed8c070c..3e6d8171 100644 --- a/Services/ProcessRuleCreationService.cs +++ b/Services/ProcessRuleCreationService.cs @@ -179,14 +179,8 @@ public async Task DeleteRuleAsync( { ArgumentNullException.ThrowIfNull(process); - var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); - var existingIndex = FindExistingRuleIndex(rules, process); - if (existingIndex < 0) - { - return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage); - } - - return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false); + return await this.DeleteMatchingRuleAsync(rules => FindExistingRuleIndex(rules, process), cancellationToken) + .ConfigureAwait(false); } // The saved-rules list in the Rules tab holds rules, not processes: it can address a rule @@ -200,14 +194,9 @@ public async Task DeleteRuleByIdAsync( return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage); } - var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); - var existingIndex = rules.FindIndex(rule => string.Equals(rule.Id, ruleId, StringComparison.Ordinal)); - if (existingIndex < 0) - { - return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage); - } - - return await this.RemoveAtAsync(rules, existingIndex, cancellationToken).ConfigureAwait(false); + return await this.DeleteMatchingRuleAsync( + rules => rules.FindIndex(rule => string.Equals(rule.Id, ruleId, StringComparison.Ordinal)), + cancellationToken).ConfigureAwait(false); } // Editing a rule in place, from the saved-rules list. The affinity payload is not editable @@ -232,68 +221,78 @@ public async Task UpdateRuleWithCoreSelectionAsync( ProcessOperationUserMessages.RealtimePriorityBlocked); } - var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); - var existingIndex = rules.FindIndex(candidate => string.Equals(candidate.Id, rule.Id, StringComparison.Ordinal)); - if (existingIndex < 0) - { - return ProcessRuleCreationResult.Failed("NoSavedRuleToUpdate", NoSavedRuleMessage); - } - - var existing = rules[existingIndex]; - var updated = existing with - { - IsEnabled = rule.IsEnabled, - Priority = rule.Priority, - MemoryPriority = rule.MemoryPriority, - IoPriority = rule.IoPriority, - EfficiencyMode = rule.EfficiencyMode, - CpuAssignmentMode = rule.CpuAssignmentMode, - PreventSystemSleepWhileRunning = rule.PreventSystemSleepWhileRunning, - ApplyPriorityOnStart = rule.Priority.HasValue, - ApplyMemoryPriorityOnStart = rule.MemoryPriority.HasValue, - ApplyIoPriorityOnStart = rule.IoPriority.HasValue, - ApplyEfficiencyModeOnStart = rule.EfficiencyMode.HasValue, - UpdatedAt = DateTime.UtcNow, - }; - - if (coreSelection != null) - { - var affinity = await this.BuildAffinityPayloadFromCoreSelectionAsync(coreSelection, "Saved rule editor", cancellationToken).ConfigureAwait(false); - if (!affinity.Success) - { - return affinity; - } - - if (affinity.Payload == null) + var result = await this.ruleStore.EditAsync( + async rules => { - return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage); - } + var existingIndex = rules.FindIndex(candidate => string.Equals(candidate.Id, rule.Id, StringComparison.Ordinal)); + if (existingIndex < 0) + { + return ProcessRuleCreationResult.Failed("NoSavedRuleToUpdate", NoSavedRuleMessage); + } - updated = updated with - { - CpuSelection = affinity.Payload.CpuSelection, - LegacyAffinityMask = HasSelectionPayload(affinity.Payload.CpuSelection) ? null : affinity.Payload.LegacyAffinityMask, - ApplyAffinityOnStart = true, - }; - } + var existing = rules[existingIndex]; + var updated = existing with + { + IsEnabled = rule.IsEnabled, + Priority = rule.Priority, + MemoryPriority = rule.MemoryPriority, + IoPriority = rule.IoPriority, + EfficiencyMode = rule.EfficiencyMode, + CpuAssignmentMode = rule.CpuAssignmentMode, + PreventSystemSleepWhileRunning = rule.PreventSystemSleepWhileRunning, + ApplyPriorityOnStart = rule.Priority.HasValue, + ApplyMemoryPriorityOnStart = rule.MemoryPriority.HasValue, + ApplyIoPriorityOnStart = rule.IoPriority.HasValue, + ApplyEfficiencyModeOnStart = rule.EfficiencyMode.HasValue, + UpdatedAt = DateTime.UtcNow, + }; + + if (coreSelection != null) + { + var affinity = await this.BuildAffinityPayloadFromCoreSelectionAsync(coreSelection, "Saved rule editor", cancellationToken).ConfigureAwait(false); + if (!affinity.Success) + { + return affinity; + } + + if (affinity.Payload == null) + { + return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage); + } + + updated = updated with + { + CpuSelection = affinity.Payload.CpuSelection, + LegacyAffinityMask = HasSelectionPayload(affinity.Payload.CpuSelection) ? null : affinity.Payload.LegacyAffinityMask, + ApplyAffinityOnStart = true, + }; + } - rules[existingIndex] = updated; + rules[existingIndex] = updated; - cancellationToken.ThrowIfCancellationRequested(); - await this.ruleStore.SaveAsync(rules).ConfigureAwait(false); + var processName = string.IsNullOrWhiteSpace(updated.ProcessName) + ? "process" + : updated.ProcessName.Trim(); - var processName = string.IsNullOrWhiteSpace(updated.ProcessName) - ? "process" - : updated.ProcessName.Trim(); - this.logger.LogInformation("Updated saved rule {RuleId} for process {ProcessName}", updated.Id, processName); + return new ProcessRuleCreationResult + { + Success = true, + Updated = true, + Rule = updated, + UserMessage = $"Updated saved rule for {processName}.", + }; + }, + cancellationToken).ConfigureAwait(false); - return new ProcessRuleCreationResult + if (result.Rule is { } updated) { - Success = true, - Updated = true, - Rule = updated, - UserMessage = $"Updated saved rule for {processName}.", - }; + this.logger.LogInformation( + "Updated saved rule {RuleId} for process {ProcessName}", + updated.Id, + string.IsNullOrWhiteSpace(updated.ProcessName) ? "process" : updated.ProcessName.Trim()); + } + + return result; } // Nothing checked saved rules against the machine they are running on. A rule that pins @@ -339,25 +338,32 @@ public async Task> GetRulesNeedingTopologyReviewAsync( .ToList(); } - private async Task RemoveAtAsync( - List rules, - int index, + private async Task DeleteMatchingRuleAsync( + Func, int> findRule, CancellationToken cancellationToken) { - var removed = rules[index]; - rules.RemoveAt(index); + var removed = await this.ruleStore.EditAsync( + rules => + { + var index = findRule(rules); + if (index < 0) + { + return Task.FromResult(null); + } - cancellationToken.ThrowIfCancellationRequested(); - await this.ruleStore.SaveAsync(rules).ConfigureAwait(false); + var rule = rules[index]; + rules.RemoveAt(index); + return Task.FromResult(rule); + }, + cancellationToken).ConfigureAwait(false); - var processName = string.IsNullOrWhiteSpace(removed.ProcessName) - ? "process" - : removed.ProcessName.Trim(); - this.logger.LogInformation( - "Deleted saved rule {RuleId} for process {ProcessName}", - removed.Id, - processName); + if (removed == null) + { + return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage); + } + var processName = string.IsNullOrWhiteSpace(removed.ProcessName) ? "process" : removed.ProcessName.Trim(); + this.logger.LogInformation("Deleted saved rule {RuleId} for process {ProcessName}", removed.Id, processName); return new ProcessRuleCreationResult { Success = true, @@ -386,83 +392,84 @@ public async Task SaveRuleAsync( return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage); } - var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); - var existingIndex = FindExistingRuleIndex(rules, process); - var created = existingIndex < 0; - var now = DateTime.UtcNow; - var processName = string.IsNullOrWhiteSpace(process.Name) - ? "process" - : process.Name.Trim(); - var executablePath = string.IsNullOrWhiteSpace(process.ExecutablePath) - ? null - : process.ExecutablePath.Trim(); - var existing = created ? null : rules[existingIndex]; - - // Saving is a merge, not a replacement. A caller that does not carry a field - or a - // field that could not be read from the process this time - must not silently erase - // what the rule already had: that turned "Apply CPU assignment and save as rule" into - // a quiet way to lose the memory and I/O priority saved a moment earlier. Removing a - // field is done by deleting the rule, which is an explicit action. - var hasAffinityPayload = HasSelectionPayload(payload.CpuSelection) || payload.LegacyAffinityMask.HasValue; - var cpuSelection = hasAffinityPayload ? payload.CpuSelection : existing?.CpuSelection; - var legacyAffinityMask = hasAffinityPayload - ? (HasSelectionPayload(payload.CpuSelection) ? null : payload.LegacyAffinityMask) - : existing?.LegacyAffinityMask; - var cpuAssignmentMode = hasAffinityPayload - ? payload.CpuAssignmentMode - : existing?.CpuAssignmentMode ?? payload.CpuAssignmentMode; - var priority = payload.Priority ?? existing?.Priority; - var memoryPriority = payload.MemoryPriority ?? existing?.MemoryPriority; - var ioPriority = payload.IoPriority ?? existing?.IoPriority; - var efficiencyMode = payload.EfficiencyMode ?? existing?.EfficiencyMode; - - var rule = new PersistentProcessRule - { - Id = existing?.Id ?? Guid.NewGuid().ToString("N"), - Name = $"{processName} rule", - IsEnabled = true, - ProcessName = processName, - ExecutablePath = executablePath, - CpuSelection = cpuSelection, - LegacyAffinityMask = HasSelectionPayload(cpuSelection) ? null : legacyAffinityMask, - CpuAssignmentMode = cpuAssignmentMode, - Priority = priority, - MemoryPriority = memoryPriority, - IoPriority = ioPriority, - EfficiencyMode = efficiencyMode, - ApplyAffinityOnStart = HasSelectionPayload(cpuSelection) || legacyAffinityMask.HasValue, - ApplyPriorityOnStart = priority.HasValue, - ApplyMemoryPriorityOnStart = memoryPriority.HasValue, - ApplyIoPriorityOnStart = ioPriority.HasValue, - ApplyEfficiencyModeOnStart = efficiencyMode.HasValue, - PreventSystemSleepWhileRunning = payload.PreventSystemSleepWhileRunning, - CreatedAt = existing?.CreatedAt ?? now, - UpdatedAt = now, - Description = RuleDescription, - }; - - if (created) - { - rules.Add(rule); - } - else - { - rules[existingIndex] = rule; - } - - cancellationToken.ThrowIfCancellationRequested(); - await this.ruleStore.SaveAsync(rules).ConfigureAwait(false); + return await this.ruleStore.EditAsync( + rules => + { + var existingIndex = FindExistingRuleIndex(rules, process); + var created = existingIndex < 0; + var now = DateTime.UtcNow; + var processName = string.IsNullOrWhiteSpace(process.Name) + ? "process" + : process.Name.Trim(); + var executablePath = string.IsNullOrWhiteSpace(process.ExecutablePath) + ? null + : process.ExecutablePath.Trim(); + var existing = created ? null : rules[existingIndex]; + + // Saving is a merge, not a replacement. A caller that does not carry a field - or a + // field that could not be read from the process this time - must not silently erase + // what the rule already had: that turned "Apply CPU assignment and save as rule" into + // a quiet way to lose the memory and I/O priority saved a moment earlier. Removing a + // field is done by deleting the rule, which is an explicit action. + var hasAffinityPayload = HasSelectionPayload(payload.CpuSelection) || payload.LegacyAffinityMask.HasValue; + var cpuSelection = hasAffinityPayload ? payload.CpuSelection : existing?.CpuSelection; + var legacyAffinityMask = hasAffinityPayload + ? (HasSelectionPayload(payload.CpuSelection) ? null : payload.LegacyAffinityMask) + : existing?.LegacyAffinityMask; + var cpuAssignmentMode = hasAffinityPayload + ? payload.CpuAssignmentMode + : existing?.CpuAssignmentMode ?? payload.CpuAssignmentMode; + var priority = payload.Priority ?? existing?.Priority; + var memoryPriority = payload.MemoryPriority ?? existing?.MemoryPriority; + var ioPriority = payload.IoPriority ?? existing?.IoPriority; + var efficiencyMode = payload.EfficiencyMode ?? existing?.EfficiencyMode; + + var rule = new PersistentProcessRule + { + Id = existing?.Id ?? Guid.NewGuid().ToString("N"), + Name = $"{processName} rule", + IsEnabled = true, + ProcessName = processName, + ExecutablePath = executablePath, + CpuSelection = cpuSelection, + LegacyAffinityMask = HasSelectionPayload(cpuSelection) ? null : legacyAffinityMask, + CpuAssignmentMode = cpuAssignmentMode, + Priority = priority, + MemoryPriority = memoryPriority, + IoPriority = ioPriority, + EfficiencyMode = efficiencyMode, + ApplyAffinityOnStart = HasSelectionPayload(cpuSelection) || legacyAffinityMask.HasValue, + ApplyPriorityOnStart = priority.HasValue, + ApplyMemoryPriorityOnStart = memoryPriority.HasValue, + ApplyIoPriorityOnStart = ioPriority.HasValue, + ApplyEfficiencyModeOnStart = efficiencyMode.HasValue, + PreventSystemSleepWhileRunning = payload.PreventSystemSleepWhileRunning, + CreatedAt = existing?.CreatedAt ?? now, + UpdatedAt = now, + Description = RuleDescription, + }; + + if (created) + { + rules.Add(rule); + } + else + { + rules[existingIndex] = rule; + } - return new ProcessRuleCreationResult - { - Success = true, - Created = created, - Updated = !created, - Rule = rule, - UserMessage = created - ? $"Saved rule for {processName}." - : $"Updated saved rule for {processName}.", - }; + return Task.FromResult(new ProcessRuleCreationResult + { + Success = true, + Created = created, + Updated = !created, + Rule = rule, + UserMessage = created + ? $"Saved rule for {processName}." + : $"Updated saved rule for {processName}.", + }); + }, + cancellationToken).ConfigureAwait(false); } private static PayloadBuildResult BuildLegacyAffinityPayload(IReadOnlyList currentCoreSelection) diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 8658a5ed..72d501e1 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -189,6 +189,19 @@ private double CalculateCpuUsage(Process process) } } + internal static DateTime? TryGetProcessStartTimeUtc(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + return process.StartTime.ToUniversalTime(); + } + catch (Exception ex) when (ex is ArgumentException || IsPassiveProcessAccessException(ex) || IsTerminatedProcessException(ex)) + { + return null; + } + } + public ProcessModel CreateProcessModel(Process process) { return this.CreateProcessModel(process, this.foregroundProcessService?.TryGetForegroundProcessId()); @@ -290,11 +303,11 @@ private ProcessModel CreateProcessModel(Process process, int? foregroundProcessI { try { - startTimeUtc = process.StartTime.ToUniversalTime(); + startTimeUtc = model.StartTimeUtc = process.StartTime.ToUniversalTime(); } catch (Exception ex) when (IsPassiveProcessAccessException(ex) || IsTerminatedProcessException(ex)) { - // Start time is used only to validate static metadata against PID reuse. + // Start time may be inaccessible for protected processes. } try diff --git a/Services/ServiceConfiguration.cs b/Services/ServiceConfiguration.cs index 4933c184..598fb27d 100644 --- a/Services/ServiceConfiguration.cs +++ b/Services/ServiceConfiguration.cs @@ -50,7 +50,7 @@ private static IServiceCollection ConfigureServiceInfrastructure(this IServiceCo services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(TimeProvider.System); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/Services/SmartNotificationService.cs b/Services/SmartNotificationService.cs deleted file mode 100644 index b0408c63..00000000 --- a/Services/SmartNotificationService.cs +++ /dev/null @@ -1,665 +0,0 @@ -namespace ThreadPilot.Services -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Microsoft.Extensions.Logging; - using ThreadPilot.Models; - - public class SmartNotificationService : ISmartNotificationService, IDisposable - { - private readonly ILogger logger; - private readonly INotificationService baseNotificationService; - private readonly ConcurrentQueue notificationQueue = new(); - private readonly ConcurrentDictionary scheduledNotifications = new(); - private readonly ConcurrentDictionary lastNotificationTimes = new(); - private readonly ConcurrentDictionary> notificationHistory = new(); - private readonly List sentNotifications = new(); - - private readonly object historyLock = new(); - private readonly System.Threading.Timer processingTimer; - private readonly System.Threading.Timer cleanupTimer; - private readonly SemaphoreSlim processingLock = new(1, 1); - - private NotificationPreferences preferences = new(); - private DateTime? doNotDisturbUntil; - - private volatile bool disposed; - - public event EventHandler? NotificationSent; - - public event EventHandler? NotificationThrottled; - - public event EventHandler? NotificationDeduplicated; - - public event EventHandler? DoNotDisturbChanged; - - public SmartNotificationService( - ILogger logger, - INotificationService baseNotificationService) - { - this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); - this.baseNotificationService = baseNotificationService ?? throw new ArgumentNullException(nameof(baseNotificationService)); - - this.preferences = this.CreateDefaultPreferences(); - - // Set up processing timer (process queue every 2 seconds) - this.processingTimer = new System.Threading.Timer(this.ProcessQueueCallback, null, - TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2)); - - // Set up cleanup timer (clean history every hour) - this.cleanupTimer = new System.Threading.Timer(this.CleanupCallback, null, - TimeSpan.FromHours(1), TimeSpan.FromHours(1)); - } - - public async Task InitializeAsync() - { - this.logger.LogInformation("Initializing SmartNotificationService"); - - // Initialize default preferences - this.preferences = this.CreateDefaultPreferences(); - - // Load preferences from storage (simplified) - await this.LoadPreferencesAsync(); - } - - public async Task SendNotificationAsync(SmartNotification notification) - { - try - { - // Validate notification - if (string.IsNullOrWhiteSpace(notification.Title) && string.IsNullOrWhiteSpace(notification.Message)) - { - this.logger.LogWarning("Attempted to send notification with empty title and message"); - return false; - } - - // Check if notifications are enabled - if (!this.preferences.IsEnabled) - { - this.logger.LogDebug("Notifications are disabled, skipping notification: {Title}", notification.Title); - return false; - } - - // Check category preferences - if (this.preferences.CategoryEnabled.TryGetValue(notification.Category, out var categoryEnabled) && !categoryEnabled) - { - this.logger.LogDebug( - "Category {Category} is disabled, skipping notification: {Title}", - notification.Category, notification.Title); - return false; - } - - // Check minimum priority - if (notification.Priority < this.preferences.MinimumPriority) - { - this.logger.LogDebug( - "Notification priority {Priority} below minimum {MinPriority}, skipping: {Title}", - notification.Priority, this.preferences.MinimumPriority, notification.Title); - return false; - } - - // Check Do Not Disturb mode - if (this.IsDoNotDisturbActive() && notification.Priority < NotificationPriority.Critical) - { - this.logger.LogDebug("Do Not Disturb is active, skipping non-critical notification: {Title}", notification.Title); - return false; - } - - // Check throttling - if (this.IsThrottled(notification)) - { - this.NotificationThrottled?.Invoke(this, new SmartNotificationEventArgs - { - Notification = notification, - Reason = "Throttled due to rate limiting", - }); - return false; - } - - // Check deduplication - if (this.IsDuplicate(notification)) - { - this.NotificationDeduplicated?.Invoke(this, new SmartNotificationEventArgs - { - Notification = notification, - Reason = "Deduplicated - similar notification recently sent", - }); - return false; - } - - // Add to queue for processing - this.notificationQueue.Enqueue(notification); - this.logger.LogDebug( - "Queued notification: {Title} (Priority: {Priority}, Category: {Category})", - notification.Title, notification.Priority, notification.Category); - - return true; - } - catch (Exception ex) - { - this.logger.LogError(ex, "Error sending notification: {Title}", notification.Title); - return false; - } - } - - public async Task SendNotificationAsync(string title, string message, - NotificationPriority priority = NotificationPriority.Normal, - NotificationCategory category = NotificationCategory.Information) - { - var notification = new SmartNotification - { - Title = title, - Message = message, - Priority = priority, - Category = category, - DeduplicationKey = $"{category}:{title}:{message}".GetHashCode().ToString(), - }; - - return await this.SendNotificationAsync(notification); - } - - public Task ScheduleNotificationAsync(SmartNotification notification, DateTime deliveryTime) - { - ArgumentNullException.ThrowIfNull(notification); - - notification.ScheduledFor = deliveryTime; - - this.scheduledNotifications[notification.Id] = notification; - - this.logger.LogDebug( - "Scheduled notification {Id} for delivery at {DeliveryTime}", - notification.Id, deliveryTime); - - return Task.FromResult(true); - } - - public async Task CancelNotificationAsync(string notificationId) - { - var removed = this.scheduledNotifications.TryRemove(notificationId, out var notification); - if (removed) - { - this.logger.LogDebug("Cancelled scheduled notification: {Id}", notificationId); - } - return removed; - } - - public async Task> GetPendingNotificationsAsync() - { - var pending = new List(); - - // Add queued notifications - pending.AddRange(this.notificationQueue.ToArray()); - - // Add scheduled notifications - pending.AddRange(this.scheduledNotifications.Values); - - return pending.OrderByDescending(n => n.Priority).ThenBy(n => n.CreatedAt).ToList(); - } - - public async Task> GetNotificationHistoryAsync(TimeSpan? period = null) - { - var cutoff = period.HasValue ? DateTime.UtcNow - period.Value : DateTime.MinValue; - - lock (this.sentNotifications) - { - return this.sentNotifications - .Where(n => n.CreatedAt >= cutoff) - .OrderByDescending(n => n.CreatedAt) - .ToList(); - } - } - - public Task ClearHistoryAsync() - { - lock (this.sentNotifications) - { - this.sentNotifications.Clear(); - } - - lock (this.historyLock) - { - this.notificationHistory.Clear(); - } - - this.lastNotificationTimes.Clear(); - this.logger.LogInformation("Cleared notification history"); - return Task.CompletedTask; - } - - public async Task UpdatePreferencesAsync(NotificationPreferences preferences) - { - this.preferences = preferences ?? throw new ArgumentNullException(nameof(preferences)); - await this.SavePreferencesAsync(); - this.logger.LogInformation("Updated notification preferences"); - } - - public async Task GetPreferencesAsync() - { - return this.preferences; - } - - public async Task SetDoNotDisturbAsync(bool enabled, TimeSpan? duration = null) - { - var wasActive = this.IsDoNotDisturbActive(); - - if (enabled) - { - this.doNotDisturbUntil = duration.HasValue - ? DateTime.UtcNow + duration.Value - : DateTime.MaxValue; - this.preferences.DoNotDisturbMode = true; - } - else - { - this.doNotDisturbUntil = null; - this.preferences.DoNotDisturbMode = false; - } - - var isActive = this.IsDoNotDisturbActive(); - if (wasActive != isActive) - { - this.DoNotDisturbChanged?.Invoke(this, isActive); - this.logger.LogInformation("Do Not Disturb mode {Status}", isActive ? "enabled" : "disabled"); - } - } - - public bool IsDoNotDisturbActive() - { - if (!this.preferences.DoNotDisturbMode) - { - return false; - } - - if (this.doNotDisturbUntil.HasValue) - { - if (DateTime.UtcNow <= this.doNotDisturbUntil.Value) - { - return true; - } - - this.preferences.DoNotDisturbMode = false; - this.doNotDisturbUntil = null; - this.DoNotDisturbChanged?.Invoke(this, false); - return false; - } - - return IsWithinQuietHours( - DateTime.Now.TimeOfDay, - this.preferences.DoNotDisturbStart, - this.preferences.DoNotDisturbEnd); - } - - internal static bool IsWithinQuietHours(TimeSpan timeOfDay, TimeSpan start, TimeSpan end) - { - if (start == end) - { - return false; - } - - return start < end - ? timeOfDay >= start && timeOfDay <= end - : timeOfDay >= start || timeOfDay <= end; - } - - public async Task> GetStatisticsAsync() - { - var stats = new Dictionary(); - - lock (this.sentNotifications) - { - var last24Hours = this.sentNotifications.Where(n => n.CreatedAt >= DateTime.UtcNow.AddDays(-1)).ToList(); - var lastWeek = this.sentNotifications.Where(n => n.CreatedAt >= DateTime.UtcNow.AddDays(-7)).ToList(); - - stats["TotalSent"] = this.sentNotifications.Count; - stats["SentLast24Hours"] = last24Hours.Count; - stats["SentLastWeek"] = lastWeek.Count; - stats["PendingCount"] = this.notificationQueue.Count; - stats["ScheduledCount"] = this.scheduledNotifications.Count; - - // Category breakdown - var categoryStats = this.sentNotifications - .GroupBy(n => n.Category) - .ToDictionary(g => g.Key.ToString(), g => g.Count()); - stats["ByCategory"] = categoryStats; - - // Priority breakdown - var priorityStats = this.sentNotifications - .GroupBy(n => n.Priority) - .ToDictionary(g => g.Key.ToString(), g => g.Count()); - stats["ByPriority"] = priorityStats; - } - - return stats; - } - - public async Task TestNotificationAsync() - { - var testNotification = new SmartNotification - { - Title = "Test Notification", - Message = "This is a test notification from ThreadPilot Smart Notification System", - Priority = NotificationPriority.Normal, - Category = NotificationCategory.System, - }; - - return await this.SendNotificationAsync(testNotification); - } - - private void ProcessQueueCallback(object? state) - { - TaskSafety.FireAndForget(this.ProcessQueueCallbackAsync(), ex => - { - this.logger.LogWarning(ex, "Error during notification queue processing"); - }); - } - - private async Task ProcessQueueCallbackAsync() - { - if (this.disposed) - { - return; - } - - try - { - await this.processingLock.WaitAsync().ConfigureAwait(false); - } - catch (ObjectDisposedException) - { - return; - } - - try - { - var processedCount = 0; - var maxProcessPerCycle = 10; - - while (this.notificationQueue.TryDequeue(out var notification) && processedCount < maxProcessPerCycle) - { - await this.ProcessNotificationAsync(notification); - processedCount++; - } - - // Process scheduled notifications - var now = DateTime.UtcNow; - var dueNotifications = this.scheduledNotifications.Values - .Where(n => n.ScheduledFor <= now) - .ToList(); - - foreach (var notification in dueNotifications) - { - this.scheduledNotifications.TryRemove(notification.Id, out _); - await this.ProcessNotificationAsync(notification); - } - } - finally - { - try - { - this.processingLock.Release(); - } - catch (ObjectDisposedException) - { - } - } - } - - private async Task ProcessNotificationAsync(SmartNotification notification) - { - try - { - // Check if notification has expired - if (notification.ExpiresAfter.HasValue && - DateTime.UtcNow - notification.CreatedAt > notification.ExpiresAfter.Value) - { - this.logger.LogDebug("Notification expired: {Title}", notification.Title); - return; - } - - // Send through base notification service - await this.baseNotificationService.ShowNotificationAsync( - notification.Title, - notification.Message, - this.ConvertToNotificationType(notification.Priority)); - - this.RecordNotificationSent(notification); - - this.NotificationSent?.Invoke(this, new SmartNotificationEventArgs - { - Notification = notification, - Reason = "Successfully delivered", - }); - - this.logger.LogDebug("Successfully sent notification: {Title}", notification.Title); - } - catch (Exception ex) - { - if (notification.RetryCount < notification.MaxRetries) - { - notification.RetryCount++; - this.notificationQueue.Enqueue(notification); - this.logger.LogWarning( - ex, - "Retrying notification: {Title} (Attempt {Retry}/{Max})", - notification.Title, notification.RetryCount, notification.MaxRetries); - return; - } - - this.logger.LogError( - ex, - "Failed to send notification after {MaxRetries} attempts: {Title}", - notification.MaxRetries, notification.Title); - } - } - - private bool IsThrottled(SmartNotification notification) - { - if (!this.preferences.ThrottleConfigs.TryGetValue(notification.Category, out var config)) - { - return false; // No throttling configured for this category - } - - var key = $"{notification.Category}:{notification.DeduplicationKey}"; - var now = DateTime.UtcNow; - - // Check minimum interval - if (this.lastNotificationTimes.TryGetValue(key, out var lastTime)) - { - if (now - lastTime < config.MinInterval) - { - return true; - } - } - - // Check hourly and daily limits - var oneHourAgo = now.AddHours(-1); - var oneDayAgo = now.AddDays(-1); - - lock (this.historyLock) - { - var history = this.notificationHistory.GetOrAdd(key, _ => new List()); - - history.RemoveAll(t => t < oneDayAgo); - - var hourlyCount = history.Count(t => t >= oneHourAgo); - var dailyCount = history.Count; - - return hourlyCount >= config.MaxPerHour || dailyCount >= config.MaxPerDay; - } - } - - private bool IsDuplicate(SmartNotification notification) - { - if (string.IsNullOrEmpty(notification.DeduplicationKey)) - { - return false; - } - - if (!this.preferences.ThrottleConfigs.TryGetValue(notification.Category, out var config) || - !config.EnableDeduplication) - { - return false; - } - - var key = $"{notification.Category}:{notification.DeduplicationKey}"; - if (this.lastNotificationTimes.TryGetValue(key, out var lastTime)) - { - return DateTime.UtcNow - lastTime < config.DeduplicationWindow; - } - - return false; - } - - private void RecordNotificationSent(SmartNotification notification) - { - var key = $"{notification.Category}:{notification.DeduplicationKey}"; - var now = DateTime.UtcNow; - - this.lastNotificationTimes[key] = now; - - lock (this.historyLock) - { - this.notificationHistory.GetOrAdd(key, _ => new List()).Add(now); - } - - lock (this.sentNotifications) - { - this.sentNotifications.Add(notification); - - // Keep only last 1000 notifications in memory - if (this.sentNotifications.Count > 1000) - { - this.sentNotifications.RemoveRange(0, this.sentNotifications.Count - 1000); - } - } - } - - private NotificationType ConvertToNotificationType(NotificationPriority priority) - { - return priority switch - { - NotificationPriority.Critical => NotificationType.Error, - NotificationPriority.High => NotificationType.Warning, - NotificationPriority.Normal => NotificationType.Information, - NotificationPriority.Low => NotificationType.Information, - _ => NotificationType.Information, - }; - } - - private NotificationPreferences CreateDefaultPreferences() - { - var preferences = new NotificationPreferences(); - - // Enable all categories by default - foreach (NotificationCategory category in Enum.GetValues()) - { - preferences.CategoryEnabled[category] = true; - preferences.ThrottleConfigs[category] = new NotificationThrottleConfig - { - Category = category, - MinInterval = TimeSpan.FromSeconds(30), - MaxPerHour = category == NotificationCategory.Error ? 20 : 10, - MaxPerDay = category == NotificationCategory.Error ? 100 : 50, - }; - } - - return preferences; - } - - private Task LoadPreferencesAsync() - { - // Simplified - would load from actual storage - this.logger.LogDebug("Loaded notification preferences"); - return Task.CompletedTask; - } - - private Task SavePreferencesAsync() - { - // Simplified - would save to actual storage - this.logger.LogDebug("Saved notification preferences"); - return Task.CompletedTask; - } - - private void CleanupCallback(object? state) - { - TaskSafety.FireAndForget(this.CleanupCallbackAsync(), ex => - { - this.logger.LogWarning(ex, "Error during notification cleanup"); - }); - } - - private async Task CleanupCallbackAsync() - { - try - { - var cutoff = DateTime.UtcNow.AddDays(-7); - - // Clean notification history - var keysToRemove = new List(); - lock (this.historyLock) - { - foreach (var kvp in this.notificationHistory) - { - kvp.Value.RemoveAll(t => t < cutoff); - if (kvp.Value.Count == 0) - { - keysToRemove.Add(kvp.Key); - } - } - - foreach (var key in keysToRemove) - { - this.notificationHistory.TryRemove(key, out _); - } - } - - var staleTimestampKeys = this.lastNotificationTimes - .Where(kvp => kvp.Value < cutoff) - .Select(kvp => kvp.Key) - .ToList(); - foreach (var key in staleTimestampKeys) - { - this.lastNotificationTimes.TryRemove(key, out _); - } - - this.logger.LogDebug( - "Cleaned up notification history, removed {Count} empty entries and {TimestampCount} stale timestamps", - keysToRemove.Count, - staleTimestampKeys.Count); - } - catch (Exception ex) - { - this.logger.LogWarning(ex, "Error during notification cleanup"); - } - } - - protected virtual void Dispose(bool disposing) - { - if (this.disposed) - { - return; - } - - this.disposed = true; - - if (disposing) - { - this.processingTimer?.Dispose(); - this.cleanupTimer?.Dispose(); - this.processingLock?.Dispose(); - this.logger.LogInformation("SmartNotificationService disposed"); - } - } - - public void Dispose() - { - this.Dispose(disposing: true); - GC.SuppressFinalize(this); - } - } -} - diff --git a/Services/SystemTweaksService.cs b/Services/SystemTweaksService.cs index 61191708..45bbdc05 100644 --- a/Services/SystemTweaksService.cs +++ b/Services/SystemTweaksService.cs @@ -815,7 +815,6 @@ private async Task SetRegistryTargetsAsync( var backups = this.LoadRegistryBackups(); var changedBackups = false; - var changedTargets = new List(); try { foreach (var target in targets) @@ -833,71 +832,97 @@ private async Task SetRegistryTargetsAsync( await SaveRegistryBackupsAsync(backups); } - foreach (var target in targets) - { - var backupKey = target.BackupKey; + await WriteDriverRegistryTargetsAsync( + targets, + target => + { + if (enabled) + { + return enabledValue; + } - // The backup file is user-writable: only restore a value this tweak itself could have written. - var desiredValue = enabled - ? enabledValue - : restoreOriginalWhenDisabled && backups.TryGetValue(backupKey, out var backup) + // A user-writable backup may restore only values this tweak itself writes. + return restoreOriginalWhenDisabled && backups.TryGetValue(target.BackupKey, out var backup) && (backup.Value == enabledValue || backup.Value == disabledValue) ? backup.Value : disabledValue; - using var key = Registry.LocalMachine.OpenSubKey(target.Path, writable: true); - if (key == null) + }, + WriteDriverRegistryValue, + async () => { - return false; - } + var status = tweak switch + { + SystemTweak.EthernetPowerSaving => await this.GetEthernetPowerSavingStatusAsync(), + SystemTweak.InterruptModeration => await this.GetInterruptModerationStatusAsync(), + SystemTweak.GpuMsiMode => await this.GetGpuMsiModeStatusAsync(), + _ => new TweakStatus { IsAvailable = false }, + }; + if (!status.IsAvailable || status.IsEnabled != enabled) + { + return false; + } - key.SetValue( - target.ValueName, - target.Kind == RegistryValueKind.String - ? desiredValue.ToString(CultureInfo.InvariantCulture) - : desiredValue, - target.Kind); - changedTargets.Add(target); + this.RaiseStatusChanged(tweak.ToString(), status); + return true; + }, + this.logger); + return true; + } + catch (Exception ex) + { + this.logger.LogWarning(ex, "Could not update driver tweak {Tweak}", tweak); + return false; + } + } + + internal static async Task WriteDriverRegistryTargetsAsync( + IEnumerable targets, + Func selectValue, + Action write, + Func> verify, + ILogger logger) + { + var written = new List(); + try + { + foreach (var target in targets) + { + write(target, selectValue(target)); + written.Add(target); } - var status = tweak switch + if (!await verify()) { - SystemTweak.EthernetPowerSaving => await this.GetEthernetPowerSavingStatusAsync(), - SystemTweak.InterruptModeration => await this.GetInterruptModerationStatusAsync(), - SystemTweak.GpuMsiMode => await this.GetGpuMsiModeStatusAsync(), - _ => new TweakStatus { IsAvailable = false }, - }; - this.RaiseStatusChanged(tweak.ToString(), status); - return status.IsAvailable && status.IsEnabled == enabled; + throw new IOException("Windows did not confirm the requested device tweak."); + } } - catch (Exception ex) + catch { - this.logger.LogWarning(ex, "Could not update driver tweak {Tweak}", tweak); - foreach (var target in changedTargets) + foreach (var target in Enumerable.Reverse(written)) { try { - using var key = Registry.LocalMachine.OpenSubKey(target.Path, writable: true); - key?.SetValue( - target.ValueName, - target.Kind == RegistryValueKind.String - ? target.Value.ToString(CultureInfo.InvariantCulture) - : target.Value, - target.Kind); + write(target, target.Value); } - catch (Exception rollbackException) + catch (Exception ex) { - this.logger.LogWarning( - rollbackException, - "Could not roll back {Path}\\{ValueName}", - target.Path, - target.ValueName); + logger.LogWarning(ex, "Could not roll back {Path}\\{ValueName}", target.Path, target.ValueName); } } - return false; + throw; } } + private static void WriteDriverRegistryValue(RegistryTarget target, int value) + { + using var key = Registry.LocalMachine.OpenSubKey(target.Path, writable: true) + ?? throw new IOException($"Device registry key '{target.Path}' is no longer available."); + key.SetValue(target.ValueName, target.Kind == RegistryValueKind.String + ? value.ToString(CultureInfo.InvariantCulture) + : value, target.Kind); + } + private Dictionary LoadRegistryBackups() { try @@ -1105,7 +1130,7 @@ public ProcessResult(int exitCode, string standardOutput, string standardError) public string StandardError { get; } } - private sealed record RegistryTarget( + internal sealed record RegistryTarget( string Path, string ValueName, int Value, diff --git a/Services/SystemUpdateClock.cs b/Services/SystemUpdateClock.cs deleted file mode 100644 index c5cd63c2..00000000 --- a/Services/SystemUpdateClock.cs +++ /dev/null @@ -1,12 +0,0 @@ -/* - * ThreadPilot - updater clock abstraction. - */ -namespace ThreadPilot.Services -{ - using System; - - public sealed class SystemUpdateClock : IUpdateClock - { - public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; - } -} diff --git a/Services/UpdateModels.cs b/Services/UpdateModels.cs index 364578dc..7a588ee5 100644 --- a/Services/UpdateModels.cs +++ b/Services/UpdateModels.cs @@ -70,11 +70,6 @@ public interface IApplicationVersionProvider string DisplayVersion { get; } } - public interface IUpdateClock - { - DateTimeOffset UtcNow { get; } - } - public interface IUpdateService { Task CheckForUpdatesAsync(UpdateCheckRequest request, CancellationToken cancellationToken = default); diff --git a/Services/UpdateService.cs b/Services/UpdateService.cs index 01b7846d..6b80b70e 100644 --- a/Services/UpdateService.cs +++ b/Services/UpdateService.cs @@ -20,7 +20,7 @@ public sealed class UpdateService : IUpdateService private readonly IUpdateInstallerService installerService; private readonly IUpdateTempDirectoryProvider tempDirectoryProvider; private readonly IApplicationShutdownService shutdownService; - private readonly IUpdateClock clock; + private readonly TimeProvider clock; private readonly ILogger logger; private readonly SemaphoreSlim checkGate = new(1, 1); private readonly SemaphoreSlim installGate = new(1, 1); @@ -33,7 +33,7 @@ public UpdateService( IUpdateInstallerService installerService, IUpdateTempDirectoryProvider tempDirectoryProvider, IApplicationShutdownService shutdownService, - IUpdateClock clock, + TimeProvider clock, ILogger logger) { this.updateChecker = updateChecker ?? throw new ArgumentNullException(nameof(updateChecker)); @@ -131,9 +131,8 @@ public async Task DownloadAndInstallAsync(UpdateReleaseInfo private async Task MarkUpdateCheckAttemptAsync(CancellationToken cancellationToken) { - var settings = this.settingsService.Settings; - settings.LastUpdateCheckUtc = this.clock.UtcNow; - await this.settingsService.UpdateSettingsAsync(settings).ConfigureAwait(false); + var checkedAt = this.clock.GetUtcNow(); + await this.settingsService.EditSettingsAsync(draft => draft.LastUpdateCheckUtc = checkedAt).ConfigureAwait(false); } private void TryCleanup(string tempDirectory) diff --git a/Services/VirtualizedProcessService.cs b/Services/VirtualizedProcessService.cs index be0e4749..ff76b7b3 100644 --- a/Services/VirtualizedProcessService.cs +++ b/Services/VirtualizedProcessService.cs @@ -24,8 +24,6 @@ public class VirtualizedProcessService : IVirtualizedProcessService, IDisposable public VirtualizedProcessConfig Configuration { get; set; } = new(); - public event EventHandler? BatchLoadProgress; - public event EventHandler? BackgroundBatchLoaded; public VirtualizedProcessService( @@ -104,32 +102,6 @@ public async Task LoadProcessBatchAsync(int batchIndex, bool batchIndex, totalBatches, batchProcesses.Count, stopwatch.ElapsedMilliseconds); return result; - } - - - public async Task> LoadProcessBatchesAsync(int startBatchIndex, int batchCount, bool activeApplicationsOnly = false) - { - var results = new List(); - var totalBatches = await this.GetTotalBatchCountAsync(activeApplicationsOnly); - - for (int i = 0; i < batchCount && (startBatchIndex + i) < totalBatches; i++) - { - var batchIndex = startBatchIndex + i; - var batch = await this.LoadProcessBatchAsync(batchIndex, activeApplicationsOnly); - results.Add(batch); - - // Report progress - this.BatchLoadProgress?.Invoke(this, new BatchLoadProgressEventArgs - { - LoadedBatches = i + 1, - TotalBatches = batchCount, - LoadedProcesses = results.Sum(r => r.Processes.Count), - TotalProcesses = batch.TotalProcessCount, - StatusMessage = $"Loaded batch {batchIndex + 1} of {totalBatches}", - }); - } - - return results; } public async Task PreloadNextBatchAsync(int currentBatchIndex, bool activeApplicationsOnly = false) @@ -164,44 +136,6 @@ public async Task PreloadNextBatchAsync(int currentBatchIndex, bool activeApplic } } - public async Task> SearchProcessesAsync(string searchTerm, bool activeApplicationsOnly = false) - { - if (string.IsNullOrWhiteSpace(searchTerm)) - { - return new List(); - } - - await this.EnsureProcessesLoadedAsync(activeApplicationsOnly); - - var filteredProcesses = activeApplicationsOnly - ? this.allProcesses?.Where(p => p.HasVisibleWindow) ?? Enumerable.Empty() - : this.allProcesses ?? Enumerable.Empty(); - - return filteredProcesses - .Where(p => p.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) || - (p.MainWindowTitle?.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) ?? false)) - .ToList(); - } - - public async Task RefreshBatchAsync(int batchIndex, bool activeApplicationsOnly = false) - { - var cacheKey = $"batch_{batchIndex}_{activeApplicationsOnly}"; - this.batchCache.TryRemove(cacheKey.GetHashCode(), out _); - - // Force refresh of all processes - await this.RefreshAllProcessesAsync(activeApplicationsOnly); - - return await this.LoadProcessBatchAsync(batchIndex, activeApplicationsOnly); - } - - public void ClearCache() - { - this.batchCache.Clear(); - this.allProcesses = null; - this.lastFullRefresh = DateTime.MinValue; - this.logger.LogInformation("Cleared virtualized process cache"); - } - private async Task EnsureProcessesLoadedAsync(bool activeApplicationsOnly) { if (this.allProcesses == null || DateTime.UtcNow - this.lastFullRefresh > this.Configuration.RefreshInterval) diff --git a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs index 29216ac6..99cbf438 100644 --- a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsModelTests.cs @@ -4,6 +4,27 @@ namespace ThreadPilot.Core.Tests public sealed class ApplicationSettingsModelTests { + [Fact] + public void LegacySettings_WithRemovedPreferences_StillDeserialize() + { + var json = """ + { + "enableQuickApplyFromTray": false, + "enableMonitoringControlFromTray": false, + "enableNotificationSound": true, + "showDetailedTooltips": false, + "autoHideNotifications": false, + "notificationPosition": "TopLeft", + "enableAutomationMonitoring": false + } + """; + var options = new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + var settings = System.Text.Json.JsonSerializer.Deserialize(json, options); + + Assert.NotNull(settings); + Assert.False(settings.EnableAutomationMonitoring); + } + [Fact] public void Constructor_StartMinimizedDefaultsFalse_ForManualLaunchVisibility() { @@ -17,8 +38,8 @@ public void Constructor_StartMinimizedDefaultsFalse_ForManualLaunchVisibility() Assert.Equal("en-US", settings.Language); Assert.True(settings.EnableAutomaticUpdateChecks); Assert.False(settings.IncludePrereleaseUpdates); - Assert.Null(settings.LastUpdateCheckUtc); - Assert.Equal(CpuAssignmentMode.AffinityMask, settings.DefaultCpuAssignmentMode); + Assert.Null(settings.LastUpdateCheckUtc); + Assert.Equal(CpuAssignmentMode.AffinityMask, settings.DefaultCpuAssignmentMode); } [Fact] @@ -26,17 +47,17 @@ public void CopyFrom_CopiesLanguage() { var source = new ApplicationSettingsModel { - Language = "zh-CN", - EnableAutomationMonitoring = false, - DefaultCpuAssignmentMode = CpuAssignmentMode.IdealProcessor, + Language = "zh-CN", + EnableAutomationMonitoring = false, + DefaultCpuAssignmentMode = CpuAssignmentMode.IdealProcessor, }; var target = new ApplicationSettingsModel(); target.CopyFrom(source); Assert.Equal("zh-CN", target.Language); - Assert.False(target.EnableAutomationMonitoring); - Assert.Equal(CpuAssignmentMode.IdealProcessor, target.DefaultCpuAssignmentMode); + Assert.False(target.EnableAutomationMonitoring); + Assert.Equal(CpuAssignmentMode.IdealProcessor, target.DefaultCpuAssignmentMode); } [Fact] @@ -47,7 +68,7 @@ public void HasSameUserSettingsAs_ReturnsTrue_WhenChangedSettingIsRestored() EnableNotifications = true, }; - var editableSettings = (ApplicationSettingsModel)savedSettings.Clone(); + var editableSettings = savedSettings.Clone(); editableSettings.EnableNotifications = false; Assert.False(editableSettings.HasSameUserSettingsAs(savedSettings)); @@ -63,7 +84,7 @@ public void HasSameUserSettingsAs_IgnoresMetadataTimestamps() { UpdatedAt = new System.DateTime(2026, 5, 16, 10, 0, 0, System.DateTimeKind.Utc), }; - var editableSettings = (ApplicationSettingsModel)savedSettings.Clone(); + var editableSettings = savedSettings.Clone(); editableSettings.UpdatedAt = savedSettings.UpdatedAt.AddMinutes(5); Assert.True(editableSettings.HasSameUserSettingsAs(savedSettings)); diff --git a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs index 45aaa4c7..83d7c893 100644 --- a/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ApplicationSettingsServiceTests.cs @@ -5,6 +5,7 @@ namespace ThreadPilot.Core.Tests using System.Globalization; using System.IO; using System.Threading.Tasks; + using System.Windows.Input; using Microsoft.Extensions.Logging.Abstractions; using ThreadPilot.Models; using ThreadPilot.Services; @@ -12,6 +13,118 @@ namespace ThreadPilot.Core.Tests public sealed class ApplicationSettingsServiceTests { + [Fact] + public async Task EditSettingsAsync_FailedShortcutEditKeepsCommittedKey() + { + var storage = new FakeSettingsStorage(); + var service = CreateService(storage); + await service.EditSettingsAsync(draft => draft.KeyboardShortcuts = + [new KeyboardShortcut { ActionName = "Test", Key = Key.A }]); + + storage.FailWrites = true; + await Assert.ThrowsAsync(() => service.EditSettingsAsync( + draft => draft.KeyboardShortcuts[0].Key = Key.B)); + + var restarted = CreateService(storage); + await restarted.LoadSettingsAsync(); + Assert.Equal(Key.A, Assert.Single(restarted.Settings.KeyboardShortcuts).Key); + Assert.Equal(Key.A, Assert.Single(service.Settings.KeyboardShortcuts).Key); + } + + [Fact] + public async Task EditSettingsAsync_RetainedDraftCannotMutateCommittedSettings() + { + var service = CreateService(new FakeSettingsStorage()); + ApplicationSettingsModel? draftOutsideEdit = null; + await service.EditSettingsAsync(draft => + { + draft.StartMinimized = false; + draft.KeyboardShortcuts = [new KeyboardShortcut { ActionName = "Test", Key = Key.A }]; + draftOutsideEdit = draft; + }); + + draftOutsideEdit!.StartMinimized = true; + draftOutsideEdit.KeyboardShortcuts[0].Key = Key.B; + Assert.False(service.Settings.StartMinimized); + Assert.Equal(Key.A, Assert.Single(service.Settings.KeyboardShortcuts).Key); + } + + [Fact] + public async Task EditSettingsAsync_FailedWriteDoesNotPublishChanges() + { + var storage = new FakeSettingsStorage { FailWrites = true }; + var service = CreateService(storage); + var changes = new List(); + service.SettingsChanged += (_, args) => changes.Add(args); + + await Assert.ThrowsAsync(() => service.EditSettingsAsync(draft => draft.StartMinimized = true)); + + Assert.False(service.Settings.StartMinimized); + Assert.Empty(changes); + + storage.FailWrites = false; + await service.EditSettingsAsync(draft => draft.StartMinimized = true); + + Assert.True(service.Settings.StartMinimized); + Assert.True(Assert.Single(changes).NewSettings.StartMinimized); + } + + [Fact] + public async Task EditSettingsAsync_ConcurrentEditsPublishCommittedSnapshotsInOrder() + { + var writeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseWrite = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var storage = new FakeSettingsStorage + { + BeforeWrite = async () => + { + if (writeStarted.TrySetResult()) + { + await releaseWrite.Task; + } + }, + }; + var service = CreateService(storage); + var published = new List(); + service.SettingsChanged += (_, args) => published.Add(args.NewSettings); + var targetGameBoost = !service.Settings.GameBoostEnabled; + + var first = service.EditSettingsAsync(draft => draft.StartMinimized = true); + try + { + await writeStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + var second = service.EditSettingsAsync(draft => draft.GameBoostEnabled = targetGameBoost); + + Assert.False(service.Settings.StartMinimized); + Assert.False(second.IsCompleted); + Assert.Empty(published); + releaseWrite.TrySetResult(); + + await Task.WhenAll(first, second); + } + finally + { + releaseWrite.TrySetResult(); + } + + Assert.Collection( + published, + firstSnapshot => + { + Assert.True(firstSnapshot.StartMinimized); + Assert.Equal(!targetGameBoost, firstSnapshot.GameBoostEnabled); + }, + secondSnapshot => + { + Assert.True(secondSnapshot.StartMinimized); + Assert.Equal(targetGameBoost, secondSnapshot.GameBoostEnabled); + }); + var reloaded = CreateService(storage); + await reloaded.LoadSettingsAsync(); + Assert.True(reloaded.Settings.StartMinimized); + Assert.Equal(targetGameBoost, reloaded.Settings.GameBoostEnabled); + } + [Fact] public async Task LoadSettingsAsync_CreatesDefaults_WhenFileIsMissing() { @@ -530,10 +643,17 @@ public bool Exists(string path) return Task.FromResult(content); } - public bool FailWrites { get; init; } + public bool FailWrites { get; set; } + + public Func? BeforeWrite { get; init; } - public Task WriteAsync(string path, string content) + public async Task WriteAsync(string path, string content) { + if (this.BeforeWrite != null) + { + await this.BeforeWrite(); + } + if (this.FailWrites) { throw new IOException("Simulated write failure."); @@ -541,7 +661,6 @@ public Task WriteAsync(string path, string content) this.Files[path] = content; this.Writes[path] = content; - return Task.CompletedTask; } } } diff --git a/Tests/ThreadPilot.Core.Tests/ConfigurationBackupTests.cs b/Tests/ThreadPilot.Core.Tests/ConfigurationBackupTests.cs index a0e9dd5b..5f412280 100644 --- a/Tests/ThreadPilot.Core.Tests/ConfigurationBackupTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ConfigurationBackupTests.cs @@ -1,6 +1,7 @@ namespace ThreadPilot.Core.Tests { using System.Diagnostics; + using Microsoft.Extensions.Logging.Abstractions; using Moq; using ThreadPilot.Models; using ThreadPilot.Services; @@ -24,19 +25,100 @@ public async Task LegacyBundle_KeepsPersistentRules() backup.SchemaVersion = "2.0"; backup.PersistentProcessRules = null; await harness.Service.ApplyAsync(ConfigurationBackupService.Parse(ConfigurationBackupService.Serialize(backup))!); - harness.Rules.Verify(x => x.SaveAsync(It.IsAny>()), Times.Never); + Assert.Empty(harness.Rules.Writes); } [Fact] - public async Task FailedImport_RestoresAllPreviousConfiguration() + public async Task FailedImport_KeepsConcurrentCommittedSettingsEdit() + { + var file = Path.Combine(Path.GetTempPath(), $"tp-review-{Guid.NewGuid():N}.json"); + try + { + var settings = new ApplicationSettingsService( + NullLogger.Instance, + new FileSettingsStorage(), file, null); + await settings.EditSettingsAsync(draft => draft.StartMinimized = false); + var harness = new Harness(); + var service = new ConfigurationBackupService(settings, harness.Associations.Object, harness.Rules); + var backup = await service.CaptureAsync(settings.Settings); + var replacing = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var writes = 0; + harness.Associations.Setup(x => x.ReplaceConfigurationAsync(It.IsAny())) + .Returns(() => + { + if (Interlocked.Increment(ref writes) == 1) + { + replacing.SetResult(); + return release.Task; + } + + return Task.FromResult(true); + }); + + var importing = service.ApplyAsync(backup); + try + { + await replacing.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await settings.EditSettingsAsync(draft => draft.StartMinimized = true); + } + finally + { + release.TrySetResult(false); + } + + await Assert.ThrowsAsync(() => importing); + var restarted = new ApplicationSettingsService( + NullLogger.Instance, + new FileSettingsStorage(), file, null); + await restarted.LoadSettingsAsync(); + Assert.True(restarted.Settings.StartMinimized); + Assert.True(settings.Settings.StartMinimized); + } + finally + { + File.Delete(file); + } + } + + [Fact] + public async Task FailedAssociationImport_RestoresRulesAndLeavesOtherSettingsAlone() + { + var harness = new Harness(); + harness.Associations.Setup(x => x.ReplaceConfigurationAsync(It.IsAny())) + .ReturnsAsync(false); + var backup = await harness.Service.CaptureAsync(harness.Settings.Object.Settings); + backup.PersistentProcessRules = [new() { Id = "new", ProcessName = "new.exe" }]; + await Assert.ThrowsAsync(() => harness.Service.ApplyAsync(backup)); + Assert.Equal("old", Assert.Single(await harness.Rules.LoadAsync()).Id); + Assert.Equal(2, harness.Rules.Writes.Count); + harness.Settings.Verify(x => x.UpdateSettingsAsync(It.IsAny()), Times.Never); + harness.Associations.Verify(x => x.ReplaceConfigurationAsync(It.IsAny()), Times.Once); + } + + [Fact] + public async Task FailedSettingsImport_RestoresRulesAndAssociationsAlreadyChanged() { var harness = new Harness(); - harness.Associations.SetupSequence(x => x.ReplaceConfigurationAsync(It.IsAny())) - .ReturnsAsync(false).ReturnsAsync(true); + var previous = new ProcessMonitorConfiguration { DefaultPowerPlanGuid = "original" }; + var current = previous; + harness.Associations.SetupGet(x => x.Configuration).Returns(() => current); + harness.Associations.Setup(x => x.ReplaceConfigurationAsync(It.IsAny())) + .ReturnsAsync((ProcessMonitorConfiguration replacement) => + { + current = replacement; + return true; + }); + harness.Settings.Setup(x => x.UpdateSettingsAsync(It.IsAny())) + .ThrowsAsync(new IOException("Settings unavailable")); var backup = await harness.Service.CaptureAsync(harness.Settings.Object.Settings); + backup.ProcessMonitorConfiguration!.DefaultPowerPlanGuid = "imported"; backup.PersistentProcessRules = [new() { Id = "new", ProcessName = "new.exe" }]; + await Assert.ThrowsAsync(() => harness.Service.ApplyAsync(backup)); - harness.Rules.Verify(x => x.SaveAsync(It.Is>(r => r.Single().Id == "old")), Times.Once); + + Assert.Equal("original", current.DefaultPowerPlanGuid); + Assert.Equal("old", Assert.Single(await harness.Rules.LoadAsync()).Id); harness.Settings.Verify(x => x.UpdateSettingsAsync(It.IsAny()), Times.Once); } @@ -47,7 +129,7 @@ public async Task InvalidRule_IsRejectedBeforeAnyWrite() var backup = await harness.Service.CaptureAsync(harness.Settings.Object.Settings); backup.PersistentProcessRules = [new() { ProcessName = "game.exe", Priority = ProcessPriorityClass.RealTime }]; await Assert.ThrowsAsync(() => harness.Service.ApplyAsync(backup)); - harness.Rules.Verify(x => x.SaveAsync(It.IsAny>()), Times.Never); + Assert.Empty(harness.Rules.Writes); harness.Associations.Verify(x => x.ReplaceConfigurationAsync(It.IsAny()), Times.Never); } @@ -63,7 +145,7 @@ private sealed class Harness public Mock Associations { get; } = new(); - public Mock Rules { get; } = new(); + public RuleStore Rules { get; } = new(); public ConfigurationBackupService Service { get; } @@ -72,8 +154,22 @@ public Harness() this.Settings.SetupGet(x => x.Settings).Returns(new ApplicationSettingsModel()); this.Associations.SetupGet(x => x.Configuration).Returns(new ProcessMonitorConfiguration()); this.Associations.Setup(x => x.ReplaceConfigurationAsync(It.IsAny())).ReturnsAsync(true); - this.Rules.Setup(x => x.LoadAsync()).ReturnsAsync([new() { Id = "old", ProcessName = "old.exe" }]); - this.Service = new(this.Settings.Object, this.Associations.Object, this.Rules.Object); + this.Service = new(this.Settings.Object, this.Associations.Object, this.Rules); + } + } + + private sealed class RuleStore : IPersistentProcessRuleStore + { + private IReadOnlyList rules = [new() { Id = "old", ProcessName = "old.exe" }]; + + public List> Writes { get; } = new(); + public Task> LoadAsync() => Task.FromResult(this.rules); + + public Task SaveAsync(IReadOnlyList replacement) + { + this.rules = replacement.ToArray(); + this.Writes.Add(this.rules); + return Task.CompletedTask; } } } diff --git a/Tests/ThreadPilot.Core.Tests/EnhancedLoggingServiceTests.cs b/Tests/ThreadPilot.Core.Tests/EnhancedLoggingServiceTests.cs new file mode 100644 index 00000000..312b697e --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/EnhancedLoggingServiceTests.cs @@ -0,0 +1,80 @@ +namespace ThreadPilot.Core.Tests +{ + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Logging.Abstractions; + using Moq; + using ThreadPilot.Models; + using ThreadPilot.Services; + + public sealed class EnhancedLoggingServiceTests : IDisposable + { + private readonly DirectoryInfo directory = Directory.CreateTempSubdirectory("threadpilot-log-"); + + [Fact] + public async Task TemporaryWriteFailure_RetriesEarlierEventsInOrder() + { + using var service = this.CreateService(); + await service.InitializeAsync(); + using (File.Open(service.CurrentLogFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) + { + await service.LogSystemEventAsync("Test", "first event", LogLevel.Error); + } + + await service.LogSystemEventAsync("Test", "second event", LogLevel.Error); + var events = await service.GetLogEntriesAsync(DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddMinutes(1)); + Assert.Contains(events, entry => entry.Message == "first event"); + Assert.Contains(events, entry => entry.Message == "second event"); + var raw = await File.ReadAllTextAsync(service.CurrentLogFilePath); + Assert.True(raw.IndexOf("first event", StringComparison.Ordinal) < raw.IndexOf("second event", StringComparison.Ordinal)); + Assert.Single(events, entry => entry.Message == "first event"); + } + + [Fact] + public async Task OversizeLog_RotatesAndKeepsNewEventsAndExport() + { + using var service = this.CreateService(); + await service.InitializeAsync(); + await File.AppendAllTextAsync(service.CurrentLogFilePath, new string(' ', (1024 * 1024) + 1) + Environment.NewLine); + await service.LogSystemEventAsync("Test", "after rotation", LogLevel.Error); + + var paths = this.directory.GetFiles("ThreadPilot*.log"); + Assert.Equal(2, paths.Length); + Assert.Contains(paths, file => file.Name.StartsWith("ThreadPilot_", StringComparison.Ordinal)); + Assert.Contains("after rotation", await File.ReadAllTextAsync(service.CurrentLogFilePath), StringComparison.Ordinal); + var exported = await service.ExportLogsAsync(DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddMinutes(1), Path.Combine(this.directory.FullName, "export.txt")); + Assert.Contains("after rotation", await File.ReadAllTextAsync(exported), StringComparison.Ordinal); + Assert.Equal(2, (await service.GetLogStatisticsAsync()).TotalLogFiles); + } + + [Fact] + public async Task Cleanup_RemovesExpiredLogsAndKeepsCurrentAndRecentFiles() + { + using var service = this.CreateService(); + await service.InitializeAsync(); + var expired = Path.Combine(this.directory.FullName, "ThreadPilot_expired.log"); + var recent = Path.Combine(this.directory.FullName, "ThreadPilot_recent.log"); + await File.WriteAllTextAsync(expired, "expired"); + await File.WriteAllTextAsync(recent, "recent"); + File.SetCreationTimeUtc(expired, DateTime.UtcNow.AddDays(-10)); + + await service.CleanupOldLogsAsync(); + + Assert.False(File.Exists(expired)); + Assert.True(File.Exists(recent)); + Assert.True(File.Exists(service.CurrentLogFilePath)); + } + + public void Dispose() => this.directory.Delete(recursive: true); + + private EnhancedLoggingService CreateService() + { + var settings = new Mock(); + settings.SetupGet(x => x.Settings).Returns(new ApplicationSettingsModel + { + MaxLogFileSizeMb = 1, + LogRetentionDays = 2, + }); + return new EnhancedLoggingService(NullLogger.Instance, settings.Object, this.directory.FullName); + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs b/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs index 0e5df94d..17da5f60 100644 --- a/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs @@ -111,6 +111,76 @@ public async Task GameExit_RestoresBackground_AndDeletesJournal() Assert.False(File.Exists(this.journalPath)); } + [Fact] + public async Task UnwritableJournal_PreventsGameBoostChanges() + { + Directory.CreateDirectory(this.journalPath); + try + { + using var service = this.CreateService(); + + await service.TickAsync(); + + Assert.Empty(this.processes.CpuSets[ChromePid]); + } + finally + { + Directory.Delete(this.journalPath); + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task LockedStartupJournal_IsRetriedBeforeAnyNewSession(bool enabled) + { + using (var crashed = this.CreateService()) + { + await crashed.TickAsync(); + } + + Assert.NotEmpty(this.processes.CpuSets[ChromePid]); + const int nextGamePid = 401; + this.processes.Add(nextGamePid, "NextGame", @"D:\SteamLibrary\steamapps\common\NextGame\NextGame.exe"); + this.foregroundPid = nextGamePid; + this.settings.GameBoostEnabled = enabled; + using var service = this.CreateService(); + using (File.Open(this.journalPath, FileMode.Open, FileAccess.Read, FileShare.None)) + { + await service.StartAsync(); + await service.TickAsync(); + Assert.Null(service.ActiveGameName); + Assert.Empty(this.processes.CpuSets[nextGamePid]); + } + + await service.TickAsync(); + Assert.Equal(enabled ? "NextGame" : null, service.ActiveGameName); + await service.StopAsync(); + + Assert.Empty(this.processes.CpuSets[ChromePid]); + Assert.False(File.Exists(this.journalPath)); + } + + [Fact] + public async Task FailedRestore_RemainsInJournalForTheNextAttempt() + { + using var service = this.CreateService(); + await service.TickAsync(); + this.processes.FailClear.Add(ChromePid); + + this.processes.Exit(GamePid); + await service.TickAsync(); + + Assert.NotEmpty(this.processes.CpuSets[ChromePid]); + Assert.True(File.Exists(this.journalPath)); + + this.processes.FailClear.Clear(); + await service.StopAsync(); + + Assert.Empty(this.processes.CpuSets[ChromePid]); + Assert.False(File.Exists(this.journalPath)); + } + [Fact] public async Task HeldGame_ExitEvent_EndsTheSessionAndRestores_WithoutATick() { @@ -705,6 +775,11 @@ public FakeProcesses() processService.Setup(s => s.ClearProcessCpuSetAsync(It.IsAny())) .ReturnsAsync((ProcessModel p) => { + if (this.FailClear.Contains(p.ProcessId)) + { + return false; + } + this.CpuSets[p.ProcessId] = []; return true; }); @@ -760,6 +835,8 @@ public FakeProcesses() public HashSet FailButApply { get; } = new(); + public HashSet FailClear { get; } = new(); + public List ApplyCalls { get; } = new(); ///

Gets the names the background rescans built a full model for. diff --git a/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs b/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs index 8f5b5f0a..40c1b079 100644 --- a/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs +++ b/Tests/ThreadPilot.Core.Tests/GitHubUpdateCheckerTests.cs @@ -8,7 +8,7 @@ namespace ThreadPilot.Core.Tests public sealed class GitHubUpdateCheckerTests { [Fact] - public async Task GetLatestVersionAsync_ReturnsStableRelease_WhenTagIsSemver() + public async Task GetLatestReleaseInfoAsync_ReturnsStableRelease_WhenTagIsSemver() { var client = new FakeGitHubReleaseClient( """ @@ -21,34 +21,36 @@ public async Task GetLatestVersionAsync_ReturnsStableRelease_WhenTagIsSemver() """); var checker = new GitHubUpdateChecker(client); - var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + var release = await checker.GetLatestReleaseInfoAsync("PrimeBuild-pc", "ThreadPilot"); - Assert.Equal(new System.Version(1, 2, 3), latest); - Assert.Equal("https://example.test/releases/v1.2.3", releaseUrl); + Assert.NotNull(release); + Assert.Equal(new SemanticVersion(1, 2, 3), release.Version); + Assert.Equal("https://example.test/releases/v1.2.3", release.ReleasePageUrl.AbsoluteUri); } - [Fact] - public async Task GetLatestVersionAsync_IgnoresDraftOrPrerelease() + [Theory] + [InlineData("true", "false")] + [InlineData("false", "true")] + public async Task GetLatestReleaseInfoAsync_IgnoresDraftOrPrerelease(string draft, string prerelease) { var client = new FakeGitHubReleaseClient( - """ + $$""" { - "tag_name": "v1.2.3-beta1", - "prerelease": true, - "draft": false, - "html_url": "https://example.test/releases/v1.2.3-beta1" + "tag_name": "v1.2.3", + "prerelease": {{prerelease}}, + "draft": {{draft}}, + "html_url": "https://example.test/releases/v1.2.3" } """); var checker = new GitHubUpdateChecker(client); - var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + var release = await checker.GetLatestReleaseInfoAsync("PrimeBuild-pc", "ThreadPilot"); - Assert.Null(latest); - Assert.Null(releaseUrl); + Assert.Null(release); } [Fact] - public async Task GetLatestVersionAsync_ReturnsNull_WhenTagCannotBeParsed() + public async Task GetLatestReleaseInfoAsync_ReturnsNull_WhenTagCannotBeParsed() { var client = new FakeGitHubReleaseClient( """ @@ -61,10 +63,9 @@ public async Task GetLatestVersionAsync_ReturnsNull_WhenTagCannotBeParsed() """); var checker = new GitHubUpdateChecker(client); - var (latest, releaseUrl) = await checker.GetLatestVersionAsync("PrimeBuild-pc", "ThreadPilot"); + var release = await checker.GetLatestReleaseInfoAsync("PrimeBuild-pc", "ThreadPilot"); - Assert.Null(latest); - Assert.Equal("https://example.test/releases/release-main", releaseUrl); + Assert.Null(release); } private sealed class FakeGitHubReleaseClient : IGitHubReleaseClient @@ -76,11 +77,6 @@ public FakeGitHubReleaseClient(string responseJson) this.responseJson = responseJson; } - public Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) - { - return Task.FromResult(this.responseJson); - } - public Task GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) { return Task.FromResult($"[{this.responseJson}]"); diff --git a/Tests/ThreadPilot.Core.Tests/LogFileManagerTests.cs b/Tests/ThreadPilot.Core.Tests/LogFileManagerTests.cs deleted file mode 100644 index 6124b91c..00000000 --- a/Tests/ThreadPilot.Core.Tests/LogFileManagerTests.cs +++ /dev/null @@ -1,123 +0,0 @@ -namespace ThreadPilot.Core.Tests -{ - using Microsoft.Extensions.Logging.Abstractions; - using ThreadPilot.Services; - - public sealed class LogFileManagerTests - { - [Fact] - public async Task WriteReadStatisticsAndExport_RoundTripStructuredEntries() - { - var directory = CreateTemporaryDirectory(); - var exportPath = Path.Combine(directory, "export.txt"); - using var manager = new LogFileManager(NullLogger.Instance, directory); - var now = DateTime.UtcNow; - var information = CreateEntry(now.AddMinutes(-2), "Information", "started"); - var warning = CreateEntry(now.AddMinutes(-1), "Warning", "warning"); - var error = CreateEntry(now, "Error", "failed"); - - try - { - await manager.InitializeAsync(); - await manager.WriteLogEntriesAsync([information, "not-json", warning]); - await manager.WriteLogEntryAsync(error); - - var entries = await manager.ReadLogEntriesAsync(now.AddMinutes(-3), now.AddMinutes(1), maxEntries: 2); - var statistics = await manager.GetStatisticsAsync(); - var resultPath = await manager.ExportLogsAsync(now.AddMinutes(-3), now.AddMinutes(1), exportPath); - - Assert.Equal([error, warning], entries); - Assert.Equal(1, statistics.TotalLogFiles); - Assert.Equal(1, statistics.InfoCount); - Assert.Equal(1, statistics.WarningCount); - Assert.Equal(1, statistics.ErrorCount); - Assert.True(statistics.CurrentFileSizeBytes > 0); - Assert.Equal(exportPath, resultPath); - var export = await File.ReadAllTextAsync(exportPath); - Assert.Contains("# Total Entries: 3", export, StringComparison.Ordinal); - Assert.Contains(information, export, StringComparison.Ordinal); - Assert.DoesNotContain("not-json", export, StringComparison.Ordinal); - } - finally - { - DeleteDirectory(directory); - } - } - - [Fact] - public async Task WriteLogEntry_WhenSizeLimitExceeded_RotatesAndKeepsCurrentLog() - { - var directory = CreateTemporaryDirectory(); - using var manager = new LogFileManager(NullLogger.Instance, directory); - - try - { - await manager.InitializeAsync(); - manager.UpdateConfiguration(maxFileSizeMb: 0, retentionDays: 7); - - await manager.WriteLogEntryAsync(CreateEntry(DateTime.UtcNow, "Information", "after rotation")); - - var files = Directory.GetFiles(directory, "*.log"); - Assert.Equal(2, files.Length); - Assert.Contains(files, path => Path.GetFileName(path) == "ThreadPilot.log"); - Assert.Contains(files, path => Path.GetFileName(path).StartsWith("ThreadPilot_", StringComparison.Ordinal)); - Assert.Contains("after rotation", await File.ReadAllTextAsync(manager.CurrentLogFilePath), StringComparison.Ordinal); - } - finally - { - DeleteDirectory(directory); - } - } - - [Fact] - public async Task CleanupOldLogs_RemovesExpiredAndExcessFilesButKeepsCurrentLog() - { - var directory = CreateTemporaryDirectory(); - using var manager = new LogFileManager(NullLogger.Instance, directory); - - try - { - await manager.InitializeAsync(); - var expired = Path.Combine(directory, "ThreadPilot_expired.log"); - var older = Path.Combine(directory, "ThreadPilot_older.log"); - var newer = Path.Combine(directory, "ThreadPilot_newer.log"); - await File.WriteAllTextAsync(expired, "expired"); - await File.WriteAllTextAsync(older, "older"); - await File.WriteAllTextAsync(newer, "newer"); - File.SetCreationTimeUtc(expired, DateTime.UtcNow.AddDays(-10)); - File.SetCreationTimeUtc(older, DateTime.UtcNow.AddHours(-2)); - File.SetCreationTimeUtc(newer, DateTime.UtcNow.AddHours(-1)); - manager.UpdateConfiguration(maxFileSizeMb: 10, retentionDays: 2, maxLogFiles: 1); - - await manager.CleanupOldLogsAsync(); - - Assert.True(File.Exists(manager.CurrentLogFilePath)); - Assert.False(File.Exists(expired)); - Assert.False(File.Exists(older)); - Assert.True(File.Exists(newer)); - } - finally - { - DeleteDirectory(directory); - } - } - - private static string CreateEntry(DateTime timestamp, string level, string message) => - $"{{\"timestamp\":\"{timestamp:yyyy-MM-dd HH:mm:ss.fff}\",\"level\":\"{level}\",\"message\":\"{message}\"}}"; - - private static string CreateTemporaryDirectory() - { - var directory = Path.Combine(Path.GetTempPath(), $"threadpilot-log-manager-{Guid.NewGuid():N}"); - Directory.CreateDirectory(directory); - return directory; - } - - private static void DeleteDirectory(string directory) - { - if (Directory.Exists(directory)) - { - Directory.Delete(directory, recursive: true); - } - } - } -} diff --git a/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs b/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs index ecdab621..819cf0e2 100644 --- a/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs @@ -4,8 +4,8 @@ namespace ThreadPilot.Core.Tests public sealed partial class PackagingMetadataTests { - private const string ReleaseVersion = "1.7.9"; - private const string ReleaseAssemblyVersion = "1.7.9.0"; + private const string ReleaseVersion = "1.7.10"; + private const string ReleaseAssemblyVersion = "1.7.10.0"; [Fact] public void InnoInstaller_UsesStableDisplayNameAndSeparateVersionMetadata() @@ -63,22 +63,14 @@ public void PrimaryInstaller_RemovesThreadPilotOwnedDataOnlyDuringUninstall() } [Fact] - public void PortableUninstallers_RemoveCurrentAndLegacyStartupTasks() + public void LocalPortablePackages_UseOneUninstallerForCurrentAndLegacyStartupTasks() { var root = FindRepositoryRoot(); - var paths = new[] - { - Path.Combine(root, "build", "build-release.ps1"), - Path.Combine(root, "build", "package-release-zips.ps1"), - Path.Combine(root, ".github", "workflows", "release.yml"), - }; - - foreach (var path in paths) - { - var script = File.ReadAllText(path); - Assert.Contains("ThreadPilot_Launch", script, StringComparison.Ordinal); - Assert.Contains("ThreadPilot_Startup", script, StringComparison.Ordinal); - } + var uninstaller = Path.Combine(root, "build", "portable-uninstall.bat"); + AssertFileContains(uninstaller, "ThreadPilot_Launch"); + AssertFileContains(uninstaller, "ThreadPilot_Startup"); + AssertFileContains(Path.Combine(root, "build", "package-release-zips.ps1"), "portable-uninstall.bat"); + AssertFileContains(Path.Combine(root, "build", "build-release.ps1"), "package-release-zips.ps1"); } [Fact] @@ -149,7 +141,7 @@ private static string FindRepositoryRoot() throw new InvalidOperationException("Repository root could not be located."); } - [GeneratedRegex("#define MyAppVersion \"1\\.7\\.9\"", RegexOptions.CultureInvariant)] + [GeneratedRegex("#define MyAppVersion \"1\\.7\\.10\"", RegexOptions.CultureInvariant)] private static partial Regex MyAppVersionRegex(); } } diff --git a/Tests/ThreadPilot.Core.Tests/PersistentRuleAutoApplyServiceTests.cs b/Tests/ThreadPilot.Core.Tests/PersistentRuleAutoApplyServiceTests.cs index f8b7920a..2b93f88c 100644 --- a/Tests/ThreadPilot.Core.Tests/PersistentRuleAutoApplyServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PersistentRuleAutoApplyServiceTests.cs @@ -542,7 +542,7 @@ public async Task PathRetry_WhenLifetimeEnds_DoesNotRefreshOrApply(string reason }).Returns(Task.CompletedTask); using var lifetime = new CancellationTokenSource(); var service = CreateService([rule], engine.Object, processService: processes.Object, enhancedLogger: diagnostics.Object); - var pending = service.ApplyForProcessStartAsync(process, lifetime.Token); + var pending = service.ApplyForProcessStartAsync(process, cancellationToken: lifetime.Token); await scheduled.Task.WaitAsync(TimeSpan.FromSeconds(5)); // A duplicate discovery must not start another retry loop. diff --git a/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs index 6c340b87..c5f3bc29 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs @@ -41,12 +41,12 @@ public async Task Start_AppliesRulesToAlreadyRunningProcesses_AndRecoveryReevalu autoApply.Verify( x => x.ApplyForDiscoveredProcessesAsync( It.Is>(ps => ps.Any(p => p.ProcessId == 41)), - It.IsAny()), Times.Once); + It.IsAny>(), It.IsAny()), Times.Once); autoApply.Verify(x => x.MarkProcessExited(41), Times.Once); var applied = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); autoApply.Setup(x => x.ApplyForDiscoveredProcessesAsync( It.Is>(ps => ps.Any(p => p.ProcessId == 42)), - It.IsAny())) + It.IsAny>(), It.IsAny())) .Callback(() => applied.TrySetResult()) .ReturnsAsync(Array.Empty()); monitor.RunningProcesses.Add(new ProcessModel { ProcessId = 42, Name = "missed-during-sleep" }); @@ -180,6 +180,41 @@ public async Task SetAutomationMonitoringEnabledAsync_StartsAndPersistsEnabledSt Assert.True(settings.EnableAutomationMonitoring); } + [Fact] + public async Task SetAutomationMonitoringEnabledAsync_LateEnableKeepsDisabledPreference() + { + var monitor = new FakeProcessMonitorService(); + var settings = new ApplicationSettingsModel { EnableAutomationMonitoring = true }; + var scanEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finishScan = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + var autoApply = CreateAutoApplyService(); + autoApply.Setup(x => x.ApplyForDiscoveredProcessesAsync( + It.IsAny>(), It.IsAny>(), + It.IsAny())).Returns(() => + { + scanEntered.TrySetResult(); + return finishScan.Task; + }); + using var manager = CreateService(monitor, CreateAssociationService(new()), + CreatePowerPlanService(), CreateNotificationService(), CreateProcessService(), + CreateCoreMaskService(), CreateAffinityApplyService(), autoApply, settings: settings); + var starting = manager.SetAutomationMonitoringEnabledAsync(true); + try + { + await scanEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + await manager.SetAutomationMonitoringEnabledAsync(false); + Assert.False(settings.EnableAutomationMonitoring); + } + finally + { + finishScan.TrySetResult(Array.Empty()); + await starting.WaitAsync(TimeSpan.FromSeconds(5)); + } + + Assert.False(manager.IsRunning); + Assert.False(settings.EnableAutomationMonitoring); + } + [Fact] public async Task StartAsync_SelectsHighestPriorityAssociation() { @@ -245,7 +280,7 @@ public async Task PersistentRuleAndAssociation_OrderIsObservable() }; var autoApply = CreateAutoApplyService(); autoApply - .Setup(x => x.ApplyForProcessStartAsync(process, It.IsAny())) + .Setup(x => x.ApplyForProcessStartAsync(process, It.IsAny>(), It.IsAny())) .ReturnsAsync(() => { process.Priority = ProcessPriorityClass.High; @@ -287,7 +322,7 @@ public async Task PersistentRuleAndAssociation_OrderIsObservable() await Task.Delay(50); Assert.Equal(ProcessPriorityClass.Normal, process.Priority); - autoApply.Verify(x => x.ApplyForProcessStartAsync(process, It.IsAny()), Times.Once); + autoApply.Verify(x => x.ApplyForProcessStartAsync(process, It.IsAny>(), It.IsAny()), Times.Once); processService.Verify(x => x.SetProcessPriority(process, ProcessPriorityClass.Normal, ProcessPriorityWriteSource.PowerPlanAssociation), Times.Once); } @@ -468,8 +503,171 @@ public async Task StopAsync_RestoresDefaultPowerPlan_WhenConfigured() coreMaskService.Verify(x => x.UnregisterMaskApplication(21), Times.Once); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Recovery_WhenThePidWasReused_AppliesTheNewProcessAssociation(bool sameExecutable) + { + var started = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); + var first = new ProcessModel { ProcessId = 42, Name = "first", StartTimeUtc = started }; + var replacement = new ProcessModel + { + ProcessId = 42, + Name = sameExecutable ? "first" : "replacement", + StartTimeUtc = started.AddMinutes(1), + }; + var monitor = new FakeProcessMonitorService { RunningProcesses = { first } }; + var config = new ProcessMonitorConfiguration + { + PowerPlanChangeDelayMs = 0, + Associations = + { + new ProcessPowerPlanAssociation("first", "plan-first", "First") { CoreMaskId = "mask-first" }, + new ProcessPowerPlanAssociation("replacement", "plan-replacement", "Replacement") { CoreMaskId = "mask-replacement" }, + }, + }; + var masks = CreateCoreMaskService(); + masks.SetupGet(x => x.AvailableMasks).Returns(new ObservableCollection + { + new() { Id = "mask-first", Name = "First", BoolMask = new ObservableCollection { true, false } }, + new() { Id = "mask-replacement", Name = "Replacement", BoolMask = new ObservableCollection { false, true } }, + }); + masks.Setup(x => x.RegisterMaskApplication(42, It.IsAny())); + var processes = CreateProcessService(); + processes.Setup(x => x.TrackAppliedMask(42, It.IsAny())); + var affinity = CreateAffinityApplyService(); + using var manager = CreateService(monitor, CreateAssociationService(config), + CreatePowerPlanService(), CreateNotificationService(), processes, masks, affinity); + + await manager.StartAsync(); + affinity.Verify(x => x.ApplyAsync(first, 1), Times.Once); + monitor.RunningProcesses.Clear(); + monitor.RunningProcesses.Add(replacement); + monitor.RaiseSnapshotRefreshed(); + + affinity.Verify(x => x.ApplyAsync(replacement, sameExecutable ? 1 : 2), Times.Once); + } + + [Theory] + [InlineData(ProcessPriorityClass.Normal)] + [InlineData(ProcessPriorityClass.BelowNormal)] + public async Task Recovery_PreservesAssociationAndManualPriorityWhileReapplyingOtherRuleFields( + ProcessPriorityClass priorityBeforeRecovery) + { + var process = new ProcessModel { ProcessId = 42, Name = "game", Priority = ProcessPriorityClass.Normal }; + var monitor = new FakeProcessMonitorService { RunningProcesses = { process } }; + var configuration = new ProcessMonitorConfiguration + { + Associations = + { + new ProcessPowerPlanAssociation("game", "plan-game", "Game") + { + ProcessPriority = nameof(ProcessPriorityClass.Normal), + }, + }, + }; + var settings = new Mock(); + settings.SetupGet(x => x.Settings).Returns(new ApplicationSettingsModel { ApplyPersistentRulesOnProcessStart = true }); + var store = new Mock(); + store.Setup(x => x.LoadAsync()).ReturnsAsync( + [ + new PersistentProcessRule + { + ProcessName = "game", + IsEnabled = true, + Priority = ProcessPriorityClass.High, + ApplyPriorityOnStart = true, + MemoryPriority = ProcessMemoryPriority.Low, + ApplyMemoryPriorityOnStart = true, + }, + ]); + var processes = CreateProcessService(); + processes.Setup(x => x.RefreshProcessInfo(process)).Returns(Task.CompletedTask); + processes.Setup(x => x.TrackPriorityChange(42, It.IsAny())); + processes.Setup(x => x.SetProcessPriority(process, It.IsAny(), It.IsAny())) + .Callback((ProcessModel target, ProcessPriorityClass priority, ProcessPriorityWriteSource _) => target.Priority = priority) + .Returns(Task.CompletedTask); + var actualMemoryPriority = ProcessMemoryPriority.Normal; + var memory = new Mock(); + memory.Setup(x => x.SetMemoryPriorityAsync(process, It.IsAny())) + .Callback((ProcessModel _, ProcessMemoryPriority priority) => actualMemoryPriority = priority) + .ReturnsAsync(ProcessOperationResult.Succeeded("Memory priority applied", string.Empty)); + var affinity = CreateAffinityApplyService(); + var matcher = new PersistentProcessRuleMatcher(); + var engine = new PersistentRulesEngine(store.Object, matcher, affinity.Object, processes.Object, + memory.Object, NullLogger.Instance); + var autoApply = new PersistentRuleAutoApplyService(store.Object, matcher, engine, settings.Object, + NullLogger.Instance); + using var manager = new ProcessMonitorManagerService( + monitor, CreateAssociationService(configuration).Object, CreatePowerPlanService().Object, + CreateNotificationService().Object, settings.Object, processes.Object, CreateCoreMaskService().Object, + affinity.Object, autoApply, new PowerPlanTransitionGate(TimeSpan.FromSeconds(2), () => DateTimeOffset.UtcNow), + NullLogger.Instance, CreateEnhancedLogger().Object); + + await manager.StartAsync(); + Assert.Equal(ProcessPriorityClass.Normal, process.Priority); + Assert.Equal(ProcessMemoryPriority.Low, actualMemoryPriority); + + process.Priority = priorityBeforeRecovery; + actualMemoryPriority = ProcessMemoryPriority.Normal; + monitor.RaiseSnapshotRefreshed(); + + Assert.Equal(ProcessMemoryPriority.Low, actualMemoryPriority); + Assert.Equal(priorityBeforeRecovery, process.Priority); + } + [Fact] - public async Task ProcessStarted_AppliesConfiguredCoreMaskForMatchingProcess() + public async Task StartAsync_WhenAnAssociatedProcessStartsDuringTheScan_KeepsItsPowerPlan() + { + var monitor = new FakeProcessMonitorService + { + RunningProcesses = { new ProcessModel { ProcessId = 80, Name = "unrelated" } }, + }; + var config = new ProcessMonitorConfiguration + { + DefaultPowerPlanGuid = "plan-default", + PowerPlanChangeDelayMs = 0, + Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") }, + }; + var activePlan = "balanced"; + var power = CreatePowerPlanService(); + power.Setup(x => x.GetActivePowerPlan()) + .ReturnsAsync(() => new PowerPlanModel { Guid = activePlan, Name = activePlan }); + power.Setup(x => x.SetActivePowerPlanByGuidAsync(It.IsAny(), It.IsAny())) + .Callback((string id, bool _) => activePlan = id) + .ReturnsAsync(true); + var scanEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finishScan = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + var autoApply = CreateAutoApplyService(); + autoApply.Setup(x => x.ApplyForDiscoveredProcessesAsync( + It.IsAny>(), It.IsAny>(), It.IsAny())).Returns(() => + { + scanEntered.TrySetResult(); + return finishScan.Task; + }); + using var manager = CreateService(monitor, CreateAssociationService(config), power, + CreateNotificationService(), CreateProcessService(), CreateCoreMaskService(), CreateAffinityApplyService(), + autoApply); + var evaluation = manager.StartAsync(); + try + { + await scanEntered.Task.WaitAsync(TimeSpan.FromSeconds(5)); + monitor.RaiseProcessStarted(new ProcessModel { ProcessId = 42, Name = "game" }); + Assert.Equal("plan-game", activePlan); + } + finally + { + finishScan.TrySetResult(Array.Empty()); + await evaluation.WaitAsync(TimeSpan.FromSeconds(5)); + } + + Assert.Equal("plan-game", activePlan); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DiscoveredOrStartedProcess_AppliesConfiguredCoreMaskOnce(bool alreadyRunning) { var process = new ProcessModel { ProcessId = 31, Name = "game" }; var processMonitor = new FakeProcessMonitorService(); @@ -513,9 +711,16 @@ public async Task ProcessStarted_AppliesConfiguredCoreMaskForMatchingProcess() coreMaskService, affinityApplyService); + if (alreadyRunning) + { + processMonitor.RunningProcesses.Add(process); + } + await manager.StartAsync(); + affinityApplyService.Verify(x => x.ApplyAsync(process, 1), alreadyRunning ? Times.Once() : Times.Never()); processMonitor.RaiseProcessStarted(process); - await Task.Delay(100); + processMonitor.RaiseProcessStarted(process); + await manager.EvaluateCurrentProcessesAsync(); affinityApplyService.Verify(x => x.ApplyAsync(process, 1), Times.Once); processService.Verify(x => x.TrackAppliedMask(31, "mask-game"), Times.Once); @@ -552,10 +757,10 @@ public async Task ProcessStarted_AppliesPersistentRulesThroughCoordinator() autoApplyService.Verify( x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), - It.IsAny()), + It.IsAny>(), It.IsAny()), Times.Once); autoApplyService.Verify( - x => x.ApplyForProcessStartAsync(process, It.IsAny()), + x => x.ApplyForProcessStartAsync(process, It.IsAny>(), It.IsAny()), Times.Once); } @@ -580,7 +785,7 @@ public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleSnapshotApplyC autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), - It.IsAny())) + It.IsAny>(), It.IsAny())) .ThrowsAsync(new OperationCanceledException()); var logger = new CapturingLogger(); var manager = CreateService( @@ -616,7 +821,7 @@ public async Task ProcessStarted_WhenPersistentRuleAutoApplyCancels_DoesNotLogWa autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, - It.IsAny())) + It.IsAny>(), It.IsAny())) .ThrowsAsync(new OperationCanceledException()); var logger = new CapturingLogger(); var manager = CreateService( @@ -658,7 +863,7 @@ public async Task EvaluateCurrentProcessesAsync_WhenPersistentRuleAutoApplyThrow autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), - It.IsAny())) + It.IsAny>(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("auto apply failed")); var logger = new CapturingLogger(); var manager = CreateService( @@ -697,7 +902,7 @@ public async Task ProcessStarted_WhenPersistentRuleAutoApplyThrows_LogsWarningWi autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, - It.IsAny())) + It.IsAny>(), It.IsAny())) .ThrowsAsync(new InvalidOperationException("auto apply failed")); var logger = new CapturingLogger(); var manager = CreateService( @@ -737,7 +942,7 @@ public async Task ProcessStarted_WhenPersistentRuleAutoApplySucceeds_LogsEnhance autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, - It.IsAny())) + It.IsAny>(), It.IsAny())) .ReturnsAsync(new[] { new PersistentRuleAutoApplyResult @@ -790,7 +995,7 @@ public async Task ProcessStarted_WhenPersistentRuleAutoApplyReturnsFailure_DoesN autoApplyService .Setup(x => x.ApplyForProcessStartAsync( process, - It.IsAny())) + It.IsAny>(), It.IsAny())) .ReturnsAsync(new[] { new PersistentRuleAutoApplyResult @@ -950,8 +1155,8 @@ public async Task StopAsync_CancelsUnassociatedAutomationAndRestartGetsFreshLife var automation = CreateAutoApplyService(); var tokens = new List(); automation.Setup(x => x.ApplyForProcessStartAsync( - It.IsAny(), It.IsAny())) - .Callback((_, token) => tokens.Add(token)) + It.IsAny(), It.IsAny>(), It.IsAny())) + .Callback((ProcessModel _, Func _, CancellationToken token) => tokens.Add(token)) .ReturnsAsync(Array.Empty()); using var manager = CreateService( monitor, @@ -998,8 +1203,8 @@ private static ProcessMonitorManagerService CreateService( var settingsService = new Mock(MockBehavior.Loose); settingsService.SetupGet(x => x.Settings).Returns(() => persistedSettings); settingsService - .Setup(x => x.UpdateSettingsAsync(It.IsAny())) - .Callback(updated => persistedSettings.CopyFrom(updated)) + .Setup(x => x.EditSettingsAsync(It.IsAny>())) + .Callback>(edit => edit(persistedSettings)) .Returns(Task.CompletedTask); return new ProcessMonitorManagerService( @@ -1094,12 +1299,12 @@ private static Mock CreateAutoApplyService() autoApplyService .Setup(x => x.ApplyForDiscoveredProcessesAsync( It.IsAny>(), - It.IsAny())) + It.IsAny>(), It.IsAny())) .ReturnsAsync(Array.Empty()); autoApplyService .Setup(x => x.ApplyForProcessStartAsync( It.IsAny(), - It.IsAny())) + It.IsAny>(), It.IsAny())) .ReturnsAsync(Array.Empty()); autoApplyService.Setup(x => x.MarkProcessExited(It.IsAny())); return autoApplyService; diff --git a/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationServiceTests.cs new file mode 100644 index 00000000..c7b94aac --- /dev/null +++ b/Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationServiceTests.cs @@ -0,0 +1,45 @@ +namespace ThreadPilot.Core.Tests +{ + using ThreadPilot.Models; + using ThreadPilot.Services; + + public sealed class ProcessPowerPlanAssociationServiceTests + { + [Fact] + public async Task FailedWrite_PreservesPublishedConfigurationAndReturnsFailure() + { + var directory = Directory.CreateTempSubdirectory("threadpilot-association-"); + var file = Path.Combine(directory.FullName, "ProcessPowerPlanAssociations.json"); + Directory.CreateDirectory(file); + try + { + var service = new ProcessPowerPlanAssociationService(directory.FullName); + var events = new List(); + service.ConfigurationChanged += (_, args) => events.Add(args.ChangeType); + var proposed = new ProcessMonitorConfiguration { DefaultPowerPlanGuid = "imported" }; + var association = new ProcessPowerPlanAssociation("game", "fast", "Fast"); + + Assert.False(await service.SetDefaultPowerPlanAsync("balanced", "Balanced")); + Assert.False(await service.AddAssociationAsync(association)); + Assert.False(await service.SaveMonitoringSettingsAsync(false, 321)); + Assert.False(await service.ReplaceConfigurationAsync(proposed)); + Assert.Empty(service.Configuration.Associations); + Assert.Empty(service.Configuration.DefaultPowerPlanGuid); + Assert.NotEqual(321, service.Configuration.PowerPlanChangeDelayMs); + Assert.Equal(new[] { "SaveError", "SaveError", "SaveError", "SaveError" }, events); + + Directory.Delete(file); + Assert.True(await service.SetDefaultPowerPlanAsync("balanced", "Balanced")); + Assert.True(await service.AddAssociationAsync(association)); + var reloaded = new ProcessPowerPlanAssociationService(directory.FullName); + Assert.True(await reloaded.LoadConfigurationAsync()); + Assert.Equal("balanced", reloaded.Configuration.DefaultPowerPlanGuid); + Assert.Equal("game", Assert.Single(reloaded.Configuration.Associations).ExecutableName); + } + finally + { + directory.Delete(recursive: true); + } + } + } +} diff --git a/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs index 61b517a5..d1d516d4 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessRuleCreationServiceTests.cs @@ -5,6 +5,7 @@ namespace ThreadPilot.Core.Tests { using System.Diagnostics; using Microsoft.Extensions.Logging.Abstractions; + using Moq; using ThreadPilot.Models; using ThreadPilot.Services; @@ -410,6 +411,94 @@ public async Task UpdateRule_SaveThenReload_PreservesUpdatedValues() } } + [Fact] + public async Task SaveRuleAsync_WhenRulesAreTemporarilyUnreadable_PreservesExistingRules() + { + var file = CreateTemporaryFilePath(); + try + { + var existing = new PersistentProcessRule { Id = "saved-before-lock", ProcessName = "first" }; + await new PersistentProcessRuleJsonStore(() => file).SaveAsync([existing]); + + using var fileLock = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.None); + var store = new PersistentProcessRuleJsonStore(() => file, copyFile: (source, backup) => + { + try + { + File.Copy(source, backup); + } + finally + { + // Release the real Windows lock after the first preservation attempt, + // which is made from inside the failed read path. + fileLock.Dispose(); + } + }); + var service = CreateService(store); + var process = CreateProcess(); + var payload = new ProcessRuleCreationPayload { Priority = ProcessPriorityClass.AboveNormal }; + await Assert.ThrowsAsync(() => service.SaveRuleAsync(process, payload)); + Assert.Equal(existing.Id, Assert.Single(await new PersistentProcessRuleJsonStore(() => file).LoadAsync()).Id); + + var result = await service.SaveRuleAsync(process, payload); + var saved = await new PersistentProcessRuleJsonStore(() => file).LoadAsync(); + + Assert.Contains(saved, rule => rule.Id == existing.Id); + Assert.True(result.Success); + Assert.Equal(2, saved.Count); + } + finally + { + DeleteTemporaryDirectory(file); + } + } + + [Fact] + public async Task ConcurrentUpdates_PersistBothRules() + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + var file = CreateTemporaryFilePath(); + try + { + var first = new PersistentProcessRule { Id = "first", ProcessName = "first" }; + var second = new PersistentProcessRule { Id = "second", ProcessName = "second" }; + var store = new PersistentProcessRuleJsonStore(() => file); + await store.SaveAsync([first, second]); + var editStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var firstEdit = ((IPersistentProcessRuleStore)store).EditAsync( + async draft => + { + draft[0] = first with { Priority = ProcessPriorityClass.AboveNormal }; + editStarted.SetResult(); + await release.Task.WaitAsync(timeout.Token); + return true; + }, + timeout.Token); + await editStarted.Task.WaitAsync(timeout.Token); + var secondEdit = CreateService(store).UpdateRuleAsync( + second with { Priority = ProcessPriorityClass.BelowNormal }, timeout.Token); + try + { + Assert.False(secondEdit.IsCompleted); + } + finally + { + release.SetResult(); + } + + await firstEdit; + Assert.True((await secondEdit).Success); + var saved = await new PersistentProcessRuleJsonStore(() => file).LoadAsync(); + Assert.Equal(ProcessPriorityClass.AboveNormal, saved.Single(rule => rule.Id == "first").Priority); + Assert.Equal(ProcessPriorityClass.BelowNormal, saved.Single(rule => rule.Id == "second").Priority); + } + finally + { + DeleteTemporaryDirectory(file); + } + } + private static ProcessRuleCreationService CreateService( IPersistentProcessRuleStore store, ICpuTopologyProvider? topologyProvider = null) => diff --git a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs index beade96f..a34a6544 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessViewModelAffinityTests.cs @@ -103,7 +103,7 @@ public void PollingInterval_InitializesAndUpdatesFromSettings() Assert.Equal(2345, timer.Interval); - var updated = (ApplicationSettingsModel)initial.Clone(); + var updated = initial.Clone(); updated.PollingIntervalMs = 6789; settingsService.Raise( service => service.SettingsChanged += null, @@ -123,7 +123,7 @@ public void SelectingProcessInCpuSetsMode_SynchronizesCheckboxesFromWindowsCpuSe It.IsAny(), CpuAssignmentMode.CpuSets)) .ReturnsAsync([0]); var gameModeService = new Mock(MockBehavior.Loose); - var settings = new ApplicationSettingsModel { DefaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask }; + var settings = new ApplicationSettingsModel { DefaultCpuAssignmentMode = CpuAssignmentMode.AffinityMask }; var settingsService = new Mock(MockBehavior.Loose); settingsService.SetupGet(service => service.Settings).Returns(settings); using var viewModel = CreateViewModel( diff --git a/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs b/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs index 4411d181..ff74866b 100644 --- a/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs @@ -139,8 +139,13 @@ public async Task SaveSettingsCommand_PersistsSelectedLanguage() var harness = new Harness(); ApplicationSettingsModel? savedSettings = null; harness.SettingsService - .Setup(service => service.UpdateSettingsAsync(It.IsAny())) - .Callback(settings => savedSettings = (ApplicationSettingsModel)settings.Clone()) + .Setup(service => service.EditSettingsAsync(It.IsAny>())) + .Callback>(edit => + { + var draft = harness.PersistedSettings.Clone(); + edit(draft); + savedSettings = draft; + }) .Returns(Task.CompletedTask); var viewModel = harness.CreateViewModel(); viewModel.Settings.Language = "zh-CN"; @@ -242,20 +247,24 @@ public async Task SaveSettingsCommand_MergesPendingEditWithExternalUpdate() var harness = new Harness(); ApplicationSettingsModel? savedSettings = null; harness.SettingsService - .Setup(service => service.UpdateSettingsAsync(It.IsAny())) - .Callback(settings => savedSettings = (ApplicationSettingsModel)settings.Clone()) + .Setup(service => service.EditSettingsAsync(It.IsAny>())) + .Callback>(edit => + { + var draft = harness.PersistedSettings.Clone(); + edit(draft); + savedSettings = draft; + }) .Returns(Task.CompletedTask); var viewModel = harness.CreateViewModel(); viewModel.Settings.Language = "it-IT"; - var externalUpdate = (ApplicationSettingsModel)harness.PersistedSettings.Clone(); - externalUpdate.LastUpdateCheckUtc = DateTimeOffset.UtcNow; - - viewModel.ApplyPersistedSettings(externalUpdate); + // The background edit reached the store before the dispatcher delivered its event. + var checkTime = DateTimeOffset.UtcNow; + harness.PersistedSettings.LastUpdateCheckUtc = checkTime; await ((IAsyncRelayCommand)viewModel.SaveSettingsCommand).ExecuteAsync(null); Assert.NotNull(savedSettings); Assert.Equal("it-IT", savedSettings.Language); - Assert.Equal(externalUpdate.LastUpdateCheckUtc, savedSettings.LastUpdateCheckUtc); + Assert.Equal(checkTime, savedSettings.LastUpdateCheckUtc); } [Fact] @@ -263,7 +272,8 @@ public async Task NavigationPrompt_SavePersistsPendingSettingsBeforeNavigating() { var harness = new Harness(); harness.SettingsService - .Setup(service => service.UpdateSettingsAsync(It.IsAny())) + .Setup(service => service.EditSettingsAsync(It.IsAny>())) + .Callback>(edit => edit(harness.PersistedSettings)) .Returns(Task.CompletedTask); var viewModel = harness.CreateViewModel(); viewModel.Settings.Language = "it-IT"; @@ -275,9 +285,7 @@ public async Task NavigationPrompt_SavePersistsPendingSettingsBeforeNavigating() Assert.True(canNavigate); Assert.False(viewModel.HasUnsavedChanges); - harness.SettingsService.Verify( - service => service.UpdateSettingsAsync(It.Is(settings => settings.Language == "it-IT")), - Times.Once); + Assert.Equal("it-IT", harness.PersistedSettings.Language); } [Fact] diff --git a/Tests/ThreadPilot.Core.Tests/SmartNotificationQuietHoursTests.cs b/Tests/ThreadPilot.Core.Tests/SmartNotificationQuietHoursTests.cs deleted file mode 100644 index f93cef9b..00000000 --- a/Tests/ThreadPilot.Core.Tests/SmartNotificationQuietHoursTests.cs +++ /dev/null @@ -1,46 +0,0 @@ -namespace ThreadPilot.Core.Tests -{ - using ThreadPilot.Services; - - public sealed class SmartNotificationQuietHoursTests - { - [Theory] - [InlineData(23, 0, 22, 8, true)] - [InlineData(2, 0, 22, 8, true)] - [InlineData(7, 59, 22, 8, true)] - [InlineData(22, 0, 22, 8, true)] - [InlineData(8, 0, 22, 8, true)] - [InlineData(12, 0, 22, 8, false)] - [InlineData(21, 59, 22, 8, false)] - [InlineData(9, 0, 22, 8, false)] - [InlineData(12, 0, 9, 17, true)] - [InlineData(9, 0, 9, 17, true)] - [InlineData(17, 0, 9, 17, true)] - [InlineData(8, 59, 9, 17, false)] - [InlineData(17, 1, 9, 17, false)] - [InlineData(23, 0, 9, 17, false)] - public void IsWithinQuietHours_HandlesOvernightAndSameDayWindows( - int hour, - int minute, - int startHour, - int endHour, - bool expected) - { - var actual = SmartNotificationService.IsWithinQuietHours( - new TimeSpan(hour, minute, 0), - TimeSpan.FromHours(startHour), - TimeSpan.FromHours(endHour)); - - Assert.Equal(expected, actual); - } - - [Fact] - public void IsWithinQuietHours_ZeroLengthWindow_IsNeverActive() - { - Assert.False(SmartNotificationService.IsWithinQuietHours( - TimeSpan.FromHours(10), - TimeSpan.FromHours(10), - TimeSpan.FromHours(10))); - } - } -} diff --git a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs index aefb045a..8626f209 100644 --- a/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SystemTweaksGameBoostTests.cs @@ -16,8 +16,13 @@ public async Task Load_ShowsSettingsAndDecision_ToggleSavesAtOnce() ApplicationSettingsModel? saved = null; var settingsService = new Mock(); settingsService.SetupGet(s => s.Settings).Returns(settings); - settingsService.Setup(s => s.UpdateSettingsAsync(It.IsAny())) - .Callback((ApplicationSettingsModel model) => saved = model) + settingsService.Setup(s => s.EditSettingsAsync(It.IsAny>())) + .Callback((Action edit) => + { + var updated = settings.Clone(); + edit(updated); + saved = updated; + }) .Returns(Task.CompletedTask); var session = new Mock(); session.Setup(s => s.GetDecisionAsync()).ReturnsAsync(GameBoostDecision.None); diff --git a/Tests/ThreadPilot.Core.Tests/SystemTweaksStartupAndStyleTests.cs b/Tests/ThreadPilot.Core.Tests/SystemTweaksStartupAndStyleTests.cs index 00e87691..29062518 100644 --- a/Tests/ThreadPilot.Core.Tests/SystemTweaksStartupAndStyleTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SystemTweaksStartupAndStyleTests.cs @@ -1,9 +1,41 @@ namespace ThreadPilot.Core.Tests { using System.Xml.Linq; + using ThreadPilot.Services; public sealed class SystemTweaksStartupAndStyleTests { + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task FailedDeviceTweak_RestoresEarlierWrites(bool secondDeviceDisappears) + { + SystemTweaksService.RegistryTarget[] targets = + [ + new("first", "value", 2, Microsoft.Win32.RegistryValueKind.DWord), + new("second", "value", 3, Microsoft.Win32.RegistryValueKind.DWord), + ]; + var values = targets.ToDictionary(target => target.Path, target => target.Value); + + await Assert.ThrowsAsync(() => SystemTweaksService.WriteDriverRegistryTargetsAsync( + targets, + _ => 1, + (target, value) => + { + if (secondDeviceDisappears && target.Path == "second") + { + throw new IOException("Device unavailable"); + } + + values[target.Path] = value; + }, + () => Task.FromResult(false), + Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance)); + + Assert.Equal(2, values["first"]); + Assert.Equal(3, values["second"]); + } + [Fact] public void Startup_LoadsPersistedTweakStateBeforePageNavigation() { diff --git a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj index 8a0f4e6b..aa95657f 100644 --- a/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj +++ b/Tests/ThreadPilot.Core.Tests/ThreadPilot.Core.Tests.csproj @@ -21,6 +21,10 @@ + + + + diff --git a/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs b/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs index 6bdeadf7..b219059c 100644 --- a/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/UpdateServiceTests.cs @@ -59,7 +59,7 @@ public async Task GitHubUpdateChecker_ExcludesPrereleasesByDefault() public async Task CheckForUpdatesAsync_StartupChecksOnEveryLaunch() { var harness = new Harness(); - harness.Settings.LastUpdateCheckUtc = harness.Clock.UtcNow.AddDays(-2); + harness.Settings.LastUpdateCheckUtc = harness.Clock.GetUtcNow().AddDays(-2); var result = await harness.Service.CheckForUpdatesAsync(new UpdateCheckRequest(UpdateCheckTrigger.Startup)); @@ -76,7 +76,7 @@ public async Task CheckForUpdatesAsync_ManualFindsNewerStableRelease() Assert.True(result.IsUpdateAvailable); Assert.Equal("1.4.0", result.Release?.Version.ToString()); - Assert.Equal(harness.Clock.UtcNow, harness.SavedSettings?.LastUpdateCheckUtc); + Assert.Equal(harness.Clock.GetUtcNow(), harness.SavedSettings?.LastUpdateCheckUtc); } [Fact] @@ -327,13 +327,13 @@ public Harness() { this.TempDirectory = Directory.CreateTempSubdirectory("ThreadPilotUpdateTest").FullName; var settingsService = new Mock(); - settingsService.SetupGet(service => service.Settings).Returns(() => (ApplicationSettingsModel)this.Settings.Clone()); + settingsService.SetupGet(service => service.Settings).Returns(() => this.Settings.Clone()); settingsService - .Setup(service => service.UpdateSettingsAsync(It.IsAny())) - .Callback(settings => + .Setup(service => service.EditSettingsAsync(It.IsAny>())) + .Callback>(edit => { - this.SavedSettings = (ApplicationSettingsModel)settings.Clone(); - this.Settings.CopyFrom(settings); + edit(this.Settings); + this.SavedSettings = this.Settings.Clone(); }) .Returns(Task.CompletedTask); @@ -361,9 +361,9 @@ public Harness() } } - private sealed class FakeClock : IUpdateClock + private sealed class FakeClock : TimeProvider { - public DateTimeOffset UtcNow { get; } = new(2026, 6, 7, 12, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => new(2026, 6, 7, 12, 0, 0, TimeSpan.Zero); } private sealed class FakeGitHubReleaseClient : IGitHubReleaseClient @@ -377,11 +377,6 @@ public FakeGitHubReleaseClient(string releasesJson) this.releasesJson = releasesJson; } - public Task GetLatestReleaseJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) - { - throw new NotSupportedException(); - } - public Task GetReleasesJsonAsync(string owner, string repo, CancellationToken cancellationToken = default) { this.RequestedReleases = true; diff --git a/ThreadPilot.csproj b/ThreadPilot.csproj index 66863be6..7f1edc2a 100644 --- a/ThreadPilot.csproj +++ b/ThreadPilot.csproj @@ -23,10 +23,10 @@ copies text, and an elevated process should not deserialize data another program can put there. --> false CS1998;CS0067;CS0414;WFAC010;IL3000;MVVMTK0034 - 1.7.9 - 1.7.9.0 - 1.7.9.0 - 1.7.9 + 1.7.10 + 1.7.10.0 + 1.7.10.0 + 1.7.10 diff --git a/ViewModels/ProcessPowerPlanAssociationViewModel.cs b/ViewModels/ProcessPowerPlanAssociationViewModel.cs index 6a13b0d5..e0cab954 100644 --- a/ViewModels/ProcessPowerPlanAssociationViewModel.cs +++ b/ViewModels/ProcessPowerPlanAssociationViewModel.cs @@ -3,6 +3,7 @@ namespace ThreadPilot.ViewModels using System; using System.Collections.Generic; using System.Collections.ObjectModel; + using System.ComponentModel; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -453,6 +454,11 @@ private static string DescribeCores(PersistentProcessRule rule) protected override void OnDispose() { + foreach (var association in this.Associations) + { + association.PropertyChanged -= this.OnAssociationPropertyChanged; + } + this.associationService.ConfigurationChanged -= this.OnConfigurationChanged; this.monitorManagerService.ServiceStatusChanged -= this.OnServiceStatusChanged; this.monitorManagerService.ProcessPowerPlanChanged -= this.OnProcessPowerPlanChanged; @@ -472,6 +478,24 @@ public override async Task InitializeAsync() this.UpdateServiceStatus(); } + partial void OnAssociationsChanged( + ObservableCollection? oldValue, + ObservableCollection newValue) + { + if (oldValue != null) + { + foreach (var association in oldValue) + { + association.PropertyChanged -= this.OnAssociationPropertyChanged; + } + } + + foreach (var association in newValue) + { + association.PropertyChanged += this.OnAssociationPropertyChanged; + } + } + partial void OnSelectedAssociationChanged(ProcessPowerPlanAssociation? value) { if (value == null) @@ -489,9 +513,7 @@ public async Task LoadDataAsync() { this.SetStatus("Loading data..."); - // Load associations - var associationsData = await this.associationService.GetAssociationsAsync(); - this.Associations = new ObservableCollection(associationsData); + await this.RefreshAssociationsAsync(); // Load power plans var powerPlans = await this.powerPlanService.GetPowerPlansAsync(); @@ -569,7 +591,7 @@ public async Task AddAssociationAsync() } else { - this.SetStatus("Failed to add rule - it may already exist", false); + this.ShowConfigurationError("Failed to add rule - it may already exist"); } } catch (Exception ex) @@ -597,9 +619,10 @@ public async Task UpdateAssociationAsync() this.SetStatus("Updating rule..."); - this.ApplyEditorToAssociation(this.SelectedAssociation); + var updated = this.SelectedAssociation.CreateSnapshot(); + this.ApplyEditorToAssociation(updated); - var success = await this.associationService.UpdateAssociationAsync(this.SelectedAssociation); + var success = await this.associationService.UpdateAssociationAsync(updated); if (success) { await this.LoadDataAsync(); @@ -607,7 +630,7 @@ public async Task UpdateAssociationAsync() } else { - this.SetStatus("Failed to update rule", false); + this.ShowConfigurationError("Failed to update rule"); } } catch (Exception ex) @@ -616,6 +639,42 @@ public async Task UpdateAssociationAsync() } } + private void OnAssociationPropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(ProcessPowerPlanAssociation.IsEnabled) && sender is ProcessPowerPlanAssociation association) + { + TaskSafety.FireAndForget(this.SaveAssociationEnabledAsync(association), ex => + this.Logger.LogError(ex, "Failed to update power plan association {AssociationId}", association.Id)); + } + } + + private async Task SaveAssociationEnabledAsync(ProcessPowerPlanAssociation association) + { + this.SetStatus("Updating rule..."); + var updated = association.CreateSnapshot(); + updated.UpdatedAt = DateTime.UtcNow; + if (!await this.associationService.UpdateAssociationAsync(updated)) + { + await this.RefreshAssociationsAsync(); + this.ShowConfigurationError("Failed to update rule"); + return; + } + + this.SetStatus("Rule updated successfully.", false); + } + + private async Task RefreshAssociationsAsync() + { + var savedAssociations = await this.associationService.GetAssociationsAsync(); + this.Associations = new ObservableCollection(savedAssociations); + } + + private void ShowConfigurationError(string message) + { + this.SetCriticalStatus(message); + this.SetError(message); + } + [RelayCommand] public async Task RemoveAssociationAsync() { @@ -638,7 +697,7 @@ public async Task RemoveAssociationAsync() } else { - this.SetStatus("Failed to remove rule", false); + this.ShowConfigurationError("Failed to remove rule"); } } catch (Exception ex) @@ -667,7 +726,7 @@ public async Task SetDefaultPowerPlanAsync() } else { - this.SetStatus("Failed to set default power plan", false); + this.ShowConfigurationError("Failed to set default power plan"); } } catch (Exception ex) @@ -718,19 +777,15 @@ public async Task SaveConfigurationAsync() { this.SetStatus("Saving configuration..."); - // Update configuration with current settings - var config = this.associationService.Configuration; - config.PreventDuplicatePowerPlanChanges = this.PreventDuplicatePowerPlanChanges; - config.PowerPlanChangeDelayMs = this.PowerPlanChangeDelayMs; - - var success = await this.associationService.SaveConfigurationAsync(); + var success = await this.associationService.SaveMonitoringSettingsAsync( + this.PreventDuplicatePowerPlanChanges, this.PowerPlanChangeDelayMs); if (success) { this.SetStatus("Configuration saved and active.", false); } else { - this.SetStatus("Failed to save configuration", false); + this.ShowConfigurationError("Failed to save configuration"); } } catch (Exception ex) @@ -810,7 +865,7 @@ public void ClearSelectedExecutable() private void OnConfigurationChanged(object? sender, ConfigurationChangedEventArgs e) { - if (this.isInitialized) + if (this.isInitialized && !e.ChangeType.EndsWith("Error", StringComparison.Ordinal)) { _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(async () => await this.LoadDataAsync()); } diff --git a/ViewModels/ProcessViewModel.Behaviors.partial.cs b/ViewModels/ProcessViewModel.Behaviors.partial.cs index 609c7b8b..b2a364d1 100644 --- a/ViewModels/ProcessViewModel.Behaviors.partial.cs +++ b/ViewModels/ProcessViewModel.Behaviors.partial.cs @@ -30,24 +30,9 @@ private void SetupVirtualizedProcessService() this.virtualizedProcessService.Configuration.EnableBackgroundLoading = true; // Subscribe to events - this.virtualizedProcessService.BatchLoadProgress += this.OnBatchLoadProgress; this.virtualizedProcessService.BackgroundBatchLoaded += this.OnBackgroundBatchLoaded; } - private void OnBatchLoadProgress(object? sender, BatchLoadProgressEventArgs e) - { - if (this.isUiRefreshPaused || !this.isProcessViewActive) - { - return; - } - - _ = System.Windows.Application.Current.Dispatcher.InvokeAsync(() => - { - this.LoadingProgress = e.ProgressPercentage; - this.LoadingStatusText = e.StatusMessage; - }); - } - private void OnBackgroundBatchLoaded(object? sender, ProcessBatchResult e) { this.Logger.LogDebug( @@ -620,7 +605,6 @@ await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => // BUG FIX: Ensure loading state is properly cleared this.ClearStatus(); - this.LoadingProgress = 0.0; this.LoadingStatusText = string.Empty; }); @@ -631,7 +615,6 @@ await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { // BUG FIX: Ensure loading state is cleared even on error - this.LoadingProgress = 0.0; this.LoadingStatusText = string.Empty; this.SetStatus($"Error loading more processes: {ex.Message}", false); }); @@ -653,7 +636,6 @@ public async Task LoadProcesses() // PERFORMANCE IMPROVEMENT: Progressive loading with status updates await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { - this.LoadingProgress = 0.0; this.LoadingStatusText = this.ShowActiveApplicationsOnly ? "Loading active applications..." : "Loading processes..."; this.SetStatus(this.LoadingStatusText); }); @@ -717,7 +699,6 @@ await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => // BUG FIX: Ensure loading state is properly cleared this.ClearStatus(); - this.LoadingProgress = 0.0; this.LoadingStatusText = string.Empty; }); @@ -729,7 +710,6 @@ await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => await System.Windows.Application.Current.Dispatcher.InvokeAsync(() => { // BUG FIX: Ensure loading state is cleared even on error - this.LoadingProgress = 0.0; this.LoadingStatusText = string.Empty; this.SetStatus($"Error loading processes: {ex.Message}", false); }); diff --git a/ViewModels/ProcessViewModel.cs b/ViewModels/ProcessViewModel.cs index 8b56b6dd..fe38b6cd 100644 --- a/ViewModels/ProcessViewModel.cs +++ b/ViewModels/ProcessViewModel.cs @@ -153,9 +153,6 @@ public partial class ProcessViewModel : BaseViewModel private bool isProcessListLocked = false; // PERFORMANCE IMPROVEMENT: Progressive loading support - [ObservableProperty] - private double loadingProgress = 0.0; - [ObservableProperty] private string loadingStatusText = string.Empty; diff --git a/ViewModels/SettingsViewModel.cs b/ViewModels/SettingsViewModel.cs index 06127174..23c07540 100644 --- a/ViewModels/SettingsViewModel.cs +++ b/ViewModels/SettingsViewModel.cs @@ -126,8 +126,8 @@ public SettingsViewModel( this.ApplicationVersion = this.versionProvider.DisplayVersion; // Initialize with current settings - this.settings = (ApplicationSettingsModel)this.settingsService.Settings.Clone(); - this.savedSettingsSnapshot = (ApplicationSettingsModel)this.settings.Clone(); + this.settings = this.settingsService.Settings.Clone(); + this.savedSettingsSnapshot = this.settings.Clone(); this.appliedThemePreference = this.settings.UseDarkTheme; this.LatestUpdateVersion = this.GetLocalizedString("Settings_UpdateNotChecked", "Not checked"); this.ReservedCpuSetsStatus = this.GetLocalizedString("SettingsView_ReservedCpuSetsUnknown", "Reserved CPU Sets: status unavailable."); @@ -307,6 +307,13 @@ partial void OnIsUpdateAvailableChanged(bool value) this.DownloadAndInstallUpdateCommand.NotifyCanExecuteChanged(); } + private Task PersistEditedSettingsAsync() + { + var baseline = this.savedSettingsSnapshot; + var edited = this.Settings.Clone(); + return this.settingsService.EditSettingsAsync(draft => draft.CopyFrom(MergeSettings(baseline, edited, draft))); + } + private async Task SaveSettingsAsync() { string previousDefaultPowerPlanGuid = string.Empty; @@ -372,7 +379,7 @@ private async Task SaveSettingsAsync() } } - await this.settingsService.UpdateSettingsAsync(this.Settings); + await this.PersistEditedSettingsAsync(); var useDarkTheme = this.Settings.HasUserThemePreference ? this.Settings.UseDarkTheme @@ -683,7 +690,7 @@ internal void ApplyPersistedSettings(ApplicationSettingsModel newSettings) this.isSyncingFromService = true; try { - var persistedSettings = (ApplicationSettingsModel)newSettings.Clone(); + var persistedSettings = newSettings.Clone(); if (!string.IsNullOrWhiteSpace(this.cachedDefaultPowerPlanGuid)) { persistedSettings.DefaultPowerPlanId = this.cachedDefaultPowerPlanGuid; @@ -792,7 +799,7 @@ private async Task RefreshPowerPlansAsync() // Saved before the installer starts, since this copy is closed for it. this.Settings.AutostartWithWindows = true; - await this.settingsService.UpdateSettingsAsync(this.Settings); + await this.PersistEditedSettingsAsync(); var result = await this.updateService.DownloadAndInstallAsync(check.Release); return result.Status == UpdateInstallStatus.Started ? null : result.Message; } @@ -964,7 +971,7 @@ private void UpdatePendingChangesState() private void SetSavedSettingsSnapshot(ApplicationSettingsModel settingsSnapshot) { - this.savedSettingsSnapshot = (ApplicationSettingsModel)settingsSnapshot.Clone(); + this.savedSettingsSnapshot = settingsSnapshot.Clone(); this.HasUnsavedChanges = false; } } diff --git a/ViewModels/SystemTweaksViewModel.GameBoost.cs b/ViewModels/SystemTweaksViewModel.GameBoost.cs index f40949b4..54853e97 100644 --- a/ViewModels/SystemTweaksViewModel.GameBoost.cs +++ b/ViewModels/SystemTweaksViewModel.GameBoost.cs @@ -119,18 +119,25 @@ private async Task SaveGameBoostAsync() return; } - var updated = (ApplicationSettingsModel)this.settingsService.Settings.Clone(); - updated.GameBoostEnabled = this.GameBoostEnabled; - updated.GameBoostMode = this.GameBoostIsolation ? GameBoostMode.Isolation : GameBoostMode.Automatic; - updated.GameBoostAboveNormalPriority = this.GameBoostAboveNormal; - updated.GameBoostManualGames = SplitLines(this.GameBoostManualGamesText); - updated.GameBoostExcludedGames = SplitLines(this.GameBoostExcludedGamesText); - updated.GameBoostBackgroundProcesses = SplitLines(this.GameBoostBackgroundText); - - await this.settingsService.UpdateSettingsAsync(updated); + var enabled = this.GameBoostEnabled; + var mode = this.GameBoostIsolation ? GameBoostMode.Isolation : GameBoostMode.Automatic; + var aboveNormal = this.GameBoostAboveNormal; + var manualGames = SplitLines(this.GameBoostManualGamesText); + var excludedGames = SplitLines(this.GameBoostExcludedGamesText); + var backgroundProcesses = SplitLines(this.GameBoostBackgroundText); + + await this.settingsService.EditSettingsAsync(draft => + { + draft.GameBoostEnabled = enabled; + draft.GameBoostMode = mode; + draft.GameBoostAboveNormalPriority = aboveNormal; + draft.GameBoostManualGames = manualGames; + draft.GameBoostExcludedGames = excludedGames; + draft.GameBoostBackgroundProcesses = backgroundProcesses; + }); await this.LogUserActionAsync( "GameBoostSettingsChanged", - $"Game Boost {(updated.GameBoostEnabled ? "on" : "off")}, {updated.GameBoostMode}", + $"Game Boost {(enabled ? "on" : "off")}, {mode}", "GameBoost"); await this.RefreshGameBoostDecisionTextAsync(); } diff --git a/Views/ProcessPowerPlanAssociationView.xaml b/Views/ProcessPowerPlanAssociationView.xaml index f9305fed..4ce72dbc 100644 --- a/Views/ProcessPowerPlanAssociationView.xaml +++ b/Views/ProcessPowerPlanAssociationView.xaml @@ -264,13 +264,19 @@ SelectedItem="{Binding SelectedAssociation}" AutoGenerateColumns="False" CanUserAddRows="False" + IsReadOnly="True" GridLinesVisibility="Horizontal" HeadersVisibility="Column" BorderThickness="1"> - + + + + + + + @@ -547,7 +553,7 @@ - +