acdream/tests/AcDream.Headless.Tests/HeadlessCharacterOptionsSeederTests.cs
Erik bcfddc97e7 feat(CT): CT2 — Runtime character-title ownership + wire
Campaign CT slice CT2: the client now learns the character's earned
titles and current display title from the server, owns that state in
Runtime, and can send a display-title change. No UI (CT3/CT4).

Wire (Core.Net):
- GameEvents.ParseCharacterTitleTable (0x0029 CharacterTitle): retail
  CharacterTitleTable::UnPack @0x005c6e90 skips a leading u32 into no
  field — its own Pack @0x005c6e40 always writes the literal 1 there,
  matching ACE's unconditional Writer.Write(1u) — then reads
  displayTitleId, then a count-prefixed PList<uint> of earned ids.
- GameEvents.ParseUpdateTitle (0x002B UpdateTitle): titleId +
  setAsDisplay, per CM_Social::DispatchUI_AddOrSetCharacterTitle
  @0x006a54c0 -> Handle_Social__AddOrSetCharacterTitle @0x00564260,
  which ALWAYS adds (SendNotice_AddCharacterTitle, unconditional) and
  additionally sets display only when setAsDisplay != 0
  (SendNotice_SetDisplayCharacterTitle, gated).
- SocialActions.BuildTitleSet / WorldSession.SendSetTitle: outbound
  TitleSet (0x002C), u32 titleId, matching ACE's GameActionSetTitle.
- GameEventWiring gains onCharacterTitleTable/onUpdateTitle delegate
  holes (Core.Net cannot reference AcDream.Runtime directly).

Runtime:
- New RuntimeCharacterTitleState (RuntimeCharacterState.Titles): earned
  title id set + display title id, TableReplaced/TitleAdded/
  DisplayTitleChanged events matching retail's unconditional-add /
  gated-display-set contract, clears at generation reset.
  RuntimeCharacterOwnershipSnapshot/CaptureOwnership/IsConverged and
  RuntimeCharacterSnapshot extended (trailing optional fields, no
  existing call site broken).
- IRuntimeCharacterCommands.SetTitle: generation-gated, sends
  TitleSet only — NO optimistic local mutation. Verified against
  retail's own CM_Social::Event_SetDisplayCharacterTitle @0x006a5720,
  which sends the wire message and touches no local field; the display
  title updates only from the server's own echo (the CA-campaign
  lesson: never re-add an optimistic write). Implemented on both hosts
  (DirectGameRuntimeCommandAdapter direct-send;
  CurrentGameRuntimeCommandAdapter via LiveCommandBus /
  LiveSessionCommandRouter's new SetTitleRuntimeCmd).
- LiveSessionEventRouter wires the two inbound events unconditionally
  (RuntimeCharacterState.Titles is a required child, not an optional
  sibling like Fellowship/Allegiance).

App (non-UI plumbing + resolver):
- CharacterTitleResolver (src/AcDream.App/UI/Layout/): ports
  CharacterTitleTable::GetCharacterTitleFromID @0x005c6ed0 — titleId ->
  EnumMapper(0x22000041) canonical key -> compute_str_hash ->
  StringTable(0x2300000E) localized text. Runtime stays id-only; CT3/
  CT4 consume this for display. DIDs hardcoded per the RetailKeyNames
  precedent (CT1 verified them end-to-end).

Register: no new row. Retail's send path is non-optimistic and so is
ours — no deviation to record for this slice.

Tests: wire conformance (byte-exact + truncation) in
CharacterTitleEventsTests.cs + SocialActionsTests.cs; Runtime owner
unit tests in RuntimeCharacterTitleStateTests.cs plus integration in
RuntimeCharacterStateTests.cs; a no-local-mutation command test in
DirectGameRuntimeCommandAdapterTests.cs; an InstalledDat pin
(CharacterTitleResolverLiveDatTests.cs, ids 0/1/2/3/5/13/14, run green
with ACDREAM_RUN_INSTALLED_DAT_TESTS=1). Full solution build green;
hermetic filtered suite green (15,380 passed / 0 failed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 22:03:22 +02:00

295 lines
12 KiB
C#

using AcDream.Core.Net.Messages;
using AcDream.Headless.Hosting;
using AcDream.Runtime;
using AcDream.Runtime.Gameplay;
namespace AcDream.Headless.Tests;
/// <summary>
/// Campaign OP slice OP7 (2026-08-11), D8: the declared-vs-actual diff engine
/// (<see cref="HeadlessCharacterOptionsSeeder"/>) unit-tested against a fake
/// <see cref="IRuntimeCharacterCommands"/> so these tests never need a live
/// session, a wire, or a physics/collision fixture — only a bare
/// <see cref="GameRuntime"/> for its <c>CharacterOwner.Options</c> state and
/// <c>Generation</c> token. <see cref="RuntimeCharacterOptionsState.Replace"/>
/// stands in for "a PlayerDescription just landed" exactly like
/// <c>LiveSessionEventRouter</c>'s own <c>onCharacterOptions</c> wiring does.
/// </summary>
public sealed class HeadlessCharacterOptionsSeederTests
{
// AutoRepeatAttack (0x00, Options1 0x00000002) is auto-save — sends
// SetSingleOption (0x0005) immediately, per CharacterOptionTable.
// IgnoreTradeRequests (0x03, Options1 0x00020000) is batched — dirties
// the module; only SaveOptions flushes it. Both are exercised by name
// throughout this file's tests.
private const uint AutoSaveMask = 0x00000002u;
[Fact]
public void DeclaredEqualsActualSendsNothing()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0u, 0u);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.AutoRepeatAttack] = false,
},
runtime,
commands);
seeder.NoteLoginCompleteSent();
seeder.NoteOptionsSeeded();
Assert.Empty(commands.CallOrder);
}
[Fact]
public void AutoSaveDifferenceSendsExactlyOneSetSingleOption()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0u, 0u);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.AutoRepeatAttack] = true,
},
runtime,
commands);
seeder.NoteLoginCompleteSent();
seeder.NoteOptionsSeeded();
var call = Assert.Single(commands.SingleOptionCalls);
Assert.Equal((uint)CharacterOptionId.AutoRepeatAttack, call.OptionId);
Assert.True(call.Value);
Assert.Equal(0, commands.SaveOptionsCallCount);
Assert.Equal(["set:0"], commands.CallOrder);
}
[Fact]
public void BatchedDifferenceSendsSetSingleOptionThenExactlyOneSaveOptionsAtTheEnd()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0u, 0u);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.IgnoreTradeRequests] = true,
},
runtime,
commands);
seeder.NoteLoginCompleteSent();
seeder.NoteOptionsSeeded();
var call = Assert.Single(commands.SingleOptionCalls);
Assert.Equal((uint)CharacterOptionId.IgnoreTradeRequests, call.OptionId);
Assert.True(call.Value);
Assert.Equal(1, commands.SaveOptionsCallCount);
Assert.Equal(["set:3", "save"], commands.CallOrder);
}
[Fact]
public void MixedDeclarationOrdersAllSetsBeforeTheSingleFlush()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0u, 0u);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
// Declared out of id order on purpose — the seeder sorts
// id-ascending internally, so the batched id (0x03) is
// expected AFTER the auto-save id (0x00) regardless of
// declaration order, with the flush always last.
[CharacterOptionId.IgnoreTradeRequests] = true,
[CharacterOptionId.AutoRepeatAttack] = true,
},
runtime,
commands);
seeder.NoteLoginCompleteSent();
seeder.NoteOptionsSeeded();
Assert.Equal(2, commands.SingleOptionCalls.Count);
Assert.Equal(1, commands.SaveOptionsCallCount);
Assert.Equal(["set:0", "set:3", "save"], commands.CallOrder);
}
[Fact]
public void NeitherPreconditionAloneSendsAnything()
{
using GameRuntime runtime = NewRuntime();
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.AutoRepeatAttack] = true,
},
runtime,
commands);
// Login-complete alone: HasServerSeed is still false (no Replace
// ever ran), so the diff cannot trust live state yet.
seeder.NoteLoginCompleteSent();
Assert.Empty(commands.CallOrder);
// Now the seed lands — both preconditions are satisfied and the
// deferred diff runs from THIS call.
runtime.CharacterOwner.Options.Replace(0u, 0u);
seeder.NoteOptionsSeeded();
Assert.Single(commands.SingleOptionCalls);
}
[Fact]
public void OptionsSeededBeforeLoginCompleteDefersUntilLoginCompleteArrives()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0u, 0u);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.AutoRepeatAttack] = true,
},
runtime,
commands);
seeder.NoteOptionsSeeded();
Assert.Empty(commands.CallOrder);
seeder.NoteLoginCompleteSent();
Assert.Single(commands.SingleOptionCalls);
}
[Fact]
public void EmptyDeclarationNeverSendsRegardlessOfBothSignals()
{
using GameRuntime runtime = NewRuntime();
runtime.CharacterOwner.Options.Replace(0xFFFFFFFFu, 0xFFFFFFFFu);
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var seeder = new HeadlessCharacterOptionsSeeder(
new Dictionary<CharacterOptionId, bool>(),
runtime,
commands);
Assert.False(seeder.HasDeclaredOptions);
seeder.NoteLoginCompleteSent();
seeder.NoteOptionsSeeded();
Assert.Empty(commands.CallOrder);
}
/// <summary>
/// D8 idempotence — the acceptance bar is "by construction", not a
/// special-cased dedupe: a fresh, second seeder instance (mirroring the
/// fresh instance <c>HeadlessSessionHost.CreateEventRoute</c> constructs
/// per reconnect) diffs against the SAME declared dictionary but against
/// live state that already reflects what the first seeder sent — the
/// second diff simply finds nothing to do.
/// </summary>
[Fact]
public void ReconnectWithSameDeclarationsAgainstServerThatNowAgreesSendsNothing()
{
using GameRuntime runtime = NewRuntime();
var declared = new Dictionary<CharacterOptionId, bool>
{
[CharacterOptionId.AutoRepeatAttack] = true,
};
// First connect: server has the option OFF; the bot's declared
// value differs, so it sends once.
runtime.CharacterOwner.Options.Replace(0u, 0u);
var firstCommands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var firstSeeder = new HeadlessCharacterOptionsSeeder(
declared, runtime, firstCommands);
firstSeeder.NoteLoginCompleteSent();
firstSeeder.NoteOptionsSeeded();
Assert.Single(firstCommands.SingleOptionCalls);
// Reconnect: a fresh seeder instance (per CreateEventRoute's own
// per-route construction), and the server's fresh PlayerDescription
// now echoes what the bot itself set last time.
runtime.CharacterOwner.Options.ResetSession();
runtime.CharacterOwner.Options.Replace(AutoSaveMask, 0u);
var secondCommands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
var secondSeeder = new HeadlessCharacterOptionsSeeder(
declared, runtime, secondCommands);
secondSeeder.NoteLoginCompleteSent();
secondSeeder.NoteOptionsSeeded();
Assert.Empty(secondCommands.CallOrder);
}
private static GameRuntime NewRuntime()
{
var gameplay = new HeadlessGameplayOperations();
var runtime = new GameRuntime(new GameRuntimeDependencies(
gameplay,
gameplay,
gameplay,
gameplay));
gameplay.Bind(runtime, catalog: null, () => "account");
return runtime;
}
/// <summary>
/// Writes the bit into <paramref name="options"/> as part of
/// <see cref="SetSingleOption"/>, mirroring the REAL
/// <c>DirectGameRuntimeCommandAdapter.SetSingleOption</c> →
/// <c>RuntimeCharacterOptionsState.TrySetOption</c> contract: the local
/// copy updates synchronously, in the same call, before the method
/// returns. Without this, a fake that only records the call (never
/// mutating live state) would make a SECOND diff pass — e.g. a
/// legitimate redundant <c>NoteLoginCompleteSent</c>/<c>NoteOptionsSeeded</c>
/// pairing — re-find the same already-handled mismatch and re-send it,
/// which is a fidelity gap in the fake, not a real defect: production's
/// idempotence depends on exactly this synchronous local write.
/// </summary>
private sealed class FakeCharacterCommands(
RuntimeCharacterOptionsState options) : IRuntimeCharacterCommands
{
internal List<(uint OptionId, bool Value)> SingleOptionCalls { get; } = [];
internal int SaveOptionsCallCount { get; private set; }
internal List<string> CallOrder { get; } = [];
public RuntimeCommandResult Advance(
RuntimeGenerationToken expectedGeneration,
in RuntimeAdvancementCommand command) =>
throw new NotSupportedException(
"HeadlessCharacterOptionsSeeder never calls Advance.");
public RuntimeCommandResult SetSingleOption(
RuntimeGenerationToken expectedGeneration,
uint optionId,
bool value)
{
SingleOptionCalls.Add((optionId, value));
CallOrder.Add($"set:{optionId}");
options.SetOptionBit(optionId, value);
return new RuntimeCommandResult(
RuntimeCommandStatus.Accepted,
expectedGeneration);
}
public RuntimeCommandResult SaveOptions(
RuntimeGenerationToken expectedGeneration)
{
SaveOptionsCallCount++;
CallOrder.Add("save");
return new RuntimeCommandResult(
RuntimeCommandStatus.Accepted,
expectedGeneration);
}
public RuntimeCommandResult SetTitle(
RuntimeGenerationToken expectedGeneration,
uint titleId) =>
throw new NotSupportedException(
"HeadlessCharacterOptionsSeeder never calls SetTitle.");
}
}