From 52b0b008603a3036e1dbfad82e82a9034bd5346d Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:33:03 -0800 Subject: [PATCH 01/29] ServerPack: card-actions hook for a server's own buttons Adds partial void ServerCardActions(), drawn at the top of the server card under RynthCore's verdict (render thread). ServerPackUi takes an optional cardActions delegate; the plugin passes DrawCardActions (a delegate cannot bind an unimplemented partial, CS0762). Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 11 +++++- Plugins/Shared/ServerPack/ServerPackUi.cs | 6 ++- .../ServerPackHooksTests.cs | 39 ++++++++++++++++++- 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index f1f30c3..d2f1a96 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -33,6 +33,8 @@ // plugins that apply a server rule without knowing the server. // ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. // RunOnTick(action) work for the next tick (a page's button, on the render thread). +// ServerCardActions() the server's own buttons at the top of its card, under RynthCore's verdict +// (render thread: ImGui calls only; queue work with RunOnTick). // Send(command) a chat command as if typed (pump thread, logged in only); // LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window. // Resources\quests..csv (no code) the server's own quest list: embedded by ServerPlugin.props and @@ -102,7 +104,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase var verbs = new List(); ServerCommandVerbs(verbs); foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); - _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages); + _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions); } internal ServerPackInfo Info => _model.Info; @@ -147,6 +149,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current). partial void ServerRender(); /// + /// Drawn at the top of the server card, under RynthCore's verdict; render thread; queue work with RunOnTick. + /// + partial void ServerCardActions(); + /// /// An incoming chat line (pump thread, logged in only): set to keep it out of /// the chat window (it comes in true when an earlier plugin already ate it). /// @@ -165,6 +171,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// The live numbers of the profile ("values"). Any thread. internal ServerProfileValues ProfileValues => _profileValues; + // A delegate cannot bind an unimplemented partial method (CS0762), so the card gets this wrapper. + private void DrawCardActions() => ServerCardActions(); + /// The pages this plugin draws. internal IReadOnlyList Pages => _pages; diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs index f1a65da..e5fe52c 100644 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -26,6 +26,7 @@ internal sealed class ServerPackUi private readonly Func _world; private readonly string _windowTitle; private readonly IReadOnlyList _pages; + private readonly Action? _cardActions; private string _status = string.Empty; /// The standalone window is open ("/rserver"). @@ -34,12 +35,14 @@ internal sealed class ServerPackUi /// "RynthColdeve 0.1.0", for the title and the card. /// The world name the client reports now (null when unknown). /// The server's own pages: tabs of the window after the card. - public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null) + /// The server's own buttons, drawn under the verdict (render thread); null when it has none. + public ServerPackUi(ServerPackModel model, string pluginLabel, Func world, IReadOnlyList? pages = null, Action? cardActions = null) { _model = model; _pluginLabel = pluginLabel; _world = world; _pages = pages ?? Array.Empty(); + _cardActions = cardActions; _windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id; } @@ -82,6 +85,7 @@ internal sealed class ServerPackUi { ServerPackInfo info = _model.Info; RenderVerdict(info); + if (_cardActions != null) { ImGui.Separator(); _cardActions(); } ImGui.Separator(); RenderFacts(info); if (info.Commands.Length > 0) diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs index 66de8ea..68ce76b 100644 --- a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -24,6 +24,7 @@ internal static class ServerPackHooksTests r.Add("hooks: settings migration runs once, and a broken file means defaults", SettingsMigration); r.Add("hooks: profile values are published, validated and read back", ProfileValues); r.Add("hooks: the own-reply window opens, stretches and closes", ReplyWindow); + r.Add("hooks: the card draws server actions under the verdict, once", CardActions); } internal static string TempDir() @@ -199,4 +200,40 @@ internal static class ServerPackHooksTests req.Clear(); Check.False(req.Awaiting(1001), "cleared"); } -} + + // Source scan: the card hands the server's own buttons a spot right under RynthCore's verdict. + private static string ServerPackDir() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("Plugins\\Shared\\ServerPack not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins", "Shared", "ServerPack"); + } + + private static int CountOf(string text, string needle) + { + int n = 0, at = 0; + while ((at = text.IndexOf(needle, at, StringComparison.Ordinal)) >= 0) { n++; at += needle.Length; } + return n; + } + + private static void CardActions() + { + string ui = File.ReadAllText(Path.Combine(ServerPackDir(), "ServerPackUi.cs")); + string plugin = File.ReadAllText(Path.Combine(ServerPackDir(), "ServerPackPlugin.cs")); + + int body = ui.IndexOf("public void RenderBody()", StringComparison.Ordinal); + Check.True(body >= 0, "RenderBody exists"); + int verdict = ui.IndexOf("RenderVerdict(info);", body, StringComparison.Ordinal); + int facts = ui.IndexOf("RenderFacts(info);", body, StringComparison.Ordinal); + Check.True(verdict > body && facts > verdict, "RenderBody draws the verdict, then the facts"); + Check.Eq(CountOf(ui, "_cardActions()"), 1, "the card actions are invoked exactly once"); + int call = ui.IndexOf("_cardActions()", StringComparison.Ordinal); + Check.True(call > verdict && call < facts, "the actions are drawn after the verdict and before the facts"); + + Check.True(plugin.Contains("DrawCardActions", StringComparison.Ordinal) && plugin.Contains("partial void ServerCardActions();", StringComparison.Ordinal), + "the plugin declares the ServerCardActions hook and DrawCardActions"); + Check.True(plugin.Contains("_pages, DrawCardActions)", StringComparison.Ordinal), "the plugin passes DrawCardActions to ServerPackUi"); + } +} \ No newline at end of file -- 2.43.0 From 5c6af0bbe5545554fd092c9448945c0da354d3a4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:34:27 -0800 Subject: [PATCH 02/29] ServerPack: card actions add no separator of their own Hookless servers render exactly as before: call _cardActions?.Invoke() after RenderVerdict and let the existing separator close the block. Test now pins the RenderBody separator count and restores the trailing CRLF. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackUi.cs | 2 +- Tools/RynthServerPack.Tests/ServerPackHooksTests.cs | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackUi.cs b/Plugins/Shared/ServerPack/ServerPackUi.cs index e5fe52c..1df73e6 100644 --- a/Plugins/Shared/ServerPack/ServerPackUi.cs +++ b/Plugins/Shared/ServerPack/ServerPackUi.cs @@ -85,7 +85,7 @@ internal sealed class ServerPackUi { ServerPackInfo info = _model.Info; RenderVerdict(info); - if (_cardActions != null) { ImGui.Separator(); _cardActions(); } + _cardActions?.Invoke(); ImGui.Separator(); RenderFacts(info); if (info.Commands.Length > 0) diff --git a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs index 68ce76b..0ef0c2a 100644 --- a/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackHooksTests.cs @@ -228,12 +228,17 @@ internal static class ServerPackHooksTests int verdict = ui.IndexOf("RenderVerdict(info);", body, StringComparison.Ordinal); int facts = ui.IndexOf("RenderFacts(info);", body, StringComparison.Ordinal); Check.True(verdict > body && facts > verdict, "RenderBody draws the verdict, then the facts"); - Check.Eq(CountOf(ui, "_cardActions()"), 1, "the card actions are invoked exactly once"); - int call = ui.IndexOf("_cardActions()", StringComparison.Ordinal); + Check.Eq(CountOf(ui, "_cardActions?.Invoke()"), 1, "the card actions are invoked exactly once"); + int call = ui.IndexOf("_cardActions?.Invoke()", StringComparison.Ordinal); Check.True(call > verdict && call < facts, "the actions are drawn after the verdict and before the facts"); + // Hookless servers must render exactly as before: no separator was added to the card (base RenderBody has 5). + int bodyEnd = ui.IndexOf("private void RenderVerdict", body, StringComparison.Ordinal); + Check.Eq(CountOf(ui.Substring(body, bodyEnd - body), "ImGui.Separator()"), 5, "RenderBody separator count is unchanged from base"); + Check.False(ui.Substring(verdict, call - verdict).Contains("Separator", StringComparison.Ordinal), "no separator between the verdict and the actions"); + Check.True(plugin.Contains("DrawCardActions", StringComparison.Ordinal) && plugin.Contains("partial void ServerCardActions();", StringComparison.Ordinal), "the plugin declares the ServerCardActions hook and DrawCardActions"); Check.True(plugin.Contains("_pages, DrawCardActions)", StringComparison.Ordinal), "the plugin passes DrawCardActions to ServerPackUi"); } -} \ No newline at end of file +} -- 2.43.0 From dd802169338f62b49aa4f37cb921fb0192a2e290 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:36:19 -0800 Subject: [PATCH 03/29] ServerPack: open a web page in the engine's panel, else the browser Pure allowlist/route rules (ServerWebOpen) plus the host opener (ServerPackWeb): ShellExecuteW on a background STA thread; panel seams stubbed. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 81 +++++++++++++++++++ Plugins/Shared/ServerPack/ServerPlugin.props | 3 + Plugins/Shared/ServerPack/ServerWebOpen.cs | 79 ++++++++++++++++++ Tools/RynthServerPack.Tests/Program.cs | 1 + .../RynthServerPack.Tests.csproj | 2 + .../ServerWebOpenTests.cs | 49 +++++++++++ 6 files changed, 215 insertions(+) create mode 100644 Plugins/Shared/ServerPack/ServerPackWeb.cs create mode 100644 Plugins/Shared/ServerPack/ServerWebOpen.cs create mode 100644 Tools/RynthServerPack.Tests/ServerWebOpenTests.cs diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs new file mode 100644 index 0000000..af3c95e --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -0,0 +1,81 @@ +// 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. +// +// 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.InteropServices; +using System.Threading; + +namespace RynthCore.Plugin.ServerPack; + +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); + + // Seams for the engine's web panel. + private bool PanelAvailable => false; + + private bool TryOpenPanel(WebOpenRequest r, out string error) + { + error = "The web panel is not available."; + return false; + } + + /// Opens the page (pump thread). `done` gets the route taken and a message without the URL. + internal void OpenWeb(WebOpenRequest r, Action done) + { + WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable); + if (route == WebOpenRoute.Refused) + { + done(new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); + return; + } + + if (route == WebOpenRoute.Panel) + { + if (TryOpenPanel(r, out string error)) + { + done(new WebOpenOutcome(route, true, "Opened in the web panel.")); + return; + } + // The panel failed: the browser is the fallback, and the report below says it was the browser. + LogTagged("web panel did not open: " + error); + route = WebOpenRoute.Browser; + } + + string url = r.Url; + var thread = new Thread(() => + { + string message; + bool ok; + try + { + long code = ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1).ToInt64(); + ok = code > 32; + message = ok ? "Opened in your browser." : $"Couldn't open your browser (code {code})."; + } + catch (Exception) + { + ok = false; + message = "Couldn't open your browser (code 0)."; + } + done(new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); + }) + { + IsBackground = true, + Name = "ServerPack web open", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + } + + /// Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired. + internal void CloseWeb() + { + } +} diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props index 9e8606b..d7abb0d 100644 --- a/Plugins/Shared/ServerPack/ServerPlugin.props +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -67,6 +67,9 @@ + + + diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs new file mode 100644 index 0000000..2100a4d --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -0,0 +1,79 @@ +// ServerWebOpen.cs - the rules for opening a server's web page from a server plugin: which URLs are +// allowed and where the page goes (the engine's web panel when it has one, else the system browser). +// Pure (no engine, no threads): RynthServerPack.Tests covers it. The host side is ServerPackWeb.cs. +// No Regex: the plugins are NativeAOT and Regex costs size, so the key is parsed by hand. +using System; +using System.Collections.Generic; + +namespace RynthCore.Plugin.ServerPack; + +/// A page to open. The URL comes from constants in the plugin, never from chat. +internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title); + +internal enum WebOpenRoute { Panel, Browser, Refused } + +/// What happened. The message never contains the URL. +internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message); + +internal static class ServerWebOpen +{ + /// + /// Absolute https, no userinfo, the default port, and a host equal to an allowed entry + /// (OrdinalIgnoreCase). An entry "*.x" matches subdomains of x only, never x itself. + /// + public static bool IsAllowedUrl(string? url, IReadOnlyList allowedHosts) + { + if (string.IsNullOrEmpty(url) || allowedHosts == null) return false; + if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; + if (!string.Equals(uri.Scheme, "https", StringComparison.Ordinal)) return false; + if (uri.UserInfo.Length != 0 || !uri.IsDefaultPort) return false; + string host = uri.Host; + if (host.Length == 0) return false; + + foreach (string entry in allowedHosts) + { + if (string.IsNullOrEmpty(entry)) continue; + if (entry.StartsWith("*.", StringComparison.Ordinal)) + { + string suffix = entry.Substring(1); // ".x" + if (suffix.Length > 1 + && host.Length > suffix.Length + && host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) + return true; + } + else if (string.Equals(host, entry, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; + } + + /// ^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token). + public static bool IsValidProfileKey(string? key) + { + if (key == null) return false; + int slash = key.IndexOf('/'); + if (slash < 1 || slash > 32) return false; + if (key.Length - slash - 1 != 32) return false; + for (int i = 0; i < slash; i++) + { + char c = key[i]; + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false; + } + for (int i = slash + 1; i < key.Length; i++) + { + char c = key[i]; + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; + } + return true; + } + + /// Refused if the URL is not allowed; Browser if there is no panel or no valid key; else Panel. + public static WebOpenRoute Route(WebOpenRequest r, bool panelAvailable) + { + if (!IsAllowedUrl(r.Url, r.AllowedHosts)) return WebOpenRoute.Refused; + if (!panelAvailable || !IsValidProfileKey(r.ProfileKey)) return WebOpenRoute.Browser; + return WebOpenRoute.Panel; + } +} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 0bf26e2..88e690e 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -22,6 +22,7 @@ internal static class Program ServerPackCommandsTests.Register(runner); DreamWeaveSkillsTests.Register(runner); DreamWeaveTests.Register(runner); + ServerWebOpenTests.Register(runner); return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index cd4e37a..67ccd9a 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -32,6 +32,8 @@ + + diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs new file mode 100644 index 0000000..acbeb10 --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -0,0 +1,49 @@ +using System; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// The web opener's pure part: which URLs a server plugin may open, and where the page goes. +internal static class ServerWebOpenTests +{ + public static void Register(Runner r) + { + r.Add("web open: only https on an allowed host, and the route follows the engine", Rules); + } + + private static readonly string[] Hosts = { "www.acdreamweave.com" }; + private static readonly string[] Wild = { "*.acdreamweave.com" }; + private const string Key = "dreamweave/0123456789abcdef0123456789abcdef"; + + private static void Rules() + { + Check.True(ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com/x", Hosts), "https on the host"); + Check.True(ServerWebOpen.IsAllowedUrl("https://WWW.AcDreamWeave.com/x", Hosts), "host case-insensitive"); + Check.True(!ServerWebOpen.IsAllowedUrl("http://www.acdreamweave.com/x", Hosts), "http refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://user@www.acdreamweave.com/x", Hosts), "userinfo refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com:444/x", Hosts), "other port refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com.evil.com/x", Hosts), "suffix host refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("javascript:alert(1)", Hosts), "javascript refused"); + Check.True(!ServerWebOpen.IsAllowedUrl(null, Hosts), "null refused"); + Check.True(!ServerWebOpen.IsAllowedUrl("/relative", Hosts), "relative refused"); + + Check.True(ServerWebOpen.IsAllowedUrl("https://wiki.acdreamweave.com/", Wild), "wildcard matches a subdomain"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://acdreamweave.com/", Wild), "wildcard excludes the bare domain"); + Check.True(!ServerWebOpen.IsAllowedUrl("https://evilacdreamweave.com/", Wild), "wildcard needs the dot"); + + Check.True(ServerWebOpen.IsValidProfileKey(Key), "dreamweave/ + 32 hex"); + Check.True(!ServerWebOpen.IsValidProfileKey("dreamweave/0123456789ABCDEF0123456789abcdef"), "uppercase refused"); + Check.True(!ServerWebOpen.IsValidProfileKey("../0123456789abcdef0123456789abcdef"), "dotdot refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(Key + "0"), "longer refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(""), "empty refused"); + Check.True(!ServerWebOpen.IsValidProfileKey(null), "null refused"); + + var ok = new WebOpenRequest("https://www.acdreamweave.com/x", Hosts, Key, "t"); + Check.Eq(ServerWebOpen.Route(ok, true), WebOpenRoute.Panel, "panel"); + Check.Eq(ServerWebOpen.Route(ok, false), WebOpenRoute.Browser, "no panel -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "" }, true), WebOpenRoute.Browser, "empty key -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "Bad/Key" }, true), WebOpenRoute.Browser, "bad key -> browser"); + Check.Eq(ServerWebOpen.Route(ok with { Url = "http://www.acdreamweave.com/x" }, true), WebOpenRoute.Refused, "bad url refused"); + } +} -- 2.43.0 From c085c16e1534c62a260485a20bcd149517d763b4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:38:48 -0800 Subject: [PATCH 04/29] ServerPack web open: fall back only before the panel navigates PanelResult + pure FallbackToBrowser; guard TryOpenPanel throws; guard done callbacks; hand ShellExecuteW the validated absolute URI. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 38 ++++++++++++------- Plugins/Shared/ServerPack/ServerWebOpen.cs | 19 ++++++++++ .../ServerWebOpenTests.cs | 7 ++++ 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index af3c95e..cabecd7 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -17,13 +17,14 @@ 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); - // Seams for the engine's web panel. + // Seam for the engine's web panel (a stub until the engine API is wired). private bool PanelAvailable => false; - private bool TryOpenPanel(WebOpenRequest r, out string error) + private PanelResult TryOpenPanel(WebOpenRequest r) => PanelResult.RefusedBeforeNavigate; + + private static void Finish(Action done, WebOpenOutcome outcome) { - error = "The web panel is not available."; - return false; + try { done(outcome); } catch { } } /// Opens the page (pump thread). `done` gets the route taken and a message without the URL. @@ -32,23 +33,35 @@ public sealed partial class ServerPackPlugin WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable); if (route == WebOpenRoute.Refused) { - done(new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); + Finish(done, new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened.")); return; } if (route == WebOpenRoute.Panel) { - if (TryOpenPanel(r, out string error)) + PanelResult result; + try { result = TryOpenPanel(r); } + catch (Exception) { result = PanelResult.RefusedBeforeNavigate; } + + if (result == PanelResult.Opened) { - done(new WebOpenOutcome(route, true, "Opened in the web panel.")); + Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel.")); return; } - // The panel failed: the browser is the fallback, and the report below says it was the browser. - LogTagged("web panel did not open: " + error); - route = WebOpenRoute.Browser; + if (!ServerWebOpen.FallbackToBrowser(result)) + { + LogTagged("web panel: " + result); + Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel couldn't open that page.")); + return; + } + LogTagged("web panel: " + result + ", using the browser"); } - string url = r.Url; + 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.")); + return; + } var thread = new Thread(() => { string message; @@ -64,7 +77,7 @@ public sealed partial class ServerPackPlugin ok = false; message = "Couldn't open your browser (code 0)."; } - done(new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); + Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); }) { IsBackground = true, @@ -73,7 +86,6 @@ public sealed partial class ServerPackPlugin thread.SetApartmentState(ApartmentState.STA); thread.Start(); } - /// Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired. internal void CloseWeb() { diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs index 2100a4d..7b0392c 100644 --- a/Plugins/Shared/ServerPack/ServerWebOpen.cs +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -12,6 +12,9 @@ internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedH internal enum WebOpenRoute { Panel, Browser, Refused } +/// What the engine's panel did. Only a refusal before navigating may fall back to the browser. +internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate } + /// What happened. The message never contains the URL. internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message); @@ -22,13 +25,25 @@ internal static class ServerWebOpen /// (OrdinalIgnoreCase). An entry "*.x" matches subdomains of x only, never x itself. /// public static bool IsAllowedUrl(string? url, IReadOnlyList allowedHosts) + => TryGetAllowedUri(url, allowedHosts, out _); + + /// The same check, giving the validated absolute URI (what the browser should be handed). + public static bool TryGetAllowedUri(string? url, IReadOnlyList allowedHosts, out string absoluteUri) { + absoluteUri = string.Empty; if (string.IsNullOrEmpty(url) || allowedHosts == null) return false; if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false; if (!string.Equals(uri.Scheme, "https", StringComparison.Ordinal)) return false; if (uri.UserInfo.Length != 0 || !uri.IsDefaultPort) return false; string host = uri.Host; if (host.Length == 0) return false; + if (!HostAllowed(host, allowedHosts)) return false; + absoluteUri = uri.AbsoluteUri; + return true; + } + + private static bool HostAllowed(string host, IReadOnlyList allowedHosts) + { foreach (string entry in allowedHosts) { @@ -49,6 +64,10 @@ internal static class ServerWebOpen return false; } + /// Fall back to the browser only when the panel refused before navigating. After a + /// navigate the one-time code is spent (a dead link), and UrlNotAllowed must not bypass the engine's list. + public static bool FallbackToBrowser(PanelResult r) => r == PanelResult.RefusedBeforeNavigate; + /// ^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token). public static bool IsValidProfileKey(string? key) { diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs index acbeb10..25ffd9e 100644 --- a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -45,5 +45,12 @@ internal static class ServerWebOpenTests Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "" }, true), WebOpenRoute.Browser, "empty key -> browser"); Check.Eq(ServerWebOpen.Route(ok with { ProfileKey = "Bad/Key" }, true), WebOpenRoute.Browser, "bad key -> browser"); Check.Eq(ServerWebOpen.Route(ok with { Url = "http://www.acdreamweave.com/x" }, true), WebOpenRoute.Refused, "bad url refused"); + + Check.True(ServerWebOpen.FallbackToBrowser(PanelResult.RefusedBeforeNavigate), "refused before navigate -> browser"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.Opened), "opened -> no browser"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.UrlNotAllowed), "engine allowlist is not bypassed"); + Check.True(!ServerWebOpen.FallbackToBrowser(PanelResult.FailedAfterNavigate), "spent code -> no browser"); + Check.True(ServerWebOpen.TryGetAllowedUri("https://www.acdreamweave.com/x?a=1", Hosts, out string abs) && abs == "https://www.acdreamweave.com/x?a=1", "validated absolute uri"); + Check.True(!ServerWebOpen.TryGetAllowedUri("http://www.acdreamweave.com/", Hosts, out string none) && none.Length == 0, "refused gives no uri"); } } -- 2.43.0 From 8ceba81070925174ffbd80d6988cb35746901045 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:46:37 -0800 Subject: [PATCH 05/29] ServerPack: ServerUsageLines, a server's own /rserver usage lines An optional hook, collected once in the constructor. ServerPackCommands.Usage appends a server's lines (trimmed, blanks dropped) after the shared two, and "/rserver help" and an unknown word print them all. A server without the hook prints exactly the two lines it always has (pinned on Coldeve). ServerProjectsTests.PluginsDir is internal so other tests can share it. Co-Authored-By: Claude Opus 5.5 --- .../Shared/ServerPack/ServerPackCommands.cs | 20 ++++++++++++++----- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 16 ++++++++++++--- .../ServerPackCommandsTests.cs | 20 +++++++++++++++++++ .../ServerProjectsTests.cs | 2 +- 4 files changed, 49 insertions(+), 9 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackCommands.cs b/Plugins/Shared/ServerPack/ServerPackCommands.cs index 8cdd6c0..d258f2f 100644 --- a/Plugins/Shared/ServerPack/ServerPackCommands.cs +++ b/Plugins/Shared/ServerPack/ServerPackCommands.cs @@ -46,12 +46,22 @@ internal static class ServerPackCommands /// "/rserver [show|hide|toggle]": the window after it. public static string Window(string serverName, bool shown) => CommandReply.Shown($"The {serverName} window", shown); - /// The usage, two lines. - public static string[] Usage(string serverName) => new[] + /// + /// The usage: two lines, then the server's own (ServerUsageLines), if any. With none, the two lines are + /// exactly what every server plugin has always printed. + /// + public static string[] Usage(string serverName, IReadOnlyList? serverLines = null) { - $"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).", - $"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.", - }; + var lines = new List + { + $"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).", + $"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.", + }; + if (serverLines != null) + foreach (string l in serverLines) + if (!string.IsNullOrWhiteSpace(l)) lines.Add(l.Trim()); + return lines.ToArray(); + } public static string Unknown(string word) => $"Unknown '/rserver {word}'."; } diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index d2f1a96..a30ac23 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -32,6 +32,7 @@ // SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other // plugins that apply a server rule without knowing the server. // ServerCommandVerbs(list) its own "/rserver " words, handled in ServerChatCommand. +// ServerUsageLines(add) the usage lines for those words, after the shared two (help, unknown word). // RunOnTick(action) work for the next tick (a page's button, on the render thread). // ServerCardActions() the server's own buttons at the top of its card, under RynthCore's verdict // (render thread: ImGui calls only; queue work with RunOnTick). @@ -87,6 +88,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase private readonly ConcurrentQueue _tickActions = new(); // The server's own "/rserver" verbs (ServerCommandVerbs). private readonly HashSet _serverVerbs = new(StringComparer.OrdinalIgnoreCase); + // The server's own "/rserver" usage lines (ServerUsageLines), after the shared two. + private readonly List _usageLines = new(); private volatile bool _loginComplete; private volatile string? _world; private bool _wasActive; @@ -104,6 +107,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase var verbs = new List(); ServerCommandVerbs(verbs); foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); + ServerUsageLines(_usageLines.Add); _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions); } @@ -135,6 +139,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// instead of being read as another server's id. Called once, from the constructor. /// partial void ServerCommandVerbs(List verbs); + /// + /// Usage lines for the server's own verbs, printed after the shared two by "/rserver help" and an + /// unknown word. Called once, from the constructor (no Host yet). + /// + partial void ServerUsageLines(Action add); /// Extra lines for "/rserver info". partial void ServerInfoLines(Action line); /// The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet). @@ -475,9 +484,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase bool handled = false; ServerChatCommand(parts, ref handled); if (handled) return; - if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + ServerPackCommands.Usage(Info.Name)[0]); - else ChatLine(ServerPackCommands.Usage(Info.Name)[0]); - ChatLine(ServerPackCommands.Usage(Info.Name)[1]); + string[] usage = ServerPackCommands.Usage(Info.Name, _usageLines); + if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + usage[0]); + else ChatLine(usage[0]); + for (int i = 1; i < usage.Length; i++) ChatLine(usage[i]); } private void PrintInfo() diff --git a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs index 7ab9644..7a50db9 100644 --- a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using RynthCore.Plugin.ServerPack; using RynthCore.Plugin.Shared; using RynthCore.RynthAiTests.Harness; @@ -50,6 +51,25 @@ internal static class ServerPackCommandsTests Check.Eq(usage.Length, 2, "two usage lines"); Check.True(usage[0].Contains("/rserver [show|hide|toggle]") && usage[1].Contains("/rserver auto|on|off"), "the usage names every verb"); Check.Eq(ServerPackCommands.Unknown("wobble"), "Unknown '/rserver wobble'.", "an unknown word"); + + // A server without ServerUsageLines (Coldeve) prints exactly the two shared lines, byte for byte. + string[] pinned = + { + "/rserver [show|hide|toggle] - the Coldeve server card (also in the Mini Remote's Char section).", + "/rserver info - what is known about Coldeve; /rserver auto|on|off - this character's override.", + }; + Check.Eq(string.Join("\n", usage), string.Join("\n", pinned), "hookless usage is unchanged"); + Check.Eq(string.Join("\n", ServerPackCommands.Usage("Coldeve", new List())), string.Join("\n", pinned), "no own lines: unchanged"); + Check.Eq(string.Join("\n", ServerPackCommands.Usage("Coldeve", new List { "", " " })), string.Join("\n", pinned), "blank own lines are dropped"); + string coldeve = string.Join("\n", System.IO.Directory.GetFiles(System.IO.Path.Combine(ServerProjectsTests.PluginsDir(), "RynthCore.Plugin.RynthColdeve"), "*.cs", System.IO.SearchOption.AllDirectories) + .Where(f => !f.Contains("\\obj\\") && !f.Contains("\\bin\\")).Select(System.IO.File.ReadAllText)); + Check.False(coldeve.Contains("ServerUsageLines", StringComparison.Ordinal), "Coldeve has no ServerUsageLines (so the pin above is what it prints)"); + + // A server's own lines follow the shared two, which stay first and unchanged. + string[] own = ServerPackCommands.Usage("Coldeve", new List { " /rserver x - one more line " }); + Check.Eq(own.Length, 3, "an own line is appended"); + Check.Eq(own[2], "/rserver x - one more line", "trimmed"); + Check.True(own[0] == pinned[0] && own[1] == pinned[1], "the shared two come first, unchanged"); } private static void Queue() diff --git a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs index 621b92c..7e8468b 100644 --- a/Tools/RynthServerPack.Tests/ServerProjectsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerProjectsTests.cs @@ -35,7 +35,7 @@ internal static class ServerProjectsTests "levistras", }; - private static string PluginsDir() + internal static string PluginsDir() { string? dir = AppContext.BaseDirectory; while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) -- 2.43.0 From 8dda4fdf96e512d0239415dd2d7292ae848a87fd Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:45:18 -0800 Subject: [PATCH 06/29] ServerPack web open: a request never prints its URL; Windows error wording WebOpenRequest is a record, so its generated ToString printed the URL, which can carry a one-time code. It now names the title only. The browser failure reads "Couldn't open your browser (Windows error N)." Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 4 ++-- Plugins/Shared/ServerPack/ServerWebOpen.cs | 10 ++++++++-- .../RynthServerPack.Tests/ServerWebOpenTests.cs | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index cabecd7..d2ee718 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -70,12 +70,12 @@ public sealed partial class ServerPackPlugin { long code = ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1).ToInt64(); ok = code > 32; - message = ok ? "Opened in your browser." : $"Couldn't open your browser (code {code})."; + message = ok ? "Opened in your browser." : $"Couldn't open your browser (Windows error {code})."; } catch (Exception) { ok = false; - message = "Couldn't open your browser (code 0)."; + message = "Couldn't open your browser (Windows error 0)."; } Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, ok, message)); }) diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs index 7b0392c..760c526 100644 --- a/Plugins/Shared/ServerPack/ServerWebOpen.cs +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -7,8 +7,14 @@ using System.Collections.Generic; namespace RynthCore.Plugin.ServerPack; -/// A page to open. The URL comes from constants in the plugin, never from chat. -internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title); +/// +/// A page to open. The URL comes from constants in the plugin, never from chat, but it may carry a +/// one-time code, so ToString names the title only (a record's generated ToString would print the URL). +/// +internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedHosts, string ProfileKey, string Title) +{ + public override string ToString() => "WebOpenRequest(" + Title + ")"; +} internal enum WebOpenRoute { Panel, Browser, Refused } diff --git a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs index 25ffd9e..a17c88f 100644 --- a/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs +++ b/Tools/RynthServerPack.Tests/ServerWebOpenTests.cs @@ -10,12 +10,28 @@ internal static class ServerWebOpenTests public static void Register(Runner r) { r.Add("web open: only https on an allowed host, and the route follows the engine", Rules); + r.Add("web open: a request never prints its URL, and the browser's error says Windows", NoUrlInText); } private static readonly string[] Hosts = { "www.acdreamweave.com" }; private static readonly string[] Wild = { "*.acdreamweave.com" }; private const string Key = "dreamweave/0123456789abcdef0123456789abcdef"; + private static void NoUrlInText() + { + const string secret = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; + var r = new WebOpenRequest("https://www.acdreamweave.com/launch?code=" + secret + "&to=%2Fmarket", Hosts, Key, "DreamWeave"); + Check.Eq(r.ToString(), "WebOpenRequest(DreamWeave)", "ToString names the title only"); + Check.False(r.ToString().Contains(secret, StringComparison.Ordinal), "ToString never carries the code"); + Check.False(("" + r).Contains("acdreamweave", StringComparison.Ordinal), "nor the URL"); + Check.False((r with { Title = "x" }).ToString().Contains(secret, StringComparison.Ordinal), "a copy neither"); + + string web = System.IO.File.ReadAllText(System.IO.Path.Combine(ServerProjectsTests.PluginsDir(), "Shared", "ServerPack", "ServerPackWeb.cs")); + Check.True(web.Contains("$\"Couldn't open your browser (Windows error {code}).\"", StringComparison.Ordinal), "the browser failure names the Windows error"); + Check.True(web.Contains("\"Couldn't open your browser (Windows error 0).\"", StringComparison.Ordinal), "and its exception path"); + Check.False(web.Contains("(code ", StringComparison.Ordinal), "the old \"(code N)\" wording is gone"); + } + private static void Rules() { Check.True(ServerWebOpen.IsAllowedUrl("https://www.acdreamweave.com/x", Hosts), "https on the host"); -- 2.43.0 From fbd6458a0f2c1f9132d8012a2f83414037963e8f Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:41:13 -0800 Subject: [PATCH 07/29] RynthDreamWeave: web destinations and the launch reply's wire text DreamWeaveWeb (constants-only destinations and launch URL) and LaunchWire (/weblogin request, [WEB] reply parser that refuses player-authored copies). Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 38 +++++ .../DreamWeave/LaunchWire.cs | 53 +++++++ .../DreamWeaveWebTests.cs | 130 ++++++++++++++++++ Tools/RynthServerPack.Tests/Program.cs | 1 + .../RynthServerPack.Tests.csproj | 3 + 5 files changed, 225 insertions(+) create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs create mode 100644 Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs new file mode 100644 index 0000000..6e8ce44 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -0,0 +1,38 @@ +// DreamWeave's website destinations: where each button goes. The host and the paths are constants +// (the site's registry: dreamweave-market Source/ACE.Market/Site/SiteTools.cs and HostRouting.cs); +// nothing here is ever read from chat. Pure, so RynthServerPack.Tests compiles it directly. +using System; + +namespace RynthCore.Plugin.RynthDreamWeave; + +/// One website page a DreamWeave button opens. +internal sealed record WebDestination(string Id, string Label, string Path, string Tooltip); + +internal static class DreamWeaveWeb +{ + public const string SiteBase = "https://www.acdreamweave.com"; + + /// The only host the panel or the browser may be sent to. + public static readonly string[] AllowedHosts = { "www.acdreamweave.com" }; + + public const string PanelTitle = "DreamWeave"; + + public static readonly WebDestination[] Destinations = + { + new("market", "Market", "/market", "The player market, logged in as this account."), + new("suit", "Suit Builder", "/tools/suit", "Plan a suit from this account's characters."), + new("abilities", "Ability Planner", "/tools/abilities", "Plan a class ability build."), + }; + + public static WebDestination? ById(string? id) + { + if (string.IsNullOrEmpty(id)) return null; + foreach (WebDestination d in Destinations) + if (string.Equals(d.Id, id, StringComparison.OrdinalIgnoreCase)) return d; + return null; + } + + /// The sign-in URL for a destination. The caller has already checked the code with LaunchWire. + public static string LaunchUrl(string code, WebDestination d) + => SiteBase + "/launch?code=" + code + "&to=" + Uri.EscapeDataString(d.Path); +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs new file mode 100644 index 0000000..90b2e20 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs @@ -0,0 +1,53 @@ +// The wire text of DreamWeave's website sign-in: the "/weblogin" request and ACE's reply line. +// The code comes from chat; nothing else does. The line that carries it is eaten by the caller +// and the code is never logged, saved or chatted. +// Success: "[WEB] Launch code: <43 chars A-Za-z0-9_-> (single use, expires in 60 seconds)". +// Any other "[WEB] " line is a refusal worded for the player. +using System; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal static class LaunchWire +{ + public const string RequestCommand = "/weblogin"; + public const string ReplyLead = "[WEB] "; + public const string SuccessLead = "[WEB] Launch code: "; + public const int CodeLength = 43; + public const long ReplyTimeoutMs = 10_000, MinIntervalMs = 3_000; + + /// The chat line to send for a destination. One place to add an argument later. + public static string RequestFor(WebDestination d) => RequestCommand; + + public static bool IsCodeChar(char c) + => (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_'; + + /// + /// True when is a [WEB] reply from the server: then either + /// is set (success) or is (a refusal). + /// False for anything else, and for a player's copy of the line. A line that starts like a + /// success but whose code is malformed is false, never a refusal and never a code. + /// + public static bool TryParse(string? text, int chatType, out string code, out string refusal) + { + code = ""; + refusal = ""; + if (text == null || ChatSource.IsPlayerAuthored(chatType)) return false; + if (!ChatSource.StartsWithMarker(text, ReplyLead)) return false; + + int start = ChatSource.ContentStart(text); + ReadOnlySpan line = text.AsSpan(start); + if (line.StartsWith(SuccessLead.AsSpan(), StringComparison.Ordinal)) + { + ReadOnlySpan rest = line.Slice(SuccessLead.Length); + if (rest.Length <= CodeLength || rest[CodeLength] != ' ') return false; + for (int i = 0; i < CodeLength; i++) + if (!IsCodeChar(rest[i])) return false; + code = rest.Slice(0, CodeLength).ToString(); + return true; + } + + refusal = line.Slice(ReplyLead.Length).ToString(); + return true; + } +} diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs new file mode 100644 index 0000000..eeb81b1 --- /dev/null +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Xml.Linq; +using RynthCore.Plugin.RynthDreamWeave; +using RynthCore.Plugin.ServerPack; +using RynthCore.RynthAiTests.Harness; + +namespace RynthServerPack.Tests; + +// DreamWeave's web buttons, the pure part: the destinations and the "/weblogin" reply's wire text. +internal static class DreamWeaveWebTests +{ + public static void Register(Runner r) + { + r.Add("dreamweave web: a player's copy of the launch line is never taken", PlayerCopy); + r.Add("dreamweave web: the launch URL is built from constants and a clean code", UrlFromConstants); + r.Add("dreamweave web: destination ids are verbs no one else uses", IdsAreFree); + r.Add("dreamweave web: ACE's refusals parse as refusals, other lines are ignored", Refusals); + } + + private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars + private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; + + private static bool Parse(string? text, int type, out string code, out string refusal) + => LaunchWire.TryParse(text, type, out code, out refusal); + + private static void PlayerCopy() + { + Check.Eq(Code.Length, LaunchWire.CodeLength, "fixture code is 43 chars"); + + foreach (int type in new[] { 0x02, 0x03, 0x08, 0x0C, 0x13 }) + Check.True(!Parse(Line, type, out _, out _), "player-authored chat type 0x" + type.ToString("X2") + " refused"); + + Check.True(!Parse("Bob tells you, " + Line, 0x05, out _, out _), "a tell wrapper with a system type refused"); + Check.True(!Parse("hello " + Line, 0x05, out _, out _), "the lead mid-line refused"); + + Check.True(Parse(Line, 0x05, out string code, out string refusal), "valid line, system type"); + Check.Eq(code, Code, "the code"); + Check.Eq(refusal, "", "no refusal on success"); + Check.True(Parse(Line, -1, out code, out _), "unknown type: the anchor alone protects"); + Check.Eq(code, Code, "the code (type -1)"); + Check.True(!Parse(null, 0x05, out _, out _), "null refused"); + Check.True(!Parse("", 0x05, out _, out _), "empty refused"); + } + + private static void UrlFromConstants() + { + string head = "[WEB] Launch code: "; + Check.True(!Parse(head + Code.Substring(1) + " (single use)", 0x05, out _, out _), "42-char code refused"); + Check.True(!Parse(head + Code + "A (single use)", 0x05, out _, out _), "44-char run (no space after 43) refused"); + Check.True(!Parse(head + Code + "&to=//evil.com", 0x05, out _, out _), "code followed by &to= refused"); + Check.True(!Parse(head + Code, 0x05, out _, out _), "no trailing space refused"); + Check.True(!Parse(head + Code.Substring(0, 42) + "! (single use)", 0x05, out _, out _), "bad code char refused"); + Check.True(!Parse(head + Code.Substring(0, 42) + "% (single use)", 0x05, out _, out _), "percent in code refused"); + + // None of the malformed success lines may leak out as a refusal either. + Check.True(!Parse(head + Code.Substring(1) + " x", 0x05, out _, out string r1) && r1 == "", "malformed success is not a refusal"); + + WebDestination suit = DreamWeaveWeb.ById("suit")!; + string url = DreamWeaveWeb.LaunchUrl(Code, suit); + Check.True(url.StartsWith(DreamWeaveWeb.SiteBase + "/launch?code=", StringComparison.Ordinal), "url starts with the base"); + Check.Eq(url, DreamWeaveWeb.SiteBase + "/launch?code=" + Code + "&to=%2Ftools%2Fsuit", "exact suit url"); + Check.True(url.EndsWith("%2Ftools%2Fsuit", StringComparison.Ordinal), "ends with the escaped path"); + Check.Eq(url.Split("&to=").Length - 1, 1, "exactly one &to="); + + foreach (WebDestination d in DreamWeaveWeb.Destinations) + { + string u = DreamWeaveWeb.LaunchUrl(Code, d); + Check.True(ServerWebOpen.IsAllowedUrl(u, DreamWeaveWeb.AllowedHosts), d.Id + ": url passes the allowlist"); + Check.True(d.Path.StartsWith("/", StringComparison.Ordinal) && !d.Path.StartsWith("//", StringComparison.Ordinal), d.Id + ": path is rooted, not //"); + Check.True(d.Path.IndexOfAny(new[] { '?', '#', '\\' }) < 0, d.Id + ": no ? # or backslash in path"); + Check.True(d.Label.Length > 0 && d.Tooltip.Length > 0, d.Id + ": label and tooltip"); + } + Check.True(DreamWeaveWeb.ById("SUIT") == suit, "ById is case-insensitive"); + Check.True(DreamWeaveWeb.ById("nope") == null && DreamWeaveWeb.ById(null) == null && DreamWeaveWeb.ById("") == null, "unknown id -> null"); + Check.Eq(LaunchWire.RequestFor(suit), "/weblogin", "request is /weblogin"); + } + + private static void IdsAreFree() + { + var seen = new HashSet(); + string[] serverIds = ServerPluginIds(); + Check.True(serverIds.Length > 0, "found the server plugin ids"); + foreach (WebDestination d in DreamWeaveWeb.Destinations) + { + Check.True(d.Id.Length >= 1 && d.Id.Length <= 16 && d.Id.All(c => c >= 'a' && c <= 'z'), d.Id + ": 1-16 chars [a-z]"); + Check.True(Array.IndexOf(ServerPackCommands.SharedVerbs, d.Id) < 0, d.Id + ": not a shared verb"); + Check.True(Array.IndexOf(serverIds, d.Id) < 0, d.Id + ": not a server plugin id"); + Check.True(seen.Add(d.Id), d.Id + ": unique"); + } + } + + private static void Refusals() + { + string[] lines = + { + "[WEB] Signing in to the website from the game is turned off on this server.", + "[WEB] The website sign-in service is not available right now.", + "[WEB] You are requesting website sign-in codes too quickly. Wait a minute and try again.", + }; + foreach (string l in lines) + { + Check.True(Parse(l, 0x05, out string code, out string refusal), "refusal parses: " + l); + Check.Eq(code, "", "no code in a refusal"); + Check.Eq(refusal, l.Substring(LaunchWire.ReplyLead.Length), "refusal text after the lead"); + Check.True(!Parse(l, 0x02, out _, out _), "a player's copy of a refusal is ignored"); + } + Check.True(!Parse("You say, \"hi\"", 0x05, out _, out _), "other chat ignored"); + Check.True(!Parse("[WEBX] Launch code: " + Code, 0x05, out _, out _), "lookalike lead ignored"); + } + + private static string[] ServerPluginIds() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); + var ids = new List(); + foreach (string p in Directory.GetDirectories(Path.Combine(dir, "Plugins"), "RynthCore.Plugin.Rynth*")) + { + string csproj = Path.Combine(p, Path.GetFileName(p) + ".csproj"); + if (!File.Exists(csproj)) continue; + string id = XDocument.Load(csproj).Descendants("RynthPluginServerId").FirstOrDefault()?.Value.Trim() ?? ""; + if (id.Length > 0) ids.Add(id); + } + return ids.ToArray(); + } +} diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 88e690e..36323eb 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -23,6 +23,7 @@ internal static class Program DreamWeaveSkillsTests.Register(runner); DreamWeaveTests.Register(runner); ServerWebOpenTests.Register(runner); + DreamWeaveWebTests.Register(runner); return runner.Run("RynthServerPack tests", args.Length > 0 ? args[0] : null); } } diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index 67ccd9a..a0fc97d 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -34,6 +34,9 @@ + + + -- 2.43.0 From 5e732cecb70379e306483c3e80cfa9f64cd62d82 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:44:41 -0800 Subject: [PATCH 08/29] RynthDreamWeave: link ChatSource into the plugin, strict alphabet tests, harden the launch stem The plugin project did not compile (ChatSource not linked). LaunchWire now treats any line starting with the success stem as success-shaped: malformed, it is dropped, never returned as refusal text. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/LaunchWire.cs | 5 ++- .../RynthCore.Plugin.RynthDreamWeave.csproj | 5 +++ .../DreamWeaveWebTests.cs | 39 +++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs index 90b2e20..b0fea6d 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs @@ -13,6 +13,8 @@ internal static class LaunchWire public const string RequestCommand = "/weblogin"; public const string ReplyLead = "[WEB] "; public const string SuccessLead = "[WEB] Launch code: "; + /// Any line starting like this has the success shape: malformed, it is dropped, never shown as a refusal. + private const string SuccessStem = "[WEB] Launch code"; public const int CodeLength = 43; public const long ReplyTimeoutMs = 10_000, MinIntervalMs = 3_000; @@ -37,8 +39,9 @@ internal static class LaunchWire int start = ChatSource.ContentStart(text); ReadOnlySpan line = text.AsSpan(start); - if (line.StartsWith(SuccessLead.AsSpan(), StringComparison.Ordinal)) + if (line.StartsWith(SuccessStem.AsSpan(), StringComparison.Ordinal)) { + if (!line.StartsWith(SuccessLead.AsSpan(), StringComparison.Ordinal)) return false; ReadOnlySpan rest = line.Slice(SuccessLead.Length); if (rest.Length <= CodeLength || rest[CodeLength] != ' ') return false; for (int i = 0; i < CodeLength; i++) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index a80a980..854d7fe 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -13,6 +13,11 @@ DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. + + + + + diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index eeb81b1..509412a 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -17,6 +17,7 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: a player's copy of the launch line is never taken", PlayerCopy); r.Add("dreamweave web: the launch URL is built from constants and a clean code", UrlFromConstants); r.Add("dreamweave web: destination ids are verbs no one else uses", IdsAreFree); + r.Add("dreamweave web: LaunchWire: code alphabet is strict", Alphabet); r.Add("dreamweave web: ACE's refusals parse as refusals, other lines are ignored", Refusals); } @@ -92,6 +93,44 @@ internal static class DreamWeaveWebTests } } + private static void Alphabet() + { + const string b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + Check.Eq(b64.Length, 64, "64 base64url chars"); + foreach (char c in b64) + Check.True(LaunchWire.IsCodeChar(c), "accepted: " + c); + + char[] bad = { '+', '/', '=', '&', '?', '#', '%', '.', ' ', '\t', '!', '~', '\u00e9', '\u0000' }; + foreach (char c in bad) + { + string name = "U+" + ((int)c).ToString("X4"); + Check.True(!LaunchWire.IsCodeChar(c), "IsCodeChar rejects " + name); + foreach (int idx in new[] { 0, 21, 42 }) + { + char[] chars = Code.ToCharArray(); + chars[idx] = c; + string line = "[WEB] Launch code: " + new string(chars) + " (single use, expires in 60 seconds)"; + Check.True(!Parse(line, 0x05, out string code, out string refusal), "refused: " + name + " at " + idx); + Check.Eq(code, "", "no code: " + name + " at " + idx); + Check.Eq(refusal, "", "no refusal: " + name + " at " + idx); + } + } + + // Round trip of a code holding both '-' and '_'. + string dashed = "-_" + Code.Substring(2); + Check.True(Parse("[WEB] Launch code: " + dashed + " (single use, expires in 60 seconds)", 0x05, out string got, out _), "dash/underscore code parses"); + Check.Eq(got, dashed, "dash/underscore code intact"); + Check.True(DreamWeaveWeb.LaunchUrl(got, DreamWeaveWeb.ById("market")!).Contains("code=" + dashed + "&to=", StringComparison.Ordinal), "url carries the code verbatim"); + + // The stem alone marks the success shape: malformed, it is dropped, never a refusal. + foreach (string l in new[] { "[WEB] Launch code:" + Code, "[WEB] Launch code " + Code, "[WEB] Launch code", "[WEB] Launch codes " + Code }) + { + Check.True(!Parse(l, 0x05, out string c2, out string r2), "malformed success-shaped line dropped: " + l); + Check.Eq(c2, "", "no code: " + l); + Check.Eq(r2, "", "no refusal text: " + l); + } + } + private static void Refusals() { string[] lines = -- 2.43.0 From 1eb8bf1e8aad474d2a1583210541abeca6507c8a Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:47:57 -0800 Subject: [PATCH 09/29] RynthDreamWeave: launch request state Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebLauncher.cs | 90 +++++++++++++++++ .../DreamWeaveWebTests.cs | 99 ++++++++++++++++++- .../RynthServerPack.Tests.csproj | 1 + 3 files changed, 189 insertions(+), 1 deletion(-) create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs new file mode 100644 index 0000000..56d70f6 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -0,0 +1,90 @@ +// The launch request state machine for the website buttons: one "/weblogin" at a time, a 10 s +// reply window, and a status line for the card. Pure (no engine calls), so RynthServerPack.Tests +// compiles it directly. The code is handed to the caller through OnChatLine and goes nowhere +// else: never into Status, never into the message, never into a field. +using System; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal enum LaunchBegin { Started, Busy, TooSoon } +internal enum LaunchLine { NotOurs, Code, Refused } + +internal sealed class WebLauncher +{ + /// Held by the chat pump and the render thread around every call. + public readonly object Gate = new(); + + private WebDestination? _pending; + private long _deadlineMs; + private long _lastBeginMs; + private bool _everBegun; + + public WebDestination? Pending => _pending; + public string Status { get; private set; } = ""; + + /// Busy while a request is pending (checked first); else TooSoon within MinIntervalMs of the last Begin. + public LaunchBegin Begin(WebDestination d, long nowMs) + { + if (_pending != null) return LaunchBegin.Busy; + if (_everBegun && nowMs - _lastBeginMs < LaunchWire.MinIntervalMs) return LaunchBegin.TooSoon; + _pending = d; + _everBegun = true; + _lastBeginMs = nowMs; + _deadlineMs = nowMs + LaunchWire.ReplyTimeoutMs; + Status = "Asking DreamWeave for a login code for " + d.Label + "..."; + return LaunchBegin.Started; + } + + /// The send failed: nothing was asked, so nothing is pending. + public void Cancel(string status) + { + _pending = null; + Status = status; + } + + /// + /// NotOurs unless a request is pending and the deadline has not passed. Code and Refused clear + /// Pending and the caller eats the line. On Code, is empty and the + /// code is only in . + /// + public LaunchLine OnChatLine(string text, int chatType, long nowMs, out WebDestination? dest, out string code, out string message) + { + dest = null; + code = ""; + message = ""; + WebDestination? p = _pending; + if (p == null || nowMs >= _deadlineMs) return LaunchLine.NotOurs; + if (!LaunchWire.TryParse(text, chatType, out string parsedCode, out string refusal)) return LaunchLine.NotOurs; + + _pending = null; + dest = p; + if (parsedCode.Length > 0) + { + code = parsedCode; + Status = "Opening " + p.Label + "..."; + return LaunchLine.Code; + } + message = refusal; + Status = p.Label + ": DreamWeave said: " + refusal; + return LaunchLine.Refused; + } + + /// The pending destination once, at or after Begin + ReplyTimeoutMs; null otherwise. + public WebDestination? TakeTimedOut(long nowMs) + { + WebDestination? p = _pending; + if (p == null || nowMs < _deadlineMs) return null; + _pending = null; + Status = "No reply from DreamWeave to " + LaunchWire.RequestCommand + " within " + + (LaunchWire.ReplyTimeoutMs / 1000) + " s, so nothing was opened."; + return p; + } + + /// Login/logout: forget the request and the status. + public void Reset() + { + _pending = null; + Status = ""; + _everBegun = false; + } +} \ No newline at end of file diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 509412a..5585fc0 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -19,8 +19,10 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: destination ids are verbs no one else uses", IdsAreFree); r.Add("dreamweave web: LaunchWire: code alphabet is strict", Alphabet); r.Add("dreamweave web: ACE's refusals parse as refusals, other lines are ignored", Refusals); + r.Add("dreamweave web: replies count only while asked, once", RepliesOnlyWhileAsked); + r.Add("dreamweave web: one request at a time, never stuck", OneAtATime); + r.Add("dreamweave web: the code never reaches a status or message", CodeNeverInStatus); } - private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; @@ -150,6 +152,101 @@ internal static class DreamWeaveWebTests Check.True(!Parse("[WEBX] Launch code: " + Code, 0x05, out _, out _), "lookalike lead ignored"); } + private static WebDestination Market => DreamWeaveWeb.ById("market")!; + + private static void RepliesOnlyWhileAsked() + { + var w = new WebLauncher(); + Check.True(w.OnChatLine(Line, 0x05, 0, out _, out _, out _) == LaunchLine.NotOurs, "nothing pending: not ours"); + + Check.True(w.Begin(Market, 1000) == LaunchBegin.Started, "begin"); + Check.Eq(w.Status, "Asking DreamWeave for a login code for Market...", "asking status"); + var k = w.OnChatLine(Line, 0x05, 1000 + 9_999, out var dest, out string code, out string msg); + Check.True(k == LaunchLine.Code, "line at +9,999 ms is the code"); + Check.Eq(code, Code, "the code"); + Check.Eq(msg, "", "no message on a code"); + Check.True(ReferenceEquals(dest, Market), "destination handed back"); + Check.True(w.Pending == null, "code clears pending"); + Check.True(w.OnChatLine(Line, 0x05, 1000 + 9_999, out dest, out code, out msg) == LaunchLine.NotOurs, "an identical second line is not ours"); + Check.True(dest == null && code == "" && msg == "", "no outputs on NotOurs"); + + // Timeout at exactly +10,000. + var t = new WebLauncher(); + t.Begin(Market, 50_000); + Check.True(t.OnChatLine(Line, 0x05, 60_000, out _, out _, out _) == LaunchLine.NotOurs, "line at +10,000 ms is late"); + Check.True(t.TakeTimedOut(59_999) == null, "not timed out at +9,999"); + Check.True(ReferenceEquals(t.TakeTimedOut(60_000), Market), "timed out once at +10,000"); + Check.True(t.TakeTimedOut(60_001) == null, "and only once"); + Check.True(t.Pending == null, "timeout clears pending"); + Check.Eq(t.Status, "No reply from DreamWeave to /weblogin within 10 s, so nothing was opened.", "timeout status"); + + // Refusal clears pending. + var f = new WebLauncher(); + f.Begin(Market, 0); + string refusal = "[WEB] The website sign-in service is not available right now."; + Check.True(f.OnChatLine(refusal, 0x05, 10, out dest, out code, out msg) == LaunchLine.Refused, "refusal"); + Check.Eq(msg, "The website sign-in service is not available right now.", "refusal message"); + Check.Eq(code, "", "no code on refusal"); + Check.Eq(f.Status, "Market: DreamWeave said: The website sign-in service is not available right now.", "refusal status"); + Check.True(f.Pending == null, "refusal clears pending"); + + // A player's copy and unrelated chat leave the request pending. + var p = new WebLauncher(); + p.Begin(Market, 0); + Check.True(p.OnChatLine(Line, 0x02, 5, out _, out _, out _) == LaunchLine.NotOurs, "player copy not ours"); + Check.True(p.OnChatLine("You say, \"hi\"", 0x05, 5, out _, out _, out _) == LaunchLine.NotOurs, "other chat not ours"); + Check.True(p.Pending != null, "still pending"); + + // Reset clears pending and status. + p.Reset(); + Check.True(p.Pending == null, "reset clears pending"); + Check.Eq(p.Status, "", "reset clears status"); + Check.True(p.OnChatLine(Line, 0x05, 5, out _, out _, out _) == LaunchLine.NotOurs, "after reset: not ours"); + } + + private static void OneAtATime() + { + var w = new WebLauncher(); + Check.True(w.Begin(Market, 100_000) == LaunchBegin.Started, "first begin"); + Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 100_001) == LaunchBegin.Busy, "second while pending: busy"); + Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 100_000 + 5_000) == LaunchBegin.Busy, "busy wins over too-soon/free"); + Check.True(ReferenceEquals(w.Pending, Market), "first request still the pending one"); + + w.Cancel("Could not send /weblogin."); + Check.True(w.Pending == null, "cancel clears pending"); + Check.Eq(w.Status, "Could not send /weblogin.", "cancel status"); + Check.True(w.Begin(Market, 100_000 + 2_999) == LaunchBegin.TooSoon, "within 3 s of the last begin: too soon"); + Check.True(w.Pending == null, "too soon starts nothing"); + Check.True(w.Begin(Market, 100_000 + 3_000) == LaunchBegin.Started, "at 3 s: started"); + + // Never stuck: a timeout frees the slot. + Check.True(w.TakeTimedOut(103_000 + 10_000) != null, "timeout"); + Check.True(w.Begin(Market, 113_000) == LaunchBegin.Started, "begin after timeout"); + } + + private static void CodeNeverInStatus() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + Check.True(!w.Status.Contains(Code), "status while asking"); + var k = w.OnChatLine(Line, 0x05, 100, out _, out string code, out string msg); + Check.True(k == LaunchLine.Code, "code flow"); + Check.Eq(code.Length, 43, "43-char code returned"); + Check.True(!w.Status.Contains(Code), "status after code"); + Check.True(!msg.Contains(Code), "message after code"); + Check.True(!w.Status.Contains(code.Substring(0, 12)), "no code fragment in status"); + + // Timeout and refusal paths too. + var t = new WebLauncher(); + t.Begin(Market, 0); + t.TakeTimedOut(10_000); + Check.True(!t.Status.Contains(Code), "timeout status"); + var f = new WebLauncher(); + f.Begin(Market, 0); + f.OnChatLine("[WEB] nope", 0x05, 1, out _, out _, out msg); + Check.True(!f.Status.Contains(Code) && !msg.Contains(Code), "refusal status and message"); + } + private static string[] ServerPluginIds() { string? dir = AppContext.BaseDirectory; diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index a0fc97d..1fb19fa 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -37,6 +37,7 @@ + -- 2.43.0 From c03a38a3e850b46f32775d1bf60ba8dbdae41948 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:52:07 -0800 Subject: [PATCH 10/29] RynthDreamWeave: launch state review fixes Code-shaped refusals are replaced, self-expiry in Begin, Reset keeps the throttle, late valid codes are eaten as Stale within the code lifetime, thread contract documented. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/LaunchWire.cs | 2 + .../DreamWeave/WebLauncher.cs | 77 ++++++++++++---- .../DreamWeaveWebTests.cs | 89 ++++++++++++++++++- 3 files changed, 151 insertions(+), 17 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs index b0fea6d..aba5a34 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs @@ -17,6 +17,8 @@ internal static class LaunchWire private const string SuccessStem = "[WEB] Launch code"; public const int CodeLength = 43; public const long ReplyTimeoutMs = 10_000, MinIntervalMs = 3_000; + /// How long a code stays valid server-side: a code arriving this long after the reply deadline is still eaten, never opened. + public const long CodeLifetimeMs = 60_000; /// The chat line to send for a destination. One place to add an argument later. public static string RequestFor(WebDestination d) => RequestCommand; diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 56d70f6..9150cec 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -7,30 +7,46 @@ using System; namespace RynthCore.Plugin.RynthDreamWeave; internal enum LaunchBegin { Started, Busy, TooSoon } -internal enum LaunchLine { NotOurs, Code, Refused } +internal enum LaunchLine { NotOurs, Code, Refused, Stale } +/// +/// Not thread-safe. Every member, including the Pending and Status getters, must be called under +/// lock (Gate). The callers are the chat pump, the tick thread and the render thread. Hold +/// the lock only around calls into this class, never around Send or ShellExecute. nowMs must come +/// from one monotonic clock (Environment.TickCount64). After a Code reply, Status reads +/// "Opening X..."; if the open then fails, the caller must overwrite Status. +/// internal sealed class WebLauncher { - /// Held by the chat pump and the render thread around every call. public readonly object Gate = new(); + private const string UnexpectedReply = "DreamWeave sent an unexpected reply."; + private WebDestination? _pending; private long _deadlineMs; private long _lastBeginMs; private bool _everBegun; + // A request that expired: its late code is eaten (Stale) until the code itself would have expired. + private bool _expired; + private long _expiredDeadlineMs; public WebDestination? Pending => _pending; public string Status { get; private set; } = ""; - /// Busy while a request is pending (checked first); else TooSoon within MinIntervalMs of the last Begin. + /// + /// A pending request already past its deadline is expired here first. Then: Busy while a request + /// is pending; else TooSoon within MinIntervalMs of the last Begin; else Started. + /// public LaunchBegin Begin(WebDestination d, long nowMs) { + if (_pending != null && nowMs >= _deadlineMs) Expire(); if (_pending != null) return LaunchBegin.Busy; if (_everBegun && nowMs - _lastBeginMs < LaunchWire.MinIntervalMs) return LaunchBegin.TooSoon; _pending = d; _everBegun = true; _lastBeginMs = nowMs; _deadlineMs = nowMs + LaunchWire.ReplyTimeoutMs; + _expired = false; Status = "Asking DreamWeave for a login code for " + d.Label + "..."; return LaunchBegin.Started; } @@ -43,19 +59,30 @@ internal sealed class WebLauncher } /// - /// NotOurs unless a request is pending and the deadline has not passed. Code and Refused clear - /// Pending and the caller eats the line. On Code, is empty and the - /// code is only in . + /// NotOurs unless a request is pending, or expired within the code's lifetime. Before the + /// deadline, Code and Refused clear Pending and the caller eats the line. After the deadline, + /// a valid code is Stale (eat it, open nothing; dest null, code empty) until CodeLifetimeMs + /// past the deadline; any other line is NotOurs. On Code, message is empty. /// public LaunchLine OnChatLine(string text, int chatType, long nowMs, out WebDestination? dest, out string code, out string message) { dest = null; code = ""; message = ""; - WebDestination? p = _pending; - if (p == null || nowMs >= _deadlineMs) return LaunchLine.NotOurs; + long deadline; + if (_pending != null) deadline = _deadlineMs; + else if (_expired) deadline = _expiredDeadlineMs; + else return LaunchLine.NotOurs; + if (!LaunchWire.TryParse(text, chatType, out string parsedCode, out string refusal)) return LaunchLine.NotOurs; + if (nowMs >= deadline) + { + if (parsedCode.Length > 0 && nowMs < deadline + LaunchWire.CodeLifetimeMs) return LaunchLine.Stale; + return LaunchLine.NotOurs; + } + + WebDestination p = _pending!; _pending = null; dest = p; if (parsedCode.Length > 0) @@ -64,8 +91,8 @@ internal sealed class WebLauncher Status = "Opening " + p.Label + "..."; return LaunchLine.Code; } - message = refusal; - Status = p.Label + ": DreamWeave said: " + refusal; + message = HasCodeRun(refusal) ? UnexpectedReply : refusal; + Status = p.Label + ": DreamWeave said: " + message; return LaunchLine.Refused; } @@ -74,17 +101,35 @@ internal sealed class WebLauncher { WebDestination? p = _pending; if (p == null || nowMs < _deadlineMs) return null; - _pending = null; - Status = "No reply from DreamWeave to " + LaunchWire.RequestCommand + " within " - + (LaunchWire.ReplyTimeoutMs / 1000) + " s, so nothing was opened."; + Expire(); return p; } - /// Login/logout: forget the request and the status. + /// Login/logout: forget the pending request and the status. The throttle survives. public void Reset() { _pending = null; Status = ""; - _everBegun = false; } -} \ No newline at end of file + + private void Expire() + { + _pending = null; + _expired = true; + _expiredDeadlineMs = _deadlineMs; + Status = "No reply from DreamWeave to " + LaunchWire.RequestCommand + " within " + + (LaunchWire.ReplyTimeoutMs / 1000) + " s, so nothing was opened."; + } + + /// True when the text holds CodeLength or more consecutive code characters. + private static bool HasCodeRun(string s) + { + int run = 0; + foreach (char c in s) + { + run = LaunchWire.IsCodeChar(c) ? run + 1 : 0; + if (run >= LaunchWire.CodeLength) return true; + } + return false; + } +} diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 5585fc0..456bb2a 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -22,7 +22,12 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: replies count only while asked, once", RepliesOnlyWhileAsked); r.Add("dreamweave web: one request at a time, never stuck", OneAtATime); r.Add("dreamweave web: the code never reaches a status or message", CodeNeverInStatus); + r.Add("dreamweave web: a code-shaped refusal is replaced, never shown", CodeShapedRefusal); + r.Add("dreamweave web: an expired request frees itself", SelfExpiry); + r.Add("dreamweave web: reset keeps the throttle", ResetKeepsThrottle); + r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); } + private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; @@ -173,7 +178,7 @@ internal static class DreamWeaveWebTests // Timeout at exactly +10,000. var t = new WebLauncher(); t.Begin(Market, 50_000); - Check.True(t.OnChatLine(Line, 0x05, 60_000, out _, out _, out _) == LaunchLine.NotOurs, "line at +10,000 ms is late"); + Check.True(t.OnChatLine(Line, 0x05, 60_000, out _, out _, out _) == LaunchLine.Stale, "a valid code at +10,000 ms is late: stale, not a code"); Check.True(t.TakeTimedOut(59_999) == null, "not timed out at +9,999"); Check.True(ReferenceEquals(t.TakeTimedOut(60_000), Market), "timed out once at +10,000"); Check.True(t.TakeTimedOut(60_001) == null, "and only once"); @@ -247,6 +252,88 @@ internal static class DreamWeaveWebTests Check.True(!f.Status.Contains(Code) && !msg.Contains(Code), "refusal status and message"); } + private static void CodeShapedRefusal() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + var k = w.OnChatLine("[WEB] Try again later: " + Code, 0x05, 10, out var dest, out string code, out string msg); + Check.True(k == LaunchLine.Refused, "still a refusal, so the caller eats the line"); + Check.True(ReferenceEquals(dest, Market), "destination handed back"); + Check.Eq(code, "", "no code"); + Check.True(!msg.Contains(Code), "message has no code"); + Check.True(!w.Status.Contains(Code), "status has no code"); + Check.Eq(msg, "DreamWeave sent an unexpected reply.", "fixed replacement text"); + Check.Eq(w.Status, "Market: DreamWeave said: DreamWeave sent an unexpected reply.", "status from the replacement"); + Check.True(w.Pending == null, "pending cleared"); + + // A long run of code chars anywhere, and a 42-char run (below the limit) left alone. + var w2 = new WebLauncher(); + w2.Begin(Market, 0); + w2.OnChatLine("[WEB] x " + Code + Code + " y", 0x05, 10, out _, out _, out msg); + Check.Eq(msg, "DreamWeave sent an unexpected reply.", "longer run replaced"); + var w3 = new WebLauncher(); + w3.Begin(Market, 0); + w3.OnChatLine("[WEB] id " + Code.Substring(1) + " ok", 0x05, 10, out _, out _, out msg); + Check.Eq(msg, "id " + Code.Substring(1) + " ok", "42-char run is ordinary text"); + } + private static void SelfExpiry() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + Check.True(w.Begin(Market, 9_999) == LaunchBegin.Busy, "before the deadline: busy"); + Check.True(w.Begin(Market, 10_001) != LaunchBegin.Busy, "past the deadline: not busy"); + + var x = new WebLauncher(); + x.Begin(Market, 0); + Check.True(x.Begin(DreamWeaveWeb.ById("suit")!, 10_001) == LaunchBegin.Started, "expired, then started as normal"); + Check.True(x.Pending!.Id == "suit", "the new request is the pending one"); + Check.True(x.TakeTimedOut(10_001) == null, "the new request is not timed out yet"); + Check.Eq(x.TakeTimedOut(20_001)?.Id ?? "none", "suit", "and it times out at its own deadline"); + } + private static void ResetKeepsThrottle() + { + var w = new WebLauncher(); + Check.True(w.Begin(Market, 1_000) == LaunchBegin.Started, "begin"); + w.Reset(); + Check.True(w.Pending == null, "reset clears pending"); + Check.True(w.Begin(Market, 1_001) == LaunchBegin.TooSoon, "throttle survives a relog"); + } + + private static void LateCodeIsStale() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + var k = w.OnChatLine(Line, 0x05, 10_500, out var dest, out string code, out string msg); + Check.True(k == LaunchLine.Stale, "valid code at +10,500 ms is stale"); + Check.True(dest == null && code == "" && msg == "", "stale carries nothing"); + Check.True(w.Pending != null, "stale does not clear pending"); + Check.True(!w.Status.Contains(Code), "status has no code"); + Check.True(ReferenceEquals(w.TakeTimedOut(10_500), Market), "timeout still fires once"); + Check.True(w.TakeTimedOut(10_501) == null, "and only once"); + Check.Eq(w.Status, "No reply from DreamWeave to /weblogin within 10 s, so nothing was opened.", "timeout status intact"); + Check.True(w.OnChatLine(Line, 0x05, 20_000, out dest, out code, out _) == LaunchLine.Stale, "still stale after the timeout was taken"); + Check.True(dest == null && code == "", "no destination or code"); + Check.True(w.OnChatLine(Line, 0x05, 69_999, out _, out _, out _) == LaunchLine.Stale, "last stale ms (+69,999)"); + Check.True(w.OnChatLine(Line, 0x05, 70_001, out _, out _, out _) == LaunchLine.NotOurs, "at +70,001 ms: not ours"); + Check.True(w.OnChatLine("[WEB] some refusal", 0x05, 20_000, out _, out _, out _) == LaunchLine.NotOurs, "a late refusal is not ours"); + Check.True(w.OnChatLine(Line, 0x02, 20_000, out _, out _, out _) == LaunchLine.NotOurs, "a late player copy is not ours"); + + var n = new WebLauncher(); + Check.True(n.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.NotOurs, "no Begin ever: not ours"); + + // A consumed request leaves no stale window. + var c = new WebLauncher(); + c.Begin(Market, 0); + c.OnChatLine(Line, 0x05, 100, out _, out _, out _); + Check.True(c.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.NotOurs, "after a code: not ours"); + + // A new Begin ends the old stale window. + var b = new WebLauncher(); + b.Begin(Market, 0); + b.TakeTimedOut(10_000); + b.Begin(Market, 20_000); + Check.True(b.OnChatLine(Line, 0x05, 20_100, out _, out _, out _) == LaunchLine.Code, "new request takes the code"); + } private static string[] ServerPluginIds() { string? dir = AppContext.BaseDirectory; -- 2.43.0 From dd4cbd83bb78c7289e11465dc147e5d9747d066f Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 14:56:03 -0800 Subject: [PATCH 11/29] RynthDreamWeave: forward-only stale window for late codes Replace the _expired flag with _staleUntilMs, raised by every started Begin and never lowered, so an earlier request's late code is eaten after overlap, Cancel or Reset. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebLauncher.cs | 34 ++++------- .../DreamWeaveWebTests.cs | 58 +++++++++++++++++-- 2 files changed, 64 insertions(+), 28 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 9150cec..422370a 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -26,9 +26,10 @@ internal sealed class WebLauncher private long _deadlineMs; private long _lastBeginMs; private bool _everBegun; - // A request that expired: its late code is eaten (Stale) until the code itself would have expired. - private bool _expired; - private long _expiredDeadlineMs; + // Forward-only: the moment after which no code from any request begun so far can still be valid. + // Nothing lowers it (not Begin, Cancel, Reset, Code, Refused or Expire), so a late code from any + // earlier request is still eaten as Stale, whatever happened to the requests since. + private long _staleUntilMs = long.MinValue; public WebDestination? Pending => _pending; public string Status { get; private set; } = ""; @@ -46,7 +47,7 @@ internal sealed class WebLauncher _everBegun = true; _lastBeginMs = nowMs; _deadlineMs = nowMs + LaunchWire.ReplyTimeoutMs; - _expired = false; + _staleUntilMs = Math.Max(_staleUntilMs, nowMs + LaunchWire.ReplyTimeoutMs + LaunchWire.CodeLifetimeMs); Status = "Asking DreamWeave for a login code for " + d.Label + "..."; return LaunchBegin.Started; } @@ -59,30 +60,22 @@ internal sealed class WebLauncher } /// - /// NotOurs unless a request is pending, or expired within the code's lifetime. Before the - /// deadline, Code and Refused clear Pending and the caller eats the line. After the deadline, - /// a valid code is Stale (eat it, open nothing; dest null, code empty) until CodeLifetimeMs - /// past the deadline; any other line is NotOurs. On Code, message is empty. + /// A pending request before its deadline takes the line: Code or Refused clears Pending and the + /// caller eats it (on Code, message is empty). Otherwise a line TryParse reads as a valid code is + /// Stale (eat it, open nothing; dest null, code and message empty) while nowMs is before the + /// forward-only stale deadline, and NotOurs after. Any other line outside a request is NotOurs. /// public LaunchLine OnChatLine(string text, int chatType, long nowMs, out WebDestination? dest, out string code, out string message) { dest = null; code = ""; message = ""; - long deadline; - if (_pending != null) deadline = _deadlineMs; - else if (_expired) deadline = _expiredDeadlineMs; - else return LaunchLine.NotOurs; - if (!LaunchWire.TryParse(text, chatType, out string parsedCode, out string refusal)) return LaunchLine.NotOurs; - if (nowMs >= deadline) - { - if (parsedCode.Length > 0 && nowMs < deadline + LaunchWire.CodeLifetimeMs) return LaunchLine.Stale; - return LaunchLine.NotOurs; - } + WebDestination? p = _pending; + if (p == null || nowMs >= _deadlineMs) + return parsedCode.Length > 0 && nowMs < _staleUntilMs ? LaunchLine.Stale : LaunchLine.NotOurs; - WebDestination p = _pending!; _pending = null; dest = p; if (parsedCode.Length > 0) @@ -95,7 +88,6 @@ internal sealed class WebLauncher Status = p.Label + ": DreamWeave said: " + message; return LaunchLine.Refused; } - /// The pending destination once, at or after Begin + ReplyTimeoutMs; null otherwise. public WebDestination? TakeTimedOut(long nowMs) { @@ -115,8 +107,6 @@ internal sealed class WebLauncher private void Expire() { _pending = null; - _expired = true; - _expiredDeadlineMs = _deadlineMs; Status = "No reply from DreamWeave to " + LaunchWire.RequestCommand + " within " + (LaunchWire.ReplyTimeoutMs / 1000) + " s, so nothing was opened."; } diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 456bb2a..08d4c84 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -26,6 +26,7 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: an expired request frees itself", SelfExpiry); r.Add("dreamweave web: reset keeps the throttle", ResetKeepsThrottle); r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); + r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); } private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars @@ -172,8 +173,8 @@ internal static class DreamWeaveWebTests Check.Eq(msg, "", "no message on a code"); Check.True(ReferenceEquals(dest, Market), "destination handed back"); Check.True(w.Pending == null, "code clears pending"); - Check.True(w.OnChatLine(Line, 0x05, 1000 + 9_999, out dest, out code, out msg) == LaunchLine.NotOurs, "an identical second line is not ours"); - Check.True(dest == null && code == "" && msg == "", "no outputs on NotOurs"); + Check.True(w.OnChatLine(Line, 0x05, 1000 + 9_999, out dest, out code, out msg) == LaunchLine.Stale, "an identical second line is stale: eaten, opens nothing"); + Check.True(dest == null && code == "" && msg == "", "no outputs on Stale"); // Timeout at exactly +10,000. var t = new WebLauncher(); @@ -206,7 +207,7 @@ internal static class DreamWeaveWebTests p.Reset(); Check.True(p.Pending == null, "reset clears pending"); Check.Eq(p.Status, "", "reset clears status"); - Check.True(p.OnChatLine(Line, 0x05, 5, out _, out _, out _) == LaunchLine.NotOurs, "after reset: not ours"); + Check.True(p.OnChatLine(Line, 0x05, 5, out _, out _, out _) == LaunchLine.Stale, "after reset: a code is stale, still eaten"); } private static void OneAtATime() @@ -276,6 +277,7 @@ internal static class DreamWeaveWebTests w3.OnChatLine("[WEB] id " + Code.Substring(1) + " ok", 0x05, 10, out _, out _, out msg); Check.Eq(msg, "id " + Code.Substring(1) + " ok", "42-char run is ordinary text"); } + private static void SelfExpiry() { var w = new WebLauncher(); @@ -290,6 +292,7 @@ internal static class DreamWeaveWebTests Check.True(x.TakeTimedOut(10_001) == null, "the new request is not timed out yet"); Check.Eq(x.TakeTimedOut(20_001)?.Id ?? "none", "suit", "and it times out at its own deadline"); } + private static void ResetKeepsThrottle() { var w = new WebLauncher(); @@ -325,15 +328,58 @@ internal static class DreamWeaveWebTests var c = new WebLauncher(); c.Begin(Market, 0); c.OnChatLine(Line, 0x05, 100, out _, out _, out _); - Check.True(c.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.NotOurs, "after a code: not ours"); + Check.True(c.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.Stale, "after a consumed code: a repeat is stale"); - // A new Begin ends the old stale window. + // A new Begin never ends the old stale window: the new request takes a code while pending, + // and the window still covers the old code once the new request is gone. var b = new WebLauncher(); b.Begin(Market, 0); b.TakeTimedOut(10_000); b.Begin(Market, 20_000); - Check.True(b.OnChatLine(Line, 0x05, 20_100, out _, out _, out _) == LaunchLine.Code, "new request takes the code"); + Check.True(b.OnChatLine(Line, 0x05, 20_100, out _, out _, out _) == LaunchLine.Code, "new request takes the code while pending"); + Check.True(b.OnChatLine(Line, 0x05, 20_200, out _, out _, out _) == LaunchLine.Stale, "then a further valid code is stale"); + + // Window upper boundary. + Check.Eq(LaunchWire.CodeLifetimeMs, 60_000L, "code lifetime"); + var u = new WebLauncher(); + u.Begin(Market, 0); + Check.True(u.OnChatLine(Line, 0x05, 69_999, out _, out _, out _) == LaunchLine.Stale, "+69,999 stale"); + Check.True(u.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "+70,000 not ours"); } + + private static void OverlappingRequests() + { + // Scenario 1: request 1 times out, request 2 begins, request 1's late code arrives. + var w = new WebLauncher(); + w.Begin(Market, 0); + w.TakeTimedOut(10_000); + Check.True(w.Begin(Market, 13_000) == LaunchBegin.Started, "request 2"); + Check.True(w.OnChatLine(Line, 0x05, 14_000, out _, out _, out _) == LaunchLine.Code, "the late code is taken by request 2 (indistinguishable)"); + Check.True(w.OnChatLine(Line, 0x05, 15_000, out var dest, out string code, out string msg) == LaunchLine.Stale, "request 2's own reply is stale, never chat"); + Check.True(dest == null && code == "" && msg == "", "stale carries nothing"); + + // Scenario 2: request 1 expires, request 2 begins and is cancelled, the late code arrives. + var c = new WebLauncher(); + c.Begin(Market, 0); + c.TakeTimedOut(10_000); + c.Begin(Market, 13_000); + c.Cancel("Could not send /weblogin."); + Check.True(c.OnChatLine(Line, 0x05, 14_000, out _, out _, out _) == LaunchLine.Stale, "after cancel: stale"); + + // Reset while pending, then the code. + var r = new WebLauncher(); + r.Begin(Market, 0); + r.Reset(); + Check.True(r.OnChatLine(Line, 0x05, 5_000, out _, out _, out _) == LaunchLine.Stale, "after reset while pending: stale"); + Check.True(r.OnChatLine("[WEB] some refusal", 0x05, 5_000, out _, out _, out _) == LaunchLine.NotOurs, "refusals outside a request stay not ours"); + + // Cancel right after Begin: the ask may have been sent anyway. + var k = new WebLauncher(); + k.Begin(Market, 0); + k.Cancel("x"); + Check.True(k.OnChatLine(Line, 0x05, 2_000, out _, out _, out _) == LaunchLine.Stale, "cancelled request's code is stale"); + } + private static string[] ServerPluginIds() { string? dir = AppContext.BaseDirectory; -- 2.43.0 From e7af2e2100176857b6a717edccea07918705b552 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:00:41 -0800 Subject: [PATCH 12/29] RynthDreamWeave: Task 4 review minors Restore blank line before the pending-destination doc comment, fix the stale-window test comment, and pin that a refused Begin does not extend the stale window. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebLauncher.cs | 1 + Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 422370a..42a87e0 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -88,6 +88,7 @@ internal sealed class WebLauncher Status = p.Label + ": DreamWeave said: " + message; return LaunchLine.Refused; } + /// The pending destination once, at or after Begin + ReplyTimeoutMs; null otherwise. public WebDestination? TakeTimedOut(long nowMs) { diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 08d4c84..3fb1378 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -324,7 +324,7 @@ internal static class DreamWeaveWebTests var n = new WebLauncher(); Check.True(n.OnChatLine(Line, 0x05, 10_500, out _, out _, out _) == LaunchLine.NotOurs, "no Begin ever: not ours"); - // A consumed request leaves no stale window. + // A consumed request's window persists: a repeat is eaten. var c = new WebLauncher(); c.Begin(Market, 0); c.OnChatLine(Line, 0x05, 100, out _, out _, out _); @@ -339,6 +339,13 @@ internal static class DreamWeaveWebTests Check.True(b.OnChatLine(Line, 0x05, 20_100, out _, out _, out _) == LaunchLine.Code, "new request takes the code while pending"); Check.True(b.OnChatLine(Line, 0x05, 20_200, out _, out _, out _) == LaunchLine.Stale, "then a further valid code is stale"); + // A refused Begin does not extend the stale window. + var t = new WebLauncher(); + t.Begin(Market, 0); + t.Cancel("send failed"); // Pending would answer Busy; TooSoon needs a free slot + Check.True(t.Begin(Market, 2_999) == LaunchBegin.TooSoon, "second begin inside the throttle is refused"); + Check.True(t.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "a refused Begin leaves the window anchored at the first"); + // Window upper boundary. Check.Eq(LaunchWire.CodeLifetimeMs, 60_000L, "code lifetime"); var u = new WebLauncher(); -- 2.43.0 From 2522534979a85fbfd9fe7ab87c9d61ccf3c0c2a1 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:01:35 -0800 Subject: [PATCH 13/29] RynthDreamWeave: per-account web profile key WebProfile.Key(serverId, account) = serverId/ + 32 lowercase hex of SHA-256 over the server id and the trimmed, lower-cased account; null without an account. Keys pass ServerWebOpen.IsValidProfileKey. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebProfile.cs | 23 +++++++++++++++++ .../DreamWeaveWebTests.cs | 25 +++++++++++++++++++ .../RynthServerPack.Tests.csproj | 1 + 3 files changed, 49 insertions(+) create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs new file mode 100644 index 0000000..d799222 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs @@ -0,0 +1,23 @@ +// The per-account web profile key: each account gets its own WebView2 profile folder, so website +// cookies never cross accounts. Pure, so RynthServerPack.Tests compiles it directly. +using System; +using System.Security.Cryptography; +using System.Text; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal static class WebProfile +{ + /// + /// "serverId/" plus the first 32 lowercase hex chars of SHA-256(UTF-8(serverId + "\n" + the trimmed, + /// lower-cased account)); null when there is no account. The server id (not the world name) keeps + /// one site's cookies together. The hash keeps the account name out of the folder name. The result + /// passes ServerWebOpen.IsValidProfileKey when serverId matches ^[a-z0-9-]{1,32}$. + /// + public static string? Key(string serverId, string? account) + { + if (string.IsNullOrWhiteSpace(account)) return null; + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(serverId + "\n" + account.Trim().ToLowerInvariant())); + return serverId + "/" + Convert.ToHexString(hash).ToLowerInvariant().Substring(0, 32); + } +} diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 3fb1378..dfbc215 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -27,6 +27,7 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: reset keeps the throttle", ResetKeepsThrottle); r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); + r.Add("dreamweave web: profile keys separate accounts", ProfileKeys); } private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars @@ -354,6 +355,30 @@ internal static class DreamWeaveWebTests Check.True(u.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "+70,000 not ours"); } + private static void ProfileKeys() + { + string? a = WebProfile.Key("dreamweave", "Alice"); + string? b = WebProfile.Key("dreamweave", "Bob"); + Check.True(a != null && b != null, "keys exist"); + Check.True(a != b, "different accounts -> different keys"); + Check.Eq(WebProfile.Key("dreamweave", " alice "), a, "trimmed and case-folded"); + Check.Eq(WebProfile.Key("dreamweave", "ALICE"), a, "case-folded"); + Check.Eq(WebProfile.Key("dreamweave", "Alice"), a, "stable across calls"); + Check.True(WebProfile.Key("coldeve", "Alice") != a, "same account, other server -> different key"); + Check.True(a!.StartsWith("dreamweave/", StringComparison.Ordinal), "prefixed by the server id"); + string[] accounts = { "Alice", "Bob", "a", "x y", "caf" + (char)0xE9, "A-very-long-account-name-0123456789-0123456789-0123456789" }; + foreach (string acct in accounts) + { + string? k = WebProfile.Key("dreamweave", acct); + Check.True(ServerWebOpen.IsValidProfileKey(k), "valid key for " + acct.Length + " chars"); + // A 1-2 char account could appear in the server id or the hex by chance; the rest cannot. + if (acct.Length >= 3) Check.True(!k!.Contains(acct.Trim().ToLowerInvariant()), "key never contains the account text"); + } + Check.True(WebProfile.Key("dreamweave", null) == null, "null account -> null"); + Check.True(WebProfile.Key("dreamweave", "") == null, "empty account -> null"); + Check.True(WebProfile.Key("dreamweave", " ") == null, "blank account -> null"); + } + private static void OverlappingRequests() { // Scenario 1: request 1 times out, request 2 begins, request 1's late code arrives. diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index 1fb19fa..68c8d8a 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -38,6 +38,7 @@ + -- 2.43.0 From acfd04fa46d42bb3daaa89d24763271ed401f1d4 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:04:27 -0800 Subject: [PATCH 14/29] RynthDreamWeave: pin the profile-key format and enforce its contract Golden pins for dreamweave/coldeve alice keys, a Busy-Begin stale-window pin, and Key returns null when the result fails ServerWebOpen.IsValidProfileKey. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebProfile.cs | 8 +++++--- Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs | 12 ++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs index d799222..561a12e 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebProfile.cs @@ -3,6 +3,7 @@ using System; using System.Security.Cryptography; using System.Text; +using RynthCore.Plugin.ServerPack; namespace RynthCore.Plugin.RynthDreamWeave; @@ -11,13 +12,14 @@ internal static class WebProfile /// /// "serverId/" plus the first 32 lowercase hex chars of SHA-256(UTF-8(serverId + "\n" + the trimmed, /// lower-cased account)); null when there is no account. The server id (not the world name) keeps - /// one site's cookies together. The hash keeps the account name out of the folder name. The result - /// passes ServerWebOpen.IsValidProfileKey when serverId matches ^[a-z0-9-]{1,32}$. + /// one site's cookies together. The hash keeps the account name out of the folder name. A result that fails + /// ServerWebOpen.IsValidProfileKey (a serverId outside ^[a-z0-9-]{1,32}$) is null, never a bad key. /// public static string? Key(string serverId, string? account) { if (string.IsNullOrWhiteSpace(account)) return null; byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(serverId + "\n" + account.Trim().ToLowerInvariant())); - return serverId + "/" + Convert.ToHexString(hash).ToLowerInvariant().Substring(0, 32); + string key = serverId + "/" + Convert.ToHexString(hash).ToLowerInvariant().Substring(0, 32); + return ServerWebOpen.IsValidProfileKey(key) ? key : null; } } diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index dfbc215..f324f56 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -347,6 +347,13 @@ internal static class DreamWeaveWebTests Check.True(t.Begin(Market, 2_999) == LaunchBegin.TooSoon, "second begin inside the throttle is refused"); Check.True(t.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "a refused Begin leaves the window anchored at the first"); + // A Busy Begin does not extend the stale window either. + var y = new WebLauncher(); + y.Begin(Market, 0); + Check.True(y.Begin(Market, 9_999) == LaunchBegin.Busy, "second begin while pending is Busy"); + y.Cancel("send failed"); + Check.True(y.OnChatLine(Line, 0x05, 70_000, out _, out _, out _) == LaunchLine.NotOurs, "a Busy Begin leaves the window anchored at the first"); + // Window upper boundary. Check.Eq(LaunchWire.CodeLifetimeMs, 60_000L, "code lifetime"); var u = new WebLauncher(); @@ -374,6 +381,11 @@ internal static class DreamWeaveWebTests // A 1-2 char account could appear in the server id or the hex by chance; the rest cannot. if (acct.Length >= 3) Check.True(!k!.Contains(acct.Trim().ToLowerInvariant()), "key never contains the account text"); } + Check.Eq(WebProfile.Key("dreamweave", "alice"), "dreamweave/67b613ccd746148225de235baae58eab", "key format is frozen (changing it orphans saved web logins)"); + Check.Eq(WebProfile.Key("coldeve", "alice"), "coldeve/1101ebeaa4456aba9ca33cd292d7b99c", "key format is frozen (changing it orphans saved web logins)"); + Check.True(WebProfile.Key("DreamWeave", "alice") == null, "uppercase server id -> null"); + Check.True(WebProfile.Key("dream/weave", "alice") == null, "slash in server id -> null"); + Check.True(WebProfile.Key("", "alice") == null, "empty server id -> null"); Check.True(WebProfile.Key("dreamweave", null) == null, "null account -> null"); Check.True(WebProfile.Key("dreamweave", "") == null, "empty account -> null"); Check.True(WebProfile.Key("dreamweave", " ") == null, "blank account -> null"); -- 2.43.0 From f012dc5c69976809a21aea17c0e48747d1c44076 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:11:22 -0800 Subject: [PATCH 15/29] RynthDreamWeave: Market, Suit Builder and Ability Planner buttons and /rserver verbs DreamWeaveWebTools.cs wires the launcher into the ServerPack hooks: the card buttons (render thread, draw only, a click queues StartLaunch with RunOnTick), the /rserver market|suit|abilities verbs, the /weblogin reply read off chat (Code, Refused and Stale eat the line; Stale does nothing else), the 10 s timeout polled every tick, and Reset at login, logout and shutdown. Every launcher call is under lock (Gate); Send, OpenWeb, Reply and the log are always outside it. OpenWeb's answer replaces the "Opening X..." status. WebButtons.cs draws the buttons and is the only ImGui code in the web tools. A source-scan test pins the thread rules. Rebased onto release 2026.11.8.1, which ships its own DreamWeavePlugin.cs (bank check, Bank page) and DreamWeaveSkills.cs (Skills and Character panels, /rserver skills). Those files keep the one implementation of each shared hook and call the web tools' Web* method first; the web code lives in DreamWeaveWebTools.cs. The ImGui scan covers the web tools' own files. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/WebButtons.cs | 55 +++ .../DreamWeavePlugin.cs | 14 +- .../DreamWeaveSkills.cs | 8 +- .../DreamWeaveWebTools.cs | 318 ++++++++++++++++++ .../RynthCore.Plugin.RynthDreamWeave.csproj | 2 +- .../ServerData.cs | 1 + .../DreamWeaveWebTests.cs | 201 +++++++++++ 7 files changed, 596 insertions(+), 3 deletions(-) create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs create mode 100644 Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs new file mode 100644 index 0000000..e51b456 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs @@ -0,0 +1,55 @@ +// The DreamWeave card's website buttons (Market, Suit Builder, Ability Planner). Render thread, inside +// the card hook only: this file draws and nothing else. It calls no host function, sends nothing and +// opens nothing; a click is handed to the caller, which queues the work for the tick (RunOnTick). +// It never switches the ImGui context (RenderEmbedded and OnRender own it), and it draws no +// Begin/End or Push/Pop pairs, so an exception part-way can't leave ImGui's stacks unbalanced. +using System; +using ImGuiNET; +using RynthCore.Plugin.Shared; + +namespace RynthCore.Plugin.RynthDreamWeave; + +internal static class WebButtons +{ + /// Shown on the card, and answered to a verb, when RynthCore doesn't see the world as DreamWeave. + public const string NotDreamWeave = "The web tools are DreamWeave's; RynthCore doesn't see this world as DreamWeave."; + + /// + /// One small button per destination on one row, each with its tooltip; while a request is pending, + /// the status line instead. The launcher's state is copied out under its lock first, then drawn. + /// + public static void Draw(WebLauncher l, bool active, Action click) + { + if (!active) + { + SafeImGui.TextWrapped(NotDreamWeave); + return; + } + + bool pending; + string status; + lock (l.Gate) + { + pending = l.Pending != null; + status = l.Status; + } + + if (pending) + { + SafeImGui.TextDisabled(status); + return; + } + + WebDestination? clicked = null; + bool first = true; + foreach (WebDestination d in DreamWeaveWeb.Destinations) + { + if (!first) ImGui.SameLine(); + first = false; + if (ImGui.SmallButton(d.Label + "##dw_web_" + d.Id)) clicked = d; + if (ImGui.IsItemHovered()) SafeImGui.SetTooltip(d.Tooltip); + } + if (status.Length > 0) SafeImGui.TextWrapped(status); + if (clicked != null) click(clicked); + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs index 94600a8..2c6f79d 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeavePlugin.cs @@ -2,6 +2,9 @@ // (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the every-minute bank check that gives Lum/hr its // luminance on DreamWeave (DreamWeave/DreamWeaveBank.cs, 2026-11-02), published as the profile value // "bankLuminance" for the session stats, and its Bank page (DreamWeave/DreamWeavePages.cs). +// The website buttons and verbs (DreamWeaveWebTools.cs) share these hooks: each one below hands off to +// its Web* method first, so a launch-code line is read whatever the world is and the bank's own gates +// stay as they were. using System; using RynthCore.Plugin.RynthDreamWeave; @@ -30,18 +33,25 @@ public sealed partial class ServerPackPlugin partial void ServerLoginComplete() { + WebLoginComplete(); lock (_bank.Gate) _bank.Login(Environment.TickCount64); } partial void ServerLogout() { + WebLogout(); lock (_bank.Gate) _bank.Logout(); } - partial void ServerShutdown() => SaveDreamWeaveSettings(); + partial void ServerShutdown() + { + WebShutdown(); + SaveDreamWeaveSettings(); + } partial void ServerChatText(string text, int chatType, ref bool eat) { + WebChatText(text, chatType, ref eat); if (!Active) return; bool ours; long? value; @@ -62,6 +72,7 @@ public sealed partial class ServerPackPlugin partial void ServerTick(bool active) { + WebTick(); if (!active) return; string? check; lock (_bank.Gate) @@ -92,5 +103,6 @@ public sealed partial class ServerPackPlugin string lum = _bank.Luminance is long l ? l.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) : "not read yet"; line($"Bank check every minute {(_bank.CheckEveryMinute ? "on" : "off")}; banked luminance {lum}."); } + WebInfoLines(line); } } diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs index 3488036..145bf98 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveSkills.cs @@ -235,10 +235,16 @@ public sealed partial class ServerPackPlugin // ── /rserver skills ───────────────────────────────────────────────── - partial void ServerCommandVerbs(List verbs) => verbs.Add("skills"); + partial void ServerCommandVerbs(List verbs) + { + verbs.Add("skills"); + WebCommandVerbs(verbs); // DreamWeaveWebTools.cs: the website verbs + } partial void ServerChatCommand(string[] parts, ref bool handled) { + WebChatCommand(parts, ref handled); // DreamWeaveWebTools.cs: a website verb + if (handled) return; if (parts.Length < 2 || !parts[1].Equals("skills", StringComparison.OrdinalIgnoreCase)) return; handled = true; // "press character|titles": what AC's own Character button or Titles window does now (the engine runs it diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs new file mode 100644 index 0000000..407d5a2 --- /dev/null +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -0,0 +1,318 @@ +// DreamWeaveWebTools.cs - RynthDreamWeave's website tools, through the shared server plugin's hooks +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the card's Market, Suit Builder and Ability Planner +// buttons and "/rserver market | suit | abilities", which open the website logged in as this account. +// The hooks it shares with the bank and the Skills panel are implemented once, in DreamWeavePlugin.cs and +// DreamWeaveSkills.cs, and call the Web* methods here first. +// +// The flow: a button (render thread) queues StartLaunch for the tick; a verb runs it on the pump. It +// sends "/weblogin"; ACE answers "[WEB] Launch code: ..." and the chat hook eats that line and opens +// DreamWeaveWeb.LaunchUrl through OpenWeb (ServerPackWeb.cs). Only the code comes from chat; the host +// and the path are constants. The code is never logged, saved, chatted or put in a status line. +// +// Threads (WebLauncher's remark): every launcher call is made under lock (_web.Gate), and the lock is +// held around launcher calls only, never around Send, OpenWeb, Reply or the log. Times come from +// Environment.TickCount64. The card hook runs on the render thread and only draws (WebButtons); the +// chat, tick, command and login hooks run on the plugin pump; OpenWeb's `done` may run on its worker +// thread. No hook lets an exception out: this code runs inside acclient. +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Plugin.RynthDreamWeave; + +namespace RynthCore.Plugin.ServerPack; + +public sealed partial class ServerPackPlugin +{ + private readonly WebLauncher _web = new(); + // The card's click handler, made once (render thread only). + private Action? _webClick; + // The "no in-game web panel" line, once per login (set from OpenWeb's done, any thread). + private int _webNoPanelNoted; + // The card's draw failure, logged once rather than every frame (render thread only). + private bool _webDrawFailed; + + private enum WebBrowserWhy { PanelFellBack, NoPanel, NoAccount } + + private void WebCommandVerbs(List verbs) + { + try + { + foreach (WebDestination d in DreamWeaveWeb.Destinations) verbs.Add(d.Id); + } + catch (Exception) + { + // The constructor has no Host to log to yet; the verbs are constants, so this can't happen. + } + } + + partial void ServerCardActions() + { + try + { + WebButtons.Draw(_web, Active, _webClick ??= d => RunOnTick(() => StartLaunch(d))); + } + catch (Exception ex) + { + if (!_webDrawFailed) + { + _webDrawFailed = true; + LogTagged("The web buttons failed to draw: " + ex.GetType().Name); + } + } + } + + private void WebChatCommand(string[] parts, ref bool handled) + { + try + { + if (parts.Length < 2) return; + WebDestination? d = DreamWeaveWeb.ById(parts[1]); + if (d == null) return; + handled = true; + StartLaunch(d); + } + catch (Exception ex) + { + LogTagged("A web verb failed: " + ex.GetType().Name); + } + } + + /// Asks DreamWeave for a login code for . Pump thread (a verb, or a button's RunOnTick). + private void StartLaunch(WebDestination d) + { + try + { + if (!Active) + { + Reply.Fail(WebButtons.NotDreamWeave); + return; + } + + LaunchBegin begun; + string status; + lock (_web.Gate) + { + begun = _web.Begin(d, Environment.TickCount64); + status = _web.Status; + } + if (begun == LaunchBegin.Busy) + { + Reply.Fail("Already asking DreamWeave for a login code; wait a moment."); + return; + } + if (begun == LaunchBegin.TooSoon) + { + Reply.Fail("Wait a few seconds between web opens."); + return; + } + + if (!Send(LaunchWire.RequestFor(d))) + { + const string notSent = "Couldn't send /weblogin (not in the world)."; + lock (_web.Gate) _web.Cancel(notSent); + Reply.Fail(notSent); + return; + } + Reply.Ok(status); + } + catch (Exception ex) + { + LogTagged("Starting a web open failed: " + ex.GetType().Name); + } + } + + private void WebChatText(string text, int chatType, ref bool eat) + { + LaunchLine kind = LaunchLine.NotOurs; + try + { + if (!Active) return; + WebDestination? d; + string launchCode; + string status; + lock (_web.Gate) + { + kind = _web.OnChatLine(text, chatType, Environment.TickCount64, out d, out launchCode, out _); + status = _web.Status; + } + switch (kind) + { + case LaunchLine.NotOurs: + return; + case LaunchLine.Stale: + // A late or repeated code: keep it out of chat and open nothing. No reply, no status, no log. + eat = true; + return; + case LaunchLine.Refused: + eat = true; + Reply.Fail(status); + return; + case LaunchLine.Code: + eat = true; + if (d != null) OpenLaunch(d, DreamWeaveWeb.LaunchUrl(launchCode, d), status); + return; + } + } + catch (Exception ex) + { + // The line that answered our request never reaches chat, whatever failed after it was read. + if (kind != LaunchLine.NotOurs) eat = true; + LogTagged("Reading a web reply failed: " + ex.GetType().Name); + } + } + + /// + /// Opens the launch URL (pump thread). is the status the launcher set on the + /// code ("Opening X..."); the answer replaces it, so the card never stays on it. + /// + private void OpenLaunch(WebDestination d, string url, string opening) + { + try + { + string? account = Host.TryGetAccountName(out string name) ? name : null; + var request = new WebOpenRequest(url, DreamWeaveWeb.AllowedHosts, + WebProfile.Key(Info.Id, account) ?? "", DreamWeaveWeb.PanelTitle); + bool panel = PanelAvailable; + WebBrowserWhy why = ServerWebOpen.Route(request, panel) != WebOpenRoute.Browser ? WebBrowserWhy.PanelFellBack + : panel ? WebBrowserWhy.NoAccount : WebBrowserWhy.NoPanel; + OpenWeb(request, outcome => WebOpened(d, outcome, why, opening)); + } + catch (Exception ex) + { + LogTagged("Opening a web page failed: " + ex.GetType().Name); + WebOpenFailed(d, "Couldn't open " + d.Label + ".", opening); + } + } + + /// OpenWeb's answer. Any thread (the browser opens on a worker thread). + private void WebOpened(WebDestination d, WebOpenOutcome outcome, WebBrowserWhy why, string opening) + { + try + { + if (!outcome.Ok) + { + WebOpenFailed(d, "Couldn't open " + d.Label + ": " + outcome.Message, opening); + return; + } + + string text; + string? note = null; + if (outcome.Route != WebOpenRoute.Browser) text = "Opened " + d.Label + "."; + else if (why == WebBrowserWhy.NoPanel) + { + text = "Opened " + d.Label + "."; + if (Interlocked.Exchange(ref _webNoPanelNoted, 1) == 0) + note = "This RynthCore has no in-game web panel, so " + d.Label + " opened in your browser."; + } + else if (why == WebBrowserWhy.NoAccount) + text = "Opened " + d.Label + " in your browser, not the web panel: RynthCore didn't report the account name."; + else + text = "Opened " + d.Label + " in your browser: the web panel didn't take it."; + + ReplaceOpeningStatus(opening, text); + Reply.Ok(text); + if (note != null) Reply.Ok(note); + } + catch (Exception) + { + // OpenWeb's Finish swallows this too; nothing here may reach the engine. + } + } + + private void WebOpenFailed(WebDestination d, string text, string opening) + { + try + { + ReplaceOpeningStatus(opening, text); + Reply.Fail(text); + } + catch (Exception) + { + } + } + + /// + /// Puts the answer in the card's status, unless a newer request has taken over the launcher since the + /// code came in (then its own status stands). Cancel is the launcher's status setter; with nothing + /// pending it only sets the status. + /// + private void ReplaceOpeningStatus(string opening, string text) + { + lock (_web.Gate) + { + if (_web.Pending == null && _web.Status == opening) _web.Cancel(text); + } + } + + private void WebTick() + { + try + { + WebDestination? timedOut; + string status = ""; + lock (_web.Gate) + { + timedOut = _web.TakeTimedOut(Environment.TickCount64); + if (timedOut != null) status = _web.Status; + } + if (timedOut != null) Reply.Fail(status); + } + catch (Exception ex) + { + LogTagged("The web request timer failed: " + ex.GetType().Name); + } + } + + private void WebInfoLines(Action line) + { + try + { + string status; + lock (_web.Gate) status = _web.Status; + line("Web tools (/rserver market | suit | abilities): " + (status.Length > 0 ? status : "none opened this login.")); + } + catch (Exception ex) + { + LogTagged("The web tools' info line failed: " + ex.GetType().Name); + } + } + + private void WebLoginComplete() + { + try + { + lock (_web.Gate) _web.Reset(); + Interlocked.Exchange(ref _webNoPanelNoted, 0); + } + catch (Exception ex) + { + LogTagged("Resetting the web tools at login failed: " + ex.GetType().Name); + } + } + + private void WebLogout() + { + try + { + lock (_web.Gate) _web.Reset(); + CloseWeb(); + } + catch (Exception ex) + { + LogTagged("Closing the web tools at logout failed: " + ex.GetType().Name); + } + } + + private void WebShutdown() + { + try + { + lock (_web.Gate) _web.Reset(); + CloseWeb(); + } + catch (Exception ex) + { + LogTagged("Closing the web tools at shutdown failed: " + ex.GetType().Name); + } + } +} diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index 854d7fe..76189d4 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -10,7 +10,7 @@ DreamWeave play.acdreamweave.com DreamWeave|Dream Weave - DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. + DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, with Market, Suit Builder and Ability Planner buttons that open the website logged in as this account, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs index e17a30b..bd67bc2 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs @@ -35,6 +35,7 @@ internal static class ServerData "Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).", "Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).", "Web character sheet you can publish (/charsheet).", + "Market, Suit Builder and Ability Planner open logged in from this card (/rserver market | suit | abilities).", }, Commands = new[] { diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index f324f56..a62293d 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -28,6 +28,207 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); r.Add("dreamweave web: profile keys separate accounts", ProfileKeys); + r.Add("dreamweave web: ImGui only in WebButtons, no context switching, no host calls from draw", ThreadRules); + r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); + } + + // -- Host wiring (source scan: the plugin is NativeAOT, so its host code can't run here) -- + + private static string PluginsRoot() + { + string? dir = AppContext.BaseDirectory; + while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) + dir = Path.GetDirectoryName(dir); + if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); + return Path.Combine(dir, "Plugins"); + } + + private static IEnumerable SourceFiles(string root) + => Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories) + .Where(p => !p.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + && !p.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)); + + /// + /// The website feature's own files, the ones its rules hold to: DreamWeaveWeb*.cs, Web*.cs and LaunchWire.cs. + /// The plugin's other features (the Skills and Character panels, the Bank page) draw with ImGui themselves. + /// + private static List WebFiles(string dw) + { + var files = SourceFiles(dw).Where(p => + { + string n = Path.GetFileName(p); + return n.StartsWith("DreamWeaveWeb", StringComparison.Ordinal) || n.StartsWith("Web", StringComparison.Ordinal) || n == "LaunchWire.cs"; + }).ToList(); + Check.True(files.Count >= 6, "the website feature's files are found (" + files.Count + ")"); + return files; + } + + /// The text with // comments removed (a "//" right after ':' is a URL, kept), so a rule named in a comment doesn't count. + private static string StripComments(string text) + { + var sb = new System.Text.StringBuilder(text.Length); + foreach (string line in text.Split('\n')) + { + int at = 0, cut = -1; + while ((at = line.IndexOf("//", at, StringComparison.Ordinal)) >= 0) + { + if (at == 0 || line[at - 1] != ':') { cut = at; break; } + at += 2; + } + sb.Append(cut >= 0 ? line.Substring(0, cut) : line).Append('\n'); + } + return sb.ToString(); + } + + /// The statement after each : a balanced { } block, or up to the next ';'. + private static List StatementsAfter(string code, string head) + { + var found = new List(); + int at = 0; + while ((at = code.IndexOf(head, at, StringComparison.Ordinal)) >= 0) + { + int i = at + head.Length; + while (i < code.Length && char.IsWhiteSpace(code[i])) i++; + if (i < code.Length && code[i] == '{') + { + int depth = 0, j = i; + for (; j < code.Length; j++) + { + if (code[j] == '{') depth++; + else if (code[j] == '}' && --depth == 0) break; + } + found.Add(code.Substring(i, Math.Min(j + 1, code.Length) - i)); + } + else + { + int semi = code.IndexOf(';', i); + found.Add(code.Substring(i, (semi < 0 ? code.Length : semi + 1) - i)); + } + at = i; + } + return found; + } + + /// The token as a call or member access of its own: "ChatLine(" matches, "OnChatLine(" does not. + private static bool Mentions(string code, string token) + => System.Text.RegularExpressions.Regex.IsMatch(code, @"(?= 0) { n++; at += needle.Length; } + return n; + } + + // DreamWeavePlugin.cs and DreamWeaveSkills.cs own the hooks the web tools share with the bank and the Skills + // panel: each hands off to its Web* method before its own code, so no gate of theirs comes first. + private static void HooksHandOff() + { + string dw = Path.Combine(PluginsRoot(), "RynthCore.Plugin.RynthDreamWeave"); + string plugin = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeavePlugin.cs"))); + string skills = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeaveSkills.cs"))); + (string Code, string Head, string Call)[] hooks = + { + (plugin, "partial void ServerLoginComplete()", "WebLoginComplete();"), + (plugin, "partial void ServerLogout()", "WebLogout();"), + (plugin, "partial void ServerShutdown()", "WebShutdown();"), + (plugin, "partial void ServerChatText(string text, int chatType, ref bool eat)", "WebChatText(text, chatType, ref eat);"), + (plugin, "partial void ServerTick(bool active)", "WebTick();"), + (skills, "partial void ServerChatCommand(string[] parts, ref bool handled)", "WebChatCommand(parts, ref handled);"), + (skills, "partial void ServerCommandVerbs(List verbs)", null!), + }; + foreach (var (code, head, call) in hooks) + { + List body = StatementsAfter(code, head); + Check.Eq(body.Count, 1, head + ": implemented once"); + if (body.Count != 1 || call == null) continue; + Check.True(body[0].TrimStart('{', ' ', '\n', '\r').StartsWith(call, StringComparison.Ordinal), head + ": " + call + " comes first"); + } + List verbs = StatementsAfter(skills, "partial void ServerCommandVerbs(List verbs)"); + Check.True(verbs.Count == 1 && verbs[0].Contains("WebCommandVerbs(verbs);", StringComparison.Ordinal), "ServerCommandVerbs adds the web verbs"); + List info = StatementsAfter(plugin, "partial void ServerInfoLines(Action line)"); + Check.True(info.Count == 1 && info[0].Contains("WebInfoLines(line);", StringComparison.Ordinal), "ServerInfoLines adds the web tools' line"); + // The web tools implement none of the hooks they are handed: one implementation each, in the hub files. + string web = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeaveWebTools.cs"))); + foreach (string hook in new[] { "ServerLoginComplete", "ServerLogout", "ServerShutdown", "ServerChatText", "ServerTick", "ServerChatCommand", "ServerCommandVerbs", "ServerInfoLines" }) + Check.False(web.Contains("partial void " + hook + "(", StringComparison.Ordinal), "DreamWeaveWebTools.cs leaves " + hook + " to the hub"); + } + + private static void ThreadRules() + { + string plugins = PluginsRoot(); + string dw = Path.Combine(plugins, "RynthCore.Plugin.RynthDreamWeave"); + string buttonsPath = Path.Combine(dw, "DreamWeave", "WebButtons.cs"); + string hostPath = Path.Combine(dw, "DreamWeaveWebTools.cs"); + Check.True(File.Exists(buttonsPath), "DreamWeave\\WebButtons.cs exists"); + Check.True(File.Exists(hostPath), "DreamWeaveWebTools.cs exists"); + if (!File.Exists(buttonsPath) || !File.Exists(hostPath)) return; + + var bareImGui = new System.Text.RegularExpressions.Regex(@"(? drawLocks = StatementsAfter(buttons, "lock (l.Gate)"); + Check.Eq(drawLocks.Count, 1, "WebButtons.cs: one lock, to copy Pending and Status out"); + foreach (string s in drawLocks) + Check.False(bareImGui.IsMatch(s) || s.Contains("SafeImGui", StringComparison.Ordinal) || s.Contains("click(", StringComparison.Ordinal), + "WebButtons.cs: nothing is drawn or clicked under the lock"); + + string host = StripComments(File.ReadAllText(hostPath)); + List cardHook = StatementsAfter(host, "partial void ServerCardActions()"); + Check.Eq(cardHook.Count, 1, "DreamWeaveWebTools.cs implements ServerCardActions once"); + string clickPath = cardHook.Count == 1 ? cardHook[0] : ""; + Check.True(clickPath.Contains("WebButtons.Draw(", StringComparison.Ordinal), "the card hook draws through WebButtons.Draw"); + Check.True(host.Contains("RunOnTick(() => StartLaunch(d))", StringComparison.Ordinal), "the button path queues StartLaunch with RunOnTick"); + Check.False(clickPath.Contains("StartLaunch(d)", StringComparison.Ordinal) && !clickPath.Contains("RunOnTick(", StringComparison.Ordinal), + "the card hook never calls StartLaunch directly"); + + // Every lock on the launcher holds launcher calls only: no send, open, reply or log under it. + List hostLocks = StatementsAfter(host, "lock (_web.Gate)"); + Check.True(hostLocks.Count >= 5, "the host takes the launcher's lock (" + hostLocks.Count + " places)"); + foreach (string s in hostLocks) + foreach (string banned in new[] { "Send(", "OpenWeb(", "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "Host.", "ShellExecute", "CloseWeb(" }) + Check.False(Mentions(s, banned), "no " + banned + " under lock (_web.Gate): " + s.Trim().Replace('\n', ' ')); + Check.False(host.Contains("DateTime", StringComparison.Ordinal) || host.Contains("Stopwatch", StringComparison.Ordinal), "nowMs comes from Environment.TickCount64 only"); + Check.True(host.Contains("Environment.TickCount64", StringComparison.Ordinal), "the host uses Environment.TickCount64"); + + // The code goes into the launch URL and nowhere else. + int uses = System.Text.RegularExpressions.Regex.Matches(host, @"\blaunchCode\b").Count; + Check.Eq(uses, 3, "launchCode: declared, filled by OnChatLine, used once (DreamWeaveWeb.LaunchUrl)"); + Check.Eq(CountOf(host, "out launchCode"), 1, "launchCode is filled only by OnChatLine"); + Check.True(host.Contains("DreamWeaveWeb.LaunchUrl(launchCode, ", StringComparison.Ordinal), "the code's one use is the launch URL"); + + // Stale eats the line and does nothing else. + int stale = host.IndexOf("case LaunchLine.Stale:", StringComparison.Ordinal); + Check.True(stale >= 0, "the chat hook handles LaunchLine.Stale"); + if (stale >= 0) + { + int end = host.IndexOf("return;", stale, StringComparison.Ordinal); + string arm = end < 0 ? "" : host.Substring(stale, end - stale); + Check.True(arm.Contains("eat = true;", StringComparison.Ordinal), "Stale eats the line"); + foreach (string banned in new[] { "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "OpenWeb(", "Cancel(", "Host." }) + Check.False(Mentions(arm, banned), "Stale does nothing else: no " + banned); + } } private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars -- 2.43.0 From 5fbbf4e65436920fa336c210548821e86f88b0ca Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:22:09 -0800 Subject: [PATCH 16/29] RynthDreamWeave: Task 6 review fixes (code never to chat, allow-list scan, result generation) - ServerChatText reads every line through the launcher, with no Active gate first: a code answering our request is eaten whatever the world is now, and opens nothing when the world is no longer DreamWeave. - WebLauncher: a generation token (Begin when Started, Reset) and SetResult(generation, status), which replaces the status compare and the use of Cancel as a status setter. The no-panel note is once per login epoch, so an answer from an earlier login can't spend it. - An open failure reads "Market: Couldn't open your browser (code N)." - StartLaunch's catch answers "Couldn't start the web open." - ServerUsageLines: an optional shared hook for a server's own usage lines; DreamWeave lists market | suit | abilities. Hookless servers print the same two lines as before (pinned on Coldeve). - The source scan is allow-lists: every lock is on the launcher's Gate and calls only its members, the Stale arm is exactly eat = true, Draw calls only ImGui, SafeImGui and click. Comments are stripped without touching string literals. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 10 + .../DreamWeave/WebLauncher.cs | 20 +- .../DreamWeaveWebTools.cs | 83 ++++-- .../DreamWeaveWebTests.cs | 262 ++++++++++++++---- .../ServerPackCommandsTests.cs | 6 + 5 files changed, 299 insertions(+), 82 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index 6e8ce44..0436ea3 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -32,6 +32,16 @@ internal static class DreamWeaveWeb return null; } + /// The "/rserver" usage line for the destinations' verbs (ServerUsageLines). + public static string UsageLine() + { + var ids = new string[Destinations.Length]; + var labels = new string[Destinations.Length]; + for (int i = 0; i < Destinations.Length; i++) { ids[i] = Destinations[i].Id; labels[i] = Destinations[i].Label; } + return "/rserver " + string.Join(" | ", ids) + " - open the website's " + string.Join(", ", labels) + + ", logged in as this account."; + } + /// The sign-in URL for a destination. The caller has already checked the code with LaunchWire. public static string LaunchUrl(string code, WebDestination d) => SiteBase + "/launch?code=" + code + "&to=" + Uri.EscapeDataString(d.Path); diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 42a87e0..0f7bb48 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -14,7 +14,10 @@ internal enum LaunchLine { NotOurs, Code, Refused, Stale } /// lock (Gate). The callers are the chat pump, the tick thread and the render thread. Hold /// the lock only around calls into this class, never around Send or ShellExecute. nowMs must come /// from one monotonic clock (Environment.TickCount64). After a Code reply, Status reads -/// "Opening X..."; if the open then fails, the caller must overwrite Status. +/// "Opening X..."; the caller then reports the open's answer with SetResult, never by setting Status +/// another way. Generation names the request a Code or Refused reply resolved: read it under the same +/// lock, right after OnChatLine, and pass it to SetResult. Begin (when Started) and Reset move it on, +/// so an answer for an older request, or one from before a relog, never overwrites a newer status. /// internal sealed class WebLauncher { @@ -30,8 +33,12 @@ internal sealed class WebLauncher // Nothing lowers it (not Begin, Cancel, Reset, Code, Refused or Expire), so a late code from any // earlier request is still eaten as Stale, whatever happened to the requests since. private long _staleUntilMs = long.MinValue; + private long _generation; public WebDestination? Pending => _pending; + + /// The current request's generation: after OnChatLine returns Code or Refused, the one it resolved. + public long Generation => _generation; public string Status { get; private set; } = ""; /// @@ -44,6 +51,7 @@ internal sealed class WebLauncher if (_pending != null) return LaunchBegin.Busy; if (_everBegun && nowMs - _lastBeginMs < LaunchWire.MinIntervalMs) return LaunchBegin.TooSoon; _pending = d; + _generation++; _everBegun = true; _lastBeginMs = nowMs; _deadlineMs = nowMs + LaunchWire.ReplyTimeoutMs; @@ -102,9 +110,19 @@ internal sealed class WebLauncher public void Reset() { _pending = null; + _generation++; Status = ""; } + /// + /// The answer to the request of (the open's result): set as Status only + /// while nothing is pending and no Begin or Reset has happened since; otherwise ignored. + /// + public void SetResult(long generation, string status) + { + if (_pending == null && generation == _generation) Status = status; + } + private void Expire() { _pending = null; diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index 407d5a2..66f55c8 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -26,8 +26,10 @@ public sealed partial class ServerPackPlugin private readonly WebLauncher _web = new(); // The card's click handler, made once (render thread only). private Action? _webClick; - // The "no in-game web panel" line, once per login (set from OpenWeb's done, any thread). - private int _webNoPanelNoted; + // Counts logins, so an answer from before a relog never spends this login's "no web panel" line. + private int _webLoginEpoch; + // The login that has had the "no in-game web panel" line (set from OpenWeb's done, any thread). + private int _webNoPanelNotedEpoch; // The card's draw failure, logged once rather than every frame (render thread only). private bool _webDrawFailed; @@ -45,6 +47,18 @@ public sealed partial class ServerPackPlugin } } + partial void ServerUsageLines(Action add) + { + try + { + add(DreamWeaveWeb.UsageLine()); + } + catch (Exception) + { + // The constructor has no Host to log to yet; the destinations are constants. + } + } + partial void ServerCardActions() { try @@ -117,23 +131,33 @@ public sealed partial class ServerPackPlugin } catch (Exception ex) { - LogTagged("Starting a web open failed: " + ex.GetType().Name); + try + { + LogTagged("Starting a web open failed: " + ex.GetType().Name); + Reply.Fail("Couldn't start the web open."); + } + catch (Exception) + { + } } } private void WebChatText(string text, int chatType, ref bool eat) { + // No Active check before the launcher: only a request it began (or its stale window) is ever + // not NotOurs, and a code that answers one must be eaten whatever the world is now. LaunchLine kind = LaunchLine.NotOurs; try { - if (!Active) return; WebDestination? d; string launchCode; string status; + long generation; lock (_web.Gate) { kind = _web.OnChatLine(text, chatType, Environment.TickCount64, out d, out launchCode, out _); status = _web.Status; + generation = _web.Generation; } switch (kind) { @@ -149,7 +173,13 @@ public sealed partial class ServerPackPlugin return; case LaunchLine.Code: eat = true; - if (d != null) OpenLaunch(d, DreamWeaveWeb.LaunchUrl(launchCode, d), status); + if (d == null) return; + if (!Active) + { + WebOpenFailed(d, generation, WebButtons.NotDreamWeave); + return; + } + OpenLaunch(d, DreamWeaveWeb.LaunchUrl(launchCode, d), generation); return; } } @@ -162,11 +192,12 @@ public sealed partial class ServerPackPlugin } /// - /// Opens the launch URL (pump thread). is the status the launcher set on the - /// code ("Opening X..."); the answer replaces it, so the card never stays on it. + /// Opens the launch URL (pump thread). is the request the code answered; + /// the open's answer replaces its "Opening X..." status (SetResult), so the card never stays on it. /// - private void OpenLaunch(WebDestination d, string url, string opening) + private void OpenLaunch(WebDestination d, string url, long generation) { + int epoch = Volatile.Read(ref _webLoginEpoch); try { string? account = Host.TryGetAccountName(out string name) ? name : null; @@ -175,23 +206,23 @@ public sealed partial class ServerPackPlugin bool panel = PanelAvailable; WebBrowserWhy why = ServerWebOpen.Route(request, panel) != WebOpenRoute.Browser ? WebBrowserWhy.PanelFellBack : panel ? WebBrowserWhy.NoAccount : WebBrowserWhy.NoPanel; - OpenWeb(request, outcome => WebOpened(d, outcome, why, opening)); + OpenWeb(request, outcome => WebOpened(d, outcome, why, generation, epoch)); } catch (Exception ex) { LogTagged("Opening a web page failed: " + ex.GetType().Name); - WebOpenFailed(d, "Couldn't open " + d.Label + ".", opening); + WebOpenFailed(d, generation, "Couldn't open " + d.Label + "."); } } /// OpenWeb's answer. Any thread (the browser opens on a worker thread). - private void WebOpened(WebDestination d, WebOpenOutcome outcome, WebBrowserWhy why, string opening) + private void WebOpened(WebDestination d, WebOpenOutcome outcome, WebBrowserWhy why, long generation, int epoch) { try { if (!outcome.Ok) { - WebOpenFailed(d, "Couldn't open " + d.Label + ": " + outcome.Message, opening); + WebOpenFailed(d, generation, d.Label + ": " + outcome.Message); return; } @@ -201,7 +232,8 @@ public sealed partial class ServerPackPlugin else if (why == WebBrowserWhy.NoPanel) { text = "Opened " + d.Label + "."; - if (Interlocked.Exchange(ref _webNoPanelNoted, 1) == 0) + // Once per login, and never spent by an answer from an earlier login. + if (epoch == Volatile.Read(ref _webLoginEpoch) && Interlocked.Exchange(ref _webNoPanelNotedEpoch, epoch) != epoch) note = "This RynthCore has no in-game web panel, so " + d.Label + " opened in your browser."; } else if (why == WebBrowserWhy.NoAccount) @@ -209,7 +241,7 @@ public sealed partial class ServerPackPlugin else text = "Opened " + d.Label + " in your browser: the web panel didn't take it."; - ReplaceOpeningStatus(opening, text); + SetWebResult(generation, text); Reply.Ok(text); if (note != null) Reply.Ok(note); } @@ -219,11 +251,11 @@ public sealed partial class ServerPackPlugin } } - private void WebOpenFailed(WebDestination d, string text, string opening) + private void WebOpenFailed(WebDestination d, long generation, string text) { try { - ReplaceOpeningStatus(opening, text); + SetWebResult(generation, text); Reply.Fail(text); } catch (Exception) @@ -231,17 +263,10 @@ public sealed partial class ServerPackPlugin } } - /// - /// Puts the answer in the card's status, unless a newer request has taken over the launcher since the - /// code came in (then its own status stands). Cancel is the launcher's status setter; with nothing - /// pending it only sets the status. - /// - private void ReplaceOpeningStatus(string opening, string text) + /// The open's answer as the card's status, unless a newer request (or a relog) has taken over since. + private void SetWebResult(long generation, string text) { - lock (_web.Gate) - { - if (_web.Pending == null && _web.Status == opening) _web.Cancel(text); - } + lock (_web.Gate) _web.SetResult(generation, text); } private void WebTick() @@ -249,11 +274,11 @@ public sealed partial class ServerPackPlugin try { WebDestination? timedOut; - string status = ""; + string status; lock (_web.Gate) { timedOut = _web.TakeTimedOut(Environment.TickCount64); - if (timedOut != null) status = _web.Status; + status = _web.Status; } if (timedOut != null) Reply.Fail(status); } @@ -282,7 +307,7 @@ public sealed partial class ServerPackPlugin try { lock (_web.Gate) _web.Reset(); - Interlocked.Exchange(ref _webNoPanelNoted, 0); + Interlocked.Increment(ref _webLoginEpoch); } catch (Exception ex) { diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index a62293d..1caeac3 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -29,10 +29,13 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); r.Add("dreamweave web: profile keys separate accounts", ProfileKeys); r.Add("dreamweave web: ImGui only in WebButtons, no context switching, no host calls from draw", ThreadRules); + r.Add("dreamweave web: an open's answer lands only on its own request", ResultGeneration); + r.Add("dreamweave web: the source scan's helpers read code, not comments or strings", ScanHelpers); r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); } // -- Host wiring (source scan: the plugin is NativeAOT, so its host code can't run here) -- + // The rules are allow-lists: what may appear is named, so a new spelling of a forbidden call fails. private static string PluginsRoot() { @@ -63,55 +66,133 @@ internal static class DreamWeaveWebTests return files; } - /// The text with // comments removed (a "//" right after ':' is a URL, kept), so a rule named in a comment doesn't count. - private static string StripComments(string text) + /// + /// The text with // and /* */ comments removed. String literals ("...", @"...", $"...") and char + /// literals are kept as they are, so a "//" inside one is not a comment. + /// + internal static string StripComments(string text) { var sb = new System.Text.StringBuilder(text.Length); - foreach (string line in text.Split('\n')) + int i = 0; + while (i < text.Length) { - int at = 0, cut = -1; - while ((at = line.IndexOf("//", at, StringComparison.Ordinal)) >= 0) + char c = text[i]; + char next = i + 1 < text.Length ? text[i + 1] : '\0'; + if (c == '/' && next == '/') { - if (at == 0 || line[at - 1] != ':') { cut = at; break; } - at += 2; + while (i < text.Length && text[i] != '\n') i++; + continue; } - sb.Append(cut >= 0 ? line.Substring(0, cut) : line).Append('\n'); + if (c == '/' && next == '*') + { + int end = text.IndexOf("*/", i + 2, StringComparison.Ordinal); + i = end < 0 ? text.Length : end + 2; + sb.Append(' '); + continue; + } + if (c == '"' || (c == '@' && next == '"') || (c == '$' && next == '"') || (c == '$' && next == '@') || (c == '@' && next == '$')) + { + int start = i; + bool verbatim = false; + while (i < text.Length && text[i] != '"') { if (text[i] == '@') verbatim = true; i++; } + i++; // the opening quote + while (i < text.Length) + { + if (verbatim) + { + if (text[i] == '"' && i + 1 < text.Length && text[i + 1] == '"') { i += 2; continue; } + if (text[i] == '"') { i++; break; } + } + else + { + if (text[i] == '\\') { i += 2; continue; } + if (text[i] == '"' || text[i] == '\n') { i++; break; } + } + i++; + } + sb.Append(text, start, Math.Min(i, text.Length) - start); + continue; + } + if (c == '\'') + { + int start = i++; + while (i < text.Length && text[i] != '\'' && text[i] != '\n') i += text[i] == '\\' ? 2 : 1; + i++; + sb.Append(text, start, Math.Min(i, text.Length) - start); + continue; + } + sb.Append(c); + i++; } return sb.ToString(); } - /// The statement after each : a balanced { } block, or up to the next ';'. + /// The statement at : a balanced { } block, or up to the next ';'. + private static string StatementAt(string code, int i) + { + while (i < code.Length && char.IsWhiteSpace(code[i])) i++; + if (i < code.Length && code[i] == '{') + { + int depth = 0, j = i; + for (; j < code.Length; j++) + { + if (code[j] == '{') depth++; + else if (code[j] == '}' && --depth == 0) break; + } + return code.Substring(i, Math.Min(j + 1, code.Length) - i); + } + int semi = code.IndexOf(';', i); + return code.Substring(i, (semi < 0 ? code.Length : semi + 1) - i); + } + + /// The statement after each . private static List StatementsAfter(string code, string head) { var found = new List(); int at = 0; while ((at = code.IndexOf(head, at, StringComparison.Ordinal)) >= 0) { - int i = at + head.Length; - while (i < code.Length && char.IsWhiteSpace(code[i])) i++; - if (i < code.Length && code[i] == '{') - { - int depth = 0, j = i; - for (; j < code.Length; j++) - { - if (code[j] == '{') depth++; - else if (code[j] == '}' && --depth == 0) break; - } - found.Add(code.Substring(i, Math.Min(j + 1, code.Length) - i)); - } - else - { - int semi = code.IndexOf(';', i); - found.Add(code.Substring(i, (semi < 0 ? code.Length : semi + 1) - i)); - } - at = i; + found.Add(StatementAt(code, at + head.Length)); + at += head.Length; } return found; } - /// The token as a call or member access of its own: "ChatLine(" matches, "OnChatLine(" does not. - private static bool Mentions(string code, string token) - => System.Text.RegularExpressions.Regex.IsMatch(code, @"(?Every lock statement: its target (trimmed) and its body. + internal static List<(string Target, string Body)> Locks(string code) + { + var found = new List<(string, string)>(); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(code, @"\block\s*\(")) + { + int open = m.Index + m.Length - 1, depth = 0, j = open; + for (; j < code.Length; j++) + { + if (code[j] == '(') depth++; + else if (code[j] == ')' && --depth == 0) break; + } + if (j >= code.Length) { found.Add(("", "")); continue; } + found.Add((code.Substring(open + 1, j - open - 1).Trim(), StatementAt(code, j + 1))); + } + return found; + } + + /// + /// Every call in that is not a member call on + /// ("_web.Begin(" is allowed; "Send(", "Helper(", "if (", "x._web.Begin(" are not). + /// + internal static List CallsNotOn(string body, string receiver) + { + var bad = new List(); + var allowed = new System.Text.RegularExpressions.Regex("^" + System.Text.RegularExpressions.Regex.Escape(receiver) + @"\.[A-Za-z_][A-Za-z0-9_]*$"); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(body, @"(? System.Text.RegularExpressions.Regex.Replace(s, @"\s+", ""); private static int CountOf(string text, string needle) { @@ -182,33 +263,47 @@ internal static class DreamWeaveWebTests foreach (string f in SourceFiles(plugins)) Check.False(processStart.IsMatch(StripComments(File.ReadAllText(f))), Path.GetFileName(f) + ": no Process.Start under Plugins (ShellExecuteW only)"); + // WebButtons.cs calls only ImGui/SafeImGui, the launcher (under its lock) and the click it was handed. string buttons = StripComments(File.ReadAllText(buttonsPath)); - foreach (string banned in new[] { "Host.", "Send(", "OpenWeb(", "RunOnTick(", "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "ShellExecute" }) - Check.False(Mentions(buttons, banned), "WebButtons.cs: no " + banned + " (draw only draws)"); + int draw = buttons.IndexOf("public static void Draw(", StringComparison.Ordinal); + Check.True(draw >= 0, "WebButtons.Draw exists"); + string drawBody = draw < 0 ? "" : StatementAt(buttons, buttons.IndexOf(')', draw) + 1); + var drawAllowed = new System.Text.RegularExpressions.Regex(@"^(ImGui\.[A-Za-z]+|SafeImGui\.[A-Za-z]+|click|lock|if|foreach)\($"); + var drawCalls = new List(); + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(drawBody, @"(? drawLocks = StatementsAfter(buttons, "lock (l.Gate)"); + foreach (string pair in new[] { "Begin", "End", "Push", "Pop" }) + Check.False(System.Text.RegularExpressions.Regex.IsMatch(buttons, @"ImGui\." + pair), "WebButtons.cs: no ImGui." + pair + "* (no paired calls)"); + List<(string Target, string Body)> drawLocks = Locks(buttons); Check.Eq(drawLocks.Count, 1, "WebButtons.cs: one lock, to copy Pending and Status out"); - foreach (string s in drawLocks) - Check.False(bareImGui.IsMatch(s) || s.Contains("SafeImGui", StringComparison.Ordinal) || s.Contains("click(", StringComparison.Ordinal), - "WebButtons.cs: nothing is drawn or clicked under the lock"); + foreach (var (target, body) in drawLocks) + { + Check.Eq(target, "l.Gate", "WebButtons.cs: the lock is the launcher's Gate"); + Check.Eq(string.Join(" ", CallsNotOn(body, "l")), "", "WebButtons.cs: only launcher members under the lock"); + Check.Eq(Collapse(body), "{pending=l.Pending!=null;status=l.Status;}", "WebButtons.cs: the lock copies Pending and Status, nothing else"); + } string host = StripComments(File.ReadAllText(hostPath)); List cardHook = StatementsAfter(host, "partial void ServerCardActions()"); Check.Eq(cardHook.Count, 1, "DreamWeaveWebTools.cs implements ServerCardActions once"); string clickPath = cardHook.Count == 1 ? cardHook[0] : ""; - Check.True(clickPath.Contains("WebButtons.Draw(", StringComparison.Ordinal), "the card hook draws through WebButtons.Draw"); - Check.True(host.Contains("RunOnTick(() => StartLaunch(d))", StringComparison.Ordinal), "the button path queues StartLaunch with RunOnTick"); - Check.False(clickPath.Contains("StartLaunch(d)", StringComparison.Ordinal) && !clickPath.Contains("RunOnTick(", StringComparison.Ordinal), - "the card hook never calls StartLaunch directly"); + Check.True(clickPath.Contains("WebButtons.Draw(_web, Active, _webClick ??= d => RunOnTick(() => StartLaunch(d)));", StringComparison.Ordinal), + "the card hook draws through WebButtons.Draw, and a click only queues StartLaunch with RunOnTick"); + Check.Eq(CountOf(host, "StartLaunch("), 3, "StartLaunch: defined, queued by the click, called by the verb (nothing else)"); - // Every lock on the launcher holds launcher calls only: no send, open, reply or log under it. - List hostLocks = StatementsAfter(host, "lock (_web.Gate)"); + // Every lock in the host is on the launcher and holds launcher member calls only. + List<(string Target, string Body)> hostLocks = Locks(host); Check.True(hostLocks.Count >= 5, "the host takes the launcher's lock (" + hostLocks.Count + " places)"); - foreach (string s in hostLocks) - foreach (string banned in new[] { "Send(", "OpenWeb(", "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "Host.", "ShellExecute", "CloseWeb(" }) - Check.False(Mentions(s, banned), "no " + banned + " under lock (_web.Gate): " + s.Trim().Replace('\n', ' ')); + foreach (var (target, body) in hostLocks) + { + Check.Eq(target, "_web.Gate", "every lock in the host is lock (_web.Gate)"); + Check.Eq(string.Join(" ", CallsNotOn(body, "_web")), "", "only _web members under lock (_web.Gate): " + Collapse(body)); + } Check.False(host.Contains("DateTime", StringComparison.Ordinal) || host.Contains("Stopwatch", StringComparison.Ordinal), "nowMs comes from Environment.TickCount64 only"); Check.True(host.Contains("Environment.TickCount64", StringComparison.Ordinal), "the host uses Environment.TickCount64"); @@ -218,19 +313,82 @@ internal static class DreamWeaveWebTests Check.Eq(CountOf(host, "out launchCode"), 1, "launchCode is filled only by OnChatLine"); Check.True(host.Contains("DreamWeaveWeb.LaunchUrl(launchCode, ", StringComparison.Ordinal), "the code's one use is the launch URL"); + // The chat hook reads every line through the launcher, whatever the world: no Active before OnChatLine. + List chatHook = StatementsAfter(host, "private void WebChatText(string text, int chatType, ref bool eat)"); + Check.Eq(chatHook.Count, 1, "DreamWeaveWebTools.cs implements WebChatText once"); + string chat = chatHook.Count == 1 ? chatHook[0] : ""; + int onChat = chat.IndexOf("OnChatLine(", StringComparison.Ordinal); + Check.True(onChat > 0, "ServerChatText calls OnChatLine"); + Check.False(onChat > 0 && System.Text.RegularExpressions.Regex.IsMatch(chat.Substring(0, onChat), @"(?= 0, "the chat hook handles LaunchLine.Stale"); if (stale >= 0) { - int end = host.IndexOf("return;", stale, StringComparison.Ordinal); - string arm = end < 0 ? "" : host.Substring(stale, end - stale); - Check.True(arm.Contains("eat = true;", StringComparison.Ordinal), "Stale eats the line"); - foreach (string banned in new[] { "Reply.", "ChatLine(", "ChatFail(", "LogTagged(", "OpenWeb(", "Cancel(", "Host." }) - Check.False(Mentions(arm, banned), "Stale does nothing else: no " + banned); + int from = stale + "case LaunchLine.Stale:".Length; + int end = host.IndexOf("return;", from, StringComparison.Ordinal); + Check.Eq(end < 0 ? "" : Collapse(host.Substring(from, end - from)), "eat=true;", "the Stale arm is exactly 'eat = true; return;'"); } } + private static void ResultGeneration() + { + var w = new WebLauncher(); + w.Begin(Market, 0); + Check.True(w.OnChatLine(Line, 0x05, 100, out _, out _, out _) == LaunchLine.Code, "request 1: code"); + long gen1 = w.Generation; + Check.True(w.Begin(DreamWeaveWeb.ById("suit")!, 3_100) == LaunchBegin.Started, "request 2, 3 s later"); + Check.True(w.OnChatLine(Line, 0x05, 3_200, out _, out _, out _) == LaunchLine.Code, "request 2: code"); + long gen2 = w.Generation; + Check.True(gen2 != gen1, "each request has its own generation"); + Check.Eq(w.Status, "Opening Suit Builder...", "request 2 is opening"); + w.SetResult(gen1, "x"); + Check.Eq(w.Status, "Opening Suit Builder...", "request 1's late answer leaves the status alone"); + w.SetResult(gen2, "y"); + Check.Eq(w.Status, "y", "request 2's answer sets it"); + + // Pending, or after a Reset (a relog), an answer is ignored too. + var p = new WebLauncher(); + p.Begin(Market, 0); + long g = p.Generation; + p.SetResult(g, "x"); + Check.Eq(p.Status, "Asking DreamWeave for a login code for Market...", "ignored while a request is pending"); + p.OnChatLine(Line, 0x05, 100, out _, out _, out _); + g = p.Generation; + p.Reset(); + p.SetResult(g, "x"); + Check.Eq(p.Status, "", "an answer from before a Reset is ignored"); + + // A refused Begin moves nothing on. + var r = new WebLauncher(); + r.Begin(Market, 0); + r.OnChatLine(Line, 0x05, 100, out _, out _, out _); + long rg = r.Generation; + Check.True(r.Begin(Market, 200) == LaunchBegin.TooSoon, "too soon"); + r.SetResult(rg, "opened"); + Check.Eq(r.Status, "opened", "a TooSoon Begin keeps the open's generation"); + } + + private static void ScanHelpers() + { + string src = "int a = 1; // lock (x) { Send(); }\nstring u = \"https://x//y\"; /* Reply.Ok() */ char q = '\"'; string v = @\"a\"\"//b\"; lock (_web.Gate) b = 2;\n"; + string code = StripComments(src); + Check.False(code.Contains("Send", StringComparison.Ordinal) || code.Contains("Reply", StringComparison.Ordinal), "comments removed"); + Check.True(code.Contains("\"https://x//y\"", StringComparison.Ordinal), "// inside a string kept"); + Check.True(code.Contains("@\"a\"\"//b\"", StringComparison.Ordinal), "// inside a verbatim string kept"); + Check.True(code.Contains("lock (_web.Gate) b = 2;", StringComparison.Ordinal), "code after a char literal holding a quote kept"); + + var locks = Locks("lock(_web.Gate){ Send(\"x\"); } lock ( other ) _web.Begin(); lock (_web.Gate) { _web.Begin(d, Environment.TickCount64); if (a) b(); }"); + Check.Eq(locks.Count, 3, "every lock found, with or without a space"); + Check.Eq(locks[0].Target, "_web.Gate", "target"); + Check.Eq(string.Join(" ", CallsNotOn(locks[0].Body, "_web")), "Send(", "a bare call under the lock is caught"); + Check.Eq(locks[1].Target, "other", "another target is reported as it is"); + Check.Eq(string.Join(" ", CallsNotOn(locks[2].Body, "_web")), "if( b(", "keywords and helpers are not launcher calls"); + Check.Eq(string.Join(" ", CallsNotOn("x._web.Begin(); _web.Begin(); _web.Gate.Foo();", "_web")), "x._web.Begin( _web.Gate.Foo(", "only a direct _web member call is allowed"); + } + private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars private const string Line = "[WEB] Launch code: " + Code + " (single use, expires in 60 seconds)"; diff --git a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs index 7a50db9..25b7eaa 100644 --- a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs @@ -70,6 +70,12 @@ internal static class ServerPackCommandsTests Check.Eq(own.Length, 3, "an own line is appended"); Check.Eq(own[2], "/rserver x - one more line", "trimmed"); Check.True(own[0] == pinned[0] && own[1] == pinned[1], "the shared two come first, unchanged"); + + // DreamWeave's verbs follow the shared two. + string[] dw = ServerPackCommands.Usage("DreamWeave", new List { RynthCore.Plugin.RynthDreamWeave.DreamWeaveWeb.UsageLine() }); + Check.Eq(dw.Length, 3, "DreamWeave: three usage lines"); + Check.Eq(dw[2], "/rserver market | suit | abilities - open the website's Market, Suit Builder, Ability Planner, logged in as this account.", "DreamWeave's own line"); + Check.True(dw[0] == ServerPackCommands.Usage("DreamWeave")[0] && dw[1] == ServerPackCommands.Usage("DreamWeave")[1], "the shared two come first, unchanged"); } private static void Queue() -- 2.43.0 From d70f780e603ab0b38c61b93d0bd1fcd18d4a9b6c Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:31:21 -0800 Subject: [PATCH 17/29] RynthDreamWeave: Task 6 re-review, close the source-scan gaps - Calls: one CallPattern for the lock and Draw allow-lists, which also reads "?." member chains and a type-argument list before "(", so Reply?.Fail( and Notify( count as non-launcher calls. - Monitor is banned in WebButtons.cs and DreamWeaveWebTools.cs; the host takes the launcher's lock in exactly 9 places, and each lock body is pinned exactly (no host property read under it either). - ServerChatText: everything before its first lock is pinned exactly (declarations only), so no gate, return or throw can come before the launcher reads the line. - WebLauncher.cs holds no Action, Func or delegate; any scanned file with a raw string literal fails, since the scan does not model them. - Usage: "Market, Suit Builder or Ability Planner". The shared two lines are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 5 +- .../DreamWeaveWebTests.cs | 54 ++++++++++++++++--- .../ServerPackCommandsTests.cs | 2 +- 3 files changed, 51 insertions(+), 10 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index 0436ea3..199bb1f 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -38,8 +38,9 @@ internal static class DreamWeaveWeb var ids = new string[Destinations.Length]; var labels = new string[Destinations.Length]; for (int i = 0; i < Destinations.Length; i++) { ids[i] = Destinations[i].Id; labels[i] = Destinations[i].Label; } - return "/rserver " + string.Join(" | ", ids) + " - open the website's " + string.Join(", ", labels) - + ", logged in as this account."; + string choices = labels.Length < 2 ? string.Join("", labels) + : string.Join(", ", labels, 0, labels.Length - 1) + " or " + labels[labels.Length - 1]; + return "/rserver " + string.Join(" | ", ids) + " - open the website's " + choices + ", logged in as this account."; } /// The sign-in URL for a destination. The caller has already checked the code with LaunchWire. diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 1caeac3..5f09271 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -176,15 +176,22 @@ internal static class DreamWeaveWebTests return found; } + /// + /// A call: an identifier or a member chain (".", "?."), an optional type-argument list, then "(". + /// Group 1 is the chain; the type arguments are left out of it ("Notify(" is "Notify"). + /// + private static readonly System.Text.RegularExpressions.Regex CallPattern = new( + @"(?();{}]*>)?\s*\("); + /// /// Every call in that is not a member call on - /// ("_web.Begin(" is allowed; "Send(", "Helper(", "if (", "x._web.Begin(" are not). + /// ("_web.Begin(" is allowed; "Send(", "Helper(", "if (", "x._web.Begin(", "a?.Invoke(", "Notify(" are not). /// internal static List CallsNotOn(string body, string receiver) { var bad = new List(); var allowed = new System.Text.RegularExpressions.Regex("^" + System.Text.RegularExpressions.Regex.Escape(receiver) + @"\.[A-Za-z_][A-Za-z0-9_]*$"); - foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(body, @"(?(); - foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(drawBody, @"(? hostLocks = Locks(host); - Check.True(hostLocks.Count >= 5, "the host takes the launcher's lock (" + hostLocks.Count + " places)"); + Check.Eq(hostLocks.Count, 9, "the host takes the launcher's lock in exactly 9 places"); foreach (var (target, body) in hostLocks) { Check.Eq(target, "_web.Gate", "every lock in the host is lock (_web.Gate)"); Check.Eq(string.Join(" ", CallsNotOn(body, "_web")), "", "only _web members under lock (_web.Gate): " + Collapse(body)); } + // Each lock body, exactly: launcher calls and reads, nothing else (no host property read either). + string[] lockBodies = + { + "{begun=_web.Begin(d,Environment.TickCount64);status=_web.Status;}", // StartLaunch + "_web.Cancel(notSent);", // StartLaunch, send failed + "{kind=_web.OnChatLine(text,chatType,Environment.TickCount64,outd,outlaunchCode,out_);status=_web.Status;generation=_web.Generation;}", // ServerChatText + "_web.SetResult(generation,text);", // SetWebResult + "{timedOut=_web.TakeTimedOut(Environment.TickCount64);status=_web.Status;}", // ServerTick + "status=_web.Status;", // ServerInfoLines + "_web.Reset();", // ServerLoginComplete + "_web.Reset();", // ServerLogout + "_web.Reset();", // ServerShutdown + }; + Check.Eq(string.Join("\n", hostLocks.Select(l => Collapse(l.Body))), string.Join("\n", lockBodies), "the host's lock bodies, exactly"); Check.False(host.Contains("DateTime", StringComparison.Ordinal) || host.Contains("Stopwatch", StringComparison.Ordinal), "nowMs comes from Environment.TickCount64 only"); Check.True(host.Contains("Environment.TickCount64", StringComparison.Ordinal), "the host uses Environment.TickCount64"); @@ -319,8 +354,11 @@ internal static class DreamWeaveWebTests string chat = chatHook.Count == 1 ? chatHook[0] : ""; int onChat = chat.IndexOf("OnChatLine(", StringComparison.Ordinal); Check.True(onChat > 0, "ServerChatText calls OnChatLine"); - Check.False(onChat > 0 && System.Text.RegularExpressions.Regex.IsMatch(chat.Substring(0, onChat), @"(?", + "{LaunchLinekind=LaunchLine.NotOurs;try{WebDestination?d;stringlaunchCode;stringstatus;longgeneration;", + "ServerChatText: nothing but declarations before the launcher reads the line (a code must be eaten whatever the world is now)"); // Stale eats the line and does nothing else. int stale = host.IndexOf("case LaunchLine.Stale:", StringComparison.Ordinal); @@ -387,6 +425,8 @@ internal static class DreamWeaveWebTests Check.Eq(locks[1].Target, "other", "another target is reported as it is"); Check.Eq(string.Join(" ", CallsNotOn(locks[2].Body, "_web")), "if( b(", "keywords and helpers are not launcher calls"); Check.Eq(string.Join(" ", CallsNotOn("x._web.Begin(); _web.Begin(); _web.Gate.Foo();", "_web")), "x._web.Begin( _web.Gate.Foo(", "only a direct _web member call is allowed"); + Check.Eq(string.Join(" ", CallsNotOn("a?.Invoke(x); Notify(y); _web.Begin();", "_web")), "a?.Invoke( Notify(", "null-conditional and generic calls are calls"); + Check.Eq(string.Join(" ", CallsNotOn("_web?.Begin(); _web.Begin();", "_web")), "_web?.Begin(", "_web?. is not the allowed form; a generic _web member call is"); } private const string Code = "AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-_AbCde"; // 43 chars diff --git a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs index 25b7eaa..b088ea4 100644 --- a/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs @@ -74,7 +74,7 @@ internal static class ServerPackCommandsTests // DreamWeave's verbs follow the shared two. string[] dw = ServerPackCommands.Usage("DreamWeave", new List { RynthCore.Plugin.RynthDreamWeave.DreamWeaveWeb.UsageLine() }); Check.Eq(dw.Length, 3, "DreamWeave: three usage lines"); - Check.Eq(dw[2], "/rserver market | suit | abilities - open the website's Market, Suit Builder, Ability Planner, logged in as this account.", "DreamWeave's own line"); + Check.Eq(dw[2], "/rserver market | suit | abilities - open the website's Market, Suit Builder or Ability Planner, logged in as this account.", "DreamWeave's own line"); Check.True(dw[0] == ServerPackCommands.Usage("DreamWeave")[0] && dw[1] == ServerPackCommands.Usage("DreamWeave")[1], "the shared two come first, unchanged"); } -- 2.43.0 From 7003094f56a772b9aff407f35bfe315a5f05adab Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 15:43:49 -0800 Subject: [PATCH 18/29] RynthDreamWeave: final-review fixes (malformed code lines never shown, wording) - LaunchWire.IsSuccessShaped: a server line starting "[WEB] Launch code", well formed or not. OnChatLine keeps a malformed one out of chat: a pending request takes it as Refused with the unexpected-reply message; otherwise Stale inside the stale window, NotOurs after. TryParse and its pins are unchanged. - An empty "[WEB] " refusal is an unexpected reply too. - Wording: "an unexpected reply (is RynthDreamWeave up to date?)", "Wait a few seconds between website opens.", "Couldn't open the website." - Tests: the raw-string guard covers only the DreamWeave files the scan parses; the scan test's name says its catch logs through LogTagged; the directory walkers added on this branch use ServerProjectsTests.PluginsDir(). Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/LaunchWire.cs | 8 ++ .../DreamWeave/WebLauncher.cs | 29 +++++- .../DreamWeaveWebTools.cs | 4 +- .../DreamWeaveWebTests.cs | 98 ++++++++++++++----- 4 files changed, 107 insertions(+), 32 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs index aba5a34..551e481 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/LaunchWire.cs @@ -26,6 +26,14 @@ internal static class LaunchWire public static bool IsCodeChar(char c) => (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '_'; + /// + /// True when is a server line that starts like a success ("[WEB] Launch code"), + /// well formed or not. TryParse rejects a malformed one; the caller must still keep it out of chat, + /// since it may carry most of a code. + /// + public static bool IsSuccessShaped(string? text, int chatType) + => text != null && !ChatSource.IsPlayerAuthored(chatType) && ChatSource.StartsWithMarker(text, SuccessStem); + /// /// True when is a [WEB] reply from the server: then either /// is set (success) or is (a refusal). diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs index 0f7bb48..f2b058c 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebLauncher.cs @@ -23,7 +23,7 @@ internal sealed class WebLauncher { public readonly object Gate = new(); - private const string UnexpectedReply = "DreamWeave sent an unexpected reply."; + private const string UnexpectedReply = "an unexpected reply (is RynthDreamWeave up to date?)"; private WebDestination? _pending; private long _deadlineMs; @@ -72,13 +72,26 @@ internal sealed class WebLauncher /// caller eats it (on Code, message is empty). Otherwise a line TryParse reads as a valid code is /// Stale (eat it, open nothing; dest null, code and message empty) while nowMs is before the /// forward-only stale deadline, and NotOurs after. Any other line outside a request is NotOurs. + /// A success-shaped line TryParse rejects (a malformed code) is treated the same way, never shown: + /// a pending request takes it as Refused with the unexpected-reply message; otherwise Stale inside + /// the window and NotOurs after. An empty refusal, or one holding a code-length run, is unexpected too. /// public LaunchLine OnChatLine(string text, int chatType, long nowMs, out WebDestination? dest, out string code, out string message) { dest = null; code = ""; message = ""; - if (!LaunchWire.TryParse(text, chatType, out string parsedCode, out string refusal)) return LaunchLine.NotOurs; + if (!LaunchWire.TryParse(text, chatType, out string parsedCode, out string refusal)) + { + if (!LaunchWire.IsSuccessShaped(text, chatType)) return LaunchLine.NotOurs; + WebDestination? sp = _pending; + if (sp == null || nowMs >= _deadlineMs) return nowMs < _staleUntilMs ? LaunchLine.Stale : LaunchLine.NotOurs; + _pending = null; + dest = sp; + message = UnexpectedReply; + Status = sp.Label + ": DreamWeave sent " + UnexpectedReply; + return LaunchLine.Refused; + } WebDestination? p = _pending; if (p == null || nowMs >= _deadlineMs) @@ -92,8 +105,16 @@ internal sealed class WebLauncher Status = "Opening " + p.Label + "..."; return LaunchLine.Code; } - message = HasCodeRun(refusal) ? UnexpectedReply : refusal; - Status = p.Label + ": DreamWeave said: " + message; + if (refusal.Trim().Length == 0 || HasCodeRun(refusal)) + { + message = UnexpectedReply; + Status = p.Label + ": DreamWeave sent " + UnexpectedReply; + } + else + { + message = refusal; + Status = p.Label + ": DreamWeave said: " + refusal; + } return LaunchLine.Refused; } diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index 66f55c8..71aec1f 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -116,7 +116,7 @@ public sealed partial class ServerPackPlugin } if (begun == LaunchBegin.TooSoon) { - Reply.Fail("Wait a few seconds between web opens."); + Reply.Fail("Wait a few seconds between website opens."); return; } @@ -134,7 +134,7 @@ public sealed partial class ServerPackPlugin try { LogTagged("Starting a web open failed: " + ex.GetType().Name); - Reply.Fail("Couldn't start the web open."); + Reply.Fail("Couldn't open the website."); } catch (Exception) { diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 5f09271..05d8914 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -28,8 +28,9 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: a late code is eaten while it could still be valid", LateCodeIsStale); r.Add("dreamweave web: overlapping requests never leak a code to chat", OverlappingRequests); r.Add("dreamweave web: profile keys separate accounts", ProfileKeys); - r.Add("dreamweave web: ImGui only in WebButtons, no context switching, no host calls from draw", ThreadRules); + r.Add("dreamweave web: ImGui only in WebButtons, no context switching, draw makes no host calls (its catch logs via LogTagged)", ThreadRules); r.Add("dreamweave web: an open's answer lands only on its own request", ResultGeneration); + r.Add("dreamweave web: a malformed launch-code line never reaches chat", MalformedSuccess); r.Add("dreamweave web: the source scan's helpers read code, not comments or strings", ScanHelpers); r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); } @@ -37,15 +38,6 @@ internal static class DreamWeaveWebTests // -- Host wiring (source scan: the plugin is NativeAOT, so its host code can't run here) -- // The rules are allow-lists: what may appear is named, so a new spelling of a forbidden call fails. - private static string PluginsRoot() - { - string? dir = AppContext.BaseDirectory; - while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) - dir = Path.GetDirectoryName(dir); - if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); - return Path.Combine(dir, "Plugins"); - } - private static IEnumerable SourceFiles(string root) => Directory.GetFiles(root, "*.cs", SearchOption.AllDirectories) .Where(p => !p.Contains(Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) @@ -212,7 +204,7 @@ internal static class DreamWeaveWebTests // panel: each hands off to its Web* method before its own code, so no gate of theirs comes first. private static void HooksHandOff() { - string dw = Path.Combine(PluginsRoot(), "RynthCore.Plugin.RynthDreamWeave"); + string dw = Path.Combine(ServerProjectsTests.PluginsDir(), "RynthCore.Plugin.RynthDreamWeave"); string plugin = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeavePlugin.cs"))); string skills = StripComments(File.ReadAllText(Path.Combine(dw, "DreamWeaveSkills.cs"))); (string Code, string Head, string Call)[] hooks = @@ -242,9 +234,11 @@ internal static class DreamWeaveWebTests Check.False(web.Contains("partial void " + hook + "(", StringComparison.Ordinal), "DreamWeaveWebTools.cs leaves " + hook + " to the hub"); } + // The draw path makes no host calls. ServerCardActions' catch (render thread) does log through + // LogTagged once per failure, the shared pattern RenderEmbedded's own catch already follows. private static void ThreadRules() { - string plugins = PluginsRoot(); + string plugins = ServerProjectsTests.PluginsDir(); string dw = Path.Combine(plugins, "RynthCore.Plugin.RynthDreamWeave"); string buttonsPath = Path.Combine(dw, "DreamWeave", "WebButtons.cs"); string hostPath = Path.Combine(dw, "DreamWeaveWebTools.cs"); @@ -266,14 +260,15 @@ internal static class DreamWeaveWebTests } } + // StripComments does not model raw string literals: a DreamWeave file with one must fail, not scan + // wrongly. Only the files this scan parses in depth are held to it (the web tools' files and the two hub + // files HooksHandOff reads), so another server, or another DreamWeave feature, can't break it. + foreach (string f in WebFiles(dw).Concat(new[] { Path.Combine(dw, "DreamWeavePlugin.cs"), Path.Combine(dw, "DreamWeaveSkills.cs") })) + Check.False(File.ReadAllText(f).Contains("\"\"\"", StringComparison.Ordinal), Path.GetFileName(f) + ": no raw string literal (the scan does not support them)"); + var processStart = new System.Text.RegularExpressions.Regex(@"\bProcess\s*\.\s*Start\b"); foreach (string f in SourceFiles(plugins)) - { - string raw = File.ReadAllText(f); - // StripComments does not model raw string literals: a file with one must fail, not scan wrongly. - Check.False(raw.Contains("\"\"\"", StringComparison.Ordinal), Path.GetFileName(f) + ": no raw string literal (the scan does not support them)"); - Check.False(processStart.IsMatch(StripComments(raw)), Path.GetFileName(f) + ": no Process.Start under Plugins (ShellExecuteW only)"); - } + Check.False(processStart.IsMatch(StripComments(File.ReadAllText(f))), Path.GetFileName(f) + ": no Process.Start under Plugins (ShellExecuteW only)"); // Monitor would take the launcher's lock without a lock statement, out of the scan's sight. var monitor = new System.Text.RegularExpressions.Regex(@"\bMonitor\s*\."); @@ -371,6 +366,61 @@ internal static class DreamWeaveWebTests } } + private static void MalformedSuccess() + { + string head = "[WEB] Launch code: "; + string long44 = head + Code + "A (single use, expires in 60 seconds)"; + string dotted = head + Code + "."; + foreach (string l in new[] { long44, dotted }) + { + Check.True(!Parse(l, 0x05, out _, out _), "TryParse still rejects it: " + l.Length + " chars"); + Check.True(LaunchWire.IsSuccessShaped(l, 0x05), "success-shaped: " + l.Length + " chars"); + Check.False(LaunchWire.IsSuccessShaped(l, 0x02), "a player's copy is not success-shaped"); + } + Check.True(LaunchWire.IsSuccessShaped(" [WEB] Launch code", 0x05), "the stem alone, past leading space"); + Check.False(LaunchWire.IsSuccessShaped("[WEB] Signing in is turned off.", 0x05), "a refusal is not success-shaped"); + Check.False(LaunchWire.IsSuccessShaped(null, 0x05), "null is not success-shaped"); + + foreach (string l in new[] { long44, dotted }) + { + // Pending: the request takes the line as an unexpected reply; nothing of the code survives. + var w = new WebLauncher(); + w.Begin(Market, 0); + var k = w.OnChatLine(l, 0x05, 100, out var dest, out string code, out string msg); + Check.True(k == LaunchLine.Refused, "pending: a malformed code line is Refused (eaten), not NotOurs"); + Check.True(ReferenceEquals(dest, Market), "pending: the destination is handed back"); + Check.Eq(code, "", "pending: no code"); + Check.Eq(msg, "an unexpected reply (is RynthDreamWeave up to date?)", "pending: the fixed message"); + Check.Eq(w.Status, "Market: DreamWeave sent an unexpected reply (is RynthDreamWeave up to date?)", "pending: the status"); + Check.True(w.Pending == null, "pending: cleared"); + Check.False(w.Status.Contains(Code.Substring(0, 12), StringComparison.Ordinal) || msg.Contains(Code.Substring(0, 12), StringComparison.Ordinal), "pending: no code in status or message"); + + // A player's copy while pending is still not ours. + var p = new WebLauncher(); + p.Begin(Market, 0); + Check.True(p.OnChatLine(l, 0x02, 100, out _, out _, out _) == LaunchLine.NotOurs, "player copy (0x02): not ours"); + Check.True(p.Pending != null, "player copy leaves the request pending"); + + // Not pending: Stale inside the window, NotOurs after it. + var s = new WebLauncher(); + s.Begin(Market, 0); + s.TakeTimedOut(10_000); + Check.True(s.OnChatLine(l, 0x05, 20_000, out dest, out code, out msg) == LaunchLine.Stale, "not pending, inside the window: Stale"); + Check.True(dest == null && code == "" && msg == "", "Stale carries nothing"); + Check.True(s.OnChatLine(l, 0x05, 70_001, out _, out _, out _) == LaunchLine.NotOurs, "after the window: NotOurs"); + Check.True(new WebLauncher().OnChatLine(l, 0x05, 5, out _, out _, out _) == LaunchLine.NotOurs, "no Begin ever: NotOurs"); + } + + // An empty refusal is an unexpected reply too. + foreach (string l in new[] { "[WEB] ", "[WEB] " }) + { + var e = new WebLauncher(); + e.Begin(Market, 0); + Check.True(e.OnChatLine(l, 0x05, 10, out _, out _, out string msg) == LaunchLine.Refused, "empty refusal: Refused"); + Check.Eq(msg, "an unexpected reply (is RynthDreamWeave up to date?)", "empty refusal: the fixed message"); + } + } + private static void ResultGeneration() { var w = new WebLauncher(); @@ -663,15 +713,15 @@ internal static class DreamWeaveWebTests Check.Eq(code, "", "no code"); Check.True(!msg.Contains(Code), "message has no code"); Check.True(!w.Status.Contains(Code), "status has no code"); - Check.Eq(msg, "DreamWeave sent an unexpected reply.", "fixed replacement text"); - Check.Eq(w.Status, "Market: DreamWeave said: DreamWeave sent an unexpected reply.", "status from the replacement"); + Check.Eq(msg, "an unexpected reply (is RynthDreamWeave up to date?)", "fixed replacement text"); + Check.Eq(w.Status, "Market: DreamWeave sent an unexpected reply (is RynthDreamWeave up to date?)", "status from the replacement"); Check.True(w.Pending == null, "pending cleared"); // A long run of code chars anywhere, and a 42-char run (below the limit) left alone. var w2 = new WebLauncher(); w2.Begin(Market, 0); w2.OnChatLine("[WEB] x " + Code + Code + " y", 0x05, 10, out _, out _, out msg); - Check.Eq(msg, "DreamWeave sent an unexpected reply.", "longer run replaced"); + Check.Eq(msg, "an unexpected reply (is RynthDreamWeave up to date?)", "longer run replaced"); var w3 = new WebLauncher(); w3.Begin(Market, 0); w3.OnChatLine("[WEB] id " + Code.Substring(1) + " ok", 0x05, 10, out _, out _, out msg); @@ -825,12 +875,8 @@ internal static class DreamWeaveWebTests private static string[] ServerPluginIds() { - string? dir = AppContext.BaseDirectory; - while (dir != null && !Directory.Exists(Path.Combine(dir, "Plugins", "Shared", "ServerPack"))) - dir = Path.GetDirectoryName(dir); - if (dir == null) throw new DirectoryNotFoundException("Plugins not found above " + AppContext.BaseDirectory); var ids = new List(); - foreach (string p in Directory.GetDirectories(Path.Combine(dir, "Plugins"), "RynthCore.Plugin.Rynth*")) + foreach (string p in Directory.GetDirectories(ServerProjectsTests.PluginsDir(), "RynthCore.Plugin.Rynth*")) { string csproj = Path.Combine(p, Path.GetFileName(p) + ".csproj"); if (!File.Exists(csproj)) continue; -- 2.43.0 From b72720aca4521aac6c8286865cf9ee10b69a0b75 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 13:37:48 -0800 Subject: [PATCH 19/29] RynthDreamWeave: declare minEngineApi 90 so release builds stop raising it to the SDK API The csproj declared nothing, so ServerPlugin.props defaulted it to 66, and a release build (RynthPluginSharedSdk=true) raises any declared value under 88 to the SDK's API (95): the plugin would then load on no current engine. Audit of every RynthCore SDK member the plugin compiles against (DreamWeave's own code, the shared ServerPack and the RynthSuite files it links). "Isolated" means called only from a [MethodImpl(NoInlining)] method behind its Has* check, which an older Runtime\PluginShared SDK copy cannot fail; a Has* check inside an ordinary method does not protect it. Not isolated, so the minimum must cover them: - v90 RynthAcPanel: type of the static field MainAcPanels (DreamWeaveSkills.cs) - v90 IsAcPanelOpen, AcPanel, RynthAcPanelOp, HasAcPanels: DreamWeaveSkills.cs (HasAcPanels checked in the same method) - v90 PanelScale, PanelDragWithLastItem, GetIconTexture, RynthIconKind: DreamWeave/SkillsPanel.cs - v90 HasFramelessWindows: ServerPackPlugin.BuildSectionsJson - v89 SetPanelOpen, HasSetPanelOpen, RynthPanelOpen: ServerPackPlugin.SetWindow, DreamWeaveSkills.cs, SkillsPanel.cs (Has* checked in the same method) - v79 HasTraining, TryGetTrainingInfo, TrainSkill: DreamWeave/SkillsReader.cs (HasTraining checked in the same method) - v78 HasServerMessages, SetServerMessageInterest: ServerPackPlugin.Initialize; RynthCore.PluginSdk.Net.ServerMessage: DreamWeaveSkills.ServerMessage - before v62 (table fields ahead of the v62 append marker in RynthCoreApiNative.cs): Log, WriteToChat, InvokeChatParser, TryGetWorldName, TryGetAccountName, TryGetObjectName, TryGetPlayerVitals, TryGetObjectIntProperty, TryGetObjectQuadProperty, GetPlayerId, ImGuiContext, Version and their Has* checks Isolated, so they do not count: - v94 HasWebPanel, OpenWebPanel, GetWebPanelState, CloseWebPanel and the WebPanel* types: only in ServerPackWeb.cs's NoInlining *Core methods, which catch MissingMethodException and TypeLoadException (from pr/serverpack-web-panel-engine on) - the bar menu (v95) uses no SDK member: it compares Host.Version to DreamWeaveWeb.BarMenuEngineApi Highest non-isolated API: 90. Declared 90. Co-Authored-By: Claude Opus 5.5 --- .../RynthCore.Plugin.RynthDreamWeave.csproj | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index 76189d4..e719ce5 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -11,6 +11,11 @@ play.acdreamweave.com DreamWeave|Dream Weave DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, with Market, Suit Builder and Ability Planner buttons that open the website logged in as this account, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. + + 90 -- 2.43.0 From 0ba3b5909e3fc72a08b4b0fcb2e135934b2890ea Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 16:54:51 -0800 Subject: [PATCH 20/29] 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 --- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 3 + Plugins/Shared/ServerPack/ServerPackWeb.cs | 177 ++++++++- Plugins/Shared/ServerPack/ServerPlugin.props | 1 + Plugins/Shared/ServerPack/ServerWebOpen.cs | 8 +- Plugins/Shared/ServerPack/ServerWebPanel.cs | 203 ++++++++++ Tools/RynthServerPack.Tests/Program.cs | 1 + .../RynthServerPack.Tests.csproj | 2 + .../ServerWebPanelTests.cs | 360 ++++++++++++++++++ 8 files changed, 733 insertions(+), 22 deletions(-) create mode 100644 Plugins/Shared/ServerPack/ServerWebPanel.cs create mode 100644 Tools/RynthServerPack.Tests/ServerWebPanelTests.cs diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index a30ac23..71e8046 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -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."); diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index d2ee718..e27e758 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -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!; + + /// The engine has a web panel (HasWebPanel; false on an older core or SDK). Any thread. + private bool PanelAvailable => WebPanel.Available; private static void Finish(Action done, WebOpenOutcome outcome) { try { done(outcome); } catch { } } - /// Opens the page (pump thread). `done` gets the route taken and a message without the URL. + /// Opens the page (pump thread). `done` gets the route taken and a message without the URL, once. internal void OpenWeb(WebOpenRequest r, Action 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); + } + + /// The panel's answer (pump thread: at once, or from the tick's poll). Exactly one Finish or browser open. + private void AfterPanel(WebOpenRequest r, PanelResult result, Action 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 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(); } - /// Closes the engine's web panel if this plugin opened one. Nothing to close until the panel API is wired. + + /// The tick's poll of a queued open (OnTick, pump thread). + private void PollWeb() + { + try { _webPanel?.Poll(Environment.TickCount64); } + catch (Exception) { } + } + + /// Closes the engine's web panel only if this plugin opened it; answers a waiting open. Pump thread. 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); +} \ No newline at end of file diff --git a/Plugins/Shared/ServerPack/ServerPlugin.props b/Plugins/Shared/ServerPack/ServerPlugin.props index d7abb0d..3fc013a 100644 --- a/Plugins/Shared/ServerPack/ServerPlugin.props +++ b/Plugins/Shared/ServerPack/ServerPlugin.props @@ -69,6 +69,7 @@ + diff --git a/Plugins/Shared/ServerPack/ServerWebOpen.cs b/Plugins/Shared/ServerPack/ServerWebOpen.cs index 760c526..69618b7 100644 --- a/Plugins/Shared/ServerPack/ServerWebOpen.cs +++ b/Plugins/Shared/ServerPack/ServerWebOpen.cs @@ -19,7 +19,13 @@ internal sealed record WebOpenRequest(string Url, IReadOnlyList AllowedH internal enum WebOpenRoute { Panel, Browser, Refused } /// What the engine's panel did. Only a refusal before navigating may fall back to the browser. -internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate } +/// +/// 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. +/// +internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate, OpenedInBrowserByEngine, BadArgs, Pending, Closed, NoAnswer } /// What happened. The message never contains the URL. internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message); diff --git a/Plugins/Shared/ServerPack/ServerWebPanel.cs b/Plugins/Shared/ServerPack/ServerWebPanel.cs new file mode 100644 index 0000000..e0d9e90 --- /dev/null +++ b/Plugins/Shared/ServerPack/ServerWebPanel.cs @@ -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; + +/// The engine's web-panel calls, in primitives and strings only (WEB_PANEL.md's values as ints). +internal interface IWebPanelEngine +{ + bool HasPanel(); + /// A handle (> 0), or a negative WebPanelResult. + int Open(string url, string[] allowlist, string profileKey, string title); + /// The WebPanelStatus; fills the WebPanelStateFlags, the error and the navigation count. + int GetState(int handle, out int flags, out int error, out uint navigationCount); + int Close(int handle); +} + +/// WEB_PANEL.md's numbers (RynthCore.PluginSdk WebPanelResult, WebPanelStatus, WebPanelStateFlags). +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 +{ + /// + /// 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. + /// + public const long PollTimeoutMs = 20_000; + + private sealed class WaitingOpen + { + public WaitingOpen(int handle, long deadlineMs, Action then) + { + Handle = handle; + DeadlineMs = deadlineMs; + Then = then; + } + + public int Handle { get; } + public long DeadlineMs { get; } + public Action 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; + + /// The engine has a web panel. False when the call throws. + public bool Available + { + get + { + try { return _engine.HasPanel(); } + catch (Exception) { return false; } + } + } + + /// An open is queued and not yet answered. + public bool Waiting => Volatile.Read(ref _waiting) != null; + + /// OpenWebPanel's return: a handle is Pending (queued, not opened); else the refusal. + 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; + } + } + + /// + /// 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. + /// + 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; + } + } + + /// + /// Opens in the panel. 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. + /// + public void Open(WebOpenRequest r, long nowMs, Action then) + { + Answer(Interlocked.Exchange(ref _waiting, null), PanelResult.Closed); + + int code; + try + { + var hosts = new List(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)); + } + + /// The tick: answers the waiting open once its state decides, or at the timeout. + 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); + } + + /// Closes the panel only if this plugin opened it, and answers a waiting open Closed. + 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 then, PanelResult result) + { + try { then(result); } + catch (Exception) { } + } +} \ No newline at end of file diff --git a/Tools/RynthServerPack.Tests/Program.cs b/Tools/RynthServerPack.Tests/Program.cs index 36323eb..3d28d8a 100644 --- a/Tools/RynthServerPack.Tests/Program.cs +++ b/Tools/RynthServerPack.Tests/Program.cs @@ -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); } diff --git a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj index 68c8d8a..b846c57 100644 --- a/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj +++ b/Tools/RynthServerPack.Tests/RynthServerPack.Tests.csproj @@ -34,6 +34,8 @@ + + diff --git a/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs b/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs new file mode 100644 index 0000000..c01627e --- /dev/null +++ b/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs @@ -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 Closed = new(); + public readonly List 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()) + Check.Eq(ServerWebOpen.FallbackToBrowser(p), p == PanelResult.RefusedBeforeNavigate, "fallback for " + p); + } + + private static List Answers(out Action then) + { + var list = new List(); + 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(); + 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(); + 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; + } +} \ No newline at end of file -- 2.43.0 From 9a2cbb59c7655d9a0fefa922082db2bcece58399 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 17:20:38 -0800 Subject: [PATCH 21/29] ServerPack: one browser decision after the panel, pinned by scan AfterPanel now asks ServerWebOpen.FallbackToBrowser first and opens the browser only there; the RefusedBeforeNavigate switch arm is gone. A source scan pins OpenInBrowser(r, done) to exactly two places (OpenWeb's browser route and right after the guard), so a browser open added to another arm (a spent code opened twice) fails the tests. Checked by mutation: an extra arm gives 3, a moved call fails the guard check. A newer Open answers the older waiting open Closed only once the engine has queued it; a refused or throwing second open leaves the first waiting (test added, RED against the old order). The SDK-name scan also covers the WebPanel*Fn table slots. Trailing newlines restored. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 14 ++++-- Plugins/Shared/ServerPack/ServerWebPanel.cs | 9 ++-- .../ServerWebPanelTests.cs | 47 ++++++++++++++++++- 3 files changed, 58 insertions(+), 12 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index e27e758..102dffc 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -71,6 +71,14 @@ public sealed partial class ServerPackPlugin { try { + // The one browser decision after the panel (ServerWebOpen.FallbackToBrowser: a refusal before + // navigating only). Every other answer below ends without the browser: the code may be spent. + if (ServerWebOpen.FallbackToBrowser(result)) + { + LogTagged("web panel: " + result + ", using the browser"); + OpenInBrowser(r, done); + return; + } switch (result) { case PanelResult.Opened: @@ -81,10 +89,6 @@ public sealed partial class ServerPackPlugin 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. @@ -225,4 +229,4 @@ public sealed partial class ServerPackPlugin [MethodImpl(MethodImplOptions.NoInlining)] private int WebPanelCloseCore(int handle) => Host.CloseWebPanel(handle); -} \ No newline at end of file +} diff --git a/Plugins/Shared/ServerPack/ServerWebPanel.cs b/Plugins/Shared/ServerPack/ServerWebPanel.cs index e0d9e90..ba5b816 100644 --- a/Plugins/Shared/ServerPack/ServerWebPanel.cs +++ b/Plugins/Shared/ServerPack/ServerWebPanel.cs @@ -128,12 +128,11 @@ internal sealed class ServerWebPanel /// /// Opens in the panel. 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. + /// for a refusal, else later from Poll, Close or a newer Open. A newer Open that the engine queued + /// answers the older one Closed (the engine superseded it); a refused one leaves the older one waiting. /// public void Open(WebOpenRequest r, long nowMs, Action then) { - Answer(Interlocked.Exchange(ref _waiting, null), PanelResult.Closed); - int code; try { @@ -152,7 +151,7 @@ internal sealed class ServerWebPanel return; } Interlocked.Exchange(ref _handle, code); - Interlocked.Exchange(ref _waiting, new WaitingOpen(code, nowMs + PollTimeoutMs, then)); + Answer(Interlocked.Exchange(ref _waiting, new WaitingOpen(code, nowMs + PollTimeoutMs, then)), PanelResult.Closed); } /// The tick: answers the waiting open once its state decides, or at the timeout. @@ -200,4 +199,4 @@ internal sealed class ServerWebPanel try { then(result); } catch (Exception) { } } -} \ No newline at end of file +} diff --git a/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs b/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs index c01627e..afe243e 100644 --- a/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs +++ b/Tools/RynthServerPack.Tests/ServerWebPanelTests.cs @@ -232,6 +232,33 @@ internal static class ServerWebPanelTests p3.Open(Req, 2, _ => { }); p3.Close(); Check.Eq(string.Join(",", e3.Closed), "9", "a refused open keeps the earlier handle ours to close"); + + // A refused second open leaves the first one waiting; the tick still answers it. + foreach (int refusal in new[] { -1, -2, -3, -4, -5 }) + { + var e4 = new FakeEngine { OpenReturns = 7, Status = S_Starting }; + var p4 = new ServerWebPanel(e4); + var a1 = Answers(out var t1); + var a2 = Answers(out var t2); + p4.Open(Req, 0, t1); + e4.OpenReturns = refusal; + p4.Open(Req, 10, t2); + Check.Eq(a1.Count, 0, "refused second open (" + refusal + "): the first is not answered"); + Check.True(p4.Waiting, "refused second open (" + refusal + "): the first still waits"); + Check.Eq(a2.Count, 1, "refused second open (" + refusal + "): answered at once"); + e4.Status = S_Ready; + p4.Poll(20); + Check.Eq(string.Join(",", a1), PanelResult.Opened.ToString(), "refused second open (" + refusal + "): the first opens on the tick"); + } + // Thrown second open: the same. + var e5 = new FakeEngine { OpenReturns = 7, Status = S_Starting }; + var p5 = new ServerWebPanel(e5); + var b1 = Answers(out var u1); + p5.Open(Req, 0, u1); + e5.ThrowOnOpen = true; + p5.Open(Req, 10, _ => { }); + Check.Eq(b1.Count, 0, "a second open that throws leaves the first unanswered"); + Check.True(p5.Waiting, "and waiting"); } private static void Exceptions() @@ -282,7 +309,7 @@ internal static class ServerWebPanelTests 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"); + var sdkName = new System.Text.RegularExpressions.Regex(@"\b(HasWebPanel|OpenWebPanel|NavigateWebPanel|CloseWebPanel|GetWebPanelState|WebPanelOptions|WebPanelState|WebPanelStatus|WebPanelFlags|WebPanelResult|WebPanelStateFlags|WebPanelOpenNative|WebPanelStateNative|WebPanelOpenFn|WebPanelNavigateFn|WebPanelCloseFn|WebPanelGetStateFn)\b"); string[] helpers = { "WebPanelHasCore", "WebPanelOpenCore", "WebPanelStateCore", "WebPanelCloseCore" }; // Every server plugin source other than ServerPackWeb.cs names none of them (the pure seam uses ints). @@ -327,6 +354,15 @@ internal static class ServerWebPanelTests } Check.True(web.Contains("Flags = WebPanelFlags.FallbackToBrowser", StringComparison.Ordinal), "the open asks the engine to fall back to the browser"); + // The browser opens from two places only: OpenWeb's browser route, and right after AfterPanel's + // FallbackToBrowser guard. A browser open in any switch arm would spend the code twice. + string collapsed = System.Text.RegularExpressions.Regex.Replace(web, @"\s+", ""); + Check.Eq(CountOf(web, "OpenInBrowser(r, done)"), 2, "ServerPackWeb.cs: OpenInBrowser(r, done) appears exactly twice"); + Check.Eq(CountOf(collapsed, "if(ServerWebOpen.FallbackToBrowser(result)){LogTagged(\"webpanel:\"+result+\",usingthebrowser\");OpenInBrowser(r,done);return;}"), 1, + "AfterPanel: the browser open sits right after the FallbackToBrowser guard"); + Check.Eq(CountOf(collapsed, "}OpenInBrowser(r,done);}"), 1, "OpenWeb: the other is the browser route at its end"); + Check.Eq(CountOf(web, "ServerWebOpen.FallbackToBrowser("), 1, "AfterPanel asks FallbackToBrowser once"); + // 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"); @@ -343,6 +379,13 @@ internal static class ServerWebPanelTests Check.Eq(System.Text.RegularExpressions.Regex.Matches(web, @"\b_webPanel\?\.Poll\(Environment\.TickCount64\)").Count, 1, "PollWeb polls with Environment.TickCount64"); } + private static int CountOf(string text, string needle) + { + int n = 0, at = 0; + while ((at = text.IndexOf(needle, at, StringComparison.Ordinal)) >= 0) { n++; at += needle.Length; } + return n; + } + private static int BodyEnd(string code, int from) { int open = code.IndexOf('{', from); @@ -357,4 +400,4 @@ internal static class ServerWebPanelTests } return code.Length; } -} \ No newline at end of file +} -- 2.43.0 From 865c3a399787155864ff7a6ba77ffdd3f1658e02 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 13:28:29 -0800 Subject: [PATCH 22/29] ServerPack: the web panel is plugin API v94 The engine's web panel landed as plugin API v94 (was v93 provisional on up/web-panel; renumbered after upstream's v93). Only comments named the number: the panel is found through RynthCoreHost.HasWebPanel. Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackWeb.cs | 2 +- Plugins/Shared/ServerPack/ServerWebPanel.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackWeb.cs b/Plugins/Shared/ServerPack/ServerPackWeb.cs index 102dffc..6840ed0 100644 --- a/Plugins/Shared/ServerPack/ServerPackWeb.cs +++ b/Plugins/Shared/ServerPack/ServerPackWeb.cs @@ -4,7 +4,7 @@ // 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 +// The panel (RynthCore plugin API v94, 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 diff --git a/Plugins/Shared/ServerPack/ServerWebPanel.cs b/Plugins/Shared/ServerPack/ServerWebPanel.cs index ba5b816..978e309 100644 --- a/Plugins/Shared/ServerPack/ServerWebPanel.cs +++ b/Plugins/Shared/ServerPack/ServerWebPanel.cs @@ -1,4 +1,4 @@ -// ServerWebPanel.cs - the engine's web panel (RynthCore plugin API v93, docs\WEB_PANEL.md) as the +// ServerWebPanel.cs - the engine's web panel (RynthCore plugin API v94, 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. -- 2.43.0 From 4afb8f3ac362dd7768de223bc83b52a64d6398e5 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 20:07:53 -0800 Subject: [PATCH 23/29] ServerPack: optional bar menu on the server's window (ServerBarMenu hook) Co-Authored-By: Claude Opus 5.5 --- Plugins/Shared/ServerPack/ServerPackModel.cs | 19 ++++++- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 10 +++- .../ServerPackModelTests.cs | 56 +++++++++++++++++++ 3 files changed, 83 insertions(+), 2 deletions(-) diff --git a/Plugins/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs index da1e059..016e24e 100644 --- a/Plugins/Shared/ServerPack/ServerPackModel.cs +++ b/Plugins/Shared/ServerPack/ServerPackModel.cs @@ -21,6 +21,9 @@ namespace RynthCore.Plugin.ServerPack; /// RynthCore's verdict for this plugin's server. internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason); +/// One entry of the server window's bar-icon dropdown: a click runs as a chat command. is one Phosphor glyph. +internal sealed record ServerBarMenuItem(string Id, string Tooltip, string Icon, string Command); + internal sealed class ServerPackModel { /// Payloads longer than this are not ours (a push is a few hundred bytes). @@ -170,7 +173,7 @@ internal sealed class ServerPackModel /// shared "Server" section of the Mini Remote. /// public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList? pages = null, - IReadOnlyList? windows = null, bool frameless = false) + IReadOnlyList? windows = null, bool frameless = false, IReadOnlyList? barMenu = null) { var sb = new StringBuilder(512); sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name)); @@ -185,6 +188,20 @@ internal sealed class ServerPackModel sb.Append(",\"icon\":").Append(Q(WindowIcon)); sb.Append(",\"width\":").Append(tabs ? ServerPackPages.Width : 460).Append(",\"height\":").Append(ServerPackPages.Height); sb.Append(",\"minWidth\":320,\"minHeight\":200,\"bar\":true,\"server\":").Append(Q(info.Id)); + // The bar icon's hover dropdown (RynthCore API 94); an older engine ignores the key. + if (barMenu != null && barMenu.Count > 0) + { + sb.Append(",\"barMenu\":["); + for (int i = 0; i < barMenu.Count; i++) + { + ServerBarMenuItem item = barMenu[i]; + sb.Append(i == 0 ? "" : ",").Append("{\"id\":").Append(Q(item.Id)); + sb.Append(",\"tooltip\":").Append(Q(item.Tooltip)); + sb.Append(",\"icon\":").Append(Q(item.Icon)); + sb.Append(",\"command\":").Append(Q(item.Command)).Append('}'); + } + sb.Append(']'); + } sb.Append('}'); // The server's own windows (ServerWindows, ServerPackWindows.cs, 2026-11-07). if (windows != null) sb.Append(ServerPackWindows.Json(windows, info.Id, frameless)); diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index 71e8046..16a00ee 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -77,6 +77,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase private readonly List _pages; // The server's own windows (ServerWindows), validated the same way. private readonly List _windows; + // The server window's bar-icon dropdown (ServerBarMenu), for the sections manifest. + private readonly List _barMenu = new(); private readonly List _pageNotes = new(); private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name)); private readonly ServerProfileValues _profileValues = new(); @@ -109,6 +111,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim()); ServerUsageLines(_usageLines.Add); _ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions); + ServerBarMenu(_barMenu); } internal ServerPackInfo Info => _model.Info; @@ -158,6 +161,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current). partial void ServerRender(); /// + /// Items for a hover dropdown on the server window's bar icon (RynthCore API 94; an older engine + /// ignores it). Called once, from the constructor (no Host yet). + /// + partial void ServerBarMenu(List items); + /// /// Drawn at the top of the server card, under RynthCore's verdict; render thread; queue work with RunOnTick. /// partial void ServerCardActions(); @@ -301,7 +309,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// internal string? BuildSectionsJson() => _sectionsJson ??= ServerPackModel.BuildSectionsJson(Info, RynthPluginInfo.Name, _pages, _windows, - frameless: _windows.Count > 0 && Host.HasFramelessWindows); + frameless: _windows.Count > 0 && Host.HasFramelessWindows, barMenu: _barMenu); /// /// RynthPluginRenderEmbed "window:<id>": one of the server's own windows (ServerWindows), into the diff --git a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs index ccea702..ef241ca 100644 --- a/Tools/RynthServerPack.Tests/ServerPackModelTests.cs +++ b/Tools/RynthServerPack.Tests/ServerPackModelTests.cs @@ -1,6 +1,8 @@ using System; using System.Linq; +using System.Collections.Generic; using System.Text.Json; +using RynthCore.Engine.UI.Sections; using RynthCore.Plugin.ServerPack; using RynthCore.RynthAiTests.Harness; @@ -18,6 +20,9 @@ internal static class ServerPackModelTests r.Add("server pack: before any push the world name decides", WorldFallback); r.Add("server pack: override commands are checked before sending", ForceCommands); r.Add("server pack: the sections manifest declares the server and a server-only card", SectionsJson); + r.Add("server pack: no bar menu writes no barMenu key", NoBarMenuKey); + r.Add("server pack: the bar menu items reach the engine parser as given", BarMenuRoundTrip); + r.Add("server pack: a bar menu tooltip with quotes and backslashes round-trips", BarMenuEscapes); r.Add("server pack: logout clears the verdict", ClearOnLogout); r.Add("server pack: the card's botting line and address", InfoText); r.Add("server pack: the RynthServer.Profile JSON carries the server's settings", ProfileJson); @@ -217,6 +222,57 @@ internal static class ServerPackModelTests Check.Eq(odd.RootElement.GetProperty("servers")[0].GetProperty("hosts")[0].GetString(), "a\\b", "escaped"); } + private static ServerBarMenuItem[] MenuItems() => new[] + { + new ServerBarMenuItem("market", "Market", ((char)0xE470).ToString(), "/rserver market"), + new ServerBarMenuItem("suit", "Suit Builder", ((char)0xE40A).ToString(), "/rserver suit"), + new ServerBarMenuItem("abilities", "Ability Planner", ((char)0xE6A2).ToString(), "/rserver abilities"), + }; + + private static void NoBarMenuKey() + { + string plain = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve"); + Check.Eq(ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve", null, barMenu: null), plain, "null pages and null menu are the default"); + Check.Eq(ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve", null, barMenu: new List()), plain, "an empty menu is the default"); + Check.False(plain.Contains("barMenu"), "no barMenu key"); + } + + private static void BarMenuRoundTrip() + { + ServerBarMenuItem[] items = MenuItems(); + string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve", null, barMenu: items); + SectionManifest m = SectionManifestParser.Parse("RynthColdeve", json, out string error); + Check.Eq(error, string.Empty, "parses clean: " + error); + SectionBarMenuItem[] menu = m.Windows.Single().Menu; + Check.Eq(menu.Length, 3, "three items"); + for (int i = 0; i < items.Length; i++) + { + Check.Eq(menu[i].Id, items[i].Id, "id " + i); + Check.Eq(menu[i].Tooltip, items[i].Tooltip, "tooltip " + i); + Check.Eq(menu[i].Icon, items[i].Icon, "icon " + i); + Check.Eq(menu[i].Command, items[i].Command, "command " + i); + } + + // With windows of the server's own (ServerWindows), the menu stays on the server's window only. + var own = new[] { new ServerWindow("skills", "Skills", "x", 300, 400, 200, 200, false, _ => default) }; + SectionManifest both = SectionManifestParser.Parse("RynthColdeve", + ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve", null, own, barMenu: items), out error); + Check.Eq(error, string.Empty, "with a window of its own: parses clean: " + error); + Check.Eq(both.Windows.Length, 2, "with a window of its own: two windows"); + Check.Eq(both.Windows[0].Menu.Length, 3, "with a window of its own: the server window has the menu"); + Check.Eq(both.Windows[1].Menu.Length, 0, "with a window of its own: that window has none"); + } + + private static void BarMenuEscapes() + { + const string tip = "Say \"hi\" \\ there"; + var items = new[] { new ServerBarMenuItem("odd", tip, ((char)0xE470).ToString(), "/rserver market") }; + string json = ServerPackModel.BuildSectionsJson(Coldeve(), "RynthColdeve", null, barMenu: items); + SectionManifest m = SectionManifestParser.Parse("RynthColdeve", json, out string error); + Check.Eq(error, string.Empty, "parses clean: " + error); + Check.Eq(m.Windows.Single().Menu.Single().Tooltip, tip, "tooltip survives escaping"); + } + private static void ClearOnLogout() { var model = new ServerPackModel(Coldeve()); -- 2.43.0 From 1d7605db23bb7213aeaf09c8fcaa89b0e53ef567 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 20:12:39 -0800 Subject: [PATCH 24/29] RynthDreamWeave: web links in the bar icon's dropdown; card buttons only on older engines Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 26 +++++++++ .../DreamWeaveWebTools.cs | 15 +++++ .../DreamWeaveWebTests.cs | 56 +++++++++++++++++++ 3 files changed, 97 insertions(+) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index 199bb1f..b7b746a 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -2,6 +2,8 @@ // (the site's registry: dreamweave-market Source/ACE.Market/Site/SiteTools.cs and HostRouting.cs); // nothing here is ever read from chat. Pure, so RynthServerPack.Tests compiles it directly. using System; +using System.Collections.Generic; +using RynthCore.Plugin.ServerPack; namespace RynthCore.Plugin.RynthDreamWeave; @@ -24,6 +26,30 @@ internal static class DreamWeaveWeb new("abilities", "Ability Planner", "/tools/abilities", "Plan a class ability build."), }; + /// The first engine API that draws a plugin window's bar-icon dropdown from the manifest's barMenu. + internal const uint BarMenuEngineApi = 94; + + /// Whether an engine of this API version draws the bar menu (so the card's buttons are redundant). + internal static bool EngineDrawsBarMenu(uint engineVersion) => engineVersion >= BarMenuEngineApi; + + /// The Phosphor glyph (private-use character) for a destination's menu item; "" when it has none. + internal static string Icon(string id) => id switch + { + "market" => ((char)0xE470).ToString(), // Storefront + "suit" => ((char)0xE40A).ToString(), // Shield + "abilities" => ((char)0xE6A2).ToString(), // Sparkle + _ => string.Empty, + }; + + /// One bar-menu item per destination: id, label as tooltip, glyph, and the /rserver verb. + internal static List BarMenu() + { + var items = new List(Destinations.Length); + foreach (WebDestination d in Destinations) + items.Add(new ServerBarMenuItem(d.Id, d.Label, Icon(d.Id), "/rserver " + d.Id)); + return items; + } + public static WebDestination? ById(string? id) { if (string.IsNullOrEmpty(id)) return null; diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index 71aec1f..e27ec05 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -59,10 +59,25 @@ public sealed partial class ServerPackPlugin } } + partial void ServerBarMenu(List items) + { + try + { + items.AddRange(DreamWeaveWeb.BarMenu()); + } + catch (Exception) + { + // The constructor has no Host to log to yet; the destinations are constants. + } + } + partial void ServerCardActions() { try { + // An engine that draws the bar icon's dropdown carries the links; the card keeps its buttons + // (and the status line) only for older engines, so no one loses them. + if (DreamWeaveWeb.EngineDrawsBarMenu(Host.Version)) return; WebButtons.Draw(_web, Active, _webClick ??= d => RunOnTick(() => StartLaunch(d))); } catch (Exception ex) diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index 05d8914..794d7f7 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; +using RynthCore.Engine.UI.Sections; using RynthCore.Plugin.RynthDreamWeave; using RynthCore.Plugin.ServerPack; using RynthCore.RynthAiTests.Harness; @@ -33,6 +34,61 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: a malformed launch-code line never reaches chat", MalformedSuccess); r.Add("dreamweave web: the source scan's helpers read code, not comments or strings", ScanHelpers); r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); + r.Add("dreamweave web: the bar icon's menu lists the destinations, in the engine's own terms", BarMenuItems); + r.Add("dreamweave web: the engine draws the bar menu from API 94", EngineDrawsMenu); + r.Add("dreamweave web: the card hides its buttons only when the engine's version says it draws the menu", CardHidesButtonsOnNewEngines); + } + + private static void BarMenuItems() + { + List items = DreamWeaveWeb.BarMenu(); + string[][] want = + { + new[] { "market", "Market", ((char)0xE470).ToString(), "/rserver market" }, + new[] { "suit", "Suit Builder", ((char)0xE40A).ToString(), "/rserver suit" }, + new[] { "abilities", "Ability Planner", ((char)0xE6A2).ToString(), "/rserver abilities" }, + }; + Check.Eq(items.Count, want.Length, "one item per destination"); + for (int i = 0; i < want.Length && i < items.Count; i++) + { + Check.Eq(items[i].Id, want[i][0], "id " + i); + Check.Eq(items[i].Tooltip, want[i][1], "tooltip " + i); + Check.Eq(items[i].Icon, want[i][2], "icon " + i); + Check.Eq(items[i].Command, want[i][3], "command " + i); + Check.Eq(SectionManifestParser.Command(items[i].Command), items[i].Command, "the engine keeps the command " + i); + Check.Eq(SectionManifestParser.Icon(items[i].Icon), items[i].Icon, "the engine keeps the icon " + i); + Check.True(DreamWeaveWeb.ById(items[i].Id) != null, "the command's verb is a destination: " + items[i].Id); + } + Check.True(items.Count <= SectionManifestParser.MaxBarMenuItems, "within the engine's cap"); + + // And through the manifest, as the engine reads it. + var info = new ServerPackInfo("dreamweave", "DreamWeave", new[] { "play.acdreamweave.com" }, Array.Empty()); + SectionManifest m = SectionManifestParser.Parse("RynthDreamWeave", ServerPackModel.BuildSectionsJson(info, "RynthDreamWeave", null, barMenu: items), out string error); + Check.Eq(error, string.Empty, "parses clean: " + error); + Check.Eq(m.Windows.Single().Menu.Length, 3, "the engine reads three items"); + } + + private static void EngineDrawsMenu() + { + Check.Eq(DreamWeaveWeb.BarMenuEngineApi, 94u, "the engine API that draws the bar menu"); + Check.False(DreamWeaveWeb.EngineDrawsBarMenu(93), "93: the card keeps its buttons"); + Check.True(DreamWeaveWeb.EngineDrawsBarMenu(94), "94: the engine draws the menu"); + Check.True(DreamWeaveWeb.EngineDrawsBarMenu(95), "95: the engine draws the menu"); + Check.False(DreamWeaveWeb.EngineDrawsBarMenu(0), "0: unknown version keeps the buttons"); + } + + private static void CardHidesButtonsOnNewEngines() + { + string hostPath = Path.Combine(ServerProjectsTests.PluginsDir(), "RynthCore.Plugin.RynthDreamWeave", "DreamWeaveWebTools.cs"); + Check.True(File.Exists(hostPath), "DreamWeaveWebTools.cs exists"); + if (!File.Exists(hostPath)) return; + string host = StripComments(File.ReadAllText(hostPath)); + List card = StatementsAfter(host, "partial void ServerCardActions()"); + Check.Eq(card.Count, 1, "ServerCardActions implemented once"); + Check.True(card.Count == 1 && card[0].Contains("EngineDrawsBarMenu(Host.Version)", StringComparison.Ordinal), + "ServerCardActions asks the running engine's version (Host.Version)"); + Check.False(host.Contains("CurrentApiVersion", StringComparison.Ordinal), "the plugin never reads the compile-time CurrentApiVersion"); + Check.True(host.Contains("DreamWeaveWeb.BarMenu()", StringComparison.Ordinal), "ServerBarMenu supplies DreamWeaveWeb.BarMenu()"); } // -- Host wiring (source scan: the plugin is NativeAOT, so its host code can't run here) -- -- 2.43.0 From 17601b9768270648c048b404a6d019182ebdaaab Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sat, 7 Nov 2026 20:29:43 -0800 Subject: [PATCH 25/29] DreamWeave: pin bar menu API to the engine's constant Link the engine's PluginContractVersion into the tests and compare the plugin's BarMenuEngineApi to PluginContractVersion.BarMenu instead of a literal 94. Reword the plugin description: links in the bar icon dropdown, card buttons on older RynthCore. Co-Authored-By: Claude Opus 5.5 --- .../RynthCore.Plugin.RynthDreamWeave.csproj | 2 +- Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs | 10 ++++++---- .../RynthServerPack.Tests/RynthServerPack.Tests.csproj | 2 ++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index e719ce5..43fb7b9 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -10,7 +10,7 @@ DreamWeave play.acdreamweave.com DreamWeave|Dream Weave - DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, with Market, Suit Builder and Ability Planner buttons that open the website logged in as this account, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. + DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. Market, Suit Builder and Ability Planner open the website logged in as this account: as links in the bar icon's dropdown, or as buttons on the card on older RynthCore. + + -- 2.43.0 From aa4551e8b12117ce7a2dff56e48cd166067c6c09 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 13:31:47 -0800 Subject: [PATCH 26/29] DreamWeave: the bar menu is plugin API v95 The engine's barMenu manifest key landed as plugin API v95 (was v94 on up/bar-menu; renumbered after the web panel's v94). BarMenuEngineApi and the comments follow; the test still pins the const to the engine's own PluginContractVersion.BarMenu. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 2 +- Plugins/Shared/ServerPack/ServerPackModel.cs | 2 +- Plugins/Shared/ServerPack/ServerPackPlugin.cs | 2 +- Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index b7b746a..aa5c566 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -27,7 +27,7 @@ internal static class DreamWeaveWeb }; /// The first engine API that draws a plugin window's bar-icon dropdown from the manifest's barMenu. - internal const uint BarMenuEngineApi = 94; + internal const uint BarMenuEngineApi = 95; /// Whether an engine of this API version draws the bar menu (so the card's buttons are redundant). internal static bool EngineDrawsBarMenu(uint engineVersion) => engineVersion >= BarMenuEngineApi; diff --git a/Plugins/Shared/ServerPack/ServerPackModel.cs b/Plugins/Shared/ServerPack/ServerPackModel.cs index 016e24e..a863365 100644 --- a/Plugins/Shared/ServerPack/ServerPackModel.cs +++ b/Plugins/Shared/ServerPack/ServerPackModel.cs @@ -188,7 +188,7 @@ internal sealed class ServerPackModel sb.Append(",\"icon\":").Append(Q(WindowIcon)); sb.Append(",\"width\":").Append(tabs ? ServerPackPages.Width : 460).Append(",\"height\":").Append(ServerPackPages.Height); sb.Append(",\"minWidth\":320,\"minHeight\":200,\"bar\":true,\"server\":").Append(Q(info.Id)); - // The bar icon's hover dropdown (RynthCore API 94); an older engine ignores the key. + // The bar icon's hover dropdown (RynthCore API 95); an older engine ignores the key. if (barMenu != null && barMenu.Count > 0) { sb.Append(",\"barMenu\":["); diff --git a/Plugins/Shared/ServerPack/ServerPackPlugin.cs b/Plugins/Shared/ServerPack/ServerPackPlugin.cs index 16a00ee..61bcfe1 100644 --- a/Plugins/Shared/ServerPack/ServerPackPlugin.cs +++ b/Plugins/Shared/ServerPack/ServerPackPlugin.cs @@ -161,7 +161,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase /// Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current). partial void ServerRender(); /// - /// Items for a hover dropdown on the server window's bar icon (RynthCore API 94; an older engine + /// Items for a hover dropdown on the server window's bar icon (RynthCore API 95; an older engine /// ignores it). Called once, from the constructor (no Host yet). /// partial void ServerBarMenu(List items); diff --git a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs index f79e7af..66203c0 100644 --- a/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs +++ b/Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs @@ -35,7 +35,7 @@ internal static class DreamWeaveWebTests r.Add("dreamweave web: the source scan's helpers read code, not comments or strings", ScanHelpers); r.Add("dreamweave web: the plugin's shared hooks hand off to the web tools first", HooksHandOff); r.Add("dreamweave web: the bar icon's menu lists the destinations, in the engine's own terms", BarMenuItems); - r.Add("dreamweave web: the engine draws the bar menu from API 94", EngineDrawsMenu); + r.Add("dreamweave web: the engine draws the bar menu from API 95", EngineDrawsMenu); r.Add("dreamweave web: the card hides its buttons only when the engine's version says it draws the menu", CardHidesButtonsOnNewEngines); } -- 2.43.0 From 806f5268fd4fda1918fda39a70dd793cf4473a82 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 13:45:49 -0800 Subject: [PATCH 27/29] DreamWeave: card text names the bar icon's menu On engines that draw the bar menu the card has no link buttons, so the card's info line now says the links open from the bar icon's menu, or this card on older RynthCore. Co-Authored-By: Claude Opus 5.5 --- Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs index bd67bc2..9177f5d 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs @@ -35,7 +35,7 @@ internal static class ServerData "Experience bonuses: gear, augmentations, alt-character catch-up and offline (/bonus).", "Fast tick opt-in: faster spell release, fast-chug and melee stick-to-target (/fasttick).", "Web character sheet you can publish (/charsheet).", - "Market, Suit Builder and Ability Planner open logged in from this card (/rserver market | suit | abilities).", + "Market, Suit Builder and Ability Planner open logged in from the bar icon's menu, or this card on older RynthCore (/rserver market | suit | abilities).", }, Commands = new[] { -- 2.43.0 From 6570ff1bc1c58b7fa2e72645fc9abb9217aff81d Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 8 Nov 2026 10:55:36 -0800 Subject: [PATCH 28/29] DreamWeave: abilities link opens the live class ability page The third bar-menu item (and card button on older engines) now opens /play/abilities, the live class ability panel, labelled Class Abilities. /rserver abilities keeps its verb. Co-Authored-By: Claude Opus 5.5 --- .../DreamWeave/DreamWeaveWeb.cs | 2 +- .../RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs | 2 +- .../RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs | 2 +- .../RynthCore.Plugin.RynthDreamWeave.csproj | 2 +- Plugins/RynthCore.Plugin.RynthDreamWeave/ServerData.cs | 2 +- Tools/RynthServerPack.Tests/DreamWeaveWebTests.cs | 4 +++- Tools/RynthServerPack.Tests/ServerPackCommandsTests.cs | 2 +- Tools/RynthServerPack.Tests/ServerPackModelTests.cs | 2 +- 8 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs index aa5c566..f119368 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/DreamWeaveWeb.cs @@ -23,7 +23,7 @@ internal static class DreamWeaveWeb { new("market", "Market", "/market", "The player market, logged in as this account."), new("suit", "Suit Builder", "/tools/suit", "Plan a suit from this account's characters."), - new("abilities", "Ability Planner", "/tools/abilities", "Plan a class ability build."), + new("abilities", "Class Abilities", "/play/abilities", "Raise and lower this character's class abilities live."), }; /// The first engine API that draws a plugin window's bar-icon dropdown from the manifest's barMenu. diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs index e51b456..19b6aaf 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeave/WebButtons.cs @@ -1,4 +1,4 @@ -// The DreamWeave card's website buttons (Market, Suit Builder, Ability Planner). Render thread, inside +// The DreamWeave card's website buttons (Market, Suit Builder, Class Abilities). Render thread, inside // the card hook only: this file draws and nothing else. It calls no host function, sends nothing and // opens nothing; a click is handed to the caller, which queues the work for the tick (RunOnTick). // It never switches the ImGui context (RenderEmbedded and OnRender own it), and it draws no diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs index e27ec05..a720b58 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/DreamWeaveWebTools.cs @@ -1,5 +1,5 @@ // DreamWeaveWebTools.cs - RynthDreamWeave's website tools, through the shared server plugin's hooks -// (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the card's Market, Suit Builder and Ability Planner +// (Plugins/Shared/ServerPack/ServerPackPlugin.cs): the card's Market, Suit Builder and Class Abilities // buttons and "/rserver market | suit | abilities", which open the website logged in as this account. // The hooks it shares with the bank and the Skills panel are implemented once, in DreamWeavePlugin.cs and // DreamWeaveSkills.cs, and call the Web* methods here first. diff --git a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj index 43fb7b9..92485d3 100644 --- a/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj +++ b/Plugins/RynthCore.Plugin.RynthDreamWeave/RynthCore.Plugin.RynthDreamWeave.csproj @@ -10,7 +10,7 @@ DreamWeave play.acdreamweave.com DreamWeave|Dream Weave - DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. Market, Suit Builder and Ability Planner open the website logged in as this account: as links in the bar icon's dropdown, or as buttons on the card on older RynthCore. + DreamWeave only: the server card (rules, server features, player commands, links, account setup) in its own window on the RynthCore bar, the retail Character panel whose XP for next level keeps reading past level 275, and the bank check every minute that gives Lum/hr its luminance. Market, Suit Builder and Class Abilities open the website logged in as this account: as links in the bar icon's dropdown, or as buttons on the card on older RynthCore.