Web panel: an in-game WebView2 page for plugins (API v94) #12

Open
AwfulWaffle wants to merge 17 commits from AwfulWaffle/RynthCore:web-panel into main
7 changed files with 116 additions and 21 deletions
Showing only changes of commit 537a40a430 - Show all commits

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 <noreply@anthropic.com>
Daniel Wallace 2026-11-07 16:14:57 -08:00

View file

@ -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

View file

@ -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
`<LocalAppData>\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 (<why>), 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

View file

@ -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);

View file

@ -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();
}
/// <summary>The foreground is a window of this process (not null, not another program, not the browser process).</summary>
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 { }

View file

@ -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)
{

View file

@ -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;
/// <summary>The engine's WebPanelApi.Open path: read the caller's struct, then the host.</summary>
@ -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;
}

View file

@ -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;
}
/// <summary>
/// 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.
/// </summary>
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");
}
/// <summary>
/// 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.
/// </summary>
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");