feat(phase9): ability system gap fixes -- pause propagation, handlers, chooser, aura actions

- Fix pause propagation: ExecuteActions for-loop breaks on HasPendingInteraction();
  effect loop in ExecuteSingleAction also stops when any pending state is set
- Add HasPendingInteraction() helper to GameState covering all 7 pending types
- Create 4 missing handlers: GameCostGroupPickHandler, GameActionGroupPickHandler,
  GameBranchPickHandler, GameRevealChoicePickHandler + register in ServiceRegistration
- Add corresponding request/response records to GameMessages.cs
- Fix ActionNeedsClientTargets: short-circuit false when Chooser == Random
- Add ChooserActorId to PendingTriggeredTarget; FireTrigger sets it to opponent/ally
  when Chooser.Opponent/Ally; GameHandlerBase pushes to ChooserActorId
- ResumeTriggeredAbility validates against ChooserActorId (falls back to ActorId)
- Fix ApplyOnEventEffect: Action[] -> ActionGroup?; PendingDeferredEffect gains
  ActionGroupJson field; deferred firing uses ResolveActionGroup + ExecuteActions
- Wire OnEnterAuraActions / OnLeaveAuraActions into FireAuraTransition (one-shot,
  restricted to the entering/leaving unit)

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-04-21 06:09:32 -04:00
co-authored by Claude Happy
parent 80b92b17b9
commit 95c01cffb5
11 changed files with 411 additions and 15 deletions
+85 -9
View File
@@ -287,11 +287,27 @@ public static class AbilitySystem
// If any action needs a human pick, pause and request client input.
var effectiveActions = GetEffectiveActions(def, ctx, abilityIndex: 0, def.Range, def.Duration) ?? [];
if (effectiveActions.Any(ActionNeedsClientTargets))
var pickAction = Array.Find(effectiveActions, ActionNeedsClientTargets);
if (pickAction is not null)
{
// Determine which player must actually submit the target picks.
// For Chooser.Opponent/Ally, route the request to the non-activating player.
string chooserActorId = pickAction.Target.Chooser switch
{
TargetChooser.Opponent =>
state.GetEnemyIds(ownerId).FirstOrDefault() ?? ownerId,
TargetChooser.Ally =>
state.Players.Values
.FirstOrDefault(p => p.AccountId != ownerId
&& state.AreAllies(p.AccountId, ownerId))
?.AccountId ?? ownerId,
_ => ownerId, // Self or default
};
state.PendingTriggeredTarget = new PendingTriggeredTarget
{
ActorId = ownerId,
ChooserActorId = chooserActorId,
SourceInstanceId = card.InstanceId,
AbilityName = def.Name ?? "Triggered Ability",
ActionsJson = JsonSerializer.Serialize(effectiveActions, _jsonOpts),
@@ -326,11 +342,6 @@ public static class AbilitySystem
{
state.PendingDeferredEffects.Remove(pending);
Models.Action[]? deferredActions;
try { deferredActions = JsonSerializer.Deserialize<Models.Action[]>(pending.ActionsJson, _jsonOpts); }
catch { continue; }
if (deferredActions is null || deferredActions.Length == 0) continue;
var dSrc = state.Players.Values
.SelectMany(p => p.Field).OfType<FieldCard>()
.FirstOrDefault(f => f.InstanceId == pending.SourceInstanceId);
@@ -342,7 +353,26 @@ public static class AbilitySystem
if (tgt is not null)
dCtx.ResolvedTargets[0] = [tgt];
ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false);
// Prefer ActionGroupJson (full recursive tree) over legacy flat ActionsJson.
if (pending.ActionGroupJson is not null)
{
Models.ActionGroup? ag;
try { ag = JsonSerializer.Deserialize<Models.ActionGroup>(pending.ActionGroupJson, _jsonOpts); }
catch { continue; }
if (ag is null) continue;
var resolved = ResolveActionGroup(ag, dCtx, abilityIndex: 0,
range: null, forceDuration: null, continuationActions: []);
if (resolved is not null)
ExecuteActions(resolved, dCtx, clientTargets: null, requireClientTargets: false);
}
else
{
Models.Action[]? deferredActions;
try { deferredActions = JsonSerializer.Deserialize<Models.Action[]>(pending.ActionsJson, _jsonOpts); }
catch { continue; }
if (deferredActions is null || deferredActions.Length == 0) continue;
ExecuteActions(deferredActions, dCtx, clientTargets: null, requireClientTargets: false);
}
}
return state;
@@ -1058,8 +1088,12 @@ public static class AbilitySystem
try
{
for (int i = 0; i < actions.Length; i++)
{
ExecuteSingleAction(actions[i], ctx, clientTargets, actionIndex: i,
requireClientTargets, activationRange, restrictTargets, forceDuration);
// Stop iterating as soon as any interactive pause is set.
if (ctx.State.HasPendingInteraction()) break;
}
}
finally
{
@@ -1160,7 +1194,14 @@ public static class AbilitySystem
}
foreach (var effect in action.Effects)
{
ExecuteEffect(effect, target, duration, ctx);
// Stop as soon as an effect sets an interactive pause.
if (ctx.State.HasPendingInteraction()) return;
}
// Also stop between targets if a pause was set mid-loop.
if (ctx.State.HasPendingInteraction()) return;
}
}
@@ -1192,6 +1233,10 @@ public static class AbilitySystem
if (sel.Count.All)
return false;
// Random chooser: server resolves without client input regardless of ownership.
if (sel.Chooser == TargetChooser.Random)
return false;
// These ownerships are auto-resolved: self, random, chained from prior action.
return sel.Ownership is not (
TargetOwnership.Self or
@@ -1216,7 +1261,12 @@ public static class AbilitySystem
if (pending.RequestId != requestId)
throw new GameException("REQUEST_ID_MISMATCH");
if (pending.ActorId != actorId)
// ChooserActorId is who must respond — may be an opponent/ally for Chooser.Opponent/Ally.
// Fall back to ActorId for older records that predate ChooserActorId.
var expectedChooser = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
if (expectedChooser != actorId)
throw new GameException("NOT_YOUR_TRIGGER");
// Clear before executing so any nested triggers don't see a stale request.
@@ -2515,7 +2565,11 @@ public static class AbilitySystem
OwnerAccountId = ctx.ActorId,
TriggerJson = JsonSerializer.Serialize(aoe.Trigger, _jsonOpts),
TargetRef = targetRef,
ActionsJson = JsonSerializer.Serialize(aoe.Actions, _jsonOpts),
// Store the ActionGroup as the canonical form; ActionsJson is a legacy fallback.
ActionGroupJson = aoe.ActionGroup is not null
? JsonSerializer.Serialize(aoe.ActionGroup, _jsonOpts)
: null,
ActionsJson = "[]",
});
break;
}
@@ -4230,6 +4284,17 @@ public static class AbilitySystem
Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId },
});
ApplyAuraEffects(state, auraOwnerId, auraUnit, def, targetUnitId);
// Execute one-shot OnEnterAuraActions (not duration-tracked, fired once on enter).
if (def.OnEnterAuraActions is not null)
{
var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit };
var resolved = ResolveActionGroup(def.OnEnterAuraActions, ctx, abilityIndex: 0,
range: def.AuraRange, forceDuration: null, continuationActions: []);
if (resolved is not null)
ExecuteActions(resolved, ctx, clientTargets: null,
restrictTargets: new HashSet<string> { targetUnitId });
}
}
else if (wasIn && !isIn)
{
@@ -4240,6 +4305,17 @@ public static class AbilitySystem
Data = new TriggerEventData { SourceId = auraUnit.InstanceId, TargetId = targetUnitId },
});
HandleAuraLeave(state, auraUnit, def, targetUnitId, auraOwnerId);
// Execute one-shot OnLeaveAuraActions (fired once on leave, regardless of ClearOnLeave).
if (def.OnLeaveAuraActions is not null)
{
var ctx = new AbilityContext { State = state, ActorId = auraOwnerId, Source = auraUnit };
var resolved = ResolveActionGroup(def.OnLeaveAuraActions, ctx, abilityIndex: 0,
range: null, forceDuration: null, continuationActions: []);
if (resolved is not null)
ExecuteActions(resolved, ctx, clientTargets: null,
restrictTargets: new HashSet<string> { targetUnitId });
}
}
}
}
@@ -465,8 +465,8 @@ public sealed class ApplyOnEventEffect : Effect
{
public TriggerEvent Trigger { get; set; } = null!;
/// <summary>
/// Full action tree executed when the trigger fires. Supports chained targeting and
/// nested ActionGroups. Replaces the old flat Effect[] for recursive ability trees.
/// Action tree executed when the trigger fires. Supports chained targeting and
/// nested ActionGroups via recursive ActionGroup.
/// </summary>
public Action[] Actions { get; set; } = [];
public ActionGroup? ActionGroup { get; set; }
}
@@ -10,9 +10,16 @@ public sealed class PendingTriggeredTarget
/// <summary>Correlation ID sent to the client so responses can be matched.</summary>
public string RequestId { get; set; } = Guid.NewGuid().ToString("N");
/// <summary>AccountId of the player who must pick the target.</summary>
/// <summary>AccountId of the player whose ability triggered (the ability owner).</summary>
public string ActorId { get; set; } = string.Empty;
/// <summary>
/// AccountId of the player who must actually pick the targets.
/// Equals <see cref="ActorId"/> when <c>Chooser == Self</c>;
/// set to an opponent or ally ID when <c>Chooser == Opponent/Ally</c>.
/// </summary>
public string ChooserActorId { get; set; } = string.Empty;
/// <summary>InstanceId of the unit whose triggered ability is paused.</summary>
public string SourceInstanceId { get; set; } = string.Empty;
+50
View File
@@ -860,3 +860,53 @@ public sealed record GameCostPickRequest(
/// <summary>Acknowledged response for a cost pick submission.</summary>
public sealed record GameCostPickResponse(bool Success);
/// <summary>
/// Sent by the chooser to select which CostGroup option to pay when logic is OR/XOR.
/// </summary>
public sealed record GameCostGroupPickRequest(
Guid SessionId,
string RequestId,
/// <summary>0-based index of the chosen cost option within the pending group.</summary>
int ChoiceIndex);
/// <summary>Acknowledged response for a cost-group pick submission.</summary>
public sealed record GameCostGroupPickResponse(bool Success);
/// <summary>
/// Sent by the chooser to select which ActionGroup branch to execute when logic is OR/XOR.
/// </summary>
public sealed record GameActionGroupPickRequest(
Guid SessionId,
string RequestId,
/// <summary>0-based index of the chosen child action/group.</summary>
int ChoiceIndex);
/// <summary>Acknowledged response for an action-group pick submission.</summary>
public sealed record GameActionGroupPickResponse(bool Success);
/// <summary>
/// Sent by the chooser (Opponent/Ally) to pick a ChooseOne branch.
/// </summary>
public sealed record GameBranchPickRequest(
Guid SessionId,
string RequestId,
/// <summary>0-based index of the chosen branch.</summary>
int BranchIndex);
/// <summary>Acknowledged response for a branch pick submission.</summary>
public sealed record GameBranchPickResponse(bool Success);
/// <summary>
/// Sent by the chooser to order the revealed cards (e.g. StackDeckEffect interactive).
/// </summary>
public sealed record GameRevealChoicePickRequest(
Guid SessionId,
string RequestId,
/// <summary>
/// 0-based indices of the revealed cards in the desired top-to-bottom order.
/// Cards not listed are placed at the bottom of the deck.
/// </summary>
int[] OrderedIndices);
/// <summary>Acknowledged response for a reveal-choice pick submission.</summary>
public sealed record GameRevealChoicePickResponse(bool Success);
+22 -1
View File
@@ -147,6 +147,18 @@ public sealed class GameState
/// Paused until the chooser submits a <c>game.reveal_choice_pick</c> response.
/// </summary>
public Abilities.Models.PendingRevealChoicePick? PendingRevealChoicePick { get; set; }
/// <summary>
/// Returns true when any interactive pause is in effect (ability execution must stop).
/// </summary>
public bool HasPendingInteraction() =>
PendingCostPick is not null ||
PendingCostGroupPick is not null ||
PendingActionGroupPick is not null ||
PendingBranchPick is not null ||
PendingTilePick is not null ||
PendingPlayerPick is not null ||
PendingRevealChoicePick is not null;
}
public sealed class PlayerState
@@ -422,8 +434,17 @@ public sealed class PendingDeferredEffect
/// <summary>InstanceId (card) or AccountId (player) of the entity to apply effects to.</summary>
public string TargetRef { get; set; } = string.Empty;
/// <summary>Serialized Action[] JSON — actions executed when the trigger fires.</summary>
/// <summary>
/// Serialized Action[] JSON — actions executed when the trigger fires.
/// Kept for backward-compatibility; superseded by <see cref="ActionGroupJson"/> when present.
/// </summary>
public string ActionsJson { get; set; } = "[]";
/// <summary>
/// Serialized ActionGroup? JSON — full recursive action tree. When non-null, used in
/// preference to <see cref="ActionsJson"/>.
/// </summary>
public string? ActionGroupJson { get; set; }
}
/// <summary>
@@ -0,0 +1,56 @@
namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
using SOR.Game.Abilities;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.action_group_pick — chooser selects which ActionGroup child to execute when
/// logic is OR/XOR.
/// </summary>
internal sealed class GameActionGroupPickHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameActionGroupPickHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.action_group_pick";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameActionGroupPickRequest>(message.Payload);
var actorId = connection.UserId;
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
var prevStateJson = session.StateJson!;
var state = GameEngine.Deserialize(prevStateJson);
var newState = AbilitySystem.ResumeActionGroupPick(
state, actorId, req.RequestId, req.ChoiceIndex);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.action_group_pick",
JsonSerializer.Serialize(req), ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.action_group_pick.ack", message.Seq,
new GameActionGroupPickResponse(true));
}
}
@@ -0,0 +1,56 @@
namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
using SOR.Game.Abilities;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.branch_pick — the non-activating player (Opponent/Ally chooser) selects which
/// ChooseOne branch to execute.
/// </summary>
internal sealed class GameBranchPickHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameBranchPickHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.branch_pick";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameBranchPickRequest>(message.Payload);
var actorId = connection.UserId;
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
var prevStateJson = session.StateJson!;
var state = GameEngine.Deserialize(prevStateJson);
var newState = AbilitySystem.ResumeBranchPick(
state, actorId, req.RequestId, req.BranchIndex);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.branch_pick",
JsonSerializer.Serialize(req), ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.branch_pick.ack", message.Seq,
new GameBranchPickResponse(true));
}
}
@@ -0,0 +1,57 @@
namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
using SOR.Game.Abilities;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.cost_group_pick — chooser selects which cost option to pay when a CostGroup
/// has OR/XOR logic requiring an interactive decision.
/// Resumes cost payment and then executes the ability actions.
/// </summary>
internal sealed class GameCostGroupPickHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameCostGroupPickHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.cost_group_pick";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameCostGroupPickRequest>(message.Payload);
var actorId = connection.UserId;
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
var prevStateJson = session.StateJson!;
var state = GameEngine.Deserialize(prevStateJson);
var newState = AbilitySystem.ResumeCostGroupPick(
state, actorId, req.RequestId, req.ChoiceIndex);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.cost_group_pick",
JsonSerializer.Serialize(req), ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.cost_group_pick.ack", message.Seq,
new GameCostGroupPickResponse(true));
}
}
@@ -265,7 +265,11 @@ internal abstract class GameHandlerBase
? JsonSerializer.Serialize(firstClientPickAction)
: pending.ActionsJson; // fallback: send raw actions list
await clientPush.PushAsync(pending.ActorId,
// Route to ChooserActorId (may be opponent/ally for Chooser.Opponent/Ally abilities).
var targetPlayer = string.IsNullOrEmpty(pending.ChooserActorId)
? pending.ActorId
: pending.ChooserActorId;
await clientPush.PushAsync(targetPlayer,
ServerMessage.Push("game.ability.triggered_target_request",
new TriggeredTargetRequestPush(
pending.RequestId,
@@ -0,0 +1,57 @@
namespace SOR.Game.Handlers;
using System.Text.Json;
using SOR.Database.Contexts;
using SOR.Game.Abilities;
using SOR.Networking.Abstractions.Messaging;
using SOR.Networking.Abstractions.Push;
using SOR.Networking.Abstractions.Transport;
using SOR.Shared.Networking;
/// <summary>
/// game.reveal_choice_pick — the chooser submits the desired ordering of revealed
/// cards (e.g. StackDeckEffect interactive path).
/// Cards not listed in <c>OrderedIndices</c> are placed at the bottom of the deck.
/// </summary>
internal sealed class GameRevealChoicePickHandler : GameHandlerBase, IMessageHandler
{
private readonly IMessageSerializer _serializer;
private readonly GameDbContext _gameDb;
private readonly IClientPush _clientPush;
public GameRevealChoicePickHandler(
IMessageSerializer serializer,
GameDbContext gameDb,
IClientPush clientPush)
{
_serializer = serializer;
_gameDb = gameDb;
_clientPush = clientPush;
}
public string MessageType => "game.reveal_choice_pick";
public async Task<IServerMessage?> HandleAsync(
IClientMessage message,
AuthenticatedConnection connection,
CancellationToken ct)
{
var req = _serializer.DeserializePayload<GameRevealChoicePickRequest>(message.Payload);
var actorId = connection.UserId;
var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
var prevStateJson = session.StateJson!;
var state = GameEngine.Deserialize(prevStateJson);
var newState = AbilitySystem.ResumeRevealChoicePick(
state, actorId, req.RequestId, req.OrderedIndices);
await SaveStateAsync(_gameDb, session, newState, actorId, "game.reveal_choice_pick",
JsonSerializer.Serialize(req), ct);
await PushStateToPlayersAsync(_clientPush, session, newState, ct, prevStateJson);
return ServerMessage.Reply("game.reveal_choice_pick.ack", message.Seq,
new GameRevealChoicePickResponse(true));
}
}
@@ -103,6 +103,18 @@ public static class ServiceRegistration
// Interactive cost pick response (player submits card/unit selections for an interactive cost)
services.AddTransient<IMessageHandler, GameCostPickHandler>();
// Interactive cost-group pick (chooser selects which OR/XOR cost option to pay)
services.AddTransient<IMessageHandler, GameCostGroupPickHandler>();
// Interactive action-group pick (chooser selects which OR/XOR action branch to execute)
services.AddTransient<IMessageHandler, GameActionGroupPickHandler>();
// ChooseOne branch pick (Opponent/Ally chooser selects a branch)
services.AddTransient<IMessageHandler, GameBranchPickHandler>();
// Reveal-choice pick (chooser orders revealed cards, e.g. StackDeck interactive)
services.AddTransient<IMessageHandler, GameRevealChoicePickHandler>();
return services;
}
}