using System.Collections.Concurrent; using System.IO; using System.IO.Pipes; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Ipc; using ClassNotify.Shared.Models; using ClassNotify.Shared.Services; namespace ClassNotify.Client.Services { public class IpcClient { private readonly string _pipeName; private readonly Dispatcher _dispatcher; private NamedPipeClientStream? _pipeStream; private StreamWriter? _writer; private MainWindow? _currentWindow; private TaskCompletionSource<(bool Success, string Message)>? _renewTcs; private TaskCompletionSource<(bool Success, string Message, string? ClassName, string? ExpireDate)>? _activateTcs; private TaskCompletionSource? _clientStateTcs; private TaskCompletionSource<(bool Success, string Message)>? _updateClassNameTcs; private TaskCompletionSource<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)>? _pairingModeTcs; private TaskCompletionSource? _pairingSessionTcs; public event Action? OnClassDisplayNameChanged; public event Action? OnEnterPairingMode; private DeviceLicenseStatusDto? _currentLicenseStatus; private static readonly ClientNotificationDeduplicator _deduplicator = new(); private readonly object _pipeLock = new(); private readonly string? _ipcToken; public IpcClient(Dispatcher dispatcher, string pipeName = "ClassNotify_Ipc_Pipe", string? ipcToken = null) { _dispatcher = dispatcher; _pipeName = pipeName; _ipcToken = ipcToken ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_IPC_TOKEN"); } public void Start(CancellationToken cancellationToken) { Task.Run(async () => { while (!cancellationToken.IsCancellationRequested) { try { _pipeStream = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await _pipeStream.ConnectAsync(5000, cancellationToken); _writer = new StreamWriter(_pipeStream, Encoding.UTF8) { AutoFlush = true }; var reader = new StreamReader(_pipeStream, Encoding.UTF8); // Send Hello handshake immediately upon connection (Protocol Version 2 with Launch Token) var helloJson = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = _ipcToken ?? string.Empty }); await _writer.WriteLineAsync(helloJson); await _writer.FlushAsync(); while (_pipeStream.IsConnected && !cancellationToken.IsCancellationRequested) { var line = await reader.ReadLineAsync(cancellationToken); if (string.IsNullOrEmpty(line)) break; ProcessIpcMessage(line); } } catch (OperationCanceledException) { break; } catch { await Task.Delay(3000, cancellationToken); } finally { lock (_pipeLock) { _writer?.Dispose(); _writer = null; _pipeStream?.Dispose(); _pipeStream = null; } } } }, cancellationToken); } private void Log(string msg) { try { var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "logs"); Directory.CreateDirectory(logDir); var logFile = Path.Combine(logDir, "client.log"); File.AppendAllText(logFile, $"[{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] [IpcClient] {msg}\r\n"); } catch { } } private void ProcessIpcMessage(string json) { try { var msg = JsonSerializer.Deserialize(json); if (msg == null) return; Log($"Received IPC command: type={msg.Type}"); if (msg.Type == IpcCommandType.Ping) { SendPong(); return; } if (msg.Type == IpcCommandType.TtsCheck) { CheckTtsAndReply(); return; } if (msg.Type == IpcCommandType.UpdateLicenseStatus && !string.IsNullOrEmpty(msg.PayloadJson)) { var status = JsonSerializer.Deserialize(msg.PayloadJson); if (status != null) { HandleLicenseStatus(status); } return; } if (msg.Type == IpcCommandType.RenewResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); bool ok = doc.RootElement.GetProperty("success").GetBoolean(); string replyMsg = doc.RootElement.GetProperty("message").GetString() ?? string.Empty; _renewTcs?.TrySetResult((ok, replyMsg)); } catch (Exception ex) { Log($"[License] Failed to parse RenewResult: {ex.Message}"); _renewTcs?.TrySetResult((false, "解析续费响应失败")); } return; } if (msg.Type == IpcCommandType.ActivateResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); bool ok = doc.RootElement.GetProperty("success").GetBoolean(); string replyMsg = doc.RootElement.GetProperty("message").GetString() ?? string.Empty; string? className = doc.RootElement.TryGetProperty("className", out var cn) ? cn.GetString() : null; string? expireDate = doc.RootElement.TryGetProperty("expireDate", out var ed) ? ed.GetString() : null; _activateTcs?.TrySetResult((ok, replyMsg, className, expireDate)); } catch (Exception ex) { Log($"[Activation] Failed to parse ActivateResult: {ex.Message}"); _activateTcs?.TrySetResult((false, "解析激活响应失败", null, null)); } return; } if (msg.Type == IpcCommandType.ClientStateResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { var state = JsonSerializer.Deserialize(msg.PayloadJson); _clientStateTcs?.TrySetResult(state); } catch (Exception ex) { Log($"[ClientState] Failed to parse ClientStateResult: {ex.Message}"); _clientStateTcs?.TrySetResult(null); } return; } if (msg.Type == IpcCommandType.UpdateClassNameResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); bool ok = doc.RootElement.GetProperty("success").GetBoolean(); string replyMsg = doc.RootElement.GetProperty("message").GetString() ?? string.Empty; _updateClassNameTcs?.TrySetResult((ok, replyMsg)); } catch (Exception ex) { Log($"[ClassName] Failed to parse UpdateClassNameResult: {ex.Message}"); _updateClassNameTcs?.TrySetResult((false, "解析更新班级响应失败")); } return; } if (msg.Type == IpcCommandType.PairingModeResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); bool ok = doc.RootElement.GetProperty("success").GetBoolean(); string? code = doc.RootElement.TryGetProperty("pairingCode", out var c) ? c.GetString() : null; int ttl = doc.RootElement.TryGetProperty("ttlSeconds", out var t) ? t.GetInt32() : 600; string? err = doc.RootElement.TryGetProperty("errorMessage", out var e) ? e.GetString() : null; _pairingModeTcs?.TrySetResult((ok, code, ttl, err)); } catch (Exception ex) { Log($"[Pairing] Failed to parse PairingModeResult: {ex.Message}"); _pairingModeTcs?.TrySetResult((false, null, 0, "解析配对响应失败")); } return; } if (msg.Type == IpcCommandType.PairingSessionResult && !string.IsNullOrEmpty(msg.PayloadJson)) { try { var session = JsonSerializer.Deserialize(msg.PayloadJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); _pairingSessionTcs?.TrySetResult(session ?? new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "解析响应为空" }); } catch (Exception ex) { Log($"[Pairing] Failed to parse PairingSessionResult: {ex.Message}"); _pairingSessionTcs?.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "解析配对响应失败" }); } return; } if (msg.Type == IpcCommandType.ClassDisplayNameChanged && !string.IsNullOrEmpty(msg.PayloadJson)) { try { string newName = msg.PayloadJson.Trim('"'); if (msg.PayloadJson.Trim().StartsWith("{")) { using var doc = JsonDocument.Parse(msg.PayloadJson); if (doc.RootElement.TryGetProperty("className", out var cn)) { newName = cn.GetString() ?? ""; } } if (!string.IsNullOrEmpty(newName)) { Log($"[ClassName] Class display name updated via IPC push: {newName}"); _dispatcher.Invoke(() => OnClassDisplayNameChanged?.Invoke(newName)); } } catch (Exception ex) { Log($"[ClassName] Error handling ClassDisplayNameChanged IPC: {ex.Message}"); } return; } if (msg.Type == IpcCommandType.EnterPairingMode && !string.IsNullOrEmpty(msg.PayloadJson)) { try { using var doc = JsonDocument.Parse(msg.PayloadJson); string pairingCode = doc.RootElement.GetProperty("PairingCode").GetString() ?? ""; int ttl = doc.RootElement.GetProperty("TtlSeconds").GetInt32(); Log($"[PairingMode] Received EnterPairingMode push: Code={pairingCode}, TTL={ttl}s"); _dispatcher.Invoke(() => OnEnterPairingMode?.Invoke(pairingCode, ttl)); } catch (Exception ex) { Log($"[PairingMode] Error handling EnterPairingMode IPC: {ex.Message}"); } return; } if (msg.Type == IpcCommandType.CloseNotification) { AudioTtsService.Stop(); var cancelledNotifId = msg.PayloadJson; _dispatcher.Invoke(() => { if (_currentWindow != null) { Log($"[Cancel] Closing current notification window due to CloseNotification IPC."); _currentWindow.Close(); _currentWindow = null; } }); if (!string.IsNullOrEmpty(cancelledNotifId)) { SendAck(cancelledNotifId, string.Empty, AckStatus.Cancelled); Log($"[Cancel] Dispatched Cancelled ACK receipt for notification {cancelledNotifId}"); } return; } if (msg.Type == IpcCommandType.ShowNotification && !string.IsNullOrEmpty(msg.PayloadJson)) { var notification = JsonSerializer.Deserialize(msg.PayloadJson); if (notification != null) { // P1 Batch 9: Client-side idempotent duplicate suppression for at-least-once delivery if (!_deduplicator.TryProcess(notification.Id)) { Log($"[Idempotent] Notification {notification.Id} already processed. Suppressing duplicate window & TTS."); SendAck(notification.Id, notification.ClassId, AckStatus.Delivered, notification.CorrelationId); return; } // P79 Layer 2 LocalLicenseGuard: Emergency bypasses; normal notifications blocked if license expired or invalid if (notification.Type != ClassNotify.Shared.Enums.NotificationType.Urgent) { if (_currentLicenseStatus != null) { bool isExp = _currentLicenseStatus.Status == "Expired" || (_currentLicenseStatus.LicensedUntilUtc.HasValue && DateTimeOffset.UtcNow > _currentLicenseStatus.LicensedUntilUtc.Value); if (isExp || !_currentLicenseStatus.CanReceiveNormalNotifications) { Log($"[LocalLicenseGuard] Suppressing normal notification {notification.Id} due to license expiration (Status={_currentLicenseStatus.Status}, LicensedUntil={_currentLicenseStatus.LicensedUntilUtc:u})"); SendAck(notification.Id, notification.ClassId, AckStatus.Delivered, notification.CorrelationId); return; } } } try { _dispatcher.Invoke(() => { _currentWindow?.Close(); _currentWindow = new MainWindow(notification, (status) => { SendAck(notification.Id, notification.ClassId, status, notification.CorrelationId); }); _currentWindow.Show(); _currentWindow.Activate(); // P0-05 Fix: Report Delivered ONLY after the window is actually displayed on screen SendAck(notification.Id, notification.ClassId, AckStatus.Delivered, notification.CorrelationId); // P2.3: Capture visual receipt after short delay to allow UI to render (robust retry loop) var win = _currentWindow; var notifId = notification.Id; Task.Run(async () => { try { byte[]? jpeg = null; for (int attempt = 1; attempt <= 6; attempt++) { await Task.Delay(350); await _dispatcher.InvokeAsync(() => { if (win != null && win.IsVisible && win.ActualWidth > 0) { jpeg = SimpleVisualReceipt.Capture(win); } }); if (jpeg != null && jpeg.Length > 0) { Log($"[VisualReceipt] Captured on attempt {attempt} ({jpeg.Length} bytes)"); break; } } if (jpeg != null && jpeg.Length > 0) { await ReportVisualReceiptAsync(notifId, jpeg); } else { Log($"[VisualReceipt] Could not capture visual receipt after 6 attempts for {notifId}"); } } catch (Exception ex) { Log($"[VisualReceipt] Failed to capture/send visual receipt: {ex.Message}"); } }); }); } catch (Exception ex) { Log($"[NotificationRenderError] Failed to render notification {notification.Id}: {ex}"); try { _dispatcher.Invoke(() => { _currentWindow?.Close(); _currentWindow = null; }); } catch { } // Turn 81 Brain Invariant: Level 1 Notification Boundary Exception Interception // Immediately dispatch Failed ACK with sanitized failure code and user-friendly explanation SendAck( notification.Id, notification.ClassId, AckStatus.Failed, notification.CorrelationId, failureCode: "DISPLAY_RENDER_FAILED", failureReason: "大屏显示渲染异常,正在自动恢复"); } } } } catch (Exception ex) { Log($"Error in ProcessIpcMessage: {ex}"); } } private static TtsCheckResultDto? _cachedTtsCheckResult; private static readonly object _ttsCheckLock = new(); private void CheckTtsAndReply() { try { TtsCheckResultDto resultDto; lock (_ttsCheckLock) { if (_cachedTtsCheckResult != null) { resultDto = _cachedTtsCheckResult; } else { Log("Performing one-time TTS engine availability check..."); using var synth = new System.Speech.Synthesis.SpeechSynthesizer(); var voices = synth.GetInstalledVoices(); int voiceCount = voices.Count; bool available = voiceCount > 0; Log($"TTS check completed: available={available}, voiceCount={voiceCount}"); resultDto = new TtsCheckResultDto { Available = available, VoiceCount = voiceCount }; _cachedTtsCheckResult = resultDto; } } var replyMsg = new IpcMessage { Type = IpcCommandType.TtsCheckResult, PayloadJson = JsonSerializer.Serialize(resultDto) }; lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { _writer.WriteLine(JsonSerializer.Serialize(replyMsg)); _writer.Flush(); Log("Sent TtsCheckResult to Service."); } else { Log($"Failed to send TtsCheckResult: writer={_writer != null}, stream={_pipeStream != null}, connected={_pipeStream?.IsConnected}"); } } } catch (Exception ex) { Log($"Exception in CheckTtsAndReply: {ex}"); var resultDto = new TtsCheckResultDto { Available = false, VoiceCount = 0 }; var replyMsg = new IpcMessage { Type = IpcCommandType.TtsCheckResult, PayloadJson = JsonSerializer.Serialize(resultDto) }; lock (_pipeLock) { _writer?.WriteLine(JsonSerializer.Serialize(replyMsg)); _writer?.Flush(); } } } private void SendPong() { try { lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { var pongMsg = new IpcMessage { Type = IpcCommandType.Pong, PayloadJson = DateTimeOffset.UtcNow.ToString("O") }; _writer.WriteLine(JsonSerializer.Serialize(pongMsg)); } } } catch { } } private void SendAck(string msgId, string classId, AckStatus status, string? correlationId = null, string? failureCode = null, string? failureReason = null) { try { lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { var ack = new AckReceiptDto { MessageId = msgId, ClassId = classId, Status = status, CorrelationId = correlationId ?? string.Empty, FailureCode = failureCode, FailureReason = failureReason, Remark = failureReason, Timestamp = DateTimeOffset.UtcNow }; var ipcMsg = new IpcMessage { Type = IpcCommandType.ReportAck, PayloadJson = JsonSerializer.Serialize(ack) }; _writer.WriteLine(JsonSerializer.Serialize(ipcMsg)); } } } catch { } } public async Task ReportVisualReceiptAsync(string notificationId, byte[] jpegBytes) { try { if (string.IsNullOrWhiteSpace(notificationId) || jpegBytes == null || jpegBytes.Length == 0) return; if (jpegBytes.Length > 512 * 1024) { Log($"[VisualReceipt] Payload exceeds 512 KiB ({jpegBytes.Length} bytes). Discarding."); return; } var dto = new VisualReceiptIpcDto { NotificationId = notificationId, JpegBytes = jpegBytes }; var ipcMsg = new IpcMessage { Type = IpcCommandType.ReportVisualReceipt, PayloadJson = JsonSerializer.Serialize(dto) }; lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { _writer.WriteLine(JsonSerializer.Serialize(ipcMsg)); _writer.Flush(); Log($"[VisualReceipt] Sent visual receipt to Service for notification {notificationId} ({jpegBytes.Length} bytes)"); } } await Task.CompletedTask; } catch (Exception ex) { Log($"[VisualReceipt] Error sending visual receipt: {ex.Message}"); } } public async Task<(bool Success, string Message)> RequestRenewAsync(string code) { var tcs = new TaskCompletionSource<(bool Success, string Message)>(TaskCreationOptions.RunContinuationsAsynchronously); _renewTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.RequestRenew, PayloadJson = code }; await SendIpcMessageAsync(msg); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); cts.Token.Register(() => tcs.TrySetResult((false, "请求服务器超时,请检查网络"))); try { return await tcs.Task; } finally { _renewTcs = null; } } public async Task<(bool Success, string Message, string? ClassName, string? ExpireDate)> RequestActivateAsync(string code, string? customClassName = null) { var maskedCode = string.IsNullOrWhiteSpace(code) ? "****" : (code.Length > 4 ? "****" + code[^4..] : "****"); Log($"[IpcClient] RequestActivateAsync: Sending IPC RequestActivate to Service with code='{maskedCode}', customClassName='{customClassName}'"); var tcs = new TaskCompletionSource<(bool Success, string Message, string? ClassName, string? ExpireDate)>(TaskCreationOptions.RunContinuationsAsynchronously); _activateTcs = tcs; var reqDto = new DeviceActivationRequestDto { ActivationCode = code, CustomClassName = customClassName, HardwareComponentsHash = ClassNotify.Service.Services.HardwareFingerprintProvider.GetHardwareComponentsHash(), FingerprintVersion = 1 }; var msg = new IpcMessage { Type = IpcCommandType.RequestActivate, PayloadJson = JsonSerializer.Serialize(reqDto) }; bool sent = await SendIpcMessageAsync(msg); if (!sent) { _activateTcs = null; return (false, "无法连接到后台服务,请确认服务已启动", null, null); } using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); cts.Token.Register(() => tcs.TrySetResult((false, "请求服务器超时,请检查网络", null, null))); try { return await tcs.Task; } finally { _activateTcs = null; } } public async Task<(bool Success, string Message)> RequestUpdateClassNameAsync(string newClassName) { var tcs = new TaskCompletionSource<(bool Success, string Message)>(TaskCreationOptions.RunContinuationsAsynchronously); _updateClassNameTcs = tcs; var reqDto = new UpdateClassNameRequestDto { ClassName = newClassName }; var msg = new IpcMessage { Type = IpcCommandType.RequestUpdateClassName, PayloadJson = JsonSerializer.Serialize(reqDto) }; bool sent = await SendIpcMessageAsync(msg); if (!sent) { _updateClassNameTcs = null; return (false, "无法连接到后台服务,请确认服务运行正常"); } using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); cts.Token.Register(() => tcs.TrySetResult((false, "请求更新班级名称超时,请检查网络"))); try { return await tcs.Task; } finally { _updateClassNameTcs = null; } } public async Task<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)> RequestStartPairingAsync() { var tcs = new TaskCompletionSource<(bool Success, string? PairingCode, int TtlSeconds, string? ErrorMessage)>(TaskCreationOptions.RunContinuationsAsynchronously); _pairingModeTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.RequestPairingMode, PayloadJson = "{}" }; bool sent = await SendIpcMessageAsync(msg); if (!sent) { _pairingModeTcs = null; return (false, null, 0, "无法连接到后台服务,请确认服务运行正常"); } using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); cts.Token.Register(() => tcs.TrySetResult((false, null, 0, "请求配对码超时,请重试"))); try { return await tcs.Task; } finally { _pairingModeTcs = null; } } public async Task RequestPairingSessionAsync(PairingPurpose purpose) { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _pairingSessionTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.RequestPairingSession, PayloadJson = JsonSerializer.Serialize(new { purpose = purpose.ToString() }) }; bool sent = await SendIpcMessageAsync(msg); if (!sent) { _pairingSessionTcs = null; return new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "无法连接到后台服务,请确认服务运行正常" }; } using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); cts.Token.Register(() => tcs.TrySetResult(new PairingSessionDto { State = PairingSessionState.Failed, ErrorMessage = "请求配对码超时,请重试" })); try { return await tcs.Task; } finally { _pairingSessionTcs = null; } } public async Task GetClientStateAsync() { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); _clientStateTcs = tcs; var msg = new IpcMessage { Type = IpcCommandType.GetClientState, PayloadJson = "{}" }; bool sent = await SendIpcMessageAsync(msg); if (!sent) { _clientStateTcs = null; return null; } using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); cts.Token.Register(() => tcs.TrySetResult(null)); try { return await tcs.Task; } finally { _clientStateTcs = null; } } private async Task SendIpcMessageAsync(IpcMessage msg) { // Immediate check first lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { try { _writer.WriteLine(JsonSerializer.Serialize(msg)); _writer.Flush(); return true; } catch (Exception ex) { Log($"[IpcClient] Error sending IPC message immediately: {ex.Message}"); } } } // Quick poll if pipe is still initializing (max 600ms) var deadline = DateTimeOffset.UtcNow.AddMilliseconds(600); while (DateTimeOffset.UtcNow < deadline) { await Task.Delay(50); lock (_pipeLock) { if (_writer != null && _pipeStream != null && _pipeStream.IsConnected) { try { _writer.WriteLine(JsonSerializer.Serialize(msg)); _writer.Flush(); return true; } catch (Exception ex) { Log($"[IpcClient] Error sending IPC message in poll: {ex.Message}"); return false; } } } } Log("[IpcClient] SendIpcMessageAsync timed out (pipe not connected)."); return false; } private void HandleLicenseStatus(DeviceLicenseStatusDto status) { _currentLicenseStatus = status; Log($"[License] Updated status: Status={status.Status}, Tier={status.Tier}, RemainingDays={status.RemainingDays}"); if (status.Status == "Valid" || status.Status == "Perpetual" || status.Status == "OfflineGrace") { return; } // Frequency limiter: at most once per server calendar day (Server-Authoritative Clock & Persistence) try { var appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var dir = Path.Combine(appData, "ClassNotify"); Directory.CreateDirectory(dir); var flagFile = Path.Combine(dir, "license_last_remind_date.txt"); var todayKey = !string.IsNullOrWhiteSpace(status.ReminderDateKey) ? status.ReminderDateKey : status.ServerNowUtc.ToOffset(TimeSpan.FromHours(8)).ToString("yyyy-MM-dd"); if (File.Exists(flagFile)) { var lastRemind = File.ReadAllText(flagFile).Trim(); if (lastRemind == todayKey) { Log($"[License] Daily reminder already shown today for key {todayKey}, suppressing popup."); return; } } File.WriteAllText(flagFile, todayKey); } catch (Exception ex) { Log($"[License] Warning checking reminder flag: {ex.Message}"); } _dispatcher.Invoke(() => { var reminder = new LicenseReminderWindow(status, () => { var renewDialog = new RenewDialog(async (code) => { return await RequestRenewAsync(code); }); renewDialog.ShowDialog(); }); reminder.Show(); }); } public void AcknowledgeCurrentWindow() { _dispatcher.Invoke(() => { if (_currentWindow != null) { Log("[Acknowledge] Invoking BtnAcknowledge on active display window."); _currentWindow.SimulateAcknowledgeClick(); } else { Log("[Acknowledge] Warning: No active notification window found to acknowledge."); } }); } } }