diff --git a/Models/ProcessModel.cs b/Models/ProcessModel.cs index 3b54b21..cbe6c25 100644 --- a/Models/ProcessModel.cs +++ b/Models/ProcessModel.cs @@ -59,6 +59,14 @@ public partial class ProcessModel : ObservableObject [ObservableProperty] private bool isRegistryPriorityEnabled; + internal DateTime? StartTimeUtc { get; set; } + + internal bool IsSameInstance(ProcessModel other) => + this.ProcessId == other.ProcessId + && (this.StartTimeUtc.HasValue && other.StartTimeUtc.HasValue + ? this.StartTimeUtc == other.StartTimeUtc + : string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase)); + public void ForceNotifyProcessorAffinityChanged() { this.OnPropertyChanged(nameof(this.ProcessorAffinity)); diff --git a/Services/ProcessMonitorManagerService.cs b/Services/ProcessMonitorManagerService.cs index 96df021..98b3d5e 100644 --- a/Services/ProcessMonitorManagerService.cs +++ b/Services/ProcessMonitorManagerService.cs @@ -241,6 +241,7 @@ private async Task EvaluateCurrentProcessesAsync(bool resetRuleAttempts) try { + var trackedBeforeScan = this.runningAssociatedProcesses.ToArray(); var currentProcesses = (await this.processMonitorService.GetRunningProcessesAsync()).ToList(); if (resetRuleAttempts) { @@ -253,17 +254,18 @@ private async Task EvaluateCurrentProcessesAsync(bool resetRuleAttempts) } await this.ApplyPersistentRulesForDiscoveredProcessesAsync(currentProcesses); - var associatedProcesses = new List(); - var currentProcessIds = new HashSet(currentProcesses.Select(p => p.ProcessId)); + var currentById = currentProcesses.DistinctBy(process => process.ProcessId) + .ToDictionary(process => process.ProcessId); - // Remove stale tracked processes that are no longer running - foreach (var trackedPid in this.runningAssociatedProcesses.Keys) + // A snapshot can contain a different process that reused a tracked PID. + foreach (var tracked in trackedBeforeScan) { - if (!currentProcessIds.Contains(trackedPid) && this.runningAssociatedProcesses.TryRemove(trackedPid, out _)) + if ((!currentById.TryGetValue(tracked.Key, out var current) || !tracked.Value.IsSameInstance(current)) + && this.runningAssociatedProcesses.TryRemove(tracked)) { - this.coreMaskService.UnregisterMaskApplication(trackedPid); - this.processService.UntrackProcess(trackedPid); - this.persistentRuleAutoApplyService.MarkProcessExited(trackedPid); + this.coreMaskService.UnregisterMaskApplication(tracked.Key); + this.processService.UntrackProcess(tracked.Key); + this.persistentRuleAutoApplyService.MarkProcessExited(tracked.Key); } } @@ -273,13 +275,12 @@ private async Task EvaluateCurrentProcessesAsync(bool resetRuleAttempts) var association = this.configuration.FindMatchingAssociation(process); if (association != null) { - associatedProcesses.Add(process); this.runningAssociatedProcesses[process.ProcessId] = process; } } // Determine which power plan should be active - await this.DeterminePowerPlanAsync(associatedProcesses); + await this.UpdatePowerPlanAsync(); } catch (Exception ex) { @@ -287,67 +288,7 @@ private async Task EvaluateCurrentProcessesAsync(bool resetRuleAttempts) } } - public async Task ForceDefaultPowerPlanAsync() - { - if (this.configuration?.DefaultPowerPlanGuid == null) - { - return; - } - - try - { - await this.powerPlanChangeSemaphore.WaitAsync(); - - var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); - var decision = this.powerPlanTransitionGate.ShouldApply( - this.configuration.DefaultPowerPlanGuid, - currentPowerPlan?.Guid); - if (!decision.ShouldApply) - { - this.logger.LogDebug( - "Default power plan restore suppressed for {PowerPlanGuid}: {Reason}", - this.configuration.DefaultPowerPlanGuid, - decision.SuppressionReason); - return; - } - - this.powerPlanTransitionGate.RecordAttempt(this.configuration.DefaultPowerPlanGuid); - var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync( - this.configuration.DefaultPowerPlanGuid, - this.configuration.PreventDuplicatePowerPlanChanges); - - if (success) - { - var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(this.configuration.DefaultPowerPlanGuid); - // Note: We don't have a specific process for this event, so we'll use a dummy one - var dummyProcess = new ProcessModel { Name = "System", ProcessId = -1 }; - var dummyAssociation = new ProcessPowerPlanAssociation("System", this.configuration.DefaultPowerPlanGuid, this.configuration.DefaultPowerPlanName); - - this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( - dummyProcess, dummyAssociation, currentPowerPlan, newPowerPlan, "DefaultRestored")); - - // Show notification for default power plan restoration - await this.notificationService.ShowPowerPlanChangeNotificationAsync( - currentPowerPlan?.Name ?? "Unknown", - newPowerPlan?.Name ?? this.configuration.DefaultPowerPlanName, - string.Empty); - } - else - { - this.logger.LogWarning( - "Failed to restore default power plan {PowerPlanGuid}", - this.configuration.DefaultPowerPlanGuid); - } - } - catch (Exception ex) - { - this.SetStatus(this.isRunning, "Error setting default power plan", $"Error: {ex.Message}", ex); - } - finally - { - this.powerPlanChangeSemaphore.Release(); - } - } + public Task ForceDefaultPowerPlanAsync() => this.UpdatePowerPlanAsync(forceDefault: true); public async Task GetCurrentActivePowerPlanAsync() { @@ -386,6 +327,7 @@ private async Task OnProcessStartedAsync(ProcessEventArgs e) return; } + var monitoringToken = this.automationLifetime.Token; try { this.logger.LogDebug( @@ -416,10 +358,8 @@ private async Task OnProcessStartedAsync(ProcessEventArgs e) } var association = associationCandidates.FirstOrDefault(candidate => candidate.MatchesProcess(e.Process)); - if (association != null) + if (association != null && await this.TrackRunningAssociationAsync(e.Process, monitoringToken)) { - this.runningAssociatedProcesses[e.Process.ProcessId] = e.Process; - await this.enhancedLogger.LogProcessMonitoringEventAsync( LogEventTypes.ProcessMonitoring.AssociationTriggered, e.Process.Name, e.Process.ProcessId, @@ -428,6 +368,11 @@ await this.enhancedLogger.LogProcessMonitoringEventAsync( // Apply CPU affinity mask if configured await this.ApplyCoreMaskAndPriorityAsync(e.Process, association); + if (monitoringToken.IsCancellationRequested || !this.IsTrackedAssociation(e.Process)) + { + return; + } + // Schedule power plan change with delay if configured if (this.configuration.PowerPlanChangeDelayMs > 0) { @@ -440,7 +385,7 @@ await this.enhancedLogger.LogSystemEventAsync( } else { - await this.ChangePowerPlanForProcess(e.Process, association, "ProcessStarted"); + await this.UpdatePowerPlanAsync(startedProcess: e.Process); } } } @@ -456,6 +401,28 @@ await this.enhancedLogger.LogErrorAsync(ex, "ProcessMonitorManagerService.OnProc } } + private async Task TrackRunningAssociationAsync(ProcessModel process, CancellationToken monitoringToken) + { + if (monitoringToken.IsCancellationRequested) + { + return false; + } + + // Register before checking liveness so a concurrent stop can remove the entry. + this.runningAssociatedProcesses[process.ProcessId] = process; + if (await this.processService.IsProcessStillRunning(process) && !monitoringToken.IsCancellationRequested) + { + return this.IsTrackedAssociation(process); + } + + this.runningAssociatedProcesses.TryRemove(KeyValuePair.Create(process.ProcessId, process)); + return false; + } + + private bool IsTrackedAssociation(ProcessModel process) => + this.runningAssociatedProcesses.TryGetValue(process.ProcessId, out var tracked) && + ReferenceEquals(tracked, process); + private void OnProcessStopped(object? sender, ProcessEventArgs e) { TaskSafety.FireAndForget(this.OnProcessStoppedAsync(e), ex => @@ -479,9 +446,7 @@ private async Task OnProcessStoppedAsync(ProcessEventArgs e) if (this.runningAssociatedProcesses.TryRemove(e.Process.ProcessId, out _)) { - // Check if there are any other associated processes still running - var remainingProcesses = this.runningAssociatedProcesses.Values.ToList(); - await this.DeterminePowerPlanAsync(remainingProcesses); + await this.UpdatePowerPlanAsync(); } } catch (Exception ex) @@ -546,103 +511,130 @@ private async Task DelayedPowerPlanChangeCallbackAsync() return; } - var runningProcesses = this.runningAssociatedProcesses.Values.ToList(); - await this.DeterminePowerPlanAsync(runningProcesses); + await this.UpdatePowerPlanAsync(); } - private async Task DeterminePowerPlanAsync(IList associatedProcesses) + private async Task UpdatePowerPlanAsync(ProcessModel? startedProcess = null, bool forceDefault = false) { - if (this.configuration == null) - { - return; - } - + await this.powerPlanChangeSemaphore.WaitAsync(); try { - if (associatedProcesses.Any()) + var configuration = this.configuration; + if (configuration == null || (!forceDefault && !this.isRunning)) { - // Find the highest priority association among running processes - var associations = associatedProcesses - .Select(p => this.configuration.FindMatchingAssociation(p)) - .Where(a => a != null) - .OrderByDescending(a => a!.Priority) - .ToList(); - - if (associations.Any()) + return; + } + + if (startedProcess != null) + { + var association = configuration.FindMatchingAssociation(startedProcess); + if (association != null) { - var topAssociation = associations.First()!; - var matchingProcess = associatedProcesses.First(p => topAssociation.MatchesProcess(p)); - await this.ChangePowerPlanForProcess(matchingProcess, topAssociation, "ProcessStarted"); + await this.TryChangePowerPlanForProcessAsync(startedProcess, association, configuration); } + + return; } - else + + if (!forceDefault) { - // No associated processes running, revert to default - if (!string.IsNullOrEmpty(this.configuration.DefaultPowerPlanGuid)) + // Read the list after any in-flight plan change has completed. Stop events + // remove their processes before waiting for this lock. + var candidates = this.runningAssociatedProcesses.Values + .Select(process => (Process: process, Association: configuration.FindMatchingAssociation(process))) + .Where(candidate => candidate.Association != null) + .OrderByDescending(candidate => candidate.Association!.Priority); + foreach (var candidate in candidates) { - await this.ForceDefaultPowerPlanAsync(); + if (await this.TryChangePowerPlanForProcessAsync(candidate.Process, candidate.Association!, configuration)) + { + return; + } } } + + if ((forceDefault || this.isRunning) && !string.IsNullOrEmpty(configuration.DefaultPowerPlanGuid)) + { + await this.RestoreDefaultPowerPlanAsync(configuration); + } } catch (Exception ex) { this.SetStatus(this.isRunning, "Error determining power plan", $"Error: {ex.Message}", ex); } + finally + { + this.powerPlanChangeSemaphore.Release(); + } } - private async Task ChangePowerPlanForProcess(ProcessModel process, ProcessPowerPlanAssociation association, string action) + private async Task RestoreDefaultPowerPlanAsync(ProcessMonitorConfiguration configuration) { - try + var guid = configuration.DefaultPowerPlanGuid; + var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); + var decision = this.powerPlanTransitionGate.ShouldApply(guid, currentPowerPlan?.Guid); + if (!decision.ShouldApply) { - await this.powerPlanChangeSemaphore.WaitAsync(); + this.logger.LogDebug("Default power plan restore suppressed for {PowerPlanGuid}: {Reason}", guid, decision.SuppressionReason); + return; + } - var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); - var decision = this.powerPlanTransitionGate.ShouldApply( - association.PowerPlanGuid, - currentPowerPlan?.Guid); - if (!decision.ShouldApply) - { - this.logger.LogDebug( - "Power plan change suppressed for {PowerPlanGuid}: {Reason}", - association.PowerPlanGuid, - decision.SuppressionReason); - return; - } + this.powerPlanTransitionGate.RecordAttempt(guid); + if (!await this.powerPlanService.SetActivePowerPlanByGuidAsync(guid, configuration.PreventDuplicatePowerPlanChanges)) + { + this.logger.LogWarning("Failed to restore default power plan {PowerPlanGuid}", guid); + return; + } - this.powerPlanTransitionGate.RecordAttempt(association.PowerPlanGuid); - var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync( - association.PowerPlanGuid, - this.configuration?.PreventDuplicatePowerPlanChanges ?? true); + var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(guid); + var systemProcess = new ProcessModel { Name = "System", ProcessId = -1 }; + var defaultAssociation = new ProcessPowerPlanAssociation("System", guid, configuration.DefaultPowerPlanName); + this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( + systemProcess, defaultAssociation, currentPowerPlan, newPowerPlan, "DefaultRestored")); + await this.notificationService.ShowPowerPlanChangeNotificationAsync( + currentPowerPlan?.Name ?? "Unknown", newPowerPlan?.Name ?? configuration.DefaultPowerPlanName, string.Empty); + } - if (success) - { - var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(association.PowerPlanGuid); - this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( - process, association, currentPowerPlan, newPowerPlan, action)); - - // Show notification for power plan change - await this.notificationService.ShowPowerPlanChangeNotificationAsync( - currentPowerPlan?.Name ?? "Unknown", - newPowerPlan?.Name ?? association.PowerPlanName, - process.Name); - } - else - { - this.logger.LogWarning( - "Failed to change power plan to {PowerPlanGuid} for process {ProcessName} (PID: {ProcessId})", - association.PowerPlanGuid, - process.Name, - process.ProcessId); - } + private async Task TryChangePowerPlanForProcessAsync( + ProcessModel process, ProcessPowerPlanAssociation association, ProcessMonitorConfiguration configuration) + { + if (!this.isRunning || !this.IsTrackedAssociation(process)) + { + return false; } - catch (Exception ex) + + var currentPowerPlan = await this.powerPlanService.GetActivePowerPlan(); + var stillRunning = await this.processService.IsProcessStillRunning(process); + if (!stillRunning || !this.isRunning || !this.IsTrackedAssociation(process)) { - this.SetStatus(this.isRunning, "Error changing power plan", $"Error: {ex.Message}", ex); + return false; } - finally + + var decision = this.powerPlanTransitionGate.ShouldApply(association.PowerPlanGuid, currentPowerPlan?.Guid); + if (!decision.ShouldApply) { - this.powerPlanChangeSemaphore.Release(); + this.logger.LogDebug( + "Power plan change suppressed for {PowerPlanGuid}: {Reason}", association.PowerPlanGuid, decision.SuppressionReason); + return true; } + + this.powerPlanTransitionGate.RecordAttempt(association.PowerPlanGuid); + var success = await this.powerPlanService.SetActivePowerPlanByGuidAsync( + association.PowerPlanGuid, configuration.PreventDuplicatePowerPlanChanges); + if (!success) + { + this.logger.LogWarning( + "Failed to change power plan to {PowerPlanGuid} for process {ProcessName} (PID: {ProcessId})", + association.PowerPlanGuid, process.Name, process.ProcessId); + return true; + } + + var newPowerPlan = await this.powerPlanService.GetPowerPlanByGuidAsync(association.PowerPlanGuid); + this.ProcessPowerPlanChanged?.Invoke(this, new ProcessPowerPlanChangeEventArgs( + process, association, currentPowerPlan, newPowerPlan, "ProcessStarted")); + await this.notificationService.ShowPowerPlanChangeNotificationAsync( + currentPowerPlan?.Name ?? "Unknown", newPowerPlan?.Name ?? association.PowerPlanName, process.Name); + return true; } private void SetStatus(bool isRunning, string status, string? details = null, Exception? error = null) diff --git a/Services/ProcessMonitorService.cs b/Services/ProcessMonitorService.cs index 38f03aa..87588f5 100644 --- a/Services/ProcessMonitorService.cs +++ b/Services/ProcessMonitorService.cs @@ -431,13 +431,14 @@ private void HandleProcessStarted(int processId, string processName) { ProcessId = processId, Name = NormalizeProcessName(processName), + StartTimeUtc = ProcessService.TryGetProcessStartTimeUtc(processId), Classification = ProcessClassification.Unknown, } : null; if (process != null) { - this.runningProcesses.TryAdd(processId, process); + this.UpdateRunningProcess(process); this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); } } @@ -520,9 +521,8 @@ private async Task RunFallbackPollingAsync(CancellationToken cancellationToken) return; } - if (!this.runningProcesses.ContainsKey(process.ProcessId)) + if (this.UpdateRunningProcess(process)) { - this.runningProcesses.TryAdd(process.ProcessId, process); this.ProcessStarted?.Invoke(this, new ProcessEventArgs(process)); detectedChanges++; } @@ -560,6 +560,17 @@ private async Task RunFallbackPollingAsync(CancellationToken cancellationToken) } } + private bool UpdateRunningProcess(ProcessModel process) + { + var pid = process.ProcessId; + if (this.runningProcesses.TryGetValue(pid, out var existing) && !existing.IsSameInstance(process)) + { + return this.runningProcesses.TryUpdate(pid, process, existing); + } + + return this.runningProcesses.TryAdd(pid, process); + } + private void UpdateAdaptivePollingInterval(int detectedChanges) { if (!this.isFallbackPollingActive || this.fallbackTimer == null) diff --git a/Services/ProcessService.cs b/Services/ProcessService.cs index 8658a5e..72d501e 100644 --- a/Services/ProcessService.cs +++ b/Services/ProcessService.cs @@ -189,6 +189,19 @@ private double CalculateCpuUsage(Process process) } } + internal static DateTime? TryGetProcessStartTimeUtc(int processId) + { + try + { + using var process = Process.GetProcessById(processId); + return process.StartTime.ToUniversalTime(); + } + catch (Exception ex) when (ex is ArgumentException || IsPassiveProcessAccessException(ex) || IsTerminatedProcessException(ex)) + { + return null; + } + } + public ProcessModel CreateProcessModel(Process process) { return this.CreateProcessModel(process, this.foregroundProcessService?.TryGetForegroundProcessId()); @@ -290,11 +303,11 @@ private ProcessModel CreateProcessModel(Process process, int? foregroundProcessI { try { - startTimeUtc = process.StartTime.ToUniversalTime(); + startTimeUtc = model.StartTimeUtc = process.StartTime.ToUniversalTime(); } catch (Exception ex) when (IsPassiveProcessAccessException(ex) || IsTerminatedProcessException(ex)) { - // Start time is used only to validate static metadata against PID reuse. + // Start time may be inaccessible for protected processes. } try diff --git a/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs index 6c340b8..052f080 100644 --- a/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs +++ b/Tests/ThreadPilot.Core.Tests/ProcessMonitorManagerServiceTests.cs @@ -979,6 +979,180 @@ public async Task StopAsync_CancelsUnassociatedAutomationAndRestartGetsFreshLife Assert.True(tokens[1].IsCancellationRequested); } + [Theory] + [InlineData(0)] + [InlineData(25)] + public async Task ProcessStopped_DuringStartRefresh_DoesNotApplyExitedProcessPlan(int delayMs) + { + var processMonitor = new FakeProcessMonitorService(); + var process = new ProcessModel { ProcessId = 21, Name = "game" }; + var powerPlans = new PowerPlanState(); + var processService = CreateProcessService(); + var refresh = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + processService.Setup(x => x.IsProcessStillRunning(process)).ReturnsAsync(false); + using var manager = CreatePowerPlanManager(processMonitor, powerPlans, processService, delayMs); + processService.Setup(x => x.RefreshProcessInfo(process)).Returns(refresh.Task); + + await manager.StartAsync(); + processMonitor.RaiseProcessStarted(process); + processService.Verify(x => x.RefreshProcessInfo(process), Times.Once); + processMonitor.RaiseProcessStopped(process); + refresh.SetException(new InvalidOperationException("Process no longer exists")); + + // Give the start continuation and the delayed power plan callback time to finish. + await Task.WhenAny(powerPlans.GameApplied.Task, Task.Delay(500)); + Assert.Equal("balanced", powerPlans.Active); + Assert.Empty(manager.RunningAssociatedProcesses); + powerPlans.Service.Verify(x => x.SetActivePowerPlanByGuidAsync("plan-game", true), Times.Never); + } + + [Fact] + public async Task ProcessStopped_DuringActivePlanRead_SkipsExitedProcessPlan() + { + var processMonitor = new FakeProcessMonitorService(); + var process = new ProcessModel { ProcessId = 21, Name = "game" }; + var powerPlans = new PowerPlanState(); + var processService = CreateProcessService(); + using var manager = CreatePowerPlanManager(processMonitor, powerPlans, processService); + await manager.StartAsync(); + + var readStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finishRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var restoreChecked = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + powerPlans.Service.SetupSequence(x => x.GetActivePowerPlan()) + .Returns(() => + { + readStarted.TrySetResult(); + return finishRead.Task; + }) + .Returns(() => + { + restoreChecked.TrySetResult(); + return Task.FromResult(powerPlans.Current); + }) + .Returns(() => Task.FromResult(powerPlans.Current)); + + processMonitor.RaiseProcessStarted(process); + try + { + await readStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + processMonitor.RaiseProcessStopped(process); + } + finally + { + finishRead.TrySetResult(powerPlans.Current); + } + + await restoreChecked.Task.WaitAsync(TimeSpan.FromSeconds(5)); + powerPlans.Service.Verify(x => x.SetActivePowerPlanByGuidAsync("plan-game", true), Times.Never); + Assert.Equal("balanced", powerPlans.Active); + } + + [Fact] + public async Task ProcessStopped_RestoresDefaultOnlyAfterLastInstanceExits() + { + var processMonitor = new FakeProcessMonitorService(); + var first = new ProcessModel { ProcessId = 21, Name = "game" }; + var second = new ProcessModel { ProcessId = 22, Name = "game" }; + var powerPlans = new PowerPlanState(); + using var manager = CreatePowerPlanManager(processMonitor, powerPlans, CreateProcessService()); + + await manager.StartAsync(); + processMonitor.RaiseProcessStarted(first); + processMonitor.RaiseProcessStarted(second); + await powerPlans.GameApplied.Task.WaitAsync(TimeSpan.FromSeconds(5)); + processMonitor.RaiseProcessStopped(first); + Assert.Equal("plan-game", powerPlans.Active); + powerPlans.Service.Verify(x => x.SetActivePowerPlanByGuidAsync("balanced", true), Times.Never); + + processMonitor.RaiseProcessStopped(second); + await powerPlans.DefaultRestored.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("balanced", powerPlans.Active); + Assert.Empty(manager.RunningAssociatedProcesses); + } + + [Fact] + public async Task Snapshot_WhenPidIsReusedByUnassociatedProcess_RestoresDefaultPlan() + { + var game = new ProcessModel { ProcessId = 21, Name = "game" }; + var monitor = new FakeProcessMonitorService { RunningProcesses = { game } }; + var plans = new PowerPlanState(); + using var manager = CreatePowerPlanManager(monitor, plans, CreateProcessService()); + + await manager.StartAsync(); + Assert.Equal("plan-game", plans.Active); + + monitor.RunningProcesses.Clear(); + monitor.RunningProcesses.Add(new ProcessModel { ProcessId = 21, Name = "unrelated" }); + await manager.EvaluateCurrentProcessesAsync(); + + Assert.Equal("balanced", plans.Active); + Assert.Empty(manager.RunningAssociatedProcesses); + } + + [Fact] + public async Task ProcessStopped_DuringPlanChange_ReevaluatesAfterTheWrite() + { + var processMonitor = new FakeProcessMonitorService(); + var game = new ProcessModel { ProcessId = 21, Name = "game" }; + var secondary = new ProcessModel { ProcessId = 22, Name = "secondary" }; + var powerPlans = new PowerPlanState(); + var writeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finishWrite = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + powerPlans.Service.Setup(x => x.SetActivePowerPlanByGuidAsync("plan-game", true)) + .Returns(async () => + { + writeStarted.TrySetResult(); + await finishWrite.Task; + return powerPlans.SetActive("plan-game"); + }); + using var manager = CreatePowerPlanManager( + processMonitor, powerPlans, CreateProcessService(), + delayMs: 25, additionalAssociation: new ProcessPowerPlanAssociation("secondary", "plan-secondary", "Secondary")); + await manager.StartAsync(); + processMonitor.RaiseProcessStarted(game); + try + { + await writeStarted.Task.WaitAsync(TimeSpan.FromSeconds(5)); + processMonitor.RaiseProcessStarted(secondary); + processMonitor.RaiseProcessStopped(game); + processMonitor.RaiseProcessStopped(secondary); + } + finally + { + finishWrite.TrySetResult(); + } + + await powerPlans.DefaultRestored.Task.WaitAsync(TimeSpan.FromSeconds(5)); + Assert.Equal("balanced", powerPlans.Active); + powerPlans.Service.Verify(x => x.SetActivePowerPlanByGuidAsync("plan-secondary", true), Times.Never); + } + + private static ProcessMonitorManagerService CreatePowerPlanManager( + FakeProcessMonitorService processMonitor, + PowerPlanState powerPlans, + Mock processService, + int delayMs = 0, + ProcessPowerPlanAssociation? additionalAssociation = null) + { + var configuration = new ProcessMonitorConfiguration + { + DefaultPowerPlanGuid = "balanced", + DefaultPowerPlanName = "Balanced", + PowerPlanChangeDelayMs = delayMs, + Associations = { new ProcessPowerPlanAssociation("game", "plan-game", "Game") }, + }; + if (additionalAssociation != null) + { + configuration.Associations.Add(additionalAssociation); + } + + processService.Setup(x => x.RefreshProcessInfo(It.IsAny())).Returns(Task.CompletedTask); + return CreateService( + processMonitor, CreateAssociationService(configuration), powerPlans.Service, + CreateNotificationService(), processService, CreateCoreMaskService(), CreateAffinityApplyService()); + } + private static ProcessMonitorManagerService CreateService( FakeProcessMonitorService processMonitorService, Mock associationService, @@ -1067,6 +1241,7 @@ private static Mock CreateProcessService() { var processService = new Mock(MockBehavior.Strict); processService.Setup(x => x.UntrackProcess(It.IsAny())); + processService.Setup(x => x.IsProcessStillRunning(It.IsAny())).ReturnsAsync(true); return processService; } @@ -1105,6 +1280,43 @@ private static Mock CreateAutoApplyService() return autoApplyService; } + private sealed class PowerPlanState + { + public PowerPlanState() + { + this.Service = CreatePowerPlanService(); + this.Service.Setup(x => x.GetActivePowerPlan()).ReturnsAsync(() => this.Current); + this.Service.Setup(x => x.SetActivePowerPlanByGuidAsync(It.IsAny(), true)) + .ReturnsAsync((string guid, bool _) => this.SetActive(guid)); + } + + public Mock Service { get; } + + public string Active { get; private set; } = "balanced"; + + public PowerPlanModel Current => new() { Guid = this.Active, Name = this.Active }; + + public TaskCompletionSource GameApplied { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource DefaultRestored { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public bool SetActive(string guid) + { + this.Active = guid; + if (guid == "plan-game") + { + this.GameApplied.TrySetResult(); + } + + if (guid == "balanced") + { + this.DefaultRestored.TrySetResult(); + } + + return true; + } + } + private sealed class FakeProcessMonitorService : IProcessMonitorService { public event EventHandler? ProcessStarted;