diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs index f973f3c..7147313 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs @@ -21,8 +21,8 @@ internal static unsafe class WebPanelApi { try { - if (s_shutdown || EngineLifecycle.IsShuttingDown) return (int)WebPanelCode.ShuttingDown; - if (!EngineSettings.WebPanel) return (int)WebPanelCode.Unavailable; + int refusal = WebPanelApiRules.OpenRefusal(s_shutdown || EngineLifecycle.IsShuttingDown, EngineSettings.WebPanel); + if (refusal != 0) return refusal; EngineWebPanelEnvironment env; WebPanelHost host; lock (Sync) @@ -46,7 +46,8 @@ internal static unsafe class WebPanelApi { try { - if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + int refusal = WebPanelApiRules.CallRefusal(s_shutdown); + if (refusal != 0) return refusal; if (!WebPanelNativeArgs.TryReadUtf8(urlUtf8, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs; WebPanelHost? host = s_host; return host == null ? (int)WebPanelCode.StaleHandle : host.Navigate(handle, url); @@ -62,7 +63,8 @@ internal static unsafe class WebPanelApi { try { - if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + int refusal = WebPanelApiRules.CallRefusal(s_shutdown); + if (refusal != 0) return refusal; WebPanelHost? host = s_host; return host == null ? (int)WebPanelCode.StaleHandle : host.Close(handle); } @@ -77,26 +79,22 @@ internal static unsafe class WebPanelApi { try { - if (state == null || state->Size < (uint)((byte*)state->Reserved - (byte*)state)) return (int)WebPanelCode.BadArgs; - if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + if (!WebPanelApiRules.StateArgsOk(state)) return (int)WebPanelCode.BadArgs; + int refusal = WebPanelApiRules.CallRefusal(s_shutdown); + if (refusal != 0) return refusal; WebPanelHost? host = s_host; WebPanelSnapshot s; int r; if (host == null) { - s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0); - r = (int)WebPanelStatusCode.Superseded; + s = WebPanelApiRules.NoPanel(handle); + r = s.Status; } else { r = host.GetState(handle, out s); } - state->Handle = s.Handle; - state->Status = s.Status; - state->Flags = s.Flags; - state->Error = s.Error; - state->LastHttpStatus = s.LastHttpStatus; - state->NavigationCount = s.NavigationCount; + WebPanelApiRules.WriteState(state, s); return r; } catch (System.Exception ex) @@ -118,7 +116,10 @@ internal static unsafe class WebPanelApi host?.Shutdown(ShutdownBudgetMs); } - /// Redacted one-liner (no query, fragment or userinfo). + /// The live panel handle, 0 when none was opened: lets the engine close it (WebPanelApi.Close(LiveHandle)). + internal static int LiveHandle => s_host?.LiveHandle ?? 0; + + /// Redacted one-liner (no query, fragment or userinfo); includes the WebView2 browser pid. internal static string Describe() { WebPanelHost? host = s_host; @@ -135,6 +136,7 @@ internal static unsafe class WebPanelApi internal static int Close(int handle) => (int)WebPanelCode.Unavailable; internal static int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable; internal static void Shutdown() { } + internal static int LiveHandle => 0; internal static string Describe() => "web panel: not available in this engine build"; } #endif diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs new file mode 100644 index 0000000..68ed920 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs @@ -0,0 +1,46 @@ +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.WebPanel; + +/// What WebPanelGetState reports for one handle. +internal readonly record struct WebPanelSnapshot(int Handle, int Status, uint Flags, int Error, int LastHttpStatus, uint NavigationCount); + +/// +/// The pure decisions of the v93 ABI glue (WebPanelApi.cs), kept apart so tools\WebPanelTests can check them +/// without the engine: refusals, the GetState argument check, and writing the result struct. +/// +internal static unsafe class WebPanelApiRules +{ + /// 0 to go on, else the refusal. Shutting down wins over the engine.json "WebPanel" kill switch. + public static int OpenRefusal(bool shuttingDown, bool enabled) => + shuttingDown ? (int)WebPanelCode.ShuttingDown : enabled ? 0 : (int)WebPanelCode.Unavailable; + + /// Navigate, Close and GetState: 0 to go on, else ShuttingDown. + public static int CallRefusal(bool shuttingDown) => shuttingDown ? (int)WebPanelCode.ShuttingDown : 0; + + /// OffsetOf(Reserved): the smallest Size a caller's WebPanelStateNative may declare (32 on x86). + public static uint StateMinSize + { + get + { + WebPanelStateNative s = default; + return (uint)((byte*)s.Reserved - (byte*)&s); + } + } + + public static bool StateArgsOk(WebPanelStateNative* state) => state != null && state->Size >= StateMinSize; + + /// What a handle reads when no panel was ever opened. + public static WebPanelSnapshot NoPanel(int handle) => new(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0); + + /// Writes the fields before Reserved only (the caller's Size covers at least those). + public static void WriteState(WebPanelStateNative* state, in WebPanelSnapshot s) + { + state->Handle = s.Handle; + state->Status = s.Status; + state->Flags = s.Flags; + state->Error = s.Error; + state->LastHttpStatus = s.LastHttpStatus; + state->NavigationCount = s.NavigationCount; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs index 9f8e60d..1bf2096 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -29,8 +29,6 @@ using static RynthCore.Engine.WebPanel.WebPanelNative; namespace RynthCore.Engine.WebPanel; -internal readonly record struct WebPanelSnapshot(int Handle, int Status, uint Flags, int Error, int LastHttpStatus, uint NavigationCount); - internal sealed unsafe class WebPanelHost { private const uint WM_RUN = WM_APP + 1; @@ -66,7 +64,8 @@ internal sealed unsafe class WebPanelHost // ---- panel thread only ---- private IntPtr _staHwnd, _hook, _bgBrush, _captionBrush; private string _className = ""; - private bool _windowFailed, _tornDown, _open, _timerOn, _inSizeMove; + private bool _windowFailed, _tornDown, _timerOn, _inSizeMove; + private volatile bool _open; private int _serving; // the handle whose request the panel shows private WebPanelRequest? _req; private string _title = "RynthCore"; @@ -115,9 +114,7 @@ internal sealed unsafe class WebPanelHost { // First call (or the thread died): start it and return at once. The thread creates its // window first, then drains the queue. - _threadDone = false; - _hwnd = IntPtr.Zero; - _thread = _env.StartStaThread("RynthCore.WebPanel", ThreadMain); + StartThreadLocked(); } else if (_hwnd != IntPtr.Zero) { @@ -199,6 +196,9 @@ internal sealed unsafe class WebPanelHost SafeLog($"shutdown: the panel thread did not finish within {budgetMs} ms"); } + /// The live handle (0 before the first Open), for engine-side callers such as a close-on-command. + public int LiveHandle { get { lock (_sync) return _live; } } + public string Describe() { lock (_sync) @@ -206,10 +206,18 @@ internal sealed unsafe class WebPanelHost string thread = _thread == null ? "not started" : _threadDone ? "stopped" : "running"; string status = ((WebPanelStatusCode)_status).ToString(); return $"web panel: thread {thread}{(_shuttingDown ? " (shut down)" : "")}, handle {_live}, {status}, error {_error}, " + - $"http {_http}, navigations {_navCount}, environments {_environmentCount}, flags {_flags}, url {WebPanelUrlPolicy.Redact(_liveUrl)}"; + $"http {_http}, navigations {_navCount}, environments {_environmentCount}, flags {_flags}, browser pid {_browserPid}, url {WebPanelUrlPolicy.Redact(_liveUrl)}"; } } + /// Under _sync. _threadDone goes false only once the thread exists, so a failed start leaves it true. + private void StartThreadLocked() + { + _hwnd = IntPtr.Zero; + _thread = _env.StartStaThread("RynthCore.WebPanel", ThreadMain); + _threadDone = false; + } + // The live request's allowlist, for Navigate's caller-side check (set on Open, under _sync). private string[] _currentAllowlist = Array.Empty(); @@ -241,6 +249,9 @@ internal sealed unsafe class WebPanelHost internal string SourceForTests => _source; internal bool ThreadRunningForTests { get { lock (_sync) return _thread != null && !_threadDone && _thread.IsAlive; } } internal bool PostForTests(Action a) => Post(() => a(_web)); + internal bool PanelOpenForTests => _open; + /// A failure arriving late for (the harness passes a superseded one). + internal bool FailForTests(int handle) => Post(() => Fail(handle, WebPanelCode.ProcessFailed, "synthetic (harness)", allowFallback: false)); // ============================ panel thread ============================ @@ -286,6 +297,14 @@ internal sealed unsafe class WebPanelHost { _threadDone = true; _hwnd = IntPtr.Zero; + // An Open queued after this thread's last drain (e.g. while a failed window creation was being + // torn down) would otherwise wait for the next Open: start a fresh thread for it now. The new + // thread cannot finish (its finally takes this lock) before _threadDone is set back. + if (!_shuttingDown && !_queue.IsEmpty) + { + try { StartThreadLocked(); } + catch (Exception ex) { SafeLog("could not restart the panel thread: " + ex.GetType().Name); } + } } } } @@ -623,21 +642,29 @@ internal sealed unsafe class WebPanelHost private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e) { - string url = e.Uri; - if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return; // our own close, or the page's - string[] allow = _req?.Allowlist ?? Array.Empty(); - if (!WebPanelUrlPolicy.IsAllowed(url, allow)) + try { - e.Cancel = true; - RouteOffList(url); - return; + string url = e.Uri; + if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return; // our own close, or the page's + string[] allow = _req?.Allowlist ?? Array.Empty(); + if (!WebPanelUrlPolicy.IsAllowed(url, allow)) + { + e.Cancel = true; + RouteOffList(url); + return; + } + int handle = _serving; + SetState(handle, () => + { + _navCount++; + if (_status != (int)WebPanelStatusCode.Closed && _status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Loading; + }); } - int handle = _serving; - SetState(handle, () => + catch { - _navCount++; - if (_status != (int)WebPanelStatusCode.Closed && _status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Loading; - }); + // Fail closed: a guard that threw must not let the navigation through. + try { e.Cancel = true; } catch { } + } } private void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e) @@ -657,16 +684,24 @@ internal sealed unsafe class WebPanelHost private void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) { - e.Handled = true; // never a second window - string url = e.Uri; - string[] allow = _req?.Allowlist ?? Array.Empty(); - if (WebPanelUrlPolicy.IsAllowed(url, allow)) + try { - try { _web?.Navigate(url); } catch { } + e.Handled = true; // never a second window + string url = e.Uri; + string[] allow = _req?.Allowlist ?? Array.Empty(); + if (WebPanelUrlPolicy.IsAllowed(url, allow)) + { + try { _web?.Navigate(url); } catch { } + } + else + { + RouteOffList(url); + } } - else + catch { - RouteOffList(url); + // Fail closed: still no second window. + try { e.Handled = true; } catch { } } } @@ -704,9 +739,16 @@ internal sealed unsafe class WebPanelHost private void OnPermissionRequested(object? sender, CoreWebView2PermissionRequestedEventArgs e) { - e.State = e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead - ? CoreWebView2PermissionState.Allow - : CoreWebView2PermissionState.Deny; + // ClipboardRead only for a frame on the allowlist (iframes are unrestricted otherwise); everything else denied. + CoreWebView2PermissionState state = CoreWebView2PermissionState.Deny; + try + { + if (e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead + && WebPanelUrlPolicy.IsAllowed(e.Uri, _req?.Allowlist ?? Array.Empty())) + state = CoreWebView2PermissionState.Allow; + } + catch { state = CoreWebView2PermissionState.Deny; } + e.State = state; } private void OnAcceleratorKeyPressed(object? sender, CoreWebView2AcceleratorKeyPressedEventArgs e) @@ -722,22 +764,54 @@ internal sealed unsafe class WebPanelHost private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e) { CoreWebView2ProcessFailedKind kind = e.ProcessFailedKind; - int handle = _serving; - Post(() => HandleProcessFailed(handle, kind)); // tear down outside WebView2's own callback + Post(() => HandleProcessFailed(kind)); // act outside WebView2's own callback } - private void HandleProcessFailed(int handle, CoreWebView2ProcessFailedKind kind) + // RenderProcessUnresponsive: WebView2 raises it repeatedly while the main frame's renderer stays hung. One + // report can be a long script; this many within the window fails the panel like a renderer exit. + private const int UnresponsiveLimit = 3; + private const long UnresponsiveWindowMs = 30000; + private int _unresponsiveCount; + private long _unresponsiveSinceMs; + + /// + /// Only two kinds end the panel (WebView2's own docs, Microsoft.Web.WebView2.Core.xml, + /// CoreWebView2ProcessFailedKind): BrowserProcessExited (everything is gone: full teardown) and + /// RenderProcessExited (the main frame's renderer: about:blank, recreate on the next Open). GPU, utility, + /// sandbox helper and PPAPI processes are recreated by WebView2 and are not fatal; a frame-only renderer exit + /// does not touch the top-level document; those are logged only. Acts on the panel being served now, not on + /// the handle when the event fired, so a late event never hides a newer panel (Fail ignores a non-live handle). + /// + private void HandleProcessFailed(CoreWebView2ProcessFailedKind kind) { if (_tornDown) return; - SafeLog("WebView2 process failed: " + kind); - if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited) + int handle = _serving; + switch (kind) { - TearDownWebView(); - } - else - { - try { _web?.Navigate("about:blank"); } catch { } - _needsRecreate = true; // the next Open recreates the controller and environment + case CoreWebView2ProcessFailedKind.BrowserProcessExited: + SafeLog("WebView2 process failed: " + kind); + TearDownWebView(); + break; + case CoreWebView2ProcessFailedKind.RenderProcessExited: + SafeLog("WebView2 process failed: " + kind); + try { _web?.Navigate("about:blank"); } catch { } + _needsRecreate = true; // the next Open recreates the controller and environment + break; + case CoreWebView2ProcessFailedKind.RenderProcessUnresponsive: + { + long now = Environment.TickCount64; + if (_unresponsiveCount == 0 || now - _unresponsiveSinceMs > UnresponsiveWindowMs) { _unresponsiveCount = 0; _unresponsiveSinceMs = now; } + _unresponsiveCount++; + SafeLog($"WebView2 renderer unresponsive ({_unresponsiveCount} of {UnresponsiveLimit} within {UnresponsiveWindowMs / 1000} s)"); + if (_unresponsiveCount < UnresponsiveLimit) return; + _unresponsiveCount = 0; + try { _web?.Navigate("about:blank"); } catch { } + _needsRecreate = true; + break; + } + default: + SafeLog("WebView2 process failed (not fatal, panel kept): " + kind); + return; } // Never a browser fallback here: a navigation already ran, so the launch code is spent. Fail(handle, WebPanelCode.ProcessFailed, kind.ToString(), allowFallback: false); @@ -747,7 +821,6 @@ internal sealed unsafe class WebPanelHost private void Fail(int handle, WebPanelCode code, string reason, bool allowFallback) { - HidePanel(); bool fallback = false, ignored = false; string url = ""; lock (_sync) @@ -770,7 +843,8 @@ internal sealed unsafe class WebPanelHost } } } - if (ignored) { SafeLog($"panel failure after close or supersede: {code} ({reason})"); return; } + if (ignored) { SafeLog($"panel failure after close or supersede, panel left as it is: {code} ({reason})"); return; } + HidePanel(); SafeLog($"panel failed: {code} ({reason})"); if (!fallback) return; bool ok = false; @@ -786,10 +860,11 @@ internal sealed unsafe class WebPanelHost ShowWindow(_staHwnd, SW_SHOWNA); // Focus the panel only from within this process (the game, or a pop-out): a plugin opening it while the // player is in another program must not pull the foreground away (the PID rule keeps it hidden meanwhile). + // Never while the foreground is null (mid alt-tab): that would grab focus on the way to another program. IntPtr fg = GetForegroundWindow(); uint fgPid = 0; if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); - if (fg == IntPtr.Zero || fgPid == _ourPid) SetForegroundWindow(_staHwnd); + if (fg != IntPtr.Zero && IsOurPid(fgPid)) SetForegroundWindow(_staHwnd); if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } FocusPage(); if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } @@ -849,6 +924,9 @@ internal sealed unsafe class WebPanelHost IntPtr fg = GetForegroundWindow(); uint fgPid = 0; if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); + // The page's own dialogs (alert, file picker, sign-in) are windows of the WebView2 browser process: count + // that process as ours so they do not hide the panel they belong to. + if (IsOurPid(fgPid)) fgPid = _ourPid; bool? visible = WebPanelWindowPolicy.Visible(true, true, IsIconic(game), IsWindowVisible(game), fg == IntPtr.Zero, fgPid, _ourPid); bool shown = IsWindowVisible(_staHwnd); if (visible == false) @@ -867,6 +945,17 @@ internal sealed unsafe class WebPanelHost UpdateStateFlags(); } + /// + /// This process, or this panel's WebView2 browser process. The browser PID is CoreWebView2.BrowserProcessId, + /// read when the controller is created (OnController) and cleared by TearDownWebView; 0 while there is none. + /// + private bool IsOurPid(uint pid) + { + if (pid == 0) return false; + uint browser = _browserPid; + return pid == _ourPid || (browser != 0 && pid == browser); + } + private bool GameClientScreen(out PanelRect rect) { rect = default; diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index c72eebc..5a14d08 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -58,6 +58,7 @@ namespace EngineSettingsTests Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved); Run(nameof(TransitionGateDefaultOnAndSaved), TransitionGateDefaultOnAndSaved); + Run(nameof(WebPanelDefaultOnAndSaved), WebPanelDefaultOnAndSaved); Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved); Run(nameof(IltServerNamesEdit), IltServerNamesEdit); Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved); @@ -118,6 +119,8 @@ namespace EngineSettingsTests case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break; case "tgate-off": EngineSettings.TransitionGate = false; break; case "tgate-on": EngineSettings.TransitionGate = true; break; + case "webpanel-off": EngineSettings.WebPanel = false; break; + case "webpanel-on": EngineSettings.WebPanel = true; break; case "borderless-on": EngineSettings.BorderlessWindowed = true; break; case "borderless-off": EngineSettings.BorderlessWindowed = false; break; case "layout-on": EngineSettings.RememberWindowLayout = true; break; @@ -148,6 +151,7 @@ namespace EngineSettingsTests Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads); Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect); Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate); + Console.WriteLine("WebPanel=" + EngineSettings.WebPanel); Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed); Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout); Console.WriteLine("PanelLayoutPerCharacter=" + EngineSettings.PanelLayoutPerCharacter); @@ -415,6 +419,7 @@ namespace EngineSettingsTests (new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null), (new[] { "autoid", "all" }, "AutoIdMode", "\"All\""), (new[] { "tgate-off" }, "TransitionGate", "false"), + (new[] { "webpanel-off" }, "WebPanel", "false"), (new[] { "add-plugin", plugin }, "PluginPaths", null), (new[] { "remove-plugin", "0" }, "PluginPaths", null), }; @@ -622,6 +627,36 @@ namespace EngineSettingsTests } } + // engine.json WebPanel (2026-11-07, the v93 web panel kill switch): default on, only a hand-set false is + // written, other saves keep it, a value that is not a boolean is ignored. + private static void WebPanelDefaultOnAndSaved() + { + string dir = NewDir("webpanel"); + string path = Path.Combine(dir, "engine.json"); + + File.WriteAllText(path, LauncherFile); + Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "True", "missing: on"); + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default"); + Check(!ReadJson(path).TryGetProperty("WebPanel", out _), "the default isn't written to the file"); + + var (exit, output) = RunChild(path, "webpanel-off"); + Eq(exit, 0, "turn off (" + output.Trim() + ")"); + Eq(ReadJson(path).GetProperty("WebPanel").GetRawText(), "false", "off is saved"); + Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept"); + Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "False", "off read back at the next start"); + Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save"); + Eq(ReadJson(path).GetProperty("WebPanel").GetRawText(), "false", "off survives other saves"); + + Eq(RunChild(path, "webpanel-on").Exit, 0, "turn on"); + Check(!ReadJson(path).TryGetProperty("WebPanel", out _), "on again: dropped from the file"); + + foreach (string bad in new[] { "\"no\"", "0", "null" }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"WebPanel\": {bad}, \"LoggingLevel\"")); + Eq(DumpValue(RunChild(path, "dump").Out, "WebPanel"), "True", $"{bad}: ignored, on"); + } + } + // Settings > Display (2026-10-18): BorderlessWindowed off and RememberAcWindowPosition off by default, // RememberWindowLayout on (panels have always been remembered). Only the non-default is written; // other saves keep it; a value that is not a boolean is ignored. diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs index d753a38..80b7385 100644 --- a/tools/WebPanelHarness.Payload/PayloadEntry.cs +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -53,6 +53,8 @@ public static unsafe class PayloadEntry public static int AcceleratorKeyEvents => _host!.AcceleratorKeyEventsForTests; public static string Source => _host!.SourceForTests; public static bool ThreadRunning => _host!.ThreadRunningForTests; + public static bool PanelOpen => _host!.PanelOpenForTests; + public static bool FailHandle(int handle) => _host!.FailForTests(handle); public static string ProfileFolder(string world, string key) => WebPanelProfile.Folder(_env!.LocalAppData, world, key); diff --git a/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj index 627111a..b23a566 100644 --- a/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj +++ b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj @@ -35,6 +35,7 @@ + diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs index 5cdba28..0af02d7 100644 --- a/tools/WebPanelHarness/Program.cs +++ b/tools/WebPanelHarness/Program.cs @@ -103,6 +103,8 @@ internal static unsafe class Program Guard("StaleHandles", () => handle = CheckStaleHandles(s, handle)); Guard("ProfileSwitchRecreates", () => handle = CheckProfileSwitch(s)); Guard("NoBrowserFallbackAfterNavigation", () => CheckNoFallbackAfterNavigation(s, handle)); + Guard("GpuProcessCrashKeepsPanel", () => handle = CheckGpuCrash(s)); + Guard("LateFailureForSupersededHandle", () => handle = CheckLateFailure(s)); Guard("CreateFailureFallsBack", () => CheckCreateFailure(s)); Guard("VisibilitySameProcess", () => handle = CheckVisibilitySameProcess(s)); Unverified("VisibilityOtherProcess", "needs another process to take the foreground (alt-tab); the harness never forces it. Owner in-game check."); @@ -214,8 +216,11 @@ internal static unsafe class Program int g = _gameKeyMsgs - g0; W($"page input value {value}; fake game key messages during the test: {g}; AcceleratorKeyPressed events {(int)s.Call("get_AcceleratorKeyEvents")! - k0}; panel visible={IsWindowVisible((IntPtr)s.Call("get_HostHwnd")!)}; {FgDesc()}"); Snap((IntPtr)s.Call("get_HostHwnd")!, Path.Combine(_root, "panel-keys.png")); + // The game-side count is informational only: the keys are posted straight to the Chromium window, so the + // game could not see them here whatever the host did. Input isolation (unowned popup, separate queue) is an + // owner in-game check: type in the panel, nothing reaches AC's chat. + W($"(informational, cannot fail: game key messages {g})"); if (!value.Contains("x1q")) Fail("KeysStayInPage", $"page input is {value}, want x1q"); - else if (g != 0) Fail("KeysStayInPage", $"the game window saw {g} key message(s)"); else Ok("KeysStayInPage"); return h; } @@ -244,7 +249,6 @@ internal static unsafe class Program return; } if (!closed) { Fail("EscapeClosesAndRefocusesGame", $"AcceleratorKeyPressed fired but the panel is {st[2]}, not Closed"); return; } - if (g != 0) { Fail("EscapeClosesAndRefocusesGame", $"the game saw {g} key message(s)"); return; } if (!panelFg) { Unverified("EscapeClosesAndRefocusesGame", "closed, game saw 0 keys; the foreground hand-back could not be checked (the panel did not hold the foreground)"); return; } if (fg != _game) { Fail("EscapeClosesAndRefocusesGame", "closed, but the foreground is not the game"); return; } Ok("EscapeClosesAndRefocusesGame"); @@ -388,6 +392,92 @@ internal static unsafe class Program else Fail("OpenAfterProcessFailedRecreates", $"[{string.Join(",", st2)}]"); } + private static int CheckGpuCrash(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "GPU crash"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("GpuProcessCrashKeepsPanel", $"not Ready [{string.Join(",", a)}]"); return h; } + uint browser = (uint)(int)s.Call("get_BrowserProcessId")!; + int children = 0, readable = 0, gpu = 0; + foreach (Process p in Process.GetProcessesByName("msedgewebview2")) + { + using (p) + { + if (ParentPid(p.Id) != browser) continue; + children++; + string? cmd = CommandLine(p.Id); + if (cmd == null) continue; + readable++; + if (gpu == 0 && cmd.Contains("--type=gpu-process", StringComparison.Ordinal)) gpu = p.Id; + } + } + W($"browser pid {browser}: {children} child process(es), {readable} command line(s) readable, gpu-process pid {gpu}"); + if (gpu == 0) { Unverified("GpuProcessCrashKeepsPanel", $"no msedgewebview2 child of browser pid {browser} with --type=gpu-process ({children} children, {readable} command lines read)"); return h; } + int logs0 = LogLines.Count; + try { using var p = Process.GetProcessById(gpu); p.Kill(); } + catch (Exception ex) { Unverified("GpuProcessCrashKeepsPanel", "could not kill the gpu process: " + ex.Message); return h; } + Thread.Sleep(3000); + int[] st = State(s, h); + string alive = (string)s.Call("Eval", "document.title", 5000)!; + bool open = (bool)s.Call("get_PanelOpen")!; + var newLogs = LogLines.Skip(logs0).ToList(); + W($"killed gpu pid {gpu}: state [{string.Join(",", st)}], panel open {open}, page title {alive}; log: {string.Join(" | ", newLogs)}"); + if (st[2] != StatusReady || st[4] != 0) Fail("GpuProcessCrashKeepsPanel", $"status {st[2]} error {st[4]}, want Ready with no error"); + else if (!open) Fail("GpuProcessCrashKeepsPanel", "the panel closed"); + else if (!newLogs.Any(l => l.Contains("GpuProcessExited"))) Unverified("GpuProcessCrashKeepsPanel", "panel stayed Ready, but no GpuProcessExited ProcessFailed event arrived within 3 s, so the handler path was not shown"); + else Ok("GpuProcessCrashKeepsPanel"); + return h; + } + + private static int CheckLateFailure(Session s) + { + var (a, _) = Open(s, "https://panel.test/index.html", Allow, title: "Old"); + bool ra = WaitStatus(s, a, StatusReady, 30000, out _); + var (b, _) = Open(s, "https://panel.test/b.html", Allow, title: "New"); + bool rb = WaitStatus(s, b, StatusReady, 30000, out _); + bool open0 = (bool)s.Call("get_PanelOpen")!; + bool posted = (bool)s.Call("FailHandle", a)!; + Thread.Sleep(600); + int[] st = State(s, b); + bool open = (bool)s.Call("get_PanelOpen")!; + W($"late synthetic failure for superseded handle {a} (posted {posted}): newer handle {b} state [{string.Join(",", st)}], panel open before {open0} after {open}"); + if (!ra || !rb || !open0) Fail("LateFailureForSupersededHandle", "setup: panels not Ready/open"); + else if (st[2] != StatusReady) Fail("LateFailureForSupersededHandle", $"newer panel status {st[2]}, want Ready"); + else if (!open) Fail("LateFailureForSupersededHandle", "the late failure hid the newer panel"); + else Ok("LateFailureForSupersededHandle"); + return b; + } + + private static uint ParentPid(int pid) + { + IntPtr h = OpenProcess(0x1000 /* PROCESS_QUERY_LIMITED_INFORMATION */, false, pid); + if (h == IntPtr.Zero) return 0; + try + { + PROCESS_BASIC_INFORMATION pbi; + return NtQueryInformationProcess(h, 0, &pbi, sizeof(PROCESS_BASIC_INFORMATION), out _) == 0 ? (uint)pbi.InheritedFromUniqueProcessId.ToInt64() : 0; + } + finally { CloseHandle(h); } + } + + /// ProcessCommandLineInformation (60): a UNICODE_STRING followed by its text, in our buffer. + private static string? CommandLine(int pid) + { + IntPtr h = OpenProcess(0x1000, false, pid); + if (h == IntPtr.Zero) return null; + try + { + byte[] buf = new byte[65536]; + fixed (byte* b = buf) + { + if (NtQueryInformationProcess(h, 60, b, buf.Length, out _) != 0) return null; + int len = *(ushort*)b; + char* text = *(char**)(b + IntPtr.Size); + return text == null ? null : new string(text, 0, len / 2); + } + } + finally { CloseHandle(h); } + } + private static void CheckCreateFailure(Session s) { Drain(BrowserCalls); @@ -492,14 +582,15 @@ internal static unsafe class Program _pumpSession = s; var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow); if (!WaitStatus(s, h, StatusReady, 30000, out int[] st)) { Fail("UnloadWhileVisibleCollected", $"not Ready [{string.Join(",", st)}]"); } - W($"session 2 open: state [{string.Join(",", State(s, h))}] host visible {IsWindowVisible((IntPtr)s.Call("get_HostHwnd")!)}"); + bool visible = IsWindowVisible((IntPtr)s.Call("get_HostHwnd")!); + W($"session 2 open: state [{string.Join(",", State(s, h))}] host visible {visible}"); var sd = Stopwatch.StartNew(); s.Call("Shutdown", 2000); W($"Shutdown(2000) returned in {sd.ElapsedMilliseconds} ms (panel open; window shown only if the harness held the foreground)"); - UnloadAndJudge("UnloadWhileVisibleCollected", ref s); + UnloadAndJudge("UnloadWhileVisibleCollected", ref s, visible ? null : "collected, but the panel window was not visible (the PID rule hid it: the harness did not hold the foreground), so the visible-teardown path was not shown"); } - private static void UnloadAndJudge(string name, ref Session s) + private static void UnloadAndJudge(string name, ref Session s, string? unverifiedIfCollected = null) { _pumpSession = null; _pumpHandle = 0; @@ -511,6 +602,7 @@ internal static unsafe class Program while (weak.IsAlive && sw.ElapsedMilliseconds < 3000) { GC.Collect(); GC.WaitForPendingFinalizers(); if (weak.IsAlive) Thread.Sleep(20); } W($"{name}: context {(weak.IsAlive ? "STILL HELD" : "collected")} after {sw.ElapsedMilliseconds} ms"); if (weak.IsAlive) Fail(name, "the payload context was not collected within 3000 ms"); + else if (unverifiedIfCollected != null) Unverified(name, unverifiedIfCollected); else Ok(name); } @@ -933,6 +1025,10 @@ internal static unsafe class Program [DllImport("gdi32.dll")] private static extern bool DeleteObject(IntPtr o); [DllImport("gdi32.dll")] private static extern bool DeleteDC(IntPtr dc); [DllImport("gdi32.dll")] private static extern int GetDIBits(IntPtr dc, IntPtr bmp, uint start, uint lines, byte* bits, ref BITMAPINFOHEADER bi, uint usage); + [StructLayout(LayoutKind.Sequential)] private struct PROCESS_BASIC_INFORMATION { public IntPtr ExitStatus, PebBaseAddress, AffinityMask, BasePriority, UniqueProcessId, InheritedFromUniqueProcessId; } + [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess(IntPtr h, int cls, void* info, int len, out int ret); + [DllImport("kernel32.dll")] private static extern IntPtr OpenProcess(uint access, bool inherit, int pid); + [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr h); [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); [DllImport("kernel32.dll")] private static extern IntPtr GetModuleHandleW(IntPtr n); } diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs index e734733..76e04bf 100644 --- a/tools/WebPanelTests/Program.cs +++ b/tools/WebPanelTests/Program.cs @@ -1,9 +1,11 @@ +using System.Text; +using RynthCore.Engine.Plugins; using RynthCore.Engine.WebPanel; namespace WebPanelTests; /// The web panel's pure policies: URL allowlist, redaction, visibility, layout, profile folder. -internal static class Program +internal static unsafe class Program { private static int _checks, _failed; private static string _case = ""; @@ -22,6 +24,8 @@ internal static class Program Visibility(); Layout(); Profile(); + ApiRules(); + NativeArgs(); Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)"); return _failed == 0 ? 0 : 1; @@ -188,6 +192,88 @@ internal static class Program Check(wild.X >= 0 && wild.Y >= 0 && wild.W <= 1 && wild.H <= 1 && wild.X + wild.W <= 1.000001, "FromUserRect clamps to 0..1"); } + // WebPanelApi's pure parts (WebPanelApiRules): the kill switch and shutdown refusals, the GetState Size check. + private static void ApiRules() + { + Case("ApiRules"); + Eq(WebPanelApiRules.OpenRefusal(shuttingDown: false, enabled: true), 0, "enabled, running: go on"); + Eq(WebPanelApiRules.OpenRefusal(false, false), (int)WebPanelCode.Unavailable, "engine.json WebPanel false: Unavailable"); + Eq(WebPanelApiRules.OpenRefusal(true, true), (int)WebPanelCode.ShuttingDown, "shutting down: ShuttingDown"); + Eq(WebPanelApiRules.OpenRefusal(true, false), (int)WebPanelCode.ShuttingDown, "shutting down wins over the kill switch"); + Eq(WebPanelApiRules.CallRefusal(false), 0, "calls go on while running"); + Eq(WebPanelApiRules.CallRefusal(true), (int)WebPanelCode.ShuttingDown, "calls refused after shutdown"); + + uint min = WebPanelApiRules.StateMinSize; + if (IntPtr.Size == 4) Eq(min, 28u, "OffsetOf(Reserved) of the state struct on x86"); + Check(min > 0 && min < (uint)sizeof(WebPanelStateNative), "min size is inside the struct"); + Check(!WebPanelApiRules.StateArgsOk(null), "null state refused"); + WebPanelStateNative st = default; + st.Size = min - 1; + Check(!WebPanelApiRules.StateArgsOk(&st), "Size below OffsetOf(Reserved) refused"); + st.Size = min; + Check(WebPanelApiRules.StateArgsOk(&st), "Size == OffsetOf(Reserved) accepted"); + st.Size = (uint)sizeof(WebPanelStateNative); + Check(WebPanelApiRules.StateArgsOk(&st), "full Size accepted"); + + st.Reserved[0] = 0xDEADBEEF; + WebPanelApiRules.WriteState(&st, new WebPanelSnapshot(7, 3, 5, -9, 200, 4)); + Eq(st.Handle, 7, "handle written"); + Eq(st.Status, 3, "status written"); + Eq(st.Flags, 5u, "flags written"); + Eq(st.Error, -9, "error written"); + Eq(st.LastHttpStatus, 200, "http written"); + Eq(st.NavigationCount, 4u, "navigations written"); + Eq(st.Reserved[0], 0xDEADBEEFu, "Reserved untouched"); + Eq(WebPanelApiRules.NoPanel(9).Status, (int)WebPanelStatusCode.Superseded, "no panel yet: Superseded"); + } + + // WebPanelNativeArgs: the strings are copied out of the caller's buffers; bad arguments are BadArgs. + private static void NativeArgs() + { + Case("NativeArgs"); + const string lad = @"C:\lad"; + Eq(WebPanelNativeArgs.TryBuildRequest(null, lad, "W", out _), (int)WebPanelCode.BadArgs, "null struct"); + + int Build(string? url, string? allow, string? key, string? title, uint size, uint flags, out WebPanelRequest? req) + { + byte[] u = Z(url), a = Z(allow), k = Z(key), ti = Z(title); + fixed (byte* pu = u, pa = a, pk = k, pt = ti) + { + var o = new WebPanelOpenNative + { + Size = size, Flags = flags, + Url = url == null ? null : pu, Allowlist = allow == null ? null : pa, + ProfileKey = key == null ? null : pk, Title = title == null ? null : pt, + }; + int rc = WebPanelNativeArgs.TryBuildRequest(&o, lad, "W", out req); + Array.Fill(u, (byte)'Z'); Array.Fill(a, (byte)'Z'); // the caller's buffers die right after the call + return rc; + } + } + static byte[] Z(string? s) => s == null ? new byte[1] : Encoding.UTF8.GetBytes(s + "\0"); + uint full = (uint)sizeof(WebPanelOpenNative); + + Eq(Build("https://a.test/x?code=1", "a.test", "k", "T", full, 0xFF, out var r), 0, "good request"); + Eq(r?.Url, "https://a.test/x?code=1", "url copied before the buffer was overwritten"); + Eq(r?.Allowlist.Length, 1, "allowlist parsed"); + Eq(r?.Title, "T", "title copied"); + Eq(r?.Flags, 3u, "unknown flag bits dropped"); + Check(r != null && r.ProfileFolder.StartsWith(lad, StringComparison.Ordinal), "profile folder under LocalAppData"); + Eq(Build("https://a.test/", "a.test", null, null, full, 0, out r), 0, "null key and title"); + Eq(r?.Title, "", "null title is empty"); + Eq(Build("https://a.test/", "a.test", null, null, 31, 0, out _), (int)WebPanelCode.BadArgs, "Size below OffsetOf(Reserved)"); + Eq(Build(null, "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "no url"); + Eq(Build("", "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "empty url"); + Eq(Build("https://a.test/", null, null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "no allowlist"); + Eq(Build("https://a.test/", "*.com", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "bad allowlist"); + Eq(Build("https://a.test/", "a.test", null, new string('t', 129), full, 0, out _), (int)WebPanelCode.BadArgs, "title over 128 bytes"); + Eq(Build("https://a.test/", "a.test", new string('k', 257), null, full, 0, out _), (int)WebPanelCode.BadArgs, "key over 256 bytes"); + Eq(Build("https://a.test/" + new string('p', 4096), "a.test", null, null, full, 0, out _), (int)WebPanelCode.BadArgs, "url over 4096 bytes"); + + byte[] bad = { 0x68, 0xC3, 0x28, 0 }; // invalid UTF-8 + fixed (byte* pb = bad) Check(!WebPanelNativeArgs.TryReadUtf8(pb, 16, true, out _), "invalid UTF-8 refused"); + } + private static void Profile() { Case("Profile"); diff --git a/tools/WebPanelTests/WebPanelTests.csproj b/tools/WebPanelTests/WebPanelTests.csproj index 1ca3121..3151aae 100644 --- a/tools/WebPanelTests/WebPanelTests.csproj +++ b/tools/WebPanelTests/WebPanelTests.csproj @@ -13,12 +13,18 @@ enable true WebPanelTests + true + $(NoWarn);CS0649;CS0169 + + + +