ServerPack: use the engine's web panel when it has one

OpenWeb now opens the page in RynthCore's in-game web panel (plugin API v93)
and falls back to the system browser only when the panel refused before
navigating. A handle from OpenWebPanel only means queued, so the open is
answered from OnTick (PollWeb), which reads GetWebPanelState until it decides:
Loading/Ready opened; Failed+OpenedInBrowser the engine opened the browser
(do nothing more); Failed+ProcessFailed spent; Failed+RuntimeMissing or
CreateFailed with no browser and no navigation falls back. A 20 s poll
timeout answers NoAnswer (neutral, no fallback). done fires exactly once.

ServerWebPanel.cs is pure (an int/string engine seam), so the mappings and
the once-only answer are tested with a fake engine. Every SDK web-panel name
sits in four NoInlining helpers in ServerPackWeb.cs, each called inside
catch (MissingMethodException) and catch (TypeLoadException); a source scan
pins that, the poll's place in OnTick, and the absence of locks. CloseWeb
closes only the handle this plugin opened.

Builds only against a RynthCore SDK with the web panel (0ef12d7); against
418d80b the helpers do not compile (8 errors, all in ServerPackWeb.cs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel Wallace 2026-11-07 16:54:51 -08:00
commit 0ba3b5909e
8 changed files with 733 additions and 22 deletions

View file

@ -268,6 +268,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); }
}
// A queued web-panel open is answered from here (ServerPackWeb.cs).
PollWeb();
bool active = Active;
if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden)
ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here.");

View file

@ -1,14 +1,22 @@
// ServerPackWeb.cs - the host side of ServerWebOpen: open a server's web page in the engine's web
// panel when it has one, else in the system browser. A server's own code calls OpenWeb on the pump
// (ServerChatCommand, a RunOnTick action); the answer goes to `done`, which may run on a worker
// thread (Reply is any-thread). The answer never contains the URL.
// (ServerChatCommand, a RunOnTick action); the answer goes to `done` exactly once, and it may run on
// the pump (a refusal, or the tick's poll of a queued open) or on a worker thread (the browser). Reply
// is any-thread. The answer never contains the URL, and nothing here logs it.
//
// The panel (RynthCore plugin API v93, docs\WEB_PANEL.md): ServerWebPanel.cs reads the engine's codes
// and states and holds the one open the tick waits on (OnTick -> PollWeb). The engine calls are the
// four NoInlining helpers at the bottom, the only code that names an SDK web-panel member, each called
// inside catch (MissingMethodException) and catch (TypeLoadException): on a core whose
// Runtime\PluginShared SDK predates the panel they fail that call, not the plugin's load.
//
// Never Process.Start inside acclient: the browser opens with ShellExecuteW, as the engine does
// (ProblemReport.cs), on its own short-lived STA thread so the shell call never blocks the pump.
// The panel seams (PanelAvailable, TryOpenPanel) are stubs until the engine API is wired.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.ServerPack;
@ -17,17 +25,22 @@ public sealed partial class ServerPackPlugin
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string? operation, string file, string? parameters, string? directory, int showCmd);
// Seam for the engine's web panel (a stub until the engine API is wired).
private bool PanelAvailable => false;
private ServerWebPanel? _webPanel;
private PanelResult TryOpenPanel(WebOpenRequest r) => PanelResult.RefusedBeforeNavigate;
private ServerWebPanel WebPanel
=> Volatile.Read(ref _webPanel)
?? Interlocked.CompareExchange(ref _webPanel, new ServerWebPanel(new EngineWebPanel(this)), null)
?? _webPanel!;
/// <summary>The engine has a web panel (HasWebPanel; false on an older core or SDK). Any thread.</summary>
private bool PanelAvailable => WebPanel.Available;
private static void Finish(Action<WebOpenOutcome> done, WebOpenOutcome outcome)
{
try { done(outcome); } catch { }
}
/// <summary>Opens the page (pump thread). `done` gets the route taken and a message without the URL.</summary>
/// <summary>Opens the page (pump thread). `done` gets the route taken and a message without the URL, once.</summary>
internal void OpenWeb(WebOpenRequest r, Action<WebOpenOutcome> done)
{
WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable);
@ -39,24 +52,68 @@ public sealed partial class ServerPackPlugin
if (route == WebOpenRoute.Panel)
{
PanelResult result;
try { result = TryOpenPanel(r); }
catch (Exception) { result = PanelResult.RefusedBeforeNavigate; }
if (result == PanelResult.Opened)
try
{
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel."));
return;
WebPanel.Open(r, Environment.TickCount64, result => AfterPanel(r, result, done));
}
if (!ServerWebOpen.FallbackToBrowser(result))
catch (Exception)
{
LogTagged("web panel: " + result);
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel couldn't open that page."));
return;
AfterPanel(r, PanelResult.RefusedBeforeNavigate, done);
}
LogTagged("web panel: " + result + ", using the browser");
return;
}
OpenInBrowser(r, done);
}
/// <summary>The panel's answer (pump thread: at once, or from the tick's poll). Exactly one Finish or browser open.</summary>
private void AfterPanel(WebOpenRequest r, PanelResult result, Action<WebOpenOutcome> done)
{
try
{
switch (result)
{
case PanelResult.Opened:
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel."));
return;
case PanelResult.OpenedInBrowserByEngine:
// RynthCore opened the browser itself (and said so in chat): never a second time.
LogTagged("web panel: OpenedInBrowserByEngine");
Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, true, "Opened in your browser."));
return;
case PanelResult.RefusedBeforeNavigate:
LogTagged("web panel: RefusedBeforeNavigate, using the browser");
OpenInBrowser(r, done);
return;
case PanelResult.UrlNotAllowed:
case PanelResult.BadArgs:
// A plugin bug: the request did not pass the engine's checks. The browser would hide it.
LogTagged("web panel: " + result + " (a plugin bug: the engine refused the request; not sent to the browser)");
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel refused that page (a plugin bug, logged)."));
return;
case PanelResult.FailedAfterNavigate:
LogTagged("web panel: FailedAfterNavigate");
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel stopped while loading the page; open it again."));
return;
case PanelResult.Closed:
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel was closed before the page loaded."));
return;
default:
// NoAnswer (the poll timed out or the state could not be read), or Pending, which
// ServerWebPanel never answers with. Neutral: the panel may still show; no browser.
LogTagged("web panel: " + result);
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel hasn't shown the page yet; it may still appear."));
return;
}
}
catch (Exception)
{
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel couldn't open that page."));
}
}
private void OpenInBrowser(WebOpenRequest r, Action<WebOpenOutcome> done)
{
if (!ServerWebOpen.TryGetAllowedUri(r.Url, r.AllowedHosts, out string url))
{
Finish(done, new WebOpenOutcome(WebOpenRoute.Refused, false, "That page is not on this server's list of pages, so it was not opened."));
@ -86,8 +143,86 @@ public sealed partial class ServerPackPlugin
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
/// <summary>Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired.</summary>
/// <summary>The tick's poll of a queued open (OnTick, pump thread).</summary>
private void PollWeb()
{
try { _webPanel?.Poll(Environment.TickCount64); }
catch (Exception) { }
}
/// <summary>Closes the engine's web panel only if this plugin opened it; answers a waiting open. Pump thread.</summary>
internal void CloseWeb()
{
try { _webPanel?.Close(); }
catch (Exception) { }
}
}
// -- The engine calls. Each helper is the only code naming its SDK members, and each wrapper catches
// the two exceptions an older Runtime\PluginShared SDK raises when it JITs the helper. --
private sealed class EngineWebPanel : IWebPanelEngine
{
private readonly ServerPackPlugin _plugin;
public EngineWebPanel(ServerPackPlugin plugin) => _plugin = plugin;
public bool HasPanel()
{
try { return _plugin.WebPanelHasCore(); }
catch (MissingMethodException) { return false; }
catch (TypeLoadException) { return false; }
}
public int Open(string url, string[] allowlist, string profileKey, string title)
{
try { return _plugin.WebPanelOpenCore(url, allowlist, profileKey, title); }
catch (MissingMethodException) { return WebPanelCodes.Unavailable; }
catch (TypeLoadException) { return WebPanelCodes.Unavailable; }
}
public int GetState(int handle, out int flags, out int error, out uint navigationCount)
{
flags = 0;
error = 0;
navigationCount = 0;
try { return _plugin.WebPanelStateCore(handle, out flags, out error, out navigationCount); }
catch (MissingMethodException) { return WebPanelCodes.StatusNone; }
catch (TypeLoadException) { return WebPanelCodes.StatusNone; }
}
public int Close(int handle)
{
try { return _plugin.WebPanelCloseCore(handle); }
catch (MissingMethodException) { return WebPanelCodes.Unavailable; }
catch (TypeLoadException) { return WebPanelCodes.Unavailable; }
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool WebPanelHasCore() => Host.HasWebPanel;
[MethodImpl(MethodImplOptions.NoInlining)]
private int WebPanelOpenCore(string url, string[] allowlist, string profileKey, string title)
=> Host.OpenWebPanel(new WebPanelOptions
{
Url = url,
Allowlist = allowlist,
ProfileKey = profileKey,
Title = title,
Flags = WebPanelFlags.FallbackToBrowser,
});
[MethodImpl(MethodImplOptions.NoInlining)]
private int WebPanelStateCore(int handle, out int flags, out int error, out uint navigationCount)
{
WebPanelStatus status = Host.GetWebPanelState(handle, out WebPanelState state);
flags = (int)state.Flags;
error = (int)state.Error;
navigationCount = state.NavigationCount;
return (int)status;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private int WebPanelCloseCore(int handle) => Host.CloseWebPanel(handle);
}

View file

@ -69,6 +69,7 @@
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" />
<!-- Open a web page in the engine's panel, else the browser (allowlisted https only). -->
<Compile Include="$(MSBuildThisFileDirectory)ServerWebOpen.cs" Link="ServerPack\ServerWebOpen.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerWebPanel.cs" Link="ServerPack\ServerWebPanel.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackWeb.cs" Link="ServerPack\ServerPackWeb.cs" />
</ItemGroup>

View file

@ -19,7 +19,13 @@ internal sealed record WebOpenRequest(string Url, IReadOnlyList<string> AllowedH
internal enum WebOpenRoute { Panel, Browser, Refused }
/// <summary>What the engine's panel did. Only a refusal before navigating may fall back to the browser.</summary>
internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate }
/// <remarks>
/// OpenedInBrowserByEngine: the engine's own fallback opened the system browser (do nothing more).
/// BadArgs and UrlNotAllowed: plugin bugs, never sent to the browser. Pending: the engine queued the
/// open and the tick polls its state (ServerWebPanel). Closed: closed or replaced before it loaded.
/// NoAnswer: the state never settled before the poll timeout (or could not be read); neutral, no fallback.
/// </remarks>
internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate, OpenedInBrowserByEngine, BadArgs, Pending, Closed, NoAnswer }
/// <summary>What happened. The message never contains the URL.</summary>
internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message);

View file

@ -0,0 +1,203 @@
// ServerWebPanel.cs - the engine's web panel (RynthCore plugin API v93, docs\WEB_PANEL.md) as the
// ServerPack sees it: the engine's codes and states read as a PanelResult, and the one open the tick
// waits on. Pure (no SDK types, no engine): the calls go through IWebPanelEngine, which ServerPackWeb.cs
// implements with NoInlining helpers and RynthServerPack.Tests fakes.
//
// An open that returns a handle (> 0) is only queued, so its answer comes later: the plugin's OnTick
// calls Poll, and the first state that decides (WEB_PANEL.md: Failed, its error and OpenedInBrowser
// appear together, so one poll is enough) answers it. `then` runs exactly once per Open: at once for a
// refusal, else from Poll (a state, or the timeout), from Close, or from a newer Open. No locks: the
// waiting open and the handle move by Interlocked only, and `then` never runs under anything.
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Plugin.ServerPack;
/// <summary>The engine's web-panel calls, in primitives and strings only (WEB_PANEL.md's values as ints).</summary>
internal interface IWebPanelEngine
{
bool HasPanel();
/// <summary>A handle (&gt; 0), or a negative WebPanelResult.</summary>
int Open(string url, string[] allowlist, string profileKey, string title);
/// <summary>The WebPanelStatus; fills the WebPanelStateFlags, the error and the navigation count.</summary>
int GetState(int handle, out int flags, out int error, out uint navigationCount);
int Close(int handle);
}
/// <summary>WEB_PANEL.md's numbers (RynthCore.PluginSdk WebPanelResult, WebPanelStatus, WebPanelStateFlags).</summary>
internal static class WebPanelCodes
{
public const int BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3, Unavailable = -4, ShuttingDown = -5;
public const int StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9;
public const int StatusNone = 0, StatusStarting = 1, StatusLoading = 2, StatusReady = 3;
public const int StatusClosed = 4, StatusFailed = 5, StatusSuperseded = 6;
public const int FlagOpenedInBrowser = 4;
}
internal sealed class ServerWebPanel
{
/// <summary>
/// How long a queued open may stay Starting before it is answered NoAnswer (neutral, no browser).
/// 20 s covers a cold WebView2 start (creating the environment and the browser process) with room
/// to spare; past it something is wrong, and opening the browser too could spend the code twice.
/// The handle is kept, so logout still closes the panel if it shows up late.
/// </summary>
public const long PollTimeoutMs = 20_000;
private sealed class WaitingOpen
{
public WaitingOpen(int handle, long deadlineMs, Action<PanelResult> then)
{
Handle = handle;
DeadlineMs = deadlineMs;
Then = then;
}
public int Handle { get; }
public long DeadlineMs { get; }
public Action<PanelResult> Then { get; }
}
private readonly IWebPanelEngine _engine;
private WaitingOpen? _waiting;
// The handle this plugin opened last (0 = none); the only one Close ever closes.
private int _handle;
public ServerWebPanel(IWebPanelEngine engine) => _engine = engine;
/// <summary>The engine has a web panel. False when the call throws.</summary>
public bool Available
{
get
{
try { return _engine.HasPanel(); }
catch (Exception) { return false; }
}
}
/// <summary>An open is queued and not yet answered.</summary>
public bool Waiting => Volatile.Read(ref _waiting) != null;
/// <summary>OpenWebPanel's return: a handle is Pending (queued, not opened); else the refusal.</summary>
public static PanelResult FromOpenCode(int code)
{
if (code > 0) return PanelResult.Pending;
switch (code)
{
case WebPanelCodes.BadArgs: return PanelResult.BadArgs;
case WebPanelCodes.UrlNotAllowed: return PanelResult.UrlNotAllowed;
case WebPanelCodes.NoGameWindow:
case WebPanelCodes.Unavailable:
case WebPanelCodes.ShuttingDown:
return PanelResult.RefusedBeforeNavigate;
default:
// Not a documented Open return. No handle was issued, so nothing navigated: a refusal.
return PanelResult.RefusedBeforeNavigate;
}
}
/// <summary>
/// A polled state. Loading/Ready: Opened. Failed with OpenedInBrowser: the engine opened the browser.
/// Failed with RuntimeMissing/CreateFailed, no browser and no navigation: RefusedBeforeNavigate (we
/// try the browser; with FallbackToBrowser set this means the engine's own ShellExecute failed).
/// Any other Failed (ProcessFailed, or an error after a navigation): FailedAfterNavigate, the code is
/// spent. Closed/Superseded: Closed. Starting: Pending. None or anything else: NoAnswer.
/// </summary>
public static PanelResult FromState(int status, int flags, int error, uint navigationCount)
{
switch (status)
{
case WebPanelCodes.StatusStarting:
return PanelResult.Pending;
case WebPanelCodes.StatusLoading:
case WebPanelCodes.StatusReady:
return PanelResult.Opened;
case WebPanelCodes.StatusFailed:
if ((flags & WebPanelCodes.FlagOpenedInBrowser) != 0) return PanelResult.OpenedInBrowserByEngine;
if ((error == WebPanelCodes.RuntimeMissing || error == WebPanelCodes.CreateFailed) && navigationCount == 0)
return PanelResult.RefusedBeforeNavigate;
return PanelResult.FailedAfterNavigate;
case WebPanelCodes.StatusClosed:
case WebPanelCodes.StatusSuperseded:
return PanelResult.Closed;
default:
return PanelResult.NoAnswer;
}
}
/// <summary>
/// Opens <paramref name="r"/> in the panel. <paramref name="then"/> gets the answer exactly once: now
/// for a refusal, else later from Poll, Close or a newer Open. A newer Open answers the older one Closed.
/// </summary>
public void Open(WebOpenRequest r, long nowMs, Action<PanelResult> then)
{
Answer(Interlocked.Exchange(ref _waiting, null), PanelResult.Closed);
int code;
try
{
var hosts = new List<string>(r.AllowedHosts);
code = _engine.Open(r.Url, hosts.ToArray(), r.ProfileKey, r.Title);
}
catch (Exception)
{
code = WebPanelCodes.Unavailable;
}
PanelResult result = FromOpenCode(code);
if (result != PanelResult.Pending)
{
Run(then, result);
return;
}
Interlocked.Exchange(ref _handle, code);
Interlocked.Exchange(ref _waiting, new WaitingOpen(code, nowMs + PollTimeoutMs, then));
}
/// <summary>The tick: answers the waiting open once its state decides, or at the timeout.</summary>
public void Poll(long nowMs)
{
WaitingOpen? w = Volatile.Read(ref _waiting);
if (w == null) return;
PanelResult result;
try
{
int status = _engine.GetState(w.Handle, out int flags, out int error, out uint navigationCount);
result = FromState(status, flags, error, navigationCount);
}
catch (Exception)
{
// The handle was issued, so the engine may still navigate: never the browser from here.
result = PanelResult.NoAnswer;
}
if (result == PanelResult.Pending)
{
if (nowMs < w.DeadlineMs) return;
result = PanelResult.NoAnswer;
}
if (Interlocked.CompareExchange(ref _waiting, null, w) == w) Run(w.Then, result);
}
/// <summary>Closes the panel only if this plugin opened it, and answers a waiting open Closed.</summary>
public void Close()
{
Answer(Interlocked.Exchange(ref _waiting, null), PanelResult.Closed);
int handle = Interlocked.Exchange(ref _handle, 0);
if (handle <= 0) return;
try { _engine.Close(handle); }
catch (Exception) { }
}
private static void Answer(WaitingOpen? w, PanelResult result)
{
if (w != null) Run(w.Then, result);
}
private static void Run(Action<PanelResult> then, PanelResult result)
{
try { then(result); }
catch (Exception) { }
}
}

View file

@ -23,6 +23,7 @@ internal static class Program
DreamWeaveSkillsTests.Register(runner);
DreamWeaveTests.Register(runner);
ServerWebOpenTests.Register(runner);
ServerWebPanelTests.Register(runner);
DreamWeaveWebTests.Register(runner);
return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null);
}

View file

@ -34,6 +34,8 @@
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<!-- The web opener's pure rules (allowlist, route). -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerWebOpen.cs" Link="Plugin\ServerWebOpen.cs" />
<!-- The engine web panel's answers and the one open the tick waits on (pure: the engine is a seam). -->
<Compile Include="..\..\Plugins\Shared\ServerPack\ServerWebPanel.cs" Link="Plugin\ServerWebPanel.cs" />
<!-- DreamWeave's web destinations and the launch reply's wire text (pure). -->
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthDreamWeave\DreamWeave\DreamWeaveWeb.cs" Link="DreamWeave\DreamWeaveWeb.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthDreamWeave\DreamWeave\LaunchWire.cs" Link="DreamWeave\LaunchWire.cs" />

View file

@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Plugin.ServerPack;
using RynthCore.RynthAiTests.Harness;
namespace RynthServerPack.Tests;
// The engine web panel's answers as PanelResult, and the one open the tick waits on (ServerWebPanel.cs),
// against a fake engine. The plugin's own engine calls (ServerPackWeb.cs) are checked by source scan.
internal static class ServerWebPanelTests
{
public static void Register(Runner r)
{
r.Add("web panel: every Open return code maps to a PanelResult", OpenCodes);
r.Add("web panel: every state maps to a PanelResult", States);
r.Add("web panel: only a refusal before navigating falls back to the browser", Fallback);
r.Add("web panel: a refusal answers at once, exactly once", SyncAnswers);
r.Add("web panel: a queued open is answered by the tick's poll, exactly once", PollAnswers);
r.Add("web panel: a queued open that never settles times out, neutral", Timeout);
r.Add("web panel: Close closes only our own handle and answers a waiting open", CloseOwnHandle);
r.Add("web panel: engine exceptions and a throwing answer never escape", Exceptions);
r.Add("web panel: SDK references sit in NoInlining helpers behind both catches, no locks", SourceRules);
}
private const int S_None = 0, S_Starting = 1, S_Loading = 2, S_Ready = 3, S_Closed = 4, S_Failed = 5, S_Superseded = 6;
private const int F_Visible = 1, F_Focused = 2, F_OpenedInBrowser = 4;
private sealed class FakeEngine : IWebPanelEngine
{
public bool Has = true;
public int OpenReturns = 7;
public int Status = S_Starting, Flags, Error;
public uint Nav;
public bool ThrowOnOpen, ThrowOnState, ThrowOnHas;
public readonly List<int> Closed = new();
public readonly List<string> Opens = new();
public int StateCalls;
public bool HasPanel() => ThrowOnHas ? throw new InvalidOperationException("has") : Has;
public int Open(string url, string[] allowlist, string profileKey, string title)
{
if (ThrowOnOpen) throw new MissingMethodException("open");
Opens.Add(string.Join(",", allowlist) + "|" + profileKey + "|" + title);
return OpenReturns;
}
public int GetState(int handle, out int flags, out int error, out uint navigationCount)
{
StateCalls++;
if (ThrowOnState) throw new TypeLoadException("state");
flags = Flags; error = Error; navigationCount = Nav;
return Status;
}
public int Close(int handle) { Closed.Add(handle); return 1; }
}
private static readonly WebOpenRequest Req = new("https://www.acdreamweave.com/x?code=secret",
new[] { "www.acdreamweave.com" }, "dreamweave/0123456789abcdef0123456789abcdef", "DreamWeave");
private static void OpenCodes()
{
Check.Eq(ServerWebPanel.FromOpenCode(1), PanelResult.Pending, "handle 1 is queued, not opened");
Check.Eq(ServerWebPanel.FromOpenCode(12345), PanelResult.Pending, "any handle > 0 is queued");
Check.Eq(ServerWebPanel.FromOpenCode(-1), PanelResult.BadArgs, "BadArgs");
Check.Eq(ServerWebPanel.FromOpenCode(-2), PanelResult.UrlNotAllowed, "UrlNotAllowed");
Check.Eq(ServerWebPanel.FromOpenCode(-3), PanelResult.RefusedBeforeNavigate, "NoGameWindow refuses before navigating");
Check.Eq(ServerWebPanel.FromOpenCode(-4), PanelResult.RefusedBeforeNavigate, "Unavailable refuses before navigating");
Check.Eq(ServerWebPanel.FromOpenCode(-5), PanelResult.RefusedBeforeNavigate, "ShuttingDown refuses before navigating");
// No handle was issued, so nothing navigated: an undocumented code is a refusal too.
foreach (int c in new[] { 0, -6, -7, -8, -9, -10, int.MinValue })
Check.Eq(ServerWebPanel.FromOpenCode(c), PanelResult.RefusedBeforeNavigate, "undocumented open code " + c + ": no handle, refusal");
}
private static void States()
{
Check.Eq(ServerWebPanel.FromState(S_Starting, 0, 0, 0), PanelResult.Pending, "Starting: keep polling");
Check.Eq(ServerWebPanel.FromState(S_Loading, F_Visible, 0, 1), PanelResult.Opened, "Loading: opened");
Check.Eq(ServerWebPanel.FromState(S_Ready, F_Visible | F_Focused, 0, 1), PanelResult.Opened, "Ready: opened");
Check.Eq(ServerWebPanel.FromState(S_Failed, F_OpenedInBrowser, -7, 0), PanelResult.OpenedInBrowserByEngine, "Failed+OpenedInBrowser (RuntimeMissing): the engine opened it");
Check.Eq(ServerWebPanel.FromState(S_Failed, F_OpenedInBrowser, -8, 0), PanelResult.OpenedInBrowserByEngine, "Failed+OpenedInBrowser (CreateFailed): the engine opened it");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -9, 1), PanelResult.FailedAfterNavigate, "Failed+ProcessFailed: the code is spent");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -9, 0), PanelResult.FailedAfterNavigate, "ProcessFailed never falls back, whatever the count");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -7, 0), PanelResult.RefusedBeforeNavigate, "RuntimeMissing, no browser, no navigation: fall back ourselves");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -8, 0), PanelResult.RefusedBeforeNavigate, "CreateFailed, no browser, no navigation: fall back ourselves");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -7, 1), PanelResult.FailedAfterNavigate, "RuntimeMissing after a navigation: spent, no fallback");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -8, 2), PanelResult.FailedAfterNavigate, "CreateFailed after a navigation: spent, no fallback");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, 0, 0), PanelResult.FailedAfterNavigate, "Failed with an unknown error: no fallback");
Check.Eq(ServerWebPanel.FromState(S_Failed, 0, -4, 0), PanelResult.FailedAfterNavigate, "Failed with an undocumented error: no fallback");
Check.Eq(ServerWebPanel.FromState(S_Closed, 0, 0, 0), PanelResult.Closed, "Closed before it loaded");
Check.Eq(ServerWebPanel.FromState(S_Superseded, 0, 0, 0), PanelResult.Closed, "Superseded: replaced");
Check.Eq(ServerWebPanel.FromState(S_None, 0, 0, 0), PanelResult.NoAnswer, "None (older engine, shutting down): neutral");
Check.Eq(ServerWebPanel.FromState(99, 0, 0, 0), PanelResult.NoAnswer, "an undocumented status: neutral");
Check.Eq(ServerWebPanel.FromState(-4, 0, 0, 0), PanelResult.NoAnswer, "a negative status: neutral");
}
private static void Fallback()
{
foreach (PanelResult p in Enum.GetValues<PanelResult>())
Check.Eq(ServerWebOpen.FallbackToBrowser(p), p == PanelResult.RefusedBeforeNavigate, "fallback for " + p);
}
private static List<PanelResult> Answers(out Action<PanelResult> then)
{
var list = new List<PanelResult>();
then = list.Add;
return list;
}
private static void SyncAnswers()
{
foreach ((int code, PanelResult want) in new[] { (-1, PanelResult.BadArgs), (-2, PanelResult.UrlNotAllowed), (-3, PanelResult.RefusedBeforeNavigate), (-4, PanelResult.RefusedBeforeNavigate), (-5, PanelResult.RefusedBeforeNavigate) })
{
var e = new FakeEngine { OpenReturns = code };
var p = new ServerWebPanel(e);
var got = Answers(out var then);
p.Open(Req, 0, then);
Check.Eq(string.Join(",", got), want.ToString(), "open code " + code + ": answered at once");
Check.False(p.Waiting, "open code " + code + ": nothing waits");
p.Poll(1);
p.Poll(ServerWebPanel.PollTimeoutMs + 5);
Check.Eq(got.Count, 1, "open code " + code + ": the poll never answers again");
Check.Eq(e.StateCalls, 0, "open code " + code + ": no state is read");
p.Close();
Check.Eq(e.Closed.Count, 0, "open code " + code + ": no handle, nothing to close");
}
var o = new FakeEngine();
new ServerWebPanel(o).Open(Req, 0, _ => { });
Check.Eq(string.Join(" ", o.Opens), "www.acdreamweave.com|dreamweave/0123456789abcdef0123456789abcdef|DreamWeave", "the request's allowlist, profile key and title reach the engine");
}
private static void PollAnswers()
{
var cases = new (int Status, int Flags, int Error, uint Nav, PanelResult Want)[]
{
(S_Loading, F_Visible, 0, 1, PanelResult.Opened),
(S_Ready, F_Visible, 0, 1, PanelResult.Opened),
(S_Failed, F_OpenedInBrowser, -7, 0, PanelResult.OpenedInBrowserByEngine),
(S_Failed, 0, -9, 1, PanelResult.FailedAfterNavigate),
(S_Failed, 0, -7, 0, PanelResult.RefusedBeforeNavigate),
(S_Failed, 0, -8, 0, PanelResult.RefusedBeforeNavigate),
(S_Closed, 0, 0, 0, PanelResult.Closed),
(S_Superseded, 0, 0, 0, PanelResult.Closed),
(S_None, 0, 0, 0, PanelResult.NoAnswer),
};
foreach (var c in cases)
{
var e = new FakeEngine { Status = S_Starting };
var p = new ServerWebPanel(e);
var got = Answers(out var then);
p.Open(Req, 1_000, then);
Check.Eq(got.Count, 0, c.Want + ": a handle is not an answer");
Check.True(p.Waiting, c.Want + ": waiting after a handle");
p.Poll(1_100);
p.Poll(1_200);
Check.Eq(got.Count, 0, c.Want + ": Starting keeps waiting");
e.Status = c.Status; e.Flags = c.Flags; e.Error = c.Error; e.Nav = c.Nav;
p.Poll(1_300);
Check.Eq(string.Join(",", got), c.Want.ToString(), "state " + c.Status + "/" + c.Flags + "/" + c.Error + "/" + c.Nav + ": one poll decides");
Check.False(p.Waiting, c.Want + ": nothing waits after the answer");
int calls = e.StateCalls;
p.Poll(1_400);
p.Poll(1_000 + ServerWebPanel.PollTimeoutMs + 1);
Check.Eq(got.Count, 1, c.Want + ": answered exactly once");
Check.Eq(e.StateCalls, calls, c.Want + ": no polling after the answer");
}
}
private static void Timeout()
{
Check.True(ServerWebPanel.PollTimeoutMs >= 5_000 && ServerWebPanel.PollTimeoutMs <= 60_000, "the poll timeout is between 5 and 60 seconds");
var e = new FakeEngine { Status = S_Starting };
var p = new ServerWebPanel(e);
var got = Answers(out var then);
p.Open(Req, 10_000, then);
p.Poll(10_000 + ServerWebPanel.PollTimeoutMs - 1);
Check.Eq(got.Count, 0, "still Starting just before the timeout: waiting");
p.Poll(10_000 + ServerWebPanel.PollTimeoutMs);
Check.Eq(string.Join(",", got), PanelResult.NoAnswer.ToString(), "at the timeout: NoAnswer");
Check.False(ServerWebOpen.FallbackToBrowser(PanelResult.NoAnswer), "a timeout never opens the browser");
p.Poll(10_000 + ServerWebPanel.PollTimeoutMs + 50);
Check.Eq(got.Count, 1, "the timeout answers once");
// The handle is kept: the panel may still show, and logout closes it.
p.Close();
Check.Eq(string.Join(",", e.Closed), "7", "a timed-out open's handle is still ours to close");
}
private static void CloseOwnHandle()
{
var none = new FakeEngine();
new ServerWebPanel(none).Close();
Check.Eq(none.Closed.Count, 0, "never opened: Close calls nothing");
var e = new FakeEngine { OpenReturns = 7, Status = S_Starting };
var p = new ServerWebPanel(e);
var got = Answers(out var then);
p.Open(Req, 0, then);
p.Close();
Check.Eq(string.Join(",", got), PanelResult.Closed.ToString(), "Close answers the waiting open as Closed");
Check.Eq(string.Join(",", e.Closed), "7", "Close closes our handle");
p.Close();
Check.Eq(string.Join(",", e.Closed), "7", "a second Close closes nothing");
Check.Eq(got.Count, 1, "and answers nothing again");
// A newer open replaces the one we waited on; Close then closes the newer handle only.
var e2 = new FakeEngine { OpenReturns = 7, Status = S_Starting };
var p2 = new ServerWebPanel(e2);
var first = Answers(out var then1);
var second = Answers(out var then2);
p2.Open(Req, 0, then1);
e2.OpenReturns = 8;
p2.Open(Req, 10, then2);
Check.Eq(string.Join(",", first), PanelResult.Closed.ToString(), "a newer open answers the older one as Closed");
Check.Eq(second.Count, 0, "the newer one still waits");
e2.Status = S_Ready;
p2.Poll(20);
Check.Eq(string.Join(",", second), PanelResult.Opened.ToString(), "the newer one opens");
p2.Close();
Check.Eq(string.Join(",", e2.Closed), "8", "Close closes the newest handle only");
Check.Eq(first.Count, 1, "the older answer is not repeated");
// An opened panel (answered) is still closed by Close; a refused one gives nothing to close.
var e3 = new FakeEngine { OpenReturns = 9, Status = S_Ready };
var p3 = new ServerWebPanel(e3);
p3.Open(Req, 0, _ => { });
p3.Poll(1);
e3.OpenReturns = -4;
p3.Open(Req, 2, _ => { });
p3.Close();
Check.Eq(string.Join(",", e3.Closed), "9", "a refused open keeps the earlier handle ours to close");
}
private static void Exceptions()
{
var e = new FakeEngine { ThrowOnOpen = true };
var p = new ServerWebPanel(e);
var got = Answers(out var then);
p.Open(Req, 0, then);
Check.Eq(string.Join(",", got), PanelResult.RefusedBeforeNavigate.ToString(), "Open throwing: refused before navigating");
var s = new FakeEngine { Status = S_Starting };
var ps = new ServerWebPanel(s);
var sg = Answers(out var sthen);
ps.Open(Req, 0, sthen);
s.ThrowOnState = true;
ps.Poll(1);
Check.Eq(string.Join(",", sg), PanelResult.NoAnswer.ToString(), "GetState throwing after a handle: neutral, never the browser");
var h = new FakeEngine { ThrowOnHas = true };
Check.False(new ServerWebPanel(h).Available, "HasPanel throwing: not available");
Check.True(new ServerWebPanel(new FakeEngine()).Available, "HasPanel true: available");
Check.False(new ServerWebPanel(new FakeEngine { Has = false }).Available, "HasPanel false: not available");
var t = new FakeEngine { OpenReturns = -4 };
bool threw = false;
try { new ServerWebPanel(t).Open(Req, 0, _ => throw new InvalidOperationException("answer")); }
catch (Exception) { threw = true; }
Check.False(threw, "a throwing answer (sync) never escapes Open");
var tp = new FakeEngine { Status = S_Starting };
var ptp = new ServerWebPanel(tp);
ptp.Open(Req, 0, _ => throw new InvalidOperationException("answer"));
tp.Status = S_Ready;
threw = false;
try { ptp.Poll(1); } catch (Exception) { threw = true; }
Check.False(threw, "a throwing answer (polled) never escapes Poll");
Check.False(ptp.Waiting, "and the open is still answered");
}
// ServerPackWeb.cs runs inside acclient against whatever SDK the installed core ships.
private static void SourceRules()
{
string shared = Path.Combine(ServerProjectsTests.PluginsDir(), "Shared", "ServerPack");
string webPath = Path.Combine(shared, "ServerPackWeb.cs");
string panelPath = Path.Combine(shared, "ServerWebPanel.cs");
string pluginPath = Path.Combine(shared, "ServerPackPlugin.cs");
string web = DreamWeaveWebTests.StripComments(File.ReadAllText(webPath));
string panel = DreamWeaveWebTests.StripComments(File.ReadAllText(panelPath));
// The SDK web-panel names, and the only methods allowed to name them.
var sdkName = new System.Text.RegularExpressions.Regex(@"\b(HasWebPanel|OpenWebPanel|NavigateWebPanel|CloseWebPanel|GetWebPanelState|WebPanelOptions|WebPanelState|WebPanelStatus|WebPanelFlags|WebPanelResult|WebPanelStateFlags|WebPanelOpenNative|WebPanelStateNative)\b");
string[] helpers = { "WebPanelHasCore", "WebPanelOpenCore", "WebPanelStateCore", "WebPanelCloseCore" };
// Every server plugin source other than ServerPackWeb.cs names none of them (the pure seam uses ints).
foreach (string f in Directory.GetFiles(ServerProjectsTests.PluginsDir(), "*.cs", SearchOption.AllDirectories)
.Where(p => !p.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
&& !p.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)))
{
if (string.Equals(Path.GetFullPath(f), Path.GetFullPath(webPath), StringComparison.OrdinalIgnoreCase)) continue;
Check.False(sdkName.IsMatch(DreamWeaveWebTests.StripComments(File.ReadAllText(f))), Path.GetFileName(f) + ": no SDK web-panel names outside ServerPackWeb.cs");
}
// In ServerPackWeb.cs, each SDK name sits inside one of the helpers, and each helper is NoInlining
// and takes and returns primitives and strings only.
var methodHead = new System.Text.RegularExpressions.Regex(
@"\[MethodImpl\(MethodImplOptions\.NoInlining\)\]\s*private\s+(bool|int)\s+(" + string.Join("|", helpers) + @")\(([^)]*)\)");
var spans = new List<(int Start, int End)>();
var found = new List<string>();
foreach (System.Text.RegularExpressions.Match m in methodHead.Matches(web))
{
found.Add(m.Groups[2].Value);
foreach (string param in m.Groups[3].Value.Split(',', StringSplitOptions.RemoveEmptyEntries))
{
string type = param.Trim().Split(' ')[0] == "out" ? param.Trim().Split(' ')[1] : param.Trim().Split(' ')[0];
Check.True(type is "int" or "uint" or "string" or "string[]", m.Groups[2].Value + ": parameter type " + type + " is a primitive or string");
}
int bodyStart = m.Index + m.Length;
int end = BodyEnd(web, bodyStart);
spans.Add((m.Index, end));
}
Check.Eq(string.Join(",", found.OrderBy(x => x)), string.Join(",", helpers.OrderBy(x => x)), "the four helpers, each NoInlining, returning bool or int");
var stray = new List<string>();
foreach (System.Text.RegularExpressions.Match m in sdkName.Matches(web))
if (!spans.Any(s => m.Index >= s.Start && m.Index < s.End)) stray.Add(m.Value + "@" + m.Index);
Check.Eq(string.Join(" ", stray), "", "ServerPackWeb.cs: SDK web-panel names only inside the NoInlining helpers");
// Each helper is called exactly once, inside a try with both catches.
foreach (string h in helpers)
{
var call = new System.Text.RegularExpressions.Regex(@"try\s*\{\s*return\s+_plugin\." + h + @"\([^;]*\);\s*\}\s*catch\s*\(MissingMethodException\)\s*\{[^{}]*\}\s*catch\s*\(TypeLoadException\)\s*\{[^{}]*\}");
Check.Eq(call.Matches(web).Count, 1, h + ": called once, as try { return _plugin." + h + "(...); } catch (MissingMethodException) { } catch (TypeLoadException) { }");
Check.Eq(System.Text.RegularExpressions.Regex.Matches(web, @"\b" + h + @"\(").Count, 2, h + ": declared and called once (nothing else calls it)");
}
Check.True(web.Contains("Flags = WebPanelFlags.FallbackToBrowser", StringComparison.Ordinal), "the open asks the engine to fall back to the browser");
// No locks in the web code: the waiting open and the handle move by Interlocked only.
Check.Eq(DreamWeaveWebTests.Locks(web).Count, 0, "ServerPackWeb.cs takes no lock");
Check.Eq(DreamWeaveWebTests.Locks(panel).Count, 0, "ServerWebPanel.cs takes no lock");
Check.False(System.Text.RegularExpressions.Regex.IsMatch(web + panel, @"\bMonitor\s*\."), "no Monitor in the web code");
// The poll runs from the plugin's OnTick once, after the tick's queued actions and before ServerTick.
string plugin = DreamWeaveWebTests.StripComments(File.ReadAllText(pluginPath));
Check.Eq(System.Text.RegularExpressions.Regex.Matches(plugin, @"\bPollWeb\(\);").Count, 1, "ServerPackPlugin.cs calls PollWeb() once");
int tick = plugin.IndexOf("public override void OnTick()", StringComparison.Ordinal);
int poll = plugin.IndexOf("PollWeb();", StringComparison.Ordinal);
int login = plugin.IndexOf("if (!_loginComplete) return;", tick < 0 ? 0 : tick, StringComparison.Ordinal);
int serverTick = plugin.IndexOf("ServerTick(active);", tick < 0 ? 0 : tick, StringComparison.Ordinal);
Check.True(tick >= 0 && login > tick && poll > login && poll < serverTick, "PollWeb runs in OnTick, logged in, before ServerTick");
Check.Eq(System.Text.RegularExpressions.Regex.Matches(web, @"\b_webPanel\?\.Poll\(Environment\.TickCount64\)").Count, 1, "PollWeb polls with Environment.TickCount64");
}
private static int BodyEnd(string code, int from)
{
int open = code.IndexOf('{', from);
int arrow = code.IndexOf("=>", from, StringComparison.Ordinal);
if (arrow >= 0 && (open < 0 || arrow < open)) { int semi = code.IndexOf(';', arrow); return semi < 0 ? code.Length : semi + 1; }
if (open < 0) return code.Length;
int depth = 0;
for (int j = open; j < code.Length; j++)
{
if (code[j] == '{') depth++;
else if (code[j] == '}' && --depth == 0) return j + 1;
}
return code.Length;
}
}