Add EventDef notices, morning and lesson bells, and info toasts.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Leonid Pershin
2026-08-20 20:46:33 +03:00
co-authored by Cursor
parent ea3f5c7bf1
commit a554738084
38 changed files with 952 additions and 22 deletions
@@ -90,6 +90,37 @@ public class GameSocketTests(AppHostFixture fixture)
Assert.InRange(elapsed.TotalMinutes, 0.5, 2);
}
[Fact]
public async Task OpenSchool_AfterMorning_GetsNotice_AndReopenDoesNotReplayInfo()
{
using var client = await CreateOwnerHttpClientAsync();
await SchoolApiTests.ResetAsync(client);
var beforeMorning = new DateTime(2012, 4, 3, 5, 55, 0, DateTimeKind.Utc);
var school = await SchoolApiTests.CreateAsync(client, "Утро тост", beforeMorning);
using var socket = await OpenSchoolAsync(school.Id, client);
await SendAsync(socket, buffer =>
ProtocolCodec.WriteSetSpeed(buffer, new ClientSetSpeedMessage(SpeedIndex: 4)));
var notice = ProtocolCodec.ReadNotice(
await ReceiveUntilAsync(socket, MessageType.ServerNotice, TimeSpan.FromSeconds(20)));
Assert.Equal("DayStarted", notice.DefName);
Assert.Equal(NoticeSeverity.Info, notice.Severity);
Assert.False(notice.Pause);
Assert.Equal(8000u, notice.TtlMs);
Assert.Equal(0u, notice.PersonId);
await SendAsync(socket, buffer =>
ProtocolCodec.WriteSetRunning(buffer, new ClientSetRunningMessage(Running: false)));
await SendAsync(socket, buffer => ProtocolCodec.WriteCloseSchool(buffer));
await SendAsync(socket, buffer =>
ProtocolCodec.WriteOpenSchool(buffer, new ClientOpenSchoolMessage(school.Id)));
var replayed = await TryReceiveNoticeAsync(socket, TimeSpan.FromSeconds(2));
Assert.Null(replayed);
}
[Fact]
public async Task OpeningASchool_SendsAMapSnapshot()
{
@@ -707,6 +738,45 @@ public class GameSocketTests(AppHostFixture fixture)
}
}
private static async Task<ServerNoticeMessage?> TryReceiveNoticeAsync(WebSocket socket, TimeSpan duration)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
cts.CancelAfter(duration);
var buffer = new byte[64 * 1024];
var chunks = new List<byte>();
while (true)
{
WebSocketReceiveResult result;
try
{
result = await socket.ReceiveAsync(buffer, cts.Token);
}
catch (OperationCanceledException) when (!TestContext.Current.CancellationToken.IsCancellationRequested)
{
return null;
}
if (result.MessageType == WebSocketMessageType.Close)
{
return null;
}
chunks.AddRange(buffer.AsSpan(0, result.Count).ToArray());
if (!result.EndOfMessage)
{
continue;
}
var frame = chunks.ToArray();
chunks.Clear();
if (ProtocolCodec.PeekMessageType(frame) == MessageType.ServerNotice)
{
return ProtocolCodec.ReadNotice(frame);
}
}
}
private sealed record StaffingSnapshot(IReadOnlyList<ApplicantSnapshot> Applicants);
private sealed record ApplicantSnapshot(string Id, string FullName);
@@ -0,0 +1,57 @@
using HSchool.Content;
namespace HSchool.Content.Tests;
public class EventDefTests
{
private readonly CatalogLoader _loader = new();
[Fact]
public void VanillaCore_LoadsDayAndLessonStarted()
{
var catalog = LoadVanilla();
Assert.True(catalog.Events.ContainsKey("DayStarted"));
Assert.Equal(EventSeverities.Info, catalog.Events["DayStarted"].Severity);
Assert.False(catalog.Events["DayStarted"].Pause);
Assert.Equal(8000, catalog.Events["DayStarted"].TtlMs);
Assert.Equal(EventTriggers.DayStart, catalog.Events["DayStarted"].Trigger);
Assert.Equal(EventActions.None, catalog.Events["DayStarted"].Action);
Assert.True(catalog.Events.ContainsKey("LessonStarted"));
Assert.Equal(EventSeverities.Info, catalog.Events["LessonStarted"].Severity);
Assert.False(catalog.Events["LessonStarted"].Pause);
Assert.Equal(8000, catalog.Events["LessonStarted"].TtlMs);
Assert.Equal(EventTriggers.LessonStart, catalog.Events["LessonStarted"].Trigger);
Assert.Equal(EventActions.None, catalog.Events["LessonStarted"].Action);
Assert.True(catalog.Events.ContainsKey("GenerationFailed"));
Assert.Equal(EventTriggers.GenerationFailed, catalog.Events["GenerationFailed"].Trigger);
Assert.Equal("Начало дня", catalog.Label("ru", catalog.Events["DayStarted"]));
Assert.Equal("The day has started", catalog.Label("en", catalog.Events["DayStarted"]));
}
[Fact]
public void UnknownTrigger_FailsTheCatalog()
{
var documents = PackDocuments.FromDirectory(
CatalogLoader.CorePackId,
Path.Combine(AppContext.BaseDirectory, "vanilla"))
.Append(PackDocuments.Def(
CatalogLoader.CorePackId,
"events",
"bad",
"""{ "defName": "BadMoon", "severity": "info", "ttlMs": 1, "trigger": "fullMoon", "action": "none" }"""))
.ToList();
var ex = Assert.Throws<ContentLoadException>(() => _loader.Load([CatalogLoader.CorePackId], documents));
Assert.Contains("trigger", ex.Message, StringComparison.Ordinal);
Assert.Contains("fullMoon", ex.Message, StringComparison.Ordinal);
}
private DefCatalog LoadVanilla()
{
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
return _loader.Load([CatalogLoader.CorePackId], PackDocuments.FromDirectory(CatalogLoader.CorePackId, root));
}
}
@@ -96,6 +96,41 @@ public class ProtocolCodecTests
Assert.Equal(MessageType.ClientSkipEmpty, ProtocolCodec.PeekMessageType(buffer[..length]));
}
[Fact]
public void DismissNotice_RoundTripsAndIsFiveBytes()
{
var message = new ClientDismissNoticeMessage(0x01020304);
Span<byte> buffer = stackalloc byte[ProtocolCodec.MaxFrameSize];
var length = ProtocolCodec.WriteDismissNotice(buffer, message);
Assert.Equal(5, length);
Assert.Equal((byte)MessageType.ClientDismissNotice, buffer[0]);
Assert.Equal(new byte[] { 0x04, 0x03, 0x02, 0x01 }, buffer[1..5].ToArray());
Assert.Equal(message, ProtocolCodec.ReadDismissNotice(buffer[..length]));
}
[Fact]
public void Notice_RoundTripsAndMatchesByteLayout()
{
var message = new ServerNoticeMessage(0x0A0B0C0D, "DayStarted", NoticeSeverity.Info, Pause: false, TtlMs: 8000, PersonId: 0);
var size = ProtocolCodec.NoticeSize(message);
Span<byte> buffer = stackalloc byte[size];
var length = ProtocolCodec.WriteNotice(buffer, message);
Assert.Equal(size, length);
Assert.Equal((byte)MessageType.ServerNotice, buffer[0]);
Assert.Equal(new byte[] { 0x0D, 0x0C, 0x0B, 0x0A }, buffer[1..5].ToArray());
Assert.Equal((ushort)10, System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(buffer[5..7]));
Assert.Equal("DayStarted"u8.ToArray(), buffer[7..17].ToArray());
Assert.Equal(NoticeSeverity.Info, buffer[17]);
Assert.Equal(0, buffer[18]);
Assert.Equal(8000u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(buffer[19..23]));
Assert.Equal(0u, System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(buffer[23..27]));
Assert.Equal(message, ProtocolCodec.ReadNotice(buffer[..length]));
}
[Fact]
public void Welcome_RoundTripsAndIsFourBytes()
{
@@ -0,0 +1,80 @@
using HSchool.Content;
using HSchool.People;
namespace HSchool.Simulation.Tests;
public class WorldEventTests
{
private static readonly DateTime TuesdayNight = new(2012, 4, 3, 5, 59, 0, DateTimeKind.Utc);
private static readonly DateTime TuesdayMorning = new(2012, 4, 3, 6, 0, 0, DateTimeKind.Utc);
private static readonly DateTime BeforeFirstBell = new(2012, 4, 3, 8, 29, 0, DateTimeKind.Utc);
[Fact]
public void CrossingWorkMorning_YieldsOneDayStart_AndARepeatTickDoesNot()
{
using var school = Open(TuesdayNight);
school.Tick(0.2d, 5d);
var first = school.DrainWorldEvents();
Assert.Equal(TuesdayMorning, school.Clock.Time);
Assert.Equal([EventTriggers.DayStart], first.Select(row => row.Trigger));
school.Tick(0.2d, 1d);
Assert.Empty(school.DrainWorldEvents());
}
[Fact]
public void EnteringALessonPeriod_YieldsOneLessonStartForTheSchool()
{
using var school = OpenStaffed(BeforeFirstBell);
Assert.True(school.Roster!.Classes.Count > 1);
school.Tick(0.2d, 5d);
var first = school.DrainWorldEvents();
Assert.Equal(new DateTime(2012, 4, 3, 8, 30, 0, DateTimeKind.Utc), school.Clock.Time);
Assert.Equal([EventTriggers.LessonStart], first.Select(row => row.Trigger));
Assert.Single(first);
school.Tick(0.2d, 5d);
Assert.Empty(school.DrainWorldEvents());
}
private static School Open(DateTime start)
{
var (catalog, map) = Vanilla();
return School.Create(1, "Факты", start, catalog, map);
}
private static School OpenStaffed(DateTime start)
{
var (catalog, map) = Vanilla();
var roster = RosterGenerator.Generate(catalog, map, schoolSeed: 1, "Russia", start);
var pool = ApplicantPool.Create(catalog, roster, schoolSeed: 1, "Russia", start);
var school = School.Create(1, "Звонок", start, catalog, map);
school.InstallPeople(roster, seed: 1, "Russia", pool);
school.ConfigurePresence(weekDays: 5, maxDecisionsPerTick: 10_000);
return school;
}
private static (DefCatalog Catalog, MapLayout Map) Vanilla()
{
var root = Path.Combine(AppContext.BaseDirectory, "vanilla");
var documents = new List<ContentDocument>();
foreach (var path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories))
{
if (!path.EndsWith(".jsonc", StringComparison.OrdinalIgnoreCase)
&& !path.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var relative = Path.GetRelativePath(root, path).Replace('\\', '/');
documents.Add(new ContentDocument(CatalogLoader.CorePackId, relative, File.ReadAllText(path)));
}
var catalog = new CatalogLoader().Load([CatalogLoader.CorePackId], documents);
var map = CatalogLoader.LastDefaultMap([CatalogLoader.CorePackId], documents);
Assert.NotNull(map);
return (catalog, map);
}
}