acdream/src/AcDream.Core/Chat/ChatLog.cs
Erik e17caa2942 fix(chat): translate WeenieError templates + strip Tell target punctuation + Turbine routing diagnostics
Three post-launch fixes from the 2026-04-25 live verify session.

1. WeenieError display bug. Many ACE WeenieError / WeenieErrorWithString
   codes are *informational*, not error-level — the user saw cryptic
   "WeenieError 0x051B: General" / "WeenieError 0x051D" at login, but
   those decode as "You have entered the General channel." and
   "Turbine Chat is enabled." per ACE WeenieError(WithString).cs
   templates. New static helper Core/Chat/WeenieErrorMessages.cs maps
   ~30 high-frequency codes to retail-faithful templates with `_`
   placeholder substitution. ChatLog.OnWeenieError now routes through
   Format(); unknown codes still fall back to "WeenieError 0xNNNN[: param]"
   so nothing is silently lost. New codes can be added in 30 seconds
   when the user reports one.

2. Tell target eats trailing punctuation. Retail muscle memory is
   "/t Name, message" — comma is the separator. Our split-on-whitespace
   pulled "Name," (with comma) as the target, server returned 0x052B
   "That person is not available now." because no such character.
   ChatInputParser.TryParseTargeted now strips a trailing ,;:.!? from
   the target token so "/t Caith, hi" and "/t Caith hi" both work.
   Added 7 Theory cases covering each separator + the long-form alias.

3. TurbineChat routing diagnostics. The user's ACE login showed the
   "TurbineChatIsEnabled" + "YouHaveEnteredThe_Channel" notifications
   for General/Trade/LFG, confirming TurbineChat IS active server-side.
   But outbound /g /trade /lfg might still fall back to legacy
   ChatChannel (which the server then rejects). Added diagnostic
   Console.WriteLines so the next launch shows:
     - "chat: SetTurbineChatChannels parsed enabled=true general=0x... ..."
       (when ACE sends the 0x0295 channel-id table)
     - "chat: outbound TurbineChat General room=0x... cookie=0x... len=N"
       (when SendChatCmd routes a Turbine kind through 0xF7DE)
     - "chat: outbound legacy ChatChannel Fellowship id=0x... len=N"
       (when SendChatCmd uses the legacy 0x0147 path)
     - "chat: SendChatCmd kind=General dropped (turbine.Enabled=false no legacy id)"
       (when neither path can dispatch — usually means ACE didn't send
       0x0295 yet and the kind is Turbine-only)

   Sets up Bug 3 (proper outbound TurbineChat for /g /trade /lfg) for
   a follow-up commit once the next live trace shows the actual flow.

18 new tests:
- WeenieErrorMessagesTests: 11 covering known templates + fallback.
- ChatInputParserTests: +7 Theory cases for trailing-punctuation strip.

Solution total: 1007 green (114 UI + 650 Core + 243 Core.Net), 0 warnings.

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

259 lines
8.9 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;
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;
// ── 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)
{
string effectiveSender = 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>GameEvent ChannelBroadcast (0x0147).</summary>
public void OnChannelBroadcast(uint channelId, string sender, string text)
{
Append(new ChatEntry(
Kind: ChatKind.Channel,
Sender: sender,
Text: text,
SenderGuid: 0,
ChannelId: channelId));
}
/// <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>GameEvent CommunicationTransientString (0x02EB) — e.g. "Your spell fizzled!"</summary>
public void OnSystemMessage(string text, uint chatType)
{
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>
public void OnSelfSent(ChatKind kind, string text, string targetOrChannel = "")
{
Append(new ChatEntry(
Kind: kind,
Sender: targetOrChannel, // used as "to whom" for Tell / channel name for Channel
Text: text,
SenderGuid: 0,
ChannelId: 0));
}
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; }
}