From 0b0d2cb072b4e6ad3a6a15cd2b1b046ecfe6ea18 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:17:22 -0800 Subject: [PATCH 01/17] Web panel: URL, window and profile policies with offline tests Pure C# policies (allowlist/redaction, visibility/layout, profile folder) plus tools/WebPanelTests (107 assertions). Co-Authored-By: Claude Opus 5.5 --- .../WebPanel/WebPanelProfile.cs | 42 ++++ .../WebPanel/WebPanelUrlPolicy.cs | 119 ++++++++++ .../WebPanel/WebPanelWindowPolicy.cs | 67 ++++++ tools/WebPanelTests/Program.cs | 216 ++++++++++++++++++ tools/WebPanelTests/WebPanelTests.csproj | 24 ++ 5 files changed, 468 insertions(+) create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelProfile.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs create mode 100644 tools/WebPanelTests/Program.cs create mode 100644 tools/WebPanelTests/WebPanelTests.csproj diff --git a/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs new file mode 100644 index 0000000..f875638 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs @@ -0,0 +1,42 @@ +using System.Security.Cryptography; +using System.Text; + +namespace RynthCore.Engine.WebPanel; + +/// Pure per-world, per-profile-key WebView2 user data folder naming. No file access. +internal static class WebPanelProfile +{ + /// + /// <localAppData>\RynthCore\WebPanel\<world>\<hex>. World: [A-Za-z0-9 _-] kept, others + /// '_', trimmed, max 64, empty -> "_default". Hex: first 16 bytes of + /// SHA-256(UTF-8(key.Trim().ToLowerInvariant())) as lowercase hex; empty key -> "default". + /// + public static string Folder(string localAppData, string? worldName, string? profileKey) + { + return Path.Combine(localAppData, "RynthCore", "WebPanel", SanitizeWorld(worldName), KeyHex(profileKey)); + } + + private static string SanitizeWorld(string? world) + { + if (string.IsNullOrWhiteSpace(world)) return "_default"; + var sb = new StringBuilder(); + foreach (char c in world.Trim()) + { + bool keep = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == ' ' || c == '_' || c == '-'; + sb.Append(keep ? c : '_'); + } + string s = sb.ToString(); + if (s.Length > 64) s = s.Substring(0, 64); + s = s.Trim(); // a trailing space is not a valid Windows folder name + return s.Length == 0 ? "_default" : s; + } + + private static string KeyHex(string? key) + { + string k = (key ?? "").Trim().ToLowerInvariant(); + if (k.Length == 0) return "default"; + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(k)); + return Convert.ToHexString(hash, 0, 16).ToLowerInvariant(); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs new file mode 100644 index 0000000..1b94aab --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs @@ -0,0 +1,119 @@ +using System.Text; + +namespace RynthCore.Engine.WebPanel; + +/// +/// Pure URL rules for the web panel: the navigation allowlist, the "safe to hand to the system +/// browser" test, and log redaction. No Win32, no WebView2. +/// +internal static class WebPanelUrlPolicy +{ + public const int MaxEntries = 16, MaxEntryLength = 253, MaxUrlBytes = 4096; + + /// + /// Parses a '\n'-separated allowlist (blank lines ignored, '\r' tolerated). An entry is + /// "host" (exact) or "*.suffix" (any subdomain depth, not the suffix itself; the suffix must + /// contain a dot). No scheme, path, port or other '*'. False on 0 or more than 16 entries or + /// any bad entry. + /// + public static bool TryParseAllowlist(string? text, out string[] entries) + { + entries = Array.Empty(); + if (string.IsNullOrWhiteSpace(text)) return false; + + var list = new List(); + foreach (string raw in text.Split('\n')) + { + string e = raw.Trim().ToLowerInvariant(); + if (e.Length == 0) continue; + if (list.Count >= MaxEntries) return false; + if (!IsValidEntry(e)) return false; + list.Add(e); + } + if (list.Count == 0) return false; + entries = list.ToArray(); + return true; + } + + private static bool IsValidEntry(string e) + { + if (e.Length > MaxEntryLength) return false; + string host = e; + if (e.StartsWith("*.", StringComparison.Ordinal)) + { + host = e.Substring(2); + if (host.IndexOf('.') < 0) return false; // "*.com" would allow a whole TLD + } + return IsValidHostName(host); + } + + private static bool IsValidHostName(string host) + { + if (host.Length == 0) return false; + foreach (string label in host.Split('.')) + { + if (label.Length == 0 || label.Length > 63) return false; + if (label[0] == '-' || label[^1] == '-') return false; + foreach (char c in label) + { + bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-'; + if (!ok) return false; + } + } + return true; + } + + /// + /// https only, no userinfo, default port; host compared via Uri.IdnHost, case-insensitive, + /// one trailing dot stripped. "about:blank" is allowed. + /// + public static bool IsAllowed(string? url, IReadOnlyList entries) + { + if (string.IsNullOrEmpty(url)) return false; + if (Encoding.UTF8.GetByteCount(url) > MaxUrlBytes) return false; + if (string.Equals(url, "about:blank", StringComparison.OrdinalIgnoreCase)) return true; + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; + if (uri.Scheme != Uri.UriSchemeHttps) return false; + if (uri.UserInfo.Length != 0) return false; + if (!uri.IsDefaultPort) return false; + + string host = uri.IdnHost.ToLowerInvariant(); + if (host.EndsWith('.')) host = host.Substring(0, host.Length - 1); + if (host.Length == 0) return false; + + foreach (string entry in entries) + { + if (entry.StartsWith("*.", StringComparison.Ordinal)) + { + string suffix = entry.Substring(1); // ".example.com" + if (host.Length > suffix.Length && host.EndsWith(suffix, StringComparison.Ordinal)) return true; + } + else if (host == entry) + { + return true; + } + } + return false; + } + + /// Absolute http/https without userinfo: the only URLs that may reach ShellExecute. + public static bool IsBrowserSafe(string? url) + { + if (string.IsNullOrWhiteSpace(url)) return false; + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; + if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) return false; + if (uri.UserInfo.Length != 0) return false; + return uri.Host.Length != 0; + } + + /// "scheme://host[:port]/path" with no userinfo, query or fragment; "<invalid url>" if unparseable. + public static string Redact(string? url) + { + const string Invalid = ""; + if (string.IsNullOrEmpty(url)) return Invalid; + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return Invalid; + if (uri.Host.Length == 0) return Invalid; + string port = uri.IsDefaultPort ? "" : ":" + uri.Port; + return uri.Scheme + "://" + uri.Host + port + uri.AbsolutePath; + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs new file mode 100644 index 0000000..654edaa --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs @@ -0,0 +1,67 @@ +namespace RynthCore.Engine.WebPanel; + +internal readonly record struct PanelRect(int Left, int Top, int Right, int Bottom) +{ + public int Width => Right - Left; + public int Height => Bottom - Top; +} + +/// Panel placement as fractions (0..1) of the game client rect. +internal readonly record struct PanelFractions(double X, double Y, double W, double H); + +/// Pure visibility and layout rules for the web panel window. No Win32. +internal static class WebPanelWindowPolicy +{ + public const int DefaultPercent = 88, MinPercent = 30, MaxPercent = 100, MinWidthPx = 480, MinHeightPx = 320; + + /// + /// false when closed, the game is gone, iconic or invisible; null (keep current) when the + /// foreground window is null mid alt-tab, so the panel never flickers; otherwise true only + /// when the foreground window belongs to the game process. + /// + public static bool? Visible(bool open, bool gameAlive, bool gameIconic, bool gameVisible, + bool foregroundNull, uint foregroundPid, uint ourPid) + { + if (!open || !gameAlive || gameIconic || !gameVisible) return false; + if (foregroundNull) return null; + return foregroundPid == ourPid; + } + + /// Centered fractions for a size in percent of the client; 0 means the default (88). + public static PanelFractions Default(int widthPercent, int heightPercent) + { + double w = Pct(widthPercent) / 100.0; + double h = Pct(heightPercent) / 100.0; + return new PanelFractions((1 - w) / 2, (1 - h) / 2, w, h); + } + + private static int Pct(int p) => p == 0 ? DefaultPercent : Math.Clamp(p, MinPercent, MaxPercent); + + /// Screen rect for the fractions: at least 480x320 (or the whole client if smaller), never outside the client. + public static PanelRect Place(PanelRect gameClientScreen, PanelFractions f) + { + int cw = Math.Max(0, gameClientScreen.Width); + int ch = Math.Max(0, gameClientScreen.Height); + int w = Math.Clamp((int)Math.Round(Clamp01(f.W) * cw), Math.Min(MinWidthPx, cw), cw); + int h = Math.Clamp((int)Math.Round(Clamp01(f.H) * ch), Math.Min(MinHeightPx, ch), ch); + int x = Math.Clamp((int)Math.Round(Clamp01(f.X) * cw), 0, cw - w); + int y = Math.Clamp((int)Math.Round(Clamp01(f.Y) * ch), 0, ch - h); + int left = gameClientScreen.Left + x; + int top = gameClientScreen.Top + y; + return new PanelRect(left, top, left + w, top + h); + } + + /// Fractions of the client for a panel rect the user dragged or resized, clamped to 0..1. + public static PanelFractions FromUserRect(PanelRect gameClientScreen, PanelRect panelScreen) + { + int cw = gameClientScreen.Width, ch = gameClientScreen.Height; + if (cw <= 0 || ch <= 0) return Default(0, 0); + double w = Clamp01((double)panelScreen.Width / cw); + double h = Clamp01((double)panelScreen.Height / ch); + double x = Math.Clamp((double)(panelScreen.Left - gameClientScreen.Left) / cw, 0, 1 - w); + double y = Math.Clamp((double)(panelScreen.Top - gameClientScreen.Top) / ch, 0, 1 - h); + return new PanelFractions(x, y, w, h); + } + + private static double Clamp01(double v) => double.IsNaN(v) ? 0 : Math.Clamp(v, 0, 1); +} diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs new file mode 100644 index 0000000..99d8e0b --- /dev/null +++ b/tools/WebPanelTests/Program.cs @@ -0,0 +1,216 @@ +using RynthCore.Engine.WebPanel; + +namespace WebPanelTests; + +/// The web panel's pure policies: URL allowlist, redaction, visibility, layout, profile folder. +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static readonly string[] Dw = { "*.acdreamweave.com" }; + + private static int Main() + { + Allowlist_ExactAndWildcard(); + Allowlist_LookalikesRejected(); + Allowlist_CaseIdnTrailingDot(); + Allowlist_BadEntries(); + Allowlist_ParseGood(); + BrowserSafe(); + Redact(); + Visibility(); + Layout(); + Profile(); + + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} assertions)" : $"FAIL ({_failed} of {_checks} assertions)"); + return _failed == 0 ? 0 : 1; + } + + private static void Case(string name) { _case = name; Console.WriteLine("ok " + name); } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"FAIL {_case}: {what}"); + } + + private static void Eq(T got, T want, string what) => + Check(EqualityComparer.Default.Equals(got, want), $"{what}: got {got}, want {want}"); + + private static void Allowlist_ExactAndWildcard() + { + Case("Allowlist_ExactAndWildcard"); + Check(WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/x", Dw), "www subdomain allowed"); + Check(WebPanelUrlPolicy.IsAllowed("https://a.b.acdreamweave.com/", Dw), "deep subdomain allowed"); + Check(!WebPanelUrlPolicy.IsAllowed("https://acdreamweave.com/", Dw), "wildcard does not match the suffix itself"); + Check(WebPanelUrlPolicy.IsAllowed("https://acdreamweave.com/", new[] { "acdreamweave.com" }), "exact entry matches"); + Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/", new[] { "acdreamweave.com" }), "exact entry does not match subdomain"); + Check(WebPanelUrlPolicy.IsAllowed("about:blank", Dw), "about:blank allowed"); + Check(!WebPanelUrlPolicy.IsAllowed(null, Dw), "null rejected"); + Check(!WebPanelUrlPolicy.IsAllowed("", Dw), "empty rejected"); + Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/", Array.Empty()), "empty allowlist rejects all"); + } + + private static void Allowlist_LookalikesRejected() + { + Case("Allowlist_LookalikesRejected"); + foreach (string u in new[] + { + "https://www.acdreamweave.com.evil.com/", + "https://evilacdreamweave.com/", + "https://www.acdreamweave.com@evil.com/", + "https://evil.com/?h=.acdreamweave.com", + "http://www.acdreamweave.com/", + "https://www.acdreamweave.com:8443/", + "https://user:pw@www.acdreamweave.com/", + "file:///C:/x", + "javascript:alert(1)", + }) + Check(!WebPanelUrlPolicy.IsAllowed(u, Dw), "rejects " + u); + Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/" + new string('a', 5000), Dw), "over MaxUrlBytes rejected"); + } + + private static void Allowlist_CaseIdnTrailingDot() + { + Case("Allowlist_CaseIdnTrailingDot"); + Check(WebPanelUrlPolicy.IsAllowed("https://WWW.AcDreamWeave.com./", Dw), "case and one trailing dot"); + Check(WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com:443/", Dw), "explicit default port"); + string puny = new System.Globalization.IdnMapping().GetAscii("b\u00fccher.example"); + Check(WebPanelUrlPolicy.IsAllowed("https://b\u00fccher.example/", new[] { puny }), "unicode host matches its punycode entry"); + Check(WebPanelUrlPolicy.IsAllowed("https://" + puny + "/", new[] { puny }), "punycode host matches itself"); + Check(!WebPanelUrlPolicy.IsAllowed("https://bucher.example/", new[] { puny }), "ascii lookalike does not match punycode entry"); + Check(!WebPanelUrlPolicy.IsAllowed("https://xn--bcher-kva.example/", new[] { "bucher.example" }), "punycode host does not match other entry"); + } + + private static void Allowlist_BadEntries() + { + Case("Allowlist_BadEntries"); + foreach (string bad in new[] { "*", "*.com", "https://x.com", "x.com/path", "x.com:443", "a.*.com", "", " ", "x.com.", "*.x.*.com", "a b.com", "*x.com" }) + Check(!WebPanelUrlPolicy.TryParseAllowlist(bad, out _), "rejects entry list '" + bad + "'"); + Check(!WebPanelUrlPolicy.TryParseAllowlist(null, out _), "null rejected"); + string seventeen = string.Join("\n", Enumerable.Range(0, 17).Select(i => $"h{i}.example.com")); + Check(!WebPanelUrlPolicy.TryParseAllowlist(seventeen, out _), "17 entries rejected"); + string sixteen = string.Join("\n", Enumerable.Range(0, 16).Select(i => $"h{i}.example.com")); + Check(WebPanelUrlPolicy.TryParseAllowlist(sixteen, out var e16) && e16.Length == 16, "16 entries accepted"); + Check(!WebPanelUrlPolicy.TryParseAllowlist("good.example.com\nbad/entry", out _), "one bad entry fails the list"); + Check(!WebPanelUrlPolicy.TryParseAllowlist(new string('a', 254) + ".com", out _), "over-long entry rejected"); + } + + private static void Allowlist_ParseGood() + { + Case("Allowlist_ParseGood"); + Check(WebPanelUrlPolicy.TryParseAllowlist("*.AcDreamWeave.com\r\nlocalhost\n", out var e), "parses"); + Eq(e.Length, 2, "entry count"); + Eq(e[0], "*.acdreamweave.com", "lower-cased wildcard"); + Eq(e[1], "localhost", "single-label host ok"); + } + + private static void BrowserSafe() + { + Case("BrowserSafe"); + Check(WebPanelUrlPolicy.IsBrowserSafe("https://example.com/a?b=c"), "https"); + Check(WebPanelUrlPolicy.IsBrowserSafe("http://example.com/"), "http"); + foreach (string u in new[] { "file:///C:/Windows/notepad.exe", "javascript:alert(1)", "ms-settings:network", "mailto:a@b.c", "/relative/path", "example.com", "https://u:p@example.com/", "https://u@example.com/", "", " " }) + Check(!WebPanelUrlPolicy.IsBrowserSafe(u), "not safe: " + u); + Check(!WebPanelUrlPolicy.IsBrowserSafe(null), "null not safe"); + } + + private static void Redact() + { + Case("Redact"); + string r = WebPanelUrlPolicy.Redact("https://www.acdreamweave.com/launch?code=SECRET&to=/Browse#f"); + Eq(r, "https://www.acdreamweave.com/launch", "query and fragment stripped"); + Check(!r.Contains("SECRET"), "secret absent"); + Eq(WebPanelUrlPolicy.Redact("https://user:pw@host.example:8443/p/q?x=1"), "https://host.example:8443/p/q", "userinfo dropped, port kept"); + Check(!WebPanelUrlPolicy.Redact("https://user:pw@host.example/p").Contains("pw"), "password absent"); + Eq(WebPanelUrlPolicy.Redact("not a url"), "", "garbage"); + Eq(WebPanelUrlPolicy.Redact(null), "", "null"); + Eq(WebPanelUrlPolicy.Redact(""), "", "empty"); + Check(!WebPanelUrlPolicy.Redact("mailto:secret@x.com").Contains("secret"), "non-hierarchical leaks nothing"); + } + + private static void Visibility() + { + Case("Visibility"); + // open, alive, !iconic, visible, !fgNull, fgPid, ourPid + Eq(WebPanelWindowPolicy.Visible(true, true, false, true, false, 5, 5), (bool?)true, "same process shows"); + Eq(WebPanelWindowPolicy.Visible(true, true, false, true, false, 6, 5), (bool?)false, "other process hides"); + Eq(WebPanelWindowPolicy.Visible(true, true, false, true, true, 0, 5), (bool?)null, "null foreground keeps current"); + Eq(WebPanelWindowPolicy.Visible(true, true, true, true, false, 5, 5), (bool?)false, "iconic hides"); + Eq(WebPanelWindowPolicy.Visible(false, true, false, true, false, 5, 5), (bool?)false, "closed hides"); + Eq(WebPanelWindowPolicy.Visible(true, false, false, true, false, 5, 5), (bool?)false, "dead game hides"); + Eq(WebPanelWindowPolicy.Visible(true, true, false, false, false, 5, 5), (bool?)false, "invisible game hides"); + Eq(WebPanelWindowPolicy.Visible(false, true, false, true, true, 0, 5), (bool?)false, "closed beats null foreground"); + Eq(WebPanelWindowPolicy.Visible(true, true, true, true, true, 0, 5), (bool?)false, "iconic beats null foreground"); + } + + private static void Layout() + { + Case("Layout"); + var client = new PanelRect(100, 50, 1200, 800); // 1100 x 750 + var f = WebPanelWindowPolicy.Default(0, 0); + Check(Math.Abs(f.W - 0.88) < 1e-9 && Math.Abs(f.H - 0.88) < 1e-9, "0 means 88 %"); + Check(Math.Abs(f.X - 0.06) < 1e-9 && Math.Abs(f.Y - 0.06) < 1e-9, "centered"); + var r = WebPanelWindowPolicy.Place(client, f); + Eq(r.Width, 968, "88 % of 1100"); + Eq(r.Height, 660, "88 % of 750"); + Eq(r.Left - client.Left, client.Right - r.Right, "horizontally centered"); + Eq(r.Top - client.Top, client.Bottom - r.Bottom, "vertically centered"); + + var full = WebPanelWindowPolicy.Default(120, 120); + Check(full.W == 1.0 && full.H == 1.0 && full.X == 0 && full.Y == 0, "120 clamps to 100"); + var small = WebPanelWindowPolicy.Default(5, 5); + Check(Math.Abs(small.W - 0.30) < 1e-9, "5 clamps to 30"); + Eq(WebPanelWindowPolicy.Place(client, full), client, "100 % fills the client"); + + var tiny = new PanelRect(0, 0, 300, 200); + Eq(WebPanelWindowPolicy.Place(tiny, WebPanelWindowPolicy.Default(0, 0)), tiny, "tiny client clamps to client"); + var mid = new PanelRect(0, 0, 600, 400); + var m = WebPanelWindowPolicy.Place(mid, WebPanelWindowPolicy.Default(30, 30)); + Check(m.Width >= 480 && m.Height >= 320, "minimum size enforced"); + Check(m.Left >= mid.Left && m.Top >= mid.Top && m.Right <= mid.Right && m.Bottom <= mid.Bottom, "min size stays inside client"); + + // Off-screen fractions stay inside. + var off = WebPanelWindowPolicy.Place(client, new PanelFractions(0.95, 0.95, 0.5, 0.5)); + Check(off.Left >= client.Left && off.Top >= client.Top && off.Right <= client.Right && off.Bottom <= client.Bottom, "never outside client"); + + // Round trip. + var user = new PanelRect(300, 200, 1000, 700); + var rt = WebPanelWindowPolicy.Place(client, WebPanelWindowPolicy.FromUserRect(client, user)); + Check(Math.Abs(rt.Left - user.Left) <= 1 && Math.Abs(rt.Top - user.Top) <= 1 && + Math.Abs(rt.Right - user.Right) <= 1 && Math.Abs(rt.Bottom - user.Bottom) <= 1, $"round trip within 1 px: {rt}"); + var wild = WebPanelWindowPolicy.FromUserRect(client, new PanelRect(-500, -500, 5000, 5000)); + Check(wild.X >= 0 && wild.Y >= 0 && wild.W <= 1 && wild.H <= 1 && wild.X + wild.W <= 1.000001, "FromUserRect clamps to 0..1"); + } + + private static void Profile() + { + Case("Profile"); + const string root = @"C:\Users\x\AppData\Local"; + string a = WebPanelProfile.Folder(root, "DreamWeave", "Alice"); + Eq(a, WebPanelProfile.Folder(root, "DreamWeave", " ALICE "), "case/space-insensitive key"); + Check(a != WebPanelProfile.Folder(root, "DreamWeave", "Bob"), "different keys differ"); + Check(a != WebPanelProfile.Folder(root, "Other", "Alice"), "different worlds differ"); + string leaf = Path.GetFileName(a); + Eq(leaf.Length, 32, "hex is 32 chars"); + Check(leaf.All(c => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')), "lowercase hex"); + // SHA-256("alice") first 16 bytes. + Eq(leaf, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("alice")), 0, 16).ToLowerInvariant(), "hash of lowered key"); + Eq(Path.GetFileName(WebPanelProfile.Folder(root, "W", "")), "default", "empty key"); + Eq(Path.GetFileName(WebPanelProfile.Folder(root, "W", null)), "default", "null key"); + + string evil = WebPanelProfile.Folder(root, "Dream/Weave..", "k"); + Check(!evil.Contains(".."), "no dot-dot"); + Eq(Path.GetFileName(Path.GetDirectoryName(evil)!), "Dream_Weave__", "world sanitized"); + Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, null, "k"))!), "_default", "null world"); + Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, " ", "k"))!), "_default", "blank world"); + Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, new string('w', 100), "k"))!).Length, 64, "world capped at 64"); + Eq(Path.GetFileName(Path.GetDirectoryName(WebPanelProfile.Folder(root, @"..\..\x", "k"))!), "______x", "traversal neutralised"); + string full = Path.GetFullPath(evil); + Check(full.StartsWith(Path.GetFullPath(root), StringComparison.OrdinalIgnoreCase), "under localAppData"); + Check(evil.Contains(Path.Combine("RynthCore", "WebPanel")), "RynthCore\\WebPanel layout"); + } +} diff --git a/tools/WebPanelTests/WebPanelTests.csproj b/tools/WebPanelTests/WebPanelTests.csproj new file mode 100644 index 0000000..1ca3121 --- /dev/null +++ b/tools/WebPanelTests/WebPanelTests.csproj @@ -0,0 +1,24 @@ + + + + + Exe + net10.0 + enable + enable + true + WebPanelTests + + + + + + + + + -- 2.43.0 From e428f65c4d2c902b6a65cfeb34fcb1a2b1d0aa65 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:19:55 -0800 Subject: [PATCH 02/17] Web panel: IsAllowed fails closed on invalid IDN hosts Uri.IdnHost throws UriFormatException for hosts like c; catch and reject. Test project now runs with ICU so the case is covered. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs | 4 +++- tools/WebPanelTests/Program.cs | 1 + tools/WebPanelTests/WebPanelTests.csproj | 3 ++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs index 1b94aab..b572b54 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs @@ -77,7 +77,9 @@ internal static class WebPanelUrlPolicy if (uri.UserInfo.Length != 0) return false; if (!uri.IsDefaultPort) return false; - string host = uri.IdnHost.ToLowerInvariant(); + string host; + try { host = uri.IdnHost.ToLowerInvariant(); } + catch (UriFormatException) { return false; } // invalid IDN characters: fail closed if (host.EndsWith('.')) host = host.Substring(0, host.Length - 1); if (host.Length == 0) return false; diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs index 99d8e0b..581b485 100644 --- a/tools/WebPanelTests/Program.cs +++ b/tools/WebPanelTests/Program.cs @@ -71,6 +71,7 @@ internal static class Program }) Check(!WebPanelUrlPolicy.IsAllowed(u, Dw), "rejects " + u); Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/" + new string('a', 5000), Dw), "over MaxUrlBytes rejected"); + Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.c\u2100/", Dw), "invalid IDN char fails closed (no throw)"); } private static void Allowlist_CaseIdnTrailingDot() diff --git a/tools/WebPanelTests/WebPanelTests.csproj b/tools/WebPanelTests/WebPanelTests.csproj index 1ca3121..3a4bac0 100644 --- a/tools/WebPanelTests/WebPanelTests.csproj +++ b/tools/WebPanelTests/WebPanelTests.csproj @@ -11,7 +11,8 @@ net10.0 enable enable - true + + false WebPanelTests -- 2.43.0 From 0d5b9700db848bb4b311c42d66dd39fe24b77d42 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:25:57 -0800 Subject: [PATCH 03/17] Web panel tests: back to invariant globalization, add lone-surrogate check Matches the shipped engine; the surrogate host discriminates the IdnHost try/catch under invariant mode. Co-Authored-By: Claude Opus 5.5 --- tools/WebPanelTests/Program.cs | 1 + tools/WebPanelTests/WebPanelTests.csproj | 3 +-- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs index 581b485..e734733 100644 --- a/tools/WebPanelTests/Program.cs +++ b/tools/WebPanelTests/Program.cs @@ -72,6 +72,7 @@ internal static class Program Check(!WebPanelUrlPolicy.IsAllowed(u, Dw), "rejects " + u); Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.com/" + new string('a', 5000), Dw), "over MaxUrlBytes rejected"); Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.c\u2100/", Dw), "invalid IDN char fails closed (no throw)"); + Check(!WebPanelUrlPolicy.IsAllowed("https://www.acdreamweave.c" + "\uD800" + "/", Dw), "lone-surrogate host fails closed (no throw)"); } private static void Allowlist_CaseIdnTrailingDot() diff --git a/tools/WebPanelTests/WebPanelTests.csproj b/tools/WebPanelTests/WebPanelTests.csproj index 3a4bac0..1ca3121 100644 --- a/tools/WebPanelTests/WebPanelTests.csproj +++ b/tools/WebPanelTests/WebPanelTests.csproj @@ -11,8 +11,7 @@ net10.0 enable enable - - false + true WebPanelTests -- 2.43.0 From 28d480c90abc175544e4421cfe5d2391bee641b4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:31:48 -0800 Subject: [PATCH 04/17] Plugin API v93: web panel table fields and SDK wrappers (number provisional) Four appended table slots (WebPanelOpen/Navigate/Close/GetState), native structs and code enums in engine and SDK, a WebPanelApi stub answering Unavailable (CoreCLR flavour only; AOT leaves the slots zero), SDK OpenWebPanel/NavigateWebPanel/CloseWebPanel/GetWebPanelState with HasWebPanel gated on Version >= 93, parity tests in PluginManifestTests. Also adds the missing System usings to the Task 1 WebPanel files, which did not compile in the engine project (no ImplicitUsings). Co-Authored-By: Claude Opus 5.5 --- .../Plugins/PluginContract.cs | 80 +++++++++++++ .../Plugins/PluginContractVersion.cs | 3 + src/RynthCore.Engine/Plugins/PluginManager.cs | 19 +++ src/RynthCore.Engine/WebPanel/WebPanelApi.cs | 19 +++ .../WebPanel/WebPanelProfile.cs | 2 + .../WebPanel/WebPanelUrlPolicy.cs | 2 + .../WebPanel/WebPanelWindowPolicy.cs | 1 + src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 5 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 113 ++++++++++++++++++ src/RynthCore.PluginSdk/WebPanelTypes.cs | 95 +++++++++++++++ tools/PluginManifestTests/Program.cs | 101 +++++++++++++++- 11 files changed, 437 insertions(+), 3 deletions(-) create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelApi.cs create mode 100644 src/RynthCore.PluginSdk/WebPanelTypes.cs diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 8ad0b04..1e2d842 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -1069,6 +1069,74 @@ internal struct RynthCoreAPI /// reading, 0 without (never read; *ratio = -1, *ageMs = 0xFFFFFFFF). Either pointer may be null. /// Read-only, any thread, no game calls. Requires API v93+. public IntPtr GetMonsterHealthFn; + + //── v93: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ── + // No call blocks its caller (AC's main thread, the plugin pump and ImGui draws all call these). + + /// v93: int WebPanelOpen(WebPanelOpenNative* open): opens (or replaces) the web panel. + /// Returns a handle > 0, or BadArgs / UrlNotAllowed / NoGameWindow / Unavailable / ShuttingDown + /// (WebPanelCode). Requires API v93+ (provisional number). + public IntPtr WebPanelOpenFn; + /// v93: int WebPanelNavigate(int handle, byte* url): 1 queued; -2 off the allowlist + /// (opened in the system browser when it is browser-safe); -6 stale handle. + public IntPtr WebPanelNavigateFn; + /// v93: int WebPanelClose(int handle): 1 queued, 0 already closed, -6 stale handle. + public IntPtr WebPanelCloseFn; + /// v93: int WebPanelGetState(int handle, WebPanelStateNative* state): the WebPanelStatusCode + /// (a handle that is not the live one reads 6 Superseded), -1 bad args. + public IntPtr WebPanelGetStateFn; +} + +/// v93 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct WebPanelOpenNative +{ + /// sizeof the caller's struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86). + public uint Size; + /// WebPanelFlags; unknown bits ignored. + public uint Flags; + /// UTF-8 NUL-terminated, at most 4096 bytes, must pass the URL policy's IsAllowed. + public byte* Url; + /// UTF-8, '\n'-separated allowlist (WebPanelUrlPolicy.TryParseAllowlist). + public byte* Allowlist; + /// UTF-8, may be null; at most 256 bytes. + public byte* ProfileKey; + /// UTF-8, may be null; at most 128 bytes. + public byte* Title; + /// 0 = 88, else 30..100 (only when no remembered layout). + public int WidthPercent; + public int HeightPercent; + public fixed uint Reserved[4]; +} + +/// v93 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct WebPanelStateNative +{ + public uint Size; + public int Handle; + /// WebPanelStatusCode. + public int Status; + /// 1 Visible, 2 Focused, 4 OpenedInBrowser. + public uint Flags; + /// 0 or a negative WebPanelCode (RuntimeMissing / CreateFailed / ProcessFailed). + public int Error; + public int LastHttpStatus; + public uint NavigationCount; + public fixed uint Reserved[5]; +} + +/// v93 return codes of the web panel calls. Append only. +internal enum WebPanelCode +{ + Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3, + Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9, +} + +/// v93 WebPanelStateNative.Status values. Append only. +internal enum WebPanelStatusCode +{ + None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6, } /// v89 GetUiColor tokens. Append only: plugins compiled against these numbers keep them. @@ -1930,6 +1998,18 @@ internal unsafe delegate int GetAmbientLightCallbackDelegate(uint* client, uint* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetMonsterHealthCallbackDelegate(uint id, float* ratio, uint* ageMs); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int WebPanelOpenCallbackDelegate(WebPanelOpenNative* open); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int WebPanelNavigateCallbackDelegate(int handle, byte* url); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int WebPanelCloseCallbackDelegate(int handle); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int WebPanelGetStateCallbackDelegate(int handle, WebPanelStateNative* state); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 627dcad..774d6ba 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -47,5 +47,8 @@ internal static class PluginContractVersion // any thread (feature/hud-health-for-plugins, 2026-11-07). Note: feature/reload-state, // feature/engine-events and the branches built on them (unmerged) also use 93 and 94; whichever // merges second renumbers. + // v93: WebPanelOpen, WebPanelNavigate, WebPanelClose and WebPanelGetState: a WebView2 web panel over the + // game window (WebPanel\WebPanelApi.cs; DreamWeave's in-game market and tools). The number is + // PROVISIONAL: upstream may take 93 first, in which case this renumbers on merge. public const uint Current = 93; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index d939a73..e12b819 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -304,6 +304,12 @@ internal static partial class PluginManager private static SetAmbientLightFloorCallbackDelegate? _setAmbientLightFloorCallback; // v91 private static GetAmbientLightCallbackDelegate? _getAmbientLightCallback; // v91 private static GetMonsterHealthCallbackDelegate? _getMonsterHealthCallback; // v93 +#if ENGINE_CORECLR + private static WebPanelOpenCallbackDelegate? _webPanelOpenCallback; // v93 + private static WebPanelNavigateCallbackDelegate? _webPanelNavigateCallback; // v93 + private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v93 + private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v93 +#endif private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -3254,6 +3260,13 @@ internal static partial class PluginManager _setAmbientLightFloorCallback ??= AmbientLight.SetFloor; // v91 unsafe { _getAmbientLightCallback ??= AmbientLight.Get; } unsafe { _getMonsterHealthCallback ??= GetMonsterHealthAction; } // v93 +#if ENGINE_CORECLR + // v93: the AOT engine leaves these slots zero, so HasWebPanel is false there. + unsafe { _webPanelOpenCallback ??= WebPanel.WebPanelApi.Open; } + unsafe { _webPanelNavigateCallback ??= WebPanel.WebPanelApi.Navigate; } + _webPanelCloseCallback ??= WebPanel.WebPanelApi.Close; + unsafe { _webPanelGetStateCallback ??= WebPanel.WebPanelApi.GetState; } +#endif _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3427,6 +3440,12 @@ internal static partial class PluginManager _api.SetAmbientLightFloorFn = Marshal.GetFunctionPointerForDelegate(_setAmbientLightFloorCallback); _api.GetAmbientLightFn = Marshal.GetFunctionPointerForDelegate(_getAmbientLightCallback); _api.GetMonsterHealthFn = Marshal.GetFunctionPointerForDelegate(_getMonsterHealthCallback); +#if ENGINE_CORECLR + _api.WebPanelOpenFn = Marshal.GetFunctionPointerForDelegate(_webPanelOpenCallback!); + _api.WebPanelNavigateFn = Marshal.GetFunctionPointerForDelegate(_webPanelNavigateCallback!); + _api.WebPanelCloseFn = Marshal.GetFunctionPointerForDelegate(_webPanelCloseCallback!); + _api.WebPanelGetStateFn = Marshal.GetFunctionPointerForDelegate(_webPanelGetStateCallback!); +#endif RouteApiThroughLoader(); } diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs new file mode 100644 index 0000000..ae2c011 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs @@ -0,0 +1,19 @@ +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.WebPanel; + +/// +/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn). +/// Task 2 stub: every call answers Unavailable; the WebView2 host arrives in a later task. +/// No call here may block its caller (AC's main thread, the plugin pump and ImGui draws all call these). +/// +internal static class WebPanelApi +{ + public static unsafe int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable; + + public static unsafe int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable; + + public static int Close(int handle) => (int)WebPanelCode.Unavailable; + + public static unsafe int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable; +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs index f875638..b09ca79 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelProfile.cs @@ -1,3 +1,5 @@ +using System.IO; +using System; using System.Security.Cryptography; using System.Text; diff --git a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs index b572b54..230bd9b 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelUrlPolicy.cs @@ -1,3 +1,5 @@ +using System; +using System.Collections.Generic; using System.Text; namespace RynthCore.Engine.WebPanel; diff --git a/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs index 654edaa..405eaac 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelWindowPolicy.cs @@ -1,3 +1,4 @@ +using System; namespace RynthCore.Engine.WebPanel; internal readonly record struct PanelRect(int Left, int Top, int Right, int Bottom) diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 7a81114..fc6031d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -204,6 +204,11 @@ public struct RynthCoreApiNative public IntPtr GetAmbientLightFn; // int GetAmbientLight(uint* client, uint* applied) -> 1 hook live, 0 not // v93: the monster plates' last server health reading per object public IntPtr GetMonsterHealthFn; // int GetMonsterHealth(uint id, float* ratio, uint* ageMs) -> 1 reading, 0 none + // v93: a WebView2 web panel over the game window (APPEND-AT-END (ABI); number provisional) + public IntPtr WebPanelOpenFn; // int WebPanelOpen(WebPanelOpenNative*) -> handle > 0, or BadArgs/UrlNotAllowed/NoGameWindow/Unavailable/ShuttingDown + public IntPtr WebPanelNavigateFn; // int WebPanelNavigate(int handle, byte* url) -> 1 queued; -2 off-list; -6 stale + public IntPtr WebPanelCloseFn; // int WebPanelClose(int handle) -> 1 queued, 0 already closed, -6 stale + public IntPtr WebPanelGetStateFn; // int WebPanelGetState(int handle, WebPanelStateNative*) -> Status (non-live handle -> 6 Superseded), -1 bad args } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 00fc926..223bf4d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -1877,6 +1877,119 @@ public readonly unsafe struct RynthCoreHost return true; } + // ── v93: a web panel over the game window (number provisional) ─────────── + + /// + /// v93: , , and + /// . True only on an engine at API 93 or newer that fills all four. + /// + public bool HasWebPanel => _api.Version >= 93 && _api.WebPanelOpenFn != IntPtr.Zero && _api.WebPanelNavigateFn != IntPtr.Zero + && _api.WebPanelCloseFn != IntPtr.Zero && _api.WebPanelGetStateFn != IntPtr.Zero; + + /// + /// v93: opens the web panel over the game window (a second call replaces the first). Returns a handle + /// > 0, or a (BadArgs for an empty URL or allowlist, more than 16 + /// entries or a newline inside one; Unavailable on an older engine). Never blocks; the panel loads + /// after this returns - poll . Any thread. + /// + public int OpenWebPanel(WebPanelOptions options) + { + if (options == null || string.IsNullOrEmpty(options.Url) || options.Allowlist == null + || options.Allowlist.Count < 1 || options.Allowlist.Count > 16) + return (int)WebPanelResult.BadArgs; + foreach (string entry in options.Allowlist) + if (string.IsNullOrEmpty(entry) || entry.Contains('\n')) return (int)WebPanelResult.BadArgs; + if (!HasWebPanel) return (int)WebPanelResult.Unavailable; + + string allowlist = string.Join("\n", options.Allowlist); + string profile = options.ProfileKey ?? ""; + string title = options.Title ?? ""; + var enc = System.Text.Encoding.UTF8; + int nUrl = enc.GetByteCount(options.Url), nAllow = enc.GetByteCount(allowlist); + int nProfile = enc.GetByteCount(profile), nTitle = enc.GetByteCount(title); + int total = nUrl + nAllow + nProfile + nTitle + 4; + + byte[]? rented = null; + Span buf = total <= 1024 ? stackalloc byte[total] : (rented = System.Buffers.ArrayPool.Shared.Rent(total)).AsSpan(0, total); + try + { + int o = 0; + int oUrl = o; o += enc.GetBytes(options.Url, buf[o..]); buf[o++] = 0; + int oAllow = o; o += enc.GetBytes(allowlist, buf[o..]); buf[o++] = 0; + int oProfile = o; o += enc.GetBytes(profile, buf[o..]); buf[o++] = 0; + int oTitle = o; o += enc.GetBytes(title, buf[o..]); buf[o++] = 0; + fixed (byte* b = buf) + { + var open = new WebPanelOpenNative + { + Size = (uint)sizeof(WebPanelOpenNative), + Flags = (uint)options.Flags, + Url = b + oUrl, + Allowlist = b + oAllow, + ProfileKey = nProfile == 0 ? null : b + oProfile, + Title = nTitle == 0 ? null : b + oTitle, + WidthPercent = options.WidthPercent, + HeightPercent = options.HeightPercent, + }; + return ((delegate* unmanaged[Cdecl])_api.WebPanelOpenFn)(&open); + } + } + finally + { + if (rented != null) System.Buffers.ArrayPool.Shared.Return(rented); + } + } + + /// + /// v93: points the panel at . 1 queued; -2 + /// (UrlNotAllowed) when it is off the allowlist (the engine opens it in the system browser when that is + /// safe); -6 (StaleHandle) when the handle is not the live panel. Never blocks. Any thread. + /// + public int NavigateWebPanel(int handle, string url) + { + if (string.IsNullOrEmpty(url)) return (int)WebPanelResult.BadArgs; + if (!HasWebPanel) return (int)WebPanelResult.Unavailable; + int n = System.Text.Encoding.UTF8.GetByteCount(url); + byte[]? rented = null; + Span buf = n + 1 <= 1024 ? stackalloc byte[n + 1] : (rented = System.Buffers.ArrayPool.Shared.Rent(n + 1)).AsSpan(0, n + 1); + try + { + System.Text.Encoding.UTF8.GetBytes(url, buf); + buf[n] = 0; + fixed (byte* p = buf) + return ((delegate* unmanaged[Cdecl])_api.WebPanelNavigateFn)(handle, p); + } + finally + { + if (rented != null) System.Buffers.ArrayPool.Shared.Return(rented); + } + } + + /// v93: closes the panel . 1 queued, 0 already closed, -6 stale handle. Never blocks. Any thread. + public int CloseWebPanel(int handle) + { + if (!HasWebPanel) return (int)WebPanelResult.Unavailable; + return ((delegate* unmanaged[Cdecl])_api.WebPanelCloseFn)(handle); + } + + /// + /// v93: where the panel is. A handle that is not the live panel reads + /// Superseded. None (and a default ) on an older engine or bad arguments. + /// Any thread. + /// + public WebPanelStatus GetWebPanelState(int handle, out WebPanelState state) + { + state = default; + if (!HasWebPanel) return WebPanelStatus.None; + WebPanelStateNative native = default; + native.Size = (uint)sizeof(WebPanelStateNative); + int r = ((delegate* unmanaged[Cdecl])_api.WebPanelGetStateFn)(handle, &native); + if (r < 0) return WebPanelStatus.None; + var status = (WebPanelStatus)native.Status; + state = new WebPanelState(native.Handle, status, (WebPanelStateFlags)native.Flags, (WebPanelResult)native.Error, native.LastHttpStatus, native.NavigationCount); + return status; + } + private int CallSetActionKey(string action, string key, int op, out string message) { message = string.Empty; diff --git a/src/RynthCore.PluginSdk/WebPanelTypes.cs b/src/RynthCore.PluginSdk/WebPanelTypes.cs new file mode 100644 index 0000000..b05d4e0 --- /dev/null +++ b/src/RynthCore.PluginSdk/WebPanelTypes.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.PluginSdk; + +// v93: a WebView2 web panel over the game window. The native structs mirror +// RynthCore.Engine/Plugins/PluginContract.cs field for field (tools\PluginManifestTests checks sizes and +// offsets). The API number is provisional. + +/// v93 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors the engine's WebPanelOpenNative. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct WebPanelOpenNative +{ + /// sizeof this struct; the engine accepts Size >= OffsetOf(Reserved) (32 on x86). + public uint Size; + /// ; unknown bits ignored. + public uint Flags; + /// UTF-8 NUL-terminated, at most 4096 bytes. + public byte* Url; + /// UTF-8, '\n'-separated allowlist. + public byte* Allowlist; + /// UTF-8, may be null; at most 256 bytes. + public byte* ProfileKey; + /// UTF-8, may be null; at most 128 bytes. + public byte* Title; + /// 0 = 88, else 30..100 (only when no remembered layout). + public int WidthPercent; + public int HeightPercent; + public fixed uint Reserved[4]; +} + +/// v93 WebPanelGetState result (Pack 4; 48 bytes). Mirrors the engine's WebPanelStateNative. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct WebPanelStateNative +{ + public uint Size; + public int Handle; + /// . + public int Status; + /// . + public uint Flags; + /// 0 or a negative (RuntimeMissing / CreateFailed / ProcessFailed). + public int Error; + public int LastHttpStatus; + public uint NavigationCount; + public fixed uint Reserved[5]; +} + +/// Options for . +[Flags] +public enum WebPanelFlags : uint +{ + None = 0, + /// When the panel cannot open (no WebView2 runtime, creation failed), open the URL in the system browser. + FallbackToBrowser = 1, + /// Escape goes to the page instead of closing the panel. + PageKeepsEscape = 2, + // 4 is reserved: phase 2 EnableMessages. +} + +/// Results of the web panel calls; an open that succeeds returns a handle > 0 instead. +public enum WebPanelResult : int +{ + Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3, + Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9, +} + +/// Where the web panel is in its life. +public enum WebPanelStatus : int +{ + None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6, +} + +[Flags] +public enum WebPanelStateFlags : uint +{ + None = 0, Visible = 1, Focused = 2, OpenedInBrowser = 4, +} + +/// A snapshot of the web panel from . +public readonly record struct WebPanelState(int Handle, WebPanelStatus Status, WebPanelStateFlags Flags, WebPanelResult Error, int LastHttpStatus, uint NavigationCount); + +public sealed class WebPanelOptions +{ + public required string Url { get; init; } + /// 1..16 entries, no '\n' inside an entry. + public required IReadOnlyList Allowlist { get; init; } + /// Opaque; the engine lower-cases, hashes and adds the world. + public string ProfileKey { get; init; } = ""; + public string Title { get; init; } = ""; + public int WidthPercent { get; init; } = 0; + public int HeightPercent { get; init; } = 0; + public WebPanelFlags Flags { get; init; } = WebPanelFlags.FallbackToBrowser; +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 93b6dc3..c083089 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -59,6 +59,10 @@ internal static class Program Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); Run(nameof(ContainerOrderSlots), ContainerOrderSlots); + Run(nameof(WebPanelFieldsAppended), WebPanelFieldsAppended); + Run(nameof(WebPanelStructsMatch), WebPanelStructsMatch); + Run(nameof(WebPanelCodesMatch), WebPanelCodesMatch); + Run(nameof(HasWebPanel_FalseOnOldOrPartialTable), HasWebPanel_FalseOnOldOrPartialTable); Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum); Run(nameof(DedupeSamePathTwice), DedupeSamePathTwice); Run(nameof(DedupeCaseAndSlashes), DedupeCaseAndSlashes); @@ -589,6 +593,91 @@ internal static class Program "targets: the manifest and the runtime attribute both use the derived minimum"); } + // v93: the web panel's four slots are appended right after GetMonsterHealthFn, in order, on both sides. + private static void WebPanelFieldsAppended() + { + string[] slots = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; + string prev = "GetMonsterHealthFn"; + foreach (string slot in slots) + { + Eq((int)Marshal.OffsetOf(slot), + (int)Marshal.OffsetOf(prev) + IntPtr.Size, "engine " + slot + " right after " + prev); + Eq((int)Marshal.OffsetOf(slot), + (int)Marshal.OffsetOf(prev) + IntPtr.Size, "SDK " + slot + " right after " + prev); + prev = slot; + } + Eq(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "engine table: GetMonsterHealthFn precedes the four"); + Eq(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(4).Last(), "GetMonsterHealthFn", "SDK table: GetMonsterHealthFn precedes the four"); + } + + private static void StructMirror(Type engine, Type sdk, int size) + { + Eq(Marshal.SizeOf(engine), size, "engine " + engine.Name + " size"); + Eq(Marshal.SizeOf(sdk), size, "SDK " + sdk.Name + " size"); + var ef = engine.GetFields().Select(f => f.Name).ToArray(); + var sf = sdk.GetFields().Select(f => f.Name).ToArray(); + Check(ef.SequenceEqual(sf), engine.Name + " field names/order match: " + string.Join(",", ef) + " vs " + string.Join(",", sf)); + foreach (string f in ef) + Eq((int)Marshal.OffsetOf(sdk, f), (int)Marshal.OffsetOf(engine, f), engine.Name + "." + f + " offset"); + } + + // v93: the SDK's WebPanelOpenNative/WebPanelStateNative are the engine's, byte for byte. + private static void WebPanelStructsMatch() + { + int p = IntPtr.Size; + StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelOpenNative), typeof(RynthCore.PluginSdk.WebPanelOpenNative), 8 + 4 * p + 8 + 16); + StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelStateNative), typeof(RynthCore.PluginSdk.WebPanelStateNative), 48); + Eq((int)Marshal.OffsetOf("Reserved"), 8 + 4 * p + 8, "engine WebPanelOpenNative.Reserved offset (32 on x86)"); + } + + // v93: every code value agrees between the engine's enums and the SDK's. + private static void WebPanelCodesMatch() + { + Dictionary Vals(Type t) => Enum.GetNames(t).ToDictionary(n => n, n => Convert.ToInt64(Enum.Parse(t, n))); + var engine = Vals(typeof(RynthCore.Engine.Plugins.WebPanelCode)); + var sdk = Vals(typeof(RynthCore.PluginSdk.WebPanelResult)); + Eq(sdk.Count, engine.Count, "WebPanelCode vs WebPanelResult member count"); + foreach (var kv in engine) + Check(sdk.TryGetValue(kv.Key, out long v) && v == kv.Value, "WebPanelResult." + kv.Key + " = " + kv.Value); + var es = Vals(typeof(RynthCore.Engine.Plugins.WebPanelStatusCode)); + var ss = Vals(typeof(RynthCore.PluginSdk.WebPanelStatus)); + Eq(ss.Count, es.Count, "WebPanelStatusCode vs WebPanelStatus member count"); + foreach (var kv in es) + Check(ss.TryGetValue(kv.Key, out long v) && v == kv.Value, "WebPanelStatus." + kv.Key + " = " + kv.Value); + Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.Visible, 1u, "state flag Visible"); + Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.Focused, 2u, "state flag Focused"); + Eq((uint)RynthCore.PluginSdk.WebPanelStateFlags.OpenedInBrowser, 4u, "state flag OpenedInBrowser"); + Eq((uint)RynthCore.PluginSdk.WebPanelFlags.FallbackToBrowser, 1u, "open flag FallbackToBrowser"); + Eq((uint)RynthCore.PluginSdk.WebPanelFlags.PageKeepsEscape, 2u, "open flag PageKeepsEscape"); + } + + // v93: HasWebPanel needs Version >= 93 AND all four slots (an old engine's table is shorter and the + // runtime copies the full new-size struct, so slots past its end are garbage, not zero). + private static void HasWebPanel_FalseOnOldOrPartialTable() + { + IntPtr x = (IntPtr)0xDEAD; + RynthCoreHost Host(uint version, IntPtr a, IntPtr b, IntPtr c, IntPtr d) + => new RynthCoreHost(new RynthCoreApiNative { Version = version, WebPanelOpenFn = a, WebPanelNavigateFn = b, WebPanelCloseFn = c, WebPanelGetStateFn = d }); + Check(!Host(92, x, x, x, x).HasWebPanel, "Version 92 with garbage slots: false"); + Check(!Host(93, IntPtr.Zero, x, x, x).HasWebPanel, "Open zero: false"); + Check(!Host(93, x, IntPtr.Zero, x, x).HasWebPanel, "Navigate zero: false"); + Check(!Host(93, x, x, IntPtr.Zero, x).HasWebPanel, "Close zero: false"); + Check(!Host(93, x, x, x, IntPtr.Zero).HasWebPanel, "GetState zero: false"); + Check(Host(93, x, x, x, x).HasWebPanel, "Version 93, all four: true"); + var old = Host(92, x, x, x, x); + Eq(old.OpenWebPanel(new WebPanelOptions { Url = "https://a.example/", Allowlist = new[] { "a.example" } }), (int)WebPanelResult.Unavailable, "Open without the API: Unavailable"); + Eq(old.NavigateWebPanel(1, "https://a.example/"), (int)WebPanelResult.Unavailable, "Navigate without the API: Unavailable"); + Eq(old.CloseWebPanel(1), (int)WebPanelResult.Unavailable, "Close without the API: Unavailable"); + Eq(old.GetWebPanelState(1, out var st), WebPanelStatus.None, "GetState without the API: None"); + Eq(st.Handle, 0, "GetState without the API: default state"); + // Bad arguments are refused before the engine is called (the slots hold garbage, so a call would crash). + var live = Host(93, x, x, x, x); + Eq(live.OpenWebPanel(new WebPanelOptions { Url = "", Allowlist = new[] { "a" } }), (int)WebPanelResult.BadArgs, "empty URL: BadArgs"); + Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = Array.Empty() }), (int)WebPanelResult.BadArgs, "empty allowlist: BadArgs"); + Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = new[] { "a\nb" } }), (int)WebPanelResult.BadArgs, "newline in an entry: BadArgs"); + Eq(live.NavigateWebPanel(1, ""), (int)WebPanelResult.BadArgs, "navigate empty URL: BadArgs"); + } + // v79: the SDK's copies of the training structs must be the engine's, byte for byte. private static void TrainingStructsMirror() { @@ -603,11 +692,11 @@ internal static class Program Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow: - // eleven slots to v89, then v90's thirteen, v91's two and v93's one). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(27).TakeLast(6).ToArray(); + // eleven slots to v89, then v90's thirteen, v91's two, v93's one and the web panel's four). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(27).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } @@ -618,6 +707,12 @@ internal static class Program { var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); + // v93: the web panel's four slots end the table; the checks after these are on the table before them. + string[] v93 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; + Check(all.TakeLast(v93.Length).SequenceEqual(v93), "v93 slots last: " + string.Join(",", all.TakeLast(v93.Length))); + Check(sdkAll.TakeLast(v93.Length).SequenceEqual(v93), "SDK v93 slots last: " + string.Join(",", sdkAll.TakeLast(v93.Length))); + all = all.SkipLast(v93.Length).ToArray(); + sdkAll = sdkAll.SkipLast(v93.Length).ToArray(); // v93: the monster plates' health readings end the table (2026-11-07), right after v91's two. Check(all.Last() == "GetMonsterHealthFn", "v93 slot last: " + all.Last()); Check(sdkAll.Last() == "GetMonsterHealthFn", "SDK v93 slot last: " + sdkAll.Last()); -- 2.43.0 From 2841df63be62b232cd33f5dbf0f8fa0376840805 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:34:35 -0800 Subject: [PATCH 05/17] Web panel ABI: x86 struct assertions, restore v93 divider encoding WebPanelStructsMatch now asserts 48 bytes / Reserved at 32 on x86 for engine and SDK types when run 32-bit. PluginContract.cs v93 divider was double-encoded (cp1252 read of UTF-8); restored to box-drawing chars. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/Plugins/PluginContract.cs | 2 +- tools/PluginManifestTests/Program.cs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 1e2d842..184e460 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -1070,7 +1070,7 @@ internal struct RynthCoreAPI /// Read-only, any thread, no game calls. Requires API v93+. public IntPtr GetMonsterHealthFn; - //── v93: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ── + // ── v93: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ── // No call blocks its caller (AC's main thread, the plugin pump and ImGui draws all call these). /// v93: int WebPanelOpen(WebPanelOpenNative* open): opens (or replaces) the web panel. diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index c083089..77a581a 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -628,6 +628,17 @@ internal static class Program StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelOpenNative), typeof(RynthCore.PluginSdk.WebPanelOpenNative), 8 + 4 * p + 8 + 16); StructMirror(typeof(RynthCore.Engine.Plugins.WebPanelStateNative), typeof(RynthCore.PluginSdk.WebPanelStateNative), 48); Eq((int)Marshal.OffsetOf("Reserved"), 8 + 4 * p + 8, "engine WebPanelOpenNative.Reserved offset (32 on x86)"); + // The 32-bit AC client's contract: 48 bytes, Reserved at 32 (only checked when this run is x86). + if (IntPtr.Size == 4) + { + Eq(Marshal.SizeOf(), 48, "x86 engine WebPanelOpenNative size"); + Eq(Marshal.SizeOf(), 48, "x86 SDK WebPanelOpenNative size"); + Eq((int)Marshal.OffsetOf("Reserved"), 32, "x86 engine WebPanelOpenNative.Reserved offset"); + Eq((int)Marshal.OffsetOf("Reserved"), 32, "x86 SDK WebPanelOpenNative.Reserved offset"); + Eq(Marshal.SizeOf(), 48, "x86 engine WebPanelStateNative size"); + Eq(Marshal.SizeOf(), 48, "x86 SDK WebPanelStateNative size"); + } + Console.WriteLine($" (WebPanelStructsMatch ran with IntPtr.Size={IntPtr.Size})"); } // v93: every code value agrees between the engine's enums and the SDK's. -- 2.43.0 From f130be3d2b087b27018e6a69dfa3afc6f9f7d373 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:04:01 -0800 Subject: [PATCH 06/17] Web panel host: STA thread, WebView2 lifetime, allowlist, focus, visibility; offline harness WebPanelHost (CoreCLR engine only): one unowned WS_POPUP over the game client area on its own STA thread and GetMessage loop, lifted from the 2026-11-07 spike's popup-free path. Open/Navigate/Close/GetState never block: they validate, update the caller-visible state under a lock, queue work and post WM_APP+1 to the host window. WebView2Loader.dll is loaded by full path from the shim's Runtime folder; the runtime probe on the panel thread decides RuntimeMissing, any later creation failure is CreateFailed. Navigation guard (NavigationStarting incl. redirects, NewWindowRequested, LaunchingExternalUriScheme): off-list http/https goes to the system browser, anything else is dropped; logs carry only Redact()ed URLs or hosts. Escape via AcceleratorKeyPressed unless PageKeepsEscape. Visibility by the PID rule on a 50 ms timer plus a foreground WinEvent; raises only when below the game; layout remembered in layout.json. Shutdown unhooks, closes the controller, destroys the window and unregisters the class before the collectible context unloads. WebPanelNativeArgs copies every string out of the caller's (stack or pooled) buffers before anything is queued. WebPanelApi is the ABI glue (AOT keeps the Unavailable stub). engine.json "WebPanel" (default true) is the kill switch. EngineLifecycle shuts the panel down after EndSceneHook.Uninstall. The WebView2 package's WinForms/WPF references are dropped before reference resolution. Deviations from the brief: IWebPanelEnvironment gains BrowserExecutableFolderForTests (the harness forces a creation failure with it) and is excluded from the AOT build with the host; Show only takes the foreground when it is already in this process (or none). tools\WebPanelHarness (x86 exe) + tools\WebPanelHarness.Payload: fake game thread, fake 16 ms pump, collectible context mirroring EngineLoadContext, local virtual hosts, posted input only. 17 ok, 0 FAIL, 4 UNVERIFIED offline (Escape via posted input never raises AcceleratorKeyPressed; visibility needs the foreground): owner in-game checks. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/EngineLifecycle.cs | 5 + .../Plugins/EngineSettings.cs | 30 +- src/RynthCore.Engine/RynthCore.Engine.csproj | 27 + .../WebPanel/EngineWebPanelEnvironment.cs | 63 ++ .../WebPanel/IWebPanelEnvironment.cs | 32 + src/RynthCore.Engine/WebPanel/WebPanelApi.cs | 137 ++- src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 977 ++++++++++++++++++ .../WebPanel/WebPanelLayoutStore.cs | 80 ++ .../WebPanel/WebPanelNative.cs | 95 ++ .../WebPanel/WebPanelNativeArgs.cs | 55 + tools/WebPanelHarness.Payload/PayloadEntry.cs | 149 +++ .../WebPanelHarness.Payload.csproj | 51 + tools/WebPanelHarness/Program.cs | 938 +++++++++++++++++ tools/WebPanelHarness/WebPanelHarness.csproj | 52 + 14 files changed, 2682 insertions(+), 9 deletions(-) create mode 100644 src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs create mode 100644 src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelHost.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelNative.cs create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs create mode 100644 tools/WebPanelHarness.Payload/PayloadEntry.cs create mode 100644 tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj create mode 100644 tools/WebPanelHarness/Program.cs create mode 100644 tools/WebPanelHarness/WebPanelHarness.csproj diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index f10593d..b45b966 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -172,6 +172,11 @@ internal static class EngineLifecycle // we tear down anything else. Thread.Sleep(80); + // The web panel after the plugins' own Shutdowns (EndSceneHook.Uninstall above runs them, and they + // may still Close it): its STA thread, window class, WinEvent hook and WebView2 objects go before + // the collectible engine context unloads. + Step("WebPanelApi.Shutdown", () => WebPanel.WebPanelApi.Shutdown()); + Step("AvaloniaOverlay.Stop", () => AvaloniaOverlay.Stop()); // Restore AC's original window WndProc. EngineFrameController.Shutdown diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 1e707e0..4044725 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -70,6 +70,8 @@ internal static class EngineSettings private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode; // "TransitionGate": default true. False = queued game actions are never held for a death / portal. private static bool _transitionGate = true; + // "WebPanel": default true. False = the v93 web panel calls answer Unavailable (plugins open the system browser). + private static bool _webPanel = true; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -714,6 +716,26 @@ internal static class EngineSettings } } + /// "WebPanel" in engine.json (default true): the v93 web panel (WebPanel\WebPanelHost.cs, a + /// WebView2 window over the game for DreamWeave's market and tools; CoreCLR engine only). False is the + /// kill switch: WebPanelOpen answers Unavailable and plugins open the page in the system browser + /// instead. A panel already open stays until it is closed. + public static bool WebPanel + { + get + { + EnsureLoaded(); + return _webPanel; + } + set + { + EnsureLoaded(); + if (_webPanel == value) return; + _webPanel = value; + Save("WebPanel"); + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -919,6 +941,10 @@ internal static class EngineSettings (tgEl.ValueKind == JsonValueKind.True || tgEl.ValueKind == JsonValueKind.False)) _transitionGate = tgEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("WebPanel", out var wpEl) && + (wpEl.ValueKind == JsonValueKind.True || wpEl.ValueKind == JsonValueKind.False)) + _webPanel = wpEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { @@ -989,7 +1015,7 @@ internal static class EngineSettings "FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout", "RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", - "LoadAllServerPlugins", "TransitionGate", + "LoadAllServerPlugins", "TransitionGate", "WebPanel", "HoldReloadInWorld", "HoldReloadInWorldMaxMinutes", "PanelLayoutPerCharacter", "UiCostLog", "UiCostThresholdMs", @@ -1070,6 +1096,8 @@ internal static class EngineSettings w.WriteBoolean("CloseOnServerDisconnect", false); if (!_transitionGate) // default true: only a hand-set false is written w.WriteBoolean("TransitionGate", false); + if (!_webPanel) // default true: only a hand-set false is written + w.WriteBoolean("WebPanel", false); if (_loadAllServerPlugins) // default false: only a hand-set true is written w.WriteBoolean("LoadAllServerPlugins", true); if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index df21097..20ff4a7 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -43,8 +43,35 @@ true false portable + + false + Dynamic + + + + + + + + + + + + + + + + + + + true full diff --git a/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs b/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs new file mode 100644 index 0000000..49b42ac --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/EngineWebPanelEnvironment.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Reflection; +using System.Threading; +using Microsoft.Web.WebView2.Core; + +namespace RynthCore.Engine.WebPanel; + +/// The web panel host's surroundings inside acclient.exe (CoreCLR engine only). +internal sealed class EngineWebPanelEnvironment : IWebPanelEnvironment +{ + private readonly string _runtimeDir = FindRuntimeDir(); + + public IntPtr GameHwnd + { + get + { + IntPtr h = ImGuiBackend.Win32Backend.GameHwnd; + return h != IntPtr.Zero ? h : EntryPoint.GameHwnd; + } + } + + /// + /// Runtime\: the folder of the loaded RynthCore.Shim assembly, as ManagedPlugins.FindSharedDir finds it. + /// Never this assembly's Location: the engine is stream-loaded, so that is empty. + /// + public string RuntimeDir => _runtimeDir; + + public string LocalAppData => Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + + public string WorldName => Compatibility.AccountHooks.TryGetWorldName(out string name) ? name : ""; + + public void Log(string line) => RynthLog.Info("WebPanel: " + line); + + public void Chat(string line) => Compatibility.ClientHelperHooks.WriteToChat(line, 1); + + public bool OpenInBrowser(string url) + { + if (!WebPanelUrlPolicy.IsBrowserSafe(url)) return false; + IntPtr r = WebPanelNative.ShellExecuteW(IntPtr.Zero, "open", url, null, null, WebPanelNative.SW_SHOWNORMAL); + return r.ToInt64() > 32; + } + + public Thread StartStaThread(string name, ThreadStart body) => EngineThreads.Start(name, body, ApartmentState.STA); + + public Action? ConfigureForTests => null; + public int EnvironmentDelayMsForTests => 0; + public string? BrowserExecutableFolderForTests => null; + + private static string FindRuntimeDir() + { + try + { + foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) + { + if (a.GetName().Name != "RynthCore.Shim" || string.IsNullOrEmpty(a.Location)) continue; + return Path.GetDirectoryName(a.Location) ?? ""; + } + } + catch { } + return ""; + } +} diff --git a/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs b/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs new file mode 100644 index 0000000..e939b33 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/IWebPanelEnvironment.cs @@ -0,0 +1,32 @@ +using System; +using System.Threading; + +namespace RynthCore.Engine.WebPanel; + +/// +/// What the web panel host needs from its surroundings: the engine (EngineWebPanelEnvironment) or the +/// offline harness (tools\WebPanelHarness.Payload). CoreCLR engine only. +/// +internal interface IWebPanelEnvironment +{ + IntPtr GameHwnd { get; } + /// Folder holding WebView2Loader.dll and Microsoft.Web.WebView2.Core.dll. + string RuntimeDir { get; } + /// Profile and layout root (the harness: a temp folder). + string LocalAppData { get; } + /// "" when unknown. + string WorldName { get; } + /// Only ever given WebPanelUrlPolicy.Redact()ed URLs or hosts. + void Log(string line); + /// Any thread. + void Chat(string line); + /// IsBrowserSafe URLs only; the harness records instead of launching. + bool OpenInBrowser(string url); + Thread StartStaThread(string name, ThreadStart body); + /// Null in the engine. + Action? ConfigureForTests { get; } + /// 0 in the engine. + int EnvironmentDelayMsForTests { get; } + /// Null in the engine (the installed Evergreen runtime); the harness forces a creation failure with it. + string? BrowserExecutableFolderForTests { get; } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs index ae2c011..f973f3c 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs @@ -2,18 +2,139 @@ using RynthCore.Engine.Plugins; namespace RynthCore.Engine.WebPanel; +#if ENGINE_CORECLR /// -/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn). -/// Task 2 stub: every call answers Unavailable; the WebView2 host arrives in a later task. -/// No call here may block its caller (AC's main thread, the plugin pump and ImGui draws all call these). +/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn): reads +/// the native arguments (every string copied before the call returns) and hands them to the one +/// WebPanelHost. No call here blocks its caller (AC's main thread, the plugin pump and ImGui draws all call +/// these). engine.json "WebPanel": false makes Open answer Unavailable (plugins fall back to the browser). /// -internal static class WebPanelApi +internal static unsafe class WebPanelApi { - public static unsafe int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable; + private const int ShutdownBudgetMs = 2000; + private static readonly object Sync = new(); + private static WebPanelHost? s_host; + private static EngineWebPanelEnvironment? s_env; + private static volatile bool s_shutdown; - public static unsafe int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable; + internal static int Open(WebPanelOpenNative* open) + { + try + { + if (s_shutdown || EngineLifecycle.IsShuttingDown) return (int)WebPanelCode.ShuttingDown; + if (!EngineSettings.WebPanel) return (int)WebPanelCode.Unavailable; + EngineWebPanelEnvironment env; + WebPanelHost host; + lock (Sync) + { + if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + env = s_env ??= new EngineWebPanelEnvironment(); + host = s_host ??= new WebPanelHost(env); + } + int rc = WebPanelNativeArgs.TryBuildRequest(open, env.LocalAppData, env.WorldName, out WebPanelRequest? request); + if (rc != 0) return rc; + return host.Open(request!); + } + catch (System.Exception ex) + { + RynthLog.Info("WebPanel: Open failed: " + ex.GetType().Name); + return (int)WebPanelCode.Unavailable; + } + } - public static int Close(int handle) => (int)WebPanelCode.Unavailable; + internal static int Navigate(int handle, byte* urlUtf8) + { + try + { + if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + 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); + } + catch (System.Exception ex) + { + RynthLog.Info("WebPanel: Navigate failed: " + ex.GetType().Name); + return (int)WebPanelCode.Unavailable; + } + } - public static unsafe int GetState(int handle, WebPanelStateNative* state) => (int)WebPanelCode.Unavailable; + internal static int Close(int handle) + { + try + { + if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + WebPanelHost? host = s_host; + return host == null ? (int)WebPanelCode.StaleHandle : host.Close(handle); + } + catch (System.Exception ex) + { + RynthLog.Info("WebPanel: Close failed: " + ex.GetType().Name); + return (int)WebPanelCode.Unavailable; + } + } + + internal static int GetState(int handle, WebPanelStateNative* state) + { + try + { + if (state == null || state->Size < (uint)((byte*)state->Reserved - (byte*)state)) return (int)WebPanelCode.BadArgs; + if (s_shutdown) return (int)WebPanelCode.ShuttingDown; + 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; + } + 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; + return r; + } + catch (System.Exception ex) + { + RynthLog.Info("WebPanel: GetState failed: " + ex.GetType().Name); + return (int)WebPanelCode.Unavailable; + } + } + + /// EngineLifecycle, after the plugins' own Shutdowns (they may still Close). Idempotent. + internal static void Shutdown() + { + WebPanelHost? host; + lock (Sync) + { + s_shutdown = true; + host = s_host; + } + host?.Shutdown(ShutdownBudgetMs); + } + + /// Redacted one-liner (no query, fragment or userinfo). + internal static string Describe() + { + WebPanelHost? host = s_host; + string enabled = EngineSettings.WebPanel ? "on" : "off (engine.json WebPanel)"; + return host == null ? "web panel: " + enabled + ", not started" : host.Describe() + "; setting " + enabled; + } } +#else +/// The NativeAOT engine has no web panel: PluginManager leaves the v93 slots zero (HasWebPanel false). +internal static unsafe class WebPanelApi +{ + internal static int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable; + internal static int Navigate(int handle, byte* url) => (int)WebPanelCode.Unavailable; + 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 string Describe() => "web panel: not available in this engine build"; +} +#endif diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs new file mode 100644 index 0000000..9f8e60d --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -0,0 +1,977 @@ +// ============================================================================ +// RynthCore.Engine - WebPanel/WebPanelHost.cs (CoreCLR engine only) +// +// One WebView2 panel over the game's client area, on a dedicated STA thread with its own +// GetMessage loop and an UNOWNED WS_POPUP host window (an owned popup would attach the game's +// input queue). Lifted from the 2026-11-07 spike (spikes\webview2\RynthWebSpike\WebPanel.cs, +// popup-free path), which ran it inside a live acclient. +// +// Threads: Open/Navigate/Close/GetState run on any thread (AC's main thread, the plugin pump, +// ImGui draws) and never block: they validate, update the caller-visible state under _sync, +// queue work and post WM_RUN to the host window. Everything that touches Win32 windows or +// WebView2 runs on the panel thread. Shutdown posts the teardown and joins within a budget. +// +// Lifetime: everything started or registered here (thread, window class, WinEvent hook, timer, +// WebView2 controller/environment) is torn down by Shutdown, before the collectible engine +// context unloads. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.IO; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Web.WebView2.Core; +using RynthCore.Engine.Plugins; +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; + private const int CaptionPx = 28, CloseBoxPx = 34; + private const uint FlagFallback = 1, FlagPageKeepsEscape = 2; + private const uint StateVisible = 1, StateFocused = 2, StateOpenedInBrowser = 4; + private const uint VK_ESCAPE = 0x1B; + private static readonly IntPtr TimerId = (IntPtr)1; + private static readonly uint Background = Rgb(32, 32, 36), CaptionColor = Rgb(44, 44, 50), TextColor = Rgb(222, 222, 228); + + // The WndProc and WinEvent target. One live host per engine generation (WebPanelApi holds it). + private static WebPanelHost? s_active; + private static int s_classSeq; + + private readonly IWebPanelEnvironment _env; + private readonly uint _ourPid = GetCurrentProcessId(); + + // ---- caller-visible state: under _sync ---- + private readonly object _sync = new(); + private readonly ConcurrentQueue _queue = new(); + private int _nextHandle; + private int _live; + private int _status; + private uint _flags; + private int _error, _http; + private uint _navCount; + private string _liveUrl = ""; + private bool _shuttingDown; + private Thread? _thread; + private bool _threadDone; + private IntPtr _hwnd; // published once the window exists; WM_RUN goes here + + // ---- panel thread only ---- + private IntPtr _staHwnd, _hook, _bgBrush, _captionBrush; + private string _className = ""; + private bool _windowFailed, _tornDown, _open, _timerOn, _inSizeMove; + private int _serving; // the handle whose request the panel shows + private WebPanelRequest? _req; + private string _title = "RynthCore"; + private PanelFractions _fractions = WebPanelWindowPolicy.Default(0, 0); + private string _pendingUrl = ""; + private bool _loaderLoaded; + private CoreWebView2Environment? _wvEnv; + private CoreWebView2Controller? _ctl; + private CoreWebView2? _web; + private string? _profileFolder; + private bool _creating, _needsRecreate; + private int _createSeq; + + // ---- diagnostics (Describe and the offline harness) ---- + private volatile int _environmentCount, _acceleratorEvents; + private volatile uint _browserPid; + private volatile string _source = ""; + + public WebPanelHost(IWebPanelEnvironment env) => _env = env; + + // ============================ any thread ============================ + + public int Open(WebPanelRequest request) + { + if (request == null) return (int)WebPanelCode.BadArgs; + lock (_sync) if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (!WebPanelUrlPolicy.IsAllowed(request.Url, request.Allowlist)) return (int)WebPanelCode.UrlNotAllowed; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !IsWindow(game)) return (int)WebPanelCode.NoGameWindow; + + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (_nextHandle <= 0) _nextHandle = (Environment.TickCount & 0x3FFFFFFF) | 1; + int handle = _nextHandle++; + _live = handle; + _status = (int)WebPanelStatusCode.Starting; + _flags = 0; + _error = 0; + _http = 0; + _navCount = 0; + _liveUrl = request.Url; + _currentAllowlist = request.Allowlist; + _queue.Enqueue(() => ProcessOpen(handle, request)); + if (_thread == null || _threadDone) + { + // 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); + } + else if (_hwnd != IntPtr.Zero) + { + PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + } + return handle; + } + } + + public int Navigate(int handle, string url) + { + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle; + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.StaleHandle; + } + if (string.IsNullOrEmpty(url)) return (int)WebPanelCode.BadArgs; + string[] allow; + lock (_sync) allow = _currentAllowlist; + if (!WebPanelUrlPolicy.IsAllowed(url, allow)) + { + // Off the list: the system browser when that is safe (on the panel thread: ShellExecute can be slow). + Post(() => RouteOffList(url)); + return (int)WebPanelCode.UrlNotAllowed; + } + return Post(() => NavigateNow(handle, url)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown; + } + + public int Close(int handle) + { + lock (_sync) + { + if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; + if (handle <= 0 || handle != _live) return (int)WebPanelCode.StaleHandle; + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return (int)WebPanelCode.AlreadyClosed; + } + return Post(() => CloseNow(handle)) ? (int)WebPanelCode.Queued : (int)WebPanelCode.ShuttingDown; + } + + public int GetState(int handle, out WebPanelSnapshot s) + { + lock (_sync) + { + if (_shuttingDown) + { + s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.None, 0, (int)WebPanelCode.ShuttingDown, 0, 0); + return (int)WebPanelCode.ShuttingDown; + } + if (handle <= 0 || handle != _live) + { + s = new WebPanelSnapshot(handle, (int)WebPanelStatusCode.Superseded, 0, 0, 0, 0); + return (int)WebPanelStatusCode.Superseded; + } + s = new WebPanelSnapshot(_live, _status, _flags, _error, _http, _navCount); + return _status; + } + } + + /// Idempotent. Posts the teardown (which ends with WM_QUIT) and joins the thread within the budget. + public void Shutdown(int budgetMs) + { + Thread? t; + lock (_sync) + { + t = _thread; + if (!_shuttingDown) + { + _shuttingDown = true; + if (t != null && !_threadDone) + { + _queue.Enqueue(TeardownOnPanelThread); + if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + } + } + } + if (t == null || t == Thread.CurrentThread) return; + if (!t.Join(Math.Max(0, budgetMs))) + SafeLog($"shutdown: the panel thread did not finish within {budgetMs} ms"); + } + + public string Describe() + { + lock (_sync) + { + 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)}"; + } + } + + // The live request's allowlist, for Navigate's caller-side check (set on Open, under _sync). + private string[] _currentAllowlist = Array.Empty(); + + private bool Post(Action a) + { + lock (_sync) + { + if (_thread == null || _threadDone) return false; + _queue.Enqueue(a); + if (_hwnd != IntPtr.Zero) PostMessageW(_hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero); + return true; + } + } + + /// Applies to the caller-visible state only while is the live one. + private void SetState(int handle, Action apply) + { + lock (_sync) if (handle == _live) apply(); + } + + private void SafeLog(string line) { try { _env.Log(line); } catch { } } + private void SafeChat(string line) { try { _env.Chat(line); } catch { } } + + // ---- test and diagnostic views (no secrets: Source is never logged) ---- + internal IntPtr HostHwndForTests { get { lock (_sync) return _hwnd; } } + internal int EnvironmentCountForTests => _environmentCount; + internal uint BrowserProcessIdForTests => _browserPid; + internal int AcceleratorKeyEventsForTests => _acceleratorEvents; + internal string SourceForTests => _source; + internal bool ThreadRunningForTests { get { lock (_sync) return _thread != null && !_threadDone && _thread.IsAlive; } } + internal bool PostForTests(Action a) => Post(() => a(_web)); + + // ============================ panel thread ============================ + + private void ThreadMain() + { + // A thread restarted after a failed one (no window) starts clean. + _tornDown = false; + _windowFailed = false; + try + { + try { CreateHostWindow(); } + catch (Exception ex) + { + _windowFailed = true; + SafeLog("could not create the panel window: " + ex.GetType().Name + " " + ex.Message); + } + lock (_sync) _hwnd = _staHwnd; + Drain(); + if (_staHwnd != IntPtr.Zero) + { + while (GetMessageW(out MSG msg, IntPtr.Zero, 0, 0) > 0) + { + TranslateMessage(ref msg); + DispatchMessageW(ref msg); + } + } + else + { + TeardownOnPanelThread(); + } + } + catch (Exception ex) + { + SafeLog("panel thread failed: " + ex.GetType().Name + " " + ex.Message); + } + finally + { + // However the loop ended (WM_QUIT from the teardown, a GetMessage error, an exception), nothing + // this thread registered (window class, WinEvent hook, WebView2) may outlive it: the class's WndProc + // points into the collectible engine context. + if (!_tornDown) { try { TeardownOnPanelThread(); } catch { } } + lock (_sync) + { + _threadDone = true; + _hwnd = IntPtr.Zero; + } + } + } + + private void CreateHostWindow() + { + _className = $"RynthCoreWebPanel_{Environment.TickCount64:X}_{Interlocked.Increment(ref s_classSeq):X}"; + _bgBrush = CreateSolidBrush(Background); + _captionBrush = CreateSolidBrush(CaptionColor); + IntPtr inst = GetModuleHandleW(IntPtr.Zero); + fixed (char* pName = _className) + { + var wc = new WNDCLASSEXW + { + cbSize = (uint)sizeof(WNDCLASSEXW), + style = CS_HREDRAW | CS_VREDRAW, + lpfnWndProc = (IntPtr)(delegate* unmanaged[Stdcall])&WndProc, + hInstance = inst, + hCursor = LoadCursorW(IntPtr.Zero, (IntPtr)IDC_ARROW), + hbrBackground = _bgBrush, + lpszClassName = (IntPtr)pName, + }; + if (RegisterClassExW(ref wc) == 0) + { + int err = Marshal.GetLastWin32Error(); + _className = ""; + throw new InvalidOperationException("RegisterClassExW failed " + err); + } + } + s_active = this; + IntPtr h = CreateWindowExW(WS_EX_TOOLWINDOW, _className, "RynthCore", WS_POPUP | WS_CLIPCHILDREN | WS_THICKFRAME, + 0, 0, 640, 480, IntPtr.Zero, IntPtr.Zero, inst, IntPtr.Zero); + if (h == IntPtr.Zero) throw new InvalidOperationException("CreateWindowExW failed " + Marshal.GetLastWin32Error()); + _staHwnd = h; + _hook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, &WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l) + { + WebPanelHost? p = s_active; + if (p != null) + { + try + { + if (p.HandleMessage(h, m, w, l, out IntPtr r)) return r; + } + catch (Exception ex) + { + p.SafeLog("WndProc threw " + ex.GetType().Name + " " + ex.Message); + } + } + return DefWindowProcW(h, m, w, l); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static void WinEventProc(IntPtr hook, uint ev, IntPtr hwnd, int idObject, int idChild, uint thread, uint time) + { + WebPanelHost? p = s_active; + if (p == null || hook != p._hook) return; + try { p.Track(); } + catch (Exception ex) { p.SafeLog("foreground tracking threw " + ex.GetType().Name + " " + ex.Message); } + } + + private bool HandleMessage(IntPtr h, uint m, IntPtr w, IntPtr l, out IntPtr result) + { + result = IntPtr.Zero; + if (_staHwnd == IntPtr.Zero || h != _staHwnd) return false; // during CreateWindowExW: default handling + switch (m) + { + case WM_RUN: + Drain(); + return true; + case WM_TIMER: + if (w != TimerId) return false; + Track(); + return true; + case WM_SIZE: + ResizeController(); + return false; + case WM_SETFOCUS: + try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { } + return false; + case WM_CLOSE: // Alt+F4 on the panel: close it, keep the window + CloseNow(_serving); + return true; + case WM_NCHITTEST: + { + result = DefWindowProcW(h, m, w, l); + if (result == (IntPtr)HTCLIENT) + { + var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) }; + ScreenToClient(h, ref pt); + if (pt.Y >= 0 && pt.Y < CaptionPx && !InCloseBox(pt)) result = (IntPtr)HTCAPTION; + } + return true; + } + case WM_LBUTTONDOWN: + { + var pt = new POINT { X = (short)((long)l & 0xFFFF), Y = (short)(((long)l >> 16) & 0xFFFF) }; + if (InCloseBox(pt)) CloseNow(_serving); + return true; + } + case WM_PAINT: + Paint(h); + return true; + case WM_ENTERSIZEMOVE: + _inSizeMove = true; + return false; + case WM_EXITSIZEMOVE: + _inSizeMove = false; + RememberUserLayout(); + return false; + } + return false; + } + + private bool InCloseBox(POINT pt) + { + GetClientRect(_staHwnd, out RECT rc); + return pt.Y >= 0 && pt.Y < CaptionPx && pt.X >= rc.Right - CloseBoxPx && pt.X < rc.Right; + } + + private void Paint(IntPtr h) + { + IntPtr dc = BeginPaint(h, out PAINTSTRUCT ps); + try + { + GetClientRect(h, out RECT rc); + var strip = new RECT { Left = 0, Top = 0, Right = rc.Right, Bottom = Math.Min(CaptionPx, rc.Bottom) }; + FillRect(dc, ref strip, _captionBrush); + SetBkMode(dc, TRANSPARENT); + SetTextColor(dc, TextColor); + IntPtr old = SelectObject(dc, GetStockObject(DEFAULT_GUI_FONT)); + var title = new RECT { Left = 10, Top = 0, Right = Math.Max(10, rc.Right - CloseBoxPx - 6), Bottom = strip.Bottom }; + DrawTextW(dc, _title, -1, ref title, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX); + var x = new RECT { Left = rc.Right - CloseBoxPx, Top = 0, Right = rc.Right, Bottom = strip.Bottom }; + DrawTextW(dc, "X", -1, ref x, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX); + SelectObject(dc, old); + } + finally { EndPaint(h, ref ps); } + } + + private void Drain() + { + while (_queue.TryDequeue(out Action? a)) + { + try { a(); } + catch (Exception ex) { SafeLog("panel action threw " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); } // no Message: it could carry a URL + } + } + + private bool IsLive(int handle) { lock (_sync) return handle == _live && !_shuttingDown; } + + private void ProcessOpen(int handle, WebPanelRequest r) + { + if (_tornDown || !IsLive(handle)) return; // a newer Open is queued behind this one + _serving = handle; + _req = r; + _title = string.IsNullOrWhiteSpace(r.Title) ? "RynthCore" : r.Title.Trim(); + _fractions = WebPanelLayoutStore.TryLoad(_env.LocalAppData, out PanelFractions stored) + ? stored + : WebPanelWindowPolicy.Default(r.WidthPercent, r.HeightPercent); + _pendingUrl = r.Url; + if (_windowFailed) { Fail(handle, WebPanelCode.CreateFailed, "no panel window", allowFallback: true); return; } + + if (_needsRecreate || (_profileFolder != null && !string.Equals(_profileFolder, r.ProfileFolder, StringComparison.OrdinalIgnoreCase))) + TearDownWebView(); + + _open = true; + InvalidateRect(_staHwnd, IntPtr.Zero, true); + Show(); + if (_ctl != null) { NavigatePending(handle); return; } + if (!_creating) StartCreate(handle, r.ProfileFolder); + } + + private void StartCreate(int handle, string folder) + { + _creating = true; + int seq = ++_createSeq; + _profileFolder = folder; + if (!EnsureLoader(out string why)) { CreationFailed(seq, WebPanelCode.CreateFailed, why); return; } + try + { + string version = CoreWebView2Environment.GetAvailableBrowserVersionString(); + if (string.IsNullOrEmpty(version)) { CreationFailed(seq, WebPanelCode.RuntimeMissing, "no WebView2 runtime"); return; } + } + catch (Exception ex) + { + CreationFailed(seq, Classify(ex), "runtime probe: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + int delay = _env.EnvironmentDelayMsForTests; + if (delay > 0) Task.Delay(delay).ContinueWith(_ => Post(() => CreateEnvironment(seq, folder))); + else CreateEnvironment(seq, folder); + } + + private bool EnsureLoader(out string why) + { + why = ""; + if (_loaderLoaded) return true; + string path = Path.Combine(_env.RuntimeDir ?? "", "WebView2Loader.dll"); + try + { + // By full path first, so the Core wrapper's DllImport("WebView2Loader.dll") finds the loaded module. + NativeLibrary.Load(path); + _loaderLoaded = true; + return true; + } + catch (Exception ex) + { + why = "WebView2Loader.dll did not load from the runtime folder: " + ex.GetType().Name; + return false; + } + } + + private void CreateEnvironment(int seq, string folder) + { + if (seq != _createSeq || _tornDown) return; + Task t; + try + { + Directory.CreateDirectory(folder); + t = CoreWebView2Environment.CreateAsync(_env.BrowserExecutableFolderForTests, folder, new CoreWebView2EnvironmentOptions()); + } + catch (Exception ex) + { + CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + t.ContinueWith(done => Post(() => OnEnvironment(seq, done)), TaskContinuationOptions.ExecuteSynchronously); + } + + private void OnEnvironment(int seq, Task t) + { + if (seq != _createSeq || _tornDown) return; + if (!t.IsCompletedSuccessfully) + { + Exception? ex = t.Exception?.GetBaseException(); + CreationFailed(seq, WebPanelCode.CreateFailed, "environment: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8")); + return; + } + _wvEnv = t.Result; + _environmentCount++; + Task c; + try { c = _wvEnv.CreateCoreWebView2ControllerAsync(_staHwnd); } + catch (Exception ex) + { + CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + ex.GetType().Name + " 0x" + ex.HResult.ToString("X8")); + return; + } + c.ContinueWith(done => Post(() => OnController(seq, done)), TaskContinuationOptions.ExecuteSynchronously); + } + + private void OnController(int seq, Task t) + { + if (seq != _createSeq || _tornDown) + { + if (t.IsCompletedSuccessfully) { try { t.Result.Close(); } catch { } } + return; + } + if (!t.IsCompletedSuccessfully) + { + Exception? ex = t.Exception?.GetBaseException(); + CreationFailed(seq, WebPanelCode.CreateFailed, "controller: " + (ex?.GetType().Name ?? "cancelled") + " 0x" + (ex?.HResult ?? 0).ToString("X8")); + return; + } + _creating = false; + _ctl = t.Result; + _web = _ctl.CoreWebView2; + _ctl.DefaultBackgroundColor = System.Drawing.Color.FromArgb(255, 32, 32, 36); + + CoreWebView2Settings s = _web.Settings; + s.AreDevToolsEnabled = false; + s.AreBrowserAcceleratorKeysEnabled = false; + s.IsStatusBarEnabled = false; + s.AreHostObjectsAllowed = false; + s.IsWebMessageEnabled = false; // phase 2 turns it on per open + s.IsPasswordAutosaveEnabled = false; + + _web.NavigationStarting += OnNavigationStarting; + _web.NavigationCompleted += OnNavigationCompleted; + _web.NewWindowRequested += OnNewWindowRequested; + _web.PermissionRequested += OnPermissionRequested; + _web.ProcessFailed += OnProcessFailed; + _web.LaunchingExternalUriScheme += OnLaunchingExternalUriScheme; + _ctl.AcceleratorKeyPressed += OnAcceleratorKeyPressed; + _browserPid = _web.BrowserProcessId; + + _env.ConfigureForTests?.Invoke(_web); + ResizeController(); + if (_open) + { + _ctl.IsVisible = true; + NavigatePending(_serving); + FocusPage(); + } + else + { + _ctl.IsVisible = false; + } + } + + private void CreationFailed(int seq, WebPanelCode code, string reason) + { + if (seq != _createSeq) return; + _creating = false; + _wvEnv = null; + _profileFolder = null; // the next Open tries again + Fail(_serving, code, reason, allowFallback: true); + } + + /// Only the runtime probe can say RuntimeMissing; a failure after it is CreateFailed. + private static WebPanelCode Classify(Exception? ex) => + ex is WebView2RuntimeNotFoundException ? WebPanelCode.RuntimeMissing : WebPanelCode.CreateFailed; + + private void NavigatePending(int handle) + { + if (_web == null || !IsLive(handle)) return; + string url = _pendingUrl; + SetState(handle, () => _status = (int)WebPanelStatusCode.Loading); + try { _web.Navigate(url); } + catch (Exception ex) { SafeLog("navigate threw " + ex.GetType().Name + " for " + WebPanelUrlPolicy.Redact(url)); } + } + + private void NavigateNow(int handle, string url) + { + if (!IsLive(handle) || _serving != handle) return; + _pendingUrl = url; + if (_web == null) return; // still creating: the controller navigates to _pendingUrl when it is ready + NavigatePending(handle); + } + + // ---- navigation guard ---- + + 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)) + { + 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; + }); + } + + private void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e) + { + string source = _web?.Source ?? ""; + if (string.Equals(source, "about:blank", StringComparison.OrdinalIgnoreCase) || !_open) return; + _source = source; + int http = e.HttpStatusCode; + int handle = _serving; + SetState(handle, () => + { + if (_status == (int)WebPanelStatusCode.Closed || _status == (int)WebPanelStatusCode.Failed) return; + _status = (int)WebPanelStatusCode.Ready; + if (http != 0) _http = http; + }); + } + + 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 { _web?.Navigate(url); } catch { } + } + else + { + RouteOffList(url); + } + } + + /// An off-list URL: the system browser when it is browser-safe, else dropped (logged redacted). + private void RouteOffList(string url) + { + if (WebPanelUrlPolicy.IsBrowserSafe(url)) + { + bool ok = false; + try { ok = _env.OpenInBrowser(url); } catch { } + string host = Uri.TryCreate(url, UriKind.Absolute, out Uri? u) ? u.Host : "the page"; + SafeLog((ok ? "opened in the system browser: " : "the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); + if (ok) SafeChat("[RynthCore] Opened " + host + " in your web browser."); + } + else + { + SafeLog("blocked a navigation (" + SchemeOf(url) + "): " + WebPanelUrlPolicy.Redact(url)); + } + } + + private static string SchemeOf(string url) + { + int colon = url.IndexOf(':'); + if (colon <= 0 || colon > 32) return "no scheme"; + foreach (char c in url.AsSpan(0, colon)) + if (!char.IsAsciiLetterOrDigit(c) && c != '+' && c != '-' && c != '.') return "no scheme"; + return url.Substring(0, colon).ToLowerInvariant(); + } + + private void OnLaunchingExternalUriScheme(object? sender, CoreWebView2LaunchingExternalUriSchemeEventArgs e) + { + e.Cancel = true; // never hand a custom scheme to the shell, and never show WebView2's prompt for one + SafeLog("blocked an external scheme launch (" + SchemeOf(e.Uri) + ")"); + } + + private void OnPermissionRequested(object? sender, CoreWebView2PermissionRequestedEventArgs e) + { + e.State = e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead + ? CoreWebView2PermissionState.Allow + : CoreWebView2PermissionState.Deny; + } + + private void OnAcceleratorKeyPressed(object? sender, CoreWebView2AcceleratorKeyPressedEventArgs e) + { + _acceleratorEvents++; + if (e.KeyEventKind != CoreWebView2KeyEventKind.KeyDown || e.VirtualKey != VK_ESCAPE) return; + if (((_req?.Flags ?? 0) & FlagPageKeepsEscape) != 0) return; // the page gets it + e.Handled = true; + int handle = _serving; + Post(() => CloseNow(handle)); // not inside WebView2's own callback + } + + 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 + } + + private void HandleProcessFailed(int handle, CoreWebView2ProcessFailedKind kind) + { + if (_tornDown) return; + SafeLog("WebView2 process failed: " + kind); + if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited) + { + TearDownWebView(); + } + else + { + try { _web?.Navigate("about:blank"); } catch { } + _needsRecreate = true; // the next Open recreates the controller and environment + } + // Never a browser fallback here: a navigation already ran, so the launch code is spent. + Fail(handle, WebPanelCode.ProcessFailed, kind.ToString(), allowFallback: false); + } + + // ---- open, close, fail ---- + + private void Fail(int handle, WebPanelCode code, string reason, bool allowFallback) + { + HidePanel(); + bool fallback = false, ignored = false; + string url = ""; + lock (_sync) + { + if (handle != _live || _status == (int)WebPanelStatusCode.Closed) + { + ignored = true; + } + else + { + _status = (int)WebPanelStatusCode.Failed; + _error = (int)code; + WebPanelRequest? r = _req; + if (allowFallback && r != null && (code == WebPanelCode.RuntimeMissing || code == WebPanelCode.CreateFailed) + && (r.Flags & FlagFallback) != 0 && _navCount == 0 && WebPanelUrlPolicy.IsBrowserSafe(r.Url)) + { + fallback = true; + url = r.Url; + _flags |= StateOpenedInBrowser; + } + } + } + if (ignored) { SafeLog($"panel failure after close or supersede: {code} ({reason})"); return; } + SafeLog($"panel failed: {code} ({reason})"); + if (!fallback) return; + bool ok = false; + try { ok = _env.OpenInBrowser(url); } catch { } + SafeLog((ok ? "fallback: opened in the system browser: " : "fallback: the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); + string why = code == WebPanelCode.RuntimeMissing ? "WebView2 runtime not installed" : "it failed to start"; + SafeChat("[RynthCore] The in-game browser could not start (" + why + "); opened the page in your web browser."); + } + + private void Show() + { + PlaceNow(force: true); + 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). + IntPtr fg = GetForegroundWindow(); + uint fgPid = 0; + if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); + if (fg == IntPtr.Zero || fgPid == _ourPid) SetForegroundWindow(_staHwnd); + if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } + FocusPage(); + if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } + UpdateStateFlags(); + } + + private void FocusPage() + { + try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { } + } + + private void CloseNow(int handle) + { + if (!IsLive(handle) || handle != _serving) return; + if (_open) + { + HidePanel(); + if (_ctl != null) { try { _web?.Navigate("about:blank"); } catch { } } + } + SetState(handle, () => + { + if (_status != (int)WebPanelStatusCode.Failed) _status = (int)WebPanelStatusCode.Closed; + _flags &= ~(StateVisible | StateFocused); + }); + } + + /// Hides the panel (controller, window, timer); hands the foreground back to the game when the panel held it. + private void HidePanel() + { + bool hadForeground = HoldsForeground(); + _open = false; + if (_timerOn) { KillTimer(_staHwnd, TimerId); _timerOn = false; } + if (_ctl != null) { try { _ctl.IsVisible = false; } catch { } } + if (_staHwnd != IntPtr.Zero) ShowWindow(_staHwnd, SW_HIDE); + lock (_sync) if (_serving == _live) _flags &= ~(StateVisible | StateFocused); + if (hadForeground) + { + IntPtr game = _env.GameHwnd; + if (game != IntPtr.Zero && IsWindow(game)) SetForegroundWindow(game); + } + } + + private bool HoldsForeground() + { + if (_staHwnd == IntPtr.Zero) return false; + IntPtr fg = GetForegroundWindow(); + return fg != IntPtr.Zero && (fg == _staHwnd || GetAncestor(fg, GA_ROOT) == _staHwnd); + } + + // ---- tracking: 50 ms timer and the foreground WinEvent ---- + + private void Track() + { + if (!_open || _staHwnd == IntPtr.Zero) return; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !IsWindow(game)) { CloseNow(_serving); return; } + IntPtr fg = GetForegroundWindow(); + uint fgPid = 0; + if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); + bool? visible = WebPanelWindowPolicy.Visible(true, true, IsIconic(game), IsWindowVisible(game), fg == IntPtr.Zero, fgPid, _ourPid); + bool shown = IsWindowVisible(_staHwnd); + if (visible == false) + { + if (shown) ShowWindow(_staHwnd, SW_HIDE); + } + else + { + if (visible == true && !shown) { ShowWindow(_staHwnd, SW_SHOWNA); shown = true; } + if (shown) + { + if (!_inSizeMove) PlaceNow(force: false); + RaiseAboveGame(game); + } + } + UpdateStateFlags(); + } + + private bool GameClientScreen(out PanelRect rect) + { + rect = default; + IntPtr game = _env.GameHwnd; + if (game == IntPtr.Zero || !GetClientRect(game, out RECT c)) return false; + var p = new POINT(); + if (!ClientToScreen(game, ref p)) return false; + rect = new PanelRect(p.X, p.Y, p.X + c.W, p.Y + c.H); + return rect.Width > 0 && rect.Height > 0; + } + + private void PlaceNow(bool force) + { + if (!GameClientScreen(out PanelRect client)) return; + PanelRect want = WebPanelWindowPolicy.Place(client, _fractions); + GetWindowRect(_staHwnd, out RECT have); + if (!force && have.Left == want.Left && have.Top == want.Top && have.Right == want.Right && have.Bottom == want.Bottom) return; + SetWindowPos(_staHwnd, IntPtr.Zero, want.Left, want.Top, want.Width, want.Height, SWP_NOZORDER | SWP_NOACTIVATE); + } + + /// Raises the panel only when it is below the game window, so it never covers a window the user brought forward. + private void RaiseAboveGame(IntPtr game) + { + int guard = 0; + for (IntPtr h = GetWindow(game, GW_HWNDPREV); h != IntPtr.Zero && guard < 4096; h = GetWindow(h, GW_HWNDPREV), guard++) + if (h == _staHwnd) return; + SetWindowPos(_staHwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + } + + private void UpdateStateFlags() + { + bool visible = _staHwnd != IntPtr.Zero && IsWindowVisible(_staHwnd); + bool focused = HoldsForeground(); + lock (_sync) + { + if (_serving != _live) return; + _flags = (_flags & StateOpenedInBrowser) | (visible && _open ? StateVisible : 0) | (focused && _open ? StateFocused : 0); + } + } + + private void RememberUserLayout() + { + if (!GameClientScreen(out PanelRect client)) return; + GetWindowRect(_staHwnd, out RECT r); + _fractions = WebPanelWindowPolicy.FromUserRect(client, new PanelRect(r.Left, r.Top, r.Right, r.Bottom)); + if (!WebPanelLayoutStore.Save(_env.LocalAppData, _fractions)) SafeLog("could not save the panel layout"); + } + + private void ResizeController() + { + if (_ctl == null || _staHwnd == IntPtr.Zero) return; + GetClientRect(_staHwnd, out RECT rc); + try { _ctl.Bounds = new System.Drawing.Rectangle(0, CaptionPx, Math.Max(0, rc.W), Math.Max(0, rc.H - CaptionPx)); } catch { } + } + + // ---- teardown ---- + + /// Drops the controller and environment (profile switch, browser exit, shutdown). Pending creations become stale. + private void TearDownWebView() + { + _createSeq++; + _creating = false; + _needsRecreate = false; + CoreWebView2? web = _web; + CoreWebView2Controller? ctl = _ctl; + _web = null; + _ctl = null; + _wvEnv = null; + _profileFolder = null; + _browserPid = 0; + if (web != null) + { + try + { + web.NavigationStarting -= OnNavigationStarting; + web.NavigationCompleted -= OnNavigationCompleted; + web.NewWindowRequested -= OnNewWindowRequested; + web.PermissionRequested -= OnPermissionRequested; + web.ProcessFailed -= OnProcessFailed; + web.LaunchingExternalUriScheme -= OnLaunchingExternalUriScheme; + } + catch { } + } + if (ctl != null) + { + try { ctl.AcceleratorKeyPressed -= OnAcceleratorKeyPressed; } catch { } + try { ctl.Close(); } catch { } + } + } + + private void TeardownOnPanelThread() + { + if (_tornDown) return; + _tornDown = true; + _open = false; + if (_hook != IntPtr.Zero) { UnhookWinEvent(_hook); _hook = IntPtr.Zero; } + if (_timerOn && _staHwnd != IntPtr.Zero) { KillTimer(_staHwnd, TimerId); _timerOn = false; } + TearDownWebView(); + if (_staHwnd != IntPtr.Zero) { DestroyWindow(_staHwnd); _staHwnd = IntPtr.Zero; } + lock (_sync) _hwnd = IntPtr.Zero; + if (_className.Length != 0) { UnregisterClassW(_className, GetModuleHandleW(IntPtr.Zero)); _className = ""; } + if (_bgBrush != IntPtr.Zero) { DeleteObject(_bgBrush); _bgBrush = IntPtr.Zero; } + if (_captionBrush != IntPtr.Zero) { DeleteObject(_captionBrush); _captionBrush = IntPtr.Zero; } + if (s_active == this) s_active = null; + _req = null; + PostQuitMessage(0); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs b/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs new file mode 100644 index 0000000..284eb0c --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelLayoutStore.cs @@ -0,0 +1,80 @@ +using System; +using System.IO; +using System.Text.Json; + +namespace RynthCore.Engine.WebPanel; + +/// +/// The panel's remembered placement: <LocalAppData>\RynthCore\WebPanel\layout.json, {"x","y","w","h"} as +/// fractions of the game client rect (WebPanelWindowPolicy.FromUserRect). A valid stored layout beats the +/// caller's percentages. Called on the panel thread only. +/// +internal static class WebPanelLayoutStore +{ + public static string PathFor(string localAppData) => Path.Combine(localAppData, "RynthCore", "WebPanel", "layout.json"); + + public static bool TryLoad(string localAppData, out PanelFractions layout) + { + layout = default; + try + { + string path = PathFor(localAppData); + if (!File.Exists(path)) return false; + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path)); + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) return false; + if (!Num(r, "x", out double x) || !Num(r, "y", out double y) || !Num(r, "w", out double w) || !Num(r, "h", out double h)) return false; + var f = new PanelFractions(x, y, w, h); + if (!IsValid(f)) return false; + layout = f; + return true; + } + catch (Exception) + { + return false; + } + } + + public static bool IsValid(PanelFractions f) + { + const double Slack = 1e-6; + if (!double.IsFinite(f.X) || !double.IsFinite(f.Y) || !double.IsFinite(f.W) || !double.IsFinite(f.H)) return false; + if (f.W <= 0 || f.H <= 0 || f.W > 1 + Slack || f.H > 1 + Slack) return false; + if (f.X < 0 || f.Y < 0) return false; + return f.X + f.W <= 1 + Slack && f.Y + f.H <= 1 + Slack; + } + + /// Writes the layout (temp file, then a replace). False (and nothing written) when invalid or on an I/O error. + public static bool Save(string localAppData, PanelFractions f) + { + if (!IsValid(f)) return false; + try + { + string path = PathFor(localAppData); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + string tmp = path + ".tmp"; + using (var fs = new FileStream(tmp, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var w = new Utf8JsonWriter(fs)) + { + w.WriteStartObject(); + w.WriteNumber("x", f.X); + w.WriteNumber("y", f.Y); + w.WriteNumber("w", f.W); + w.WriteNumber("h", f.H); + w.WriteEndObject(); + } + File.Move(tmp, path, overwrite: true); + return true; + } + catch (Exception) + { + return false; + } + } + + private static bool Num(JsonElement r, string name, out double v) + { + v = 0; + return r.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.Number && e.TryGetDouble(out v); + } +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelNative.cs b/src/RynthCore.Engine/WebPanel/WebPanelNative.cs new file mode 100644 index 0000000..383801c --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelNative.cs @@ -0,0 +1,95 @@ +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.WebPanel; + +/// Win32 for the web panel host (CoreCLR engine only). From the 2026-11-07 WebView2 spike's Native.cs. +internal static unsafe class WebPanelNative +{ + public const uint WS_POPUP = 0x80000000, WS_CLIPCHILDREN = 0x02000000, WS_THICKFRAME = 0x00040000; + public const uint WS_EX_TOOLWINDOW = 0x00000080; + public const uint CS_VREDRAW = 0x0001, CS_HREDRAW = 0x0002; + + public const uint WM_NCCREATE = 0x0081, WM_SIZE = 0x0005, WM_SETFOCUS = 0x0007, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, + WM_NCHITTEST = 0x0084, WM_LBUTTONDOWN = 0x0201, WM_TIMER = 0x0113, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, + WM_APP = 0x8000; + public const int HTCLIENT = 1, HTCAPTION = 2; + + public const uint SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOACTIVATE = 0x0010; + public const int SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_SHOWNA = 8; + public const uint GW_HWNDPREV = 3, GA_ROOT = 2; + public static readonly IntPtr HWND_TOP = IntPtr.Zero; + + public const uint EVENT_SYSTEM_FOREGROUND = 0x0003, WINEVENT_OUTOFCONTEXT = 0x0000; + public const int TRANSPARENT = 1, DEFAULT_GUI_FONT = 17, IDC_ARROW = 32512; + public const uint DT_LEFT = 0x0000, DT_CENTER = 0x0001, DT_VCENTER = 0x0004, DT_SINGLELINE = 0x0020, DT_NOPREFIX = 0x0800, DT_END_ELLIPSIS = 0x8000; + + public static uint Rgb(int r, int g, int b) => (uint)(r | (g << 8) | (b << 16)); + + [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; public int W => Right - Left; public int H => Bottom - Top; } + [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] public struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + + [StructLayout(LayoutKind.Sequential)] + public struct WNDCLASSEXW + { + public uint cbSize, style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra; + public IntPtr hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PAINTSTRUCT { public IntPtr hdc; public int fErase; public RECT rcPaint; public int fRestore, fIncUpdate; public fixed byte rgbReserved[32]; } + + [DllImport("user32.dll", SetLastError = true)] public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool UnregisterClassW(string cls, IntPtr hInst); + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern IntPtr CreateWindowExW(uint ex, string cls, string name, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param); + [DllImport("user32.dll")] public static extern bool DestroyWindow(IntPtr h); + [DllImport("user32.dll")] public static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p); + [DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p); + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags); + [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd); + [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h); + [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] public static extern int GetMessageW(out MSG m, IntPtr h, uint min, uint max); + [DllImport("user32.dll")] public static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] public static extern IntPtr DispatchMessageW(ref MSG m); + [DllImport("user32.dll")] public static extern void PostQuitMessage(int code); + [DllImport("user32.dll")] public static extern IntPtr SetTimer(IntPtr h, IntPtr id, uint ms, IntPtr proc); + [DllImport("user32.dll")] public static extern bool KillTimer(IntPtr h, IntPtr id); + [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr h, uint cmd); + [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags); + [DllImport("user32.dll")] public static extern bool InvalidateRect(IntPtr h, IntPtr rect, bool erase); + [DllImport("user32.dll")] public static extern IntPtr BeginPaint(IntPtr h, out PAINTSTRUCT ps); + [DllImport("user32.dll")] public static extern bool EndPaint(IntPtr h, ref PAINTSTRUCT ps); + [DllImport("user32.dll")] public static extern int FillRect(IntPtr dc, ref RECT r, IntPtr brush); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int DrawTextW(IntPtr dc, string text, int count, ref RECT r, uint format); + [DllImport("user32.dll")] public static extern IntPtr LoadCursorW(IntPtr inst, IntPtr name); + [DllImport("user32.dll")] + public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmod, + delegate* unmanaged[Stdcall] proc, uint pid, uint tid, uint flags); + [DllImport("user32.dll")] public static extern bool UnhookWinEvent(IntPtr hook); + + [DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(uint color); + [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj); + [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr dc, IntPtr obj); + [DllImport("gdi32.dll")] public static extern IntPtr GetStockObject(int obj); + [DllImport("gdi32.dll")] public static extern uint SetTextColor(IntPtr dc, uint color); + [DllImport("gdi32.dll")] public static extern int SetBkMode(IntPtr dc, int mode); + + [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId(); + [DllImport("kernel32.dll")] public static extern uint GetCurrentProcessId(); + [DllImport("kernel32.dll")] public static extern IntPtr GetModuleHandleW(IntPtr name); + + /// ShellExecuteW, not Process.Start (the Process API is an AV hazard inside acclient.exe). + [DllImport("shell32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr ShellExecuteW(IntPtr hwnd, string op, string file, string? parameters, string? dir, int show); +} diff --git a/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs new file mode 100644 index 0000000..a2efc38 --- /dev/null +++ b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs @@ -0,0 +1,55 @@ +using System; +using System.Text; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.WebPanel; + +/// One open request, every string already copied out of the caller's buffers. +internal sealed record WebPanelRequest(string Url, string[] Allowlist, string ProfileFolder, string Title, int WidthPercent, int HeightPercent, uint Flags); + +/// +/// Reads the v93 WebPanelOpen argument. The SDK passes pointers into stack or pooled buffers that are gone +/// the moment the call returns, so every string is copied here, synchronously, before anything is queued. +/// Pure: no Win32, no WebView2. +/// +internal static unsafe class WebPanelNativeArgs +{ + public const int MaxAllowlistBytes = 8192, MaxProfileKeyBytes = 256, MaxTitleBytes = 128; + public const uint KnownFlags = 1 | 2; // FallbackToBrowser, PageKeepsEscape + + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + /// 0 and a request, or BadArgs. URL policy (IsAllowed) is the host's to apply. + public static int TryBuildRequest(WebPanelOpenNative* open, string localAppData, string? worldName, out WebPanelRequest? request) + { + request = null; + if (open == null) return (int)WebPanelCode.BadArgs; + uint minSize = (uint)((byte*)open->Reserved - (byte*)open); + if (open->Size < minSize) return (int)WebPanelCode.BadArgs; + if (!TryReadUtf8(open->Url, WebPanelUrlPolicy.MaxUrlBytes, true, out string url)) return (int)WebPanelCode.BadArgs; + if (!TryReadUtf8(open->Allowlist, MaxAllowlistBytes, true, out string allowText)) return (int)WebPanelCode.BadArgs; + if (!TryReadUtf8(open->ProfileKey, MaxProfileKeyBytes, false, out string key)) return (int)WebPanelCode.BadArgs; + if (!TryReadUtf8(open->Title, MaxTitleBytes, false, out string title)) return (int)WebPanelCode.BadArgs; + if (!WebPanelUrlPolicy.TryParseAllowlist(allowText, out string[] allowlist)) return (int)WebPanelCode.BadArgs; + string folder = WebPanelProfile.Folder(localAppData, worldName, key); + request = new WebPanelRequest(url, allowlist, folder, title, open->WidthPercent, open->HeightPercent, open->Flags & KnownFlags); + return 0; + } + + /// + /// A NUL-terminated UTF-8 string of at most bytes, copied. Null pointer: + /// "" (false when required). Required strings must not be empty; invalid UTF-8 is refused. + /// + public static bool TryReadUtf8(byte* p, int maxBytes, bool required, out string value) + { + value = ""; + if (p == null) return !required; + int n = 0; + while (n <= maxBytes && p[n] != 0) n++; + if (n > maxBytes) return false; + if (n == 0) return !required; + try { value = StrictUtf8.GetString(p, n); } + catch (DecoderFallbackException) { return false; } + return true; + } +} diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs new file mode 100644 index 0000000..d753a38 --- /dev/null +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -0,0 +1,149 @@ +// The harness's way into the web panel host. Everything crossing into the harness is a framework +// type (int, string, IntPtr, arrays, Action), so nothing of this collectible context is held +// by the default one. The calls mirror WebPanelApi (the engine's ABI glue): Open reads the native +// struct with WebPanelNativeArgs exactly as the engine does. +using System; +using System.IO; +using System.Threading; +using Microsoft.Web.WebView2.Core; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.WebPanel; + +public static unsafe class PayloadEntry +{ + private static StubEnvironment? _env; + private static WebPanelHost? _host; + + public static void Init(IntPtr gameHwnd, string runtimeDir, string localAppData, string panelDir, string otherDir, + Action log, Action chat, Action browser) + { + _env = new StubEnvironment(gameHwnd, runtimeDir, localAppData, panelDir, otherDir, log, chat, browser); + _host = new WebPanelHost(_env); + } + + public static void SetEnvironmentDelay(int ms) => _env!.DelayMs = ms; + public static void SetBrowserFolder(string? folder) => _env!.BrowserFolder = folder; + public static void SetWorld(string world) => _env!.World = world; + + /// The engine's WebPanelApi.Open path: read the caller's struct, then the host. + public static int Open(IntPtr nativeArgs) + { + int rc = WebPanelNativeArgs.TryBuildRequest((WebPanelOpenNative*)nativeArgs, _env!.LocalAppData, _env.WorldName, out WebPanelRequest? req); + if (rc != 0) return rc; + return _host!.Open(req!); + } + + public static int Navigate(int handle, string url) => _host!.Navigate(handle, url); + public static int Close(int handle) => _host!.Close(handle); + + /// [return, handle, status, flags, error, http, navigations]. + public static int[] GetState(int handle) + { + int r = _host!.GetState(handle, out WebPanelSnapshot s); + return new[] { r, s.Handle, s.Status, (int)s.Flags, s.Error, s.LastHttpStatus, (int)s.NavigationCount }; + } + + public static void Shutdown(int budgetMs) => _host!.Shutdown(budgetMs); + public static string Describe() => _host!.Describe(); + + public static IntPtr HostHwnd => _host!.HostHwndForTests; + public static int EnvironmentCount => _host!.EnvironmentCountForTests; + public static int BrowserProcessId => (int)_host!.BrowserProcessIdForTests; + public static int AcceleratorKeyEvents => _host!.AcceleratorKeyEventsForTests; + public static string Source => _host!.SourceForTests; + public static bool ThreadRunning => _host!.ThreadRunningForTests; + + public static string ProfileFolder(string world, string key) => WebPanelProfile.Folder(_env!.LocalAppData, world, key); + + /// Runs script in the page on the panel thread; waits here (the harness thread), never there. + public static string Eval(string js, int timeoutMs) + { + var done = new ManualResetEventSlim(); + string result = "TIMEOUT"; + bool posted = _host!.PostForTests(web => + { + if (web == null) { result = "no webview"; done.Set(); return; } + try + { + web.ExecuteScriptAsync(js).ContinueWith(t => + { + result = t.IsCompletedSuccessfully ? t.Result : "ERR " + t.Exception?.GetBaseException().Message; + done.Set(); + }); + } + catch (Exception ex) { result = "ERR " + ex.Message; done.Set(); } + }); + if (!posted) return "panel thread not running"; + done.Wait(timeoutMs); + return result; + } + + /// Drops this context's statics so nothing in it is reachable before the unload. + public static void Release() + { + _host = null; + _env = null; + } + + private sealed class StubEnvironment : IWebPanelEnvironment + { + private readonly Action _log, _chat, _browser; + private readonly string _panelDir, _otherDir; + + public StubEnvironment(IntPtr game, string runtimeDir, string localAppData, string panelDir, string otherDir, + Action log, Action chat, Action browser) + { + GameHwnd = game; + RuntimeDir = runtimeDir; + LocalAppData = localAppData; + _panelDir = panelDir; + _otherDir = otherDir; + _log = log; + _chat = chat; + _browser = browser; + } + + public volatile int DelayMs; + public volatile string? BrowserFolder; + public volatile string World = "Harness World"; + + public IntPtr GameHwnd { get; } + public string RuntimeDir { get; } + public string LocalAppData { get; } + public string WorldName => World; + public void Log(string line) => _log(line); + public void Chat(string line) => _chat(line); + public bool OpenInBrowser(string url) + { + if (!WebPanelUrlPolicy.IsBrowserSafe(url)) { _log("HARNESS: OpenInBrowser got an unsafe url"); return false; } + _browser(url); + return true; + } + public Thread StartStaThread(string name, ThreadStart body) + { + var t = new Thread(body) { Name = name, IsBackground = true }; + t.SetApartmentState(ApartmentState.STA); + t.Start(); + return t; + } + public int EnvironmentDelayMsForTests => DelayMs; + public string? BrowserExecutableFolderForTests => BrowserFolder; + + public Action? ConfigureForTests => web => + { + web.SetVirtualHostNameToFolderMapping("panel.test", _panelDir, CoreWebView2HostResourceAccessKind.Allow); + web.SetVirtualHostNameToFolderMapping("other.test", _otherDir, CoreWebView2HostResourceAccessKind.Allow); + // https://go.panel.test/redirect answers 302 to other.test. Not folder-mapped: WebResourceRequested + // is not raised for a virtual host mapping's own requests (measured: the filter on panel.test/* never fired). + web.AddWebResourceRequestedFilter("https://go.panel.test/*", CoreWebView2WebResourceContext.All); + web.WebResourceRequested += (s, e) => + { + if (!e.Request.Uri.StartsWith("https://go.panel.test/redirect", StringComparison.OrdinalIgnoreCase)) return; + e.Response = web.Environment.CreateWebResourceResponse(null, 302, "Found", + "Location: https://other.test/landing.html?code=SECRET123\r\nCache-Control: no-store"); + _log("HARNESS: served the 302 for /redirect"); + }; + }; + } +} diff --git a/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj new file mode 100644 index 0000000..627111a --- /dev/null +++ b/tools/WebPanelHarness.Payload/WebPanelHarness.Payload.csproj @@ -0,0 +1,51 @@ + + + + + net10.0-windows + x86 + win-x86 + false + Library + true + enable + true + RynthCore.Engine.WebPanel + WebPanelHarness.Payload + true + false + Dynamic + false + $(NoWarn);CS0649;CS0169 + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs new file mode 100644 index 0000000..5cdba28 --- /dev/null +++ b/tools/WebPanelHarness/Program.cs @@ -0,0 +1,938 @@ +// Offline harness for the web panel host: see WebPanelHarness.csproj. Port of the 2026-11-07 spike's +// WebSpikeHost (spikes\webview2\WebSpikeHost), popup-free path only. +using System.Collections.Concurrent; +using System.Diagnostics; +using System.IO.Compression; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Loader; +using System.Text; + +namespace WebPanelHarness; + +internal static unsafe class Program +{ + private const string Secret = "SECRET123"; + private const string Allow = "panel.test\n*.panel.test"; + private const int StatusStarting = 1, StatusLoading = 2, StatusReady = 3, StatusClosed = 4, StatusFailed = 5, StatusSuperseded = 6; + private const int CodeQueued = 1, CodeUrlNotAllowed = -2, CodeShuttingDown = -5, CodeStale = -6, CodeCreateFailed = -8, CodeProcessFailed = -9; + private const uint FlagFallback = 1, FlagPageKeepsEscape = 2; + private const int StateOpenedInBrowser = 4; + + private static readonly StringBuilder Out = new(); + private static readonly List Results = new(); + private static int _fails, _unverified; + + private static readonly ConcurrentQueue LogLines = new(); + private static readonly ConcurrentQueue ChatLines = new(); + private static readonly ConcurrentQueue BrowserCalls = new(); + + private static readonly ConcurrentQueue<(Func Fn, ManualResetEventSlim Done, string[] Result)> GameQ = new(); + private static IntPtr _game, _popOut; + private static uint _gameTid; + private static volatile int _gameKeyMsgs; + private static bool _haveForeground, _allowForeground; + + private static volatile Session? _pumpSession; + private static volatile int _pumpHandle; + private static volatile bool _pumpStop; + private static long _pumpCalls; + + private static string _root = ""; + + private static void W(string s) + { + string line = $"[{DateTime.Now:HH:mm:ss.fff}] {s}"; + Console.WriteLine(line); + lock (Out) Out.AppendLine(line); + } + + private static void Ok(string name) { Results.Add("ok " + name); W("ok " + name); } + private static void Fail(string name, string detail) { _fails++; Results.Add($"FAIL {name}: {detail}"); W($"FAIL {name}: {detail}"); } + private static void Unverified(string name, string detail) { _unverified++; Results.Add($"UNVERIFIED {name}: {detail}"); W($"UNVERIFIED {name}: {detail}"); } + + private static int Main(string[] args) + { + W($"harness pid={Environment.ProcessId} IntPtr.Size={IntPtr.Size} is64={Environment.Is64BitProcess} runtime={RuntimeInformation.FrameworkDescription} " + + $"invariantGlobalization={AppContext.TryGetSwitch("System.Globalization.Invariant", out bool inv) && inv}"); + if (IntPtr.Size != 4) { Fail("Bitness", $"IntPtr.Size={IntPtr.Size}; the harness must run 32-bit like acclient"); return Finish(); } + + string payloadDir = Path.Combine(AppContext.BaseDirectory, "payload"); + foreach (string a in args) + { + if (a.StartsWith("--payload=", StringComparison.Ordinal)) payloadDir = a.Substring(10); + // Opt in: the harness itself asks for the foreground (a plain SetForegroundWindow; Windows refuses it while + // the user is active elsewhere). Without it the foreground-dependent checks report UNVERIFIED. + if (a == "--foreground") _allowForeground = true; + } + if (Environment.GetEnvironmentVariable("WEBPANEL_HARNESS_FOREGROUND") == "1") _allowForeground = true; + _root = Path.Combine(Path.GetTempPath(), "rynth-webpanel-harness", DateTime.Now.ToString("yyyyMMdd-HHmmss")); + string lad = Path.Combine(_root, "LocalAppData"), panelDir = Path.Combine(_root, "panel"), otherDir = Path.Combine(_root, "other"); + WriteSite(panelDir, otherDir); + W($"payload {payloadDir}; temp root {_root}"); + + var up = new ManualResetEventSlim(); + var gt = new Thread(() => GameThread(up)) { IsBackground = true, Name = "FakeAcMain" }; + gt.SetApartmentState(ApartmentState.STA); + gt.Start(); + up.Wait(); + new Thread(PumpLoop) { IsBackground = true, Name = "FakeNormalPluginPump" }.Start(); + + // Foreground: only taken if this process may (it never forces it; no SendInput, no AttachThreadInput). + _haveForeground = EnsureForeground(_game); + W($"game window 0x{_game.ToInt64():X} tid={_gameTid}; harness may ask for the foreground (--foreground): {_allowForeground}; holds it: {_haveForeground} ({FgDesc()})"); + + // ---------------- session 1: the behaviour checks ---------------- + var s = new Session(payloadDir); + s.Call("Init", _game, payloadDir, lad, panelDir, otherDir, + (Action)(l => { LogLines.Enqueue(l); W(" engine log: " + l); }), + (Action)(c => { ChatLines.Enqueue(c); W(" chat: " + c); }), + (Action)(u => { BrowserCalls.Enqueue(u); W(" browser call recorded"); })); + _pumpSession = s; + + int handle = 0; + Guard("OpenIsNonBlocking", () => handle = CheckOpenIsNonBlocking(s)); + Guard("CyclesReuseEnvironment", () => handle = CheckCycles(s, handle)); + Guard("KeysStayInPage", () => handle = CheckKeys(s)); + Guard("EscapeClosesAndRefocusesGame", () => CheckEscape(s, handle)); + Guard("PageKeepsEscapeFlag", () => handle = CheckPageKeepsEscape(s)); + Guard("OffListRedirectGoesToBrowser", () => CheckRedirect(s, handle)); + Guard("WindowOpenNeverMakesAWindow", () => CheckWindowOpen(s, handle)); + Guard("CustomSchemeNeverLaunched", () => CheckCustomScheme(s, handle)); + Guard("StaleHandles", () => handle = CheckStaleHandles(s, handle)); + Guard("ProfileSwitchRecreates", () => handle = CheckProfileSwitch(s)); + Guard("NoBrowserFallbackAfterNavigation", () => CheckNoFallbackAfterNavigation(s, handle)); + 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."); + Guard("LayoutRemembered", () => handle = CheckLayout(s, lad)); + Guard("UnloadAfterCloseCollected", () => CheckUnloadAfterClose(ref s, handle)); + + // ---------------- session 2: unload with the panel up ---------------- + Guard("UnloadWhileVisibleCollected", () => CheckUnloadWhileVisible(payloadDir, lad, panelDir, otherDir)); + + Guard("NoSecretInLog", () => + { + int hits = LogLines.Count(l => l.Contains(Secret)) + ChatLines.Count(l => l.Contains(Secret)); + if (hits != 0) Fail("NoSecretInLog", $"{hits} log/chat line(s) contain {Secret}"); + else if (LogLines.IsEmpty) Fail("NoSecretInLog", "no engine log captured at all (the check would prove nothing)"); + else Ok("NoSecretInLog"); + }); + + _pumpStop = true; + W($"pump GetState calls from the fake pump thread: {Interlocked.Read(ref _pumpCalls)}"); + W($"fake game key messages total: {_gameKeyMsgs}"); + return Finish(); + } + + private static int Finish() + { + W("===== summary ====="); + foreach (string r in Results) W(r); + int exit = _fails > 0 ? 1 : _unverified > 0 ? 2 : 0; + W($"{Results.Count} checks: {Results.Count - _fails - _unverified} ok, {_fails} FAIL, {_unverified} UNVERIFIED -> exit {exit}"); + try { File.WriteAllText(Path.Combine(_root, "harness-output.txt"), Out.ToString()); } catch { } + return exit; + } + + private static void Guard(string name, Action check) + { + W($"----- {name} -----"); + try { check(); } + catch (Exception ex) { Fail(name, "threw " + (ex is TargetInvocationException t ? t.InnerException : ex)); } + } + + // ============================== checks ============================== + + private static int CheckOpenIsNonBlocking(Session s) + { + s.Call("SetEnvironmentDelay", 2000); + // Warm the argument reader and the host's validation once (an off-list URL never starts the thread). + var (warm, warmMs) = Open(s, "https://elsewhere.invalid/", Allow); + W($"warm-up open (off-list url) -> {warm} in {warmMs:F2} ms"); + bool threadBefore = (bool)s.Call("get_ThreadRunning")!; + string url = "https://panel.test/launch.html?code=" + Secret; + var (h, ms) = Open(s, url, Allow, title: "Harness launch"); + int[] st = State(s, h); + W($"first open -> handle {h} in {ms:F2} ms (thread running before: {threadBefore}); status right after: {st[2]}"); + bool ready = WaitStatus(s, h, StatusReady, 60000, out int[] fin); + string src = (string)s.Call("get_Source")!; + s.Call("SetEnvironmentDelay", 0); + if (h <= 0) { Fail("OpenIsNonBlocking", "open returned " + h); return h; } + if (threadBefore) { Fail("OpenIsNonBlocking", "the panel thread ran before the first open"); return h; } + if (ms >= 20) { Fail("OpenIsNonBlocking", $"open took {ms:F2} ms (>= 20)"); return h; } + if (st[2] != StatusStarting) { Fail("OpenIsNonBlocking", $"status right after open {st[2]}, want Starting"); return h; } + if (!ready) { Fail("OpenIsNonBlocking", $"never Ready: state [{string.Join(",", fin)}]"); return h; } + Ok("OpenIsNonBlocking"); + // The caller's buffers were overwritten with junk and freed right after Open returned (every Open does). + if (src != url) Fail("OpenCopiesCallerStrings", "page source is not the url passed in (redacted): " + Redact(src)); + else Ok("OpenCopiesCallerStrings"); + return h; + } + + private static int CheckCycles(Session s, int handle) + { + int envsBefore = (int)s.Call("get_EnvironmentCount")!; + int closeRc = (int)s.Call("Close", handle)!; + if (closeRc != CodeQueued || !WaitStatus(s, handle, StatusClosed, 5000, out _)) { Fail("CyclesReuseEnvironment", $"first close rc={closeRc} never Closed"); return handle; } + int modsAfter1 = -1, modsNow = -1; + var seq = new List(); + int h = handle; + for (int c = 1; c <= 5; c++) + { + (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Cycle " + c); + bool r = WaitStatus(s, h, StatusReady, 30000, out int[] a); + int rc = (int)s.Call("Close", h)!; + bool cl = WaitStatus(s, h, StatusClosed, 5000, out int[] b); + seq.Add($"{c}:{(r ? "Ready" : "st" + a[2])}/{(cl ? "Closed" : "st" + b[2])}(rc {rc})"); + modsNow = WebViewModuleCount(); + if (c == 1) modsAfter1 = modsNow; + } + int envs = (int)s.Call("get_EnvironmentCount")!; + W($"cycles {string.Join(" ", seq)}; environments {envsBefore} -> {envs}; webview modules after cycle 1 = {modsAfter1}, after cycle 5 = {modsNow}"); + if (seq.Any(x => !x.Contains("Ready/Closed"))) Fail("CyclesReuseEnvironment", "a cycle missed Ready or Closed: " + string.Join(" ", seq)); + else if (envs != 1 || envsBefore != 1) Fail("CyclesReuseEnvironment", $"environments created {envs} (want exactly 1)"); + else if (modsNow != modsAfter1) Fail("CyclesReuseEnvironment", $"webview module count changed {modsAfter1} -> {modsNow}"); + else Ok("CyclesReuseEnvironment"); + return h; + } + + private static int CheckKeys(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keys"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("KeysStayInPage", $"not Ready [{string.Join(",", a)}]"); return h; } + Thread.Sleep(500); + W("focus -> " + s.Call("Eval", "document.getElementById('t').focus(); JSON.stringify({active: document.activeElement && document.activeElement.id, hasFocus: document.hasFocus()})", 5000)); + IntPtr widget = RenderWidget(s, out string tree); + W("panel window tree: " + tree); + if (widget == IntPtr.Zero) { Fail("KeysStayInPage", "no Chrome_RenderWidgetHostHWND under the panel window"); return h; } + int g0 = _gameKeyMsgs, k0 = (int)s.Call("get_AcceleratorKeyEvents")!; + foreach (char ch in "x1q") PostKey(widget, char.ToUpperInvariant(ch), ch); + Thread.Sleep(1200); + string value = (string)s.Call("Eval", "document.getElementById('t').value", 5000)!; + 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")); + 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; + } + + private static void CheckEscape(Session s, int handle) + { + IntPtr widget = RenderWidget(s, out _); + if (widget == IntPtr.Zero) { Fail("EscapeClosesAndRefocusesGame", "no render widget to post to"); return; } + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + bool panelFg = EnsureForeground(host); + s.Call("Eval", "document.getElementById('t').focus(); 1", 5000); + W($"before Escape: panel holds the foreground {panelFg} ({FgDesc()}), panel visible {IsWindowVisible(host)}"); + int acc0 = (int)s.Call("get_AcceleratorKeyEvents")!; + int g0 = _gameKeyMsgs; + PostKey(widget, 0x1B, '\x1b'); + bool closed = WaitStatus(s, handle, StatusClosed, 3000, out int[] st); + int acc = (int)s.Call("get_AcceleratorKeyEvents")! - acc0; + int g = _gameKeyMsgs - g0; + Thread.Sleep(200); + IntPtr fg = GetForegroundWindow(); + W($"after posted Escape: status {st[2]}, AcceleratorKeyPressed events {acc}, game key messages {g}, foreground {FgDesc()} (game 0x{_game.ToInt64():X})"); + if (acc == 0) + { + Unverified("EscapeClosesAndRefocusesGame", $"AcceleratorKeyPressed did not fire for a POSTED Escape (status {st[2]}, panel held the foreground: {panelFg}; the page itself gets posted keys, see KeysStayInPage); Escape-to-close needs the owner's in-game check"); + if (!closed) { s.Call("Close", handle); WaitStatus(s, handle, StatusClosed, 3000, out _); } + 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"); + } + + private static int CheckPageKeepsEscape(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keeps Escape", flags: FlagFallback | FlagPageKeepsEscape); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("PageKeepsEscapeFlag", $"not Ready [{string.Join(",", a)}]"); return h; } + Thread.Sleep(400); + s.Call("Eval", "window.keys = []; document.getElementById('t').focus(); 1", 5000); + IntPtr widget = RenderWidget(s, out _); + int acc0 = (int)s.Call("get_AcceleratorKeyEvents")!; + PostKey(widget, 0x1B, '\x1b'); + Thread.Sleep(1200); + int acc = (int)s.Call("get_AcceleratorKeyEvents")! - acc0; + string keys = (string)s.Call("Eval", "JSON.stringify(window.keys)", 5000)!; + int[] st = State(s, h); + W($"flag 2: page keys {keys}, status {st[2]}, AcceleratorKeyPressed events {acc}"); + if (st[2] != StatusReady) Fail("PageKeepsEscapeFlag", $"panel status {st[2]}, want Ready (open)"); + else if (!keys.Contains("Escape")) Fail("PageKeepsEscapeFlag", "the page keydown listener did not see Escape: " + keys); + else if (acc == 0) Unverified("PageKeepsEscapeFlag", "page saw Escape and stayed open, but AcceleratorKeyPressed never fired for posted input, so the flag path itself was not exercised"); + else Ok("PageKeepsEscapeFlag"); + return h; + } + + private static void CheckRedirect(Session s, int h) + { + Drain(BrowserCalls); + string before = (string)s.Call("get_Source")!; + int rc = (int)s.Call("Navigate", h, "https://go.panel.test/redirect?code=" + Secret)!; + Thread.Sleep(2500); + string after = (string)s.Call("get_Source")!; + string[] calls = BrowserCalls.ToArray(); + string want = "https://other.test/landing.html"; + W($"navigate rc {rc}; source {Redact(before)} -> {Redact(after)}; browser calls {calls.Length}: {string.Join(" | ", calls.Select(Redact))}"); + if (rc != CodeQueued) Fail("OffListRedirectGoesToBrowser", "navigate rc " + rc); + else if (calls.Length != 1) Fail("OffListRedirectGoesToBrowser", $"{calls.Length} browser call(s), want 1 (served-302 log lines: {LogLines.Count(l => l.Contains("served the 302"))})"); + else if (Redact(calls[0]) != want) Fail("OffListRedirectGoesToBrowser", "browser got " + Redact(calls[0])); + else if (!after.StartsWith("https://panel.test/", StringComparison.Ordinal)) Fail("OffListRedirectGoesToBrowser", "panel left panel.test: " + Redact(after)); + else Ok("OffListRedirectGoesToBrowser"); + } + + private static void CheckWindowOpen(Session s, int h) + { + Drain(BrowserCalls); + uint bpid = (uint)(int)s.Call("get_BrowserProcessId")!; + HashSet before = TopLevelWindows(); + string r = (string)s.Call("Eval", "String(window.open('https://other.test/x.html?code=" + Secret + "'))", 5000)!; + Thread.Sleep(1500); + var fresh = TopLevelWindows().Where(w => !before.Contains(w) && IsWindowVisible(w)).Where(w => OwnedByUsOrWebView(w)).ToList(); + int calls = BrowserCalls.Count; + W($"window.open(other.test) -> {r}; new visible top-level windows of this process or msedgewebview2: {fresh.Count}; browser calls {calls}"); + string r2 = (string)s.Call("Eval", "String(window.open('https://panel.test/b.html'))", 5000)!; + bool onB = WaitFor(() => ((string)s.Call("get_Source")!).EndsWith("/b.html", StringComparison.Ordinal), 5000); + W($"window.open(panel.test/b.html) -> {r2}; panel on b.html: {onB}"); + if (fresh.Count != 0) Fail("WindowOpenNeverMakesAWindow", $"{fresh.Count} new top-level window(s)"); + else if (calls != 1) Fail("WindowOpenNeverMakesAWindow", $"{calls} browser call(s) for the off-list window.open, want 1"); + else if (!onB) Fail("WindowOpenNeverMakesAWindow", "window.open to an allowed url did not navigate the panel"); + else Ok("WindowOpenNeverMakesAWindow"); + WaitStatus(s, h, StatusReady, 5000, out _); + } + + private static void CheckCustomScheme(Session s, int h) + { + Drain(BrowserCalls); + string src0 = (string)s.Call("get_Source")!; + int[] st0 = State(s, h); + int logs0 = LogLines.Count; + s.Call("Eval", "location = 'ms-settings:'; 1", 5000); + Thread.Sleep(1500); + s.Call("Eval", "location = 'file:///C:/'; 1", 5000); + Thread.Sleep(1500); + string src = (string)s.Call("get_Source")!; + int[] st = State(s, h); + var newLogs = LogLines.Skip(logs0).ToList(); + W($"after ms-settings: and file:///C:/ -> source {Redact(src0)} -> {Redact(src)}; navigations {st0[6]} -> {st[6]}; browser calls {BrowserCalls.Count}; new log lines: {string.Join(" | ", newLogs)}"); + if (BrowserCalls.Count != 0) Fail("CustomSchemeNeverLaunched", "a browser call was made"); + else if (src != src0) Fail("CustomSchemeNeverLaunched", "the panel navigated away"); + else if (st[6] != st0[6]) Fail("CustomSchemeNeverLaunched", "the navigation count moved"); + else if (!newLogs.Any(l => l.Contains("(ms-settings)"))) Fail("CustomSchemeNeverLaunched", "no blocked-navigation log line for ms-settings:"); + else Ok("CustomSchemeNeverLaunched"); + } + + private static int CheckStaleHandles(Session s, int h) + { + var (h2, _) = Open(s, "https://panel.test/index.html", Allow, title: "Supersede"); + int[] old = State(s, h); + int nav = (int)s.Call("Navigate", h, "https://panel.test/b.html")!; + int close = (int)s.Call("Close", h)!; + bool ready = WaitStatus(s, h2, StatusReady, 30000, out _); + int offList = (int)s.Call("Navigate", h2, "https://other.test/x.html?code=" + Secret)!; + W($"old handle {h}: GetState {old[0]} status {old[2]}, Navigate {nav}, Close {close}; new handle {h2} = old + 1: {h2 == h + 1}; new Ready {ready}; off-list Navigate {offList}"); + Thread.Sleep(300); + if (old[0] != StatusSuperseded || old[2] != StatusSuperseded) Fail("StaleHandles", "old handle does not read Superseded"); + else if (nav != CodeStale || close != CodeStale) Fail("StaleHandles", $"old handle Navigate {nav} / Close {close}, want {CodeStale}"); + else if (h2 != h + 1) Fail("StaleHandles", "handles do not count up by one"); + else if (!ready) Fail("StaleHandles", "new handle never Ready"); + else if (offList != CodeUrlNotAllowed) Fail("StaleHandles", "off-list Navigate returned " + offList); + else Ok("StaleHandles"); + return h2; + } + + private static int CheckProfileSwitch(Session s) + { + int e0 = (int)s.Call("get_EnvironmentCount")!; + var (h1, _) = Open(s, "https://panel.test/index.html", Allow, key: "Alpha"); + bool r1 = WaitStatus(s, h1, StatusReady, 30000, out _); + int e1 = (int)s.Call("get_EnvironmentCount")!; + var (h2, _) = Open(s, "https://panel.test/b.html", Allow, key: "alpha "); + bool r2 = WaitStatus(s, h2, StatusReady, 30000, out _); + int e2 = (int)s.Call("get_EnvironmentCount")!; + string fDefault = (string)s.Call("ProfileFolder", "Harness World", "")!, fAlpha = (string)s.Call("ProfileFolder", "Harness World", "Alpha")!; + W($"environments {e0} -> {e1} (key Alpha) -> {e2} (key 'alpha ', same profile); folders default {Directory.Exists(fDefault)}, alpha {Directory.Exists(fAlpha)} ({fAlpha})"); + if (!r1 || !r2) Fail("ProfileSwitchRecreates", $"not Ready ({r1}, {r2})"); + else if (e1 != e0 + 1) Fail("ProfileSwitchRecreates", $"a new key did not create a new environment ({e0} -> {e1})"); + else if (e2 != e1) Fail("ProfileSwitchRecreates", $"the same key made another environment ({e1} -> {e2})"); + else if (fDefault == fAlpha || !Directory.Exists(fAlpha)) Fail("ProfileSwitchRecreates", "the alpha profile folder is missing or not separate"); + else Ok("ProfileSwitchRecreates"); + return h2; + } + + private static void CheckNoFallbackAfterNavigation(Session s, int h) + { + Drain(BrowserCalls); + int pid = (int)s.Call("get_BrowserProcessId")!; + if (pid == 0) { Fail("NoBrowserFallbackAfterNavigation", "no browser process id"); return; } + string name; + try { using var p = Process.GetProcessById(pid); name = p.ProcessName; if (!name.StartsWith("msedgewebview2", StringComparison.OrdinalIgnoreCase)) { Fail("NoBrowserFallbackAfterNavigation", "browser pid is " + name); return; } p.Kill(); } + catch (Exception ex) { Fail("NoBrowserFallbackAfterNavigation", "could not kill the panel's browser process: " + ex.Message); return; } + bool failed = WaitStatus(s, h, StatusFailed, 10000, out int[] st); + Thread.Sleep(500); + W($"killed browser pid {pid} ({name}); state [{string.Join(",", st)}]; browser calls {BrowserCalls.Count}"); + if (!failed) Fail("NoBrowserFallbackAfterNavigation", "status " + st[2] + ", want Failed"); + else if (st[4] != CodeProcessFailed) Fail("NoBrowserFallbackAfterNavigation", "error " + st[4] + ", want ProcessFailed"); + else if (BrowserCalls.Count != 0 || (st[3] & StateOpenedInBrowser) != 0) Fail("NoBrowserFallbackAfterNavigation", "fell back to the browser after a navigation"); + else Ok("NoBrowserFallbackAfterNavigation"); + // The next open recreates. + var (h2, _) = Open(s, "https://panel.test/index.html", Allow); + if (WaitStatus(s, h2, StatusReady, 30000, out int[] st2)) Ok("OpenAfterProcessFailedRecreates"); + else Fail("OpenAfterProcessFailedRecreates", $"[{string.Join(",", st2)}]"); + } + + private static void CheckCreateFailure(Session s) + { + Drain(BrowserCalls); + Drain(ChatLines); + s.Call("SetBrowserFolder", Path.Combine(_root, "no-such-browser")); + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); + bool failed = WaitStatus(s, h, StatusFailed, 20000, out int[] st); + s.Call("SetBrowserFolder", (string?)null); + string[] calls = BrowserCalls.ToArray(); + W($"forced create failure: state [{string.Join(",", st)}]; browser calls {calls.Length}; chat: {string.Join(" | ", ChatLines)}"); + if (!failed) Fail("CreateFailureFallsBack", "status " + st[2]); + else if (st[4] != CodeCreateFailed) Fail("CreateFailureFallsBack", "error " + st[4] + ", want CreateFailed"); + else if ((st[3] & StateOpenedInBrowser) == 0) Fail("CreateFailureFallsBack", "OpenedInBrowser flag not set"); + else if (calls.Length != 1 || Redact(calls[0]) != "https://panel.test/launch.html") Fail("CreateFailureFallsBack", $"{calls.Length} browser call(s)"); + else if (!ChatLines.Any(c => c.Contains("could not start (it failed to start)"))) Fail("CreateFailureFallsBack", "no fallback chat line"); + else Ok("CreateFailureFallsBack"); + } + + private static int CheckVisibilitySameProcess(Session s) + { + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Visibility"); + if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("VisibilitySameProcess", $"not Ready [{string.Join(",", a)}]"); return h; } + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + if (!EnsureForeground(host)) + { + Unverified("VisibilitySameProcess", $"the harness does not hold the foreground (--foreground {_allowForeground}; {FgDesc()}), so no in-process window can take it; owner in-game check (pop out a RynthCore window, panel stays)"); + return h; + } + Thread.Sleep(300); + bool visBefore = IsWindowVisible(host); + Game(() => { _popOut = CreateWindowExW(0, "FakeAcClient", "Fake pop-out", 0x00CF0000, 300, 300, 400, 300, IntPtr.Zero, IntPtr.Zero, GetModuleHandleW(IntPtr.Zero), IntPtr.Zero); ShowWindow(_popOut, 5); SetForegroundWindow(_popOut); return ""; }); + Thread.Sleep(600); + bool fgIsPop = GetForegroundWindow() == _popOut; + bool vis = IsWindowVisible(host); + Game(() => { DestroyWindow(_popOut); SetForegroundWindow(_game); return ""; }); + Thread.Sleep(300); + W($"panel visible before {visBefore}; pop-out foreground {fgIsPop}; panel visible with the pop-out in front {vis}; now {FgDesc()}"); + if (!visBefore) Fail("VisibilitySameProcess", "panel not visible before the pop-out"); + else if (!fgIsPop) Unverified("VisibilitySameProcess", "the pop-out could not take the foreground"); + else if (!vis) Fail("VisibilitySameProcess", "panel hid when another window of this process took the foreground"); + else Ok("VisibilitySameProcess"); + return h; + } + + private static int CheckLayout(Session s, string lad) + { + string path = Path.Combine(lad, "RynthCore", "WebPanel", "layout.json"); + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + // A drag is a modal loop inside DefWindowProc; WM_EXITSIZEMOVE is what the host saves on. Post the + // pair around a move made with SetWindowPos (no input involved). + GetClientRect(_game, out RECT gc); + var p = new POINT(); + ClientToScreen(_game, ref p); + PostMessageW(host, 0x0231 /* WM_ENTERSIZEMOVE */, IntPtr.Zero, IntPtr.Zero); + Thread.Sleep(150); + SetWindowPos(host, IntPtr.Zero, p.X + 20, p.Y + 30, gc.Right / 2, gc.Bottom / 2, 0x0004 | 0x0010); + PostMessageW(host, 0x0232 /* WM_EXITSIZEMOVE */, IntPtr.Zero, IntPtr.Zero); + bool saved = WaitFor(() => File.Exists(path), 3000); + string json = saved ? File.ReadAllText(path) : ""; + var (h, _) = Open(s, "https://panel.test/index.html", Allow, w: 40, hgt: 40); + WaitStatus(s, h, StatusReady, 30000, out _); + Thread.Sleep(300); + GetWindowRect(host, out RECT r); + W($"layout.json saved {saved}: {json}; panel after reopen at 40% request: [{r.Left - p.X},{r.Top - p.Y},{r.Right - r.Left}x{r.Bottom - r.Top}] client {gc.Right}x{gc.Bottom}"); + bool remembered = Math.Abs(r.Left - p.X - 20) <= 2 && Math.Abs(r.Top - p.Y - 30) <= 2 && Math.Abs((r.Right - r.Left) - gc.Right / 2) <= 2; + if (!saved) Fail("LayoutRemembered", "no layout.json after WM_EXITSIZEMOVE"); + else if (!json.Contains("\"x\"") || !json.Contains("\"h\"")) Fail("LayoutRemembered", "layout.json has no x/y/w/h: " + json); + else if (!remembered) Fail("LayoutRemembered", "the reopened panel did not take the stored layout over the 40% request"); + else Ok("LayoutRemembered"); + try { File.Delete(path); } catch { } + return h; + } + + private static void CheckUnloadAfterClose(ref Session s, int handle) + { + int[] st = State(s, handle); + int live = st[1]; + s.Call("Close", live); + WaitStatus(s, live, StatusClosed, 5000, out _); + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + var sd = Stopwatch.StartNew(); + s.Call("Shutdown", 2000); + W($"Shutdown(2000) returned in {sd.ElapsedMilliseconds} ms (panel closed)"); + bool stopped = !(bool)s.Call("get_ThreadRunning")!; + var (afterOpen, _) = Open(s, "https://panel.test/index.html", Allow); + int afterState = State(s, live)[0]; + int afterClose = (int)s.Call("Close", live)!; + W($"after Shutdown: thread stopped {stopped}, host window alive {IsWindow(host)}, Open {afterOpen}, GetState {afterState}, Close {afterClose}"); + if (!stopped || IsWindow(host) || afterOpen != CodeShuttingDown || afterState != CodeShuttingDown || afterClose != CodeShuttingDown) + Fail("ShutdownRefusesCalls", "thread or window survived, or a call did not return ShuttingDown"); + else Ok("ShutdownRefusesCalls"); + UnloadAndJudge("UnloadAfterCloseCollected", ref s); + } + + private static void CheckUnloadWhileVisible(string payloadDir, string lad, string panelDir, string otherDir) + { + var s = new Session(payloadDir); + s.Call("Init", _game, payloadDir, lad, panelDir, otherDir, + (Action)(l => { LogLines.Enqueue(l); W(" engine log (2): " + l); }), + (Action)(c => ChatLines.Enqueue(c)), + (Action)(u => BrowserCalls.Enqueue(u))); + _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")!)}"); + 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); + } + + private static void UnloadAndJudge(string name, ref Session s) + { + _pumpSession = null; + _pumpHandle = 0; + Thread.Sleep(100); + s.Call("Release"); + WeakReference weak = s.Unload(); + s = null!; + var sw = Stopwatch.StartNew(); + 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 Ok(name); + } + + // ============================== helpers ============================== + + private static (int Rc, double Ms) Open(Session s, string url, string allow, string key = "", string title = "", + uint flags = FlagFallback, int w = 0, int hgt = 0) + { + IntPtr pUrl = Utf8(url), pAllow = Utf8(allow), pKey = key.Length == 0 ? IntPtr.Zero : Utf8(key), pTitle = title.Length == 0 ? IntPtr.Zero : Utf8(title); + IntPtr pArgs = Marshal.AllocHGlobal(sizeof(OpenArgs)); + var a = (OpenArgs*)pArgs; + *a = default; + a->Size = (uint)sizeof(OpenArgs); + a->Flags = flags; + a->Url = (byte*)pUrl; a->Allowlist = (byte*)pAllow; a->ProfileKey = (byte*)pKey; a->Title = (byte*)pTitle; + a->WidthPercent = w; a->HeightPercent = hgt; + double ms = 0; + string r = Game(() => + { + long t0 = Stopwatch.GetTimestamp(); + int rc = (int)s.Call("Open", pArgs)!; + ms = Stopwatch.GetElapsedTime(t0).TotalMilliseconds; + // The SDK's buffers are stack or pooled: gone the moment the call returns. Junk them, then free. + Junk(pUrl); Junk(pAllow); Junk(pKey); Junk(pTitle); + new Span((void*)pArgs, sizeof(OpenArgs)).Fill(0xCD); + return rc.ToString(); + }); + foreach (IntPtr p in new[] { pUrl, pAllow, pKey, pTitle, pArgs }) if (p != IntPtr.Zero) Marshal.FreeHGlobal(p); + int code = int.TryParse(r, out int v) ? v : int.MinValue; + if (code > 0) _pumpHandle = code; + return (code, ms); + } + + private static readonly Dictionary Sizes = new(); + private static IntPtr Utf8(string s) + { + byte[] b = Encoding.UTF8.GetBytes(s + "\0"); + IntPtr p = Marshal.AllocHGlobal(b.Length); + Marshal.Copy(b, 0, p, b.Length); + lock (Sizes) Sizes[p] = b.Length; + return p; + } + private static void Junk(IntPtr p) + { + if (p == IntPtr.Zero) return; + int n; lock (Sizes) n = Sizes[p]; + new Span((void*)p, n - 1).Fill((byte)'Z'); + } + + private static int[] State(Session s, int h) => (int[])s.Call("GetState", h)!; + + private static bool WaitStatus(Session s, int h, int want, int ms, out int[] last) + { + var sw = Stopwatch.StartNew(); + last = State(s, h); + while (sw.ElapsedMilliseconds < ms) + { + last = State(s, h); + if (last[2] == want) return true; + if (want != StatusFailed && last[2] == StatusFailed) return false; + Thread.Sleep(25); + } + return false; + } + + private static bool WaitFor(Func f, int ms) + { + var sw = Stopwatch.StartNew(); + while (sw.ElapsedMilliseconds < ms) { if (f()) return true; Thread.Sleep(25); } + return f(); + } + + /// A plain SetForegroundWindow from the game thread (no input, no AttachThreadInput): Windows grants it or not. + private static bool EnsureForeground(IntPtr target) + { + if (IsOurs(GetForegroundWindow(), target)) return true; + if (!_allowForeground) return false; + Game(() => SetForegroundWindow(target) ? "1" : "0"); + Thread.Sleep(200); + return IsOurs(GetForegroundWindow(), target); + } + + private static bool IsOurs(IntPtr fg, IntPtr target) => fg != IntPtr.Zero && (fg == target || GetAncestor(fg, 2 /* GA_ROOT */) == target); + + private static string FgDesc() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return "foreground none"; + GetWindowThreadProcessId(fg, out uint pid); + return $"foreground 0x{fg.ToInt64():X} {Cls(fg)} pid {pid}{(pid == Environment.ProcessId ? " (this harness)" : "")}"; + } + + private static void Drain(ConcurrentQueue q) { while (q.TryDequeue(out _)) { } } + + private static string Redact(string? url) + { + if (string.IsNullOrEmpty(url) || !Uri.TryCreate(url, UriKind.Absolute, out Uri? u) || u.Host.Length == 0) return ""; + return u.Scheme + "://" + u.Host + (u.IsDefaultPort ? "" : ":" + u.Port) + u.AbsolutePath; + } + + private static void PostKey(IntPtr h, int vk, char ch) + { + uint scan = MapVirtualKeyW((uint)vk, 0); + IntPtr down = (IntPtr)(int)(1 | (scan << 16)), up = unchecked((IntPtr)(int)(1 | (scan << 16) | 0xC0000000)); + // Down and up only: the browser's own TranslateMessage makes the WM_CHAR (posting one too typed every key twice). + PostMessageW(h, 0x0100, (IntPtr)vk, down); + PostMessageW(h, 0x0101, (IntPtr)vk, up); + Thread.Sleep(60); + } + + private static IntPtr RenderWidget(Session s, out string tree) + { + IntPtr host = (IntPtr)s.Call("get_HostHwnd")!; + var all = new List(); + Collect(host, all); + var sb = new StringBuilder(); + IntPtr widget = IntPtr.Zero; + foreach (IntPtr c in all) + { + string cls = Cls(c); + GetWindowThreadProcessId(c, out uint pid); + sb.Append($"[0x{c.ToInt64():X} {cls} pid {pid}] "); + if (widget == IntPtr.Zero && cls == "Chrome_RenderWidgetHostHWND") widget = c; + } + tree = sb.ToString(); + return widget; + } + + private static void Collect(IntPtr h, List into) + { + for (IntPtr c = GetWindow(h, 5 /* GW_CHILD */); c != IntPtr.Zero; c = GetWindow(c, 2 /* GW_HWNDNEXT */)) + { + into.Add(c); + Collect(c, into); + } + } + + private static List? _enumInto; + private static HashSet TopLevelWindows() + { + _enumInto = new List(); + EnumWindows(&EnumProc, IntPtr.Zero); + var set = new HashSet(_enumInto); + _enumInto = null; + return set; + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int EnumProc(IntPtr h, IntPtr l) { _enumInto?.Add(h); return 1; } + + private static bool OwnedByUsOrWebView(IntPtr w) + { + GetWindowThreadProcessId(w, out uint pid); + if (pid == Environment.ProcessId) return true; + try { using var p = Process.GetProcessById((int)pid); return p.ProcessName.StartsWith("msedgewebview2", StringComparison.OrdinalIgnoreCase); } + catch { return false; } + } + + private static int WebViewModuleCount() + { + using var p = Process.GetCurrentProcess(); + p.Refresh(); + int n = 0; + foreach (ProcessModule m in p.Modules) + if (m.ModuleName.Contains("WebView", StringComparison.OrdinalIgnoreCase) || m.ModuleName.Contains("EmbeddedBrowser", StringComparison.OrdinalIgnoreCase)) n++; + return n; + } + + // ---- screenshot (PrintWindow PW_RENDERFULLCONTENT -> PNG), from the spike ---- + private static void Snap(IntPtr h, string path) + { + try + { + GetWindowRect(h, out RECT r); + int w = r.Right - r.Left, ht = r.Bottom - r.Top; + if (w <= 0 || ht <= 0) { W("screenshot skipped: empty window rect"); return; } + IntPtr sdc = GetDC(IntPtr.Zero), mdc = CreateCompatibleDC(sdc), bmp = CreateCompatibleBitmap(sdc, w, ht); + IntPtr old = SelectObject(mdc, bmp); + bool ok = PrintWindow(h, mdc, 2); + var bi = new BITMAPINFOHEADER { biSize = 40, biWidth = w, biHeight = -ht, biPlanes = 1, biBitCount = 32 }; + byte[] px = new byte[w * ht * 4]; + fixed (byte* p = px) GetDIBits(mdc, bmp, 0, (uint)ht, p, ref bi, 0); + SelectObject(mdc, old); DeleteObject(bmp); DeleteDC(mdc); ReleaseDC(IntPtr.Zero, sdc); + WritePng(path, w, ht, px); + W($"screenshot {path} ({w}x{ht}, PrintWindow ok={ok}, window visible={IsWindowVisible(h)})"); + } + catch (Exception ex) { W("screenshot failed: " + ex.Message); } + } + + private static void WritePng(string path, int w, int h, byte[] bgra) + { + using var raw = new MemoryStream(); + using (var z = new ZLibStream(raw, CompressionLevel.Fastest, true)) + for (int y = 0; y < h; y++) + { + z.WriteByte(0); + for (int x = 0; x < w; x++) { int i = (y * w + x) * 4; z.WriteByte(bgra[i + 2]); z.WriteByte(bgra[i + 1]); z.WriteByte(bgra[i]); } + } + using var f = File.Create(path); + f.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }); + var ihdr = new byte[13]; + BE(ihdr, 0, w); BE(ihdr, 4, h); ihdr[8] = 8; ihdr[9] = 2; + Chunk(f, "IHDR", ihdr); Chunk(f, "IDAT", raw.ToArray()); Chunk(f, "IEND", Array.Empty()); + } + + private static void BE(byte[] b, int o, int v) { b[o] = (byte)(v >> 24); b[o + 1] = (byte)(v >> 16); b[o + 2] = (byte)(v >> 8); b[o + 3] = (byte)v; } + + private static uint[]? _crc; + private static void Chunk(Stream s, string type, byte[] data) + { + if (_crc == null) { _crc = new uint[256]; for (uint n = 0; n < 256; n++) { uint c = n; for (int k = 0; k < 8; k++) c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1; _crc[n] = c; } } + var len = new byte[4]; BE(len, 0, data.Length); s.Write(len); + var td = new byte[4 + data.Length]; Encoding.ASCII.GetBytes(type).CopyTo(td, 0); data.CopyTo(td, 4); s.Write(td); + uint crc = 0xFFFFFFFF; foreach (byte b in td) crc = _crc[(crc ^ b) & 0xFF] ^ (crc >> 8); crc ^= 0xFFFFFFFF; + var cb = new byte[4]; BE(cb, 0, (int)crc); s.Write(cb); + } + + private static string Cls(IntPtr h) { char* b = stackalloc char[128]; int n = GetClassNameW(h, b, 128); return new string(b, 0, n); } + + private static void WriteSite(string panelDir, string otherDir) + { + Directory.CreateDirectory(panelDir); + Directory.CreateDirectory(otherDir); + string Page(string title) => + "" + title + "" + + "

" + title + "

" + + ""; + File.WriteAllText(Path.Combine(panelDir, "index.html"), Page("panel index")); + File.WriteAllText(Path.Combine(panelDir, "launch.html"), Page("panel launch")); + File.WriteAllText(Path.Combine(panelDir, "b.html"), Page("panel b")); + File.WriteAllText(Path.Combine(otherDir, "landing.html"), Page("other landing")); + File.WriteAllText(Path.Combine(otherDir, "x.html"), Page("other x")); + } + + // ============================== fake game ============================== + + private static string Game(Func fn) + { + var done = new ManualResetEventSlim(); + var res = new string[1]; + GameQ.Enqueue((fn, done, res)); + PostThreadMessageW(_gameTid, 0x8000 + 7, IntPtr.Zero, IntPtr.Zero); + if (!done.Wait(20000)) return "GAME THREAD TIMEOUT"; + return res[0]; + } + + private static void GameThread(ManualResetEventSlim up) + { + _gameTid = GetCurrentThreadId(); + string cls = "FakeAcClient"; + fixed (char* pc = cls) + { + var wc = new WNDCLASSEXW { cbSize = (uint)sizeof(WNDCLASSEXW), lpfnWndProc = (IntPtr)(delegate* unmanaged[Stdcall])&GameWndProc, hInstance = GetModuleHandleW(IntPtr.Zero), hbrBackground = (IntPtr)(1 + 1), lpszClassName = (IntPtr)pc }; + RegisterClassExW(ref wc); + } + _game = CreateWindowExW(0, cls, "Fake acclient (web panel harness)", 0x00CF0000 /* WS_OVERLAPPEDWINDOW */, 40, 40, 1100, 750, IntPtr.Zero, IntPtr.Zero, GetModuleHandleW(IntPtr.Zero), IntPtr.Zero); + ShowWindow(_game, 4 /* SW_SHOWNOACTIVATE */); + up.Set(); + while (true) + { + while (PeekMessageW(out MSG m, IntPtr.Zero, 0, 0, 1)) + { + if (m.hwnd == IntPtr.Zero && m.message == 0x8000 + 7) continue; + TranslateMessage(ref m); + DispatchMessageW(ref m); + } + while (GameQ.TryDequeue(out var job)) + { + try { job.Result[0] = job.Fn(); } catch (Exception ex) { job.Result[0] = "THREW " + (ex.InnerException ?? ex); } + job.Done.Set(); + } + MsgWaitForMultipleObjects(0, IntPtr.Zero, false, 10, 0x04FF); + } + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static IntPtr GameWndProc(IntPtr h, uint m, IntPtr w, IntPtr l) + { + if (m is 0x0100 or 0x0101 or 0x0102 or 0x0104 or 0x0105) Interlocked.Increment(ref _gameKeyMsgs); + return DefWindowProcW(h, m, w, l); + } + + private static void PumpLoop() + { + while (!_pumpStop) + { + Thread.Sleep(16); + PumpOnce(); + } + } + + [MethodImpl(MethodImplOptions.NoInlining)] + private static void PumpOnce() + { + Session? s = _pumpSession; + int h = _pumpHandle; + if (s == null || h == 0) return; + try { s.Call("GetState", h); Interlocked.Increment(ref _pumpCalls); } catch { } + } + + // ============================== payload context ============================== + + /// The payload in a collectible context (the shim's EngineLoadContext, reproduced). + private sealed class Session + { + private PayloadContext? _alc; + private Type? _type; + + public Session(string dir) + { + _alc = new PayloadContext(dir); + Assembly asm = _alc.LoadFromStreamOf(Path.Combine(dir, "WebPanelHarness.Payload.dll")); + _type = asm.GetType("RynthCore.Engine.WebPanel.PayloadEntry", throwOnError: true)!; + W($"payload loaded into a collectible context (IsCollectible={_alc.IsCollectible}, location '{asm.Location}')"); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public object? Call(string name, params object?[] args) + { + Type t = _type ?? throw new InvalidOperationException("payload unloaded"); + MethodInfo m = t.GetMethod(name, BindingFlags.Public | BindingFlags.Static) + ?? throw new MissingMethodException(name); + return m.Invoke(null, args); + } + + [MethodImpl(MethodImplOptions.NoInlining)] + public WeakReference Unload() + { + PayloadContext alc = _alc!; + _alc = null; + _type = null; + alc.Unload(); + return new WeakReference(alc, trackResurrection: true); + } + } + + private sealed class PayloadContext : AssemblyLoadContext + { + private static readonly HashSet PrivateFramework = new(StringComparer.OrdinalIgnoreCase) { "System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines" }; + private readonly string _dir; + public PayloadContext(string dir) : base("web panel payload", isCollectible: true) => _dir = dir; + + public Assembly LoadFromStreamOf(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + string pdb = Path.ChangeExtension(path, ".pdb"); + if (!File.Exists(pdb)) return LoadFromStream(fs); + using var ps = new FileStream(pdb, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return LoadFromStream(fs, ps); + } + + protected override Assembly? Load(AssemblyName name) + { + string? simple = name.Name; + if (string.IsNullOrEmpty(simple)) return null; + if (PrivateFramework.Contains(simple)) + { + string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, simple + ".dll"); + return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null; + } + string local = Path.Combine(_dir, simple + ".dll"); + return File.Exists(local) ? LoadFromStreamOf(local) : null; + } + + protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) + { + string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? unmanagedDllName : unmanagedDllName + ".dll"); + return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero; + } + } + + // ============================== interop ============================== + + [StructLayout(LayoutKind.Sequential, Pack = 4)] + private struct OpenArgs + { + public uint Size, Flags; + public byte* Url, Allowlist, ProfileKey, Title; + public int WidthPercent, HeightPercent; + public fixed uint Reserved[4]; + } + + [StructLayout(LayoutKind.Sequential)] private struct RECT { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] private struct BITMAPINFOHEADER { public uint biSize; public int biWidth, biHeight; public ushort biPlanes, biBitCount; public uint biCompression, biSizeImage; public int biXPelsPerMeter, biYPelsPerMeter; public uint biClrUsed, biClrImportant; } + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + [StructLayout(LayoutKind.Sequential)] private struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public POINT pt; } + [StructLayout(LayoutKind.Sequential)] private struct WNDCLASSEXW { public uint cbSize, style; public IntPtr lpfnWndProc; public int cbClsExtra, cbWndExtra; public IntPtr hInstance, hIcon, hCursor, hbrBackground, lpszMenuName, lpszClassName, hIconSm; } + + [DllImport("user32.dll")] private static extern ushort RegisterClassExW(ref WNDCLASSEXW wc); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CreateWindowExW(uint ex, string cls, string name, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param); + [DllImport("user32.dll")] private static extern bool DestroyWindow(IntPtr h); + [DllImport("user32.dll")] private static extern IntPtr DefWindowProcW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr h, int c); + [DllImport("user32.dll")] private static extern bool PeekMessageW(out MSG m, IntPtr h, uint a, uint b, uint r); + [DllImport("user32.dll")] private static extern bool TranslateMessage(ref MSG m); + [DllImport("user32.dll")] private static extern IntPtr DispatchMessageW(ref MSG m); + [DllImport("user32.dll")] private static extern bool PostThreadMessageW(uint t, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l); + [DllImport("user32.dll")] private static extern uint MsgWaitForMultipleObjects(uint n, IntPtr h, bool all, uint ms, uint mask); + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr h); + [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr h); + [DllImport("user32.dll")] private static extern bool IsWindow(IntPtr h); + [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr h, uint c); + [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr h, uint f); + [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetClassNameW(IntPtr h, char* b, int n); + [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr h, IntPtr a, int x, int y, int cx, int cy, uint f); + [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr h, out RECT r); + [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr h, ref POINT p); + [DllImport("user32.dll")] private static extern uint MapVirtualKeyW(uint code, uint type); + [DllImport("user32.dll")] private static extern bool EnumWindows(delegate* unmanaged[Stdcall] fn, IntPtr l); + [DllImport("user32.dll")] private static extern IntPtr GetDC(IntPtr h); + [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr h, IntPtr dc); + [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr h, IntPtr dc, uint f); + [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleDC(IntPtr dc); + [DllImport("gdi32.dll")] private static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int w, int h); + [DllImport("gdi32.dll")] private static extern IntPtr SelectObject(IntPtr dc, IntPtr o); + [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); + [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); + [DllImport("kernel32.dll")] private static extern IntPtr GetModuleHandleW(IntPtr n); +} diff --git a/tools/WebPanelHarness/WebPanelHarness.csproj b/tools/WebPanelHarness/WebPanelHarness.csproj new file mode 100644 index 0000000..6f320aa --- /dev/null +++ b/tools/WebPanelHarness/WebPanelHarness.csproj @@ -0,0 +1,52 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + true + enable + enable + true + WebPanelHarness + + + + + + + + + + + + + <_PayloadDir>@(_PayloadTarget->'%(RootDir)%(Directory)') + + + <_PayloadFiles Include="$(_PayloadDir)**\*.*" /> + + + + + -- 2.43.0 From 388f3fd908923731d93234f72d4934e845a5264b Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:26:37 -0800 Subject: [PATCH 07/17] Web panel host fix round 1: non-fatal process kinds, late failures, thread restart, focus and permission guards - ProcessFailed: only BrowserProcessExited (teardown) and RenderProcessExited (about:blank, recreate on the next Open) fail the panel, as WebView2's docs describe the kinds; GPU, utility, sandbox, PPAPI and frame-only renderer exits are logged only. RenderProcessUnresponsive fails it at 3 reports within 30 s. The handler acts on the panel being served now. - Fail decides "ignored" under the lock first and hides the panel only when the failure is live: a late failure for a superseded handle no longer hides the newer panel. - The panel thread's finally restarts the thread when an Open is still queued and the host is not shutting down; _threadDone goes false only after StartStaThread returns. - Show takes the foreground only when a window of this process (or of this panel's WebView2 browser process) holds it, never while the foreground is null. The visibility rule counts the browser process (CoreWebView2.BrowserProcessId) as ours, so the page's own dialogs do not hide the panel. - ClipboardRead is allowed only for an allowlisted origin. NavigationStarting and NewWindowRequested fail closed on an exception. - WebPanelApiRules: the ABI glue's pure parts (refusals, GetState Size check, state write), tested in WebPanelTests with WebPanelNativeArgs. WebPanelApi.LiveHandle and the browser pid in Describe for Task 4. - Harness: GpuProcessCrashKeepsPanel and LateFailureForSupersededHandle (both RED before the fix), UnloadWhileVisibleCollected reports UNVERIFIED when the window was not visible, the game-side key count is informational. EngineSettingsTests: WebPanel default-on round trip and setter case. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/WebPanel/WebPanelApi.cs | 32 ++-- .../WebPanel/WebPanelApiRules.cs | 46 +++++ src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 175 +++++++++++++----- tools/EngineSettingsTests/Program.cs | 35 ++++ tools/WebPanelHarness.Payload/PayloadEntry.cs | 2 + .../WebPanelHarness.Payload.csproj | 1 + tools/WebPanelHarness/Program.cs | 106 ++++++++++- tools/WebPanelTests/Program.cs | 88 ++++++++- tools/WebPanelTests/WebPanelTests.csproj | 6 + 9 files changed, 427 insertions(+), 64 deletions(-) create mode 100644 src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs 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
+ + + + -- 2.43.0 From ba7d96c7d98fb922343196102b9598e521876771 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:38:19 -0800 Subject: [PATCH 08/17] WebPanel: fix round 2 (unresponsive reset, foreground gate, clipboard, Open rollback) - Reset the unresponsive counter on teardown, on each new open and on navigation completed; harness check UnresponsiveCountResetsPerOpen. - Show only calls SetForegroundWindow when our process holds the foreground. - ClipboardRead permission is denied for about:blank. - Open rolls back live handle and status fields if the STA thread fails to start. - State struct minimum size is 28 on both platforms; test asserts it unguarded. - Harness Escape message reports game key count as informational. Co-Authored-By: Claude Opus 5.5 --- .../WebPanel/WebPanelApiRules.cs | 2 +- src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 29 +++++++++++++++++-- tools/WebPanelHarness.Payload/PayloadEntry.cs | 1 + tools/WebPanelHarness/Program.cs | 25 +++++++++++++++- tools/WebPanelTests/Program.cs | 2 +- 5 files changed, 54 insertions(+), 5 deletions(-) diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs index 68ed920..e2d1dd5 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs @@ -18,7 +18,7 @@ internal static unsafe class WebPanelApiRules /// 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). + /// OffsetOf(Reserved): the smallest Size a caller's WebPanelStateNative may declare (28 on x86 and x64: the struct has no pointer fields). public static uint StateMinSize { get diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs index 1bf2096..aec7a07 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -101,6 +101,11 @@ internal sealed unsafe class WebPanelHost if (_shuttingDown) return (int)WebPanelCode.ShuttingDown; if (_nextHandle <= 0) _nextHandle = (Environment.TickCount & 0x3FFFFFFF) | 1; int handle = _nextHandle++; + // Kept to undo below if the thread cannot start: the caller then sees a failure, and the state must agree. + int prevLive = _live, prevStatus = _status, prevError = _error, prevHttp = _http; + uint prevFlags = _flags, prevNav = _navCount; + string prevUrl = _liveUrl; + string[] prevAllow = _currentAllowlist; _live = handle; _status = (int)WebPanelStatusCode.Starting; _flags = 0; @@ -114,7 +119,18 @@ 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. - StartThreadLocked(); + try + { + StartThreadLocked(); + } + catch + { + // The queued ProcessOpen stays behind but is skipped: its handle is no longer live. + _live = prevLive; _status = prevStatus; _flags = prevFlags; _error = prevError; + _http = prevHttp; _navCount = prevNav; _liveUrl = prevUrl; _currentAllowlist = prevAllow; + _threadDone = true; + throw; // WebPanelApi reports Unavailable + } } else if (_hwnd != IntPtr.Zero) { @@ -251,6 +267,8 @@ internal sealed unsafe class WebPanelHost internal bool PostForTests(Action a) => Post(() => a(_web)); internal bool PanelOpenForTests => _open; /// A failure arriving late for (the harness passes a superseded one). + /// A renderer-unresponsive report, as WebView2 would raise it (counting against UnresponsiveLimit). + internal bool UnresponsiveForTests() => Post(() => HandleProcessFailed(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)); internal bool FailForTests(int handle) => Post(() => Fail(handle, WebPanelCode.ProcessFailed, "synthetic (harness)", allowFallback: false)); // ============================ panel thread ============================ @@ -463,6 +481,7 @@ internal sealed unsafe class WebPanelHost { if (_tornDown || !IsLive(handle)) return; // a newer Open is queued behind this one _serving = handle; + _unresponsiveCount = 0; // a new panel starts its own count _req = r; _title = string.IsNullOrWhiteSpace(r.Title) ? "RynthCore" : r.Title.Trim(); _fractions = WebPanelLayoutStore.TryLoad(_env.LocalAppData, out PanelFractions stored) @@ -669,6 +688,7 @@ internal sealed unsafe class WebPanelHost private void OnNavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e) { + _unresponsiveCount = 0; // a completed navigation means the renderer answered string source = _web?.Source ?? ""; if (string.Equals(source, "about:blank", StringComparison.OrdinalIgnoreCase) || !_open) return; _source = source; @@ -743,7 +763,9 @@ internal sealed unsafe class WebPanelHost CoreWebView2PermissionState state = CoreWebView2PermissionState.Deny; try { + // IsAllowed accepts about:blank (for our own close); a blank frame gets no clipboard. if (e.PermissionKind == CoreWebView2PermissionKind.ClipboardRead + && !string.Equals(e.Uri, "about:blank", StringComparison.OrdinalIgnoreCase) && WebPanelUrlPolicy.IsAllowed(e.Uri, _req?.Allowlist ?? Array.Empty())) state = CoreWebView2PermissionState.Allow; } @@ -861,10 +883,12 @@ internal sealed unsafe class WebPanelHost // 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. + // Only this process: a foreground in the WebView2 browser process is the page's own dialog, which keeps + // it (IsOurPid, which includes the browser, is for the visibility rule only). IntPtr fg = GetForegroundWindow(); uint fgPid = 0; if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); - if (fg != IntPtr.Zero && IsOurPid(fgPid)) SetForegroundWindow(_staHwnd); + if (fg != IntPtr.Zero && fgPid == _ourPid) SetForegroundWindow(_staHwnd); if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } FocusPage(); if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } @@ -1019,6 +1043,7 @@ internal sealed unsafe class WebPanelHost _createSeq++; _creating = false; _needsRecreate = false; + _unresponsiveCount = 0; CoreWebView2? web = _web; CoreWebView2Controller? ctl = _ctl; _web = null; diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs index 80b7385..d270cae 100644 --- a/tools/WebPanelHarness.Payload/PayloadEntry.cs +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -55,6 +55,7 @@ public static unsafe class PayloadEntry public static bool ThreadRunning => _host!.ThreadRunningForTests; public static bool PanelOpen => _host!.PanelOpenForTests; public static bool FailHandle(int handle) => _host!.FailForTests(handle); + public static bool ReportUnresponsive() => _host!.UnresponsiveForTests(); public static string ProfileFolder(string world, string key) => WebPanelProfile.Folder(_env!.LocalAppData, world, key); diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs index 0af02d7..edc372c 100644 --- a/tools/WebPanelHarness/Program.cs +++ b/tools/WebPanelHarness/Program.cs @@ -105,6 +105,7 @@ internal static unsafe class Program Guard("NoBrowserFallbackAfterNavigation", () => CheckNoFallbackAfterNavigation(s, handle)); Guard("GpuProcessCrashKeepsPanel", () => handle = CheckGpuCrash(s)); Guard("LateFailureForSupersededHandle", () => handle = CheckLateFailure(s)); + Guard("UnresponsiveCountResetsPerOpen", () => handle = CheckUnresponsiveReset(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."); @@ -249,7 +250,7 @@ internal static unsafe class Program return; } if (!closed) { Fail("EscapeClosesAndRefocusesGame", $"AcceleratorKeyPressed fired but the panel is {st[2]}, not Closed"); 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 (!panelFg) { Unverified("EscapeClosesAndRefocusesGame", $"closed (game key messages {g}, informational only); 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"); } @@ -447,6 +448,28 @@ internal static unsafe class Program return b; } + // Two unresponsive reports, a new Open, one more report: the count starts again per panel, so the new one + // stays Ready (the limit is 3 within 30 s). Reports are injected through the host's own handler. + private static int CheckUnresponsiveReset(Session s) + { + var (a, _) = Open(s, "https://panel.test/index.html", Allow, title: "Hung A"); + bool ra = WaitStatus(s, a, StatusReady, 30000, out _); + s.Call("ReportUnresponsive"); s.Call("ReportUnresponsive"); + Thread.Sleep(300); + int[] sa = State(s, a); + var (b, _) = Open(s, "https://panel.test/b.html", Allow, title: "Hung B"); + bool rb = WaitStatus(s, b, StatusReady, 30000, out _); + s.Call("ReportUnresponsive"); + Thread.Sleep(500); + int[] sb = State(s, b); + W($"two reports on {a}: state [{string.Join(",", sa)}]; then Open {b} Ready {rb}, one more report: state [{string.Join(",", sb)}]"); + if (!ra || !rb) Fail("UnresponsiveCountResetsPerOpen", "setup: not Ready"); + else if (sa[2] != StatusReady) Fail("UnresponsiveCountResetsPerOpen", "two reports already failed the panel (limit is 3)"); + else if (sb[2] != StatusReady) Fail("UnresponsiveCountResetsPerOpen", $"the third report overall failed the new panel: status {sb[2]} error {sb[4]}"); + else Ok("UnresponsiveCountResetsPerOpen"); + return b; + } + private static uint ParentPid(int pid) { IntPtr h = OpenProcess(0x1000 /* PROCESS_QUERY_LIMITED_INFORMATION */, false, pid); diff --git a/tools/WebPanelTests/Program.cs b/tools/WebPanelTests/Program.cs index 76e04bf..c89857e 100644 --- a/tools/WebPanelTests/Program.cs +++ b/tools/WebPanelTests/Program.cs @@ -204,7 +204,7 @@ internal static unsafe class Program 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"); + Eq(min, 28u, "OffsetOf(Reserved) of the state struct (no pointer fields: 28 on x86 and x64)"); Check(min > 0 && min < (uint)sizeof(WebPanelStateNative), "min size is inside the struct"); Check(!WebPanelApiRules.StateArgsOk(null), "null state refused"); WebPanelStateNative st = default; -- 2.43.0 From bfb87aba0462fdcd5ba19bcc73243bd4814a25f2 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:40:46 -0800 Subject: [PATCH 09/17] /rc webpanel status|close Status prints one redacted line (WebPanelApi.Describe plus the address space); close closes the live panel. Neither opens a URL. WebPanelHost.Describe now reports visible/focused/in-browser instead of raw flags; the stacked test-hook summaries are put back on their own members. ChatCommandReplyTests covers the verb. Co-Authored-By: Claude Opus 5.5 --- .../Compatibility/ChatCommandReplies.cs | 1 + .../Compatibility/RynthCoreChatCommands.cs | 25 +++++++++++++++++++ src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 4 +-- tools/ChatCommandReplyTests/Program.cs | 3 +++ 4 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs index 2a0e746..4e44f2c 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandReplies.cs @@ -200,6 +200,7 @@ internal static class ChatCommandReplies V("vitals", "Usage: /rc vitals (the old vitals HUD is gone: /rv plates self)", NoArgs, "hud"), V("layout", "Usage: /rc layout [status] | default | reset [confirm]", LayoutArgs), V("uicost", UiCostUsage, null), + V("webpanel", "Usage: /rc webpanel [status|close] (status is a redacted one-line report; it never opens a URL)", Words("", "status", "close")), }; /// /rc uicost: the UI frame cost breakdown (ImGui/UiCost.cs). diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 3330ce1..f174872 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -651,6 +651,13 @@ internal static class RynthCoreChatCommands return; } // /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout). + // /rc webpanel [status|close]: diagnostics for the in-game web panel. It never opens a URL + // (an arbitrary-URL command would be a phishing vector); every URL in the line is redacted. + if (IsVerb(sub, "webpanel", out string webPanelArgs)) + { + HandleWebPanelCommand(webPanelArgs); + return; + } if (IsVerb(sub, "layout", out string layoutArgs)) { HandleLayoutCommand(layoutArgs); @@ -1722,6 +1729,24 @@ internal static class RynthCoreChatCommands /// reset asks, reset confirm copies the default over this character's. Those two answer when their /// files are written (from the UI writer), or at once with why they can't run. ///
+ /// + /// /rc webpanel [status|close]. Status: one redacted line (WebPanelApi.Describe plus the address + /// space). Close: closes the live panel (WebPanelApi.Close does not block). Nothing here opens a URL. + /// + private static void HandleWebPanelCommand(string args) + { + string a = args.Trim().ToLowerInvariant(); + if (a == "close") + { + int handle = WebPanel.WebPanelApi.LiveHandle; + if (handle <= 0) { Reply("web panel: nothing to close."); return; } + int rc = WebPanel.WebPanelApi.Close(handle); + Reply($"web panel: close requested (handle {handle}, code {rc})."); + return; + } + Reply(WebPanel.WebPanelApi.Describe() + "; address space " + AddressSpace.Describe()); + } + private static void HandleLayoutCommand(string args) { UI.LayoutCommand cmd = UI.PanelLayoutPolicy.ParseCommand(args); diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs index aec7a07..c636896 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -222,7 +222,7 @@ 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}, browser pid {_browserPid}, url {WebPanelUrlPolicy.Redact(_liveUrl)}"; + $"http {_http}, navigations {_navCount}, environments {_environmentCount}, visible {((_flags & StateVisible) != 0 ? "yes" : "no")}, focused {((_flags & StateFocused) != 0 ? "yes" : "no")}, in browser {((_flags & StateOpenedInBrowser) != 0 ? "yes" : "no")}, browser pid {_browserPid}, url {WebPanelUrlPolicy.Redact(_liveUrl)}"; } } @@ -266,9 +266,9 @@ internal sealed unsafe class WebPanelHost 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). /// A renderer-unresponsive report, as WebView2 would raise it (counting against UnresponsiveLimit). internal bool UnresponsiveForTests() => Post(() => HandleProcessFailed(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)); + /// 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 ============================ diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index d2efaca..e82fc1f 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -115,6 +115,9 @@ internal static class Program ("layout", "layout", "layout frob"), ("layout", "layout reset confirm", "layout reset now"), ("layout", "layout default", "layout default now"), + ("webpanel", "webpanel status", "webpanel open"), + ("webpanel", "webpanel", "webpanel frob"), + ("webpanel", "webpanel close", "webpanel close now"), }; private static void EveryVerbValidAndInvalid() -- 2.43.0 From 9797db14a39678e53ab5350faabd4066b3ad6416 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:41:27 -0800 Subject: [PATCH 10/17] Ship WebView2 Core and the x86 loader in Runtime; installer checks; notices Build-Installer.ps1 now requires Runtime\Microsoft.Web.WebView2.Core.dll and Runtime\WebView2Loader.dll in a CoreCLR staging tree. THIRD-PARTY-NOTICES.md gains the Microsoft WebView2 SDK entry with the licence copied from the package's LICENSE.txt. A scratch EngineOnly publish put both DLLs at the target root, the loader is x86 (0x14C), and no runtimes\ folder or WinForms/Wpf DLL is present, so no csproj change was needed. Co-Authored-By: Claude Opus 5.5 --- THIRD-PARTY-NOTICES.md | 37 +++++++++++++++++++++++++++++++++++ installer/Build-Installer.ps1 | 4 +++- 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index fa14668..91ad778 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -76,3 +76,40 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## Microsoft WebView2 SDK (the in-game web panel) + +- What: `Microsoft.Web.WebView2.Core.dll` (the managed WebView2 Core wrapper) and the x86 `WebView2Loader.dll`, which the engine uses to host the in-game web panel on the CoreCLR build. They find and drive the Evergreen WebView2 Runtime already installed on the machine; the runtime itself is not shipped. +- Where: shipped in `Runtime\` of every CoreCLR install, referenced from `src/RynthCore.Engine/RynthCore.Engine.csproj` (NuGet `Microsoft.Web.WebView2` 1.0.2903.40). The package's WinForms and WPF assemblies are not used or shipped. +- Source: https://www.nuget.org/packages/Microsoft.Web.WebView2 +- Licence: Microsoft's BSD-style licence, reproduced below from the package's own LICENSE.txt. + +``` +Copyright (C) Microsoft Corporation. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * The name of Microsoft Corporation, or the names of its contributors +may not be used to endorse or promote products derived from this +software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +``` diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 8cc0b84..79f9625 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -359,7 +359,9 @@ if (-not $NativeAot) { $required += @( "$StagingDir\Runtime\RynthCore.Shim.dll", "$StagingDir\Runtime\dotnet\coreclr.dll", - "$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll" + "$StagingDir\Runtime\dotnet\System.Private.CoreLib.dll", + "$StagingDir\Runtime\Microsoft.Web.WebView2.Core.dll", + "$StagingDir\Runtime\WebView2Loader.dll" ) } if (-not $SkipDecalBridge) { -- 2.43.0 From 4e30b16bf5f47d2f4158470510d84cdb1dffcf26 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:47:57 -0800 Subject: [PATCH 11/17] WebPanel fix round 1: close reply by code, loader PE check, no-open scan, drop Core.xml - RynthCoreChatCommands: each method keeps its own summary; /rc webpanel close answers by the Close code (closing / already closed / could not close); verb added to the class header list. - Build-Installer.ps1: Assert-PeMachine throws unless Runtime\WebView2Loader.dll is x86 (0x14C). - ChatCommandReplyTests: HandleWebPanelCommand has no Open(, Navigate( or ShellExecute. - Engine csproj: Microsoft.Web.WebView2.Core.xml is not copied (with the other dropped WebView2 copies). Co-Authored-By: Claude Opus 5.5 --- installer/Build-Installer.ps1 | 15 +++++++++++++- .../Compatibility/RynthCoreChatCommands.cs | 20 ++++++++++++------- src/RynthCore.Engine/RynthCore.Engine.csproj | 2 ++ tools/ChatCommandReplyTests/Program.cs | 14 ++++++++++++- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 79f9625..b982d4d 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -339,6 +339,17 @@ if ($SkipDecalBridge) { # release.txt — which core release this install is ($release, from -Version at the top). Set-Content -Path "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII +# The PE machine field of a DLL (e_lfanew at 0x3C, then the COFF Machine at PE offset + 4). The game is +# 32-bit, so the web panel's native loader must be the x86 one (0x14C): the NuGet package also carries +# win-x64 and win-arm64 copies that would load nowhere. +function Assert-PeMachine([string]$Path, [int]$Expected) { + $bytes = [System.IO.File]::ReadAllBytes($Path) + if ($bytes.Length -lt 0x40) { throw "$Path is not a PE file (too short)" } + $pe = [System.BitConverter]::ToInt32($bytes, 0x3C) + if ($pe -lt 0 -or $pe + 6 -gt $bytes.Length) { throw "$Path is not a PE file (bad e_lfanew)" } + $machine = [System.BitConverter]::ToUInt16($bytes, $pe + 4) + if ($machine -ne $Expected) { throw ("{0}: PE machine 0x{1:X}, expected 0x{2:X}" -f $Path, $machine, $Expected) } +} # Everything a working install needs. The 2026-09-25 public installer went out # without the Loader and the SEH trampoline because nothing checked. $required = @( @@ -369,7 +380,9 @@ if (-not $SkipDecalBridge) { } $missing = @($required | Where-Object { -not (Test-Path $_) }) if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" } - +if (-not $NativeAot) { + Assert-PeMachine "$StagingDir\Runtime\WebView2Loader.dll" 0x14C +} # Report staged sizes $engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll" if (Test-Path $engineDll) { diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index f174872..b627033 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -108,6 +108,9 @@ namespace RynthCore.Engine.Compatibility; /// /rc uicost [on|off|<ms>|now|status] - the UI frame cost breakdown /// (): timing on or off, the slow-frame threshold, and (now, or /// alone) which parts of the UI frame took the time over the last seconds. Also Settings > Diagnostics. +/// /rc webpanel [status|close] - the in-game web panel (): +/// status is one redacted line (state, handle, visible/focused, browser pid, free address space); +/// close closes the panel. It never opens a URL. /// /// internal static class RynthCoreChatCommands @@ -1723,12 +1726,6 @@ internal static class RynthCoreChatCommands ReplyLines(UI.Data.Discord.ChatDiscord.HandleCommand(verb)); } - /// - /// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own, - /// or the PC-wide default and why); default makes this character's the default for new characters; - /// reset asks, reset confirm copies the default over this character's. Those two answer when their - /// files are written (from the UI writer), or at once with why they can't run. - /// /// /// /rc webpanel [status|close]. Status: one redacted line (WebPanelApi.Describe plus the address /// space). Close: closes the live panel (WebPanelApi.Close does not block). Nothing here opens a URL. @@ -1741,12 +1738,21 @@ internal static class RynthCoreChatCommands int handle = WebPanel.WebPanelApi.LiveHandle; if (handle <= 0) { Reply("web panel: nothing to close."); return; } int rc = WebPanel.WebPanelApi.Close(handle); - Reply($"web panel: close requested (handle {handle}, code {rc})."); + // 1 = closing, 0 = already closed (the WebPanelCode values); anything else is a refusal or error. + if (rc == 1) Reply("web panel: closing."); + else if (rc == 0) Reply("web panel: already closed."); + else Fail($"web panel: could not close (code {rc})."); return; } Reply(WebPanel.WebPanelApi.Describe() + "; address space " + AddressSpace.Describe()); } + /// + /// /rc layout: which panel layout this client uses and its files (UI/PanelLayout: the character's own, + /// or the PC-wide default and why); default makes this character's the default for new characters; + /// reset asks, reset confirm copies the default over this character's. Those two answer when their + /// files are written (from the UI writer), or at once with why they can't run. + /// private static void HandleLayoutCommand(string args) { UI.LayoutCommand cmd = UI.PanelLayoutPolicy.ParseCommand(args); diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 20ff4a7..a9dfca5 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -69,6 +69,8 @@ + + diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index e82fc1f..6b43a73 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -344,7 +344,19 @@ internal static class Program Check(!Regex.IsMatch(src, @"\bReply\(\$?""[Uu]sage"), "no usage line is written as a success (they go through Fail)"); Check(!Regex.IsMatch(src, @"\bReply\((usage|ServerUsage)\)"), "nor the usage constants"); Check(!Regex.IsMatch(src, @"catch \(Exception ex\) \{ RynthLog\.Compat"), "no command's exception is only logged"); - } + + Case("RynthCoreChatCommands.cs: /rc webpanel never opens or navigates (an arbitrary-URL command would be a phishing vector)"); + int wpStart = src.IndexOf("private static void HandleWebPanelCommand", StringComparison.Ordinal); + int wpEnd = src.IndexOf("private static void HandleLayoutCommand", StringComparison.Ordinal); + Check(wpStart > 0 && wpEnd > wpStart, "found HandleWebPanelCommand"); + if (wpStart > 0 && wpEnd > wpStart) + { + string wp = src.Substring(wpStart, wpEnd - wpStart); + Check(!Regex.IsMatch(wp, @"\bOpen\("), "HandleWebPanelCommand has no Open("); + Check(!Regex.IsMatch(wp, @"\bNavigate\("), "HandleWebPanelCommand has no Navigate("); + Check(!wp.Contains("ShellExecute", StringComparison.Ordinal), "HandleWebPanelCommand has no ShellExecute"); + Check(wp.Contains("WebPanelApi.Close(", StringComparison.Ordinal), "the scan reads the real body (it calls WebPanelApi.Close)"); + } } private static string? FindRepoFile(string relative) { -- 2.43.0 From 6918e6736ff6b2f010c3c8163a9a47332d3a0482 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:52:13 -0800 Subject: [PATCH 12/17] Docs: web panel API Plugin contract (docs/WEB_PANEL.md) and changelog for the v93 web panel. Co-Authored-By: Claude Opus 5.5 --- Changelog/2026-11-07-web-panel.md | 43 +++++ docs/WEB_PANEL.md | 288 ++++++++++++++++++++++++++++++ 2 files changed, 331 insertions(+) create mode 100644 Changelog/2026-11-07-web-panel.md create mode 100644 docs/WEB_PANEL.md diff --git a/Changelog/2026-11-07-web-panel.md b/Changelog/2026-11-07-web-panel.md new file mode 100644 index 0000000..3d497b2 --- /dev/null +++ b/Changelog/2026-11-07-web-panel.md @@ -0,0 +1,43 @@ +# In-game web panel: plugin API v93 + +Branch `up/web-panel`, from upstream `main` 418d80b. Not deployed. The API number 93 is provisional +(upstream may take 93 first; it renumbers on merge). CoreCLR engine only. + +## What changed + +- Four new function slots at the end of the plugin API table (`WebPanelOpenFn`, `WebPanelNavigateFn`, + `WebPanelCloseFn`, `WebPanelGetStateFn`), and SDK wrappers on `RynthCoreHost`: `HasWebPanel`, + `OpenWebPanel(WebPanelOptions)`, `NavigateWebPanel`, `CloseWebPanel`, `GetWebPanelState`. Types are in + `RynthCore.PluginSdk/WebPanelTypes.cs`. No call blocks its caller. +- `WebPanel/WebPanelHost.cs` (engine): one WebView2 panel over the game window, on its own STA thread, with an + unowned popup window, a caption bar with a close box, a remembered size and place, and Escape / Alt+F4 / `X` to close. +- Navigation allowlist (`WebPanelUrlPolicy`): https only, default port, no user info, exact host or `*.suffix` + (`*.x.com` does not match `x.com`: list both). Off-list navigations, pop-ups and custom-scheme launches never + load in the panel; an absolute http(s) URL goes to the system browser, anything else is dropped. +- Per-world, per-key WebView2 profile (`WebPanelProfile`): the plugin's key is lower-cased and hashed, and the world is added. +- `/rc webpanel [status|close]`: a redacted one-line report, and a close. +- `engine.json` `"WebPanel": false`: kill switch. `OpenWebPanel` then answers `Unavailable`. +- `RynthCore.PluginSdk.targets` already raised a shared-SDK release build's `RynthPluginMinEngineApi` below 88 to the + SDK's API; that is now 93 for every such plugin. Plugins that must run on older cores declare 88 or higher. +- `tools\WebPanelHarness`: an offline 32-bit harness for the host (see the doc). +- Docs: `docs/WEB_PANEL.md` is the plugin contract. + +## How it behaves + +- The panel never takes focus from another program. It takes the foreground only if the foreground window already + belongs to the game, and it hides while another program is in front. +- Logs and chat never carry a URL's query, fragment or user info (the launch code rides in the query). +- Failures: the panel fails only when the WebView2 browser process or the main renderer exits, or the renderer is + reported unresponsive 3 times in 30 s. Other process failures are logged. `RuntimeMissing` / `CreateFailed` fall back to + the system browser when the plugin asked for it (the default). Page permission `ClipboardRead` is allowed only + for allowlisted origins; the rest are denied. +- The NativeAOT engine flavour has no web panel: the slots stay zero and `HasWebPanel` is false. + +## Tests + +`tools/WebPanelTests`: URL allowlist and redaction, window visibility and layout, profile folder, the ABI glue. +`tools/WebPanelHarness`: the host in a collectible load context against real WebView2 (needs a desktop, the +WebView2 runtime and the x86 .NET 10 runtime; not part of `Run-AllTests.ps1`). Checks that need another program in +the foreground report UNVERIFIED and are owner in-game checks. + +Not yet tested in game. \ No newline at end of file diff --git a/docs/WEB_PANEL.md b/docs/WEB_PANEL.md new file mode 100644 index 0000000..10e7acf --- /dev/null +++ b/docs/WEB_PANEL.md @@ -0,0 +1,288 @@ +# In-game web panel (plugin API v93) + +A plugin can show a web page in a panel over the Asheron's Call window. The page runs in WebView2. +The engine owns the window, the navigation allowlist, focus and the lifetime; the plugin passes a URL, +an allowlist and a profile key, then polls for state. This file is the contract plugin authors build against. + +The API number 93 is provisional: upstream may take 93 first, in which case it renumbers on merge +(`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 93` checks, and nothing breaks. + +## Calls + +The SDK wrappers are on `RynthCoreHost` (`RynthCore.PluginSdk`). None of them blocks, and all of them are safe +to call from any thread (AC's main thread, the plugin pump, an ImGui draw). Never wait on the panel: call +`OpenWebPanel`, return, and poll `GetWebPanelState`. + +| Call | Does | +|---|---| +| `bool HasWebPanel` | True only on an engine at API 93 or newer that fills all four function slots. Check it before any other call. | +| `int OpenWebPanel(WebPanelOptions)` | Opens the panel, or replaces the open one. Returns a handle > 0, or a negative `WebPanelResult`. | +| `int NavigateWebPanel(int handle, string url)` | Points the open panel at a URL. `1` queued. | +| `int CloseWebPanel(int handle)` | Closes the panel. `1` queued, `0` already closed. | +| `WebPanelStatus GetWebPanelState(int handle, out WebPanelState state)` | Where the panel is. | + +On an engine without the feature the wrappers return `Unavailable` (`GetWebPanelState` returns `None`). +The NativeAOT engine flavour has no web panel: it leaves the four slots zero, so `HasWebPanel` is false there. +Setting `"WebPanel": false` in `engine.json` is a kill switch: `OpenWebPanel` then returns `Unavailable`. A +panel that is already open stays until it is closed. + +### WebPanelOptions + +| Field | Meaning | +|---|---| +| `Url` (required) | At most 4096 UTF-8 bytes. Must pass the same allowlist test as every other URL (below). | +| `Allowlist` (required) | 1 to 16 entries; no `\n` inside an entry. | +| `ProfileKey` | Opaque string, at most 256 UTF-8 bytes. Default empty. | +| `Title` | Caption text, at most 128 UTF-8 bytes. Default empty, which shows "RynthCore". | +| `WidthPercent`, `HeightPercent` | 0 means 88; otherwise clamped to 30..100. Used only when no layout has been remembered. | +| `Flags` | `WebPanelFlags`. Default `FallbackToBrowser`. | + +`WebPanelFlags`: + +| Flag | Value | Meaning | +|---|---|---| +| `FallbackToBrowser` | 1 | If the panel cannot start (no WebView2 runtime, creation failed), the engine opens the URL in the system browser. | +| `PageKeepsEscape` | 2 | Escape goes to the page instead of closing the panel. | + +Bit 4 is reserved. Unknown bits are ignored. + +### Return codes (`WebPanelResult`) + +| Value | Name | Meaning | +|---|---|---| +| 1 | `Queued` | Navigate or Close accepted. | +| 0 | `AlreadyClosed` | Close: the panel was already Closed or Failed. | +| -1 | `BadArgs` | Empty URL or allowlist, more than 16 entries, a bad allowlist entry, a string over its byte limit, invalid UTF-8, or a struct `Size` that is too small. | +| -2 | `UrlNotAllowed` | The URL is not allowed by the allowlist. See Navigate below. | +| -3 | `NoGameWindow` | There is no game window to cover. | +| -4 | `Unavailable` | Older engine, NativeAOT engine, `engine.json` kill switch, or an internal error. | +| -5 | `ShuttingDown` | The engine is shutting down. | +| -6 | `StaleHandle` | The handle is not the live panel (Navigate, Close). | +| -7 | `RuntimeMissing` | State `Error` only: the WebView2 runtime is not installed. | +| -8 | `CreateFailed` | State `Error` only: the panel window or WebView2 could not be created. | +| -9 | `ProcessFailed` | State `Error` only: the WebView2 browser or renderer process died or hung. | + +`OpenWebPanel` returns a handle (> 0) as soon as the request is queued. The panel loads after that, so a handle +does not mean the page loaded. A later failure shows up in the state as `Failed` with `Error` set. + +### State + +`GetWebPanelState` returns the status and fills `WebPanelState(Handle, Status, Flags, Error, LastHttpStatus, NavigationCount)`. + +| `WebPanelStatus` | Value | Meaning | +|---|---|---| +| `None` | 0 | Returned by the wrapper (not by the engine) on an older engine, bad arguments, or while the engine shuts down. | +| `Starting` | 1 | Open accepted; the WebView2 window is being created. | +| `Loading` | 2 | A navigation has started. | +| `Ready` | 3 | A navigation completed. This means the page answered, not that it succeeded: check `LastHttpStatus`. | +| `Closed` | 4 | Closed by the plugin, the player, or the engine. | +| `Failed` | 5 | See `Error`. | +| `Superseded` | 6 | The handle is not the live panel: a newer Open replaced it, or no panel was ever opened. | + +`WebPanelStateFlags`: `Visible` = 1, `Focused` = 2, `OpenedInBrowser` = 4 (the engine's fallback opened the URL in +the system browser). `LastHttpStatus` is the last non-zero HTTP status of a completed navigation. `NavigationCount` +counts navigations that started on an allowed URL since Open (the `about:blank` the engine uses to clear the page is +not counted). + +## Allowlist + +The allowlist decides what the panel may show. It is checked on Open, on Navigate, on every navigation the page +starts itself, and on pop-up requests. Entries are matched against the URL's host: + +- `host`: exactly that host. `example.com` matches `example.com` only. +- `*.suffix`: any subdomain, at any depth, but not the suffix itself. `*.example.com` matches `a.example.com` + and `a.b.example.com`, and does **not** match `example.com`. To allow both, list both entries. +- The suffix after `*.` must contain a dot, so `*.com` is rejected. +- No scheme, path, port or other `*`. Entries are lower-cased and trimmed; blank lines are ignored. +- Entries are ASCII: letters, digits, `-` and `.`; each label 1 to 63 characters, not starting or ending with `-`; + at most 253 characters per entry. Write an internationalised host in its punycode form (`xn--...`). +- 1 to 16 entries, and the joined list must fit in 8192 bytes. + +A URL is allowed only if it is `https`, has no user info, uses the default port (443), and its host matches an entry +(compared in lower case, one trailing dot ignored, IDN hosts in punycode). `about:blank` is also always allowed. +That means an `http:` URL and a URL with a port are never allowed, whatever the list says. + +### What the engine does with a URL that is not allowed + +- `OpenWebPanel`: returns `UrlNotAllowed` and opens nothing. +- `NavigateWebPanel`: returns `UrlNotAllowed`, and the engine opens the URL in the system browser instead if it + is absolute `http` or `https` without user info. Anything else is dropped and logged. +- A navigation the page starts: cancelled, then handled the same way as Navigate. +- `window.open` and other new-window requests: never a second window. An allowed URL loads in the panel; any + other goes to the system browser as above. +- Custom-scheme launches (`foo://`): blocked and logged. + +When the engine opens the system browser for an off-list URL it writes `[RynthCore] Opened in your web +browser.` to chat. Only the host is shown. Logs and chat never contain a URL's query, fragment or user info (the +launch code of a login URL rides in the query), only `scheme://host[:port]/path`. + +### Page permissions + +Everything the page asks permission for is denied, except `ClipboardRead`, which is allowed only for a frame whose +URL is on the allowlist (a blank frame gets none). Developer tools, browser accelerator keys, the status bar, +host objects, web messages and password autosave are all off. + +## Profile key + +WebView2 keeps cookies and storage in a profile folder. The plugin passes an opaque key; the engine builds the folder: + +``` +\RynthCore\WebPanel\\ +``` + +- ``: the key is trimmed and lower-cased, and the first 16 bytes of its SHA-256 (of the UTF-8 text) are written + as lower-case hex. An empty key is the folder `default`. +- ``: the connected world's name, with every character outside `A-Z a-z 0-9 space _ -` replaced by `_`, + at most 64 characters; empty becomes `_default`. + +So the same key on two worlds is two separate profiles, and `Key` and `key` are the same profile. Use a key that +names the site or account. Do not put a secret in it. +Opening with a different profile than the last Open tears WebView2 down and creates it again; same profile, the +WebView2 environment is reused. + +## Window, focus and close + +- The panel is a window over the game's client area, with a 28 px caption bar (the title, and an `X` close box). + The caption bar drags it; the frame resizes it. Minimum size is 480 x 320, or the whole client if smaller. +- The panel's size and place are remembered as fractions of the game window in + `\RynthCore\WebPanel\layout.json`, shared by all profiles. A valid stored layout wins over + `WidthPercent` / `HeightPercent`. +- **The panel never takes focus from another program.** On Open it takes the foreground only if the foreground + window already belongs to the game's process; if the player is in another program (or mid alt-tab) it does not. + It hides while another program is in the foreground, and comes back when the game is. The panel's own + WebView2 dialogs (alert, file picker) do not count as another program. +- The panel runs on its own thread, so a slow page never stalls the game's thread or the plugin pump. + +The panel closes (status `Closed`) when: + +- the plugin calls `CloseWebPanel(handle)`; +- the player presses Escape (unless `PageKeepsEscape` is set), clicks the `X`, or presses Alt+F4 on the panel; +- the game window goes away; +- `/rc webpanel close` runs; +- a newer `OpenWebPanel` replaces it (the old handle then reads `Superseded`). + +Closing hides the panel and loads `about:blank`; the WebView2 environment stays for the next Open. `CloseWebPanel` +returns `1` (queued) for the live panel, `0` if it is already `Closed` or `Failed`, and `-6` for any other handle. +After `Closed` or `Failed`, `NavigateWebPanel` returns `StaleHandle`. +At engine shutdown the panel is torn down after the plugins' own Shutdown, so a plugin may still call Close there. + +## Failures + +The state is `Failed`, with `Error` set, and the panel is hidden. + +- `RuntimeMissing` / `CreateFailed`: the panel could not start. With `FallbackToBrowser`, and only if no navigation + has happened yet and the URL is absolute `http` or `https`, the engine opens the URL in the system browser, sets + `OpenedInBrowser`, and tells the player in chat. The plugin must not open it a second time. +- `ProcessFailed`: the engine fails the panel for only these causes: the WebView2 browser process exited + (`BrowserProcessExited`), the page's main renderer exited (`RenderProcessExited`), or the renderer is reported + unresponsive (`RenderProcessUnresponsive`) 3 times within 30 seconds of the first report (a completed + navigation or a new Open resets that count). Every other kind of process failure (GPU, utility, a + frame-only renderer, and so on) is logged and the panel is kept. There is never a browser fallback for + `ProcessFailed`: a navigation already ran, so the launch code is spent. Open again to retry; WebView2 is + recreated. + +## Plugins that must run on older cores + +A plugin built against this SDK runs against the installed core's `Runtime\PluginShared` copy of the SDK. If you want +the plugin to keep working on a core without the web panel, with ShellExecute as the fallback: + +1. **Declare `RynthPluginMinEngineApi` at the plugin's true minimum.** In release builds + (`-p:RynthPluginSharedSdk=true`, as `Publish-Update.ps1` and `Build-Installer.ps1` pass), a declared minimum + *below 88* is raised to the API of the SDK the plugin was built with (93 now), and the launcher then holds the + plugin back from older cores, which kills the fallback (`RynthCore.PluginSdk.targets`: `RynthCoreManagedPluginApi` + is 88). There is no separate opt-out property: declaring a minimum of **88 or higher** is the opt-out, and a + declared 88 or higher is used as it is. Declare the lowest API your plugin really needs at load, and make + sure every call newer than that sits behind its `Has*` check. (`RynthPluginManifest=false` drops the manifest + altogether, and with it the minimum; do not use it for this.) The build prints a message when it raises a minimum. +2. **Put every reference to `HasWebPanel`, `OpenWebPanel`, `WebPanelOptions` and the other WebPanel types in one helper + marked `[MethodImpl(MethodImplOptions.NoInlining)]`, taking only strings,** and call it inside + `try { } catch (MissingMethodException) { } catch (TypeLoadException) { }`. An older `PluginShared` SDK without + these members fails the method (or the type load), not the plugin's load. +3. **Fall back to ShellExecute** when the helper throws, when `HasWebPanel` is false, or when `OpenWebPanel` returns + `Unavailable`, `NoGameWindow` or `ShuttingDown`. Do nothing more when the state is `Failed` with `OpenedInBrowser` + (the engine already opened it). Never fall back on `UrlNotAllowed` (or `BadArgs`): those are plugin bugs, and + sending the URL to the browser hides them. Only pass absolute `http` or `https` URLs without user info to ShellExecute. + +```csharp +using System.Runtime.CompilerServices; +using RynthCore.PluginSdk; + +// Returns false when the caller should open the page in the system browser itself. +private bool TryShowPanel(string url, string profileKey) +{ + try { return ShowPanelCore(url, profileKey); } + catch (MissingMethodException) { return false; } + catch (TypeLoadException) { return false; } +} + +[MethodImpl(MethodImplOptions.NoInlining)] +private bool ShowPanelCore(string url, string profileKey) +{ + if (!Host.HasWebPanel) return false; + int h = Host.OpenWebPanel(new WebPanelOptions + { + Url = url, + Allowlist = new[] { "example.com", "*.example.com" }, + ProfileKey = profileKey, + Title = "Example", + }); + if (h > 0) { _panelHandle = h; return true; } + var r = (WebPanelResult)h; + return !(r == WebPanelResult.Unavailable || r == WebPanelResult.NoGameWindow || r == WebPanelResult.ShuttingDown); +} +``` + +Poll the state from a second helper written the same way (`GetWebPanelState` and `WebPanelState` are SDK types too). + +## Native layout (for callers that do not use the SDK wrappers) + +`RynthCoreAPI` gains four function pointers at the end of the table, in this order, all `cdecl`: +`int WebPanelOpen(WebPanelOpenNative*)`, `int WebPanelNavigate(int handle, byte* url)`, +`int WebPanelClose(int handle)`, `int WebPanelGetState(int handle, WebPanelStateNative*)`. +Test `Version >= 93` before reading them: an older engine's table is shorter. + +`WebPanelOpenNative` (pack 4, 48 bytes on x86): `uint Size`, `uint Flags`, `byte* Url`, `byte* Allowlist` +(`\n`-separated), `byte* ProfileKey` (may be null), `byte* Title` (may be null), `int WidthPercent`, `int HeightPercent`, +`uint Reserved[4]`. All strings are NUL-terminated UTF-8; the engine copies them before the call returns. It accepts +`Size` of 32 or more. + +`WebPanelStateNative` (pack 4, 48 bytes): `uint Size`, `int Handle`, `int Status`, `uint Flags`, `int Error`, +`int LastHttpStatus`, `uint NavigationCount`, `uint Reserved[5]`. The engine accepts `Size` of 28 or more and writes +only the fields before `Reserved`. At the native level `WebPanelGetState` returns the status (a handle that is not the +live panel reads 6) or a negative code (`-1` bad arguments, `-5` shutting down); the wrapper turns a negative into `None`. + +## /rc webpanel + +- `/rc webpanel` or `/rc webpanel status`: one line, redacted (no query, fragment or user info): thread state, + handle, status, error, HTTP status, navigation count, WebView2 environments created, visible / focused / in browser, + the WebView2 browser process id, the URL as `scheme://host/path`, whether the `engine.json` setting is on, and the + free address space. It never opens a URL. +- `/rc webpanel close`: closes the live panel. Replies `web panel: closing.`, `web panel: already closed.`, or + `web panel: nothing to close.` when no panel was ever opened. + +## Offline harness + +`tools\WebPanelHarness` runs the real panel host in a 32-bit stand-in for the game, with a fake game window, a fake +plugin pump and a collectible load context like the engine's. Pages are served from local folders through +virtual hosts (`panel.test`, `other.test`), so it needs no network. + +``` +cd tools\WebPanelHarness +dotnet run -c Release +``` + +Prerequisites: + +- A desktop session (it opens windows) and the Evergreen WebView2 runtime. +- A **32-bit dotnet host**: the x86 .NET 10 runtime (the x86 SDK from `BUILD.md` brings it). The harness + refuses to run unless the process is 32-bit like acclient (`FAIL Bitness`). +- `--foreground` (or `WEBPANEL_HARNESS_FOREGROUND=1`) is an opt-in: the harness then asks Windows to put its fake game + window in the foreground, so the foreground-dependent checks (Escape hands focus back, same-process visibility) + can run. Without the opt-in, or when Windows refuses the request because you are active in another program, + those checks print `UNVERIFIED`. `--payload=` overrides the payload folder. +- It posts input to its own windows only and never uses `SendInput`, so it does not steer a live game client on + the same desktop. It is not part of `scripts\Run-AllTests.ps1`. + +Each check prints `ok `, `FAIL : ...` or `UNVERIFIED : ...` (not provable offline, an owner in-game +check). Exit code 0 = all ok, 1 = a FAIL, 2 = no FAIL but something UNVERIFIED. The output is also written to +`harness-output.txt` under `%TEMP%\rynth-webpanel-harness\\`. \ No newline at end of file -- 2.43.0 From 3f75a9711aa7f4f4a428759887a9d55e2d9da660 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:53:25 -0800 Subject: [PATCH 13/17] Docs: web panel dialogs claim marked unconfirmed Co-Authored-By: Claude Opus 5.5 --- docs/WEB_PANEL.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/WEB_PANEL.md b/docs/WEB_PANEL.md index 10e7acf..ac46fc4 100644 --- a/docs/WEB_PANEL.md +++ b/docs/WEB_PANEL.md @@ -150,7 +150,8 @@ WebView2 environment is reused. - **The panel never takes focus from another program.** On Open it takes the foreground only if the foreground window already belongs to the game's process; if the player is in another program (or mid alt-tab) it does not. It hides while another program is in the foreground, and comes back when the game is. The panel's own - WebView2 dialogs (alert, file picker) do not count as another program. + WebView2 dialogs (alert, file picker) are meant not to count as another program: the engine treats the + WebView2 browser process as its own. Whether those dialogs belong to that process is not yet confirmed in game. - The panel runs on its own thread, so a slow page never stalls the game's thread or the plugin pump. The panel closes (status `Closed`) when: -- 2.43.0 From 537a40a430b327ecdcc9315dcec3562ee1b9fab9 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 16:14:57 -0800 Subject: [PATCH 14/17] WebPanel final-review fix: truthful browser fallback, focus gate, docs - Creation-failure fallback sets OpenedInBrowser and says "opened" only when the system browser actually opened; otherwise chat says the browser did not open. Harness check CreateFailureBrowserFails. - FocusPage follows the same in-process foreground rule as SetForegroundWindow (Show and controller creation). Harness check NoFocusFromAnotherProcess; posted-key checks report UNVERIFIED when another process holds the foreground. - PermissionRequested: SavesInProfile = false. - WEB_PANEL.md: allowlist empty-entry rule, GetState -4, AOT renumber caveat, softened focus claim (also in the Changelog). - Formatting: ChatCommandReplyTests brace, /rc layout comment, PluginContract blank line. Co-Authored-By: Claude Opus 5.5 --- Changelog/2026-11-07-web-panel.md | 4 +- docs/WEB_PANEL.md | 22 ++++-- .../Compatibility/RynthCoreChatCommands.cs | 2 +- src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 28 +++++-- tools/ChatCommandReplyTests/Program.cs | 3 +- tools/WebPanelHarness.Payload/PayloadEntry.cs | 3 + tools/WebPanelHarness/Program.cs | 75 ++++++++++++++++++- 7 files changed, 116 insertions(+), 21 deletions(-) diff --git a/Changelog/2026-11-07-web-panel.md b/Changelog/2026-11-07-web-panel.md index 3d497b2..3a19762 100644 --- a/Changelog/2026-11-07-web-panel.md +++ b/Changelog/2026-11-07-web-panel.md @@ -24,8 +24,8 @@ Branch `up/web-panel`, from upstream `main` 418d80b. Not deployed. The API numbe ## How it behaves -- The panel never takes focus from another program. It takes the foreground only if the foreground window already - belongs to the game, and it hides while another program is in front. +- The panel is designed never to take focus from another program; confirm in game. It takes the foreground (and + page focus) only if the foreground window already belongs to the game, and it hides while another program is in front. - Logs and chat never carry a URL's query, fragment or user info (the launch code rides in the query). - Failures: the panel fails only when the WebView2 browser process or the main renderer exits, or the renderer is reported unresponsive 3 times in 30 s. Other process failures are logged. `RuntimeMissing` / `CreateFailed` fall back to diff --git a/docs/WEB_PANEL.md b/docs/WEB_PANEL.md index ac46fc4..b580ab8 100644 --- a/docs/WEB_PANEL.md +++ b/docs/WEB_PANEL.md @@ -5,7 +5,9 @@ The engine owns the window, the navigation allowlist, focus and the lifetime; th an allowlist and a profile key, then polls for state. This file is the contract plugin authors build against. The API number 93 is provisional: upstream may take 93 first, in which case it renumbers on merge -(`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 93` checks, and nothing breaks. +(`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 93` checks. That keeps a plugin working +across a renumber only for shared-SDK release builds. A NativeAOT plugin build compiles the `Version >= 93` test +in, so a plugin built against the provisional SDK must not be distributed, and must be rebuilt after a renumber. ## Calls @@ -93,7 +95,9 @@ starts itself, and on pop-up requests. Entries are matched against the URL's hos - `*.suffix`: any subdomain, at any depth, but not the suffix itself. `*.example.com` matches `a.example.com` and `a.b.example.com`, and does **not** match `example.com`. To allow both, list both entries. - The suffix after `*.` must contain a dot, so `*.com` is rejected. -- No scheme, path, port or other `*`. Entries are lower-cased and trimmed; blank lines are ignored. +- No scheme, path, port or other `*`. Entries are lower-cased and trimmed. Through the SDK wrapper an empty entry + (or one containing `\n`) is refused with `BadArgs`; at the native level, where the list is one `\n`-separated + string, blank lines are ignored. - Entries are ASCII: letters, digits, `-` and `.`; each label 1 to 63 characters, not starting or ending with `-`; at most 253 characters per entry. Write an internationalised host in its punycode form (`xn--...`). - 1 to 16 entries, and the joined list must fit in 8192 bytes. @@ -147,8 +151,9 @@ WebView2 environment is reused. - The panel's size and place are remembered as fractions of the game window in `\RynthCore\WebPanel\layout.json`, shared by all profiles. A valid stored layout wins over `WidthPercent` / `HeightPercent`. -- **The panel never takes focus from another program.** On Open it takes the foreground only if the foreground - window already belongs to the game's process; if the player is in another program (or mid alt-tab) it does not. +- **The panel is designed never to take focus from another program; confirm in game.** On Open it takes the + foreground, and moves keyboard focus into the page, only if the foreground window already belongs to the game's + process; if the player is in another program (or mid alt-tab) it does neither. It hides while another program is in the foreground, and comes back when the game is. The panel's own WebView2 dialogs (alert, file picker) are meant not to count as another program: the engine treats the WebView2 browser process as its own. Whether those dialogs belong to that process is not yet confirmed in game. @@ -172,8 +177,10 @@ At engine shutdown the panel is torn down after the plugins' own Shutdown, so a The state is `Failed`, with `Error` set, and the panel is hidden. - `RuntimeMissing` / `CreateFailed`: the panel could not start. With `FallbackToBrowser`, and only if no navigation - has happened yet and the URL is absolute `http` or `https`, the engine opens the URL in the system browser, sets - `OpenedInBrowser`, and tells the player in chat. The plugin must not open it a second time. + has happened yet and the URL is absolute `http` or `https`, the engine tries to open the URL in the system browser. + Only if the browser opens does it set `OpenedInBrowser` and tell the player the page opened there; the plugin + must not open it a second time. If the browser does not open, `OpenedInBrowser` stays clear and chat says + `[RynthCore] The in-game browser could not start (), and your web browser did not open.` - `ProcessFailed`: the engine fails the panel for only these causes: the WebView2 browser process exited (`BrowserProcessExited`), the page's main renderer exited (`RenderProcessExited`), or the renderer is reported unresponsive (`RenderProcessUnresponsive`) 3 times within 30 seconds of the first report (a completed @@ -250,7 +257,8 @@ Test `Version >= 93` before reading them: an older engine's table is shorter. `WebPanelStateNative` (pack 4, 48 bytes): `uint Size`, `int Handle`, `int Status`, `uint Flags`, `int Error`, `int LastHttpStatus`, `uint NavigationCount`, `uint Reserved[5]`. The engine accepts `Size` of 28 or more and writes only the fields before `Reserved`. At the native level `WebPanelGetState` returns the status (a handle that is not the -live panel reads 6) or a negative code (`-1` bad arguments, `-5` shutting down); the wrapper turns a negative into `None`. +live panel reads 6) or a negative code (`-1` bad arguments, `-4` unavailable: an internal exception, or an engine +build without the panel, `-5` shutting down); the wrapper turns a negative into `None`. ## /rc webpanel diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index b627033..cc52473 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -653,7 +653,6 @@ internal static class RynthCoreChatCommands SenseLayoutCommand(senseArgs); // alone, /rc sense opens or closes the panel (the switch below) return; } - // /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout). // /rc webpanel [status|close]: diagnostics for the in-game web panel. It never opens a URL // (an arbitrary-URL command would be a phishing vector); every URL in the line is redacted. if (IsVerb(sub, "webpanel", out string webPanelArgs)) @@ -661,6 +660,7 @@ internal static class RynthCoreChatCommands HandleWebPanelCommand(webPanelArgs); return; } + // /rc layout [status] | default | reset [confirm]: this client's panel layout (UI/PanelLayout). if (IsVerb(sub, "layout", out string layoutArgs)) { HandleLayoutCommand(layoutArgs); diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs index c636896..01a77dc 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -619,7 +619,7 @@ internal sealed unsafe class WebPanelHost { _ctl.IsVisible = true; NavigatePending(_serving); - FocusPage(); + if (ForegroundIsThisProcess()) FocusPage(); // the rule Show uses: never focus from another program } else { @@ -770,6 +770,8 @@ internal sealed unsafe class WebPanelHost state = CoreWebView2PermissionState.Allow; } catch { state = CoreWebView2PermissionState.Deny; } + // Never remember a decision in the profile: an Allow must not outlive an allowlist change. + try { e.SavesInProfile = false; } catch { } e.State = state; } @@ -861,7 +863,6 @@ internal sealed unsafe class WebPanelHost { fallback = true; url = r.Url; - _flags |= StateOpenedInBrowser; } } } @@ -871,9 +872,13 @@ internal sealed unsafe class WebPanelHost if (!fallback) return; bool ok = false; try { ok = _env.OpenInBrowser(url); } catch { } + // The flag reports what happened, so it is set only once the browser opened, and only for the panel that failed. + if (ok) lock (_sync) if (handle == _live) _flags |= StateOpenedInBrowser; SafeLog((ok ? "fallback: opened in the system browser: " : "fallback: the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); string why = code == WebPanelCode.RuntimeMissing ? "WebView2 runtime not installed" : "it failed to start"; - SafeChat("[RynthCore] The in-game browser could not start (" + why + "); opened the page in your web browser."); + SafeChat(ok + ? "[RynthCore] The in-game browser could not start (" + why + "); opened the page in your web browser." + : "[RynthCore] The in-game browser could not start (" + why + "), and your web browser did not open."); } private void Show() @@ -885,16 +890,23 @@ internal sealed unsafe class WebPanelHost // Never while the foreground is null (mid alt-tab): that would grab focus on the way to another program. // Only this process: a foreground in the WebView2 browser process is the page's own dialog, which keeps // it (IsOurPid, which includes the browser, is for the visibility rule only). - IntPtr fg = GetForegroundWindow(); - uint fgPid = 0; - if (fg != IntPtr.Zero) GetWindowThreadProcessId(fg, out fgPid); - if (fg != IntPtr.Zero && fgPid == _ourPid) SetForegroundWindow(_staHwnd); + bool inProcess = ForegroundIsThisProcess(); + if (inProcess) SetForegroundWindow(_staHwnd); if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } - FocusPage(); + if (inProcess) FocusPage(); // same rule: moving WebView2 focus can activate the host window if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } UpdateStateFlags(); } + /// The foreground is a window of this process (not null, not another program, not the browser process). + private bool ForegroundIsThisProcess() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return false; + GetWindowThreadProcessId(fg, out uint fgPid); + return fgPid == _ourPid; + } + private void FocusPage() { try { _ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); } catch { } diff --git a/tools/ChatCommandReplyTests/Program.cs b/tools/ChatCommandReplyTests/Program.cs index 6b43a73..627ec4f 100644 --- a/tools/ChatCommandReplyTests/Program.cs +++ b/tools/ChatCommandReplyTests/Program.cs @@ -356,7 +356,8 @@ internal static class Program Check(!Regex.IsMatch(wp, @"\bNavigate\("), "HandleWebPanelCommand has no Navigate("); Check(!wp.Contains("ShellExecute", StringComparison.Ordinal), "HandleWebPanelCommand has no ShellExecute"); Check(wp.Contains("WebPanelApi.Close(", StringComparison.Ordinal), "the scan reads the real body (it calls WebPanelApi.Close)"); - } } + } + } private static string? FindRepoFile(string relative) { diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs index d270cae..eb20ef9 100644 --- a/tools/WebPanelHarness.Payload/PayloadEntry.cs +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -24,6 +24,7 @@ public static unsafe class PayloadEntry public static void SetEnvironmentDelay(int ms) => _env!.DelayMs = ms; public static void SetBrowserFolder(string? folder) => _env!.BrowserFolder = folder; + public static void SetBrowserFails(bool fails) => _env!.BrowserFails = fails; public static void SetWorld(string world) => _env!.World = world; /// The engine's WebPanelApi.Open path: read the caller's struct, then the host. @@ -109,6 +110,7 @@ public static unsafe class PayloadEntry public volatile int DelayMs; public volatile string? BrowserFolder; + public volatile bool BrowserFails; // OpenInBrowser returns false without recording a call public volatile string World = "Harness World"; public IntPtr GameHwnd { get; } @@ -120,6 +122,7 @@ public static unsafe class PayloadEntry public bool OpenInBrowser(string url) { if (!WebPanelUrlPolicy.IsBrowserSafe(url)) { _log("HARNESS: OpenInBrowser got an unsafe url"); return false; } + if (BrowserFails) { _log("HARNESS: OpenInBrowser set to fail"); return false; } _browser(url); return true; } diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs index edc372c..df2e54d 100644 --- a/tools/WebPanelHarness/Program.cs +++ b/tools/WebPanelHarness/Program.cs @@ -107,6 +107,8 @@ internal static unsafe class Program Guard("LateFailureForSupersededHandle", () => handle = CheckLateFailure(s)); Guard("UnresponsiveCountResetsPerOpen", () => handle = CheckUnresponsiveReset(s)); Guard("CreateFailureFallsBack", () => CheckCreateFailure(s)); + Guard("CreateFailureBrowserFails", () => CheckCreateFailureBrowserFails(s)); + Guard("NoFocusFromAnotherProcess", () => { int r = CheckNoFocusFromAnotherProcess(s); if (r > 0) handle = r; }); 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."); Guard("LayoutRemembered", () => handle = CheckLayout(s, lad)); @@ -201,8 +203,21 @@ internal static unsafe class Program return h; } + /// + /// The host moves keyboard focus into the page only while this process holds the foreground (never from + /// another program), so the posted-key checks are meaningful only then. + /// + private static bool ThisProcessHoldsForeground() + { + IntPtr fg = GetForegroundWindow(); + if (fg == IntPtr.Zero) return false; + GetWindowThreadProcessId(fg, out uint pid); + return pid == Environment.ProcessId; + } + private static int CheckKeys(Session s) { + bool inProcess = ThisProcessHoldsForeground(); var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keys"); if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("KeysStayInPage", $"not Ready [{string.Join(",", a)}]"); return h; } Thread.Sleep(500); @@ -221,8 +236,9 @@ internal static unsafe class Program // 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 Ok("KeysStayInPage"); + if (value.Contains("x1q")) Ok("KeysStayInPage"); + else if (!inProcess) Unverified("KeysStayInPage", $"page input is {value}: another process held the foreground at Open ({FgDesc()}), so by design the panel did not focus the page; owner in-game check (type in the panel)"); + else Fail("KeysStayInPage", $"page input is {value}, want x1q"); return h; } @@ -257,6 +273,7 @@ internal static unsafe class Program private static int CheckPageKeepsEscape(Session s) { + bool inProcess = ThisProcessHoldsForeground(); var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Keeps Escape", flags: FlagFallback | FlagPageKeepsEscape); if (!WaitStatus(s, h, StatusReady, 30000, out int[] a)) { Fail("PageKeepsEscapeFlag", $"not Ready [{string.Join(",", a)}]"); return h; } Thread.Sleep(400); @@ -270,6 +287,7 @@ internal static unsafe class Program int[] st = State(s, h); W($"flag 2: page keys {keys}, status {st[2]}, AcceleratorKeyPressed events {acc}"); if (st[2] != StatusReady) Fail("PageKeepsEscapeFlag", $"panel status {st[2]}, want Ready (open)"); + else if (!keys.Contains("Escape") && !inProcess) Unverified("PageKeepsEscapeFlag", $"the page did not see Escape ({keys}): another process held the foreground at Open ({FgDesc()}), so by design the panel did not focus the page; owner in-game check"); else if (!keys.Contains("Escape")) Fail("PageKeepsEscapeFlag", "the page keydown listener did not see Escape: " + keys); else if (acc == 0) Unverified("PageKeepsEscapeFlag", "page saw Escape and stayed open, but AcceleratorKeyPressed never fired for posted input, so the flag path itself was not exercised"); else Ok("PageKeepsEscapeFlag"); @@ -519,6 +537,59 @@ internal static unsafe class Program else Ok("CreateFailureFallsBack"); } + private static void CheckCreateFailureBrowserFails(Session s) + { + Drain(BrowserCalls); + Drain(ChatLines); + s.Call("SetBrowserFolder", Path.Combine(_root, "no-such-browser")); + s.Call("SetBrowserFails", true); + int[] st; + bool failed; + try + { + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); + failed = WaitStatus(s, h, StatusFailed, 20000, out st); + WaitFor(() => ChatLines.Any(c => c.Contains("could not start")), 3000); + } + finally { s.Call("SetBrowserFails", false); s.Call("SetBrowserFolder", (string?)null); } + string[] chat = ChatLines.ToArray(); + W($"create failure, browser fails: state [{string.Join(",", st)}]; browser calls {BrowserCalls.Count}; chat: {string.Join(" | ", chat)}"); + if (!failed) Fail("CreateFailureBrowserFails", "status " + st[2]); + else if (st[4] != CodeCreateFailed) Fail("CreateFailureBrowserFails", "error " + st[4] + ", want CreateFailed"); + else if ((st[3] & StateOpenedInBrowser) != 0) Fail("CreateFailureBrowserFails", "OpenedInBrowser flag set although the browser did not open"); + else if (chat.Any(c => c.Contains("opened the page"))) Fail("CreateFailureBrowserFails", "chat claims the page opened"); + else if (!chat.Any(c => c.Contains("could not start (it failed to start), and your web browser did not open"))) Fail("CreateFailureBrowserFails", "no browser-did-not-open chat line"); + else Ok("CreateFailureBrowserFails"); + } + + /// + /// Only when the foreground already belongs to another process (the harness never arranges it): opening a + /// panel must leave that process in front. When this harness holds the foreground the check is UNVERIFIED. + /// + private static int CheckNoFocusFromAnotherProcess(Session s) + { + IntPtr fg0 = GetForegroundWindow(); + uint pid0 = 0; + if (fg0 != IntPtr.Zero) GetWindowThreadProcessId(fg0, out pid0); + int bpid = (int)s.Call("get_BrowserProcessId")!; + if (fg0 == IntPtr.Zero || pid0 == Environment.ProcessId || (bpid != 0 && pid0 == bpid)) + { + Unverified("NoFocusFromAnotherProcess", $"the foreground is not another process ({FgDesc()}); the harness never forces it there. Owner in-game check (alt-tab away, open the panel from a plugin)"); + return 0; + } + var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "No focus"); + bool ready = WaitStatus(s, h, StatusReady, 30000, out int[] st); + Thread.Sleep(500); + IntPtr fg1 = GetForegroundWindow(); + uint pid1 = 0; + if (fg1 != IntPtr.Zero) GetWindowThreadProcessId(fg1, out pid1); + W($"foreground before pid {pid0}, after open pid {pid1} ({FgDesc()}); state [{string.Join(",", st)}]"); + if (!ready) Fail("NoFocusFromAnotherProcess", "not Ready"); + else if (pid1 == Environment.ProcessId || (bpid != 0 && pid1 == bpid)) Fail("NoFocusFromAnotherProcess", "the panel took the foreground from another process"); + else Ok("NoFocusFromAnotherProcess"); + return h; + } + private static int CheckVisibilitySameProcess(Session s) { var (h, _) = Open(s, "https://panel.test/index.html", Allow, title: "Visibility"); -- 2.43.0 From 7e2cf67e3014da9bba79b7633472c5e7e0c59021 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 16:22:33 -0800 Subject: [PATCH 15/17] WebPanel: publish Failed together with the browser-fallback outcome A plugin polling between Failed and OpenedInBrowser saw Failed with no flag and, per the docs, opened the page itself: a second open with a spent code. While the fallback is pending the status keeps its pre-failure value; after OpenInBrowser (outside the lock) one lock sets Failed, the error and, when the browser opened, the flag. The no-fallback path is unchanged. Harness: OpenInBrowser delay mode and a continuous poll in CreateFailureFallsBack. Show comments reworded as defensive, not observed. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/WebPanel/WebPanelHost.cs | 29 ++++++++++++++----- tools/WebPanelHarness.Payload/PayloadEntry.cs | 3 ++ tools/WebPanelHarness/Program.cs | 28 +++++++++++++++--- 3 files changed, 49 insertions(+), 11 deletions(-) diff --git a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs index 01a77dc..052f00d 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelHost.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelHost.cs @@ -855,15 +855,20 @@ internal sealed unsafe class WebPanelHost } else { - _status = (int)WebPanelStatusCode.Failed; - _error = (int)code; WebPanelRequest? r = _req; if (allowFallback && r != null && (code == WebPanelCode.RuntimeMissing || code == WebPanelCode.CreateFailed) && (r.Flags & FlagFallback) != 0 && _navCount == 0 && WebPanelUrlPolicy.IsBrowserSafe(r.Url)) { + // Failed is published only together with the fallback's outcome (below): a plugin polling in + // between must never see Failed without OpenedInBrowser and open the page a second time. fallback = true; url = r.Url; } + else + { + _status = (int)WebPanelStatusCode.Failed; + _error = (int)code; + } } } if (ignored) { SafeLog($"panel failure after close or supersede, panel left as it is: {code} ({reason})"); return; } @@ -872,8 +877,17 @@ internal sealed unsafe class WebPanelHost if (!fallback) return; bool ok = false; try { ok = _env.OpenInBrowser(url); } catch { } - // The flag reports what happened, so it is set only once the browser opened, and only for the panel that failed. - if (ok) lock (_sync) if (handle == _live) _flags |= StateOpenedInBrowser; + // One lock: Failed, the error and (only when the browser opened) the flag become visible together, and only + // for the panel that failed; a Close or a newer Open in the meantime wins. + lock (_sync) + { + if (handle == _live && _status != (int)WebPanelStatusCode.Closed) + { + _status = (int)WebPanelStatusCode.Failed; + _error = (int)code; + if (ok) _flags |= StateOpenedInBrowser; + } + } SafeLog((ok ? "fallback: opened in the system browser: " : "fallback: the system browser did not open: ") + WebPanelUrlPolicy.Redact(url)); string why = code == WebPanelCode.RuntimeMissing ? "WebView2 runtime not installed" : "it failed to start"; SafeChat(ok @@ -888,12 +902,13 @@ internal sealed unsafe class WebPanelHost // 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. - // Only this process: a foreground in the WebView2 browser process is the page's own dialog, which keeps - // it (IsOurPid, which includes the browser, is for the visibility rule only). + // Only this process, defensively: a foreground in the WebView2 browser process is assumed (not observed) to + // be the page's own dialog, which should keep it (IsOurPid, which includes the browser, is for the + // visibility rule only). bool inProcess = ForegroundIsThisProcess(); if (inProcess) SetForegroundWindow(_staHwnd); if (_ctl != null) { try { _ctl.IsVisible = true; } catch { } } - if (inProcess) FocusPage(); // same rule: moving WebView2 focus can activate the host window + if (inProcess) FocusPage(); // same rule, defensively: moving WebView2 focus might activate the host window (not observed) if (!_timerOn) { SetTimer(_staHwnd, TimerId, 50, IntPtr.Zero); _timerOn = true; } UpdateStateFlags(); } diff --git a/tools/WebPanelHarness.Payload/PayloadEntry.cs b/tools/WebPanelHarness.Payload/PayloadEntry.cs index eb20ef9..bf24cf9 100644 --- a/tools/WebPanelHarness.Payload/PayloadEntry.cs +++ b/tools/WebPanelHarness.Payload/PayloadEntry.cs @@ -25,6 +25,7 @@ public static unsafe class PayloadEntry public static void SetEnvironmentDelay(int ms) => _env!.DelayMs = ms; public static void SetBrowserFolder(string? folder) => _env!.BrowserFolder = folder; public static void SetBrowserFails(bool fails) => _env!.BrowserFails = fails; + public static void SetBrowserDelay(int ms) => _env!.BrowserDelayMs = ms; public static void SetWorld(string world) => _env!.World = world; /// The engine's WebPanelApi.Open path: read the caller's struct, then the host. @@ -111,6 +112,7 @@ public static unsafe class PayloadEntry public volatile int DelayMs; public volatile string? BrowserFolder; public volatile bool BrowserFails; // OpenInBrowser returns false without recording a call + public volatile int BrowserDelayMs; // OpenInBrowser sleeps first (a slow ShellExecute) public volatile string World = "Harness World"; public IntPtr GameHwnd { get; } @@ -122,6 +124,7 @@ public static unsafe class PayloadEntry public bool OpenInBrowser(string url) { if (!WebPanelUrlPolicy.IsBrowserSafe(url)) { _log("HARNESS: OpenInBrowser got an unsafe url"); return false; } + if (BrowserDelayMs > 0) Thread.Sleep(BrowserDelayMs); if (BrowserFails) { _log("HARNESS: OpenInBrowser set to fail"); return false; } _browser(url); return true; diff --git a/tools/WebPanelHarness/Program.cs b/tools/WebPanelHarness/Program.cs index df2e54d..a50be4f 100644 --- a/tools/WebPanelHarness/Program.cs +++ b/tools/WebPanelHarness/Program.cs @@ -524,12 +524,32 @@ internal static unsafe class Program Drain(BrowserCalls); Drain(ChatLines); s.Call("SetBrowserFolder", Path.Combine(_root, "no-such-browser")); - var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); - bool failed = WaitStatus(s, h, StatusFailed, 20000, out int[] st); - s.Call("SetBrowserFolder", (string?)null); + s.Call("SetBrowserDelay", 300); // a slow browser launch widens any Failed-before-flag window + int samples = 0, failedNoFlag = 0; + bool failed = false; + int[] st; + try + { + var (h, _) = Open(s, "https://panel.test/launch.html?code=" + Secret, Allow, key: "beta"); + // Poll continuously: a plugin that sees Failed without OpenedInBrowser would open the page a second time. + var sw = Stopwatch.StartNew(); + st = State(s, h); + while (sw.ElapsedMilliseconds < 20000) + { + st = State(s, h); + samples++; + if (st[2] == StatusFailed && (st[3] & StateOpenedInBrowser) == 0) failedNoFlag++; + if (st[2] == StatusFailed && (st[3] & StateOpenedInBrowser) != 0) { failed = true; break; } + if (st[2] == StatusFailed && failedNoFlag > 400) break; // the flag is not coming + Thread.Sleep(1); + } + if (!failed) failed = st[2] == StatusFailed; + } + finally { s.Call("SetBrowserDelay", 0); s.Call("SetBrowserFolder", (string?)null); } string[] calls = BrowserCalls.ToArray(); - W($"forced create failure: state [{string.Join(",", st)}]; browser calls {calls.Length}; chat: {string.Join(" | ", ChatLines)}"); + W($"forced create failure: state [{string.Join(",", st)}]; {samples} samples, {failedNoFlag} showed Failed without OpenedInBrowser; browser calls {calls.Length}; chat: {string.Join(" | ", ChatLines)}"); if (!failed) Fail("CreateFailureFallsBack", "status " + st[2]); + else if (failedNoFlag > 0) Fail("CreateFailureFallsBack", $"{failedNoFlag} of {samples} samples showed Failed without OpenedInBrowser (a polling plugin would open the page twice)"); else if (st[4] != CodeCreateFailed) Fail("CreateFailureFallsBack", "error " + st[4] + ", want CreateFailed"); else if ((st[3] & StateOpenedInBrowser) == 0) Fail("CreateFailureFallsBack", "OpenedInBrowser flag not set"); else if (calls.Length != 1 || Redact(calls[0]) != "https://panel.test/launch.html") Fail("CreateFailureFallsBack", $"{calls.Length} browser call(s)"); -- 2.43.0 From 6edc196270d10ce6ce9cfe34e61ca0762ccdf7b2 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 16:23:03 -0800 Subject: [PATCH 16/17] Docs: Failed and OpenedInBrowser appear together Co-Authored-By: Claude Opus 5.5 --- docs/WEB_PANEL.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/WEB_PANEL.md b/docs/WEB_PANEL.md index b580ab8..9df09e4 100644 --- a/docs/WEB_PANEL.md +++ b/docs/WEB_PANEL.md @@ -181,6 +181,8 @@ The state is `Failed`, with `Error` set, and the panel is hidden. Only if the browser opens does it set `OpenedInBrowser` and tell the player the page opened there; the plugin must not open it a second time. If the browser does not open, `OpenedInBrowser` stays clear and chat says `[RynthCore] The in-game browser could not start (), and your web browser did not open.` + The status stays at its earlier value while the browser launches; `Failed`, the error and `OpenedInBrowser` + then appear together, so a poll never sees `Failed` before the engine has decided. - `ProcessFailed`: the engine fails the panel for only these causes: the WebView2 browser process exited (`BrowserProcessExited`), the page's main renderer exited (`RenderProcessExited`), or the renderer is reported unresponsive (`RenderProcessUnresponsive`) 3 times within 30 seconds of the first report (a completed -- 2.43.0 From 2225b90b2c21a0bed8d2e283794168b95a0ce392 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 13:13:05 -0800 Subject: [PATCH 17/17] Plugin API v94: renumber the web panel after upstream's v93 Upstream release 2026.11.8.1 took v93 for GetMonsterHealth. The web panel's four slots now follow GetMonsterHealthFn in the engine table and the SDK's RynthCoreApiNative, and the web panel is v94: PluginContractVersion.Current, RynthCoreSdkApiVersion, HasWebPanel (Version >= 94), the comments, docs/WEB_PANEL.md, the changelog and PluginManifestTests (HasWebPanel version cases, slot names). Still provisional: unmerged upstream branches also use 94. Co-Authored-By: Claude Opus 5.5 --- Changelog/2026-11-07-web-panel.md | 9 +++-- docs/WEB_PANEL.md | 14 +++---- .../Plugins/EngineSettings.cs | 4 +- .../Plugins/PluginContract.cs | 20 +++++----- .../Plugins/PluginContractVersion.cs | 9 +++-- src/RynthCore.Engine/Plugins/PluginManager.cs | 10 ++--- src/RynthCore.Engine/RynthCore.Engine.csproj | 2 +- src/RynthCore.Engine/WebPanel/WebPanelApi.cs | 4 +- .../WebPanel/WebPanelApiRules.cs | 2 +- .../WebPanel/WebPanelNativeArgs.cs | 2 +- src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 2 +- src/RynthCore.PluginSdk/RynthCoreHost.cs | 16 ++++---- src/RynthCore.PluginSdk/WebPanelTypes.cs | 6 +-- .../build/RynthCore.PluginSdk.targets | 2 +- tools/EngineSettingsTests/Program.cs | 2 +- tools/PluginManifestTests/Program.cs | 38 +++++++++---------- 16 files changed, 72 insertions(+), 70 deletions(-) diff --git a/Changelog/2026-11-07-web-panel.md b/Changelog/2026-11-07-web-panel.md index 3a19762..8f1ba86 100644 --- a/Changelog/2026-11-07-web-panel.md +++ b/Changelog/2026-11-07-web-panel.md @@ -1,7 +1,8 @@ -# In-game web panel: plugin API v93 +# In-game web panel: plugin API v94 -Branch `up/web-panel`, from upstream `main` 418d80b. Not deployed. The API number 93 is provisional -(upstream may take 93 first; it renumbers on merge). CoreCLR engine only. +Branch `pr/web-panel`, from upstream `main` c68204f (release 2026.11.8.1). Not deployed. The API number 94 +follows upstream's v93 (GetMonsterHealth) and is provisional (unmerged upstream branches also use 94; whichever +merges second renumbers). CoreCLR engine only. ## What changed @@ -18,7 +19,7 @@ Branch `up/web-panel`, from upstream `main` 418d80b. Not deployed. The API numbe - `/rc webpanel [status|close]`: a redacted one-line report, and a close. - `engine.json` `"WebPanel": false`: kill switch. `OpenWebPanel` then answers `Unavailable`. - `RynthCore.PluginSdk.targets` already raised a shared-SDK release build's `RynthPluginMinEngineApi` below 88 to the - SDK's API; that is now 93 for every such plugin. Plugins that must run on older cores declare 88 or higher. + SDK's API; that is now 94 for every such plugin. Plugins that must run on older cores declare 88 or higher. - `tools\WebPanelHarness`: an offline 32-bit harness for the host (see the doc). - Docs: `docs/WEB_PANEL.md` is the plugin contract. diff --git a/docs/WEB_PANEL.md b/docs/WEB_PANEL.md index 9df09e4..ed1634d 100644 --- a/docs/WEB_PANEL.md +++ b/docs/WEB_PANEL.md @@ -1,12 +1,12 @@ -# In-game web panel (plugin API v93) +# In-game web panel (plugin API v94) A plugin can show a web page in a panel over the Asheron's Call window. The page runs in WebView2. The engine owns the window, the navigation allowlist, focus and the lifetime; the plugin passes a URL, an allowlist and a profile key, then polls for state. This file is the contract plugin authors build against. -The API number 93 is provisional: upstream may take 93 first, in which case it renumbers on merge -(`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 93` checks. That keeps a plugin working -across a renumber only for shared-SDK release builds. A NativeAOT plugin build compiles the `Version >= 93` test +The API number 94 is provisional: unmerged upstream branches also use 94, and whichever merges second +renumbers (`PluginContractVersion.cs`). Write `HasWebPanel` checks, not `Version >= 94` checks. That keeps a plugin working +across a renumber only for shared-SDK release builds. A NativeAOT plugin build compiles the `Version >= 94` test in, so a plugin built against the provisional SDK must not be distributed, and must be rebuilt after a renumber. ## Calls @@ -17,7 +17,7 @@ to call from any thread (AC's main thread, the plugin pump, an ImGui draw). Neve | Call | Does | |---|---| -| `bool HasWebPanel` | True only on an engine at API 93 or newer that fills all four function slots. Check it before any other call. | +| `bool HasWebPanel` | True only on an engine at API 94 or newer that fills all four function slots. Check it before any other call. | | `int OpenWebPanel(WebPanelOptions)` | Opens the panel, or replaces the open one. Returns a handle > 0, or a negative `WebPanelResult`. | | `int NavigateWebPanel(int handle, string url)` | Points the open panel at a URL. `1` queued. | | `int CloseWebPanel(int handle)` | Closes the panel. `1` queued, `0` already closed. | @@ -198,7 +198,7 @@ the plugin to keep working on a core without the web panel, with ShellExecute as 1. **Declare `RynthPluginMinEngineApi` at the plugin's true minimum.** In release builds (`-p:RynthPluginSharedSdk=true`, as `Publish-Update.ps1` and `Build-Installer.ps1` pass), a declared minimum - *below 88* is raised to the API of the SDK the plugin was built with (93 now), and the launcher then holds the + *below 88* is raised to the API of the SDK the plugin was built with (94 now), and the launcher then holds the plugin back from older cores, which kills the fallback (`RynthCore.PluginSdk.targets`: `RynthCoreManagedPluginApi` is 88). There is no separate opt-out property: declaring a minimum of **88 or higher** is the opt-out, and a declared 88 or higher is used as it is. Declare the lowest API your plugin really needs at load, and make @@ -249,7 +249,7 @@ Poll the state from a second helper written the same way (`GetWebPanelState` and `RynthCoreAPI` gains four function pointers at the end of the table, in this order, all `cdecl`: `int WebPanelOpen(WebPanelOpenNative*)`, `int WebPanelNavigate(int handle, byte* url)`, `int WebPanelClose(int handle)`, `int WebPanelGetState(int handle, WebPanelStateNative*)`. -Test `Version >= 93` before reading them: an older engine's table is shorter. +Test `Version >= 94` before reading them: an older engine's table is shorter. `WebPanelOpenNative` (pack 4, 48 bytes on x86): `uint Size`, `uint Flags`, `byte* Url`, `byte* Allowlist` (`\n`-separated), `byte* ProfileKey` (may be null), `byte* Title` (may be null), `int WidthPercent`, `int HeightPercent`, diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 4044725..f0d9f60 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -70,7 +70,7 @@ internal static class EngineSettings private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode; // "TransitionGate": default true. False = queued game actions are never held for a death / portal. private static bool _transitionGate = true; - // "WebPanel": default true. False = the v93 web panel calls answer Unavailable (plugins open the system browser). + // "WebPanel": default true. False = the v94 web panel calls answer Unavailable (plugins open the system browser). private static bool _webPanel = true; private static bool _loaded; @@ -716,7 +716,7 @@ internal static class EngineSettings } } - /// "WebPanel" in engine.json (default true): the v93 web panel (WebPanel\WebPanelHost.cs, a + /// "WebPanel" in engine.json (default true): the v94 web panel (WebPanel\WebPanelHost.cs, a /// WebView2 window over the game for DreamWeave's market and tools; CoreCLR engine only). False is the /// kill switch: WebPanelOpen answers Unavailable and plugins open the page in the system browser /// instead. A panel already open stays until it is closed. diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 184e460..bb69de1 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -1070,24 +1070,24 @@ internal struct RynthCoreAPI /// Read-only, any thread, no game calls. Requires API v93+. public IntPtr GetMonsterHealthFn; - // ── v93: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ── + // ── v94: a WebView2 web panel over the game window (WebPanel\WebPanelApi.cs) ── // No call blocks its caller (AC's main thread, the plugin pump and ImGui draws all call these). - /// v93: int WebPanelOpen(WebPanelOpenNative* open): opens (or replaces) the web panel. + /// v94: int WebPanelOpen(WebPanelOpenNative* open): opens (or replaces) the web panel. /// Returns a handle > 0, or BadArgs / UrlNotAllowed / NoGameWindow / Unavailable / ShuttingDown - /// (WebPanelCode). Requires API v93+ (provisional number). + /// (WebPanelCode). Requires API v94+ (provisional number). public IntPtr WebPanelOpenFn; - /// v93: int WebPanelNavigate(int handle, byte* url): 1 queued; -2 off the allowlist + /// v94: int WebPanelNavigate(int handle, byte* url): 1 queued; -2 off the allowlist /// (opened in the system browser when it is browser-safe); -6 stale handle. public IntPtr WebPanelNavigateFn; - /// v93: int WebPanelClose(int handle): 1 queued, 0 already closed, -6 stale handle. + /// v94: int WebPanelClose(int handle): 1 queued, 0 already closed, -6 stale handle. public IntPtr WebPanelCloseFn; - /// v93: int WebPanelGetState(int handle, WebPanelStateNative* state): the WebPanelStatusCode + /// v94: int WebPanelGetState(int handle, WebPanelStateNative* state): the WebPanelStatusCode /// (a handle that is not the live one reads 6 Superseded), -1 bad args. public IntPtr WebPanelGetStateFn; } -/// v93 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +/// v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. [StructLayout(LayoutKind.Sequential, Pack = 4)] internal unsafe struct WebPanelOpenNative { @@ -1109,7 +1109,7 @@ internal unsafe struct WebPanelOpenNative public fixed uint Reserved[4]; } -/// v93 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. +/// v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors RynthCore.PluginSdk/WebPanelTypes.cs. [StructLayout(LayoutKind.Sequential, Pack = 4)] internal unsafe struct WebPanelStateNative { @@ -1126,14 +1126,14 @@ internal unsafe struct WebPanelStateNative public fixed uint Reserved[5]; } -/// v93 return codes of the web panel calls. Append only. +/// v94 return codes of the web panel calls. Append only. internal enum WebPanelCode { Queued = 1, AlreadyClosed = 0, BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3, Unavailable = -4, ShuttingDown = -5, StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9, } -/// v93 WebPanelStateNative.Status values. Append only. +/// v94 WebPanelStateNative.Status values. Append only. internal enum WebPanelStatusCode { None = 0, Starting = 1, Loading = 2, Ready = 3, Closed = 4, Failed = 5, Superseded = 6, diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 774d6ba..e89f2d8 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -47,8 +47,9 @@ internal static class PluginContractVersion // any thread (feature/hud-health-for-plugins, 2026-11-07). Note: feature/reload-state, // feature/engine-events and the branches built on them (unmerged) also use 93 and 94; whichever // merges second renumbers. - // v93: WebPanelOpen, WebPanelNavigate, WebPanelClose and WebPanelGetState: a WebView2 web panel over the - // game window (WebPanel\WebPanelApi.cs; DreamWeave's in-game market and tools). The number is - // PROVISIONAL: upstream may take 93 first, in which case this renumbers on merge. - public const uint Current = 93; + // v94: WebPanelOpen, WebPanelNavigate, WebPanelClose and WebPanelGetState: a WebView2 web panel over the + // game window (WebPanel\WebPanelApi.cs; DreamWeave's in-game market and tools), appended after v93's + // GetMonsterHealth (was v93 on up/web-panel; renumbered after upstream's v93). The number is + // PROVISIONAL: the unmerged branches named under v93 also use 94; whichever merges second renumbers. + public const uint Current = 94; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index e12b819..9bd837d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -305,10 +305,10 @@ internal static partial class PluginManager private static GetAmbientLightCallbackDelegate? _getAmbientLightCallback; // v91 private static GetMonsterHealthCallbackDelegate? _getMonsterHealthCallback; // v93 #if ENGINE_CORECLR - private static WebPanelOpenCallbackDelegate? _webPanelOpenCallback; // v93 - private static WebPanelNavigateCallbackDelegate? _webPanelNavigateCallback; // v93 - private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v93 - private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v93 + private static WebPanelOpenCallbackDelegate? _webPanelOpenCallback; // v94 + private static WebPanelNavigateCallbackDelegate? _webPanelNavigateCallback; // v94 + private static WebPanelCloseCallbackDelegate? _webPanelCloseCallback; // v94 + private static WebPanelGetStateCallbackDelegate? _webPanelGetStateCallback; // v94 #endif private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; @@ -3261,7 +3261,7 @@ internal static partial class PluginManager unsafe { _getAmbientLightCallback ??= AmbientLight.Get; } unsafe { _getMonsterHealthCallback ??= GetMonsterHealthAction; } // v93 #if ENGINE_CORECLR - // v93: the AOT engine leaves these slots zero, so HasWebPanel is false there. + // v94: the AOT engine leaves these slots zero, so HasWebPanel is false there. unsafe { _webPanelOpenCallback ??= WebPanel.WebPanelApi.Open; } unsafe { _webPanelNavigateCallback ??= WebPanel.WebPanelApi.Navigate; } _webPanelCloseCallback ??= WebPanel.WebPanelApi.Close; diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index a9dfca5..71a4a3a 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -49,7 +49,7 @@ diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs index 7147313..d9cae83 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelApi.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelApi.cs @@ -4,7 +4,7 @@ namespace RynthCore.Engine.WebPanel; #if ENGINE_CORECLR /// -/// The engine side of the v93 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn): reads +/// The engine side of the v94 web panel calls (PluginContract.cs WebPanelOpenFn..WebPanelGetStateFn): reads /// the native arguments (every string copied before the call returns) and hands them to the one /// WebPanelHost. No call here blocks its caller (AC's main thread, the plugin pump and ImGui draws all call /// these). engine.json "WebPanel": false makes Open answer Unavailable (plugins fall back to the browser). @@ -128,7 +128,7 @@ internal static unsafe class WebPanelApi } } #else -/// The NativeAOT engine has no web panel: PluginManager leaves the v93 slots zero (HasWebPanel false). +/// The NativeAOT engine has no web panel: PluginManager leaves the v94 slots zero (HasWebPanel false). internal static unsafe class WebPanelApi { internal static int Open(WebPanelOpenNative* open) => (int)WebPanelCode.Unavailable; diff --git a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs index e2d1dd5..db98fca 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelApiRules.cs @@ -6,7 +6,7 @@ namespace RynthCore.Engine.WebPanel; 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 +/// The pure decisions of the v94 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 diff --git a/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs index a2efc38..e319d28 100644 --- a/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs +++ b/src/RynthCore.Engine/WebPanel/WebPanelNativeArgs.cs @@ -8,7 +8,7 @@ namespace RynthCore.Engine.WebPanel; internal sealed record WebPanelRequest(string Url, string[] Allowlist, string ProfileFolder, string Title, int WidthPercent, int HeightPercent, uint Flags); /// -/// Reads the v93 WebPanelOpen argument. The SDK passes pointers into stack or pooled buffers that are gone +/// Reads the v94 WebPanelOpen argument. The SDK passes pointers into stack or pooled buffers that are gone /// the moment the call returns, so every string is copied here, synchronously, before anything is queued. /// Pure: no Win32, no WebView2. /// diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index fc6031d..6d713ad 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -204,7 +204,7 @@ public struct RynthCoreApiNative public IntPtr GetAmbientLightFn; // int GetAmbientLight(uint* client, uint* applied) -> 1 hook live, 0 not // v93: the monster plates' last server health reading per object public IntPtr GetMonsterHealthFn; // int GetMonsterHealth(uint id, float* ratio, uint* ageMs) -> 1 reading, 0 none - // v93: a WebView2 web panel over the game window (APPEND-AT-END (ABI); number provisional) + // v94: a WebView2 web panel over the game window (APPEND-AT-END (ABI); number provisional) public IntPtr WebPanelOpenFn; // int WebPanelOpen(WebPanelOpenNative*) -> handle > 0, or BadArgs/UrlNotAllowed/NoGameWindow/Unavailable/ShuttingDown public IntPtr WebPanelNavigateFn; // int WebPanelNavigate(int handle, byte* url) -> 1 queued; -2 off-list; -6 stale public IntPtr WebPanelCloseFn; // int WebPanelClose(int handle) -> 1 queued, 0 already closed, -6 stale diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 223bf4d..5e5da89 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -1877,17 +1877,17 @@ public readonly unsafe struct RynthCoreHost return true; } - // ── v93: a web panel over the game window (number provisional) ─────────── + // ── v94: a web panel over the game window (number provisional) ─────────── /// - /// v93: , , and - /// . True only on an engine at API 93 or newer that fills all four. + /// v94: , , and + /// . True only on an engine at API 94 or newer that fills all four. /// - public bool HasWebPanel => _api.Version >= 93 && _api.WebPanelOpenFn != IntPtr.Zero && _api.WebPanelNavigateFn != IntPtr.Zero + public bool HasWebPanel => _api.Version >= 94 && _api.WebPanelOpenFn != IntPtr.Zero && _api.WebPanelNavigateFn != IntPtr.Zero && _api.WebPanelCloseFn != IntPtr.Zero && _api.WebPanelGetStateFn != IntPtr.Zero; /// - /// v93: opens the web panel over the game window (a second call replaces the first). Returns a handle + /// v94: opens the web panel over the game window (a second call replaces the first). Returns a handle /// > 0, or a (BadArgs for an empty URL or allowlist, more than 16 /// entries or a newline inside one; Unavailable on an older engine). Never blocks; the panel loads /// after this returns - poll . Any thread. @@ -1941,7 +1941,7 @@ public readonly unsafe struct RynthCoreHost } /// - /// v93: points the panel at . 1 queued; -2 + /// v94: points the panel at . 1 queued; -2 /// (UrlNotAllowed) when it is off the allowlist (the engine opens it in the system browser when that is /// safe); -6 (StaleHandle) when the handle is not the live panel. Never blocks. Any thread. /// @@ -1965,7 +1965,7 @@ public readonly unsafe struct RynthCoreHost } } - /// v93: closes the panel . 1 queued, 0 already closed, -6 stale handle. Never blocks. Any thread. + /// v94: closes the panel . 1 queued, 0 already closed, -6 stale handle. Never blocks. Any thread. public int CloseWebPanel(int handle) { if (!HasWebPanel) return (int)WebPanelResult.Unavailable; @@ -1973,7 +1973,7 @@ public readonly unsafe struct RynthCoreHost } /// - /// v93: where the panel is. A handle that is not the live panel reads + /// v94: where the panel is. A handle that is not the live panel reads /// Superseded. None (and a default ) on an older engine or bad arguments. /// Any thread. /// diff --git a/src/RynthCore.PluginSdk/WebPanelTypes.cs b/src/RynthCore.PluginSdk/WebPanelTypes.cs index b05d4e0..3c8117c 100644 --- a/src/RynthCore.PluginSdk/WebPanelTypes.cs +++ b/src/RynthCore.PluginSdk/WebPanelTypes.cs @@ -4,11 +4,11 @@ using System.Runtime.InteropServices; namespace RynthCore.PluginSdk; -// v93: a WebView2 web panel over the game window. The native structs mirror +// v94: a WebView2 web panel over the game window. The native structs mirror // RynthCore.Engine/Plugins/PluginContract.cs field for field (tools\PluginManifestTests checks sizes and // offsets). The API number is provisional. -/// v93 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors the engine's WebPanelOpenNative. +/// v94 WebPanelOpen argument (Pack 4; 48 bytes on x86). Mirrors the engine's WebPanelOpenNative. [StructLayout(LayoutKind.Sequential, Pack = 4)] public unsafe struct WebPanelOpenNative { @@ -30,7 +30,7 @@ public unsafe struct WebPanelOpenNative public fixed uint Reserved[4]; } -/// v93 WebPanelGetState result (Pack 4; 48 bytes). Mirrors the engine's WebPanelStateNative. +/// v94 WebPanelGetState result (Pack 4; 48 bytes). Mirrors the engine's WebPanelStateNative. [StructLayout(LayoutKind.Sequential, Pack = 4)] public unsafe struct WebPanelStateNative { diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index ecae5c1..5abe769 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ - 93 + 94 88 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 5a14d08..78e80a6 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -627,7 +627,7 @@ namespace EngineSettingsTests } } - // engine.json WebPanel (2026-11-07, the v93 web panel kill switch): default on, only a hand-set false is + // engine.json WebPanel (2026-11-07, the v94 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() { diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index 77a581a..83dc114 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -593,7 +593,7 @@ internal static class Program "targets: the manifest and the runtime attribute both use the derived minimum"); } - // v93: the web panel's four slots are appended right after GetMonsterHealthFn, in order, on both sides. + // v94: the web panel's four slots are appended right after GetMonsterHealthFn, in order, on both sides. private static void WebPanelFieldsAppended() { string[] slots = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; @@ -621,7 +621,7 @@ internal static class Program Eq((int)Marshal.OffsetOf(sdk, f), (int)Marshal.OffsetOf(engine, f), engine.Name + "." + f + " offset"); } - // v93: the SDK's WebPanelOpenNative/WebPanelStateNative are the engine's, byte for byte. + // v94: the SDK's WebPanelOpenNative/WebPanelStateNative are the engine's, byte for byte. private static void WebPanelStructsMatch() { int p = IntPtr.Size; @@ -641,7 +641,7 @@ internal static class Program Console.WriteLine($" (WebPanelStructsMatch ran with IntPtr.Size={IntPtr.Size})"); } - // v93: every code value agrees between the engine's enums and the SDK's. + // v94: every code value agrees between the engine's enums and the SDK's. private static void WebPanelCodesMatch() { Dictionary Vals(Type t) => Enum.GetNames(t).ToDictionary(n => n, n => Convert.ToInt64(Enum.Parse(t, n))); @@ -662,27 +662,27 @@ internal static class Program Eq((uint)RynthCore.PluginSdk.WebPanelFlags.PageKeepsEscape, 2u, "open flag PageKeepsEscape"); } - // v93: HasWebPanel needs Version >= 93 AND all four slots (an old engine's table is shorter and the + // v94: HasWebPanel needs Version >= 94 AND all four slots (an old engine's table is shorter and the // runtime copies the full new-size struct, so slots past its end are garbage, not zero). private static void HasWebPanel_FalseOnOldOrPartialTable() { IntPtr x = (IntPtr)0xDEAD; RynthCoreHost Host(uint version, IntPtr a, IntPtr b, IntPtr c, IntPtr d) => new RynthCoreHost(new RynthCoreApiNative { Version = version, WebPanelOpenFn = a, WebPanelNavigateFn = b, WebPanelCloseFn = c, WebPanelGetStateFn = d }); - Check(!Host(92, x, x, x, x).HasWebPanel, "Version 92 with garbage slots: false"); - Check(!Host(93, IntPtr.Zero, x, x, x).HasWebPanel, "Open zero: false"); - Check(!Host(93, x, IntPtr.Zero, x, x).HasWebPanel, "Navigate zero: false"); - Check(!Host(93, x, x, IntPtr.Zero, x).HasWebPanel, "Close zero: false"); - Check(!Host(93, x, x, x, IntPtr.Zero).HasWebPanel, "GetState zero: false"); - Check(Host(93, x, x, x, x).HasWebPanel, "Version 93, all four: true"); - var old = Host(92, x, x, x, x); + Check(!Host(93, x, x, x, x).HasWebPanel, "Version 93 with garbage slots: false"); + Check(!Host(94, IntPtr.Zero, x, x, x).HasWebPanel, "Open zero: false"); + Check(!Host(94, x, IntPtr.Zero, x, x).HasWebPanel, "Navigate zero: false"); + Check(!Host(94, x, x, IntPtr.Zero, x).HasWebPanel, "Close zero: false"); + Check(!Host(94, x, x, x, IntPtr.Zero).HasWebPanel, "GetState zero: false"); + Check(Host(94, x, x, x, x).HasWebPanel, "Version 94, all four: true"); + var old = Host(93, x, x, x, x); Eq(old.OpenWebPanel(new WebPanelOptions { Url = "https://a.example/", Allowlist = new[] { "a.example" } }), (int)WebPanelResult.Unavailable, "Open without the API: Unavailable"); Eq(old.NavigateWebPanel(1, "https://a.example/"), (int)WebPanelResult.Unavailable, "Navigate without the API: Unavailable"); Eq(old.CloseWebPanel(1), (int)WebPanelResult.Unavailable, "Close without the API: Unavailable"); Eq(old.GetWebPanelState(1, out var st), WebPanelStatus.None, "GetState without the API: None"); Eq(st.Handle, 0, "GetState without the API: default state"); // Bad arguments are refused before the engine is called (the slots hold garbage, so a call would crash). - var live = Host(93, x, x, x, x); + var live = Host(94, x, x, x, x); Eq(live.OpenWebPanel(new WebPanelOptions { Url = "", Allowlist = new[] { "a" } }), (int)WebPanelResult.BadArgs, "empty URL: BadArgs"); Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = Array.Empty() }), (int)WebPanelResult.BadArgs, "empty allowlist: BadArgs"); Eq(live.OpenWebPanel(new WebPanelOptions { Url = "https://a/", Allowlist = new[] { "a\nb" } }), (int)WebPanelResult.BadArgs, "newline in an entry: BadArgs"); @@ -703,7 +703,7 @@ internal static class Program Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v91 follow: - // eleven slots to v89, then v90's thirteen, v91's two, v93's one and the web panel's four). + // eleven slots to v89, then v90's thirteen, v91's two, v93's one and v94's four). var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(31).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); @@ -718,12 +718,12 @@ internal static class Program { var all = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkAll = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); - // v93: the web panel's four slots end the table; the checks after these are on the table before them. - string[] v93 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; - Check(all.TakeLast(v93.Length).SequenceEqual(v93), "v93 slots last: " + string.Join(",", all.TakeLast(v93.Length))); - Check(sdkAll.TakeLast(v93.Length).SequenceEqual(v93), "SDK v93 slots last: " + string.Join(",", sdkAll.TakeLast(v93.Length))); - all = all.SkipLast(v93.Length).ToArray(); - sdkAll = sdkAll.SkipLast(v93.Length).ToArray(); + // v94: the web panel's four slots end the table; the checks after these are on the table before them. + string[] v94 = { "WebPanelOpenFn", "WebPanelNavigateFn", "WebPanelCloseFn", "WebPanelGetStateFn" }; + Check(all.TakeLast(v94.Length).SequenceEqual(v94), "v94 slots last: " + string.Join(",", all.TakeLast(v94.Length))); + Check(sdkAll.TakeLast(v94.Length).SequenceEqual(v94), "SDK v94 slots last: " + string.Join(",", sdkAll.TakeLast(v94.Length))); + all = all.SkipLast(v94.Length).ToArray(); + sdkAll = sdkAll.SkipLast(v94.Length).ToArray(); // v93: the monster plates' health readings end the table (2026-11-07), right after v91's two. Check(all.Last() == "GetMonsterHealthFn", "v93 slot last: " + all.Last()); Check(sdkAll.Last() == "GetMonsterHealthFn", "SDK v93 slot last: " + sdkAll.Last()); -- 2.43.0