acdream/tests/AcDream.Runtime.Tests/Gameplay/RuntimeCommunicationStateTests.cs
Erik e0e7888308 fix(chat): CH2 rework — SpewBox tick-driven visibility + binary-derived error table
Reworks Campaign CH slice CH2 per the REJECT-review findings doc
(docs/research/2026-08-09-ch2-review-findings.md).

BLOCKER 1 — SpewBoxController never rendered a line and leaked its
pending queue. LinesProvider only ran through UiText.OnDraw, which
gates on Visible — and the box started invisible, so the provider (the
sole caller of SpewBoxState.Tick) never ran. Gave the controller an
explicit per-frame Tick(now) driven by UiRoot's global-message-3
broadcast (a zero-size GlobalTimeSink child, the same pattern
VendorUiController.DragOverGlobalTimeSink already uses), matching
retail's gmSpewBoxUI::Update. LinesProvider now only returns the
cache. Tests rewritten to drive root.Tick(...) instead of calling the
provider directly, plus new coverage for visibility-without-a-draw,
queue-drain-without-a-draw, and bounded-queue-across-many-ticks.

BLOCKER 2 — re-derived the HandleFailureEvent routing table from the
PDB-paired binary instead of the pseudo-C's ~33-char string previews.
tools/pdb-extract/sweep_weenie_strings.py sweeps every push imm32 in
VA 0x571990-0x575480, dereferences into .rdata/.data, and decodes the
full UTF-16LE literal. Added the 5 ids dispatched via else-if (missed
by case-label enumeration), resolved 0x4F8 (previously excluded),
fixed 18 wrong strings (16 the review flagged + 2 more — 0x4E9 and
0x518 — an automated diff between every swept literal and the landed
table found). Every changed row cross-checked against ACE's
WeenieError/WeenieErrorWithString enum doc comments; both oracles
agreed on every row, including a case where the review's own proposed
text for the new 0x4E8 row was itself wrong (it was 0x4E9's text) —
corrected via the else-if block's own instruction address plus the ACE
cross-check. Pinned table count: 344 (338 + 5 + 0x4F8).

SHOULD-FIX 1 — RuntimeCommunicationState.ResetSpewBox was dead code;
folded into the ChatIdentity generation-reset stage (same lifetime
boundary), with a reset assertion added to the existing populated-reset
test.

SHOULD-FIX 2 — AddText trimmed only the trailing end and invented an
empty-string early return; retail's AddTextToScroll trims both ends
(trim(&str, 1, 1, ws)) and has no empty guard. Both retired.

SHOULD-FIX 3 — ShowWeenieError bypassed the AddText chokepoint via
ChatLog.OnWeenieError (hardcoded LogTextType 0x00); routed through
Communication.AddText(Resolve(code, param)) instead, and
ChatLog.OnWeenieError is deleted — GameEventWiring's legacy no-router
fallback now resolves + calls OnSystemMessage directly.

SHOULD-FIX 4 — retail's HandleFailureEvent switch has no default case;
an unmapped id now resolves to a null Text (silence toward the
player) instead of the invented "WeenieError 0xNNNN" hex fallback,
with a diagnostics-only console log line for the id.

NITs — AP-TBD placeholders corrected to their real register rows
(AP-178, not the unrelated AP-177 lifetime row); filed AP-180 for the
windowId dual-destination gap and corrected three stale "lands with
CH2" comments; extended SpewBoxLayoutDumpDiagnostic from dats.Portal
to dats.Local and found the SpewBox element for real — LayoutDesc
0x21000011, element 0x10000048, size 450x72, MaxConcurrentItems
(ListBox property 0x10000028) = 4, not retail's code default of 1.
AP-178 narrowed accordingly; SpewBoxState.MaxConcurrentItems and
SpewBoxController's extent/anchor/OneLine are now authored rather than
placeholder (absolute screen position and colour remain open); fixed
the "19 ids... lists 18" miscount by retiring the stale paragraph in
the class doc rewrite; aligned the UseDone handler's silent-status
check with the other two WeenieError handlers.

Full Release suite: 11,914 passed / 4 skipped / 0 failed (build 0
errors).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-09 18:14:26 +02:00

283 lines
10 KiB
C#

using AcDream.Core.Chat;
using AcDream.Core.Social;
using AcDream.Runtime.Gameplay;
namespace AcDream.Runtime.Tests.Gameplay;
public sealed class RuntimeCommunicationStateTests
{
[Fact]
public void SocialViewBorrowsFriendsAndSquelchOwners()
{
using var state = new RuntimeCommunicationState();
state.Friends.Apply(new AcDream.Core.Social.FriendsUpdate(
AcDream.Core.Social.FriendsUpdateType.Full,
[
new AcDream.Core.Social.FriendEntry(
0x50000001u,
"Friend",
Online: true,
AppearOffline: false,
Friends: [],
FriendOf: []),
]));
state.Squelch.Replace(new AcDream.Core.Social.SquelchDatabase(
new Dictionary<string, uint>(StringComparer.OrdinalIgnoreCase)
{
["account"] = 1u,
},
new Dictionary<uint, AcDream.Core.Social.SquelchInfo>(),
new AcDream.Core.Social.SquelchInfo(
string.Empty,
false,
new HashSet<uint> { 3u })));
RuntimeSocialSnapshot snapshot = state.SocialView.Snapshot;
Assert.Equal(1, snapshot.FriendCount);
Assert.Equal(1, snapshot.SquelchedAccountCount);
Assert.Equal(1, snapshot.GlobalSquelchTypeCount);
Assert.True(state.SocialView.TryGetFriend(
0x50000001u,
out RuntimeFriendSnapshot friend));
Assert.Equal("Friend", friend.Name);
Assert.True(friend.Online);
}
[Fact]
public void OwnsOneExactCommunicationGraphAndPublishesCommittedEntries()
{
using var state = new RuntimeCommunicationState();
var observer = new RecordingObserver();
using IDisposable subscription = state.Events.Subscribe(observer);
state.Chat.OnTellReceived("Bestie", "hello", 0x50000001u, logTextType: 0x03u);
RuntimeCommunicationEvent delta = Assert.Single(observer.Events);
Assert.Equal(1UL, delta.Sequence);
Assert.Equal(state.Chat.Revision, delta.Entry.Revision);
Assert.Equal(1, state.View.Count);
Assert.Equal(state.Chat.Revision, state.View.Revision);
Assert.Equal(1UL, state.LastSequence);
Assert.Equal(0, state.PendingDispatchCount);
Assert.False(state.IsDispatching);
Assert.Equal("Bestie", state.CommandTargets.LastIncomingTellSender);
Assert.Equal("hello", delta.Entry.Text);
}
[Fact]
public void ReentrantAppendPreservesSequenceForEveryObserver()
{
using var state = new RuntimeCommunicationState();
var reentrant = new ReentrantObserver(state.Chat);
var trailing = new RecordingObserver();
using IDisposable first = state.Events.Subscribe(reentrant);
using IDisposable second = state.Events.Subscribe(trailing);
state.Chat.OnSystemMessage("first", 0u);
Assert.Equal([1UL, 2UL], reentrant.Sequences);
Assert.Equal(
[1UL, 2UL],
trailing.Events.Select(item => item.Sequence).ToArray());
Assert.Equal(["first", "second"], trailing.Events
.Select(item => item.Entry.Text)
.ToArray());
Assert.Equal(0, state.PendingDispatchCount);
Assert.False(state.IsDispatching);
}
[Fact]
public void ObserverFailureDoesNotStarveLaterObserverOrOwner()
{
using var state = new RuntimeCommunicationState();
var recording = new RecordingObserver();
using IDisposable throwing =
state.Events.Subscribe(new ThrowingObserver());
using IDisposable trailing = state.Events.Subscribe(recording);
state.Chat.OnSystemMessage("still committed", 0u);
Assert.Equal(1, state.Chat.Count);
Assert.Single(recording.Events);
Assert.Equal(1, state.DispatchFailureCount);
Assert.IsType<InvalidOperationException>(state.LastDispatchFailure);
}
[Fact]
public void SessionResetsClearScopedStateWithoutClearingTranscript()
{
using var state = new RuntimeCommunicationState();
state.Chat.OnTellReceived("Bestie", "hello", 0x50000001u, logTextType: 0x03u);
state.Chat.OnSelfSent(ChatKind.Tell, "outgoing", logTextType: 0x04u, targetOrChannel: "Caith");
state.TurbineChat.OnChannelsReceived(
1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u, 10u);
state.Friends.Apply(new FriendsUpdate(
FriendsUpdateType.Full,
[new FriendEntry(1u, "Friend", true, false, [], [])]));
state.Squelch.Replace(new SquelchDatabase(
new Dictionary<string, uint> { ["account"] = 1u },
new Dictionary<uint, SquelchInfo>(),
new SquelchInfo(string.Empty, false, new HashSet<uint>())));
state.ResetCommandTargets();
state.ResetChatIdentity();
state.ResetNegotiatedChannels();
state.ResetFriends();
state.ResetSquelch();
Assert.Equal(2, state.Chat.Count);
Assert.Null(state.CommandTargets.LastIncomingTellSender);
Assert.Null(state.CommandTargets.LastOutgoingTellTarget);
Assert.False(state.TurbineChat.Enabled);
Assert.Empty(state.Friends.Snapshot());
Assert.Empty(state.Squelch.Snapshot().Accounts);
}
[Fact]
public void DisposeDetachesStreamAndAllBorrowedState()
{
var state = new RuntimeCommunicationState();
var observer = new RecordingObserver();
IDisposable subscription = state.Events.Subscribe(observer);
state.Dispose();
state.Dispose();
state.Chat.OnSystemMessage("after dispose", 0u);
Assert.True(state.IsDisposed);
Assert.Equal(0, state.SubscriberCount);
Assert.Empty(observer.Events);
Assert.Throws<ObjectDisposedException>(
() => state.Events.Subscribe(new RecordingObserver()));
subscription.Dispose();
}
[Fact]
public void IndependentRuntimeInstancesNeverShareState()
{
using var first = new RuntimeCommunicationState();
using var second = new RuntimeCommunicationState();
first.Chat.OnTellReceived("OnlyFirst", "hello", 0x50000001u, logTextType: 0x03u);
Assert.Equal(1, first.View.Count);
Assert.Equal(0, second.View.Count);
Assert.Equal("OnlyFirst", first.CommandTargets.LastIncomingTellSender);
Assert.Null(second.CommandTargets.LastIncomingTellSender);
}
// ── Campaign CH slice CH2: AddText routing chokepoint ────────────────
[Fact]
public void AddText_ClientLocal_RoutesToSpewBoxOnly_NeverChatTranscript()
{
// Retail: type == 0x1A (ClientLocal) is exactly the bit every
// ChatInterface window's default filter excludes
// (ChatInterface::ChatInterface @0x004F4550,
// m_llTextTypeFilter &= 0xFBFFFFFF). The CH1-era ChatLog.OnWeenieError
// path put EVERY WeenieError line in chat, including 0x1A ones —
// this is the fix: a ClientLocal line must reach SpewBox and never
// touch the chat transcript at all.
using var state = new RuntimeCommunicationState();
state.AddText("You can't jump while in the air", RetailLogTextType.ClientLocal);
Assert.Equal(0, state.Chat.Count);
state.SpewBox.Tick(0d);
Assert.Equal(1, state.SpewBox.Count);
Assert.Equal("You can't jump while in the air", state.SpewBox.Snapshot()[0].Text);
}
[Theory]
[InlineData(RetailLogTextType.Default)]
[InlineData(RetailLogTextType.Magic)]
[InlineData(RetailLogTextType.System)]
public void AddText_NonClientLocalTypes_RouteToChatOnly_NeverSpewBox(RetailLogTextType type)
{
using var state = new RuntimeCommunicationState();
state.AddText("Your spell fizzled.", type);
Assert.Equal(1, state.Chat.Count);
Assert.Equal("Your spell fizzled.", state.Chat.Snapshot()[0].Text);
Assert.Equal((uint)type, state.Chat.Snapshot()[0].LogTextType);
state.SpewBox.Tick(0d);
Assert.Equal(0, state.SpewBox.Count);
}
[Fact]
public void AddText_TrimsBothEnds_LikeRetailAddTextToScroll()
{
// CH2 REJECT-review rework (SHOULD-FIX 2,
// docs/research/2026-08-09-ch2-review-findings.md): retail's
// AddTextToScroll @0x00563C50 calls trim(&str, 1, 1, ws) — BOTH
// ends, not trailing-only.
using var state = new RuntimeCommunicationState();
state.AddText(" Out of Range! ", RetailLogTextType.ClientLocal);
state.SpewBox.Tick(0d);
Assert.Equal("Out of Range!", state.SpewBox.Snapshot()[0].Text);
}
[Fact]
public void AddText_EmptyAfterTrim_StillBroadcasts_LikeRetail()
{
// CH2 REJECT-review rework (SHOULD-FIX 2): retail's
// AddTextToScroll has no empty-string guard — the previous
// early-return was an unregistered acdream-only divergence, now
// retired. An all-whitespace message still reaches its destination
// as an empty string.
using var state = new RuntimeCommunicationState();
state.AddText(" ", RetailLogTextType.ClientLocal);
state.AddText(" ", RetailLogTextType.Default);
state.SpewBox.Tick(0d);
Assert.Equal(1, state.SpewBox.Count);
Assert.Equal("", state.SpewBox.Snapshot()[0].Text);
Assert.Equal(1, state.Chat.Count);
Assert.Equal("", state.Chat.Snapshot()[0].Text);
}
[Fact]
public void Dispose_ResetsSpewBox()
{
var state = new RuntimeCommunicationState();
state.AddText("about to be torn down", RetailLogTextType.ClientLocal);
state.SpewBox.Tick(0d);
Assert.Equal(1, state.SpewBox.Count);
state.Dispose();
Assert.Equal(0, state.SpewBox.Count);
}
private sealed class RecordingObserver : IRuntimeCommunicationObserver
{
public List<RuntimeCommunicationEvent> Events { get; } = [];
public void OnChat(in RuntimeCommunicationEvent delta) =>
Events.Add(delta);
}
private sealed class ReentrantObserver(ChatLog chat)
: IRuntimeCommunicationObserver
{
public List<ulong> Sequences { get; } = [];
public void OnChat(in RuntimeCommunicationEvent delta)
{
Sequences.Add(delta.Sequence);
if (delta.Sequence == 1UL)
chat.OnSystemMessage("second", 1u);
}
}
private sealed class ThrowingObserver : IRuntimeCommunicationObserver
{
public void OnChat(in RuntimeCommunicationEvent delta) =>
throw new InvalidOperationException("observer");
}
}