acdream/tests/AcDream.Core.Net.Tests/WorldSessionCharacterSelectionTests.cs
Erik ef96c55489 fix(ui,net): Campaign LA gate round 2 — char-select exit confirmation, authored row justify, world name
Finding 1 (Exit button dead): retail's gmCharacterManagementUI Exit
button (element 0x100003A4, offset 7 from the listbox base in
ListenToElementMessage@0x004ed5a0) opens MakeConfirmExitDialog
(0x004ed250), whose exact ID_CharacterManagement_ConfirmExit text
(table 0x23000002) and m_confirmExitDialogContext re-entry guard are
now ported. On confirm (matching RecvNotice_CloseDialog@0x004ed760
case 1's ConfirmationResult check) the client exits through the
EXISTING graceful window-close seam (CharacterSelectionRuntimeBindings
.RequestExit -> d.Window.Close, the same delegate
GameplayInputCommandController's Escape fallback already uses) so
disconnected/exited status events still fire via GameWindow.OnClosing
-> CompleteShutdown. Retail's real post-confirm destination is
QueueUIMode(0x10000009) -> gmEpilogueUI, an epilogue screen this round
does not port — recorded as AD-99. Credits (element 0x100003A3,
QueueUIMode(0x10000005) -> gmCreditsUI) stays visibly ghosted like
Create, same treatment, out of scope this round.

Finding 2 (row names center-aligned, retail is left): the character
row template (LayoutDesc 0x21000004, element 0x100003A5, live-DAT
confirmed HJustify=Left with three stateful Type-3 highlight-art
children and no Type-12 caption child) authors its OWN justify
directly, with no separate text child to lift a label from.
DatWidgetFactory.BuildButton's Left-justify branch required
!ReferenceEquals(labelInfo, info) — true only when a label was LIFTED
from a distinct child — so a button's own direct HJustify=Left was
silently dropped to UiButton's Center default. Widened the branch to
also honor the direct case, preserving the existing lifted-child
LabelOffsetX behavior and leaving genuinely-centered buttons
(CREATE/ENTER/DELETE/RESTORE) untouched.

Finding 3 (World box empty): parsed ACE's GameMessageServerName
(opcode 0xF7E1, ACE.Server/Network/GameMessages/Messages/
GameMessageServerName.cs; retail CM_Login::DispatchUI_WorldInfo
@0x006ad860 -> ClientUISystem::Handle_Login__WorldInfo@0x005641a0 ->
ECM_Login::SendNotice_WorldName@0x00692b10, notice 0x186a2, consumed
by gmCharacterManagementUI::UpdateWorldName@0x004ec120 /
RecvNotice_WorldName@0x004ec360 onto element 0x1000039B) as
src/AcDream.Core.Net/Messages/ServerName.cs, cross-checked against
holtburger's ServerNameData. WorldSession.ServerNameReceived fires
alongside CharacterListReceived (ACE sends both in one
SendConnectResponse batch); RuntimeCharacterSelectionState.
ApplyWorldName is the new J-owner field (ungated by lifecycle, since
either message can arrive first); CharacterManagementUiController
binds it onto the WorldTextElementId UiText. Per the LA1 status
vocabulary, the characterList STATUS event's worldName field is
intentionally NOT added this round (kept bounded to the client-side
fix) — a follow-up if the launcher UI wants it.

Also corrects AD-44, discovered stale while filing AD-99: its opening
claim ("acdream has no retained character-management screen") was
false as of this session — LA7/LA8 shipped the screen in earlier
commits without updating this row.

Tests: exit-confirm open/cancel/confirm/re-entry-guard flow;
DatWidgetFactory own-HJustify-Left/Center regression tests plus the
live-DAT pinned row-justify assertion; ServerName parse round-trip
(byte-exact vs ACE's AceWireWriter fixture, truncation/wrong-opcode
cases); WorldSession dispatch test (roster+world in one wire batch);
RuntimeCharacterSelectionState.ApplyWorldName tests (order-independent
of ApplyRoster, unchanged-value no-op, Reset clears); controller test
binding the World text element to the live snapshot. Extended the
shared RetailDialogFactoryTests.BuildDialogLayout test fixture with a
Confirmation-type branch (Accept/Reject buttons) since this is its
first RetailDialogType.Confirmation consumer.

Suites: full solution Release build green; AcDream.App.Tests 5100/6
skips, AcDream.Core.Net.Tests 965/0, AcDream.Runtime.Tests 1665/0, all
Release, 0 failures; live-DAT probes (ACDREAM_PROBE_LIVE_MOUNT=1)
green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 11:50:45 +02:00

282 lines
9.4 KiB
C#

using System.Buffers.Binary;
using System.Net;
using System.Reflection;
using AcDream.Core.Net.Messages;
using AcDream.Core.Net.Packets;
using AcDream.Core.Net.Tests.Transport;
namespace AcDream.Core.Net.Tests;
public sealed class WorldSessionCharacterSelectionTests
{
private sealed class NullTransport : IWorldSessionTransport
{
public void Send(ReadOnlySpan<byte> datagram) { }
public void Send(IPEndPoint remote, ReadOnlySpan<byte> datagram) { }
public int Receive(
Span<byte> destination,
TimeSpan timeout,
out IPEndPoint? from)
{
from = null;
return -1;
}
public ValueTask<NetReceiveResult> ReceiveAsync(
Memory<byte> destination,
CancellationToken cancellationToken) =>
ValueTask.FromCanceled<NetReceiveResult>(cancellationToken);
public void Dispose() { }
}
[Fact]
public void CharacterManagementSends_UseRetailQueuesAndExactBodies()
{
using var session = CreateSession();
var sent = new List<(byte[] Body, GameMessageGroup Queue)>();
session.GameMessageCapture =
(body, queue) => sent.Add((body, queue));
session.SendDeleteCharacter("Canonical", activeIndex: 3);
session.SendRestoreCharacter(0x50000001u);
Assert.Collection(
sent,
delete =>
{
Assert.Equal(GameMessageGroup.LoginQueue, delete.Queue);
Assert.Equal(
CharacterDelete.BuildRequestBody("Canonical", 3u),
delete.Body);
},
restore =>
{
Assert.Equal(GameMessageGroup.ControlQueue, restore.Queue);
Assert.Equal(
CharacterRestore.BuildRequestBody(0x50000001u),
restore.Body);
});
}
[Fact]
public void UiQueueReplies_DispatchInWireOrderAndRosterRefreshReplacesCharacters()
{
using var session = CreateSession();
var events = new List<string>();
session.CharacterListReceived += roster =>
events.Add($"roster:{roster.Characters[0].SecondsGreyedOut}");
session.CharacterDeleteAcknowledged += () => events.Add("delete");
session.CharacterRestoreReceived += restore =>
events.Add($"restore:{restore.Guid:X8}");
session.CharacterErrorReceived += error =>
events.Add($"error:{error.RawErrorCode:X}");
byte[] packet = BuildPacket(
BuildRoster(secondsGreyedOut: 0u),
BitConverter.GetBytes(CharacterDelete.Opcode),
BuildRestoreResponse(),
BuildCharacterError(CharacterError.Code.Delete),
BuildRoster(secondsGreyedOut: 1u));
InvokeProcessDatagram(session, packet);
Assert.Equal(
[
"roster:0",
"delete",
"restore:50000001",
"error:6",
"roster:1",
],
events);
CharacterList.Character current =
Assert.Single(session.Characters!.Characters);
Assert.Equal(1u, current.SecondsGreyedOut);
}
[Fact]
public void ServerName_Dispatches_AndPopulatesServerInfo()
{
// Campaign LA gate round 2 finding 3: ACE's SendConnectResponse
// enqueues CharacterList then ServerName in the same batch
// (AuthenticationHandler.cs:257-261) — assert both arrive, in wire
// order, through the same UIQueue dispatch path.
using var session = CreateSession();
var events = new List<string>();
session.CharacterListReceived += _ => events.Add("roster");
session.ServerNameReceived += info => events.Add($"world:{info.WorldName}");
byte[] packet = BuildPacket(
BuildRoster(secondsGreyedOut: 0u),
BuildServerName("sawato", currentConnections: 3, maxConnections: 100));
InvokeProcessDatagram(session, packet);
Assert.Equal(["roster", "world:sawato"], events);
Assert.NotNull(session.ServerInfo);
Assert.Equal("sawato", session.ServerInfo!.Value.WorldName);
Assert.Equal(3, session.ServerInfo!.Value.CurrentConnections);
Assert.Equal(100, session.ServerInfo!.Value.MaxConnections);
}
[Fact]
public void ImmediateEnterWorld_IgnoresNumErrorsSentinelBeforeServerReady()
{
var transport = new FakeAceTransport
{
AutoReplyServerReady = false,
};
using var session = new WorldSession(
new IPEndPoint(IPAddress.Loopback, 9000),
transport);
int errors = 0;
session.CharacterErrorReceived += _ => errors++;
ConfigureSentinelThenServerReady(transport);
session.Connect(
FakeAceTransport.DefaultAccountName,
"testpassword",
TimeSpan.FromSeconds(5));
session.EnterWorld(0, TimeSpan.FromSeconds(5));
Assert.Equal(WorldSession.State.InWorld, session.CurrentState);
Assert.Equal(0, errors);
}
[Fact]
public void PausedEnterWorld_IgnoresNumErrorsSentinelBeforeServerReady()
{
var transport = new FakeAceTransport
{
AutoReplyServerReady = false,
};
using var session = new WorldSession(
new IPEndPoint(IPAddress.Loopback, 9000),
transport);
int errors = 0;
session.CharacterErrorReceived += _ => errors++;
ConfigureSentinelThenServerReady(transport);
session.Connect(
FakeAceTransport.DefaultAccountName,
"testpassword",
TimeSpan.FromSeconds(5));
session.StartCharacterSelectionReceive();
session.EnterWorld(0, TimeSpan.FromSeconds(5));
Assert.Equal(WorldSession.State.InWorld, session.CurrentState);
Assert.Equal(0, errors);
}
private static WorldSession CreateSession() =>
new(
new IPEndPoint(IPAddress.Loopback, 9000),
new NullTransport());
private static void ConfigureSentinelThenServerReady(
FakeAceTransport transport)
{
transport.Model.MessageDispatched += body =>
{
if (BinaryPrimitives.ReadUInt32LittleEndian(body)
!= CharacterEnterWorld.EnterWorldRequestOpcode)
{
return;
}
transport.Model.EnqueueGameMessage(
BuildCharacterError(CharacterError.Code.NumErrors),
GameMessageGroup.UIQueue);
transport.Model.EnqueueGameMessage(
BitConverter.GetBytes(0xF7DFu),
GameMessageGroup.UIQueue);
};
}
private static byte[] BuildRoster(uint secondsGreyedOut)
{
var writer = new PacketWriter(96);
writer.WriteUInt32(CharacterList.Opcode);
writer.WriteUInt32(0u);
writer.WriteUInt32(1u);
writer.WriteUInt32(0x50000001u);
writer.WriteString16L("Character");
writer.WriteUInt32(secondsGreyedOut);
writer.WriteUInt32(0u);
writer.WriteUInt32(11u);
writer.WriteString16L("Canonical");
writer.WriteUInt32(1u);
writer.WriteUInt32(1u);
return writer.ToArray();
}
private static byte[] BuildServerName(
string worldName,
int currentConnections,
int maxConnections)
{
var writer = new PacketWriter(64);
writer.WriteUInt32(ServerName.Opcode);
writer.WriteUInt32(unchecked((uint)currentConnections));
writer.WriteUInt32(unchecked((uint)maxConnections));
writer.WriteString16L(worldName);
return writer.ToArray();
}
private static byte[] BuildRestoreResponse()
{
var writer = new PacketWriter(64);
writer.WriteUInt32(CharacterRestore.ResponseOpcode);
writer.WriteUInt32(1u);
writer.WriteUInt32(0x50000001u);
writer.WriteString16L("Character");
writer.WriteUInt32(0u);
return writer.ToArray();
}
private static byte[] BuildCharacterError(CharacterError.Code error)
{
byte[] body = new byte[8];
BinaryPrimitives.WriteUInt32LittleEndian(
body,
CharacterError.Opcode);
BinaryPrimitives.WriteUInt32LittleEndian(
body.AsSpan(4),
(uint)error);
return body;
}
private static byte[] BuildPacket(params byte[][] messages)
{
int length = messages.Sum(message =>
MessageFragmentHeader.Size + message.Length);
var fragments = new byte[length];
int position = 0;
uint sequence = 1u;
foreach (byte[] message in messages)
{
position += GameMessageFragment.WriteSingleFragment(
fragments.AsSpan(position),
sequence++,
GameMessageGroup.UIQueue,
message);
}
return PacketCodec.Encode(
new PacketHeader
{
Sequence = 1u,
Flags = PacketHeaderFlags.BlobFragments,
},
fragments,
outboundIsaac: null);
}
private static void InvokeProcessDatagram(
WorldSession session,
byte[] datagram)
{
MethodInfo method = typeof(WorldSession).GetMethod(
"ProcessDatagram",
BindingFlags.NonPublic | BindingFlags.Instance)!;
method.Invoke(
session,
[new ReadOnlyMemory<byte>(datagram), null, true]);
}
}