using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using ClassNotify.Client.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Policies; namespace ClassNotify.Client { public partial class App : Application { private IpcClient? _ipcClient; private readonly CancellationTokenSource _cts = new(); private Mutex? _singletonMutex; private Window? _activeUiWindow; public static void LogClient(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}] [PID={Environment.ProcessId}] {msg}\r\n"); } catch { } } protected override void OnStartup(StartupEventArgs e) { this.ShutdownMode = ShutdownMode.OnExplicitShutdown; base.OnStartup(e); this.DispatcherUnhandledException += (s, args) => { var ex = args.Exception; LogClient($"DispatcherUnhandledException: {ex}"); // Brain Turn 81 Invariant: // Fatal process-corrupting exceptions (OOM, StackOverflow, Native/SEH) must NOT be suppressed with Handled=true. // Allow process to terminate cleanly and let ClassNotify.Service watchdog restart the client. if (ex is OutOfMemoryException || ex is StackOverflowException || ex is System.Runtime.InteropServices.SEHException) { LogClient($"Fatal unrecoverable exception encountered ({ex.GetType().Name}). Allowing clean process exit for Service watchdog restart."); args.Handled = false; return; } // Recoverable UI/rendering exception: mark handled to keep client alive args.Handled = true; }; AppDomain.CurrentDomain.UnhandledException += (s, args) => { LogClient($"AppDomain.UnhandledException: IsTerminating={args.IsTerminating}, Error={args.ExceptionObject}"); }; TaskScheduler.UnobservedTaskException += (s, args) => { LogClient($"TaskScheduler.UnobservedTaskException: {args.Exception}"); args.SetObserved(); }; int currentSessionId = Process.GetCurrentProcess().SessionId; var cmdArgs = Environment.GetCommandLineArgs(); LogClient($"Client process starting (SessionId={currentSessionId}, CmdLine={Environment.CommandLine})"); // Extract --ipc-token and --ipc-launch-id string? ipcToken = null; string? launchId = null; for (int i = 0; i < cmdArgs.Length; i++) { if (cmdArgs[i] == "--ipc-token" && i + 1 < cmdArgs.Length) { ipcToken = cmdArgs[i + 1]; } else if (cmdArgs[i] == "--ipc-launch-id" && i + 1 < cmdArgs.Length) { launchId = cmdArgs[i + 1]; } } if (string.IsNullOrEmpty(ipcToken) && e.Args != null) { for (int i = 0; i < e.Args.Length; i++) { if (e.Args[i] == "--ipc-token" && i + 1 < e.Args.Length) { ipcToken = e.Args[i + 1]; } else if (e.Args[i] == "--ipc-launch-id" && i + 1 < e.Args.Length) { launchId = e.Args[i + 1]; } } } if (string.IsNullOrEmpty(ipcToken)) { ipcToken = Environment.GetEnvironmentVariable("CLASSNOTIFY_IPC_TOKEN"); } // ========================================================================= // Turn 48 Architecture Verdict: RELAY LAUNCHER MODE // If started by user / desktop shortcut / without token: // 1. Try wakeup existing authorized client in this session (< 50ms) // 2. If none, request Service via low-privilege Bootstrap Pipe (< 100ms) // 3. Fast exit immediately, never freeze or trigger watchdog false kills! // ========================================================================= if (string.IsNullOrEmpty(ipcToken)) { LogClient("No --ipc-token found. Acting as Relay Launcher..."); // Step 1: Try wakeup existing authorized client UI bool wokenUp = TryWakeupExistingClient(currentSessionId, LogClient); if (wokenUp) { LogClient("Successfully signalled existing authorized client to show UI. Relay exiting."); Environment.Exit(0); return; } // Step 2: Request Service Bootstrap pipe to launch authorized client in this session bool bootstrapped = TryRequestServiceBootstrap(currentSessionId, LogClient); if (bootstrapped) { LogClient("Successfully requested Service to launch authorized client. Relay exiting."); Environment.Exit(0); return; } LogClient("Service Bootstrap pipe unreachable. Service might not be running. Falling back to local activation window..."); } // ========================================================================= // AUTHORITATIVE CLIENT MODE (Service-launched or standalone fallback) // ========================================================================= bool isNewInstance; try { _singletonMutex = new Mutex(true, $@"Global\ClassNotify.Client.Session_{currentSessionId}", out isNewInstance); } catch (Exception ex) { LogClient($"Mutex exception: {ex.Message}. Falling back to true."); isNewInstance = true; } var intent = ClientLaunchIntent.BackgroundRecovery; if ((cmdArgs != null && cmdArgs.Any(a => a == "--user-interactive" || a == "--interactive" || a == "--show" || a == "-s")) || (e.Args != null && e.Args.Any(a => a == "--user-interactive" || a == "--interactive" || a == "--show" || a == "-s"))) { intent = ClientLaunchIntent.UserInteractive; } else if ((cmdArgs != null && cmdArgs.Any(a => a == "--first-run")) || (e.Args != null && e.Args.Any(a => a == "--first-run"))) { intent = ClientLaunchIntent.InstallerFirstRun; } else if (string.IsNullOrEmpty(ipcToken)) { // Standalone launch (e.g. user manually started client exe without service) intent = ClientLaunchIntent.UserInteractive; } if (!isNewInstance) { var decision = ClientLaunchPolicy.DecideLaunch(intent, existingInstanceRunning: true); if (decision.SendShowUi) { LogClient($"[{intent}] Another authorized instance is already running. Signalling it to show UI..."); TryWakeupExistingClient(currentSessionId, LogClient); } else { LogClient($"[{intent}] Another authorized instance is already running. Background recovery silent exit (Zero Disturbance Invariant)."); } Shutdown(0); return; } LogClient($"Starting authoritative IpcClient (Token present: {!string.IsNullOrEmpty(ipcToken)}, LaunchId={launchId}, Intent={intent})..."); _ipcClient = new IpcClient(this.Dispatcher, ipcToken: ipcToken); _ipcClient.OnEnterPairingMode += (pairingCode, ttlSeconds) => { LogClient($"[PairingMode] Pairing code broadcast received: Code={pairingCode}, TTL={ttlSeconds}s"); }; _ipcClient.Start(_cts.Token); StartWakeupPipeServer(currentSessionId, LogClient); var freshDecision = ClientLaunchPolicy.DecideLaunch(intent, existingInstanceRunning: false); if (freshDecision.BringToForeground) { LogClient($"[{intent}] UI display requested on fresh launch. Showing authoritative DeviceStatusWindow..."); Task.Run(async () => { await Task.Delay(300); Dispatcher.Invoke(() => ShowAuthoritativeUi()); }); } else { LogClient($"[{intent}] Starting silently in background (Zero Disturbance Invariant: UI remains hidden in system tray)."); } } private static bool TryWakeupExistingClient(int sessionId, Action log) { string pipeName = $"ClassNotify_Client_UI_Wakeup_{sessionId}"; try { using var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out); pipe.Connect(100); using var writer = new StreamWriter(pipe, Encoding.UTF8); writer.WriteLine("SHOW_UI"); writer.Flush(); log($"[Wakeup] Signalled {pipeName} successfully."); return true; } catch (Exception ex) { log($"[Wakeup] Client wakeup pipe not available: {ex.Message}"); return false; } } private static bool TryRequestServiceBootstrap(int sessionId, Action log) { string pipeName = $"ClassNotify_Service_Bootstrap_{sessionId}"; var deadline = DateTime.UtcNow.AddSeconds(3.5); while (DateTime.UtcNow < deadline) { try { using var pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut); pipe.Connect(350); using var writer = new StreamWriter(pipe, Encoding.UTF8) { AutoFlush = true }; using var reader = new StreamReader(pipe, Encoding.UTF8); writer.WriteLine("ENSURE_CLIENT_AND_SHOW"); var reply = reader.ReadLine(); log($"[Bootstrap] Service reply: {reply}"); if (reply == "OK") { return true; } } catch (TimeoutException) { } catch (IOException) { } catch (Exception ex) { log($"[Bootstrap] Service bootstrap attempt: {ex.Message}"); } Thread.Sleep(200); } log("[Bootstrap] Service bootstrap pipe not reachable after 3.5s timeout."); return false; } private void StartWakeupPipeServer(int sessionId, Action log) { Task.Run(async () => { string pipeName = $"ClassNotify_Client_UI_Wakeup_{sessionId}"; while (!_cts.Token.IsCancellationRequested) { try { using var server = new NamedPipeServerStream( pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); await server.WaitForConnectionAsync(_cts.Token); using var reader = new StreamReader(server, Encoding.UTF8); var cmd = await reader.ReadLineAsync(_cts.Token); log($"[WakeupServer] Received command: {cmd}"); if (cmd == "SHOW_UI" || cmd == "SHOW_STATUS") { Dispatcher.Invoke(() => ShowAuthoritativeUi()); } else if (cmd != null && cmd.StartsWith("TEST_ACTIVATE:")) { var code = cmd.Substring("TEST_ACTIVATE:".Length).Trim(); Dispatcher.Invoke(async () => { log($"[WakeupServer] Processing TEST_ACTIVATE: '{code}' via authoritative IpcClient"); if (_ipcClient != null) { var res = await _ipcClient.RequestActivateAsync(code); log($"[WakeupServer] TEST_ACTIVATE completed: Success={res.Success}, Msg='{res.Message}', Class='{res.ClassName}', ExpireDate='{res.ExpireDate}'"); } else { log("[WakeupServer] TEST_ACTIVATE failed: _ipcClient is null"); } }); } else if (cmd == "ACKNOWLEDGE_CURRENT") { Dispatcher.Invoke(() => { log("[WakeupServer] Processing ACKNOWLEDGE_CURRENT: Invoking BtnAcknowledge on display window"); _ipcClient?.AcknowledgeCurrentWindow(); }); } } catch (OperationCanceledException) { break; } catch (Exception ex) { log($"[WakeupServer] Error in wakeup server: {ex.Message}"); await Task.Delay(1000, _cts.Token); } } }, _cts.Token); } public async void ShowAuthoritativeUi() { try { if (_activeUiWindow != null && _activeUiWindow.IsVisible) { if (_activeUiWindow.WindowState == WindowState.Minimized) { _activeUiWindow.WindowState = WindowState.Normal; } _activeUiWindow.Activate(); _activeUiWindow.Topmost = true; _activeUiWindow.Topmost = false; _activeUiWindow.Focus(); return; } ClientStateSnapshotDto? state = null; if (_ipcClient != null) { state = await _ipcClient.GetClientStateAsync(); } // Unified DeviceStatusWindow Shell (Turn 116: Unified Modern Shell) var safeState = state ?? new ClientStateSnapshotDto { BindingState = DeviceBindingState.Unbound, ProvisioningState = "Unactivated", RealtimeChannelState = "NotApplicable" }; var statusWin = new DeviceStatusWindow(safeState, () => { }, _ipcClient); _activeUiWindow = statusWin; statusWin.Closed += (s, e) => { if (_activeUiWindow == statusWin) _activeUiWindow = null; }; statusWin.Show(); statusWin.Activate(); statusWin.Focus(); } catch (Exception ex) { var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "logs"); var logFile = Path.Combine(logDir, "client.log"); try { File.AppendAllText(logFile, $"[{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] Error in ShowAuthoritativeUi: {ex}\r\n"); } catch { } } } protected override void OnExit(ExitEventArgs e) { try { var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "logs"); var logFile = Path.Combine(logDir, "client.log"); File.AppendAllText(logFile, $"[{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] OnExit called. ExitCode={e.ApplicationExitCode}\r\n"); } catch { } _cts.Cancel(); try { _singletonMutex?.ReleaseMutex(); _singletonMutex?.Dispose(); } catch { } base.OnExit(e); } } }