acdream/src/AcDream.Core/Chat/ChatLog.cs
Erik 3501194083 fix(chat): /help client-side handler + System dedup + ThatIsNotAValidCommand template
Phase J follow-up after a 2026-04-25 trace where typing /help
produced two identical "Unknown command: help" lines (ACE fires the
text via both GameMessageSystemChat 0xF7E0 and a paired
CommunicationTransientString 0x02EB), and the server's WeenieError
0x0026 trailer rendered cryptically as "WeenieError 0x0026".

Three small changes:

1. WeenieErrorMessages: add 0x0026 ThatIsNotAValidCommand ->
   "That is not a valid command." Plus 0x0414 / 0x050F that Phase J
   already added are now covered by tests too.

2. ChatLog.OnSystemMessage dedup. Track last system text + arrival
   time; if a second identical text shows up within 1 second,
   suppress. ACE's two-path send (gag warnings, command errors,
   etc.) collapses to a single chat line. Long bursts of repeated
   text still skip the duplicates without resetting the timer.

3. Client-side /help and /clear in ChatPanel. Intercepted BEFORE
   the parser passes to the server bus:
   - /help, /?, /h (case-insensitive) -> render local cheat-sheet
     listing acdream's slash prefixes via ChatLog.OnSystemMessage.
     Avoids the round-trip to ACE that produced the duplicate
     "Unknown command: help" lines AND gives users discoverability.
   - /clear, /cls -> drains the chat log so the panel starts empty.

   New ChatVM.ShowSystemMessage() + ChatVM.Clear() expose the
   minimum surface the panel needs to dispatch client-only feedback
   without coupling the panel to ChatLog directly.

12 new tests:
- 3 WeenieErrorMessages template adds (0x0026 / 0x0414 / 0x050F).
- 4 ChatLog dedup cases (immediate dup, different text, triplet,
  bookended-by-different-text).
- 5 ChatPanel client-command cases (/help, 3 alias variants,
  /clear).

Solution total: 1033 green (243 Core.Net + 130 UI + 660 Core),
0 warnings.

Acceptance: type /help in chat -> local help banner appears, no
server round-trip, no "Unknown command: help" duplicates. Type
/clear -> chat tail empty. Welcome banner + WeenieError-templated
"You are not in an allegiance!" / "You do not belong to a
Fellowship." continue rendering once each.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 21:22:07 +02:00

354 lines
14 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
namespace AcDream.Core.Chat;
/// <summary>
/// Unified chat log — mirrors every chat-bearing message the server
/// sends (local HearSpeech, broadcast ChannelBroadcast, whispered
/// Tell, system TransientMessage, PopupString).
///
/// <para>
/// Sits behind the UI chat panel (Phase D.2) and the scripting
/// plugin API so plugins can react to chat (e.g. auto-reply, loot
/// logging).
/// </para>
///
/// <para>
/// Retail keeps ~200 lines of scrollback. Our ring buffer defaults to
/// 500 and is configurable.
/// </para>
/// </summary>
public sealed class ChatLog
{
private readonly ConcurrentQueue<ChatEntry> _buffer = new();
private readonly int _maxEntries;
private uint _localPlayerGuid;
// Phase J follow-up: ACE often sends the same system text via two
// wire paths (GameMessageSystemChat 0xF7E0 + GameEventCommunication-
// TransientString 0x02EB) for back-compat — we wired both to
// OnSystemMessage in I.5/J, so the user saw lines like "Unknown
// command: help" twice. Dedupe within a short window: track the
// last system text + arrival time; if a second identical text
// shows up within one second, skip.
private string _lastSystemText = "";
private DateTime _lastSystemAt = DateTime.MinValue;
private static readonly TimeSpan SystemDedupWindow = TimeSpan.FromSeconds(1);
public ChatLog(int maxEntries = 500)
{
if (maxEntries < 1) throw new ArgumentOutOfRangeException(nameof(maxEntries));
_maxEntries = maxEntries;
}
/// <summary>Fires every time a new entry is appended.</summary>
public event Action<ChatEntry>? EntryAppended;
/// <summary>Snapshot of all current entries, oldest first.</summary>
public ChatEntry[] Snapshot() => _buffer.ToArray();
public int Count => _buffer.Count;
/// <summary>
/// Push the authoritative local-player GUID from <c>WorldSession</c>.
/// One-way setter — only <c>GameWindow</c> should call it, exactly
/// once per live session. Used by <see cref="OnLocalSpeech"/> to
/// recognize ACE's HearSpeech echo of our own /say (server's
/// HandleActionTalk broadcasts to all in range INCLUDING the
/// sender) and re-render it as <c>"You say, ..."</c>.
/// </summary>
public void SetLocalPlayerGuid(uint guid) => _localPlayerGuid = guid;
// ── Inbound adapters ─────────────────────────────────────────────────────
/// <summary>Local or ranged HearSpeech (0x02BB / 0x02BC).</summary>
/// <remarks>
/// Phase I.5: an empty <paramref name="sender"/> is substituted with
/// "You" — the server uses this convention to indicate that the
/// player is the speaker (e.g. their own ranged shouts echo back).
/// Port from holtburger
/// <c>references/holtburger/.../client/messages.rs</c> lines 476-487.
/// </remarks>
public void OnLocalSpeech(string sender, string text, uint senderGuid, bool isRanged)
{
// Phase J: ACE's HandleActionTalk broadcasts a HearSpeech echo
// back to the sender too. Detect own echo by guid match and
// substitute "" so the formatter renders "You say, ..." (single
// first-person echo) instead of "+Acdream says, ..."
// (third-person duplicate of our optimistic, already dropped).
bool isOwnEcho = _localPlayerGuid != 0 && senderGuid == _localPlayerGuid;
string effectiveSender = (isOwnEcho || string.IsNullOrEmpty(sender)) ? "You" : sender;
Append(new ChatEntry(
Kind: isRanged ? ChatKind.RangedSpeech : ChatKind.LocalSpeech,
Sender: effectiveSender,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0));
}
/// <summary>EmoteText (0x01E0) — server-driven third-person emote.</summary>
public void OnEmote(string senderName, string text, uint senderGuid)
{
Append(new ChatEntry(
Kind: ChatKind.Emote,
Sender: senderName,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0));
}
/// <summary>SoulEmote (0x01E2) — complex emote (chat + paired animation).</summary>
public void OnSoulEmote(string senderName, string text, uint senderGuid)
{
Append(new ChatEntry(
Kind: ChatKind.SoulEmote,
Sender: senderName,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0));
}
/// <summary>PlayerKilled (0x019E) — death announcement.</summary>
/// <remarks>
/// Death messages are routed as <see cref="ChatKind.System"/> so they
/// share styling with other server announcements. The
/// <c>SenderGuid</c> field carries the victim guid; the
/// <c>ChannelId</c> field carries the killer guid (a small misuse
/// of the field but avoids a schema change).
/// </remarks>
public void OnPlayerKilled(string deathMessage, uint victimGuid, uint killerGuid)
{
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: deathMessage,
SenderGuid: victimGuid,
ChannelId: killerGuid));
}
/// <summary>WeenieError (0x028A) / WeenieErrorWithString (0x028B).</summary>
/// <remarks>
/// Phase I.5: previously-orphaned parser. The server fires this when a
/// game-logic action fails (e.g. "you don't have enough mana", "you
/// can't pick that up"). Routed as <see cref="ChatKind.System"/>; the
/// <c>ChannelId</c> field carries the WeenieError code so plugins can
/// filter or react. <paramref name="param"/> is the interpolated
/// substring (null for plain WeenieError, set for WeenieErrorWithString).
/// </remarks>
public void OnWeenieError(uint errorId, string? param)
{
// Phase I (post-launch fix): translate the wire code into the
// retail-faithful template via WeenieErrorMessages. Many codes
// are *informational* (e.g. 0x051B "You have entered the X
// channel.", 0x051D "Turbine Chat is enabled.") not errors;
// the old "WeenieError 0xNNNN" framing was misleading. Unknown
// codes still fall back to the raw "WeenieError 0xNNNN[: param]"
// form so nothing is silently lost. See
// WeenieErrorMessages.Format for the templates + lookup table.
string text = WeenieErrorMessages.Format(errorId, param);
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: errorId));
}
/// <summary>
/// Channel broadcast — legacy <c>ChatChannel (0x0147)</c> or the
/// TurbineChat (<c>0xF7DE</c>) global community channels (General,
/// Trade, LFG, Roleplay, Society, Olthoi). Pass
/// <paramref name="channelName"/> when the caller knows the
/// friendly room name (TurbineChat dispatch always does); the
/// <c>ChatVM</c> formatter renders entries as
/// <c>"[ChannelName] Sender says, \"text\""</c> when set.
/// </summary>
public void OnChannelBroadcast(uint channelId, string sender, string text, string channelName = "")
{
Append(new ChatEntry(
Kind: ChatKind.Channel,
Sender: sender,
Text: text,
SenderGuid: 0,
ChannelId: channelId)
{
ChannelName = channelName,
});
}
/// <summary>GameEvent Tell (0x02BD) — whisper received.</summary>
public void OnTellReceived(string sender, string text, uint senderGuid)
{
Append(new ChatEntry(
Kind: ChatKind.Tell,
Sender: sender,
Text: text,
SenderGuid: senderGuid,
ChannelId: 0));
}
/// <summary>
/// System chat — covers GameMessageSystemChat (0xF7E0
/// ServerMessage) and GameEventCommunicationTransientString
/// (0x02EB). Phase J follow-up: dedupe identical text arriving
/// within <see cref="SystemDedupWindow"/> so flows that fire on
/// both opcodes (e.g. "Unknown command: help" via help-command
/// failure path) only show once.
/// </summary>
public void OnSystemMessage(string text, uint chatType)
{
var now = DateTime.UtcNow;
if (text == _lastSystemText && (now - _lastSystemAt) < SystemDedupWindow)
{
// Suppress the dup — the wire-level duplicate isn't a
// user-meaningful signal. Reset the timer so a long burst
// of the same text still skips.
_lastSystemAt = now;
return;
}
_lastSystemText = text;
_lastSystemAt = now;
Append(new ChatEntry(
Kind: ChatKind.System,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: chatType));
}
/// <summary>GameEvent PopupString (0x0004) — modal dialog text.</summary>
public void OnPopup(string text)
{
Append(new ChatEntry(
Kind: ChatKind.Popup,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: 0));
}
/// <summary>
/// Phase I.7: combat-translator emits a pre-formatted line. The
/// translator (<see cref="CombatChatTranslator"/>) subscribes to
/// <see cref="Combat.CombatState"/> events and renders the retail
/// template (e.g. "You hit Mosswart for 12 slashing damage (54.0%)
/// Critical hit.") and decorates the entry with a
/// <see cref="Combat.CombatLineKind"/> so the panel can color the
/// line. Maps to holtburger's <c>info().combat()</c> /
/// <c>warning().combat()</c> / <c>error().combat()</c> tag flow at
/// <c>chat.rs:221-308</c>.
/// </summary>
public void OnCombatLine(string text, Combat.CombatLineKind kind = Combat.CombatLineKind.Info)
{
Append(new ChatEntry(
Kind: ChatKind.Combat,
Sender: "",
Text: text,
SenderGuid: 0,
ChannelId: 0)
{
CombatKind = kind,
});
}
/// <summary>
/// Echo the player's own outbound message after local send.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><b>Say</b>: pass <paramref name="targetOrChannel"/> as
/// empty; the formatter renders <c>"You say, \"text\""</c>.</item>
/// <item><b>Tell</b>: pass the target name; the formatter
/// renders <c>"You tell {target}, \"text\""</c>.</item>
/// <item><b>Channel</b>: <i>do not call</i> for global community
/// channels — the server (ACE TurbineChatHandler) echoes the
/// broadcast back to the sender already, so optimistic-echoing
/// would double-print. For legacy channels (Fellowship,
/// Allegiance) where the server may not echo, pass the
/// channel name as <paramref name="targetOrChannel"/>; it
/// becomes the entry's <c>ChannelName</c>.</item>
/// </list>
/// <c>SenderGuid == 0</c> on the resulting entry is the
/// discriminator the formatter uses to render outgoing-vs-incoming
/// (a real incoming Tell carries the sender's player guid).
/// </remarks>
public void OnSelfSent(ChatKind kind, string text, string targetOrChannel = "")
{
Append(new ChatEntry(
Kind: kind,
// For Tell, Sender carries the target name (so the formatter
// can render "You tell {Sender}..."). For LocalSpeech, we
// leave Sender empty and let the formatter substitute "You".
// For Channel callers, Sender stays empty too — ChannelName
// (below) carries the friendly name.
Sender: kind == ChatKind.Tell ? targetOrChannel : "",
Text: text,
SenderGuid: 0,
ChannelId: 0)
{
ChannelName = kind == ChatKind.Channel ? targetOrChannel : "",
});
}
private void Append(ChatEntry entry)
{
_buffer.Enqueue(entry);
while (_buffer.Count > _maxEntries)
_buffer.TryDequeue(out _);
EntryAppended?.Invoke(entry);
}
public void Clear()
{
while (_buffer.TryDequeue(out _)) { /* drain */ }
}
}
public enum ChatKind
{
LocalSpeech,
RangedSpeech,
Channel,
Tell,
System,
Popup,
Emote,
SoulEmote,
/// <summary>
/// Phase I.7: a combat feedback line emitted by
/// <see cref="CombatChatTranslator"/> from <see cref="Combat.CombatState"/>
/// events. The accompanying <see cref="ChatEntry.CombatKind"/> field
/// drives panel coloring (info / warning / error per holtburger
/// <c>chat.rs:221-308</c>).
/// </summary>
Combat,
}
public readonly record struct ChatEntry(
ChatKind Kind,
string Sender,
string Text,
uint SenderGuid,
uint ChannelId)
{
public DateTime Received { get; init; } = DateTime.UtcNow;
/// <summary>
/// Phase I.7: severity bucket for <see cref="ChatKind.Combat"/>
/// entries. Null for every other kind. Drives the
/// <see cref="ChatPanel"/>'s <c>TextColored</c> color choice.
/// </summary>
public Combat.CombatLineKind? CombatKind { get; init; }
/// <summary>
/// Friendly name of the channel for <see cref="ChatKind.Channel"/>
/// entries (e.g. "General", "Trade", "LFG", "Fellowship"). Empty
/// for non-Channel kinds. Used by <c>ChatVM.FormatEntry</c> to
/// render lines as <c>"[ChannelName] Sender says, \"text\""</c>.
/// Falls back to <c>"ch {ChannelId}"</c> if not populated.
/// </summary>
public string ChannelName { get; init; } = "";
}