Two-tier inactivity: mutual idle blocks force-concede at 10 min

Tier 1 (5 min, unchanged):
- Active player: game.inactive_warning — "you may be forfeited"
- Waiting player: game.opponent_inactive — "Accept Forfeit / Wait"

Tier 2 (10 min — mutual idle):
- If the game is still stalled after 10 min the waiting player also
  hasn't claimed forfeit, so both are treated as mutually idle
- Sends game.both_idle_warning to BOTH players
- Client closes any open tier-1 dialogs and shows "Wait" only —
  no concede or force-concede available
- Prevents the tactic of both players going idle to pressure the
  other into conceding

Monitor service now prunes notified sets on each poll so sessions
that become active again can be re-notified if they stall again.

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-03-21 06:16:13 -04:00
co-authored by Claude Happy
parent 6de3e6b79d
commit c93aaf64c0
4 changed files with 103 additions and 36 deletions
+10
View File
@@ -33,6 +33,10 @@ signal opponent_inactive(session_id: String)
## Show a warning — the opponent may accept a forfeit. ## Show a warning — the opponent may accept a forfeit.
signal inactive_warning(session_id: String) signal inactive_warning(session_id: String)
## Emitted when both players have been idle for 10 minutes (mutual idle).
## Both players must wait — no concede or force-concede is allowed.
signal both_idle_warning(session_id: String)
# ── State ───────────────────────────────────────────────────────────────────── # ── State ─────────────────────────────────────────────────────────────────────
var session_id : String = "" var session_id : String = ""
@@ -345,3 +349,9 @@ func _on_server_push(type: String, payload: Variant) -> void:
var sid : String = str(d.get("sessionId", "")) var sid : String = str(d.get("sessionId", ""))
print("[Game] PUSH inactive_warning session=", sid) print("[Game] PUSH inactive_warning session=", sid)
inactive_warning.emit(sid) inactive_warning.emit(sid)
"game.both_idle_warning":
var d := payload as Dictionary
var sid : String = str(d.get("sessionId", ""))
print("[Game] PUSH both_idle_warning session=", sid)
both_idle_warning.emit(sid)
@@ -225,6 +225,7 @@ func _ready() -> void:
Game.session_abandoned.connect(_on_session_abandoned) Game.session_abandoned.connect(_on_session_abandoned)
Game.opponent_inactive.connect(_on_opponent_inactive) Game.opponent_inactive.connect(_on_opponent_inactive)
Game.inactive_warning.connect(_on_inactive_warning) Game.inactive_warning.connect(_on_inactive_warning)
Game.both_idle_warning.connect(_on_both_idle_warning)
if Game.is_spectating: if Game.is_spectating:
_is_spectating = true _is_spectating = true
@@ -253,6 +254,8 @@ func _exit_tree() -> void:
Game.opponent_inactive.disconnect(_on_opponent_inactive) Game.opponent_inactive.disconnect(_on_opponent_inactive)
if Game.inactive_warning.is_connected(_on_inactive_warning): if Game.inactive_warning.is_connected(_on_inactive_warning):
Game.inactive_warning.disconnect(_on_inactive_warning) Game.inactive_warning.disconnect(_on_inactive_warning)
if Game.both_idle_warning.is_connected(_on_both_idle_warning):
Game.both_idle_warning.disconnect(_on_both_idle_warning)
# Remove chat overlay added to the viewport root. # Remove chat overlay added to the viewport root.
var root := get_tree().get_root() var root := get_tree().get_root()
for child in root.get_children(): for child in root.get_children():
@@ -2814,6 +2817,26 @@ func _on_inactive_warning(_sid: String) -> void:
dialog.confirmed.connect(func() -> void: dialog.queue_free()) dialog.confirmed.connect(func() -> void: dialog.queue_free())
dialog.popup_centered() dialog.popup_centered()
## Pushed when both players have been idle for 10 minutes.
## Closes any open inactive dialog and shows a Wait-only prompt to both players.
func _on_both_idle_warning(_sid: String) -> void:
# Close any lingering inactive dialogs from tier-1.
for child in get_children():
if child is ConfirmationDialog or child is AcceptDialog:
child.queue_free()
var dialog := AcceptDialog.new()
dialog.title = "Both Players Idle"
dialog.dialog_text = (
"Both players have been idle for 10 minutes.\n"
+ "Please return to continue the game."
)
dialog.ok_button_text = "Wait"
add_child(dialog)
dialog.confirmed.connect(func() -> void: dialog.queue_free())
dialog.popup_centered()
# ── State → scene ───────────────────────────────────────────────────────────── # ── State → scene ─────────────────────────────────────────────────────────────
func _on_state_updated(state: Dictionary) -> void: func _on_state_updated(state: Dictionary) -> void:
@@ -10,28 +10,31 @@ using SOR.Networking.Abstractions.Push;
using SOR.Shared.Networking; using SOR.Shared.Networking;
/// <summary> /// <summary>
/// Background service that polls for game sessions where no action has been taken /// Background service that polls for game sessions where no action has been taken.
/// for InactivityThreshold minutes.
/// ///
/// When a stalled session is found for the first time: /// Tier 1 — 5 min idle (one player's turn stalled):
/// • Pushes game.inactive_warning to the active player (whose turn it is). /// • Pushes game.inactive_warning to the active player.
/// • Pushes game.opponent_inactive to the waiting player (who can then /// • Pushes game.opponent_inactive to the waiting player, who may claim a forfeit.
/// choose to accept the forfeit via game.force_concede).
/// ///
/// Each session is only notified once per service lifetime (tracked in /// Tier 2 — 10 min idle (waiting player also hasn't claimed forfeit → mutual idle):
/// _notifiedSessions). If the session later becomes Completed/Abandoned, /// • Pushes game.both_idle_warning to BOTH players.
/// it drops out of the Active query naturally. /// • Client shows only a "Wait" option — no concede or force-concede allowed.
/// • Prevents the tactic of both players going idle to pressure the other to concede.
///
/// Sessions are tracked in in-memory sets; if a player acts the session drops out of
/// the stale query and both sets are pruned on the next poll.
/// </summary> /// </summary>
internal sealed class GameInactivityMonitorService : BackgroundService internal sealed class GameInactivityMonitorService : BackgroundService
{ {
private static readonly TimeSpan InactivityThreshold = TimeSpan.FromMinutes(5); private static readonly TimeSpan Tier1Threshold = TimeSpan.FromMinutes(5);
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(60); private static readonly TimeSpan Tier2Threshold = TimeSpan.FromMinutes(10);
private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(60);
private readonly IServiceScopeFactory _scopeFactory; private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<GameInactivityMonitorService> _logger; private readonly ILogger<GameInactivityMonitorService> _logger;
// Track which sessions we have already notified so we don't spam. private readonly HashSet<Guid> _tier1Notified = new();
private readonly HashSet<Guid> _notifiedSessions = new(); private readonly HashSet<Guid> _tier2Notified = new();
public GameInactivityMonitorService( public GameInactivityMonitorService(
IServiceScopeFactory scopeFactory, IServiceScopeFactory scopeFactory,
@@ -67,45 +70,69 @@ internal sealed class GameInactivityMonitorService : BackgroundService
private async Task CheckInactiveSessionsAsync(CancellationToken ct) private async Task CheckInactiveSessionsAsync(CancellationToken ct)
{ {
await using var scope = _scopeFactory.CreateAsyncScope(); await using var scope = _scopeFactory.CreateAsyncScope();
var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>(); var gameDb = scope.ServiceProvider.GetRequiredService<GameDbContext>();
var clientPush = scope.ServiceProvider.GetRequiredService<IClientPush>(); var clientPush = scope.ServiceProvider.GetRequiredService<IClientPush>();
var threshold = DateTimeOffset.UtcNow - InactivityThreshold; var now = DateTimeOffset.UtcNow;
var tier1Cutoff = now - Tier1Threshold;
var tier2Cutoff = now - Tier2Threshold;
var staleSessions = await gameDb.GameSessions var staleSessions = await gameDb.GameSessions
.Where(s => s.Status == GameSessionStatus.Active .Where(s => s.Status == GameSessionStatus.Active
&& s.LastActionAt != null && s.LastActionAt != null
&& s.LastActionAt < threshold && s.LastActionAt < tier1Cutoff
&& s.StateJson != null) && s.StateJson != null)
.ToListAsync(ct); .ToListAsync(ct);
// Prune notified sets: remove sessions no longer stale (player acted since last poll).
var staleIds = staleSessions.Select(s => s.Id).ToHashSet();
_tier1Notified.IntersectWith(staleIds);
_tier2Notified.IntersectWith(staleIds);
foreach (var session in staleSessions) foreach (var session in staleSessions)
{ {
if (_notifiedSessions.Contains(session.Id))
continue;
_notifiedSessions.Add(session.Id);
try try
{ {
var state = GameEngine.Deserialize(session.StateJson!); var p1 = session.PlayerOneAccountId.ToString();
var activeId = state.ActivePlayerAccountId; // inactive (hasn't acted) var p2 = session.PlayerTwoAccountId.ToString();
var otherId = session.PlayerOneAccountId.ToString() == activeId
? session.PlayerTwoAccountId.ToString()
: session.PlayerOneAccountId.ToString();
_logger.LogInformation( // ── Tier 2: mutual idle (10 min) ──────────────────────────────
"GameInactivityMonitor: session {SessionId} — active player {ActiveId} inactive for >{Minutes} min.", if (!_tier2Notified.Contains(session.Id) && session.LastActionAt < tier2Cutoff)
session.Id, activeId, (int)InactivityThreshold.TotalMinutes); {
_tier2Notified.Add(session.Id);
await Task.WhenAll( _logger.LogInformation(
clientPush.PushAsync(activeId, "GameInactivityMonitor: session {Id} — both players idle >10 min. Sending both_idle_warning.",
ServerMessage.Push("game.inactive_warning", session.Id);
await Task.WhenAll(
clientPush.PushAsync(p1, ServerMessage.Push("game.both_idle_warning",
new GameBothIdlePush(session.Id)), ct),
clientPush.PushAsync(p2, ServerMessage.Push("game.both_idle_warning",
new GameBothIdlePush(session.Id)), ct));
continue;
}
// ── Tier 1: one player idle (5 min) ───────────────────────────
if (!_tier1Notified.Contains(session.Id))
{
_tier1Notified.Add(session.Id);
var state = GameEngine.Deserialize(session.StateJson!);
var activeId = state.ActivePlayerAccountId;
var otherId = p1 == activeId ? p2 : p1;
_logger.LogInformation(
"GameInactivityMonitor: session {Id} — active player {ActiveId} idle >5 min.",
session.Id, activeId);
await Task.WhenAll(
clientPush.PushAsync(activeId, ServerMessage.Push("game.inactive_warning",
new GameInactiveWarningPush(session.Id)), ct), new GameInactiveWarningPush(session.Id)), ct),
clientPush.PushAsync(otherId, clientPush.PushAsync(otherId, ServerMessage.Push("game.opponent_inactive",
ServerMessage.Push("game.opponent_inactive",
new GameOpponentInactivePush(session.Id)), ct)); new GameOpponentInactivePush(session.Id)), ct));
}
} }
catch (Exception ex) catch (Exception ex)
{ {
+7
View File
@@ -326,6 +326,13 @@ public sealed record GameInactiveWarningPush(Guid SessionId);
/// </summary> /// </summary>
public sealed record GameOpponentInactivePush(Guid SessionId); public sealed record GameOpponentInactivePush(Guid SessionId);
/// <summary>
/// Pushed to BOTH players when neither has acted for 10 minutes (mutual idle).
/// The client must show only a "Wait" option — no concede or force-concede.
/// Replaces any open inactive dialog on the client.
/// </summary>
public sealed record GameBothIdlePush(Guid SessionId);
/// <summary> /// <summary>
/// Pushed to both players when a custom lobby is full and a GameSession has been created. /// Pushed to both players when a custom lobby is full and a GameSession has been created.
/// Players should navigate to the game screen and send game.ready. /// Players should navigate to the game screen and send game.ready.