From e9c2488ddc0ed05665203f30fdf65686e4320c72 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:53:40 -0500 Subject: [PATCH 01/28] feat: read Mirror's wire format and ids for the live game feed --- .../LiveFeed/MirrorHashTests.cs | 21 +++ .../LiveFeed/MirrorWriter.cs | 116 +++++++++++++ .../LiveFeed/MirrorHash.cs | 29 ++++ .../LiveFeed/MirrorReader.cs | 157 ++++++++++++++++++ 4 files changed, 323 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs create mode 100644 src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorWriter.cs create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/MirrorHash.cs create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/MirrorReader.cs diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs new file mode 100644 index 0000000..db63ac1 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs @@ -0,0 +1,21 @@ +using FourFoldAccountManager.Core.LiveFeed; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.LiveFeed; + +public sealed class MirrorHashTests +{ + // The ints the decompiled game passes to SendTargetRPCInternal. If a signature string or the hash drifts, the feed + // would silently never match these calls; after a game update, refresh both from the new decompile. + [Theory] + [InlineData("System.Void BattlePlayerCommands2::TargetOpenHUD(Mirror.NetworkConnectionToClient,System.UInt32[],System.Boolean)", 524349864)] + [InlineData("System.Void BattlePlayerCommands2::TargetCloseHUD(Mirror.NetworkConnectionToClient,System.Boolean)", -274237404)] + [InlineData("System.Void BattlePlayerCommands2::TargetShowBattleResult(Mirror.NetworkConnectionToClient,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.String,System.String,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)", -2013908526)] + [InlineData("System.Void BattlePlayerCommands2::TargetSkillResult(Mirror.NetworkConnectionToClient,System.Boolean,System.String)", 884216395)] + [InlineData("System.Void SimpleScenePlayer::TargetLoadScene(Mirror.NetworkConnectionToClient,System.String,System.String,UnityEngine.Vector2,System.Int32,System.Boolean)", 565832018)] + public void SignaturesHashToTheGamesOwnValues(string signature, int decompiledHash) + { + Assert.Equal(decompiledHash, MirrorHash.StableHash(signature)); + Assert.Equal((ushort)(decompiledHash & 0xFFFF), MirrorHash.FunctionHash(signature)); + } +} diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorWriter.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorWriter.cs new file mode 100644 index 0000000..57e79b1 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorWriter.cs @@ -0,0 +1,116 @@ +using System.Buffers.Binary; +using System.Text; +using FourFoldAccountManager.Core.LiveFeed; + +namespace FourFoldAccountManager.Core.Tests.LiveFeed; + +// Builds Mirror frames the way the game's server writes them, so tests never need captured traffic. +internal sealed class MirrorWriter +{ + private readonly List _bytes = []; + + public byte[] ToArray() => [.. _bytes]; + + public MirrorWriter Byte(byte value) + { + _bytes.Add(value); + return this; + } + + public MirrorWriter Bytes(ReadOnlySpan value) + { + foreach (var b in value) + { + _bytes.Add(b); + } + + return this; + } + + public MirrorWriter UShort(ushort value) => Byte((byte)value).Byte((byte)(value >> 8)); + + public MirrorWriter Bool(bool value) => Byte(value ? (byte)1 : (byte)0); + + public MirrorWriter Double(double value) + { + Span buffer = stackalloc byte[8]; + BinaryPrimitives.WriteDoubleLittleEndian(buffer, value); + return Bytes(buffer); + } + + public MirrorWriter Float(float value) + { + Span buffer = stackalloc byte[4]; + BinaryPrimitives.WriteSingleLittleEndian(buffer, value); + return Bytes(buffer); + } + + // Mirror's Compression.CompressVarUInt. + public MirrorWriter VarUInt(ulong value) + { + if (value <= 240) + { + return Byte((byte)value); + } + + if (value <= 2287) + { + return Byte((byte)(((value - 240) >> 8) + 241)).Byte((byte)((value - 240) & 0xFF)); + } + + if (value <= 67823) + { + return Byte(249).Byte((byte)((value - 2288) >> 8)).Byte((byte)((value - 2288) & 0xFF)); + } + + var count = value <= 0xFFFFFF ? 3 : value <= 0xFFFFFFFF ? 4 : 8; + Byte((byte)(247 + count)); + for (var i = 0; i < count; i++) + { + Byte((byte)(value >> (8 * i))); + } + + return this; + } + + // Mirror's zigzag varint (WriteVarInt / WriteVarLong). + public MirrorWriter VarInt(long value) => VarUInt((ulong)((value << 1) ^ (value >> 63))); + + public MirrorWriter String(string? value) + { + if (value is null) + { + return UShort(0); + } + + var bytes = Encoding.UTF8.GetBytes(value); + return UShort((ushort)(bytes.Length + 1)).Bytes(bytes); + } + + // One WebSocket frame: the batch timestamp, then each message behind its varuint length. + public static byte[] Batch(params byte[][] messages) + { + var writer = new MirrorWriter().Double(1234.5); + foreach (var message in messages) + { + writer.VarUInt((ulong)message.Length).Bytes(message); + } + + return writer.ToArray(); + } + + // A TargetRpc as Mirror sends it: RpcMessage id, netId, component index, function hash, payload with size + 1. + public static byte[] Rpc(string signature, byte[] payload) => + new MirrorWriter() + .UShort(MirrorHash.MessageId("Mirror.RpcMessage")) + .VarUInt(42) + .Byte(0) + .UShort(MirrorHash.FunctionHash(signature)) + .VarUInt((ulong)payload.Length + 1) + .Bytes(payload) + .ToArray(); + + // A NetworkMessage struct: its id, then its fields. + public static byte[] Message(string typeFullName, byte[] payload) => + new MirrorWriter().UShort(MirrorHash.MessageId(typeFullName)).Bytes(payload).ToArray(); +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/MirrorHash.cs b/src/FourFoldAccountManager.Core/LiveFeed/MirrorHash.cs new file mode 100644 index 0000000..25475fe --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/MirrorHash.cs @@ -0,0 +1,29 @@ +namespace FourFoldAccountManager.Core.LiveFeed; + +// Mirror's ids, computed the way Mirror computes them, so the allowlist is written as readable names and signatures +// instead of magic numbers. +public static class MirrorHash +{ + // Mirror's Extensions.GetStableHashCode: FNV-1a over the low byte of each char. + public static int StableHash(string text) + { + var hash = 2166136261u; + foreach (var ch in text) + { + hash ^= (byte)ch; + hash *= 16777619u; + } + + return (int)hash; + } + + // NetworkMessageId.Id: GetStableHashCode16 of the message type's full name. + public static ushort MessageId(string typeFullName) + { + var hash = StableHash(typeFullName); + return (ushort)((hash >> 16) ^ hash); + } + + // RemoteProcedureCalls.RegisterDelegate: the low 16 bits of the full signature's hash. Not the same fold as MessageId. + public static ushort FunctionHash(string signature) => (ushort)(StableHash(signature) & 0xFFFF); +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/MirrorReader.cs b/src/FourFoldAccountManager.Core/LiveFeed/MirrorReader.cs new file mode 100644 index 0000000..75ba911 --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/MirrorReader.cs @@ -0,0 +1,157 @@ +using System.Buffers.Binary; +using System.Text; + +namespace FourFoldAccountManager.Core.LiveFeed; + +// The game's traffic is untrusted input: a short or malformed buffer throws this, and the decoder turns it into a +// dropped message. Its message never contains frame contents. +internal sealed class MirrorFormatException : Exception +{ + public MirrorFormatException() : base("The data doesn't match Mirror's format.") + { + } +} + +// Reads Mirror's wire primitives (NetworkReader, Compression). Every read is bounds-checked. +internal ref struct MirrorReader +{ + private readonly ReadOnlySpan _buffer; + private int _position; + + public MirrorReader(ReadOnlySpan buffer) + { + _buffer = buffer; + _position = 0; + } + + public readonly int Remaining => _buffer.Length - _position; + + public byte ReadByte() + { + Need(1); + return _buffer[_position++]; + } + + public ReadOnlySpan ReadBytes(int count) + { + if (count < 0) + { + throw new MirrorFormatException(); + } + + Need(count); + var slice = _buffer.Slice(_position, count); + _position += count; + return slice; + } + + public ushort ReadUShort() => BinaryPrimitives.ReadUInt16LittleEndian(ReadBytes(2)); + + public double ReadDouble() => BinaryPrimitives.ReadDoubleLittleEndian(ReadBytes(8)); + + public bool ReadBool() => ReadByte() != 0; + + // Compression.DecompressVarUInt. + public ulong ReadVarUInt() + { + var b0 = ReadByte(); + if (b0 < 241) + { + return b0; + } + + var b1 = ReadByte(); + if (b0 <= 248) + { + return 240 + ((ulong)(b0 - 241) << 8) + b1; + } + + var b2 = ReadByte(); + if (b0 == 249) + { + return 2288 + ((ulong)b1 << 8) + b2; + } + + // 250..255: the value follows little-endian in (b0 - 247) bytes, two of which are already read. + var value = b1 | ((ulong)b2 << 8); + for (var i = 2; i < b0 - 247; i++) + { + value |= (ulong)ReadByte() << (8 * i); + } + + return value; + } + + // Compression.DecompressVarInt: zigzag over the varuint. + public long ReadVarInt() + { + var value = ReadVarUInt(); + return (long)(value >> 1) ^ -(long)(value & 1); + } + + public int ReadVarInt32() + { + var value = ReadVarInt(); + return value is >= int.MinValue and <= int.MaxValue ? (int)value : throw new MirrorFormatException(); + } + + // NetworkReader.ReadString: ushort (byte length + 1), 0 meaning null, then UTF-8. + public string? ReadString(int maxBytes) + { + var length = StringLength(maxBytes); + return length < 0 ? null : Encoding.UTF8.GetString(ReadBytes(length)); + } + + // For fields the feed must never keep (a username, an error): checks the length without decoding the text. + public void SkipString(int maxBytes) + { + var length = StringLength(maxBytes); + if (length > 0) + { + ReadBytes(length); + } + } + + // WriteArray: varuint (count + 1), 0 meaning null. Returns -1 for null. + public int ReadArrayCount(int maxCount) + { + var value = ReadVarUInt(); + if (value == 0) + { + return -1; + } + + return value - 1 <= (ulong)maxCount ? (int)(value - 1) : throw new MirrorFormatException(); + } + + // ReadArraySegmentAndSize: varuint (size + 1), 0 meaning empty, then the bytes. + public ReadOnlySpan ReadSegmentAndSize() + { + var value = ReadVarUInt(); + if (value == 0) + { + return default; + } + + return value - 1 <= int.MaxValue ? ReadBytes((int)(value - 1)) : throw new MirrorFormatException(); + } + + private int StringLength(int maxBytes) + { + var prefix = ReadUShort(); + if (prefix == 0) + { + return -1; + } + + return prefix - 1 <= maxBytes ? prefix - 1 : throw new MirrorFormatException(); + } + + private readonly void Need(int count) + { + if (count > Remaining) + { + throw new MirrorFormatException(); + } + } +} From 528c912cc18b995a966e5de51a9f31ab2418835a Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 13:57:29 -0500 Subject: [PATCH 02/28] feat: decode the live game feed's allowlisted messages strictly --- .../LiveFeed/GameMessageDecoderTests.cs | 100 ++++++ .../LiveFeed/GameEvents.cs | 47 +++ .../LiveFeed/GameMessageDecoder.cs | 284 ++++++++++++++++++ 3 files changed, 431 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs new file mode 100644 index 0000000..5d1e38b --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs @@ -0,0 +1,100 @@ +using FourFoldAccountManager.Core.LiveFeed; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.LiveFeed; + +public sealed class GameMessageDecoderTests +{ + private static byte[] BattleResultPayload() => + new MirrorWriter() + .Bool(true) // leveledUp + .VarInt(37) // silverGained + .VarInt(1250) // expGained + .VarInt(380) // expNeededToNextLevel + .VarInt(12) // reachedLevel + .String("Savage") // className + .String("Whirlwind") // unlockedSkillName + .VarInt(4) // gainedMaxSP + .VarInt(2) // gainedSKL + .VarInt(56) // gainedMaxHP + .VarInt(3) // gainedATT + .VarInt(1) // gainedMAG + .VarInt(2) // gainedSPD + .VarInt(1) // gainedDEF + .VarInt(0) // gainedRES + .VarInt(1) // gainedLCK + .VarInt(120) // gainedHP + .VarInt(9) // gainedSP + .ToArray(); + + // Wrong XP or silver numbers would reach every tracker plugin. + [Fact] + public void ABattleResultDecodesToItsExactValues() + { + var frame = MirrorWriter.Batch( + MirrorWriter.Rpc(GameMessageDecoder.BattleResultSignature, BattleResultPayload())); + + var result = GameMessageDecoder.DecodeBatch(frame); + + Assert.Equal( + new BattleResult(true, 37, 1250, 380, 12, "Savage", "Whirlwind", + new StatGains(MaxHp: 56, MaxSp: 4, Hp: 120, Sp: 9, Att: 3, Mag: 1, Skl: 2, Spd: 2, Def: 1, Res: 0, Lck: 1)), + Assert.Single(result.Events)); + Assert.Equal(0, result.Failures); + } + + // A payload that doesn't end exactly where the signature says it should is a different message wearing an + // allowlisted id (a 16-bit collision after a game update), so it must never become an event. + [Theory] + [InlineData(-1)] + [InlineData(1)] + public void APayloadOfTheWrongLengthIsAFailureNotAnEvent(int lengthChange) + { + var payload = BattleResultPayload(); + var altered = lengthChange < 0 ? payload[..^1] : [.. payload, 0x00]; + var frame = MirrorWriter.Batch(MirrorWriter.Rpc(GameMessageDecoder.BattleResultSignature, altered)); + + var result = GameMessageDecoder.DecodeBatch(frame); + + Assert.Empty(result.Events); + Assert.Equal(1, result.Failures); + } + + // Chat, friends and every other message stay unread: nothing about other players reaches the feed. + [Fact] + public void MessagesOutsideTheAllowlistProduceNothing() + { + var chat = MirrorWriter.Message("Game.Chat.SceneChatMessage", new MirrorWriter() + .String("shikaakwa_b3").String("").String("scene").String("SomeoneElse").String("hello") + .Bool(false).Bool(false).Bool(false).ToArray()); + var unknownRpc = MirrorWriter.Rpc( + "System.Void PlayerSpeech::RpcSay(System.String)", new MirrorWriter().String("hi").ToArray()); + + var result = GameMessageDecoder.DecodeBatch(MirrorWriter.Batch(chat, unknownRpc)); + + Assert.Empty(result.Events); + Assert.Equal(0, result.Failures); + } + + // The game server's traffic is untrusted input; nothing in it may crash or hang the app. + [Fact] + public void GarbageNeverThrows() + { + var random = new Random(20261006); + string[] signatures = + [ + GameMessageDecoder.OpenHudSignature, GameMessageDecoder.CloseHudSignature, + GameMessageDecoder.BattleResultSignature, GameMessageDecoder.SkillResultSignature, + GameMessageDecoder.LoadSceneSignature + ]; + for (var i = 0; i < 2000; i++) + { + var noise = new byte[random.Next(0, 300)]; + random.NextBytes(noise); + GameMessageDecoder.DecodeBatch(noise); + GameMessageDecoder.DecodeBatch(MirrorWriter.Batch(MirrorWriter.Rpc(signatures[i % signatures.Length], noise))); + GameMessageDecoder.DecodeBatch(MirrorWriter.Batch( + MirrorWriter.Message(GameMessageDecoder.AuthResponseType, noise))); + } + } +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs new file mode 100644 index 0000000..1b701e2 --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs @@ -0,0 +1,47 @@ +namespace FourFoldAccountManager.Core.LiveFeed; + +// What the decoder makes of the allowlisted messages. Only the fields the feed keeps are here; the rest are read to +// check the length and dropped. +public abstract record GameEvent; + +public sealed record BattleStarted(int EnemyCount) : GameEvent; + +public sealed record BattleEnded(bool Victory) : GameEvent; + +public sealed record StatGains(int MaxHp, int MaxSp, int Hp, int Sp, int Att, int Mag, int Skl, int Spd, int Def, int Res, int Lck); + +public sealed record BattleResult( + bool LeveledUp, + int SilverGained, + int ExpGained, + int ExpNeededToNextLevel, + int ReachedLevel, + string ClassName, + string? UnlockedSkillName, + StatGains Gains) : GameEvent; + +public enum SkillOutcome +{ + Hit, + Miss, + Rejected +} + +public sealed record SkillResult(string? SkillName, SkillOutcome Outcome, int TargetsAffected, string? Reason) : GameEvent; + +public sealed record SceneLoaded(string Scene) : GameEvent; + +// Failed logins are recognized too: they still prove the message id matches, which the canary needs. +public sealed record LoggedIn(bool Success) : GameEvent; + +public sealed record ModerationDisconnected(string? Reason) : GameEvent; + +// Failures: allowlisted messages that failed strict parsing; they mean the protocol no longer matches. Malformed: +// framing that couldn't be read at all; counted, but not taken as proof of a mismatch. +public sealed record BatchResult(IReadOnlyList Events, int Failures, int Malformed); + +public static class LiveFeedRules +{ + // The game's own rule (ClickToMove.IsBattleSceneName): battle instances are named with "battle". + public static bool IsBattleScene(string scene) => scene.Trim().Contains("battle", StringComparison.OrdinalIgnoreCase); +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs new file mode 100644 index 0000000..9506f09 --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs @@ -0,0 +1,284 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace FourFoldAccountManager.Core.LiveFeed; + +// Turns one WebSocket frame (a Mirror batch) into the allowlisted events. Anything not on the allowlist is skipped +// without reading past its id (an RPC: past its function hash). Allowlisted messages are parsed strictly: every field +// in order, the payload consumed exactly, values in range. One that fails is a Failure, never an event. +public static partial class GameMessageDecoder +{ + // Exact signatures and type names from the decompiled game. Mirror hashes these strings, so they must match + // character for character. After a game update, see the spec's "After a game update" procedure. + public const string OpenHudSignature = + "System.Void BattlePlayerCommands2::TargetOpenHUD(Mirror.NetworkConnectionToClient,System.UInt32[],System.Boolean)"; + + public const string CloseHudSignature = + "System.Void BattlePlayerCommands2::TargetCloseHUD(Mirror.NetworkConnectionToClient,System.Boolean)"; + + public const string BattleResultSignature = + "System.Void BattlePlayerCommands2::TargetShowBattleResult(Mirror.NetworkConnectionToClient,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.String,System.String,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)"; + + public const string SkillResultSignature = + "System.Void BattlePlayerCommands2::TargetSkillResult(Mirror.NetworkConnectionToClient,System.Boolean,System.String)"; + + public const string LoadSceneSignature = + "System.Void SimpleScenePlayer::TargetLoadScene(Mirror.NetworkConnectionToClient,System.String,System.String,UnityEngine.Vector2,System.Int32,System.Boolean)"; + + public const string RpcMessageType = "Mirror.RpcMessage"; + public const string AuthResponseType = "Game.Auth.AuthResponseMessage"; + public const string ModerationDisconnectType = "Game.Auth.ModerationDisconnectMessage"; + + private const int MaxKeptText = 256; + private const int MaxSkippedText = 4096; + private const int MaxEnemies = 16; + private const string MissedSuffix = " missed."; + + private static readonly ushort RpcMessageId = MirrorHash.MessageId(RpcMessageType); + private static readonly ushort AuthResponseId = MirrorHash.MessageId(AuthResponseType); + private static readonly ushort ModerationDisconnectId = MirrorHash.MessageId(ModerationDisconnectType); + private static readonly ushort OpenHud = MirrorHash.FunctionHash(OpenHudSignature); + private static readonly ushort CloseHud = MirrorHash.FunctionHash(CloseHudSignature); + private static readonly ushort BattleResultHash = MirrorHash.FunctionHash(BattleResultSignature); + private static readonly ushort SkillResultHash = MirrorHash.FunctionHash(SkillResultSignature); + private static readonly ushort LoadScene = MirrorHash.FunctionHash(LoadSceneSignature); + + private enum Outcome + { + Ignored, + Recognized, + Failed, + Malformed + } + + public static BatchResult DecodeBatch(ReadOnlySpan batch) + { + var events = new List(); + var failures = 0; + var malformed = 0; + var reader = new MirrorReader(batch); + try + { + // The batch timestamp. Events use the frame's arrival time, the app's clock, instead. + reader.ReadDouble(); + while (reader.Remaining > 0) + { + var length = reader.ReadVarUInt(); + if (length > (ulong)reader.Remaining) + { + throw new MirrorFormatException(); + } + + switch (DecodeMessage(reader.ReadBytes((int)length), out var gameEvent)) + { + case Outcome.Recognized: + events.Add(gameEvent!); + break; + case Outcome.Failed: + failures++; + break; + case Outcome.Malformed: + malformed++; + break; + } + } + } + catch (MirrorFormatException) + { + malformed++; + } + + return new BatchResult(events, failures, malformed); + } + + private static Outcome DecodeMessage(ReadOnlySpan message, out GameEvent? gameEvent) + { + gameEvent = null; + var reader = new MirrorReader(message); + ushort id; + ushort hash = 0; + try + { + id = reader.ReadUShort(); + if (id == RpcMessageId) + { + reader.ReadVarUInt(); // netId of the object the call is on + reader.ReadByte(); // component index + hash = reader.ReadUShort(); + if (hash != OpenHud && hash != CloseHud && hash != BattleResultHash && hash != SkillResultHash && + hash != LoadScene) + { + return Outcome.Ignored; + } + } + else if (id != AuthResponseId && id != ModerationDisconnectId) + { + return Outcome.Ignored; + } + } + catch (MirrorFormatException) + { + return Outcome.Malformed; + } + + try + { + if (id == RpcMessageId) + { + var payload = reader.ReadSegmentAndSize(); + End(ref reader); + gameEvent = ParseRpc(hash, payload); + } + else + { + gameEvent = id == AuthResponseId ? ParseAuthResponse(ref reader) : ParseModerationDisconnect(ref reader); + End(ref reader); + } + + return Outcome.Recognized; + } + catch (MirrorFormatException) + { + return Outcome.Failed; + } + } + + private static GameEvent ParseRpc(ushort hash, ReadOnlySpan payload) + { + var reader = new MirrorReader(payload); + GameEvent result; + if (hash == OpenHud) + { + result = ParseOpenHud(ref reader); + } + else if (hash == CloseHud) + { + result = new BattleEnded(reader.ReadBool()); + } + else if (hash == BattleResultHash) + { + result = ParseBattleResult(ref reader); + } + else if (hash == SkillResultHash) + { + result = ParseSkillResult(ref reader); + } + else + { + result = ParseLoadScene(ref reader); + } + + End(ref reader); + return result; + } + + private static BattleStarted ParseOpenHud(ref MirrorReader reader) + { + var count = reader.ReadArrayCount(MaxEnemies); + for (var i = 0; i < count; i++) + { + reader.ReadVarUInt(); // an enemy's netId: read to check the length, not kept + } + + reader.ReadBool(); // moveActionMenuUp, not kept + return new BattleStarted(Math.Max(count, 0)); + } + + private static BattleResult ParseBattleResult(ref MirrorReader reader) + { + // Wire order from BattlePlayerCommands2.TargetShowBattleResult. + var leveledUp = reader.ReadBool(); + var silver = AtLeastZero(reader.ReadVarInt32()); + var exp = AtLeastZero(reader.ReadVarInt32()); + var needed = AtLeastZero(reader.ReadVarInt32()); + var level = reader.ReadVarInt32(); + if (level is < 1 or > 999) + { + throw new MirrorFormatException(); + } + + var className = reader.ReadString(MaxKeptText) ?? string.Empty; + var unlocked = reader.ReadString(MaxKeptText); + var maxSp = AtLeastZero(reader.ReadVarInt32()); + var skl = AtLeastZero(reader.ReadVarInt32()); + var maxHp = AtLeastZero(reader.ReadVarInt32()); + var att = AtLeastZero(reader.ReadVarInt32()); + var mag = AtLeastZero(reader.ReadVarInt32()); + var spd = AtLeastZero(reader.ReadVarInt32()); + var def = AtLeastZero(reader.ReadVarInt32()); + var res = AtLeastZero(reader.ReadVarInt32()); + var lck = AtLeastZero(reader.ReadVarInt32()); + var hp = AtLeastZero(reader.ReadVarInt32()); + var sp = AtLeastZero(reader.ReadVarInt32()); + return new BattleResult(leveledUp, silver, exp, needed, level, className, + string.IsNullOrEmpty(unlocked) ? null : unlocked, + new StatGains(maxHp, maxSp, hp, sp, att, mag, skl, spd, def, res, lck)); + } + + // The texts come from SkillCombatService.BuildResultMessage and the rejections in BattlePlayerCommands2. + private static SkillResult ParseSkillResult(ref MirrorReader reader) + { + var ok = reader.ReadBool(); + var text = reader.ReadString(MaxKeptText) ?? string.Empty; + if (!ok) + { + return new SkillResult(null, SkillOutcome.Rejected, 0, text.Length == 0 ? null : text); + } + + if (text.Length > MissedSuffix.Length && text.EndsWith(MissedSuffix, StringComparison.Ordinal)) + { + return new SkillResult(text[..^MissedSuffix.Length], SkillOutcome.Miss, 0, null); + } + + var match = AffectedText().Match(text); + if (!match.Success) + { + throw new MirrorFormatException(); + } + + return new SkillResult(match.Groups["name"].Value, SkillOutcome.Hit, + int.Parse(match.Groups["count"].Value, CultureInfo.InvariantCulture), null); + } + + private static SceneLoaded ParseLoadScene(ref MirrorReader reader) + { + var scene = reader.ReadString(MaxKeptText); + if (string.IsNullOrWhiteSpace(scene)) + { + throw new MirrorFormatException(); + } + + reader.SkipString(MaxSkippedText); // spawnId + reader.ReadBytes(8); // serverOffset (Vector2): instance coordinates, not kept + reader.ReadVarInt32(); // transitionSerial + reader.ReadBool(); // useWorldPortalFade + return new SceneLoaded(scene); + } + + private static LoggedIn ParseAuthResponse(ref MirrorReader reader) + { + var success = reader.ReadBool(); + reader.ReadVarInt(); // accountId: the game's database id, never kept + reader.SkipString(MaxSkippedText); // username, never kept + reader.ReadBool(); // isAdmin, never kept + reader.SkipString(MaxSkippedText); // error text + return new LoggedIn(success); + } + + private static ModerationDisconnected ParseModerationDisconnect(ref MirrorReader reader) => + new(reader.ReadString(MaxSkippedText)); + + private static void End(ref MirrorReader reader) + { + if (reader.Remaining != 0) + { + throw new MirrorFormatException(); + } + } + + private static int AtLeastZero(int value) => value >= 0 ? value : throw new MirrorFormatException(); + + [GeneratedRegex(@"^(?.+) affected (?\d{1,3}) targets?\.( \d{1,3} targets? resisted\.)?$", + RegexOptions.CultureInvariant)] + private static partial Regex AffectedText(); +} From 6670b4c9e75adb2ef6f13687a074dcb6d5fa8d45 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 14:00:56 -0500 Subject: [PATCH 03/28] fix: keep the live feed's skill-text parsing and kill reason within the spec's limits --- .../LiveFeed/GameMessageDecoderTests.cs | 13 +++++++++++++ .../LiveFeed/GameMessageDecoder.cs | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs index 5d1e38b..1093992 100644 --- a/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/GameMessageDecoderTests.cs @@ -97,4 +97,17 @@ public void GarbageNeverThrows() MirrorWriter.Message(GameMessageDecoder.AuthResponseType, noise))); } } + + // A digit from another script must not slip past the skill-text pattern into int.Parse and crash the feed. + [Fact] + public void ANonAsciiDigitInSkillTextIsAFailureNotACrash() + { + var payload = new MirrorWriter().Bool(true).String("Fireball affected ٣ targets.").ToArray(); + + var result = GameMessageDecoder.DecodeBatch( + MirrorWriter.Batch(MirrorWriter.Rpc(GameMessageDecoder.SkillResultSignature, payload))); + + Assert.Empty(result.Events); + Assert.Equal(1, result.Failures); + } } diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs index 9506f09..9362d20 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs @@ -266,7 +266,7 @@ private static LoggedIn ParseAuthResponse(ref MirrorReader reader) } private static ModerationDisconnected ParseModerationDisconnect(ref MirrorReader reader) => - new(reader.ReadString(MaxSkippedText)); + new(reader.ReadString(MaxKeptText)); private static void End(ref MirrorReader reader) { @@ -278,7 +278,7 @@ private static void End(ref MirrorReader reader) private static int AtLeastZero(int value) => value >= 0 ? value : throw new MirrorFormatException(); - [GeneratedRegex(@"^(?.+) affected (?\d{1,3}) targets?\.( \d{1,3} targets? resisted\.)?$", + [GeneratedRegex(@"^(?.+) affected (?[0-9]{1,3}) targets?\.( [0-9]{1,3} targets? resisted\.)?\z", RegexOptions.CultureInvariant)] private static partial Regex AffectedText(); } From b32ba82dbd1c44f4446bf69a990e989859b9f7aa Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:28:09 -0500 Subject: [PATCH 04/28] feat: define what plugins may receive from the live game feed --- .../LiveFeed/LiveFeedPrivacyTests.cs | 30 ++++++++ .../LiveFeed/LiveFeedPayloads.cs | 71 +++++++++++++++++++ .../Plugins/PluginText.cs | 14 ++++ .../MainWindow.CommunityPlugins.cs | 15 +--- 4 files changed, 117 insertions(+), 13 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/LiveFeed/LiveFeedPrivacyTests.cs create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/LiveFeedPrivacyTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/LiveFeedPrivacyTests.cs new file mode 100644 index 0000000..37cc734 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/LiveFeedPrivacyTests.cs @@ -0,0 +1,30 @@ +using System.Text.Json; +using FourFoldAccountManager.Core.LiveFeed; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.LiveFeed; + +public sealed class LiveFeedPrivacyTests +{ + private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web); + + // The login message carries the game's account id, the username and the admin flag. A plugin must only ever learn + // that one of the user's own accounts logged in, and a failed login must not read as a login. + [Fact] + public void TheLoginEventCarriesNothingButTheAccountAndTheTime() + { + var accountId = Guid.NewGuid(); + var frame = MirrorWriter.Batch(MirrorWriter.Message(GameMessageDecoder.AuthResponseType, new MirrorWriter() + .Bool(true).VarInt(987654).String("SecretLogin").Bool(true).String("").ToArray())); + + var gameEvent = Assert.Single(GameMessageDecoder.DecodeBatch(frame).Events); + var post = LiveFeedPayloads.ForPlugins(accountId, gameEvent, DateTimeOffset.UnixEpoch); + + Assert.NotNull(post); + Assert.Equal("session.loggedIn", post.Value.Name); + var json = JsonSerializer.SerializeToElement(post.Value.Data, post.Value.Data.GetType(), Json); + Assert.Equal(new[] { "accountId", "at" }, json.EnumerateObject().Select(property => property.Name).ToArray()); + Assert.DoesNotContain("SecretLogin", json.GetRawText()); + Assert.Null(LiveFeedPayloads.ForPlugins(accountId, new LoggedIn(false), DateTimeOffset.UnixEpoch)); + } +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs b/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs new file mode 100644 index 0000000..5ecc9d6 --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs @@ -0,0 +1,71 @@ +using FourFoldAccountManager.Core.Plugins; + +namespace FourFoldAccountManager.Core.LiveFeed; + +// Exactly what plugins receive from the live feed, as in the spec's Plugin API table. This is the privacy boundary: +// a field that isn't in one of these records can't reach a plugin. Every string passes PublicGameText. +public sealed record LiveBattleStarted(Guid AccountId, int EnemyCount, DateTimeOffset At); + +public sealed record LiveBattleEnded(Guid AccountId, bool Victory, DateTimeOffset At); + +public sealed record LiveBattleResult( + Guid AccountId, + int ExpGained, + int SilverGained, + int ExpNeededToNextLevel, + bool LeveledUp, + int ReachedLevel, + string? ClassName, + string? UnlockedSkillName, + StatGains StatGains, + DateTimeOffset At); + +public sealed record LiveSkillResult( + Guid AccountId, + string? SkillName, + string Outcome, + int TargetsAffected, + string? Reason, + DateTimeOffset At); + +public sealed record LiveLocation(Guid AccountId, string? Scene, bool InBattle, DateTimeOffset At); + +public sealed record LiveSession(Guid AccountId, DateTimeOffset At); + +public sealed record LiveDisconnect(Guid AccountId, string? Reason, DateTimeOffset At); + +public sealed record LiveStatus(string State, string? Reason); + +public static class LiveFeedPayloads +{ + // The plugin event for a decoded game event, or null when the event isn't passed to plugins. + public static (string Name, object Data)? ForPlugins(Guid accountId, GameEvent gameEvent, DateTimeOffset at) => + gameEvent switch + { + BattleStarted e => ("battle.started", new LiveBattleStarted(accountId, e.EnemyCount, at)), + BattleEnded e => ("battle.ended", new LiveBattleEnded(accountId, e.Victory, at)), + BattleResult e => ("battle.result", new LiveBattleResult(accountId, e.ExpGained, e.SilverGained, + e.ExpNeededToNextLevel, e.LeveledUp, e.ReachedLevel, PluginText.PublicGameText(e.ClassName), + PluginText.PublicGameText(e.UnlockedSkillName), e.Gains, at)), + SkillResult e => ("battle.skillResult", new LiveSkillResult(accountId, + PluginText.PublicGameText(e.SkillName), + e.Outcome switch + { + SkillOutcome.Hit => "hit", + SkillOutcome.Miss => "miss", + _ => "rejected" + }, + e.TargetsAffected, PluginText.PublicGameText(e.Reason), at)), + SceneLoaded e => ("location.changed", Location(accountId, e.Scene, at)), + LoggedIn { Success: true } => ("session.loggedIn", new LiveSession(accountId, at)), + ModerationDisconnected e => ("session.disconnected", + new LiveDisconnect(accountId, PluginText.PublicGameText(e.Reason), at)), + _ => null + }; + + public static LiveLocation Location(Guid accountId, string scene, DateTimeOffset at) => + new(accountId, PluginText.PublicGameText(scene), LiveFeedRules.IsBattleScene(scene), at); + + // The game socket closed without a reason from the server: a dropped connection, a reload, a closed panel. + public static LiveDisconnect Disconnected(Guid accountId, DateTimeOffset at) => new(accountId, null, at); +} diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginText.cs b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs index 5b233c4..918b970 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginText.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginText.cs @@ -16,4 +16,18 @@ public static bool HasUnsafeCharacter(string text) => UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator => true, _ => false }); + + // Text the game wrote (a location, an item's name, a scene), made safe to hand to a plugin: trimmed, at most 64 + // characters, and dropped if it could rearrange or hide the text a plugin draws around it. + public static string? PublicGameText(string? text) + { + text = text?.Trim(); + if (string.IsNullOrEmpty(text) || HasUnsafeCharacter(text)) + { + return null; + } + + // Never cut between the two halves of a character outside the basic plane. + return text.Length <= 64 ? text : text[..(char.IsHighSurrogate(text[63]) ? 63 : 64)]; + } } diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index 279f832..be6c33a 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -214,19 +214,8 @@ private static bool IsRankingProfile(string? rankingUsername, string? profileUse !string.IsNullOrWhiteSpace(rankingUsername) && profileUsername is not null && string.Equals(profileUsername.Trim(), rankingUsername.Trim(), StringComparison.OrdinalIgnoreCase); - // Text the game's site wrote (a location, an item's name), made safe to hand to a plugin: trimmed, at most 64 - // characters, and dropped if it could rearrange or hide the text a plugin draws around it. - internal static string? PublicGameText(string? text) - { - text = text?.Trim(); - if (string.IsNullOrEmpty(text) || PluginText.HasUnsafeCharacter(text)) - { - return null; - } - - // Never cut between the two halves of a character outside the basic plane. - return text.Length <= 64 ? text : text[..(char.IsHighSurrogate(text[63]) ? 63 : 64)]; - } + // Text the game's site wrote, made safe to hand to a plugin. The rule lives in Core so the live feed shares it. + internal static string? PublicGameText(string? text) => PluginText.PublicGameText(text); IReadOnlyList IPluginHostData.GetAccounts() => _accounts.Select(account => new PluginAccountInfo( From 67128c07fee13a1cb00171232a42743146d8ebbb Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:30:32 -0500 Subject: [PATCH 05/28] feat: add the Live game feed setting, on by default --- .../Data/SettingsStoreLiveFeedTests.cs | 42 +++++++++++++++++++ .../Models/PanelSettings.cs | 4 ++ 2 files changed, 46 insertions(+) create mode 100644 src/FourFoldAccountManager.Core.Tests/Data/SettingsStoreLiveFeedTests.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Data/SettingsStoreLiveFeedTests.cs b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStoreLiveFeedTests.cs new file mode 100644 index 0000000..802f12b --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Data/SettingsStoreLiveFeedTests.cs @@ -0,0 +1,42 @@ +using System.Text.Json.Nodes; +using FourFoldAccountManager.Core.Data; +using FourFoldAccountManager.Core.Models; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Data; + +public sealed class SettingsStoreLiveFeedTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"fourfold-live-feed-{Guid.NewGuid():N}"); + private readonly SettingsStore _store; + + public SettingsStoreLiveFeedTests() + { + Directory.CreateDirectory(_root); + _store = new SettingsStore(new LocalDataPaths(_root)); + } + + private string SettingsPath => Path.Combine(_root, "settings.json"); + + public void Dispose() => Directory.Delete(_root, recursive: true); + + // Every settings file written before this feature lacks the switch; the feed is on by default. + [Fact] + public async Task OlderSettingsWithoutTheSwitchLoadWithTheFeedOn() + { + await _store.SaveAsync(PanelSettings.Default); + var json = JsonNode.Parse(await File.ReadAllTextAsync(SettingsPath))!.AsObject(); + json.Remove("liveGameFeed"); + await File.WriteAllTextAsync(SettingsPath, json.ToJsonString()); + + Assert.True((await _store.LoadAsync()).LiveGameFeed); + } + + [Fact] + public async Task TurningTheFeedOffSurvivesARestart() + { + await _store.SaveAsync(PanelSettings.Default with { LiveGameFeed = false }); + + Assert.False((await _store.LoadAsync()).LiveGameFeed); + } +} diff --git a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs index 2047b69..2905aa0 100644 --- a/src/FourFoldAccountManager.Core/Models/PanelSettings.cs +++ b/src/FourFoldAccountManager.Core/Models/PanelSettings.cs @@ -48,6 +48,10 @@ public PanelSettings(PanelLayout layout, IReadOnlyList slotAccountIds) public bool BlockStorePages { get; init; } + // Reads the game's own traffic in each panel (read-only) and sends live battle and scene events to plugins. On by + // default; a settings file from before the feed has no value and gets this default. + public bool LiveGameFeed { get; init; } = true; + [JsonConverter(typeof(LenientObjectJsonConverter))] public GlobalHotkeyChord RevealXpOverlayTabShortcut { get; init; } = GlobalHotkeyChord.DefaultRevealXpOverlayTab; From bf1556359d0463171cb793d94d7e4e7f000c9fd1 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:33:59 -0500 Subject: [PATCH 06/28] feat: count whether the live feed's XP matches the profile poll --- .../LiveFeed/XpReconciler.cs | 81 +++++++++++++++++++ .../Services/XpTrackerCoordinator.cs | 6 ++ 2 files changed, 87 insertions(+) create mode 100644 src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs new file mode 100644 index 0000000..e09f873 --- /dev/null +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -0,0 +1,81 @@ +using FourFoldAccountManager.Core.Tracking; + +namespace FourFoldAccountManager.Core.LiveFeed; + +// The evidence for trusting the feed with the XP tracker later: at each profile poll, the XP the website shows gained +// must equal the XP the feed's battle results reported over the same window. Counts only; it changes nothing. Not +// thread-safe: the feed calls it under its own lock. +public sealed class XpReconciler +{ + private readonly Dictionary> _results = []; + private readonly Dictionary _lastSamples = []; + + // Each account's last unmatched difference. The game saves XP and sends the result at about the same moment, so a + // battle that ends just before a poll can be counted a window late: +x, then -x. That pair counts as two matches. + private readonly Dictionary _openMismatches = []; + + public int Matched { get; private set; } + + public int Mismatched { get; private set; } + + public int Skipped { get; private set; } + + public void RecordResult(Guid accountId, DateTimeOffset at, string className, long expGained) + { + if (!_results.TryGetValue(accountId, out var results)) + { + _results[accountId] = results = []; + } + + results.Add((at, className, expGained)); + } + + // feedActiveSince: when the feed last became active, or null when it isn't active now. + public void RecordSample( + Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt, DateTimeOffset? feedActiveSince) + { + var hadPrevious = _lastSamples.TryGetValue(accountId, out var previous); + _lastSamples[accountId] = (sampledAt, snapshot); + var results = _results.GetValueOrDefault(accountId) ?? []; + var inWindow = hadPrevious + ? results.Where(result => result.At > previous.At && result.At <= sampledAt).ToArray() + : []; + results.RemoveAll(result => result.At <= sampledAt); + + // Only a window the feed watched from start to end, on one class at one level, can be compared exactly. + if (!hadPrevious || feedActiveSince is not { } since || since > previous.At || + ActiveClass(previous.Snapshot) is not { } before || ActiveClass(snapshot) is not { } after || + !string.Equals(before.Name, after.Name, StringComparison.OrdinalIgnoreCase) || + before.Class.Level != after.Class.Level) + { + Skipped++; + _openMismatches.Remove(accountId); + return; + } + + var polled = after.Class.CurrentXp - before.Class.CurrentXp; + var fed = inWindow + .Where(result => string.Equals(result.ClassName, after.Name, StringComparison.OrdinalIgnoreCase)) + .Sum(result => result.Exp); + var difference = fed - polled; + if (difference == 0) + { + Matched++; + _openMismatches.Remove(accountId); + return; + } + + if (_openMismatches.Remove(accountId, out var open) && open == -difference) + { + Mismatched--; + Matched += 2; + return; + } + + Mismatched++; + _openMismatches[accountId] = difference; + } + + private static (string Name, ClassProfileSnapshot Class)? ActiveClass(PlayerProgressSnapshot snapshot) => + snapshot.ActiveClassName is { } name && snapshot.Classes.TryGetValue(name, out var found) ? (name, found) : null; +} diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index 60c8110..6d64ef3 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -55,6 +55,9 @@ internal XpTrackerCoordinator( public event EventHandler? Changed; + // Raised after each successful profile read, on the poll's thread. The live feed checks its XP against it. + public event Action? ProfileSampled; + public PlayerProfileService ProfileService => _profileService; // Tests shorten the pause before the one retry of a failed profile read. @@ -262,6 +265,9 @@ result.Status is PlayerProfileReadStatus.RankingUnavailable or var sampledAt = DateTimeOffset.UtcNow; account.Session.ApplySnapshot(profile, sampledAt); account.LatestSnapshot = profile; + // A handler that throws must not turn a good read into a failed one. + try { ProfileSampled?.Invoke(account.Id, profile, sampledAt); } + catch (Exception) { } account.Status = account.Session.MissedPreviousSample ? "Partial interval; previous tracker sample failed" : account.Session.ActiveClassUnavailable From ea14891d0cb74bc727e9fcfd983d8643509007a4 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:38:25 -0500 Subject: [PATCH 07/28] feat: tap each game panel's socket read-only and decode it off the UI thread --- .../Services/AccountBrowserSessionService.cs | 8 + .../Services/LiveFeed/GameFeedTap.cs | 85 ++++ .../Services/LiveFeed/LiveGameFeed.cs | 464 ++++++++++++++++++ .../Services/LiveFeed/TapEvent.cs | 13 + 4 files changed, 570 insertions(+) create mode 100644 src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs create mode 100644 src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs create mode 100644 src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs diff --git a/src/FourFoldAccountManager.Desktop/Services/AccountBrowserSessionService.cs b/src/FourFoldAccountManager.Desktop/Services/AccountBrowserSessionService.cs index 768ad30..b0b1435 100644 --- a/src/FourFoldAccountManager.Desktop/Services/AccountBrowserSessionService.cs +++ b/src/FourFoldAccountManager.Desktop/Services/AccountBrowserSessionService.cs @@ -48,6 +48,12 @@ public AccountBrowserSessionService(LocalDataPaths paths, Func blockStoreP /// Raised when a slot is stopped from opening the store or gold page. public event Action? StorePageBlocked; + /// Raised on the UI thread when a new view is ready, before its first navigation. + public event Action? ViewCreated; + + /// Raised on the UI thread just before a view is disposed. + public event Action? ViewClosing; + public Task CreateViewAsync(Guid accountId, Panel host) => InvokeOnDispatcherAsync(() => CreateViewCoreAsync(accountId, host)); @@ -141,6 +147,7 @@ private async Task CreateViewCoreAsync(Guid accountI view.CoreWebView2.NavigationStarting += navigationStarting; view.CoreWebView2.NewWindowRequested += newWindowRequested; _views.Add(accountId, new SessionView(view, navigationStarting, newWindowRequested, scalingScriptId)); + ViewCreated?.Invoke(accountId, view.CoreWebView2); return view; } finally @@ -491,6 +498,7 @@ private void CloseViewCoreUnderLock(Guid accountId) return; } + ViewClosing?.Invoke(accountId); session.View.CoreWebView2.NavigationStarting -= session.NavigationStarting; session.View.CoreWebView2.NewWindowRequested -= session.NewWindowRequested; DetachFromParent(session.View); diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs new file mode 100644 index 0000000..04650a7 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs @@ -0,0 +1,85 @@ +using Microsoft.Web.WebView2.Core; + +namespace FourFoldAccountManager.Desktop.Services.LiveFeed; + +// Watches one panel's sockets through the DevTools protocol, read-only. It subscribes to exactly three events: a socket +// being created, a frame being received, a socket closing. Sent frames (which carry the login) are never subscribed +// to, and nothing here can send, change or intercept traffic. The handlers run on the UI thread, which draws the game +// panels, so they only queue the event's JSON; the feed's worker does all the parsing. +internal sealed class GameFeedTap(CoreWebView2 core, Guid accountId, Action enqueue, TimeProvider clock) +{ + // Small buffers: the feed never reads HTTP bodies, so the browser needn't keep them for DevTools. + private const string EnableParameters = """{"maxTotalBufferSize":1024,"maxResourceBufferSize":1024}"""; + + private CoreWebView2DevToolsProtocolEventReceiver? _created; + private CoreWebView2DevToolsProtocolEventReceiver? _frames; + private CoreWebView2DevToolsProtocolEventReceiver? _closed; + private bool _detached; + + public async Task AttachAsync() + { + // Subscribed before Network.enable, so a socket that opens at once isn't missed. + _created = core.GetDevToolsProtocolEventReceiver("Network.webSocketCreated"); + _frames = core.GetDevToolsProtocolEventReceiver("Network.webSocketFrameReceived"); + _closed = core.GetDevToolsProtocolEventReceiver("Network.webSocketClosed"); + _created.DevToolsProtocolEventReceived += OnCreated; + _frames.DevToolsProtocolEventReceived += OnFrame; + _closed.DevToolsProtocolEventReceived += OnClosed; + await core.CallDevToolsProtocolMethodAsync("Network.enable", EnableParameters); + } + + public void Detach() + { + if (_detached) + { + return; + } + + _detached = true; + if (_created is not null) + { + _created.DevToolsProtocolEventReceived -= OnCreated; + } + + if (_frames is not null) + { + _frames.DevToolsProtocolEventReceived -= OnFrame; + } + + if (_closed is not null) + { + _closed.DevToolsProtocolEventReceived -= OnClosed; + } + + _ = DisableAsync(); + } + + private async Task DisableAsync() + { + try + { + await core.CallDevToolsProtocolMethodAsync("Network.disable", "{}"); + } + catch (Exception) + { + // The view is being disposed; there's nothing left to disable. + } + } + + private void OnCreated(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs args) => + Queue(TapEventKind.SocketCreated, args); + + private void OnFrame(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs args) => + Queue(TapEventKind.Frame, args); + + private void OnClosed(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs args) => + Queue(TapEventKind.SocketClosed, args); + + private void Queue(TapEventKind kind, CoreWebView2DevToolsProtocolEventReceivedEventArgs args) + { + if (!_detached) + { + enqueue(new TapEvent(accountId, kind, args.ParameterObjectAsJson, clock.GetUtcNow())); + } + } +} diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs new file mode 100644 index 0000000..01bb553 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -0,0 +1,464 @@ +using System.Text.Json; +using System.Threading.Channels; +using System.Windows.Threading; +using FourFoldAccountManager.Core.LiveFeed; +using FourFoldAccountManager.Core.Tracking; +using Microsoft.Web.WebView2.Core; + +namespace FourFoldAccountManager.Desktop.Services.LiveFeed; + +internal sealed record LiveFeedCounters( + long Frames, long Recognized, long Dropped, long Failures, int Matched, int Mismatched, int Skipped); + +internal enum LiveFeedState +{ + Off, + Active, + Unavailable +} + +// The live game feed. It taps each game panel's socket (read-only), decodes the allowlisted messages off the UI thread, +// keeps each account's current scene, and passes events to plugins. Nothing built into the app depends on it: when it +// is off or unavailable, everything else carries on from the profile poll. +internal sealed class LiveGameFeed : IAsyncDisposable +{ + public const int QueueCapacity = 4096; + public static readonly TimeSpan CanaryTimeout = TimeSpan.FromSeconds(60); + + private readonly AccountBrowserSessionService _sessions; + private readonly XpTrackerCoordinator _tracker; + private readonly Action _postEvent; + private readonly Dispatcher _dispatcher; + private readonly TimeProvider _clock; + private readonly Channel _queue; + private readonly Task _worker; + + // UI thread only. + private readonly Dictionary _views = []; + private readonly Dictionary _taps = []; + private bool _enabled; + private bool _disposed; + + // Under _gate: read by plugin calls on the UI thread, written by the worker. + private readonly object _gate = new(); + private readonly Dictionary _accounts = []; + private readonly XpReconciler _reconciler = new(); + private LiveFeedState _state = LiveFeedState.Off; + private string? _reason; + private DateTimeOffset? _activeSince; + + private long _frames; + private long _recognized; + private long _dropped; + private long _failures; + + public LiveGameFeed( + AccountBrowserSessionService sessions, + XpTrackerCoordinator tracker, + Action postEvent, + Dispatcher dispatcher, + TimeProvider clock) + { + _sessions = sessions; + _tracker = tracker; + _postEvent = postEvent; + _dispatcher = dispatcher; + _clock = clock; + // Drop-oldest: the UI thread must never wait on the worker. Every drop is counted. + _queue = Channel.CreateBounded( + new BoundedChannelOptions(QueueCapacity) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true, + SingleWriter = true + }, + _ => Interlocked.Increment(ref _dropped)); + _sessions.ViewCreated += OnViewCreated; + _sessions.ViewClosing += OnViewClosing; + _tracker.ProfileSampled += OnProfileSampled; + _worker = Task.Run(RunAsync); + } + + // UI thread. Turning the feed on applies to a panel the next time its game connects: the tap must see the socket + // being created to know which socket is the game's. + public void SetEnabled(bool enabled) + { + if (_disposed || enabled == _enabled) + { + return; + } + + _enabled = enabled; + if (enabled) + { + foreach (var (accountId, core) in _views) + { + Attach(accountId, core); + } + } + else + { + foreach (var tap in _taps.Values) + { + tap.Detach(); + } + + _taps.Clear(); + } + + LiveStatus status; + lock (_gate) + { + _accounts.Clear(); + _state = enabled ? LiveFeedState.Active : LiveFeedState.Off; + _reason = null; + _activeSince = enabled ? _clock.GetUtcNow() : null; + status = CurrentStatus(); + } + + Post("live.statusChanged", status); + } + + public LiveStatus GetStatus() + { + lock (_gate) + { + return CurrentStatus(); + } + } + + public LiveLocation? GetLocation(Guid accountId) + { + lock (_gate) + { + return _state == LiveFeedState.Active && _accounts.TryGetValue(accountId, out var account) + ? account.Location + : null; + } + } + + public LiveFeedCounters GetCounters() + { + lock (_gate) + { + return new LiveFeedCounters( + Interlocked.Read(ref _frames), Interlocked.Read(ref _recognized), Interlocked.Read(ref _dropped), + Interlocked.Read(ref _failures), _reconciler.Matched, _reconciler.Mismatched, _reconciler.Skipped); + } + } + + public async ValueTask DisposeAsync() + { + if (_disposed) + { + return; + } + + _disposed = true; + _sessions.ViewCreated -= OnViewCreated; + _sessions.ViewClosing -= OnViewClosing; + _tracker.ProfileSampled -= OnProfileSampled; + foreach (var tap in _taps.Values) + { + tap.Detach(); + } + + _taps.Clear(); + _queue.Writer.TryComplete(); + await _worker; + } + + private void OnViewCreated(Guid accountId, CoreWebView2 core) + { + _views[accountId] = core; + if (_enabled) + { + Attach(accountId, core); + } + } + + private void OnViewClosing(Guid accountId) + { + _views.Remove(accountId); + if (_taps.Remove(accountId, out var tap)) + { + tap.Detach(); + } + + Enqueue(new TapEvent(accountId, TapEventKind.ViewClosed, string.Empty, _clock.GetUtcNow())); + } + + private void OnProfileSampled(Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt) + { + lock (_gate) + { + _reconciler.RecordSample( + accountId, snapshot, sampledAt, _state == LiveFeedState.Active ? _activeSince : null); + } + } + + private void Attach(Guid accountId, CoreWebView2 core) + { + var tap = new GameFeedTap(core, accountId, Enqueue, _clock); + _taps[accountId] = tap; + _ = AttachAsync(tap); + } + + private async Task AttachAsync(GameFeedTap tap) + { + try + { + await tap.AttachAsync(); + } + catch (Exception) + { + MarkUnavailable("The live feed couldn't attach to a game panel."); + } + } + + private void Enqueue(TapEvent tapEvent) => _queue.Writer.TryWrite(tapEvent); + + private async Task RunAsync() + { + await foreach (var tapEvent in _queue.Reader.ReadAllAsync()) + { + try + { + Handle(tapEvent); + } + catch (Exception) + { + // One bad event must never stop the feed. Nothing is logged: the event holds game traffic. + } + } + } + + private void Handle(TapEvent tapEvent) + { + switch (tapEvent.Kind) + { + case TapEventKind.SocketCreated: + OnSocketCreated(tapEvent); + break; + case TapEventKind.Frame: + OnFrame(tapEvent); + break; + case TapEventKind.SocketClosed: + OnSocketClosed(tapEvent.AccountId, RequestId(tapEvent.Json), tapEvent.At); + break; + case TapEventKind.ViewClosed: + OnSocketClosed(tapEvent.AccountId, requestId: null, tapEvent.At); + break; + } + } + + private void OnSocketCreated(TapEvent tapEvent) + { + using var document = JsonDocument.Parse(tapEvent.Json); + var root = document.RootElement; + if (!root.TryGetProperty("requestId", out var id) || id.ValueKind != JsonValueKind.String || + !root.TryGetProperty("url", out var url) || url.ValueKind != JsonValueKind.String || + !IsGameSocket(url.GetString())) + { + return; + } + + lock (_gate) + { + if (_state == LiveFeedState.Active) + { + // A new game socket (a login or a reconnect) starts the account's state and its canary afresh. + _accounts[tapEvent.AccountId] = new AccountState(id.GetString()!, tapEvent.At); + } + } + } + + private void OnFrame(TapEvent tapEvent) + { + using var document = JsonDocument.Parse(tapEvent.Json); + var root = document.RootElement; + var requestId = root.TryGetProperty("requestId", out var id) && id.ValueKind == JsonValueKind.String + ? id.GetString() + : null; + // Opcode 2 is a binary frame; Mirror sends nothing else on the game socket. + if (!root.TryGetProperty("response", out var response) || response.ValueKind != JsonValueKind.Object || + !response.TryGetProperty("opcode", out var opcode) || !opcode.TryGetInt32(out var op) || op != 2 || + !response.TryGetProperty("payloadData", out var data) || data.ValueKind != JsonValueKind.String) + { + return; + } + + // Only the account's game socket, and only while the feed is active; other frames aren't even decoded. + lock (_gate) + { + if (_state != LiveFeedState.Active || !_accounts.TryGetValue(tapEvent.AccountId, out var watched) || + watched.SocketId != requestId) + { + return; + } + } + + Interlocked.Increment(ref _frames); + byte[] batch; + try + { + batch = Convert.FromBase64String(data.GetString()!); + } + catch (FormatException) + { + Interlocked.Increment(ref _failures); + return; + } + + var result = GameMessageDecoder.DecodeBatch(batch); + Interlocked.Add(ref _recognized, result.Events.Count); + Interlocked.Add(ref _failures, result.Failures + result.Malformed); + if (result.Failures > 0) + { + MarkUnavailable("A game message didn't match the expected format. The game may have updated."); + return; + } + + var posts = new List<(string Name, object Data)>(); + bool canaryFailed; + lock (_gate) + { + if (_state != LiveFeedState.Active || !_accounts.TryGetValue(tapEvent.AccountId, out var account) || + account.SocketId != requestId) + { + return; + } + + foreach (var gameEvent in result.Events) + { + switch (gameEvent) + { + case LoggedIn: + account.SawLogin = true; + break; + case SceneLoaded scene: + account.SawScene = true; + account.Location = LiveFeedPayloads.Location(tapEvent.AccountId, scene.Scene, tapEvent.At); + break; + case BattleResult battle: + _reconciler.RecordResult(tapEvent.AccountId, tapEvent.At, battle.ClassName, battle.ExpGained); + break; + case ModerationDisconnected: + account.DisconnectPosted = true; + break; + } + + if (LiveFeedPayloads.ForPlugins(tapEvent.AccountId, gameEvent, tapEvent.At) is { } post) + { + posts.Add(post); + } + } + + // Every login sends both; 60 s of traffic without them means the ids no longer match the game. + canaryFailed = !(account.SawLogin && account.SawScene) && tapEvent.At - account.OpenedAt > CanaryTimeout; + } + + if (canaryFailed) + { + MarkUnavailable("Game protocol changed: the live feed didn't recognize the login. The game may have updated."); + return; + } + + foreach (var (name, payload) in posts) + { + Post(name, payload); + } + } + + // requestId is null when the whole view closed: whatever socket the account had is gone. + private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at) + { + bool post; + lock (_gate) + { + if (!_accounts.TryGetValue(accountId, out var account) || + (requestId is not null && account.SocketId != requestId)) + { + return; + } + + _accounts.Remove(accountId); + // A server kick already told plugins why; the socket closing after it isn't a second disconnect. + post = _state == LiveFeedState.Active && !account.DisconnectPosted; + } + + if (post) + { + Post("session.disconnected", LiveFeedPayloads.Disconnected(accountId, at)); + } + } + + private void MarkUnavailable(string reason) + { + LiveStatus status; + lock (_gate) + { + if (_state != LiveFeedState.Active) + { + return; + } + + _state = LiveFeedState.Unavailable; + _reason = reason; + _activeSince = null; + _accounts.Clear(); + status = CurrentStatus(); + } + + Post("live.statusChanged", status); + } + + private LiveStatus CurrentStatus() => new( + _state switch + { + LiveFeedState.Active => "active", + LiveFeedState.Off => "off", + _ => "unavailable" + }, + _reason); + + // Plugin pages are posted to from the UI thread, the only thread WebView2 accepts. + private void Post(string name, object? data) => + _dispatcher.InvokeAsync(() => + { + if (!_disposed) + { + _postEvent(name, data); + } + }); + + private static bool IsGameSocket(string? value) => + Uri.TryCreate(value, UriKind.Absolute, out var uri) && + uri.Scheme == "wss" && + string.Equals(uri.IdnHost, "fourfoldonline.com", StringComparison.OrdinalIgnoreCase) && + uri.IsDefaultPort && + uri.AbsolutePath.TrimEnd('/') == "/game-ws"; + + private static string? RequestId(string json) + { + using var document = JsonDocument.Parse(json); + return document.RootElement.TryGetProperty("requestId", out var id) && id.ValueKind == JsonValueKind.String + ? id.GetString() + : null; + } + + private sealed class AccountState(string socketId, DateTimeOffset openedAt) + { + public string SocketId { get; } = socketId; + + public DateTimeOffset OpenedAt { get; } = openedAt; + + public bool SawLogin { get; set; } + + public bool SawScene { get; set; } + + public bool DisconnectPosted { get; set; } + + public LiveLocation? Location { get; set; } + } +} diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs new file mode 100644 index 0000000..bff8fa5 --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs @@ -0,0 +1,13 @@ +namespace FourFoldAccountManager.Desktop.Services.LiveFeed; + +internal enum TapEventKind +{ + SocketCreated, + Frame, + SocketClosed, + ViewClosed +} + +// One DevTools event as the tap saw it. Json is the raw parameter object and may hold game traffic: it's parsed on the +// feed's worker and never logged or kept. +internal readonly record struct TapEvent(Guid AccountId, TapEventKind Kind, string Json, DateTimeOffset At); From f7a14fd4faa0aad40518b6ed31c3ec26f79d70e2 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:44:45 -0500 Subject: [PATCH 08/28] fix: keep the live feed on when a panel closes mid-attach and count only watched XP windows --- .../Services/LiveFeed/GameFeedTap.cs | 25 ++++++++++++------- .../Services/LiveFeed/LiveGameFeed.cs | 20 +++++++++------ .../Services/LiveFeed/TapEvent.cs | 6 ++++- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs index 04650a7..95b3371 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/GameFeedTap.cs @@ -36,19 +36,26 @@ public void Detach() } _detached = true; - if (_created is not null) + try { - _created.DevToolsProtocolEventReceived -= OnCreated; - } + if (_created is not null) + { + _created.DevToolsProtocolEventReceived -= OnCreated; + } - if (_frames is not null) - { - _frames.DevToolsProtocolEventReceived -= OnFrame; - } + if (_frames is not null) + { + _frames.DevToolsProtocolEventReceived -= OnFrame; + } - if (_closed is not null) + if (_closed is not null) + { + _closed.DevToolsProtocolEventReceived -= OnClosed; + } + } + catch (Exception) { - _closed.DevToolsProtocolEventReceived -= OnClosed; + // A view whose browser has died has nothing left to unsubscribe from. } _ = DisableAsync(); diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 01bb553..2d9b4c3 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -45,7 +45,6 @@ internal sealed class LiveGameFeed : IAsyncDisposable private readonly XpReconciler _reconciler = new(); private LiveFeedState _state = LiveFeedState.Off; private string? _reason; - private DateTimeOffset? _activeSince; private long _frames; private long _recognized; @@ -112,7 +111,6 @@ public void SetEnabled(bool enabled) _accounts.Clear(); _state = enabled ? LiveFeedState.Active : LiveFeedState.Off; _reason = null; - _activeSince = enabled ? _clock.GetUtcNow() : null; status = CurrentStatus(); } @@ -192,8 +190,11 @@ private void OnProfileSampled(Guid accountId, PlayerProgressSnapshot snapshot, D { lock (_gate) { - _reconciler.RecordSample( - accountId, snapshot, sampledAt, _state == LiveFeedState.Active ? _activeSince : null); + // The window only counts when the feed watched this account's game socket for all of it. + var watchedSince = _state == LiveFeedState.Active && _accounts.TryGetValue(accountId, out var account) + ? account.OpenedAt + : (DateTimeOffset?)null; + _reconciler.RecordSample(accountId, snapshot, sampledAt, watchedSince); } } @@ -201,10 +202,10 @@ private void Attach(Guid accountId, CoreWebView2 core) { var tap = new GameFeedTap(core, accountId, Enqueue, _clock); _taps[accountId] = tap; - _ = AttachAsync(tap); + _ = AttachAsync(accountId, tap); } - private async Task AttachAsync(GameFeedTap tap) + private async Task AttachAsync(Guid accountId, GameFeedTap tap) { try { @@ -212,7 +213,11 @@ private async Task AttachAsync(GameFeedTap tap) } catch (Exception) { - MarkUnavailable("The live feed couldn't attach to a game panel."); + // Resumes on the UI thread, where _taps lives. A panel closed mid-attach isn't a feed failure. + if (_taps.TryGetValue(accountId, out var current) && ReferenceEquals(current, tap)) + { + MarkUnavailable("The live feed couldn't attach to a game panel."); + } } } @@ -405,7 +410,6 @@ private void MarkUnavailable(string reason) _state = LiveFeedState.Unavailable; _reason = reason; - _activeSince = null; _accounts.Clear(); status = CurrentStatus(); } diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs index bff8fa5..573b7ba 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/TapEvent.cs @@ -10,4 +10,8 @@ internal enum TapEventKind // One DevTools event as the tap saw it. Json is the raw parameter object and may hold game traffic: it's parsed on the // feed's worker and never logged or kept. -internal readonly record struct TapEvent(Guid AccountId, TapEventKind Kind, string Json, DateTimeOffset At); +internal readonly record struct TapEvent(Guid AccountId, TapEventKind Kind, string Json, DateTimeOffset At) +{ + // Json is never printed: it may hold game traffic. + public override string ToString() => $"TapEvent {{ AccountId = {AccountId}, Kind = {Kind}, At = {At:O} }}"; +} From 79f4cb1e8103139bb796bdff8586d78a8e5b57c3 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:47:08 -0500 Subject: [PATCH 09/28] feat: give plugins live battle, skill, location and session events (API 3) --- .../Plugins/PluginManifestReaderTests.cs | 2 +- .../Plugins/PluginManifestReader.cs | 2 +- .../Plugins/PluginApiTests.cs | 5 +++ .../MainWindow.LiveFeed.cs | 38 +++++++++++++++++++ .../MainWindow.xaml.cs | 4 ++ .../Plugins/Web/PluginApi.cs | 9 +++++ .../Plugins/Web/PluginHostData.cs | 8 ++++ .../Plugins/Web/PluginSdk.cs | 18 +++++++++ 8 files changed, 84 insertions(+), 2 deletions(-) create mode 100644 src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs index ec57ddc..45d6151 100644 --- a/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Plugins/PluginManifestReaderTests.cs @@ -99,7 +99,7 @@ public void AValidManifestLoadsWithItsSitesAndCards() [InlineData("\"id\": \"nul.tools\"")] [InlineData("\"id\": \"com1.tools\"")] [InlineData("\"id\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"")] - [InlineData("\"apiVersion\": 3")] + [InlineData("\"apiVersion\": 4")] [InlineData("\"apiVersion\": \"1\"")] [InlineData("\"panel\": \"missing.html\"")] [InlineData("\"panel\": \"plugin.json\"")] diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index 000f073..e6f6c94 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -9,7 +9,7 @@ namespace FourFoldAccountManager.Core.Plugins; public static partial class PluginManifestReader { // 2 added fourfold.profile, and equipment on stats.get. - public const int SupportedApiVersion = 2; + public const int SupportedApiVersion = 3; // author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot. public const string IdPattern = @"[a-z0-9]+(-[a-z0-9]+)*(\.[a-z0-9]+(-[a-z0-9]+)*)+"; diff --git a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs index 84c26f4..9c7674c 100644 --- a/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs +++ b/src/FourFoldAccountManager.Desktop.Tests/Plugins/PluginApiTests.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.IO; using System.Text.Json; +using FourFoldAccountManager.Core.LiveFeed; using FourFoldAccountManager.Core.Models; using FourFoldAccountManager.Core.Overlay; using FourFoldAccountManager.Core.Plugins; @@ -289,6 +290,10 @@ private sealed class FakeHost : IPluginHostData public PluginTimerInfo GetTimer() => new("stopped", 0, []); + public LiveLocation? GetLocation(Guid accountId) => null; + + public LiveStatus GetLiveStatus() => new("off", null); + public bool IsPanelShowing(string pluginId) => PanelShowing; public void OpenInBrowser(Uri uri) => Opened.Add(uri); diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs new file mode 100644 index 0000000..efe74bc --- /dev/null +++ b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs @@ -0,0 +1,38 @@ +using FourFoldAccountManager.Core.LiveFeed; +using FourFoldAccountManager.Desktop.Plugins.Web; +using FourFoldAccountManager.Desktop.Services.LiveFeed; + +namespace FourFoldAccountManager.Desktop; + +// The live game feed: built once, switched on or off from Settings, read by plugins. +public partial class MainWindow +{ + private LiveGameFeed _liveFeed = null!; + + // Starts off; MainWindow_Loaded switches it to the saved setting. Panels created before then are remembered and + // tapped when it switches on. + private void InitializeLiveFeed() => + _liveFeed = new LiveGameFeed( + _browserSessions, _xpTracker, (name, data) => _communityPlugins.PostEvent(name, data), Dispatcher, + TimeProvider.System); + + // One line for Settings: the state, then the counts the feed must earn before the XP tracker relies on it. + private string LiveFeedSummary() + { + var status = _liveFeed.GetStatus(); + var counters = _liveFeed.GetCounters(); + var state = status.State switch + { + "active" => "Active", + "off" => "Off", + _ => $"Unavailable: {status.Reason}" + }; + return $"{state} · {counters.Frames:N0} frames · {counters.Recognized:N0} events · " + + $"{counters.Dropped:N0} dropped · {counters.Failures:N0} errors · XP checks: " + + $"{counters.Matched:N0} matched, {counters.Mismatched:N0} mismatched, {counters.Skipped:N0} skipped"; + } + + LiveLocation? IPluginHostData.GetLocation(Guid accountId) => _liveFeed.GetLocation(accountId); + + LiveStatus IPluginHostData.GetLiveStatus() => _liveFeed.GetStatus(); +} diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 4bb23a3..3e8573a 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -132,6 +132,7 @@ public MainWindow() _plugins.XpCalc.View.AccountSelectionRequested += SelectAccountFromPlugin; _plugins.Timer.ShortcutChangeRequested += TimerPlugin_ShortcutChangeRequested; InitializeCommunityPlugins(paths); + InitializeLiveFeed(); RefreshPluginSidebar(); PluginSidebar.OpenRequested += id => { @@ -301,6 +302,7 @@ private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { ReplaceAccounts(await _accountStore.LoadAsync()); _panelSettings = await _settingsStore.LoadAsync(); + _liveFeed.SetEnabled(_panelSettings.LiveGameFeed); try { var apiOptions = LeaderboardApiOptions.FromEnvironment(); @@ -3432,6 +3434,8 @@ private async void MainWindow_Closing(object? sender, System.ComponentModel.Canc // First, so a download that finishes now can't reach the plugins that are being disposed. _pluginHub.Dispose(); _communityPlugins.Dispose(); + // After the plugins: nothing may be posted to a plugin that is being disposed. + await _liveFeed.DisposeAsync(); try { diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs index c3b4e77..bc87eb3 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginApi.cs @@ -115,6 +115,15 @@ internal sealed class PluginApi( return host.GetProfile(AccountId(parameters)) ?? throw UnknownAccount(); case "timer.get": return host.GetTimer(); + case "location.get": + { + var accountId = AccountId(parameters); + return host.GetAccounts().Any(account => account.Id == accountId) + ? host.GetLocation(accountId) + : throw UnknownAccount(); + } + case "live.getStatus": + return host.GetLiveStatus(); case "storage.get": return await storage.GetAsync(Text(parameters, "key")); case "storage.set": diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs index 550fcb3..8ec8111 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginHostData.cs @@ -1,3 +1,5 @@ +using FourFoldAccountManager.Core.LiveFeed; + namespace FourFoldAccountManager.Desktop.Plugins.Web; public sealed record PluginAccountInfo(Guid Id, string Label, string? InGameName, bool IsOpen); @@ -61,6 +63,12 @@ public interface IPluginHostData PluginTimerInfo GetTimer(); + // The account's current scene from the live feed. Null when the feed is off or unavailable, or the account's game + // isn't connected. + LiveLocation? GetLocation(Guid accountId); + + LiveStatus GetLiveStatus(); + // True while this plugin's panel is the one showing in the strip. bool IsPanelShowing(string pluginId); diff --git a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs index 2e06c33..d48043a 100644 --- a/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs +++ b/src/FourFoldAccountManager.Desktop/Plugins/Web/PluginSdk.cs @@ -95,6 +95,24 @@ internal static class PluginSdk get: () => call('timer.get'), onChanged: callback => on('timer.changed', callback) }), + battle: Object.freeze({ + onStarted: callback => on('battle.started', callback), + onEnded: callback => on('battle.ended', callback), + onResult: callback => on('battle.result', callback), + onSkillResult: callback => on('battle.skillResult', callback) + }), + location: Object.freeze({ + get: accountId => call('location.get', { accountId }), + onChanged: callback => on('location.changed', callback) + }), + session: Object.freeze({ + onLoggedIn: callback => on('session.loggedIn', callback), + onDisconnected: callback => on('session.disconnected', callback) + }), + live: Object.freeze({ + getStatus: () => call('live.getStatus'), + onStatusChanged: callback => on('live.statusChanged', callback) + }), http: Object.freeze({ fetch: (url, options) => call('http.fetch', { url, ...(options ?? {}) }) }), openExternal: url => navigator.userActivation && !navigator.userActivation.isActive ? Promise.reject(Object.assign(new Error('openExternal needs a click.'), { code: 'unavailable' })) From 26cc51060828e97097308a5492b9aa9afe0a7d28 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 15:49:59 -0500 Subject: [PATCH 10/28] feat: add the Live game feed switch and its counters to Settings --- .../MainWindow.xaml.cs | 18 ++++++++++++++++-- .../Views/SettingsDialog.xaml | 17 +++++++++++++++++ .../Views/SettingsDialog.xaml.cs | 9 ++++++++- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 3e8573a..01c64f5 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -1077,7 +1077,9 @@ private async void Settings_Click(object sender, RoutedEventArgs e) GlobalShortcutActions.All.Where(action => _shortcuts?.IsAvailable(action) != true).ToHashSet(), showOverlaysInTheatreMode: _panelSettings.ShowOverlaysInTheatreMode, secondMonitorMode: _panelSettings.SecondMonitorMode, - blockStorePages: _panelSettings.BlockStorePages) + blockStorePages: _panelSettings.BlockStorePages, + liveGameFeed: _panelSettings.LiveGameFeed, + liveFeedSummary: LiveFeedSummary()) { Owner = this }; @@ -1103,6 +1105,7 @@ private async void Settings_Click(object sender, RoutedEventArgs e) var theatreOverlaysChanged = dialog.ShowOverlaysInTheatreMode != _panelSettings.ShowOverlaysInTheatreMode; var secondMonitorModeChanged = dialog.SecondMonitorMode != _panelSettings.SecondMonitorMode; var storeBlockChanged = dialog.BlockStorePages != _panelSettings.BlockStorePages; + var liveFeedChanged = dialog.LiveGameFeed != _panelSettings.LiveGameFeed; // Leaving Account tools mode closes the tools window; its spot is saved with the mode change. var closingToolsPlacement = secondMonitorModeChanged && dialog.SecondMonitorMode != SecondMonitorMode.AccountToolsWindow @@ -1113,6 +1116,7 @@ private async void Settings_Click(object sender, RoutedEventArgs e) !theatreOverlaysChanged && !secondMonitorModeChanged && !storeBlockChanged && + !liveFeedChanged && changedShortcuts.Length == 0 && !dialog.ResetLayoutSizes) { @@ -1141,7 +1145,8 @@ async Task PersistDialogSettingsAsync() ShowFullScreenExitButton = dialog.ShowFullScreenExitButton, ShowOverlaysInTheatreMode = dialog.ShowOverlaysInTheatreMode, SecondMonitorMode = dialog.SecondMonitorMode, - BlockStorePages = dialog.BlockStorePages + BlockStorePages = dialog.BlockStorePages, + LiveGameFeed = dialog.LiveGameFeed }); if (secondMonitorModeChanged && dialog.SecondMonitorMode == SecondMonitorMode.AccountToolsWindow) { @@ -1191,6 +1196,11 @@ async Task PersistDialogSettingsAsync() return; } + if (liveFeedChanged) + { + _liveFeed.SetEnabled(nextSettings.LiveGameFeed); + } + RefreshPlainKeyBindings(); if (dialog.ResetLayoutSizes) { @@ -1238,6 +1248,10 @@ async Task PersistDialogSettingsAsync() ? nextSettings.SecondMonitorMode == SecondMonitorMode.FloatingCards ? "Second monitor set to Floating cards." : "Second monitor set to Account tools window." + : liveFeedChanged + ? nextSettings.LiveGameFeed + ? "The live game feed is on. A panel already in a game starts sending events the next time it connects." + : "The live game feed is off." : storeBlockChanged ? nextSettings.BlockStorePages ? "The in-game store and gold buttons are now blocked." diff --git a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml index 8eb3046..bd7b7da 100644 --- a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml @@ -124,6 +124,23 @@ + + + + + + + + + + + + diff --git a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs index 43d1b9f..9f8fd85 100644 --- a/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/SettingsDialog.xaml.cs @@ -21,7 +21,9 @@ internal SettingsDialog( IReadOnlySet unavailableShortcuts, bool showOverlaysInTheatreMode, SecondMonitorMode secondMonitorMode, - bool blockStorePages) + bool blockStorePages, + bool liveGameFeed, + string liveFeedSummary) { ArgumentNullException.ThrowIfNull(shortcuts); ArgumentNullException.ThrowIfNull(unavailableShortcuts); @@ -42,6 +44,8 @@ internal SettingsDialog( AccountToolsModeOption.IsChecked = secondMonitorMode == SecondMonitorMode.AccountToolsWindow; FloatingCardsModeOption.IsChecked = secondMonitorMode == SecondMonitorMode.FloatingCards; BlockStorePagesOption.IsChecked = blockStorePages; + LiveGameFeedOption.IsChecked = liveGameFeed; + LiveFeedCountersText.Text = liveFeedSummary; _rows = new[] { RevealShortcutRow, DividerShortcutRow, NextTabShortcutRow, PreviousTabShortcutRow, TheatreShortcutRow @@ -66,6 +70,8 @@ internal SettingsDialog( public bool BlockStorePages { get; private set; } + public bool LiveGameFeed { get; private set; } + public IReadOnlyDictionary Shortcuts => _shortcuts; public bool ResetLayoutSizes { get; private set; } @@ -197,6 +203,7 @@ private void Save_Click(object sender, RoutedEventArgs e) ? SecondMonitorMode.FloatingCards : SecondMonitorMode.AccountToolsWindow; BlockStorePages = BlockStorePagesOption.IsChecked == true; + LiveGameFeed = LiveGameFeedOption.IsChecked == true; DialogResult = true; } From ce3ca3d9072677d3f2b500702ec667e6035a7e64 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 16:01:37 -0500 Subject: [PATCH 11/28] fix: drop the always-false victory flag and keep the XP evidence honest --- .../LiveFeed/MirrorHashTests.cs | 15 +++++++------ .../LiveFeed/GameEvents.cs | 2 +- .../LiveFeed/GameMessageDecoder.cs | 3 ++- .../LiveFeed/LiveFeedPayloads.cs | 6 +++-- .../LiveFeed/XpReconciler.cs | 22 ++++++++++++++----- .../Plugins/PluginManifestReader.cs | 3 ++- .../Services/LiveFeed/LiveGameFeed.cs | 10 ++++++--- 7 files changed, 41 insertions(+), 20 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs index db63ac1..c5f1c07 100644 --- a/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/MirrorHashTests.cs @@ -5,14 +5,15 @@ namespace FourFoldAccountManager.Core.Tests.LiveFeed; public sealed class MirrorHashTests { - // The ints the decompiled game passes to SendTargetRPCInternal. If a signature string or the hash drifts, the feed - // would silently never match these calls; after a game update, refresh both from the new decompile. + // Pins the decoder's own signature constants to the ints the decompiled game passes to SendTargetRPCInternal. If a + // signature or the hash drifts, the feed would silently never match these calls; after a game update, refresh both + // from the new decompile. [Theory] - [InlineData("System.Void BattlePlayerCommands2::TargetOpenHUD(Mirror.NetworkConnectionToClient,System.UInt32[],System.Boolean)", 524349864)] - [InlineData("System.Void BattlePlayerCommands2::TargetCloseHUD(Mirror.NetworkConnectionToClient,System.Boolean)", -274237404)] - [InlineData("System.Void BattlePlayerCommands2::TargetShowBattleResult(Mirror.NetworkConnectionToClient,System.Boolean,System.Int32,System.Int32,System.Int32,System.Int32,System.String,System.String,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32,System.Int32)", -2013908526)] - [InlineData("System.Void BattlePlayerCommands2::TargetSkillResult(Mirror.NetworkConnectionToClient,System.Boolean,System.String)", 884216395)] - [InlineData("System.Void SimpleScenePlayer::TargetLoadScene(Mirror.NetworkConnectionToClient,System.String,System.String,UnityEngine.Vector2,System.Int32,System.Boolean)", 565832018)] + [InlineData(GameMessageDecoder.OpenHudSignature, 524349864)] + [InlineData(GameMessageDecoder.CloseHudSignature, -274237404)] + [InlineData(GameMessageDecoder.BattleResultSignature, -2013908526)] + [InlineData(GameMessageDecoder.SkillResultSignature, 884216395)] + [InlineData(GameMessageDecoder.LoadSceneSignature, 565832018)] public void SignaturesHashToTheGamesOwnValues(string signature, int decompiledHash) { Assert.Equal(decompiledHash, MirrorHash.StableHash(signature)); diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs index 1b701e2..f1be741 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameEvents.cs @@ -6,7 +6,7 @@ public abstract record GameEvent; public sealed record BattleStarted(int EnemyCount) : GameEvent; -public sealed record BattleEnded(bool Victory) : GameEvent; +public sealed record BattleEnded : GameEvent; public sealed record StatGains(int MaxHp, int MaxSp, int Hp, int Sp, int Att, int Mag, int Skl, int Spd, int Def, int Res, int Lck); diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs index 9362d20..1ac7016 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs @@ -153,7 +153,8 @@ private static GameEvent ParseRpc(ushort hash, ReadOnlySpan payload) } else if (hash == CloseHud) { - result = new BattleEnded(reader.ReadBool()); + reader.ReadBool(); // victory: always false from the server, not kept + result = new BattleEnded(); } else if (hash == BattleResultHash) { diff --git a/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs b/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs index 5ecc9d6..49257e3 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/LiveFeedPayloads.cs @@ -6,7 +6,9 @@ namespace FourFoldAccountManager.Core.LiveFeed; // a field that isn't in one of these records can't reach a plugin. Every string passes PublicGameText. public sealed record LiveBattleStarted(Guid AccountId, int EnemyCount, DateTimeOffset At); -public sealed record LiveBattleEnded(Guid AccountId, bool Victory, DateTimeOffset At); +// No victory flag: the game passes false to every TargetCloseHUD, even after a win. A plugin should read a following +// battle.result as the win. +public sealed record LiveBattleEnded(Guid AccountId, DateTimeOffset At); public sealed record LiveBattleResult( Guid AccountId, @@ -43,7 +45,7 @@ public static (string Name, object Data)? ForPlugins(Guid accountId, GameEvent g gameEvent switch { BattleStarted e => ("battle.started", new LiveBattleStarted(accountId, e.EnemyCount, at)), - BattleEnded e => ("battle.ended", new LiveBattleEnded(accountId, e.Victory, at)), + BattleEnded e => ("battle.ended", new LiveBattleEnded(accountId, at)), BattleResult e => ("battle.result", new LiveBattleResult(accountId, e.ExpGained, e.SilverGained, e.ExpNeededToNextLevel, e.LeveledUp, e.ReachedLevel, PluginText.PublicGameText(e.ClassName), PluginText.PublicGameText(e.UnlockedSkillName), e.Gains, at)), diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs index e09f873..eedf585 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -30,9 +30,9 @@ public void RecordResult(Guid accountId, DateTimeOffset at, string className, lo results.Add((at, className, expGained)); } - // feedActiveSince: when the feed last became active, or null when it isn't active now. + // watchedSince: when the feed started watching this account's current game socket, or null when it isn't watching. public void RecordSample( - Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt, DateTimeOffset? feedActiveSince) + Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt, DateTimeOffset? watchedSince) { var hadPrevious = _lastSamples.TryGetValue(accountId, out var previous); _lastSamples[accountId] = (sampledAt, snapshot); @@ -43,9 +43,9 @@ public void RecordSample( results.RemoveAll(result => result.At <= sampledAt); // Only a window the feed watched from start to end, on one class at one level, can be compared exactly. - if (!hadPrevious || feedActiveSince is not { } since || since > previous.At || + if (!hadPrevious || watchedSince is not { } since || since > previous.At || ActiveClass(previous.Snapshot) is not { } before || ActiveClass(snapshot) is not { } after || - !string.Equals(before.Name, after.Name, StringComparison.OrdinalIgnoreCase) || + !string.Equals(NormalizeClass(before.Name), NormalizeClass(after.Name), StringComparison.Ordinal) || before.Class.Level != after.Class.Level) { Skipped++; @@ -55,8 +55,17 @@ public void RecordSample( var polled = after.Class.CurrentXp - before.Class.CurrentXp; var fed = inWindow - .Where(result => string.Equals(result.ClassName, after.Name, StringComparison.OrdinalIgnoreCase)) + .Where(result => string.Equals( + NormalizeClass(result.ClassName), NormalizeClass(after.Name), StringComparison.Ordinal)) .Sum(result => result.Exp); + if (polled == 0 && fed == 0) + { + // No battle and no XP change proves nothing about the feed, so it isn't evidence either way. + Skipped++; + _openMismatches.Remove(accountId); + return; + } + var difference = fed - polled; if (difference == 0) { @@ -76,6 +85,9 @@ public void RecordSample( _openMismatches[accountId] = difference; } + // Matches the game's SkillCatalog.Normalize, so "Dark_Knight" and "dark knight" are the same class. + private static string NormalizeClass(string? name) => (name ?? string.Empty).Trim().Replace('_', ' ').ToLowerInvariant(); + private static (string Name, ClassProfileSnapshot Class)? ActiveClass(PlayerProgressSnapshot snapshot) => snapshot.ActiveClassName is { } name && snapshot.Classes.TryGetValue(name, out var found) ? (name, found) : null; } diff --git a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs index e6f6c94..799e6db 100644 --- a/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs +++ b/src/FourFoldAccountManager.Core/Plugins/PluginManifestReader.cs @@ -8,7 +8,8 @@ namespace FourFoldAccountManager.Core.Plugins; public static partial class PluginManifestReader { - // 2 added fourfold.profile, and equipment on stats.get. + // 2 added fourfold.profile, and equipment on stats.get. 3 added the live game feed: battle, location, session and + // live events. public const int SupportedApiVersion = 3; // author.plugin-name: lowercase letters, digits and dashes in dot-separated parts, with at least one dot. diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 2d9b4c3..de4c041 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -338,8 +338,9 @@ private void OnFrame(TapEvent tapEvent) { switch (gameEvent) { - case LoggedIn: + case LoggedIn login: account.SawLogin = true; + account.LoginPosted |= login.Success; break; case SceneLoaded scene: account.SawScene = true; @@ -388,8 +389,9 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at } _accounts.Remove(accountId); - // A server kick already told plugins why; the socket closing after it isn't a second disconnect. - post = _state == LiveFeedState.Active && !account.DisconnectPosted; + // A server kick already told plugins why; the socket closing after it isn't a second disconnect. Plugins + // weren't told this session started (no successful login), so they aren't told it ended. + post = _state == LiveFeedState.Active && account.LoginPosted && !account.DisconnectPosted; } if (post) @@ -459,6 +461,8 @@ private sealed class AccountState(string socketId, DateTimeOffset openedAt) public bool SawLogin { get; set; } + public bool LoginPosted { get; set; } + public bool SawScene { get; set; } public bool DisconnectPosted { get; set; } From e26bba512590b4763ca14881078f238d1f3af6dc Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:09:56 -0500 Subject: [PATCH 12/28] fix: accept any battle result level above zero Levels have no cap in the game, and the decoder is strict: a level above 999 would have made the account's live feed unavailable. A misread message still fails the end-of-payload check. --- src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs index 1ac7016..b61e5da 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/GameMessageDecoder.cs @@ -192,8 +192,9 @@ private static BattleResult ParseBattleResult(ref MirrorReader reader) var silver = AtLeastZero(reader.ReadVarInt32()); var exp = AtLeastZero(reader.ReadVarInt32()); var needed = AtLeastZero(reader.ReadVarInt32()); + // No upper bound: levels have no cap in the game, and a misread message fails the length checks anyway. var level = reader.ReadVarInt32(); - if (level is < 1 or > 999) + if (level < 1) { throw new MirrorFormatException(); } From 9fc3d6155aad22d03539659399bfadcf5146663c Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 21:33:39 -0500 Subject: [PATCH 13/28] docs: document the live game feed for plugin authors (API 3) --- PLUGIN_AUTHORS.md | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 6a7602f..a614a98 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -70,7 +70,7 @@ A `plugin.json` that breaks any rule below is rejected: the plugin doesn't load, | `version` | yes | `MAJOR.MINOR.PATCH`, digits only, such as `1.0.0`. | | `author` | yes | 1 to 40 characters. | | `description` | no | At most 200 characters. | -| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1` and `2`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." | +| `apiVersion` | yes | A whole number: the lowest API version the plugin needs. FourFold supports `1`, `2` and `3`. Declare `2` if the plugin calls `fourfold.profile` or reads `equipment`, and `3` if it can't work without the [live game feed](#live-game-feed), so that an older FourFold tells the user to update instead of running a plugin that can't work. A higher number is rejected with "Update FourFold to use this plugin." | | `panel` | yes | Path to an existing `.html` file inside the plugin folder. Forward slashes only. | | `icon` | no | Path to a `.png` file inside the plugin folder, at most 256 by 256 pixels and 64 KB. Forward slashes only. Without one, the strip shows a default icon. | | `sites` | no | At most 10 websites the plugin may contact. Each is an origin: `https://host` or `https://host:port`, with no path, query or `user@`. The host must be a DNS name: no IP address, no trailing dot, and no name that only works on the local network. `localhost`, `.localhost`, `.local`, `.internal`, `.lan` and `.home.arpa` names are refused, and so is a single-label name such as `router`. A subdomain is its own site, so `https://example.com` doesn't cover `https://www.example.com`. An international host name is fine: FourFold converts it to its `xn--` form, and that form is what it shows users. After the conversion the host can contain only letters, digits, dots and dashes, so a name with an underscore or any other punctuation is refused. | @@ -173,6 +173,39 @@ if (!profile.isStale && profile.silver !== null) console.log(account.label, 'has The data comes from the same read as XP: about once a minute, for open accounts only. There is no profile event: read `profile.get` again when `xp.onUpdated` fires. That event also fires for changes that aren't a new read, and `updatedAt` only changes with a new one, so compare it to tell them apart. After a failed read `silver`, `gold`, `location` and `updatedAt` keep their last values and `isStale` is `true`. For a closed account the number and text fields are `null`. An unknown account id is rejected with `invalid-argument`. +### Live game feed + +```js +fourfold.battle.onResult(({ accountId, expGained, silverGained, className }) => { + console.log(accountId, 'won', expGained, 'XP and', silverGained, 'silver as', className); +}); +const status = await fourfold.live.getStatus(); +if (status.state !== 'active') console.log('no live events:', status.reason); +``` + +API 3. FourFold reads what the game sends to the user's own game panels and passes on a few events as they happen: fights, skill hits and misses, where each account is, and logins. It only reads: it never sends anything to the game or changes what the game does. Plugins get only the fields below, for the user's own accounts. Never other players' data, chat or anything else the game sends. + +The user can switch the feed off in FourFold's Settings, and a game update can stop FourFold reading it until FourFold is updated too. So treat live events as a bonus: keep `xp.get` and `profile.get` as the fallback, and check `live.getStatus()`. A plugin that does and keeps `"apiVersion": 2` also runs on an older FourFold, where `fourfold.battle`, `fourfold.location`, `fourfold.session` and `fourfold.live` don't exist: check for them before using them. Declare `3` only if the plugin can't work without the feed. + +Every event has the account's `accountId` and `at`, the time FourFold received it, as an ISO 8601 date. + +| Call | Fires | Data | +|---|---|---| +| `battle.onStarted(callback)` | A fight starts. | `{ accountId, enemyCount, at }` | +| `battle.onEnded(callback)` | A fight ends. | `{ accountId, at }` | +| `battle.onResult(callback)` | A fight is won. | See below. | +| `battle.onSkillResult(callback)` | A skill is used. | `{ accountId, skillName, outcome, targetsAffected, reason, at }` | +| `location.onChanged(callback)` | An account changes place. | `{ accountId, scene, inBattle, at }` | +| `session.onLoggedIn(callback)` | An account logs in to the game. | `{ accountId, at }` | +| `session.onDisconnected(callback)` | An account's game connection ends. | `{ accountId, reason, at }` | +| `live.onStatusChanged(callback)` | The feed's status changes. | `{ state, reason }` | + +- **Fights.** The game doesn't say whether a fight was won: a win is a `battle.onResult` after `battle.onEnded`, and an end with no result is an escape or a loss. `battle.onResult` gives `expGained` and `silverGained` (any double-XP event is already included), `expNeededToNextLevel`, `leveledUp`, `reachedLevel`, `className` (or `null`), `unlockedSkillName` (`null` when none unlocked; comma-joined when several do, at most 64 characters) and `statGains`: `{ maxHp, maxSp, hp, sp, att, mag, skl, spd, def, res, lck }`, the points the fight added. +- **Skills.** `outcome` is `"hit"`, `"miss"` or `"rejected"`. The game rolls once per cast against the skill's chance, so a miss misses every target. A rejected cast (not enough SP, say) never rolled: `skillName` is `null` and `reason` is the game's text. Otherwise `reason` is `null`. +- **Places.** `scene` is the game's own scene name, such as `westhills_b2_dungeon_01`. `inBattle` is `true` in a fight scene. `fourfold.location.get(accountId)` returns the same `{ accountId, scene, inBattle, at }` for the account's current place, or `null` when FourFold has no live data for it (a closed account, or one that hasn't changed place since the feed started). An unknown account id is rejected with `invalid-argument`. +- **Sessions.** `session.onLoggedIn` fires for a successful login only. `session.onDisconnected` fires on a kick, with the server's text in `reason`, and on a reload or a closed panel, with `reason` `null`. It also ends any fight in progress: a fight cut off by a reload never gets `battle.onEnded`, and after the login the game resumes it with a new `battle.onStarted`. +- **Status.** `fourfold.live.getStatus()` returns `{ state, reason }`. `state` is `"active"` while the feed is on and reading, `"off"` when the user switched it off, and `"unavailable"` when FourFold can't read the game, with the reason in `reason` (a game update FourFold can't read yet, say). `reason` is `null` otherwise. An account already in game when the feed is switched on sends nothing until its game reconnects. + ### Timer ```js @@ -405,9 +438,10 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve ## What plugins can't do -- Read or control the game, or see its pages, cookies or sessions. +- Control the game, or see its pages, cookies, sessions or traffic. The [live game feed](#live-game-feed)'s events are all a plugin gets from the game itself. - See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either. -- Get real-time data. XP and profile data arrive about once a minute, and the timer sends no tick events. +- Get other players' data, chat, or anything the live game feed doesn't list. +- Get real-time XP or profile data. They arrive about once a minute (the live game feed has each fight as it happens), and the timer sends no tick events. - Use shortcut keys, sounds or desktop notifications. - Draw custom cards. Cards are FourFold's data cards. - Add a settings page behind the cog. Keep settings in your own panel. From 25bc3f3f64c63ec13b543fc34f3906ced03e7bf0 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:04:33 -0500 Subject: [PATCH 14/28] feat: count XP/hr from the live game feed's fights while it watches an account --- .../Tracking/XpTrackingSessionLiveTests.cs | 101 ++++++++++++++++++ .../Tracking/XpRateWindow.cs | 14 ++- .../Tracking/XpTrackingSession.cs | 68 +++++++++++- 3 files changed, 179 insertions(+), 4 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs new file mode 100644 index 0000000..70a451a --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs @@ -0,0 +1,101 @@ +using FourFoldAccountManager.Core.Tracking; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.Tracking; + +// The live game feed feeding the XP tracker. A wrong count here is wrong XP/hr and session XP in the tracker panel, +// the calculator, every overlay card and every plugin. +public sealed class XpTrackingSessionLiveTests +{ + private static readonly DateTimeOffset Start = new(2026, 10, 6, 12, 0, 0, TimeSpan.Zero); + + private static DateTimeOffset At(double minutes) => Start.AddMinutes(minutes); + + private static long Cap(int level) => 5L * level * (level + 1); + + // A polled profile: Savage at the given level and XP, and a Mage that never moves. + private static PlayerProgressSnapshot Poll(string active, int savageLevel, long savageXp) => + new("cody", active, + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Savage"] = new(savageLevel, savageXp, Cap(savageLevel), null), + ["Mage"] = new(3, 0, Cap(3), null) + }, + []); + + [Fact] + public void AFightAndAPollInTheSameWindowCountTheXpOnce() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0.1)); + session.ApplyLiveResult(At(0.5), "Savage", 300, 12, Cap(12) - 400); + session.ApplySnapshot(Poll("Savage", 12, 400), At(1)); // the same fight, as the poll saw it + session.ApplyLiveResult(At(1.5), "Savage", 300, 12, Cap(12) - 700); + session.ApplySnapshot(Poll("Savage", 12, 700), At(2)); + + Assert.Equal(600, session.SessionGain); + // 600 over the 1.9 watched minutes (0.1 to 2), the last half minute idle. + Assert.Equal(600 / 1.9 * 60, session.RatePerHour!.Value, 6); + } + + [Fact] + public void AWatchThatBeganBeforeTheLastPollCountsOnlyFightsAfterIt() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.ApplySnapshot(Poll("Savage", 12, 400), At(1)); // 300 counted from 0 to 1 + session.BeginLive(At(0.5)); // the socket opened before that poll + session.ApplyLiveResult(At(0.75), "Savage", 300, 12, Cap(12) - 400); // already in the poll + session.ApplyLiveResult(At(1.5), "Savage", 200, 12, Cap(12) - 600); + + Assert.Equal(500, session.SessionGain); + } + + [Fact] + public void TheFirstPollAfterALiveStretchIsABaseline() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(0.5), "Savage", 300, 12, Cap(12) - 400); + session.EndLive(); + session.ApplySnapshot(Poll("Savage", 12, 400), At(1)); // the fight's XP, already counted + + Assert.False(session.IsLive); + Assert.Equal(300, session.SessionGain); + + session.ApplySnapshot(Poll("Savage", 12, 450), At(2)); + Assert.Equal(350, session.SessionGain); + } + + [Fact] + public void TheLiveRateWaitsForAMinuteAndFallsWhileIdle() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(0.5), "Savage", 300, 12, Cap(12) - 400); + Assert.Null(session.RatePerHour); // 30 s watched + + session.ApplySnapshot(Poll("Savage", 12, 400), At(1)); // a minute watched, the last 30 s idle + Assert.Equal(18000, session.RatePerHour!.Value, 6); + + session.ApplySnapshot(Poll("Savage", 12, 400), At(3)); // two more idle minutes + Assert.Equal(6000, session.RatePerHour!.Value, 6); + } + + [Fact] + public void ARepeatedOrLateFightAddsNothing() + { + // No poll at all: an account without a ranking username still gets a live rate from its fights. + var session = new XpTrackingSession(); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(1), "Savage", 300, 12, 100); + session.ApplyLiveResult(At(1), "Savage", 300, 12, 100); + session.ApplyLiveResult(At(0.5), "Savage", 300, 12, 100); + + Assert.Equal(300, session.SessionGain); + Assert.Equal(18000, session.RatePerHour!.Value, 6); + } +} diff --git a/src/FourFoldAccountManager.Core/Tracking/XpRateWindow.cs b/src/FourFoldAccountManager.Core/Tracking/XpRateWindow.cs index e406429..51afe51 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpRateWindow.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpRateWindow.cs @@ -22,7 +22,12 @@ public void Add(DateTimeOffset from, DateTimeOffset to, long gain) Prune(to); } - public double? GetRate(DateTimeOffset now) + public double? GetRate(DateTimeOffset now) => GetRate(now, null, TimeSpan.Zero); + + // The rate over the hour ending at `now`. `openFrom` adds the stretch from then to `now` as watched time that gained + // nothing (the time since the live game feed's last fight). Null until the watched time in that hour reaches + // `minCovered`. + public double? GetRate(DateTimeOffset now, DateTimeOffset? openFrom, TimeSpan minCovered) { Prune(now); var start = now - TimeSpan.FromHours(1); @@ -42,7 +47,12 @@ public void Add(DateTimeOffset from, DateTimeOffset to, long gain) coveredSeconds += seconds; } - return coveredSeconds > 0 ? gain / coveredSeconds * 3600 : null; + if (openFrom is { } open && open < now) + { + coveredSeconds += (now - (open > start ? open : start)).TotalSeconds; + } + + return coveredSeconds > 0 && coveredSeconds >= minCovered.TotalSeconds ? gain / coveredSeconds * 3600 : null; } public void ClearIntervals() => _intervals.Clear(); diff --git a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs index 074423d..86bdbdf 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs @@ -2,11 +2,21 @@ namespace FourFoldAccountManager.Core.Tracking; public sealed class XpTrackingSession { + // A live rate needs this much watched time first, so the first fight can't read as millions an hour. + public static readonly TimeSpan LiveRateMinimum = TimeSpan.FromSeconds(60); + private readonly XpRateWindow _window = new(); private bool _hasFailedPoll; private PlayerProgressSnapshot? _baselineSnapshot; private DateTimeOffset? _baselineSampledAt; + // While the live game feed watches the account: the end of the last stretch counted, the watch start or the last + // fight. Null when it isn't watching. + private DateTimeOffset? _liveMark; + + // Set when a live stretch ends. The next poll only moves the baseline, because the fights counted that XP. + private bool _rebase; + public PlayerProgressSnapshot? LastSnapshot { get; private set; } public DateTimeOffset? LastSuccessfulAt { get; private set; } public double? RatePerHour { get; private set; } @@ -23,6 +33,7 @@ public sealed class XpTrackingSession : null; public bool IsStale { get; private set; } public bool IsStopped { get; private set; } + public bool IsLive => _liveMark is not null; public bool MissedPreviousSample { get; private set; } public bool ActiveClassUnavailable { get; private set; } public IReadOnlyList InvalidClassNames { get; private set; } = []; @@ -37,7 +48,17 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample MissedPreviousSample = _hasFailedPoll; ActiveClassUnavailable = string.IsNullOrWhiteSpace(snapshot.ActiveClassName); InvalidClassNames = []; - if (_hasFailedPoll || ActiveClassUnavailable) + if (IsLive || _rebase) + { + // The fights counted this XP: while live a poll adds no interval, and the first poll after a live stretch + // is a baseline. + _hasFailedPoll = false; + if (!IsLive) + { + _rebase = false; + } + } + else if (_hasFailedPoll || ActiveClassUnavailable) { // No trustworthy interval to measure after a missed poll or without an active class. _hasFailedPoll = false; @@ -62,7 +83,7 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample : []; } - RatePerHour = _window.GetRate(sampledAt); + RatePerHour = RateAt(sampledAt); LastSnapshot = snapshot; LastSuccessfulAt = sampledAt; _baselineSnapshot = snapshot; @@ -81,6 +102,49 @@ public void MarkFetchFailed() public void Stop() => IsStopped = true; + // The live game feed watches the account's game socket from `at`. A stretch never starts before the last poll, + // whose interval already counted the time up to it. + public void BeginLive(DateTimeOffset at) + { + if (IsStopped || IsLive) + { + return; + } + + _liveMark = LastSuccessfulAt is { } polled && polled > at ? polled : at; + } + + public void EndLive() + { + if (!IsLive) + { + return; + } + + _liveMark = null; + _rebase = true; + } + + // One fight's reward from the live game feed. It counts from the mark to this fight, so the time between fights is + // in the rate too. A late or repeated result, or one already inside a poll's interval, adds nothing. + public void ApplyLiveResult( + DateTimeOffset at, string? className, long expGained, int reachedLevel, long expNeededToNextLevel) + { + if (IsStopped || _liveMark is not { } mark || at <= mark) + { + return; + } + + _window.Add(mark, at, Math.Max(0, expGained)); + _liveMark = at; + RatePerHour = RateAt(at); + } + + // At a poll or a fight. While live, the time since the last fight counts as gaining nothing, so the rate falls while + // the account idles. + private double? RateAt(DateTimeOffset at) => + _liveMark is { } mark ? _window.GetRate(at, mark, LiveRateMinimum) : _window.GetRate(at); + private static PlayerProgressSnapshot ForClass(PlayerProgressSnapshot snapshot, string name) { var classes = new Dictionary(StringComparer.OrdinalIgnoreCase); From 090a31925396933a99048c6ec70def7b637e763f Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:08:31 -0500 Subject: [PATCH 15/28] feat: show each fight's exact level and XP over the last profile poll --- .../Tracking/XpTrackingSessionLiveTests.cs | 69 +++++++++++++++++++ .../LiveFeed/XpReconciler.cs | 2 +- .../Tracking/XpTrackingSession.cs | 67 +++++++++++++++++- 3 files changed, 135 insertions(+), 3 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs index 70a451a..a801c96 100644 --- a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs @@ -98,4 +98,73 @@ public void ARepeatedOrLateFightAddsNothing() Assert.Equal(300, session.SessionGain); Assert.Equal(18000, session.RatePerHour!.Value, 6); } + + [Fact] + public void AFightGivesTheExactProgressAcrossALevelUp() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, Cap(12) - 50), At(0)); + session.BeginLive(At(0)); + // The feed spells the class its own way; it must update the website's entry, not add a second one. + session.ApplyLiveResult(At(0.5), " savage", 200, 13, Cap(13) - 150); + + var display = session.DisplaySnapshot!; + var savage = display.Classes["Savage"]; + Assert.Equal((13, 150L, Cap(13)), (savage.Level, savage.CurrentXp, savage.NextLevelXp)); + Assert.Equal("Savage", display.ActiveClassName); + Assert.Equal(2, display.Classes.Count); + Assert.Equal(Cap(13) - 150, session.XpUntilNextLevel); + // The raw poll is untouched: persistence and the reconciler read it. + Assert.Equal(12, session.LastSnapshot!.Classes["Savage"].Level); + } + + [Fact] + public void AVeryHighLevelCapsTheLevelTotalLikeTheGame() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(0.5), "Savage", 1, 30000, 10); + + var savage = session.DisplaySnapshot!.Classes["Savage"]; + Assert.Equal(int.MaxValue, savage.NextLevelXp); + Assert.Equal(int.MaxValue - 10L, savage.CurrentXp); + } + + [Fact] + public void ALaggingPollKeepsTheLiveProgressAndALaterOneReplacesIt() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(0.9), "Savage", 300, 12, Cap(12) - 400); + + // Saved just before the fight landed: the display must not roll back. + session.ApplySnapshot(Poll("Savage", 12, 100), At(1)); + Assert.Equal(400, session.DisplaySnapshot!.Classes["Savage"].CurrentXp); + + // A second poll since the fight is the truth, even below the live value. + session.ApplySnapshot(Poll("Savage", 12, 350), At(2)); + Assert.Equal(350, session.DisplaySnapshot!.Classes["Savage"].CurrentXp); + } + + [Fact] + public void ANewerPollAheadOfTheFightOrOnAnotherClassReplacesTheLiveProgress() + { + var ahead = new XpTrackingSession(); + ahead.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + ahead.BeginLive(At(0)); + ahead.ApplyLiveResult(At(0.9), "Savage", 300, 12, Cap(12) - 400); + ahead.ApplySnapshot(Poll("Savage", 12, 450), At(1)); + Assert.Equal(450, ahead.DisplaySnapshot!.Classes["Savage"].CurrentXp); + + // A class switch in town, with no fight since: the poll's active class wins. + var switched = new XpTrackingSession(); + switched.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + switched.BeginLive(At(0)); + switched.ApplyLiveResult(At(0.5), "Savage", 300, 12, Cap(12) - 400); + switched.ApplySnapshot(Poll("Mage", 12, 400), At(1)); + Assert.Equal("Mage", switched.ActiveClassName); + Assert.Equal(Cap(3), switched.XpUntilNextLevel); + } } diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs index eedf585..5b0ff37 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -86,7 +86,7 @@ public void RecordSample( } // Matches the game's SkillCatalog.Normalize, so "Dark_Knight" and "dark knight" are the same class. - private static string NormalizeClass(string? name) => (name ?? string.Empty).Trim().Replace('_', ' ').ToLowerInvariant(); + internal static string NormalizeClass(string? name) => (name ?? string.Empty).Trim().Replace('_', ' ').ToLowerInvariant(); private static (string Name, ClassProfileSnapshot Class)? ActiveClass(PlayerProgressSnapshot snapshot) => snapshot.ActiveClassName is { } name && snapshot.Classes.TryGetValue(name, out var found) ? (name, found) : null; diff --git a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs index 86bdbdf..6483614 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs @@ -1,3 +1,5 @@ +using FourFoldAccountManager.Core.LiveFeed; + namespace FourFoldAccountManager.Core.Tracking; public sealed class XpTrackingSession @@ -17,14 +19,23 @@ public sealed class XpTrackingSession // Set when a live stretch ends. The next poll only moves the baseline, because the fights counted that XP. private bool _rebase; + // The active class's progress as the last fight left it. Laid over the last poll while it is the newer truth. + private LiveProgress? _liveProgress; + public PlayerProgressSnapshot? LastSnapshot { get; private set; } public DateTimeOffset? LastSuccessfulAt { get; private set; } public double? RatePerHour { get; private set; } public long SessionGain => _window.SessionGain; public IReadOnlyList Intervals => _window.Intervals; - public string? ActiveClassName => LastSnapshot?.ActiveClassName; + // The last poll with the live progress laid over it, while that progress is the newer truth (see + // LiveProgressApplies). Persistence, ProfileSampled and the reconciler use LastSnapshot, the raw poll. + public PlayerProgressSnapshot? DisplaySnapshot => + LastSnapshot is { } polled && _liveProgress is { } live && LiveProgressApplies(polled, live) + ? WithLiveProgress(polled, live) + : LastSnapshot; + public string? ActiveClassName => DisplaySnapshot?.ActiveClassName; public long? XpUntilNextLevel => - ActiveClassName is { } name && LastSnapshot?.Classes.TryGetValue(name, out var progress) == true + ActiveClassName is { } name && DisplaySnapshot?.Classes.TryGetValue(name, out var progress) == true ? progress.NextLevelXp - progress.CurrentXp : null; public double? HoursUntilNextLevel => @@ -45,6 +56,12 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample if (LastSuccessfulAt is { } previousTime && sampledAt <= previousTime) throw new ArgumentOutOfRangeException(nameof(sampledAt)); + // A poll can lag a fight by seconds, but never by two polls: from the second poll since it, the poll is the truth. + if (_liveProgress is { } progress && LastSuccessfulAt is { } previousPoll && progress.At <= previousPoll) + { + _liveProgress = null; + } + MissedPreviousSample = _hasFailedPoll; ActiveClassUnavailable = string.IsNullOrWhiteSpace(snapshot.ActiveClassName); InvalidClassNames = []; @@ -138,6 +155,15 @@ public void ApplyLiveResult( _window.Add(mark, at, Math.Max(0, expGained)); _liveMark = at; RatePerHour = RateAt(at); + // The result carries the whole state: the level reached and the XP still needed. The game levels up at most once + // per fight, so the level's total follows from the level. + if (!string.IsNullOrWhiteSpace(className)) + { + var level = Math.Max(1, reachedLevel); + var total = LevelTotal(level); + _liveProgress = new LiveProgress( + className.Trim(), level, Math.Max(0, total - Math.Max(0, expNeededToNextLevel)), total, at); + } } // At a poll or a fight. While live, the time since the last fight counts as gaining nothing, so the rate falls while @@ -174,4 +200,41 @@ public void ResetAll() ResetRate(); _window.ResetSession(); } + + // The game's ExpNeededForNextLevel: 5·L·(L+1), capped at int.MaxValue. + private static long LevelTotal(int level) + { + long capped = Math.Min(level, 1_000_000); + return Math.Min(5 * capped * (capped + 1), int.MaxValue); + } + + // Newer than the last poll, or the poll's own active class and ahead of it: the poll that was saved just before + // the fight landed. + private bool LiveProgressApplies(PlayerProgressSnapshot polled, LiveProgress live) + { + if (LastSuccessfulAt is not { } polledAt || live.At > polledAt) + { + return true; + } + + return polled.ActiveClassName is { } active && + XpReconciler.NormalizeClass(active) == XpReconciler.NormalizeClass(live.ClassName) && + polled.Classes.TryGetValue(active, out var current) && + (live.Level > current.Level || (live.Level == current.Level && live.CurrentXp > current.CurrentXp)); + } + + // The poll with the live class active and its level and XP from the fight. Its stats and equipment stay the + // poll's. The class keeps the website's spelling when the poll lists it. + private static PlayerProgressSnapshot WithLiveProgress(PlayerProgressSnapshot polled, LiveProgress live) + { + var key = polled.Classes.Keys.FirstOrDefault(name => + XpReconciler.NormalizeClass(name) == XpReconciler.NormalizeClass(live.ClassName)) ?? live.ClassName; + var classes = new Dictionary(polled.Classes, StringComparer.OrdinalIgnoreCase); + classes[key] = classes.TryGetValue(key, out var existing) + ? existing with { Level = live.Level, CurrentXp = live.CurrentXp, NextLevelXp = live.NextLevelXp } + : new ClassProfileSnapshot(live.Level, live.CurrentXp, live.NextLevelXp, null); + return polled with { ActiveClassName = key, Classes = classes }; + } + + private sealed record LiveProgress(string ClassName, int Level, long CurrentXp, long NextLevelXp, DateTimeOffset At); } From 8068e64e121be11dcc1281a5d67336a110ecc446 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:12:13 -0500 Subject: [PATCH 16/28] feat: let the live game feed drive the XP tracker, with the profile poll as the fallback --- PLUGIN_AUTHORS.md | 8 ++-- .../Services/LiveFeed/LiveGameFeed.cs | 43 +++++++++++++++++++ .../Services/XpTrackerCoordinator.cs | 35 ++++++++++++--- 3 files changed, 78 insertions(+), 8 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index a614a98..3b5b69f 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -134,7 +134,7 @@ fourfold.xp.onUpdated(({ accountId }) => console.log('new XP data for', accountI | `nextLevelXp` | number or null | XP the current level needs in total. | | `xpUntilNextLevel` | number or null | `nextLevelXp - currentXp`. | | `hoursUntilNextLevel` | number or null | At the current XP/hr. `null` when there is no rate yet. | -| `xpPerHour` | number or null | The current rate. | +| `xpPerHour` | number or null | The current rate, over the last hour. While the [live game feed](#live-game-feed) watches the account it follows each fight. | | `sessionXp` | number | XP gained this session. `0` when unknown. | | `classes` | array | `{ className, level, currentXp, nextLevelXp }` for every class. May be empty. | | `updatedAt` | string or null | Time of the last successful read, as an ISO 8601 date. | @@ -142,7 +142,9 @@ fourfold.xp.onUpdated(({ accountId }) => console.log('new XP data for', accountI FourFold reads an account's XP only while that account is open, and only if FourFold's own XP tracker can read it. If the XP tracker plugin shows no data for an account, neither will yours. For a closed account the number and text fields are `null`, `classes` is empty and `isStale` is `true`. An id that isn't one of the user's accounts is rejected with `invalid-argument`. -`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes, about once a minute for each open account. +While the [live game feed](#live-game-feed) watches an account, `className`, `level`, `currentXp`, `nextLevelXp`, `xpUntilNextLevel`, `hoursUntilNextLevel`, `xpPerHour`, `sessionXp` and the active class's row in `classes` follow each fight. `updatedAt` and `isStale` still describe the last read. Otherwise the values come from the read, about once a minute. + +`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes: about once a minute for each open account, and after each fight while the live game feed watches it. ### Stats @@ -441,7 +443,7 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve - Control the game, or see its pages, cookies, sessions or traffic. The [live game feed](#live-game-feed)'s events are all a plugin gets from the game itself. - See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either. - Get other players' data, chat, or anything the live game feed doesn't list. -- Get real-time XP or profile data. They arrive about once a minute (the live game feed has each fight as it happens), and the timer sends no tick events. +- Get real-time profile data: silver, gold and location arrive about once a minute. XP follows each fight while the live game feed watches the account, and the timer sends no tick events. - Use shortcut keys, sounds or desktop notifications. - Draw custom cards. Cards are FourFold's data cards. - Add a settings page behind the cog. Keep settings in your own panel. diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index de4c041..7e7bed6 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -2,6 +2,7 @@ using System.Threading.Channels; using System.Windows.Threading; using FourFoldAccountManager.Core.LiveFeed; +using FourFoldAccountManager.Core.Plugins; using FourFoldAccountManager.Core.Tracking; using Microsoft.Web.WebView2.Core; @@ -106,14 +107,21 @@ public void SetEnabled(bool enabled) } LiveStatus status; + Guid[] watched; lock (_gate) { + watched = _accounts.Keys.ToArray(); _accounts.Clear(); _state = enabled ? LiveFeedState.Active : LiveFeedState.Off; _reason = null; status = CurrentStatus(); } + foreach (var accountId in watched) + { + Tell(tracker => tracker.EndLive(accountId)); + } + Post("live.statusChanged", status); } @@ -268,14 +276,21 @@ private void OnSocketCreated(TapEvent tapEvent) return; } + var watching = false; lock (_gate) { if (_state == LiveFeedState.Active) { // A new game socket (a login or a reconnect) starts the account's state and its canary afresh. _accounts[tapEvent.AccountId] = new AccountState(id.GetString()!, tapEvent.At); + watching = true; } } + + if (watching) + { + Tell(tracker => tracker.BeginLive(tapEvent.AccountId, tapEvent.At)); + } } private void OnFrame(TapEvent tapEvent) @@ -325,6 +340,7 @@ private void OnFrame(TapEvent tapEvent) } var posts = new List<(string Name, object Data)>(); + var results = new List(); bool canaryFailed; lock (_gate) { @@ -348,6 +364,7 @@ private void OnFrame(TapEvent tapEvent) break; case BattleResult battle: _reconciler.RecordResult(tapEvent.AccountId, tapEvent.At, battle.ClassName, battle.ExpGained); + results.Add(battle); break; case ModerationDisconnected: account.DisconnectPosted = true; @@ -370,6 +387,13 @@ private void OnFrame(TapEvent tapEvent) return; } + foreach (var battle in results) + { + Tell(tracker => tracker.ApplyLiveResult(tapEvent.AccountId, tapEvent.At, + PluginText.PublicGameText(battle.ClassName), battle.ExpGained, battle.ReachedLevel, + battle.ExpNeededToNextLevel)); + } + foreach (var (name, payload) in posts) { Post(name, payload); @@ -394,6 +418,8 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at post = _state == LiveFeedState.Active && account.LoginPosted && !account.DisconnectPosted; } + Tell(tracker => tracker.EndLive(accountId)); + if (post) { Post("session.disconnected", LiveFeedPayloads.Disconnected(accountId, at)); @@ -403,6 +429,7 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at private void MarkUnavailable(string reason) { LiveStatus status; + Guid[] watched; lock (_gate) { if (_state != LiveFeedState.Active) @@ -412,10 +439,16 @@ private void MarkUnavailable(string reason) _state = LiveFeedState.Unavailable; _reason = reason; + watched = _accounts.Keys.ToArray(); _accounts.Clear(); status = CurrentStatus(); } + foreach (var accountId in watched) + { + Tell(tracker => tracker.EndLive(accountId)); + } + Post("live.statusChanged", status); } @@ -438,6 +471,16 @@ private void Post(string name, object? data) => } }); + // The XP tracker lives on the UI thread, like the poll that feeds it. Queued in order with the plugin posts. + private void Tell(Action call) => + _dispatcher.InvokeAsync(() => + { + if (!_disposed) + { + call(_tracker); + } + }); + private static bool IsGameSocket(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == "wss" && diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index 6d64ef3..4167a25 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -73,7 +73,13 @@ public async Task VerifyPlayerAsync(int playerId, string username) account.Id, account.Username, account.Session.RatePerHour, account.Session.SessionGain, account.Session.ActiveClassName, account.Session.XpUntilNextLevel, account.Session.HoursUntilNextLevel, - account.Session.LastSuccessfulAt, account.Status, account.Session.IsStale)).ToArray(); + account.Session.LastSuccessfulAt, StatusOf(account), account.Session.IsStale)).ToArray(); + + // While the live game feed watches the account, the two ordinary statuses say so. Problems still show as they are. + private static string StatusOf(TrackedAccount account) => + account.Session.IsLive && account.Status is "Tracking" or "Collecting baseline" + ? (account.Session.RatePerHour is null ? "Live; collecting a minute first" : "Tracking live") + : account.Status; public IReadOnlyList<(Guid AccountId, int PlayerId, string Username)> GetActiveLeaderboardProfiles() { @@ -84,9 +90,10 @@ public async Task VerifyPlayerAsync(int playerId, string username) .ToArray(); } - // The newest profile fetched this session for an open account; null until its first successful fetch. + // The newest profile fetched this session for an open account, with the live game feed's last fight laid over it; + // null until its first successful fetch. public PlayerProgressSnapshot? GetLatestSnapshot(Guid accountId) => - _active.TryGetValue(accountId, out var account) ? account.LatestSnapshot : null; + _active.TryGetValue(accountId, out var account) ? account.Session.DisplaySnapshot : null; internal XpTrackingSession? GetSessionForTesting(Guid accountId) => _active.TryGetValue(accountId, out var account) ? account.Session : null; @@ -145,6 +152,26 @@ public void ResetAll(Guid accountId) } } + // The live game feed's calls, made on the UI thread like the poll's. An account that isn't tracked is ignored: its + // panel may have closed while the call was on its way. + public void BeginLive(Guid accountId, DateTimeOffset at) => Live(accountId, session => session.BeginLive(at)); + + public void EndLive(Guid accountId) => Live(accountId, session => session.EndLive()); + + public void ApplyLiveResult( + Guid accountId, DateTimeOffset at, string? className, long expGained, int reachedLevel, long expNeededToNextLevel) => + Live(accountId, session => session.ApplyLiveResult(at, className, expGained, reachedLevel, expNeededToNextLevel)); + + private void Live(Guid accountId, Action change) + { + _dispatcher.VerifyAccess(); + if (_active.TryGetValue(accountId, out var account)) + { + change(account.Session); + NotifyChanged(); + } + } + public void RefreshActiveAccounts(IReadOnlyList visibleAccountIds) { _dispatcher.VerifyAccess(); @@ -264,7 +291,6 @@ result.Status is PlayerProfileReadStatus.RankingUnavailable or account.PlayerId = result.PlayerId; var sampledAt = DateTimeOffset.UtcNow; account.Session.ApplySnapshot(profile, sampledAt); - account.LatestSnapshot = profile; // A handler that throws must not turn a good read into a failed one. try { ProfileSampled?.Invoke(account.Id, profile, sampledAt); } catch (Exception) { } @@ -314,6 +340,5 @@ private sealed class TrackedAccount(Guid id, string? username, int? playerId) public XpTrackingSession Session { get; } = new(); public string Status { get; set; } = "Collecting baseline"; public bool CanRetryProfileRead { get; set; } = true; - public PlayerProgressSnapshot? LatestSnapshot { get; set; } } } From 024eb7ca7f868cceb0cb4eaa019c12922c2ac1fa Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:16:15 -0500 Subject: [PATCH 17/28] fix: queue the XP tracker's live calls in the order the feed's state changed --- .../Services/LiveFeed/LiveGameFeed.cs | 59 ++++++++----------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 7e7bed6..27b71cc 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -107,21 +107,14 @@ public void SetEnabled(bool enabled) } LiveStatus status; - Guid[] watched; lock (_gate) { - watched = _accounts.Keys.ToArray(); - _accounts.Clear(); + EndAllLive(); _state = enabled ? LiveFeedState.Active : LiveFeedState.Off; _reason = null; status = CurrentStatus(); } - foreach (var accountId in watched) - { - Tell(tracker => tracker.EndLive(accountId)); - } - Post("live.statusChanged", status); } @@ -276,21 +269,15 @@ private void OnSocketCreated(TapEvent tapEvent) return; } - var watching = false; lock (_gate) { if (_state == LiveFeedState.Active) { // A new game socket (a login or a reconnect) starts the account's state and its canary afresh. _accounts[tapEvent.AccountId] = new AccountState(id.GetString()!, tapEvent.At); - watching = true; + Tell(tracker => tracker.BeginLive(tapEvent.AccountId, tapEvent.At)); } } - - if (watching) - { - Tell(tracker => tracker.BeginLive(tapEvent.AccountId, tapEvent.At)); - } } private void OnFrame(TapEvent tapEvent) @@ -379,6 +366,15 @@ private void OnFrame(TapEvent tapEvent) // Every login sends both; 60 s of traffic without them means the ids no longer match the game. canaryFailed = !(account.SawLogin && account.SawScene) && tapEvent.At - account.OpenedAt > CanaryTimeout; + if (!canaryFailed) + { + foreach (var battle in results) + { + Tell(tracker => tracker.ApplyLiveResult(tapEvent.AccountId, tapEvent.At, + PluginText.PublicGameText(battle.ClassName), battle.ExpGained, battle.ReachedLevel, + battle.ExpNeededToNextLevel)); + } + } } if (canaryFailed) @@ -387,13 +383,6 @@ private void OnFrame(TapEvent tapEvent) return; } - foreach (var battle in results) - { - Tell(tracker => tracker.ApplyLiveResult(tapEvent.AccountId, tapEvent.At, - PluginText.PublicGameText(battle.ClassName), battle.ExpGained, battle.ReachedLevel, - battle.ExpNeededToNextLevel)); - } - foreach (var (name, payload) in posts) { Post(name, payload); @@ -413,13 +402,12 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at } _accounts.Remove(accountId); + Tell(tracker => tracker.EndLive(accountId)); // A server kick already told plugins why; the socket closing after it isn't a second disconnect. Plugins // weren't told this session started (no successful login), so they aren't told it ended. post = _state == LiveFeedState.Active && account.LoginPosted && !account.DisconnectPosted; } - Tell(tracker => tracker.EndLive(accountId)); - if (post) { Post("session.disconnected", LiveFeedPayloads.Disconnected(accountId, at)); @@ -429,7 +417,6 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at private void MarkUnavailable(string reason) { LiveStatus status; - Guid[] watched; lock (_gate) { if (_state != LiveFeedState.Active) @@ -439,16 +426,10 @@ private void MarkUnavailable(string reason) _state = LiveFeedState.Unavailable; _reason = reason; - watched = _accounts.Keys.ToArray(); - _accounts.Clear(); + EndAllLive(); status = CurrentStatus(); } - foreach (var accountId in watched) - { - Tell(tracker => tracker.EndLive(accountId)); - } - Post("live.statusChanged", status); } @@ -471,7 +452,19 @@ private void Post(string name, object? data) => } }); - // The XP tracker lives on the UI thread, like the poll that feeds it. Queued in order with the plugin posts. + // Under _gate: stops watching every account and tells the tracker. + private void EndAllLive() + { + foreach (var accountId in _accounts.Keys) + { + Tell(tracker => tracker.EndLive(accountId)); + } + + _accounts.Clear(); + } + + // The XP tracker lives on the UI thread, like the poll that feeds it. Called under _gate so the tracker sees calls in + // the order the feed's state changed; InvokeAsync only queues, so it can't block there. private void Tell(Action call) => _dispatcher.InvokeAsync(() => { From 7ae99eab959ad77e813f45fd58c821499a413309 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:31:03 -0500 Subject: [PATCH 18/28] fix: fall back to polling when battle results stop arriving A game update that changes only the battle result leaves login and scene decoding, so the feed stayed active with no results and XP/hr decayed to 0. Two compared windows in a row with polled XP and no results now mark the feed unavailable. --- .../LiveFeed/XpReconcilerTests.cs | 69 +++++++++++++++++++ .../LiveFeed/XpReconciler.cs | 36 ++++++++-- .../Services/LiveFeed/LiveGameFeed.cs | 10 ++- 3 files changed, 109 insertions(+), 6 deletions(-) create mode 100644 src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs new file mode 100644 index 0000000..5a44fd3 --- /dev/null +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs @@ -0,0 +1,69 @@ +using FourFoldAccountManager.Core.LiveFeed; +using FourFoldAccountManager.Core.Tracking; +using Xunit; + +namespace FourFoldAccountManager.Core.Tests.LiveFeed; + +// The reconciler's call to give up on the feed. Missing it leaves every account live with no battle results, so XP/hr +// decays to 0 while the account farms; a false call drops the feed for a timing quirk. +public sealed class XpReconcilerTests +{ + private static readonly DateTimeOffset Start = new(2026, 10, 6, 12, 0, 0, TimeSpan.Zero); + private static readonly Guid Account = Guid.NewGuid(); + + private static DateTimeOffset At(double minutes) => Start.AddMinutes(minutes); + + private static long Cap(int level) => 5L * level * (level + 1); + + // A polled profile: Savage active at level 12 with the given XP, and a Mage that never moves. + private static PlayerProgressSnapshot Poll(long savageXp) => + new("cody", "Savage", + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Savage"] = new(12, savageXp, Cap(12), null), + ["Mage"] = new(3, 0, Cap(3), null) + }, + []); + + private static bool Sample(XpReconciler reconciler, long savageXp, double minutes) => + reconciler.RecordSample(Account, Poll(savageXp), At(minutes), At(-1)); + + [Fact] + public void TwoWatchedWindowsWithXpAndNoResultsGiveUpOnTheFeed() + { + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + + Assert.False(Sample(reconciler, 200, 1)); + Assert.True(Sample(reconciler, 300, 2)); + } + + [Fact] + public void AMatchingResultInBetweenStartsTheCountAgain() + { + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + Assert.False(Sample(reconciler, 200, 1)); + reconciler.RecordResult(Account, At(1.5), "Savage", 100); + Assert.False(Sample(reconciler, 300, 2)); + + Assert.False(Sample(reconciler, 400, 3)); + Assert.True(Sample(reconciler, 500, 4)); + } + + [Fact] + public void ABattleCountedAWindowLateNeverGivesUpOnTheFeed() + { + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + // The poll sees the XP, the result lands just after it: +x, then -x. Then the other way round. + Assert.False(Sample(reconciler, 200, 1)); + reconciler.RecordResult(Account, At(1.01), "Savage", 100); + Assert.False(Sample(reconciler, 200, 2)); + reconciler.RecordResult(Account, At(2.99), "Savage", 100); + Assert.False(Sample(reconciler, 200, 3)); + Assert.False(Sample(reconciler, 300, 4)); + + Assert.Equal((4, 0), (reconciler.Matched, reconciler.Mismatched)); + } +} diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs index 5b0ff37..ba9599b 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -14,6 +14,10 @@ public sealed class XpReconciler // battle that ends just before a poll can be counted a window late: +x, then -x. That pair counts as two matches. private readonly Dictionary _openMismatches = []; + // Each account's compared windows in a row where the poll gained XP and the feed reported none. A game update that + // changes only the battle result leaves the feed active with no results; one such window can be the timing pair. + private readonly Dictionary _missedResults = []; + public int Matched { get; private set; } public int Mismatched { get; private set; } @@ -31,7 +35,8 @@ public void RecordResult(Guid accountId, DateTimeOffset at, string className, lo } // watchedSince: when the feed started watching this account's current game socket, or null when it isn't watching. - public void RecordSample( + // True when battle results have stopped arriving for this account: the feed should stop being trusted. + public bool RecordSample( Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt, DateTimeOffset? watchedSince) { var hadPrevious = _lastSamples.TryGetValue(accountId, out var previous); @@ -50,7 +55,7 @@ public void RecordSample( { Skipped++; _openMismatches.Remove(accountId); - return; + return false; } var polled = after.Class.CurrentXp - before.Class.CurrentXp; @@ -63,7 +68,27 @@ public void RecordSample( // No battle and no XP change proves nothing about the feed, so it isn't evidence either way. Skipped++; _openMismatches.Remove(accountId); - return; + return false; + } + + // Two in a row rules out the +x/-x timing pair: the second window of a pair has fed > 0. + var stopped = false; + if (polled > 0 && fed == 0) + { + var missed = _missedResults.GetValueOrDefault(accountId) + 1; + stopped = missed >= 2; + if (stopped) + { + _missedResults.Remove(accountId); + } + else + { + _missedResults[accountId] = missed; + } + } + else + { + _missedResults.Remove(accountId); } var difference = fed - polled; @@ -71,18 +96,19 @@ public void RecordSample( { Matched++; _openMismatches.Remove(accountId); - return; + return stopped; } if (_openMismatches.Remove(accountId, out var open) && open == -difference) { Mismatched--; Matched += 2; - return; + return stopped; } Mismatched++; _openMismatches[accountId] = difference; + return stopped; } // Matches the game's SkillCatalog.Normalize, so "Dark_Knight" and "dark knight" are the same class. diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 27b71cc..1597617 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -189,13 +189,21 @@ private void OnViewClosing(Guid accountId) private void OnProfileSampled(Guid accountId, PlayerProgressSnapshot snapshot, DateTimeOffset sampledAt) { + bool resultsStopped; lock (_gate) { // The window only counts when the feed watched this account's game socket for all of it. var watchedSince = _state == LiveFeedState.Active && _accounts.TryGetValue(accountId, out var account) ? account.OpenedAt : (DateTimeOffset?)null; - _reconciler.RecordSample(accountId, snapshot, sampledAt, watchedSince); + resultsStopped = _reconciler.RecordSample(accountId, snapshot, sampledAt, watchedSince); + } + + // A game update can change only the battle result: login and scene still decode, so nothing else notices. + // MarkUnavailable takes _gate itself. + if (resultsStopped) + { + MarkUnavailable("Battle results stopped arriving. The game may have updated."); } } From 7744d5f98e9a7d1add65fcddf1b5c5385f66047f Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:32:25 -0500 Subject: [PATCH 19/28] fix: keep idle time, reset from the press and don't double-count after a live stretch - EndLive(at) stores the stretch since the last fight as watched time that gained nothing, so XP/hr doesn't jump back up after a disconnect or F5. - ResetRate/ResetAll(now) move a live account's mark to the press. - The rebase poll uses the live progress as its baseline when the poll lags the last fight, so the next poll doesn't count that fight again. - A poll while live no longer reports a partial interval. --- .../Tracking/XpTrackingSessionLiveTests.cs | 49 ++++++++++++++++- .../Tracking/XpTrackingSession.cs | 53 ++++++++++++++----- .../Services/LiveFeed/LiveGameFeed.cs | 5 +- .../Services/XpTrackerCoordinator.cs | 6 +-- 4 files changed, 94 insertions(+), 19 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs index a801c96..eed3c72 100644 --- a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs @@ -59,7 +59,7 @@ public void TheFirstPollAfterALiveStretchIsABaseline() session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); session.BeginLive(At(0)); session.ApplyLiveResult(At(0.5), "Savage", 300, 12, Cap(12) - 400); - session.EndLive(); + session.EndLive(At(0.75)); session.ApplySnapshot(Poll("Savage", 12, 400), At(1)); // the fight's XP, already counted Assert.False(session.IsLive); @@ -167,4 +167,51 @@ public void ANewerPollAheadOfTheFightOrOnAnotherClassReplacesTheLiveProgress() Assert.Equal("Mage", switched.ActiveClassName); Assert.Equal(Cap(3), switched.XpUntilNextLevel); } + + [Fact] + public void TheIdleStretchBeforeALiveStretchEndsStaysInTheRate() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(1), "Savage", 300, 12, Cap(12) - 400); + session.EndLive(At(5)); // four idle minutes, then a disconnect + session.ApplySnapshot(Poll("Savage", 12, 400), At(6)); + + // 300 over the 5 watched minutes, not over the 1 minute of the fight. + Assert.Equal(3600, session.RatePerHour!.Value, 6); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void AResetWhileLiveStartsTheRateFromThePress(bool all) + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(1), "Savage", 200, 12, Cap(12) - 300); + if (all) session.ResetAll(At(10)); else session.ResetRate(At(10)); + session.ApplyLiveResult(At(11), "Savage", 300, 12, Cap(12) - 600); + session.ApplySnapshot(Poll("Savage", 12, 600), At(12)); + + Assert.True(session.IsLive); + // 300 over the 2 watched minutes since the press. + Assert.Equal(9000, session.RatePerHour!.Value, 6); + Assert.Equal(all ? 300 : 500, session.SessionGain); + } + + [Fact] + public void ALaggingPollAfterALiveStretchDoesNotCountTheFightAgain() + { + var session = new XpTrackingSession(); + session.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + session.BeginLive(At(0)); + session.ApplyLiveResult(At(0.9), "Savage", 300, 12, Cap(12) - 400); + session.EndLive(At(0.95)); + session.ApplySnapshot(Poll("Savage", 12, 100), At(1)); // saved just before the fight landed + session.ApplySnapshot(Poll("Savage", 12, 400), At(2)); // the same fight, which the live stretch counted + + Assert.Equal(300, session.SessionGain); + } } diff --git a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs index 6483614..b88db68 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs @@ -65,14 +65,25 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample MissedPreviousSample = _hasFailedPoll; ActiveClassUnavailable = string.IsNullOrWhiteSpace(snapshot.ActiveClassName); InvalidClassNames = []; + var baseline = snapshot; if (IsLive || _rebase) { // The fights counted this XP: while live a poll adds no interval, and the first poll after a live stretch // is a baseline. _hasFailedPoll = false; - if (!IsLive) + if (IsLive) + { + // Live counted everything, so a failed poll leaves no partial interval. + MissedPreviousSample = false; + } + else { _rebase = false; + // A poll that lags the last fight would make the next poll count that fight's XP a second time. + if (_liveProgress is { } live && IsAhead(snapshot, live)) + { + baseline = WithLiveProgress(snapshot, live); + } } } else if (_hasFailedPoll || ActiveClassUnavailable) @@ -80,11 +91,11 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample // No trustworthy interval to measure after a missed poll or without an active class. _hasFailedPoll = false; } - else if (_baselineSnapshot is { } baseline && _baselineSampledAt is { } from) + else if (_baselineSnapshot is { } previous && _baselineSampledAt is { } from) { var activeClassName = snapshot.ActiveClassName!; var gain = XpProgressCalculator.Calculate( - ForClass(baseline, activeClassName), ForClass(snapshot, activeClassName)); + ForClass(previous, activeClassName), ForClass(snapshot, activeClassName)); InvalidClassNames = gain.InvalidClasses; if (gain.ValidClassCount > 0) { @@ -103,7 +114,7 @@ public void ApplySnapshot(PlayerProgressSnapshot snapshot, DateTimeOffset sample RatePerHour = RateAt(sampledAt); LastSnapshot = snapshot; LastSuccessfulAt = sampledAt; - _baselineSnapshot = snapshot; + _baselineSnapshot = baseline; _baselineSampledAt = sampledAt; IsStale = false; } @@ -131,13 +142,20 @@ public void BeginLive(DateTimeOffset at) _liveMark = LastSuccessfulAt is { } polled && polled > at ? polled : at; } - public void EndLive() + // The stretch since the last fight was watched and gained nothing: without it, XP/hr jumps back up after a + // disconnect, F5 or feed-off that follows idle time. + public void EndLive(DateTimeOffset at) { - if (!IsLive) + if (_liveMark is not { } mark) { return; } + if (at > mark) + { + _window.Add(mark, at, 0); + } + _liveMark = null; _rebase = true; } @@ -183,7 +201,7 @@ private static PlayerProgressSnapshot ForClass(PlayerProgressSnapshot snapshot, }; } - public void ResetRate() + public void ResetRate(DateTimeOffset now) { _window.ClearIntervals(); _baselineSnapshot = null; @@ -193,11 +211,16 @@ public void ResetRate() MissedPreviousSample = false; ActiveClassUnavailable = false; InvalidClassNames = []; + // A live account stays live and keeps its live progress; its new rate starts from the press, not the last fight. + if (_liveMark is { } mark && now > mark) + { + _liveMark = now; + } } - public void ResetAll() + public void ResetAll(DateTimeOffset now) { - ResetRate(); + ResetRate(now); _window.ResetSession(); } @@ -217,12 +240,16 @@ private bool LiveProgressApplies(PlayerProgressSnapshot polled, LiveProgress liv return true; } - return polled.ActiveClassName is { } active && - XpReconciler.NormalizeClass(active) == XpReconciler.NormalizeClass(live.ClassName) && - polled.Classes.TryGetValue(active, out var current) && - (live.Level > current.Level || (live.Level == current.Level && live.CurrentXp > current.CurrentXp)); + return IsAhead(polled, live); } + // The fight was on the poll's own active class and left it further on than the poll shows. + private static bool IsAhead(PlayerProgressSnapshot polled, LiveProgress live) => + polled.ActiveClassName is { } active && + XpReconciler.NormalizeClass(active) == XpReconciler.NormalizeClass(live.ClassName) && + polled.Classes.TryGetValue(active, out var current) && + (live.Level > current.Level || (live.Level == current.Level && live.CurrentXp > current.CurrentXp)); + // The poll with the live class active and its level and XP from the fight. Its stats and equipment stay the // poll's. The class keeps the website's spelling when the poll lists it. private static PlayerProgressSnapshot WithLiveProgress(PlayerProgressSnapshot polled, LiveProgress live) diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 1597617..2bd0897 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -410,7 +410,7 @@ private void OnSocketClosed(Guid accountId, string? requestId, DateTimeOffset at } _accounts.Remove(accountId); - Tell(tracker => tracker.EndLive(accountId)); + Tell(tracker => tracker.EndLive(accountId, at)); // A server kick already told plugins why; the socket closing after it isn't a second disconnect. Plugins // weren't told this session started (no successful login), so they aren't told it ended. post = _state == LiveFeedState.Active && account.LoginPosted && !account.DisconnectPosted; @@ -463,9 +463,10 @@ private void Post(string name, object? data) => // Under _gate: stops watching every account and tells the tracker. private void EndAllLive() { + var at = _clock.GetUtcNow(); foreach (var accountId in _accounts.Keys) { - Tell(tracker => tracker.EndLive(accountId)); + Tell(tracker => tracker.EndLive(accountId, at)); } _accounts.Clear(); diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index 4167a25..913a15c 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -137,7 +137,7 @@ public void ResetRate(Guid accountId) _dispatcher.VerifyAccess(); if (_active.TryGetValue(accountId, out var account)) { - account.Session.ResetRate(); + account.Session.ResetRate(DateTimeOffset.UtcNow); NotifyChanged(); } } @@ -147,7 +147,7 @@ public void ResetAll(Guid accountId) _dispatcher.VerifyAccess(); if (_active.TryGetValue(accountId, out var account)) { - account.Session.ResetAll(); + account.Session.ResetAll(DateTimeOffset.UtcNow); NotifyChanged(); } } @@ -156,7 +156,7 @@ public void ResetAll(Guid accountId) // panel may have closed while the call was on its way. public void BeginLive(Guid accountId, DateTimeOffset at) => Live(accountId, session => session.BeginLive(at)); - public void EndLive(Guid accountId) => Live(accountId, session => session.EndLive()); + public void EndLive(Guid accountId, DateTimeOffset at) => Live(accountId, session => session.EndLive(at)); public void ApplyLiveResult( Guid accountId, DateTimeOffset at, string? className, long expGained, int reachedLevel, long expNeededToNextLevel) => From 481e258e1b98cfece8727112ee7655b73271aef2 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:32:47 -0500 Subject: [PATCH 20/28] fix: combine a frame's battle results and keep a bad tracker call from crashing the app Results in one frame share its time, so the session dropped every one but the first. The feed now sends their sum with the last result's state. A throwing call queued to the UI thread is swallowed, unlogged, like the worker's. --- .../Services/LiveFeed/LiveGameFeed.cs | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs index 2bd0897..9b43231 100644 --- a/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs +++ b/src/FourFoldAccountManager.Desktop/Services/LiveFeed/LiveGameFeed.cs @@ -374,14 +374,14 @@ private void OnFrame(TapEvent tapEvent) // Every login sends both; 60 s of traffic without them means the ids no longer match the game. canaryFailed = !(account.SawLogin && account.SawScene) && tapEvent.At - account.OpenedAt > CanaryTimeout; - if (!canaryFailed) + // One call per frame: the results share the frame's time, and the session ignores a second fight at the same + // moment. The last result holds the state they left. + if (!canaryFailed && results.Count > 0) { - foreach (var battle in results) - { - Tell(tracker => tracker.ApplyLiveResult(tapEvent.AccountId, tapEvent.At, - PluginText.PublicGameText(battle.ClassName), battle.ExpGained, battle.ReachedLevel, - battle.ExpNeededToNextLevel)); - } + var last = results[^1]; + var expGained = results.Sum(battle => (long)battle.ExpGained); + Tell(tracker => tracker.ApplyLiveResult(tapEvent.AccountId, tapEvent.At, + PluginText.PublicGameText(last.ClassName), expGained, last.ReachedLevel, last.ExpNeededToNextLevel)); } } @@ -477,9 +477,16 @@ private void EndAllLive() private void Tell(Action call) => _dispatcher.InvokeAsync(() => { - if (!_disposed) + // One bad call must never crash the app. Nothing is logged, as in the worker: the call carries game data. + try + { + if (!_disposed) + { + call(_tracker); + } + } + catch (Exception) { - call(_tracker); } }); From ecf8fb11a30177fe4851e79670feb93ba081109b Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:32:56 -0500 Subject: [PATCH 21/28] docs: say what follows each fight in the plugin authors' limits and stats --- PLUGIN_AUTHORS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index 3b5b69f..aabaf4b 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -153,7 +153,7 @@ const stats = await fourfold.stats.get(account.id); if (stats) console.log(stats.className, stats.level, stats.hp, stats.attack); ``` -`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`. +`fourfold.stats.get(accountId)` returns `{ className, level, hp, sp, attack, magic, skill, speed, luck, defense, resistance, equipment }` for the account's active class, or `null` when the account is closed or hasn't been read yet. There is no stats event: read `stats.get` again when `xp.onUpdated` fires. While the live game feed watches the account, `level` follows each fight; the stats themselves come from the last read. `hp` to `resistance` are numbers, or `null` when unknown. `equipment` is `{ armor, helmet, hair, weapon }`: each is the slot as the profile page words it, at most 64 characters, or `null` when unknown. An empty slot comes through as the page's own word for it (`Empty`, say), not as `null`. A plugin that reads `equipment` needs `"apiVersion": 2`. An unknown account id is rejected with `invalid-argument`. ### Profile @@ -443,7 +443,8 @@ If the user switches the plugin off in the plugin list, its cards are hidden eve - Control the game, or see its pages, cookies, sessions or traffic. The [live game feed](#live-game-feed)'s events are all a plugin gets from the game itself. - See logins: usernames, emails and passwords are never exposed. Plugins can't see other plugins or any file outside their own folder either. - Get other players' data, chat, or anything the live game feed doesn't list. -- Get real-time profile data: silver, gold and location arrive about once a minute. XP follows each fight while the live game feed watches the account, and the timer sends no tick events. +- Get real-time profile data: silver, gold and location arrive about once a minute. (XP follows each fight while the live game feed watches the account.) +- Get timer ticks: the timer sends no tick events. - Use shortcut keys, sounds or desktop notifications. - Draw custom cards. Cards are FourFold's data cards. - Add a settings page behind the cog. Keep settings in your own panel. From 6cc1fc6dc03efcb8c32ecb4555d78dd018dd8185 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:34:57 -0500 Subject: [PATCH 22/28] fix: don't count a timing pair's closing window as missed battle results --- .../LiveFeed/XpReconcilerTests.cs | 15 +++++++++++++++ .../LiveFeed/XpReconciler.cs | 11 +++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs index 5a44fd3..85c6dec 100644 --- a/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs @@ -66,4 +66,19 @@ public void ABattleCountedAWindowLateNeverGivesUpOnTheFeed() Assert.Equal((4, 0), (reconciler.Matched, reconciler.Mismatched)); } + + [Fact] + public void AnEarlyPairThenALatePairNeverGivesUpOnTheFeed() + { + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + // The result lands just before the poll and the XP just after it: the XP shows a window late. + reconciler.RecordResult(Account, At(0.99), "Savage", 100); + Assert.False(Sample(reconciler, 100, 1)); + Assert.False(Sample(reconciler, 200, 2)); // silent, but it closes that pair + // The next fight's XP shows before the poll and its result just after it. + Assert.False(Sample(reconciler, 300, 3)); + reconciler.RecordResult(Account, At(3.01), "Savage", 100); + Assert.False(Sample(reconciler, 300, 4)); + } } diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs index ba9599b..e0be41a 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -71,9 +71,12 @@ public bool RecordSample( return false; } - // Two in a row rules out the +x/-x timing pair: the second window of a pair has fed > 0. + // A silent window that opens a late pair is followed by one where its result arrives, and one that closes an + // early pair doesn't count, so timing pairs can't make two in a row. A real break can: -b never cancels -a. + var difference = fed - polled; + var closesPair = _openMismatches.TryGetValue(accountId, out var open) && open == -difference; var stopped = false; - if (polled > 0 && fed == 0) + if (polled > 0 && fed == 0 && !closesPair) { var missed = _missedResults.GetValueOrDefault(accountId) + 1; stopped = missed >= 2; @@ -91,7 +94,6 @@ public bool RecordSample( _missedResults.Remove(accountId); } - var difference = fed - polled; if (difference == 0) { Matched++; @@ -99,7 +101,8 @@ public bool RecordSample( return stopped; } - if (_openMismatches.Remove(accountId, out var open) && open == -difference) + _openMismatches.Remove(accountId); + if (closesPair) { Mismatched--; Matched += 2; From f5920c956132a3d6ecd3e68d4618cfd1e959d216 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:42:53 -0500 Subject: [PATCH 23/28] fix: only give up on the feed when no battle results arrive at all, and start the count over after a skipped window A stale miss from before a level-up, a reconnect or the feed switching back on could pair with a later ordinary timing miss, and a class the game spells differently from the website read as every fight missing. Either one switched the live feed off for every account. --- .../LiveFeed/XpReconcilerTests.cs | 39 +++++++++++++++++++ .../LiveFeed/XpReconciler.cs | 10 ++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs index 85c6dec..da600ab 100644 --- a/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/LiveFeed/XpReconcilerTests.cs @@ -81,4 +81,43 @@ public void AnEarlyPairThenALatePairNeverGivesUpOnTheFeed() reconciler.RecordResult(Account, At(3.01), "Savage", 100); Assert.False(Sample(reconciler, 300, 4)); } + + [Fact] + public void AMissBeforeASkippedWindowNeverPairsWithALaterOne() + { + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + Assert.False(Sample(reconciler, 200, 1)); // one miss: a fight whose result lands just after this poll + + // That fight levelled up, so the next window is skipped and the run of misses starts over. + var levelled = new PlayerProgressSnapshot("cody", "Savage", + new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["Savage"] = new(13, 50, Cap(13), null), + ["Mage"] = new(3, 0, Cap(3), null) + }, + []); + reconciler.RecordResult(Account, At(1.1), "Savage", Cap(12) - 200 + 50); + Assert.False(reconciler.RecordSample(Account, levelled, At(2), At(-1))); + + Assert.False(reconciler.RecordSample(Account, levelled with + { + Classes = new Dictionary(levelled.Classes, StringComparer.OrdinalIgnoreCase) + { + ["Savage"] = new(13, 150, Cap(13), null) + } + }, At(3), At(-1))); + } + + [Fact] + public void ResultsUnderAnotherSpellingOfTheClassAreNotMisses() + { + // The game and the website spell the class differently, so no result matches it, but results do arrive. + var reconciler = new XpReconciler(); + Sample(reconciler, 100, 0); + reconciler.RecordResult(Account, At(0.5), "Savages", 100); + Assert.False(Sample(reconciler, 200, 1)); + reconciler.RecordResult(Account, At(1.5), "Savages", 100); + Assert.False(Sample(reconciler, 300, 2)); + } } diff --git a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs index e0be41a..998e965 100644 --- a/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs +++ b/src/FourFoldAccountManager.Core/LiveFeed/XpReconciler.cs @@ -54,7 +54,10 @@ public bool RecordSample( before.Class.Level != after.Class.Level) { Skipped++; + // A skipped window breaks the run too: a stale miss from before a level-up, a reconnect or the feed + // switching back on must not pair with a later one. _openMismatches.Remove(accountId); + _missedResults.Remove(accountId); return false; } @@ -67,7 +70,10 @@ public bool RecordSample( { // No battle and no XP change proves nothing about the feed, so it isn't evidence either way. Skipped++; + // A skipped window breaks the run too: a stale miss from before a level-up, a reconnect or the feed + // switching back on must not pair with a later one. _openMismatches.Remove(accountId); + _missedResults.Remove(accountId); return false; } @@ -76,7 +82,9 @@ public bool RecordSample( var difference = fed - polled; var closesPair = _openMismatches.TryGetValue(accountId, out var open) && open == -difference; var stopped = false; - if (polled > 0 && fed == 0 && !closesPair) + // Silent means no battle result arrived at all, whatever its class: a class the game spells differently from + // the website must not read as the feed missing every fight. + if (polled > 0 && inWindow.Length == 0 && !closesPair) { var missed = _missedResults.GetValueOrDefault(accountId) + 1; stopped = missed >= 2; From 12465315f490f094f166374f1a09d6b8d2fa2c65 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:50:57 -0500 Subject: [PATCH 24/28] fix: let the live XP tracker visibly fall between fights and show its last fight's time The panel showed the last poll's time and a rate worked out only at polls and fights, so a live tracker looked once-a-minute. The rate shown (panel, cards, xp.get) is now the rate at the time of asking, the panel redraws every 5 s while an account is live, and the row shows the last fight's time. Plugins still get xp.updated only for a poll, a fight or a reset, not for every redraw. --- .../Tracking/XpTrackingSessionLiveTests.cs | 16 +++++++++++ .../Tracking/XpTrackingSession.cs | 9 +++++++ .../MainWindow.CommunityPlugins.cs | 10 ++++--- .../MainWindow.LiveFeed.cs | 14 +++++++++- .../Services/XpTrackerCoordinator.cs | 27 ++++++++++++++----- .../Views/XpTrackerRow.cs | 9 ++++--- 6 files changed, 71 insertions(+), 14 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs index eed3c72..e718119 100644 --- a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs @@ -214,4 +214,20 @@ public void ALaggingPollAfterALiveStretchDoesNotCountTheFightAgain() Assert.Equal(300, session.SessionGain); } + + [Fact] + public void TheRateShownNowFallsBetweenFightsAndStaysPutWhenPolled() + { + var live = new XpTrackingSession(); + live.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + live.BeginLive(At(0)); + live.ApplyLiveResult(At(1), "Savage", 300, 12, Cap(12) - 400); + Assert.Equal(18000, live.RateNow(At(1))!.Value, 6); + Assert.Equal(6000, live.RateNow(At(3))!.Value, 6); // two idle minutes, no poll yet + + var polled = new XpTrackingSession(); + polled.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + polled.ApplySnapshot(Poll("Savage", 12, 400), At(1)); + Assert.Equal(polled.RatePerHour, polled.RateNow(At(30))); + } } diff --git a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs index b88db68..c239226 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs @@ -45,6 +45,9 @@ public sealed class XpTrackingSession public bool IsStale { get; private set; } public bool IsStopped { get; private set; } public bool IsLive => _liveMark is not null; + + // When the live game feed last counted a fight. The poll's time alone makes a live tracker look once a minute. + public DateTimeOffset? LastFightAt { get; private set; } public bool MissedPreviousSample { get; private set; } public bool ActiveClassUnavailable { get; private set; } public IReadOnlyList InvalidClassNames { get; private set; } = []; @@ -172,6 +175,7 @@ public void ApplyLiveResult( _window.Add(mark, at, Math.Max(0, expGained)); _liveMark = at; + LastFightAt = at; RatePerHour = RateAt(at); // The result carries the whole state: the level reached and the XP still needed. The game levels up at most once // per fight, so the level's total follows from the level. @@ -186,6 +190,11 @@ public void ApplyLiveResult( // At a poll or a fight. While live, the time since the last fight counts as gaining nothing, so the rate falls while // the account idles. + // The rate to show at `now`. While live, the time since the last fight counts as gaining nothing, so the shown rate + // falls while the account idles, not only at each poll. Otherwise the rate at the last poll, as before. + public double? RateNow(DateTimeOffset now) => + _liveMark is { } mark ? _window.GetRate(now > mark ? now : mark, mark, LiveRateMinimum) : RatePerHour; + private double? RateAt(DateTimeOffset at) => _liveMark is { } mark ? _window.GetRate(at, mark, LiveRateMinimum) : _window.GetRate(at); diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs index be6c33a..126bdac 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.CommunityPlugins.cs @@ -19,8 +19,10 @@ namespace FourFoldAccountManager.Desktop; public partial class MainWindow : IPluginHostData { private readonly PluginCardStore _pluginCards = new(); - private readonly Dictionary - _postedXpUpdates = []; + // A live rate changes every time it's read, so it isn't part of what counts as new XP data: a poll, a fight + // (SessionGain, LastFightAt) or a reset (HasRate) is. + private readonly Dictionary _postedXpUpdates = []; private CommunityPluginManager _communityPlugins = null!; private PluginHub _pluginHub = null!; private string _postedAccounts = string.Empty; @@ -184,8 +186,8 @@ private void NotifyPluginsOfDataChanges() foreach (var state in _xpTracker.GetStates()) { - var current = (state.LastUpdated, state.IsStale, state.RatePerHour, state.SessionGain); - // Equals, not ==, so a NaN rate counts as unchanged instead of posting on every refresh. + var current = (state.LastUpdated, state.IsStale, state.RatePerHour is not null, state.SessionGain, + state.LastFightAt); if (!_postedXpUpdates.TryGetValue(state.AccountId, out var posted) || !posted.Equals(current)) { _postedXpUpdates[state.AccountId] = current; diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs index efe74bc..0ca081f 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs @@ -1,3 +1,4 @@ +using System.Windows.Threading; using FourFoldAccountManager.Core.LiveFeed; using FourFoldAccountManager.Desktop.Plugins.Web; using FourFoldAccountManager.Desktop.Services.LiveFeed; @@ -8,13 +9,24 @@ namespace FourFoldAccountManager.Desktop; public partial class MainWindow { private LiveGameFeed _liveFeed = null!; + private DispatcherTimer? _liveRedraw; // Starts off; MainWindow_Loaded switches it to the saved setting. Panels created before then are remembered and // tapped when it switches on. - private void InitializeLiveFeed() => + private void InitializeLiveFeed() + { _liveFeed = new LiveGameFeed( _browserSessions, _xpTracker, (name, data) => _communityPlugins.PostEvent(name, data), Dispatcher, TimeProvider.System); + // A live XP/hr falls while the account idles; redraw the panel and cards so it shows, not only at each poll. + _liveRedraw = new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Background, (_, _) => + { + if (!_shutdownStarted && _xpTracker.HasLiveAccount) + { + RefreshTrackerRows(); + } + }, Dispatcher); + } // One line for Settings: the state, then the counts the feed must earn before the XP tracker relies on it. private string LiveFeedSummary() diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index 913a15c..02ed47a 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -15,7 +15,8 @@ public sealed record XpTrackerState( double? HoursUntilNextLevel, DateTimeOffset? LastUpdated, string Status, - bool IsStale); + bool IsStale, + DateTimeOffset? LastFightAt = null); public sealed class XpTrackerCoordinator : IAsyncDisposable { @@ -69,11 +70,25 @@ public async Task VerifyPlayerAsync(int playerId, string username) return result.IsSuccess; } - public IReadOnlyList GetStates() => _active.Values.Select(account => new XpTrackerState( - account.Id, account.Username, account.Session.RatePerHour, account.Session.SessionGain, - account.Session.ActiveClassName, account.Session.XpUntilNextLevel, - account.Session.HoursUntilNextLevel, - account.Session.LastSuccessfulAt, StatusOf(account), account.Session.IsStale)).ToArray(); + // Rates are worked out at the time of asking, so a live account's XP/hr falls while it idles between fights. + public IReadOnlyList GetStates() + { + var now = DateTimeOffset.UtcNow; + return _active.Values.Select(account => + { + var rate = account.Session.RateNow(now); + var remaining = account.Session.XpUntilNextLevel; + return new XpTrackerState( + account.Id, account.Username, rate, account.Session.SessionGain, + account.Session.ActiveClassName, remaining, + remaining is { } xp && rate is { } perHour && double.IsFinite(perHour) && perHour > 0 ? xp / perHour : null, + account.Session.LastSuccessfulAt, StatusOf(account), account.Session.IsStale, + account.Session.IsLive ? account.Session.LastFightAt : null); + }).ToArray(); + } + + // The panel redraws on a timer while this is true, so a live rate visibly falls between fights. + public bool HasLiveAccount => _active.Values.Any(account => account.Session.IsLive); // While the live game feed watches the account, the two ordinary statuses say so. Problems still show as they are. private static string StatusOf(TrackedAccount account) => diff --git a/src/FourFoldAccountManager.Desktop/Views/XpTrackerRow.cs b/src/FourFoldAccountManager.Desktop/Views/XpTrackerRow.cs index 4a04b1e..e95453a 100644 --- a/src/FourFoldAccountManager.Desktop/Views/XpTrackerRow.cs +++ b/src/FourFoldAccountManager.Desktop/Views/XpTrackerRow.cs @@ -30,9 +30,12 @@ state.XpUntilNextLevel is { } remaining : "— XP to next level", FormatTimeUntilNextLevel(state.HoursUntilNextLevel), state.Status, - state.LastUpdated is { } updated - ? $"Updated {updated.ToLocalTime():h:mm:ss tt}" - : "Waiting for first snapshot"); + // While live, the last fight is newer news than the last poll. + state.LastFightAt is { } fight && (state.LastUpdated is not { } polled || fight > polled) + ? $"Last fight {fight.ToLocalTime():h:mm:ss tt}" + : state.LastUpdated is { } updated + ? $"Updated {updated.ToLocalTime():h:mm:ss tt}" + : "Waiting for first snapshot"); } private static string FormatTimeUntilNextLevel(double? hoursUntilNextLevel) From 20d50d730dd8fa807b6ac9f2120bfefd7c2ab803 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:53:44 -0500 Subject: [PATCH 25/28] fix: keep the live status, the fallen rate and clicks steady while the tracker redraws The status now reads from the rate shown beside it, going off live keeps the rate that had fallen with the idle time, the 5-s redraw skips while a mouse button is down, and the timer stops at shutdown. --- .../Tracking/XpTrackingSessionLiveTests.cs | 8 ++++++++ .../Tracking/XpTrackingSession.cs | 6 ++++-- src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs | 5 ++++- src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs | 1 + .../Services/XpTrackerCoordinator.cs | 7 ++++--- 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs index e718119..6bae3ad 100644 --- a/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs +++ b/src/FourFoldAccountManager.Core.Tests/Tracking/XpTrackingSessionLiveTests.cs @@ -221,8 +221,16 @@ public void TheRateShownNowFallsBetweenFightsAndStaysPutWhenPolled() var live = new XpTrackingSession(); live.ApplySnapshot(Poll("Savage", 12, 100), At(0)); live.BeginLive(At(0)); + Assert.Null(live.RateNow(At(0.5))); // under a minute watched live.ApplyLiveResult(At(1), "Savage", 300, 12, Cap(12) - 400); Assert.Equal(18000, live.RateNow(At(1))!.Value, 6); + // Going off live keeps the fallen rate instead of jumping back to the one at the last fight. + var ended = new XpTrackingSession(); + ended.ApplySnapshot(Poll("Savage", 12, 100), At(0)); + ended.BeginLive(At(0)); + ended.ApplyLiveResult(At(1), "Savage", 300, 12, Cap(12) - 400); + ended.EndLive(At(3)); + Assert.Equal(6000, ended.RateNow(At(3))!.Value, 6); Assert.Equal(6000, live.RateNow(At(3))!.Value, 6); // two idle minutes, no poll yet var polled = new XpTrackingSession(); diff --git a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs index c239226..3edc120 100644 --- a/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs +++ b/src/FourFoldAccountManager.Core/Tracking/XpTrackingSession.cs @@ -161,6 +161,8 @@ public void EndLive(DateTimeOffset at) _liveMark = null; _rebase = true; + // The shown rate had already fallen with the idle time; without this it would jump back up until the next poll. + RatePerHour = _window.GetRate(at); } // One fight's reward from the live game feed. It counts from the mark to this fight, so the time between fights is @@ -188,13 +190,13 @@ public void ApplyLiveResult( } } - // At a poll or a fight. While live, the time since the last fight counts as gaining nothing, so the rate falls while - // the account idles. // The rate to show at `now`. While live, the time since the last fight counts as gaining nothing, so the shown rate // falls while the account idles, not only at each poll. Otherwise the rate at the last poll, as before. public double? RateNow(DateTimeOffset now) => _liveMark is { } mark ? _window.GetRate(now > mark ? now : mark, mark, LiveRateMinimum) : RatePerHour; + // At a poll or a fight. While live, the time since the last fight counts as gaining nothing, so the rate falls while + // the account idles. private double? RateAt(DateTimeOffset at) => _liveMark is { } mark ? _window.GetRate(at, mark, LiveRateMinimum) : _window.GetRate(at); diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs index 0ca081f..b04a857 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs @@ -1,3 +1,4 @@ +using System.Windows.Input; using System.Windows.Threading; using FourFoldAccountManager.Core.LiveFeed; using FourFoldAccountManager.Desktop.Plugins.Web; @@ -21,7 +22,9 @@ private void InitializeLiveFeed() // A live XP/hr falls while the account idles; redraw the panel and cards so it shows, not only at each poll. _liveRedraw = new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Background, (_, _) => { - if (!_shutdownStarted && _xpTracker.HasLiveAccount) + // Rebuilding the rows under a press would lose the click or close its menu; the next tick catches up. + if (!_shutdownStarted && _xpTracker.HasLiveAccount && + Mouse.LeftButton != MouseButtonState.Pressed && Mouse.RightButton != MouseButtonState.Pressed) { RefreshTrackerRows(); } diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs index 01c64f5..8d32b33 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.xaml.cs @@ -3445,6 +3445,7 @@ private async void MainWindow_Closing(object? sender, System.ComponentModel.Canc // typed just before closing reaches disk instead of being lost. _plugins.XpCalc.View.FlushPendingTargetSave(); _pluginCardRefreshTimer?.Stop(); + _liveRedraw?.Stop(); // First, so a download that finishes now can't reach the plugins that are being disposed. _pluginHub.Dispose(); _communityPlugins.Dispose(); diff --git a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs index 02ed47a..23c2fd6 100644 --- a/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs +++ b/src/FourFoldAccountManager.Desktop/Services/XpTrackerCoordinator.cs @@ -82,7 +82,7 @@ public IReadOnlyList GetStates() account.Id, account.Username, rate, account.Session.SessionGain, account.Session.ActiveClassName, remaining, remaining is { } xp && rate is { } perHour && double.IsFinite(perHour) && perHour > 0 ? xp / perHour : null, - account.Session.LastSuccessfulAt, StatusOf(account), account.Session.IsStale, + account.Session.LastSuccessfulAt, StatusOf(account, rate), account.Session.IsStale, account.Session.IsLive ? account.Session.LastFightAt : null); }).ToArray(); } @@ -91,9 +91,10 @@ public IReadOnlyList GetStates() public bool HasLiveAccount => _active.Values.Any(account => account.Session.IsLive); // While the live game feed watches the account, the two ordinary statuses say so. Problems still show as they are. - private static string StatusOf(TrackedAccount account) => + // `rate` is the rate shown beside it, so the two never disagree. + private static string StatusOf(TrackedAccount account, double? rate) => account.Session.IsLive && account.Status is "Tracking" or "Collecting baseline" - ? (account.Session.RatePerHour is null ? "Live; collecting a minute first" : "Tracking live") + ? (rate is null ? "Live; collecting a minute first" : "Tracking live") : account.Status; public IReadOnlyList<(Guid AccountId, int PlayerId, string Username)> GetActiveLeaderboardProfiles() From 1b7f9b7caeb8ae41c1e18840da9d0aae5df255a8 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 22:57:26 -0500 Subject: [PATCH 26/28] fix: redraw a live XP tracker once a second, like the rate it shows --- src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs index b04a857..88f326c 100644 --- a/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs +++ b/src/FourFoldAccountManager.Desktop/MainWindow.LiveFeed.cs @@ -20,7 +20,7 @@ private void InitializeLiveFeed() _browserSessions, _xpTracker, (name, data) => _communityPlugins.PostEvent(name, data), Dispatcher, TimeProvider.System); // A live XP/hr falls while the account idles; redraw the panel and cards so it shows, not only at each poll. - _liveRedraw = new DispatcherTimer(TimeSpan.FromSeconds(5), DispatcherPriority.Background, (_, _) => + _liveRedraw = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Background, (_, _) => { // Rebuilding the rows under a press would lose the click or close its menu; the next tick catches up. if (!_shutdownStarted && _xpTracker.HasLiveAccount && From 2eea76a4e5d2a9ee91d5eff8029da5c128485772 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 23:00:48 -0500 Subject: [PATCH 27/28] fix: keep the XP tracker's Reset menu working while live rows redraw The rows are rebuilt every second while an account is live, which disconnected an open menu from its row, so Reset XP/hr did nothing. The menu now takes its account when it opens. --- .../Views/XpTrackerPanel.xaml | 2 +- .../Views/XpTrackerPanel.xaml.cs | 14 ++++++++++++-- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml b/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml index bbcd802..b60c604 100644 --- a/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml +++ b/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml @@ -19,7 +19,7 @@ - + diff --git a/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml.cs b/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml.cs index 54b7857..2160736 100644 --- a/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml.cs +++ b/src/FourFoldAccountManager.Desktop/Views/XpTrackerPanel.xaml.cs @@ -33,11 +33,21 @@ private void ResetAll_Click(object sender, RoutedEventArgs e) if (TryGetAccountId(sender, out var accountId)) ResetAllRequested?.Invoke(accountId); } + // The rows are rebuilt every second while an account is live, which disconnects an open menu from its row. So the + // account is taken when the menu opens, not when an item is clicked. + private void RowMenu_Opened(object sender, RoutedEventArgs e) + { + if (sender is ContextMenu { PlacementTarget: FrameworkElement { DataContext: XpTrackerRow row } } menu) + { + menu.Tag = row.AccountId; + } + } + private static bool TryGetAccountId(object sender, out Guid accountId) { - if (sender is MenuItem { Parent: ContextMenu { PlacementTarget: FrameworkElement { DataContext: XpTrackerRow row } } }) + if (sender is MenuItem { Parent: ContextMenu { Tag: Guid id } }) { - accountId = row.AccountId; + accountId = id; return true; } From d822948f620ce6235066074252a5fca25dc36111 Mon Sep 17 00:00:00 2001 From: Cody Simonds <36618932+CodySimonds65@users.noreply.github.com> Date: Tue, 6 Oct 2026 23:16:16 -0500 Subject: [PATCH 28/28] docs: say xp.onUpdated also fires on a reset, and that a live scene can be null --- PLUGIN_AUTHORS.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/PLUGIN_AUTHORS.md b/PLUGIN_AUTHORS.md index aabaf4b..cddd257 100644 --- a/PLUGIN_AUTHORS.md +++ b/PLUGIN_AUTHORS.md @@ -144,7 +144,7 @@ FourFold reads an account's XP only while that account is open, and only if Four While the [live game feed](#live-game-feed) watches an account, `className`, `level`, `currentXp`, `nextLevelXp`, `xpUntilNextLevel`, `hoursUntilNextLevel`, `xpPerHour`, `sessionXp` and the active class's row in `classes` follow each fight. `updatedAt` and `isStale` still describe the last read. Otherwise the values come from the read, about once a minute. -`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes: about once a minute for each open account, and after each fight while the live game feed watches it. +`fourfold.xp.onUpdated(callback)` calls `callback({ accountId })` when that account's XP data changes: about once a minute for each open account, after each fight while the live game feed watches it, and when the user resets the XP tracker. ### Stats @@ -204,7 +204,7 @@ Every event has the account's `accountId` and `at`, the time FourFold received i - **Fights.** The game doesn't say whether a fight was won: a win is a `battle.onResult` after `battle.onEnded`, and an end with no result is an escape or a loss. `battle.onResult` gives `expGained` and `silverGained` (any double-XP event is already included), `expNeededToNextLevel`, `leveledUp`, `reachedLevel`, `className` (or `null`), `unlockedSkillName` (`null` when none unlocked; comma-joined when several do, at most 64 characters) and `statGains`: `{ maxHp, maxSp, hp, sp, att, mag, skl, spd, def, res, lck }`, the points the fight added. - **Skills.** `outcome` is `"hit"`, `"miss"` or `"rejected"`. The game rolls once per cast against the skill's chance, so a miss misses every target. A rejected cast (not enough SP, say) never rolled: `skillName` is `null` and `reason` is the game's text. Otherwise `reason` is `null`. -- **Places.** `scene` is the game's own scene name, such as `westhills_b2_dungeon_01`. `inBattle` is `true` in a fight scene. `fourfold.location.get(accountId)` returns the same `{ accountId, scene, inBattle, at }` for the account's current place, or `null` when FourFold has no live data for it (a closed account, or one that hasn't changed place since the feed started). An unknown account id is rejected with `invalid-argument`. +- **Places.** `scene` is the game's own scene name, such as `westhills_b2_dungeon_01`, or `null` when the game didn't name one. `inBattle` is `true` in a fight scene. `fourfold.location.get(accountId)` returns the same `{ accountId, scene, inBattle, at }` for the account's current place, or `null` when FourFold has no live data for it (a closed account, or one that hasn't changed place since the feed started). An unknown account id is rejected with `invalid-argument`. - **Sessions.** `session.onLoggedIn` fires for a successful login only. `session.onDisconnected` fires on a kick, with the server's text in `reason`, and on a reload or a closed panel, with `reason` `null`. It also ends any fight in progress: a fight cut off by a reload never gets `battle.onEnded`, and after the login the game resumes it with a new `battle.onStarted`. - **Status.** `fourfold.live.getStatus()` returns `{ state, reason }`. `state` is `"active"` while the feed is on and reading, `"off"` when the user switched it off, and `"unavailable"` when FourFold can't read the game, with the reason in `reason` (a game update FourFold can't read yet, say). `reason` is `null` otherwise. An account already in game when the feed is switched on sends nothing until its game reconnects.