From cb06e5f0656c32d3d9991e7f75e80057037c6371 Mon Sep 17 00:00:00 2001 From: Daniel Wallace Date: Sun, 15 Nov 2026 10:48:41 -0800 Subject: [PATCH] Network tab: Join/Leave bar and the join status ChatNetwork.Classify reads the Dereth.Network mod's own status lines (on as Name@world, already on, not on, off), only on system-type lines (Broadcast 0, System 5), so a player saying them is never a status. The first view of a network tab per character session sends / and keeps that one answer out of the scrollback (the status line within 10 s, and a "Your directory page:" line within 2 s after it); every later status line is shown and moves On. Login and logout reset the session (unknown is still sent as on; off blocks Global). The main window shows a bar under the header on that tab: "Join the Dereth Network", or "On the network as
" and Leave. Join sends / on and turns on Hear Chat (AcCharacterOptions) for the discovered Global room, else the entry's fallback, remembering per server/character (networkJoinRooms, absent while empty) only when it was off before; Leave sends / off and turns that room off only if Join turned it on. A refusal is shown in the bar. The work runs on AC's main thread on a fresh posted message (WM_RYNTHCORE_NETWORK), as a typed line's send does. Co-Authored-By: Claude Opus 5.5 --- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 43 +++++ src/RynthCore.Engine/ImGui/Win32Backend.cs | 19 ++ src/RynthCore.Engine/UI/Data/ChatData.cs | 169 +++++++++++++++++- src/RynthCore.Engine/UI/Data/ChatNetwork.cs | 153 +++++++++++++++- .../UI/Data/ChatSettingsDto.cs | 2 + tools/ChatFilterTests/Program.cs | 100 +++++++++++ 6 files changed, 482 insertions(+), 4 deletions(-) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index f304320..a454307 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -129,6 +129,7 @@ internal sealed class ChatFace : IImGuiPanel y += 26; } else y = DrawHeader(new Vector2(x0, origin.Y + 4), w); + y = DrawNetworkBar(x0, y, w); _view.SyncLines(snap, lines, tab); @@ -257,6 +258,48 @@ internal sealed class ChatFace : IImGuiPanel return x > start ? x + 2 : x; // the 4 px after the channel button, 2 here and 2 left from the last gap } + /// + /// The network bar (2026-11-15, Task 11) under the header while the current tab is a network + /// tab of an active server (ChatModel.CurrentNetworkEntry): "Join the Dereth Network" until the + /// mod says this character is on it, then "On the network as Name@world" and Leave. Its first + /// view per character session asks the server (ChatModel.NoteNetworkTabViewed). A Join that + /// could not set the room option says why here, once per click. Returns the y below it. + /// + private float DrawNetworkBar(float x, float y, float w) + { + if (ChatModel.CurrentNetworkEntry() == null) return y; + ChatModel.NoteNetworkTabViewed(); + const float h = 22; + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float ty = y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + string? problem = ChatNetwork.JoinProblem; + if (ChatNetwork.On == true) + { + const float leaveW = 60; + string label = ChatNetwork.Address is { Length: > 0 } a ? "On the network as " + a : "On the network"; + dl.AddText(new Vector2(x + 4, ty), Text, label); + if (Button("##chat_net_leave", "Leave", new Vector2(x + w - leaveW, y), new Vector2(leaveW, h), Text, BtnFill)) + ChatModel.RequestNetworkLeave(); + ImGuiNET.ImGui.SetItemTooltip("Take this character off the Dereth Network"); + } + else + { + const string join = "Join the Dereth Network"; + float joinW = ImGuiNET.ImGui.CalcTextSize(join).X + 16; + if (Button("##chat_net_join", join, new Vector2(x, y), new Vector2(joinW, h), Text, TabActive)) + ChatModel.RequestNetworkJoin(); + ImGuiNET.ImGui.SetItemTooltip("Put this character on the Dereth Network and listen to its Global room"); + } + if (problem != null) + { + y += h + 2; + dl.AddText(new Vector2(x + 4, y), Faded(Text), problem); + y += ImGuiNET.ImGui.GetFontSize(); + } + else y += h; + return y + 4; + } + /// The overflow list and the Unpin menu of the pinned buttons (drawn in DrawPopups). private void DrawPinPopups() { diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index f29c555..03d00f2 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -286,6 +286,20 @@ internal static unsafe class Win32Backend PostMessage(_gameHwnd, WM_RYNTHCORE_TELL, IntPtr.Zero, IntPtr.Zero); } + // Chat's network bar (Join / Leave, and the status question on the first view of a network + // tab): its chat lines and AC option go out on a fresh game-thread dispatch, as a typed line does. + internal const uint WM_RYNTHCORE_NETWORK = 0x0400 + 0x5245; + + /// Fired on the game thread to run the chat network bar's queued work (ChatModel). + public static Action? OnChatNetwork; + + /// Callable from any thread: runs on AC's main thread. + public static void RequestChatNetwork() + { + if (_gameHwnd != IntPtr.Zero) + PostMessage(_gameHwnd, WM_RYNTHCORE_NETWORK, IntPtr.Zero, IntPtr.Zero); + } + /// The game's main window handle. public static IntPtr GameHwnd => _gameHwnd; @@ -969,6 +983,11 @@ internal static unsafe class Win32Backend OnChatTellSelected?.Invoke(); return IntPtr.Zero; } + if (msg == WM_RYNTHCORE_NETWORK) + { + OnChatNetwork?.Invoke(); + return IntPtr.Zero; + } // ── Chat: Enter in-game activates the chat TextBox ─────────── // Numpad Enter (extended key, lParam bit 24) is reserved for AC functions — never capture it. diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index e1b4607..f8d32a6 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -180,6 +180,10 @@ internal sealed unsafe class ChatSource : UiSource if (line.Route.Mention) ChatModel.PumpMentionSound(); added.Add(line); } + // The network's status lines (ChatNetwork): On follows them, and the answer to the status + // question the first view of a network tab asked is left out of the scrollback. + try { ChatModel.PumpNetworkLines(added); } + catch (Exception ex) { RynthLog.UI($"ChatSource: network status check failed ({ex.GetType().Name}: {ex.Message})."); } // A server tab's Global room, seen in chat (ChatModel.ApplyServerTabs). A new room bumps the // filter version, so the next poll routes the kept lines, these included, with the new rule. try { ChatModel.PumpDiscoverGlobalRoom(added); } @@ -1370,6 +1374,7 @@ internal static class ChatModel SetInput("", 0, null); }; Win32Backend.OnChatSend = OnSend; + Win32Backend.OnChatNetwork = RunNetworkOps; // the network bar's Join / Leave and the status question // Escape leaves the line, as retail's chat does: the half-typed text stays in the box // (it used to be erased), and Enter or a click on the box carries on typing it. Win32Backend.OnChatCancel = () => @@ -1486,7 +1491,13 @@ internal static class ChatModel public static SectionNetworkDecl? CurrentNetwork() => NetworkOfTab(CurrentTab()); /// The network declaration of (see CurrentNetwork), or null. - public static SectionNetworkDecl? NetworkOfTab(string tab) + public static SectionNetworkDecl? NetworkOfTab(string tab) => NetworkEntryOfTab(tab)?.Network; + + /// The chatTabs entry that makes the current tab a network tab (see CurrentNetwork), or null. Any thread. + public static SectionChatTabDecl? CurrentNetworkEntry() => NetworkEntryOfTab(CurrentTab()); + + /// The chatTabs entry that makes a network tab, or null. + public static SectionChatTabDecl? NetworkEntryOfTab(string tab) { if (!Volatile.Read(ref _tabServers).TryGetValue(tab, out string? server)) return null; string[] active = _activeServers; @@ -1498,11 +1509,163 @@ internal static class ChatModel foreach (ChatFilterRule rule in Filters) if (string.Equals(rule.Owner, key, StringComparison.OrdinalIgnoreCase) && string.Equals(rule.Tab, tab, StringComparison.OrdinalIgnoreCase)) - return d.Network; + return d; } return null; } + // -- Network join status (Task 11, ChatNetwork) -- + + /// Is any active server's entry a network one? Cheap (no lock); the pump checks it per poll. + private static bool AnyNetworkActive() + { + string[] active = _activeServers; + foreach (SectionChatTabDecl d in _tabDecls) + if (d.Network != null && ChatRouter.ServerIn(active, d.Server)) return true; + return false; + } + + /// + /// Pump thread (ChatSource.PollLines): status lines move ChatNetwork.On; the status question's + /// own answer is taken out of . Free while no network is active. + /// + internal static void PumpNetworkLines(List added) + { + if (added.Count == 0 || !AnyNetworkActive()) return; + long now = Environment.TickCount64; + int eaten = added.RemoveAll(l => ChatNetwork.Observe(l.Text, l.ChatType, now)); + if (eaten > 0) RynthLog.UI($"ChatModel: the network status answer ({eaten} line{(eaten == 1 ? "" : "s")}) kept out of the scrollback."); + } + + private enum NetworkOp { Query, Join, Leave } + private static readonly System.Collections.Concurrent.ConcurrentQueue _networkOps = new(); + private static bool _networkSessionHooked; + + // Settings: JoinKey(server, character) -> the room Join turned on (absent while none). + private static Dictionary _networkJoinRooms = NewMap(); + + /// + /// The main window shows a network tab (its face, every frame): the first time per character + /// session, once in the world, ask the server whether this character is on the network. + /// + public static void NoteNetworkTabViewed() + { + HookNetworkSession(); + if (!LoginLifecycleHooks.HasObservedLoginComplete || SendLinePtr == IntPtr.Zero) return; + if (!ChatNetwork.TryBeginQuery()) return; + RequestNetwork(NetworkOp.Query); + } + + /// The Join button. Any thread: the work runs on AC's main thread. + public static void RequestNetworkJoin() => RequestNetwork(NetworkOp.Join); + + /// The Leave button. Any thread: the work runs on AC's main thread. + public static void RequestNetworkLeave() => RequestNetwork(NetworkOp.Leave); + + private static void RequestNetwork(NetworkOp op) + { + if (_networkOps.Count >= 8) return; // clicks while the game thread is busy: a few is plenty + _networkOps.Enqueue(op); + Win32Backend.RequestChatNetwork(); + } + + /// A new character session asks again and knows nothing (login and logout). Once. + private static void HookNetworkSession() + { + if (_networkSessionHooked) return; + _networkSessionHooked = true; + LoginLifecycleHooks.LoginComplete += ChatNetwork.ResetSession; + LogoutLifecycleHooks.LogoutComplete += ChatNetwork.ResetSession; + } + + /// + /// AC's main thread, on a fresh window message (Win32Backend, WM_RYNTHCORE_NETWORK), as a typed + /// line is sent: the queued status question, Join and Leave. + /// + private static void RunNetworkOps() + { + while (_networkOps.TryDequeue(out NetworkOp op)) + { + try { RunNetworkOp(op); } + catch (Exception ex) { RynthLog.UI($"ChatModel: network {op} failed ({ex.GetType().Name}: {ex.Message})."); } + } + } + + private static void RunNetworkOp(NetworkOp op) + { + SectionChatTabDecl? entry = CurrentNetworkEntry(); + if (entry?.Network is not { } network) return; // the tab or its server went away meanwhile + string command = network.Command; + string key = ChatNetwork.JoinKey(entry.Server, PumpCharacterName()); + switch (op) + { + case NetworkOp.Query: + ChatNetwork.Eater.Query(Environment.TickCount64); + SendChatLine("/" + command); + break; + + case NetworkOp.Join: + { + ChatNetwork.JoinProblem = null; + SendChatLine("/" + command + " on"); + string roomName = Volatile.Read(ref _globalRooms).TryGetValue(entry.Server, out string? found) ? found : entry.GlobalRoomFallback; + if (!AcCharacterOptions.TryParseRoom(roomName, out AcCharacterOptions.Room room)) + { + ChatNetwork.JoinProblem = $"no room \"{roomName}\" to listen to"; + break; + } + // Already on: Join did not turn it on, so Leave leaves it alone. + if (!AcCharacterOptions.TryGet(room, out bool wasOn, out string why) + || (!wasOn && !AcCharacterOptions.TrySet(room, true, out why))) + { + ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(room)} Chat not set: {why}"; + RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem); + break; + } + if (!wasOn) SetJoinRoom(key, AcCharacterOptions.Name(room)); + break; + } + + case NetworkOp.Leave: + { + ChatNetwork.JoinProblem = null; + SendChatLine("/" + command + " off"); + if (!Volatile.Read(ref _networkJoinRooms).TryGetValue(key, out string? joined)) break; + if (AcCharacterOptions.TryParseRoom(joined, out AcCharacterOptions.Room room) + && !AcCharacterOptions.TrySet(room, false, out string why)) + { + ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(room)} Chat not turned off: {why}"; + RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem); + break; // kept: a later Leave tries again + } + SetJoinRoom(key, null); + break; + } + } + } + + /// Records (or with null forgets) the room Join turned on for . Saved. + private static void SetJoinRoom(string key, string? room) + { + lock (EditLock) + { + Dictionary map = NewMap(_networkJoinRooms); + if (room == null) map.Remove(key); else map[key] = room; + Volatile.Write(ref _networkJoinRooms, map); + } + SaveSettings(); + } + + /// A line through the chat parser, as a typed one goes. AC's main thread, on a fresh message. + private static unsafe void SendChatLine(string text) + { + IntPtr send = SendLinePtr; + if (send == IntPtr.Zero) return; + IntPtr ptr = Marshal.StringToHGlobalAnsi(text); + try { ((delegate* unmanaged[Cdecl])send)(ptr); } + finally { Marshal.FreeHGlobal(ptr); } + } + /// The creature selected in the game (an NPC or another player), for /tell. /// AC's main thread only. Never yourself, never an item. private static bool TryGetSelectedTellName(out string name) @@ -1862,6 +2025,7 @@ internal static class ChatModel _seededTabs = seeded; _tabServers = NewMap(dto.TabServers); _globalRooms = NewMap(dto.GlobalRooms); + _networkJoinRooms = NewMap(dto.NetworkJoinRooms); _pinnedTabs = pinned; } Interlocked.Increment(ref _filtersVersion); @@ -1928,6 +2092,7 @@ internal static class ChatModel SeededTabs = NullIfEmpty(Volatile.Read(ref _seededTabs)), TabServers = NullIfEmpty(Volatile.Read(ref _tabServers)), GlobalRooms = NullIfEmpty(Volatile.Read(ref _globalRooms)), + NetworkJoinRooms = NullIfEmpty(Volatile.Read(ref _networkJoinRooms)), PinnedTabs = Volatile.Read(ref _pinnedTabs), // always written, empty included: [] = nothing pinned, absent = All Filters = Filters.Select(ToDto).ToArray(), // Only presets the user touched: new presets in later builds start off. diff --git a/src/RynthCore.Engine/UI/Data/ChatNetwork.cs b/src/RynthCore.Engine/UI/Data/ChatNetwork.cs index bbed857..ac241e7 100644 --- a/src/RynthCore.Engine/UI/Data/ChatNetwork.cs +++ b/src/RynthCore.Engine/UI/Data/ChatNetwork.cs @@ -5,20 +5,35 @@ // command is sent through the network's own command ("/ global "), and // only while the player is on the network. Pure and engine-free: ChatModel.OnSend // calls Rewrite; tools/ChatFilterTests compiles this file as is. +// +// Join status (Task 11): whether this character is on the network is read from the +// mod's own system lines (Classify, the texts of the Dereth.Network ACE mod, +// third_party/dereth/network/ace-mod/Dereth.Network/Core/NetworkWorld.Commands.cs, which +// sends them as ChatMessageType.Broadcast). The first view of a network tab per +// character session asks ("/"), and the answer to that one question is kept +// out of the scrollback (ReplyEater): the status line, and the "Your directory page:" +// line that may follow it. Every later status line is shown and moves On. // ============================================================================ +using System; using System.Threading; namespace RynthCore.Engine.UI.Data; +/// What a status line says: on the network (as ) or off it. +internal readonly record struct NetworkStatus(bool On, string? Address); + internal static class ChatNetwork { // -1 unknown, 0 off the network, 1 on it. An int so any thread can read and write it whole. private static int _on = -1; + private static int _queried; + private static volatile string? _address; + private static volatile string? _joinProblem; /// - /// Is the player on the network this session? null = not known yet (Task 11 fills it; until then - /// a line is sent as if on). Any thread. + /// Is the player on the network this session? null = not known yet (the first view of the + /// tab asks); a line is then sent as if on. Any thread. /// public static bool? On { @@ -29,6 +44,92 @@ internal static class ChatNetwork /// Is a line to be sent as if on the network? Unknown counts as on. public static bool OnOrUnknown => On != false; + /// The network address the last "on" line named (Name@world), or null. Any thread. + public static string? Address => _address; + + /// Why the last Join could not set the room option (shown in the bar), or null. Any thread. + public static string? JoinProblem + { + get => _joinProblem; + set => _joinProblem = value; + } + + /// The status question's reply lines to keep out of the scrollback. + public static readonly NetworkReplyEater Eater = new(); + + /// True once per character session: the caller asks the server now. Any thread. + public static bool TryBeginQuery() => Interlocked.Exchange(ref _queried, 1) == 0; + + /// A new character session (login, logout): nothing known, ask again. Any thread. + public static void ResetSession() + { + On = null; + _address = null; + _joinProblem = null; + Volatile.Write(ref _queried, 0); + Eater.Clear(); + } + + /// + /// One incoming line (the pump): a status line moves On and the address; true when the line is + /// part of the status question's answer and is to be left out of the scrollback. + /// + internal static bool Observe(string text, int chatType, long nowMs) + { + NetworkStatus? status = Classify(text, chatType); + if (status is { } s) + { + On = s.On; + _address = s.On ? s.Address : null; + } + return Eater.Take(status, text, chatType, nowMs); + } + + // -- The mod's lines -- + + // ACE ChatMessageType: Broadcast 0x00 (the mod's ShowSystem), System 0x05. A player's speech, + // tells and channel lines are other types, so a player saying these words is never a status. + internal static bool IsSystemType(int chatType) => chatType is 0x00 or 0x05; + + internal const string OnPrefix = "You are on the Dereth Network as "; + internal const string OnAlreadyPrefix = "You are on the Dereth Network already, as "; + internal const string NotOnPrefix = "You are not on the Dereth Network"; + internal const string OffPrefix = "You are off the Dereth Network"; + internal const string DirectoryPrefix = "Your directory page:"; + + /// + /// What a line says about this character and the network, or null when it says nothing (or is not + /// a system line). On lines carry the address: "...as Ann@alpha." up to the first ". " or the end. + /// + internal static NetworkStatus? Classify(string text, int chatType) + { + if (string.IsNullOrEmpty(text) || !IsSystemType(chatType)) return null; + string t = text.Trim(); + if (t.StartsWith(OnAlreadyPrefix, StringComparison.Ordinal)) + return AddressAfter(t, OnAlreadyPrefix.Length) is { } a ? new NetworkStatus(true, a) : null; + if (t.StartsWith(OnPrefix, StringComparison.Ordinal)) + return AddressAfter(t, OnPrefix.Length) is { } a ? new NetworkStatus(true, a) : null; + if (t.StartsWith(NotOnPrefix, StringComparison.Ordinal) || t.StartsWith(OffPrefix, StringComparison.Ordinal)) + return new NetworkStatus(false, null); + return null; + } + + /// The status answer's second line ("Your directory page: https://..."). + internal static bool IsDirectoryLine(string text, int chatType) => + !string.IsNullOrEmpty(text) && IsSystemType(chatType) + && text.TrimStart().StartsWith(DirectoryPrefix, StringComparison.Ordinal); + + private static string? AddressAfter(string t, int start) + { + int end = t.IndexOf(". ", start, StringComparison.Ordinal); + string a = (end >= 0 ? t[start..end] : t[start..].TrimEnd('.')).Trim(); + return a.Length > 0 && a.IndexOf('@') > 0 ? a : null; + } + + /// The settings key of "Join turned the room option on" for one character on one server. + internal static string JoinKey(string server, string character) => + (server ?? "").Trim().ToLowerInvariant() + "/" + (character ?? "").Trim(); + /// /// What to send for a line typed on a network tab, or null when it must not be sent. The line is /// trimmed; empty is null; a line starting with / or @ is a command and goes unchanged; any other @@ -42,3 +143,51 @@ internal static class ChatNetwork return onNetwork ? "/" + command + " global " + text : null; } } + +/// +/// The answer to the one status question a session asks: the first status line within +/// of the question, and a "Your directory page:" line within +/// after that status line (only an "on" answer has one). Nothing +/// else is ever eaten: a status line nobody asked for, or one too late, is shown. Any thread. +/// +internal sealed class NetworkReplyEater +{ + public const long StatusWindowMs = 10_000; + public const long DirectoryWindowMs = 2_000; + + private readonly object _lock = new(); + private long _queryAt = -1, _statusAt = -1; + + /// The question was just sent. + public void Query(long nowMs) + { + lock (_lock) { _queryAt = nowMs; _statusAt = -1; } + } + + public void Clear() + { + lock (_lock) { _queryAt = -1; _statusAt = -1; } + } + + /// Is this line (already classified as ) part of the answer? + public bool Take(NetworkStatus? status, string text, int chatType, long nowMs) + { + lock (_lock) + { + if (status is { } s) + { + bool asked = _queryAt >= 0 && nowMs - _queryAt >= 0 && nowMs - _queryAt <= StatusWindowMs; + _queryAt = -1; + _statusAt = asked && s.On ? nowMs : -1; + return asked; + } + if (_statusAt >= 0 && ChatNetwork.IsDirectoryLine(text, chatType)) + { + bool soon = nowMs - _statusAt <= DirectoryWindowMs; + _statusAt = -1; + return soon; + } + return false; + } + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs index 49d42d8..613907c 100644 --- a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -85,6 +85,8 @@ internal sealed class RynthChatSettingsDto [JsonPropertyName("tabServers")] public Dictionary? TabServers { get; set; } /// Server id -> the Global room (General, Trade, LFG, Roleplay) last discovered from chat. [JsonPropertyName("globalRooms")] public Dictionary? GlobalRooms { get; set; } + /// "server/Character" -> the room whose Hear option the network bar's Join turned on (Leave turns it off again); absent while none. + [JsonPropertyName("networkJoinRooms")] public Dictionary? NetworkJoinRooms { get; set; } /// Tabs pinned to the main chat window's top bar, in pin order. [JsonPropertyName("pinnedTabs")] public string[]? PinnedTabs { get; set; } [JsonPropertyName("filters")] public RynthChatFilterDto[]? Filters { get; set; } diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 4f9e23f..12779d6 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -59,6 +59,7 @@ internal static class Program ServerTabPlans(); PinBookkeeping(); NetworkRewrite(); + NetworkStatusLines(); SharedFileReload(); LineColorTags(); LineColorKinds(); @@ -1638,6 +1639,105 @@ internal static class Program Check(ChatNetwork.On == null, "reset to unknown"); } + // 2026-11-15 (Task 11): the Dereth.Network mod's status lines (texts verbatim from + // third_party/dereth/network/ace-mod/Dereth.Network/Core/NetworkWorld.Commands.cs, sent as + // ChatMessageType.Broadcast = 0), the answer eater, and the session state. + private static void NetworkStatusLines() + { + const int Broadcast = 0, System = 5, Speech = 2, Tell = 3, Channel = 8; + + Case("Classify_OnTexts"); + var on1 = ChatNetwork.Classify("You are on the Dereth Network as Ann@alpha. Anyone on the network can see when you are online, send you tells and find your profile in its directory. Type @derethnetwork help for the commands.", Broadcast); + Check(on1 is { On: true, Address: "Ann@alpha" }, "the join line: on, as Ann@alpha"); + var on2 = ChatNetwork.Classify("You are on the Dereth Network already, as Ann@alpha.", Broadcast); + Check(on2 is { On: true, Address: "Ann@alpha" }, "already on: on, as Ann@alpha"); + var on3 = ChatNetwork.Classify("You are on the Dereth Network as Ann@alpha. The hub is connected. You have no friends on other worlds.", Broadcast); + Check(on3 is { On: true, Address: "Ann@alpha" }, "the status line: on, as Ann@alpha"); + var on4 = ChatNetwork.Classify("You are on the Dereth Network as Mary Ann@dreamweave-stage. The hub is not connected. You have 2 friends on other worlds.", System); + Check(on4 is { On: true, Address: "Mary Ann@dreamweave-stage" }, "a spaced name and a hyphenated world, System type too"); + + Case("Classify_OffTexts"); + Check(ChatNetwork.Classify("You are not on the Dereth Network.", Broadcast) is { On: false, Address: null }, "off already"); + Check(ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it.", Broadcast) is { On: false }, "off, with the hint"); + Check(ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it as Ann@alpha.", Broadcast) is { On: false, Address: null }, "the status line when off: off, no address"); + Check(ChatNetwork.Classify("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast) is { On: false }, "the leave line: off"); + + Case("Classify_LookAlikes"); + string said = "You are on the Dereth Network as Bob@alpha. The hub is connected."; + Check(ChatNetwork.Classify(said, Speech) == null, "a player saying it in Local is not a status"); + Check(ChatNetwork.Classify(said, Tell) == null, "nor in a tell"); + Check(ChatNetwork.Classify(said, Channel) == null, "nor on a channel"); + Check(ChatNetwork.Classify("You are not on the Dereth Network.", Speech) == null, "an off text said in Local is not a status"); + Check(ChatNetwork.Classify("This world is not on the Dereth Network.", Broadcast) == null, "the world's own state is not the character's"); + Check(ChatNetwork.Classify("You have entered the Roleplay channel.", Broadcast) == null, "room feedback is not a status"); + Check(ChatNetwork.Classify("You are on the Dereth Network as nobody.", Broadcast) == null, "an on line without an address is not taken"); + Check(ChatNetwork.Classify("", Broadcast) == null, "empty"); + Check(ChatNetwork.IsDirectoryLine("Your directory page: https://example.org/directory/character/", Broadcast), "the directory line"); + Check(!ChatNetwork.IsDirectoryLine("Your directory page: https://example.org/x", Speech), "a directory line said in Local is not one"); + + Case("Eater_EatsTheAnswerOnly"); + var eater = new NetworkReplyEater(); + string status = "You are on the Dereth Network as Ann@alpha. The hub is connected. You have no friends on other worlds."; + string page = "Your directory page: https://example.org/directory/character/"; + var st = ChatNetwork.Classify(status, Broadcast); + Check(!eater.Take(st, status, Broadcast, 1000), "a status line nobody asked for is shown"); + Check(!eater.Take(null, page, Broadcast, 1100), "and so is its directory line"); + eater.Query(2000); + Check(!eater.Take(null, "You have entered the Roleplay channel.", Broadcast, 2100), "an unrelated line while asking is shown"); + Check(eater.Take(st, status, Broadcast, 2500), "the answer is eaten"); + Check(eater.Take(null, page, Broadcast, 3000), "its directory line within 2 s is eaten"); + Check(!eater.Take(null, page, Broadcast, 3100), "a second directory line is shown"); + Check(!eater.Take(st, status, Broadcast, 3200), "a second status line is shown (one question, one answer)"); + + Case("Eater_Windows"); + eater.Query(10_000); + Check(!eater.Take(st, status, Broadcast, 10_000 + NetworkReplyEater.StatusWindowMs + 1), "an answer after the window is shown"); + eater.Query(30_000); + Check(eater.Take(st, status, Broadcast, 30_500), "in time: eaten"); + Check(!eater.Take(null, page, Broadcast, 30_500 + NetworkReplyEater.DirectoryWindowMs + 1), "a directory line after 2 s is shown"); + eater.Query(40_000); + var off = ChatNetwork.Classify("You are not on the Dereth Network. Type @derethnetwork on to join it as Ann@alpha.", Broadcast); + Check(eater.Take(off, "x", Broadcast, 40_100), "an off answer is eaten"); + Check(!eater.Take(null, page, Broadcast, 40_200), "an off answer has no directory line to eat"); + eater.Query(50_000); + eater.Clear(); + Check(!eater.Take(st, status, Broadcast, 50_100), "a cleared question eats nothing"); + + Case("Observe_MovesOnAndAddress"); + ChatNetwork.ResetSession(); + Check(ChatNetwork.On == null && ChatNetwork.Address == null, "a new session knows nothing"); + Check(ChatNetwork.TryBeginQuery() && !ChatNetwork.TryBeginQuery(), "one question per session"); + ChatNetwork.Eater.Query(100); + Check(ChatNetwork.Observe(status, Broadcast, 200), "the session's answer is eaten"); + Check(ChatNetwork.On == true && ChatNetwork.Address == "Ann@alpha", "and puts the character on, as Ann@alpha"); + Check(ChatNetwork.OnOrUnknown && ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "on: Global lines are sent"); + Check(!ChatNetwork.Observe(said, Speech, 300) && ChatNetwork.On == true, "a player's look-alike changes nothing"); + Check(!ChatNetwork.Observe("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast, 400), + "a later leave line is shown"); + Check(ChatNetwork.On == false && ChatNetwork.Address == null, "and puts the character off"); + Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == null, "off: Global lines are blocked"); + ChatNetwork.JoinProblem = "x"; + ChatNetwork.ResetSession(); + Check(ChatNetwork.On == null && ChatNetwork.OnOrUnknown && ChatNetwork.JoinProblem == null, "logout/login: unknown again (sent as on), no problem shown"); + Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "unknown: Global lines are sent"); + Check(ChatNetwork.TryBeginQuery(), "and the next view asks again"); + ChatNetwork.ResetSession(); + + Case("JoinKey"); + Check(ChatNetwork.JoinKey(" DreamWeave ", " Ann ") == "dreamweave/Ann", "server lower-cased, both trimmed, the name kept"); + + Case("Settings_NetworkJoinRooms"); + var opts = RynthChatJsonContext.Default.RynthChatSettingsDto; + string none = JsonSerializer.Serialize(new RynthChatSettingsDto(), opts); + Check(!none.Contains("networkJoinRooms", StringComparison.Ordinal), "absent while unset"); + var withRoom = new RynthChatSettingsDto { NetworkJoinRooms = new Dictionary { ["dreamweave/Ann"] = "Roleplay" } }; + string json = JsonSerializer.Serialize(withRoom, opts); + RynthChatSettingsDto back = JsonSerializer.Deserialize(json, opts)!; + Check(json.Contains("\"networkJoinRooms\":{\"dreamweave/Ann\":\"Roleplay\"}", StringComparison.Ordinal), "written as server/character -> room"); + Check(back.NetworkJoinRooms is { } m && m.TryGetValue("dreamweave/Ann", out string? r) && r == "Roleplay", "and read back"); + Check(JsonSerializer.Deserialize(OldFile, opts)!.NetworkJoinRooms == null, "an older file has none"); + } + private static void PinBookkeeping() { Case("Toggle_AddsAtEndAndRemoves");