From 66d37c241461b16afd5055ceb14ec26e810ba822 Mon Sep 17 00:00:00 2001 From: PrimeBuild-pc Date: Fri, 20 Nov 2026 16:44:27 +0100 Subject: [PATCH 1/4] Fix ThreadPilot reliability findings and simplify audited code --- .github/workflows/release.yml | 65 +- App.xaml.cs | 6 +- Converters/ItemIndexConverter.cs | 32 - Helpers/AffinityHelper.cs | 25 - Locales/de-DE.xaml | 5 - Locales/en-US.xaml | 5 - Locales/es-ES.xaml | 5 - Locales/fr-FR.xaml | 5 - Locales/it-IT.xaml | 5 - Locales/ru-RU.xaml | 5 - Locales/zh-CN.xaml | 5 - MainWindow.Behaviors.partial.cs | 1 + Models/ApplicationSettingsModel.cs | 142 +--- Models/ConditionalProcessProfile.cs | 273 ------- .../Core/{IModel.cs => ValidationResult.cs} | 13 - Models/LogEventTypes.cs | 101 --- Models/ProcessPowerPlanAssociation.cs | 13 +- Models/ProfileModel.cs | 91 --- Models/ThreadPilotException.cs | 115 --- Services/Abstractions/IGitHubReleaseClient.cs | 2 - Services/ApplicationSettingsService.cs | 30 +- Services/ConditionalProfileService.cs | 570 --------------- Services/ConfigurationBackupService.cs | 1 + Services/CoreMaskService.cs | 10 +- Services/EnhancedLoggingService.cs | 127 +++- Services/GameSessionService.cs | 68 +- Services/GitHubReleaseClient.cs | 6 - Services/GitHubUpdateChecker.cs | 39 - Services/IConditionalProfileService.cs | 77 -- Services/IPersistentProcessRuleStore.cs | 22 + .../IProcessPowerPlanAssociationService.cs | 4 +- Services/ISmartNotificationService.cs | 137 ---- Services/IVirtualizedProcessService.cs | 27 - Services/LogFileManager.cs | 412 ----------- .../ProcessPowerPlanAssociationService.cs | 335 +++------ Services/ProcessRuleCreationService.cs | 4 + Services/ServiceConfiguration.cs | 2 +- Services/SmartNotificationService.cs | 665 ------------------ Services/SystemTweaksService.cs | 115 +-- Services/SystemUpdateClock.cs | 12 - Services/UpdateModels.cs | 5 - Services/UpdateService.cs | 6 +- Services/VirtualizedProcessService.cs | 66 -- .../ApplicationSettingsModelTests.cs | 39 +- .../EnhancedLoggingServiceTests.cs | 80 +++ .../GameSessionServiceTests.cs | 45 ++ .../GitHubUpdateCheckerTests.cs | 42 +- .../LogFileManagerTests.cs | 123 ---- .../PackagingMetadataTests.cs | 21 +- ...ProcessPowerPlanAssociationServiceTests.cs | 45 ++ .../ProcessRuleCreationServiceTests.cs | 48 ++ .../ProcessViewModelAffinityTests.cs | 4 +- .../SettingsViewModelThemeTests.cs | 6 +- .../SmartNotificationQuietHoursTests.cs | 46 -- .../SystemTweaksStartupAndStyleTests.cs | 32 + .../ThreadPilot.Core.Tests.csproj | 4 + .../UpdateServiceTests.cs | 17 +- .../ProcessPowerPlanAssociationViewModel.cs | 89 ++- .../ProcessViewModel.Behaviors.partial.cs | 20 - ViewModels/ProcessViewModel.cs | 3 - ViewModels/SettingsViewModel.cs | 8 +- ViewModels/SystemTweaksViewModel.GameBoost.cs | 2 +- Views/ProcessPowerPlanAssociationView.xaml | 14 +- Views/ProcessView.xaml | 2 +- Views/SettingsView.xaml | 40 -- build/build-release.ps1 | 94 +-- build/package-release-zips.ps1 | 124 ++-- build/portable-uninstall.bat | 36 + 68 files changed, 950 insertions(+), 3688 deletions(-) delete mode 100644 Converters/ItemIndexConverter.cs delete mode 100644 Helpers/AffinityHelper.cs delete mode 100644 Models/ConditionalProcessProfile.cs rename Models/Core/{IModel.cs => ValidationResult.cs} (67%) delete mode 100644 Models/ProfileModel.cs delete mode 100644 Models/ThreadPilotException.cs delete mode 100644 Services/ConditionalProfileService.cs delete mode 100644 Services/IConditionalProfileService.cs delete mode 100644 Services/ISmartNotificationService.cs delete mode 100644 Services/LogFileManager.cs delete mode 100644 Services/SmartNotificationService.cs delete mode 100644 Services/SystemUpdateClock.cs create mode 100644 Tests/ThreadPilot.Core.Tests/EnhancedLoggingServiceTests.cs delete mode 100644 Tests/ThreadPilot.Core.Tests/LogFileManagerTests.cs create mode 100644 Tests/ThreadPilot.Core.Tests/ProcessPowerPlanAssociationServiceTests.cs delete mode 100644 Tests/ThreadPilot.Core.Tests/SmartNotificationQuietHoursTests.cs create mode 100644 build/portable-uninstall.bat diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 29e40047..390f7ba3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -136,68 +136,9 @@ jobs: - name: Create release packages shell: pwsh - run: | - $ErrorActionPreference = "Stop" - $version = "${{ steps.version.outputs.tag }}" - New-Item -ItemType Directory -Force -Path "artifacts/release/packages" | Out-Null - New-Item -ItemType Directory -Force -Path "artifacts/release/package-staging" | Out-Null - - $sharedUninstall = "artifacts/release/package-staging/uninstall.bat" - $sharedLicense = "artifacts/release/package-staging/LICENSE.md" - - $uninstallContent = @' - @echo off - setlocal EnableExtensions - title ThreadPilot Uninstaller - - set "APP_DIR=%~dp0" - if "%APP_DIR:~-1%"=="\" set "APP_DIR=%APP_DIR:~0,-1%" - - echo ====================================================== - echo ThreadPilot Uninstaller - echo ====================================================== - echo. - - echo [1/4] Closing running ThreadPilot processes... - taskkill /IM "ThreadPilot.exe" /F >nul 2>&1 - - echo [2/4] Removing startup task and startup registry entry... - schtasks /Delete /TN "ThreadPilot_Launch" /F >nul 2>&1 - schtasks /Delete /TN "ThreadPilot_Startup" /F >nul 2>&1 - reg delete "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" /v "ThreadPilot" /f >nul 2>&1 - - echo [3/4] Removing ThreadPilot user data for this Windows account... - rem Full uninstall removes only ThreadPilot-owned per-user AppData. Normal install/update paths never run this script. - if exist "%APPDATA%\ThreadPilot" ( - rd /s /q "%APPDATA%\ThreadPilot" - echo ThreadPilot user data removed. - ) else ( - echo No ThreadPilot user data folder found. - ) - - echo [4/4] Scheduling app folder removal... - start "" /min cmd /c "timeout /t 5 /nobreak >nul & rd /s /q \"%APP_DIR%\"" - - echo. - echo Uninstall completed. Remaining files will be removed in a few seconds. - endlocal - exit /b 0 - '@ - - Set-Content -LiteralPath $sharedUninstall -Value $uninstallContent -Encoding Ascii - Copy-Item "LICENSE" -Destination $sharedLicense -Force - - $portableStage = "artifacts/release/package-staging/portable" - New-Item -ItemType Directory -Force -Path $portableStage | Out-Null - - Copy-Item "artifacts/release/singlefile/*" -Destination $portableStage -Recurse -Force - - Copy-Item $sharedUninstall -Destination (Join-Path $portableStage "uninstall.bat") -Force - Copy-Item $sharedLicense -Destination (Join-Path $portableStage "LICENSE.md") -Force - - $portableZip = "artifacts/release/packages/ThreadPilot_$version`_Portable.zip" - - Compress-Archive -Path "$portableStage/*" -DestinationPath $portableZip -Force + env: + RELEASE_TAG: ${{ steps.version.outputs.tag }} + run: ./build/package-release-zips.ps1 -Version $env:RELEASE_TAG - name: Generate checksums shell: pwsh diff --git a/App.xaml.cs b/App.xaml.cs index 7f759661..70f84936 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -498,14 +498,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/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..afd43fcd 100644 --- a/MainWindow.Behaviors.partial.cs +++ b/MainWindow.Behaviors.partial.cs @@ -575,6 +575,7 @@ private async Task MigratePersistentRuleCpuAssignmentModesAsync() return; } + using var edit = await PersistentRuleEditGate.EnterAsync(ruleStore); var rules = await ruleStore.LoadAsync(); var migrated = CpuAssignmentModeMigrationPolicy.ApplyToRules(rules); if (migrated != null) diff --git a/Models/ApplicationSettingsModel.cs b/Models/ApplicationSettingsModel.cs index 20ad3f39..dfdb6348 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; @@ -316,7 +280,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 +294,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 +324,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 +343,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/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..4a205369 100644 --- a/Services/ApplicationSettingsService.cs +++ b/Services/ApplicationSettingsService.cs @@ -30,7 +30,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( @@ -127,7 +127,7 @@ public async Task LoadSettingsAsync() loadedSettings.Language, this.systemUiCultureProvider()); - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); + var oldSettings = this.settings.Clone(); this.settings.CopyFrom(loadedSettings); this.ValidateAndFixSettings(); @@ -199,7 +199,7 @@ public async Task UpdateSettingsAsync(ApplicationSettingsModel newSettings) try { - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); + var oldSettings = this.settings.Clone(); var resolvedLanguage = LocalizationService.ResolveLanguagePreference( newSettings.Language, this.systemUiCultureProvider()); @@ -224,7 +224,7 @@ public async Task ResetToDefaultsAsync() { this.logger.LogInformation("Resetting settings to defaults"); - var oldSettings = (ApplicationSettingsModel)this.settings.Clone(); + var oldSettings = this.settings.Clone(); this.settings = this.CreateDefaultSettings(); await this.SaveSettingsAsync(); @@ -288,15 +288,15 @@ public void ValidateAndFixSettings() } } - 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; - } + 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; + } } public async Task ExportSettingsAsync(string filePath) @@ -359,8 +359,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..37d63d26 100644 --- a/Services/ConfigurationBackupService.cs +++ b/Services/ConfigurationBackupService.cs @@ -86,6 +86,7 @@ public static void Validate(ConfigurationBackup backup) public async Task ApplyAsync(ConfigurationBackup backup) { Validate(backup); + using var edit = await PersistentRuleEditGate.EnterAsync(rules); var previous = await this.CaptureAsync(settings.Settings); try { 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..cb95c34f 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) @@ -521,16 +582,20 @@ public async Task UpdateConfigurationAsync(bool enableDebugLogging, int maxFileS 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..35eea2e8 100644 --- a/Services/GameSessionService.cs +++ b/Services/GameSessionService.cs @@ -420,6 +420,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 +815,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 +880,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 +924,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 +1010,10 @@ await this.AuditAsync( break; } - this.journal.Remove(entry); + if (outcome != RestoreOutcome.Failed) + { + this.journal.Remove(entry); + } } await this.SaveJournalAsync().ConfigureAwait(false); @@ -1011,7 +1030,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 +1045,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 +1066,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; } @@ -1152,10 +1188,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) @@ -1187,21 +1229,23 @@ private async Task> LoadJournalAsync() } } - 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; } } 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/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/IPersistentProcessRuleStore.cs b/Services/IPersistentProcessRuleStore.cs index 713b9c5d..55bfd477 100644 --- a/Services/IPersistentProcessRuleStore.cs +++ b/Services/IPersistentProcessRuleStore.cs @@ -3,6 +3,7 @@ */ namespace ThreadPilot.Services { + using System.Runtime.CompilerServices; using ThreadPilot.Models; public interface IPersistentProcessRuleStore @@ -11,4 +12,25 @@ public interface IPersistentProcessRuleStore Task SaveAsync(IReadOnlyList rules); } + + // Writers use the same gate for the entire read/edit/save operation on a store. + internal static class PersistentRuleEditGate + { + private static readonly ConditionalWeakTable Gates = new(); + + public static async Task EnterAsync( + IPersistentProcessRuleStore store, CancellationToken cancellationToken = default) + { + var gate = Gates.GetValue(store, _ => new SemaphoreSlim(1, 1)); + await gate.WaitAsync(cancellationToken).ConfigureAwait(false); + return new Lease(gate); + } + + private sealed class Lease(SemaphoreSlim gate) : IDisposable + { + private SemaphoreSlim? heldGate = gate; + + public void Dispose() => Interlocked.Exchange(ref this.heldGate, null)?.Release(); + } + } } diff --git a/Services/IProcessPowerPlanAssociationService.cs b/Services/IProcessPowerPlanAssociationService.cs index 4e2ec65b..c93e997c 100644 --- a/Services/IProcessPowerPlanAssociationService.cs +++ b/Services/IProcessPowerPlanAssociationService.cs @@ -13,7 +13,7 @@ public interface IProcessPowerPlanAssociationService Task LoadConfigurationAsync(); - Task SaveConfigurationAsync(); + Task SaveMonitoringSettingsAsync(bool preventDuplicateChanges, int delayMs); Task> GetAssociationsAsync(); @@ -35,7 +35,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/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/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..1b11cfa9 100644 --- a/Services/ProcessRuleCreationService.cs +++ b/Services/ProcessRuleCreationService.cs @@ -179,6 +179,7 @@ public async Task DeleteRuleAsync( { ArgumentNullException.ThrowIfNull(process); + using var edit = await PersistentRuleEditGate.EnterAsync(this.ruleStore, cancellationToken).ConfigureAwait(false); var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); var existingIndex = FindExistingRuleIndex(rules, process); if (existingIndex < 0) @@ -200,6 +201,7 @@ public async Task DeleteRuleByIdAsync( return ProcessRuleCreationResult.Failed("NoSavedRuleToDelete", NoSavedRuleMessage); } + using var edit = await PersistentRuleEditGate.EnterAsync(this.ruleStore, cancellationToken).ConfigureAwait(false); var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); var existingIndex = rules.FindIndex(rule => string.Equals(rule.Id, ruleId, StringComparison.Ordinal)); if (existingIndex < 0) @@ -232,6 +234,7 @@ public async Task UpdateRuleWithCoreSelectionAsync( ProcessOperationUserMessages.RealtimePriorityBlocked); } + using var edit = await PersistentRuleEditGate.EnterAsync(this.ruleStore, cancellationToken).ConfigureAwait(false); 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) @@ -386,6 +389,7 @@ public async Task SaveRuleAsync( return ProcessRuleCreationResult.Failed("NoActionableRulePayload", NoCurrentSettingsMessage); } + using var edit = await PersistentRuleEditGate.EnterAsync(this.ruleStore, cancellationToken).ConfigureAwait(false); var rules = (await this.ruleStore.LoadAsync().ConfigureAwait(false)).ToList(); var existingIndex = FindExistingRuleIndex(rules, process); var created = existingIndex < 0; 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..9aaf11cd 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)); @@ -132,7 +132,7 @@ public async Task DownloadAndInstallAsync(UpdateReleaseInfo private async Task MarkUpdateCheckAttemptAsync(CancellationToken cancellationToken) { var settings = this.settingsService.Settings; - settings.LastUpdateCheckUtc = this.clock.UtcNow; + settings.LastUpdateCheckUtc = this.clock.GetUtcNow(); await this.settingsService.UpdateSettingsAsync(settings).ConfigureAwait(false); } 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/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..5f8cbaf5 100644 --- a/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/GameSessionServiceTests.cs @@ -111,6 +111,44 @@ 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); + } + } + + [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 +743,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 +803,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..c2127b7e 100644 --- a/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs +++ b/Tests/ThreadPilot.Core.Tests/PackagingMetadataTests.cs @@ -63,22 +63,15 @@ public void PrimaryInstaller_RemovesThreadPilotOwnedDataOnlyDuringUninstall() } [Fact] - public void PortableUninstallers_RemoveCurrentAndLegacyStartupTasks() + public void PortablePackages_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"); + AssertFileContains(Path.Combine(root, ".github", "workflows", "release.yml"), "package-release-zips.ps1"); } [Fact] 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..cce456e0 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,53 @@ public async Task UpdateRule_SaveThenReload_PreservesUpdatedValues() } } + [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 physicalStore = new PersistentProcessRuleJsonStore(() => file); + await physicalStore.SaveAsync([first, second]); + var store = new Mock(); + store.Setup(x => x.LoadAsync()).Returns(() => physicalStore.LoadAsync()); + var writeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var writes = 0; + store.Setup(x => x.SaveAsync(It.IsAny>())) + .Returns(async (IReadOnlyList proposed) => + { + if (Interlocked.Increment(ref writes) == 1) + { + writeStarted.SetResult(); + await release.Task.WaitAsync(timeout.Token); + } + + await physicalStore.SaveAsync(proposed); + }); + var service = new ProcessRuleCreationService( + store.Object, null, new CpuSelectionMigrationService(), NullLogger.Instance); + var a = service.UpdateRuleAsync(first with { Priority = ProcessPriorityClass.AboveNormal }, timeout.Token); + await writeStarted.Task.WaitAsync(timeout.Token); + var b = service.UpdateRuleAsync(second with { Priority = ProcessPriorityClass.BelowNormal }, timeout.Token); + store.Verify(x => x.LoadAsync(), Times.Once); + release.SetResult(); + var results = await Task.WhenAll(a, b); + + Assert.All(results, result => Assert.True(result.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..a85e4ece 100644 --- a/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs +++ b/Tests/ThreadPilot.Core.Tests/SettingsViewModelThemeTests.cs @@ -140,7 +140,7 @@ public async Task SaveSettingsCommand_PersistsSelectedLanguage() ApplicationSettingsModel? savedSettings = null; harness.SettingsService .Setup(service => service.UpdateSettingsAsync(It.IsAny())) - .Callback(settings => savedSettings = (ApplicationSettingsModel)settings.Clone()) + .Callback(settings => savedSettings = settings.Clone()) .Returns(Task.CompletedTask); var viewModel = harness.CreateViewModel(); viewModel.Settings.Language = "zh-CN"; @@ -243,11 +243,11 @@ public async Task SaveSettingsCommand_MergesPendingEditWithExternalUpdate() ApplicationSettingsModel? savedSettings = null; harness.SettingsService .Setup(service => service.UpdateSettingsAsync(It.IsAny())) - .Callback(settings => savedSettings = (ApplicationSettingsModel)settings.Clone()) + .Callback(settings => savedSettings = settings.Clone()) .Returns(Task.CompletedTask); var viewModel = harness.CreateViewModel(); viewModel.Settings.Language = "it-IT"; - var externalUpdate = (ApplicationSettingsModel)harness.PersistedSettings.Clone(); + var externalUpdate = harness.PersistedSettings.Clone(); externalUpdate.LastUpdateCheckUtc = DateTimeOffset.UtcNow; viewModel.ApplyPersistedSettings(externalUpdate); 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/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..5e701938 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,12 +327,12 @@ 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 => { - this.SavedSettings = (ApplicationSettingsModel)settings.Clone(); + this.SavedSettings = settings.Clone(); this.Settings.CopyFrom(settings); }) .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/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..d1360e62 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."); @@ -683,7 +683,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; @@ -964,7 +964,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..f7d58f50 100644 --- a/ViewModels/SystemTweaksViewModel.GameBoost.cs +++ b/ViewModels/SystemTweaksViewModel.GameBoost.cs @@ -119,7 +119,7 @@ private async Task SaveGameBoostAsync() return; } - var updated = (ApplicationSettingsModel)this.settingsService.Settings.Clone(); + var updated = this.settingsService.Settings.Clone(); updated.GameBoostEnabled = this.GameBoostEnabled; updated.GameBoostMode = this.GameBoostIsolation ? GameBoostMode.Isolation : GameBoostMode.Automatic; updated.GameBoostAboveNormalPriority = this.GameBoostAboveNormal; 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 @@ - +