| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.IO; |
| | | 5 | | using System.Text.Json; |
| | | 6 | | using System.Threading; |
| | | 7 | | using System.Runtime.CompilerServices; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using SwitchBlade.Contracts; |
| | | 10 | | using SwitchBlade.Core; |
| | | 11 | | |
| | | 12 | | namespace SwitchBlade.Services |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Client that spawns the UIA Worker process for out-of-process UI Automation scanning. |
| | | 16 | | /// |
| | | 17 | | /// This eliminates UIA memory leaks by running all UIA scans in a separate process that |
| | | 18 | | /// terminates after each scan. When the process exits, Windows releases all UIA COM objects. |
| | | 19 | | /// </summary> |
| | | 20 | | public class UiaWorkerClient : IUiaWorkerClient |
| | | 21 | | { |
| | | 22 | | private readonly string _workerPath; |
| | | 23 | | private readonly ILogger? _logger; |
| | | 24 | | private readonly TimeSpan _timeout; |
| | | 25 | | private readonly IProcessFactory _processFactory; |
| | | 26 | | private readonly IFileSystem _fileSystem; |
| | | 27 | | private bool _disposed; |
| | | 28 | | |
| | | 29 | | // Concurrency management |
| | | 30 | | private IProcess? _activeProcess; |
| | 77 | 31 | | private readonly Lock _processLock = new(); |
| | 77 | 32 | | private readonly CancellationTokenSource _disposeCts = new(); |
| | | 33 | | |
| | 1 | 34 | | private static readonly JsonSerializerOptions JsonOptions = new() |
| | 1 | 35 | | { |
| | 1 | 36 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 1 | 37 | | WriteIndented = false |
| | 1 | 38 | | }; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Creates a new UIA Worker Client. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="logger">Logger for diagnostics.</param> |
| | | 44 | | /// <param name="timeout">Timeout for worker process execution. Default 10 seconds.</param> |
| | | 45 | | /// <param name="processFactory">Process factory for spawning workers.</param> |
| | | 46 | | /// <param name="fileSystem">File system abstraction.</param> |
| | 77 | 47 | | public UiaWorkerClient( |
| | 77 | 48 | | ILogger? logger = null, |
| | 77 | 49 | | TimeSpan? timeout = null, |
| | 77 | 50 | | IProcessFactory? processFactory = null, |
| | 77 | 51 | | IFileSystem? fileSystem = null) |
| | 77 | 52 | | { |
| | 77 | 53 | | _logger = logger; |
| | 77 | 54 | | _timeout = timeout ?? TimeSpan.FromSeconds(10); |
| | 77 | 55 | | _processFactory = processFactory ?? new ProcessFactory(new SystemProcessProvider()); |
| | 77 | 56 | | _fileSystem = fileSystem ?? new FileSystemWrapper(); |
| | | 57 | | |
| | | 58 | | // Find the worker executable relative to the main app |
| | 77 | 59 | | var appDir = AppContext.BaseDirectory; |
| | 77 | 60 | | _workerPath = Path.Combine(appDir, "SwitchBlade.UiaWorker.exe"); |
| | | 61 | | |
| | 77 | 62 | | if (!_fileSystem.FileExists(_workerPath)) |
| | 10 | 63 | | { |
| | 10 | 64 | | _logger?.Log($"[UiaWorkerClient] WARNING: Worker not found at {_workerPath}"); |
| | 10 | 65 | | } |
| | 77 | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Runs a UIA scan in the worker process with STREAMING results. |
| | | 70 | | /// Each plugin's results are yielded immediately as they complete. |
| | | 71 | | /// </summary> |
| | | 72 | | /// <param name="disabledPlugins">Set of disabled plugin names to skip.</param> |
| | | 73 | | /// <param name="excludedProcesses">Set of process names to exclude from scanning.</param> |
| | | 74 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 75 | | /// <returns>Async stream of plugin results as they arrive.</returns> |
| | | 76 | | public async IAsyncEnumerable<UiaPluginResult> ScanStreamingAsync( |
| | | 77 | | IEnumerable<string>? disabledPlugins = null, |
| | | 78 | | IEnumerable<string>? excludedProcesses = null, |
| | | 79 | | [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| | 64 | 80 | | { |
| | 64 | 81 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 82 | | |
| | 63 | 83 | | if (!_fileSystem.FileExists(_workerPath)) |
| | 2 | 84 | | { |
| | 2 | 85 | | _logger?.Log($"[UiaWorkerClient] Worker executable not found: {_workerPath}"); |
| | 2 | 86 | | yield break; |
| | | 87 | | } |
| | | 88 | | |
| | 61 | 89 | | var request = new UiaRequest |
| | 61 | 90 | | { |
| | 61 | 91 | | Command = "scan", |
| | 61 | 92 | | DisabledPlugins = disabledPlugins != null ? [.. disabledPlugins] : null, |
| | 61 | 93 | | ExcludedProcesses = excludedProcesses != null ? [.. excludedProcesses] : null |
| | 61 | 94 | | }; |
| | | 95 | | |
| | 61 | 96 | | var combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _disposeCts.Token); |
| | 61 | 97 | | combinedCts.CancelAfter(_timeout); |
| | | 98 | | |
| | | 99 | | // Pass Parent PID for watchdog |
| | 61 | 100 | | var currentProcess = _processFactory.GetCurrentProcess(); |
| | 60 | 101 | | int currentPid = currentProcess.Id; |
| | 60 | 102 | | var args = SwitchBlade.Core.Logger.IsDebugEnabled |
| | 60 | 103 | | ? $"/debug --parent {currentPid}" |
| | 60 | 104 | | : $"--parent {currentPid}"; |
| | | 105 | | |
| | 60 | 106 | | var psi = new ProcessStartInfo |
| | 60 | 107 | | { |
| | 60 | 108 | | FileName = _workerPath, |
| | 60 | 109 | | Arguments = args, |
| | 60 | 110 | | UseShellExecute = false, |
| | 60 | 111 | | CreateNoWindow = true, |
| | 60 | 112 | | RedirectStandardInput = true, |
| | 60 | 113 | | RedirectStandardOutput = true, |
| | 60 | 114 | | RedirectStandardError = true |
| | 60 | 115 | | }; |
| | | 116 | | |
| | | 117 | | IProcess? process; |
| | | 118 | | try |
| | 60 | 119 | | { |
| | 60 | 120 | | process = _processFactory.Start(psi); |
| | 55 | 121 | | if (process == null) |
| | 2 | 122 | | { |
| | 2 | 123 | | _logger?.Log("[UiaWorkerClient] Worker process failed to start (null return)"); |
| | 2 | 124 | | yield break; |
| | | 125 | | } |
| | 53 | 126 | | } |
| | 3 | 127 | | catch (OperationCanceledException) |
| | 3 | 128 | | { |
| | 3 | 129 | | throw; |
| | | 130 | | } |
| | 2 | 131 | | catch (Exception ex) |
| | 2 | 132 | | { |
| | 2 | 133 | | _logger?.LogError($"[UiaWorkerClient] Failed to start worker process", ex); |
| | 2 | 134 | | yield break; |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | lock (_processLock) |
| | 53 | 138 | | { |
| | 53 | 139 | | if (_disposed) |
| | 1 | 140 | | { |
| | 3 | 141 | | try { process.Kill(entireProcessTree: true); } catch { } |
| | 1 | 142 | | process.Dispose(); |
| | 1 | 143 | | throw new ObjectDisposedException(nameof(UiaWorkerClient)); |
| | | 144 | | } |
| | 52 | 145 | | _activeProcess = process; |
| | 52 | 146 | | } |
| | | 147 | | |
| | 52 | 148 | | _logger?.Log($"[UiaWorkerClient] Starting streaming worker: {_workerPath} (ParentPID={currentPid})"); |
| | 52 | 149 | | var startTime = Stopwatch.GetTimestamp(); |
| | | 150 | | |
| | | 151 | | // Send request via stdin |
| | | 152 | | try |
| | 52 | 153 | | { |
| | 52 | 154 | | string requestJson = JsonSerializer.Serialize(request, JsonOptions); |
| | 52 | 155 | | await process.StandardInput.WriteLineAsync(requestJson); |
| | 50 | 156 | | await process.StandardInput.FlushAsync(cancellationToken); |
| | 50 | 157 | | process.StandardInput.Close(); |
| | 50 | 158 | | } |
| | 2 | 159 | | catch (Exception ex) |
| | 2 | 160 | | { |
| | 2 | 161 | | _logger?.LogError($"[UiaWorkerClient] Failed to send request to worker", ex); |
| | | 162 | | // Continue to cleanup |
| | 2 | 163 | | } |
| | | 164 | | |
| | 52 | 165 | | process.ErrorDataReceived += (s, e) => |
| | 4 | 166 | | { |
| | 4 | 167 | | if (!string.IsNullOrEmpty(e.Data)) |
| | 2 | 168 | | { |
| | 52 | 169 | | // Log worker stderr to main log with a prefix |
| | 2 | 170 | | _logger?.Log($"[UiaWorker STDERR] {e.Data}"); |
| | 2 | 171 | | } |
| | 56 | 172 | | }; |
| | 52 | 173 | | process.BeginErrorReadLine(); |
| | | 174 | | |
| | | 175 | | // Read streaming responses line by line (STDOUT) |
| | | 176 | | try |
| | 52 | 177 | | { |
| | 69 | 178 | | while (!combinedCts.Token.IsCancellationRequested) |
| | 68 | 179 | | { |
| | | 180 | | string? line; |
| | | 181 | | try |
| | 68 | 182 | | { |
| | 68 | 183 | | line = await process.StandardOutput.ReadLineAsync(combinedCts.Token); |
| | 56 | 184 | | } |
| | 4 | 185 | | catch (OperationCanceledException) |
| | 4 | 186 | | { |
| | | 187 | | // Explicitly caught - this is the expected path for timeouts |
| | 4 | 188 | | _logger?.Log("[UiaWorkerClient] Streaming read cancelled/timed out."); |
| | 16 | 189 | | try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } |
| | 4 | 190 | | yield break; |
| | | 191 | | } |
| | | 192 | | |
| | 56 | 193 | | if (line == null) |
| | 22 | 194 | | { |
| | | 195 | | // Process ended or closed stdout |
| | 22 | 196 | | break; |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | // Final check before yielding: if we were cancelled during the read, don't return partial garbage |
| | 34 | 200 | | if (combinedCts.Token.IsCancellationRequested) |
| | 2 | 201 | | { |
| | 2 | 202 | | _logger?.Log("[UiaWorkerClient] Streaming read cancelled/timed out."); |
| | 8 | 203 | | try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } |
| | 2 | 204 | | yield break; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | UiaPluginResult? result; |
| | | 208 | | try |
| | 32 | 209 | | { |
| | 32 | 210 | | result = JsonSerializer.Deserialize<UiaPluginResult>(line, JsonOptions); |
| | 28 | 211 | | } |
| | 4 | 212 | | catch (JsonException ex) |
| | 4 | 213 | | { |
| | 4 | 214 | | _logger?.Log($"[UiaWorkerClient] Failed to parse streaming line: {ex.Message}"); |
| | 4 | 215 | | continue; |
| | | 216 | | } |
| | | 217 | | |
| | 28 | 218 | | if (result == null) |
| | 2 | 219 | | continue; |
| | | 220 | | |
| | 26 | 221 | | if (result.IsFinal) |
| | 15 | 222 | | { |
| | 15 | 223 | | _logger?.Log("[UiaWorkerClient] Received final marker."); |
| | 15 | 224 | | break; |
| | | 225 | | } |
| | | 226 | | |
| | 11 | 227 | | _logger?.Log($"[UiaWorkerClient] Received {result.Windows?.Count ?? 0} windows from {result.PluginNa |
| | 11 | 228 | | yield return result; |
| | 11 | 229 | | } |
| | | 230 | | |
| | | 231 | | // If we exited the loop naturally but cancellation was requested, log it. |
| | | 232 | | // This handles cases where ReadLineAsync might return a cached line or finish just as the token is canc |
| | 38 | 233 | | if (combinedCts.Token.IsCancellationRequested) |
| | 3 | 234 | | { |
| | 3 | 235 | | _logger?.Log("[UiaWorkerClient] Streaming read cancelled/timed out."); |
| | 3 | 236 | | } |
| | 38 | 237 | | } |
| | | 238 | | finally |
| | 46 | 239 | | { |
| | | 240 | | // Ensure active process is cleared |
| | | 241 | | lock (_processLock) |
| | 46 | 242 | | { |
| | 46 | 243 | | _activeProcess = null; |
| | 46 | 244 | | } |
| | | 245 | | |
| | | 246 | | // Wait for process to exit or kill if needed |
| | | 247 | | try |
| | 46 | 248 | | { |
| | 46 | 249 | | if (!process.HasExited) |
| | 43 | 250 | | { |
| | | 251 | | try |
| | 43 | 252 | | { |
| | 43 | 253 | | if (combinedCts.Token.IsCancellationRequested) |
| | 9 | 254 | | { |
| | 9 | 255 | | process.Kill(entireProcessTree: true); |
| | 9 | 256 | | } |
| | | 257 | | else |
| | 34 | 258 | | { |
| | 34 | 259 | | await process.WaitForExitAsync(combinedCts.Token); |
| | 28 | 260 | | } |
| | 37 | 261 | | } |
| | 6 | 262 | | catch |
| | 6 | 263 | | { |
| | 12 | 264 | | if (!process.HasExited) process.Kill(entireProcessTree: true); |
| | 2 | 265 | | } |
| | 39 | 266 | | } |
| | 41 | 267 | | } |
| | 5 | 268 | | catch (Exception ex) |
| | 5 | 269 | | { |
| | 5 | 270 | | _logger?.Log($"[UiaWorkerClient] Error during process cleanup: {ex.Message}"); |
| | 23 | 271 | | try { if (!process.HasExited) process.Kill(entireProcessTree: true); } catch { } |
| | 5 | 272 | | } |
| | | 273 | | |
| | 46 | 274 | | process.Dispose(); |
| | 46 | 275 | | combinedCts.Dispose(); |
| | | 276 | | |
| | 46 | 277 | | var elapsed = Stopwatch.GetElapsedTime(startTime); |
| | 46 | 278 | | _logger?.Log($"[UiaWorkerClient] Streaming worker completed in {elapsed.TotalMilliseconds:F0}ms"); |
| | 46 | 279 | | } |
| | 50 | 280 | | } |
| | | 281 | | |
| | | 282 | | /// <summary> |
| | | 283 | | /// Runs a UIA scan in the worker process. |
| | | 284 | | /// Convenience wrapper that collects all streaming results into a single list. |
| | | 285 | | /// </summary> |
| | | 286 | | /// <param name="disabledPlugins">Set of disabled plugin names to skip.</param> |
| | | 287 | | /// <param name="excludedProcesses">Set of process names to exclude from scanning.</param> |
| | | 288 | | /// <param name="cancellationToken">Cancellation token.</param> |
| | | 289 | | /// <returns>List of discovered windows, or empty list on failure.</returns> |
| | | 290 | | public async Task<List<WindowItem>> ScanAsync( |
| | | 291 | | IEnumerable<string>? disabledPlugins = null, |
| | | 292 | | IEnumerable<string>? excludedProcesses = null, |
| | | 293 | | CancellationToken cancellationToken = default) |
| | 23 | 294 | | { |
| | 23 | 295 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 296 | | |
| | 22 | 297 | | if (!_fileSystem.FileExists(_workerPath)) |
| | 3 | 298 | | { |
| | 3 | 299 | | _logger?.Log($"[UiaWorkerClient] Worker executable not found: {_workerPath}"); |
| | 3 | 300 | | return []; |
| | | 301 | | } |
| | | 302 | | |
| | 19 | 303 | | var allWindows = new List<WindowItem>(); |
| | | 304 | | |
| | | 305 | | try |
| | 19 | 306 | | { |
| | 73 | 307 | | await foreach (var result in ScanStreamingAsync(disabledPlugins, excludedProcesses, cancellationToken)) |
| | 8 | 308 | | { |
| | 8 | 309 | | if (result.Error != null) |
| | 3 | 310 | | { |
| | 3 | 311 | | _logger?.Log($"[UiaWorkerClient] Plugin {result.PluginName} error: {result.Error}"); |
| | 3 | 312 | | } |
| | | 313 | | |
| | 8 | 314 | | allWindows.AddRange(ConvertToWindowItems(result.Windows)); |
| | 8 | 315 | | } |
| | 14 | 316 | | return allWindows; |
| | | 317 | | } |
| | 3 | 318 | | catch (OperationCanceledException) |
| | 3 | 319 | | { |
| | 3 | 320 | | _logger?.Log("[UiaWorkerClient] Scan cancelled."); |
| | 3 | 321 | | return allWindows; |
| | | 322 | | } |
| | 2 | 323 | | catch (Exception ex) |
| | 2 | 324 | | { |
| | 2 | 325 | | _logger?.LogError("[UiaWorkerClient] ScanAsync failed mid-stream", ex); |
| | 2 | 326 | | return allWindows; |
| | | 327 | | } |
| | 22 | 328 | | } |
| | | 329 | | |
| | | 330 | | private static List<WindowItem> ConvertToWindowItems(List<UiaWindowResult>? results) |
| | 12 | 331 | | { |
| | 12 | 332 | | if (results == null || results.Count == 0) |
| | 7 | 333 | | return []; |
| | | 334 | | |
| | 5 | 335 | | var items = new List<WindowItem>(results.Count); |
| | 25 | 336 | | foreach (var r in results) |
| | 5 | 337 | | { |
| | 5 | 338 | | items.Add(new WindowItem |
| | 5 | 339 | | { |
| | 5 | 340 | | Hwnd = new IntPtr(r.Hwnd), |
| | 5 | 341 | | Title = r.Title, |
| | 5 | 342 | | ProcessName = r.ProcessName, |
| | 5 | 343 | | ExecutablePath = r.ExecutablePath, |
| | 5 | 344 | | IsFallback = r.IsFallback, |
| | 5 | 345 | | Source = null |
| | 5 | 346 | | }); |
| | 5 | 347 | | } |
| | 5 | 348 | | return items; |
| | 12 | 349 | | } |
| | | 350 | | |
| | | 351 | | public void Dispose() |
| | 15 | 352 | | { |
| | | 353 | | lock (_processLock) |
| | 15 | 354 | | { |
| | 17 | 355 | | if (_disposed) return; |
| | 13 | 356 | | _disposed = true; |
| | | 357 | | |
| | 13 | 358 | | _disposeCts.Cancel(); |
| | | 359 | | |
| | 13 | 360 | | if (_activeProcess != null) |
| | 8 | 361 | | { |
| | | 362 | | try |
| | 8 | 363 | | { |
| | 8 | 364 | | if (!_activeProcess.HasExited) |
| | 7 | 365 | | { |
| | 7 | 366 | | _logger?.Log($"[UiaWorkerClient] Dispose called - killing active worker PID {_activeProcess. |
| | 7 | 367 | | _activeProcess.Kill(entireProcessTree: true); |
| | 4 | 368 | | } |
| | 5 | 369 | | } |
| | 3 | 370 | | catch (Exception ex) |
| | 3 | 371 | | { |
| | 3 | 372 | | _logger?.Log($"[UiaWorkerClient] Failed to kill active process on Dispose: {ex.Message}"); |
| | 3 | 373 | | } |
| | | 374 | | finally |
| | 8 | 375 | | { |
| | 8 | 376 | | _activeProcess = null; |
| | 8 | 377 | | } |
| | 8 | 378 | | } |
| | 13 | 379 | | } |
| | | 380 | | |
| | 13 | 381 | | _disposeCts.Dispose(); |
| | 13 | 382 | | GC.SuppressFinalize(this); |
| | 15 | 383 | | } |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | } |