diff --git a/Client/origin-client/autoloads/Game.gd b/Client/origin-client/autoloads/Game.gd
index b56cbab..31bb179 100644
--- a/Client/origin-client/autoloads/Game.gd
+++ b/Client/origin-client/autoloads/Game.gd
@@ -25,6 +25,14 @@ signal game_over(winner_account_id: String, win_condition: String,
## Emitted when the server abandons an Initializing session (e.g. server restart).
signal session_abandoned(reason: String)
+## Emitted when the active player has been inactive for 5 minutes.
+## The local player (waiting for opponent) can call send_force_concede() to claim a win.
+signal opponent_inactive(session_id: String)
+
+## Emitted when the local player has been flagged as inactive.
+## Show a warning — the opponent may accept a forfeit.
+signal inactive_warning(session_id: String)
+
# ── State ─────────────────────────────────────────────────────────────────────
var session_id : String = ""
@@ -194,6 +202,10 @@ func send_concede() -> void:
_game_request("game.concede", {})
+func send_force_concede() -> void:
+ _game_request("game.force_concede", {})
+
+
func send_ascend(incoming_card_instance_id: String) -> void:
_game_request("game.ascend",
{ "incomingCardInstanceId": incoming_card_instance_id })
@@ -289,3 +301,15 @@ func _on_server_push(type: String, payload: Variant) -> void:
print("[Game] session abandoned: ", reason)
_clear_state()
session_abandoned.emit(reason)
+
+ "game.opponent_inactive":
+ var d := payload as Dictionary
+ var sid : String = str(d.get("sessionId", ""))
+ print("[Game] PUSH opponent_inactive session=", sid)
+ opponent_inactive.emit(sid)
+
+ "game.inactive_warning":
+ var d := payload as Dictionary
+ var sid : String = str(d.get("sessionId", ""))
+ print("[Game] PUSH inactive_warning session=", sid)
+ inactive_warning.emit(sid)
diff --git a/Client/origin-client/autoloads/ModelCache.gd b/Client/origin-client/autoloads/ModelCache.gd
index 57694f1..aa256c7 100644
--- a/Client/origin-client/autoloads/ModelCache.gd
+++ b/Client/origin-client/autoloads/ModelCache.gd
@@ -29,6 +29,15 @@ func _ready() -> void:
DirAccess.make_dir_recursive_absolute(_CACHE_DIR)
+## Remove a cached entry (memory + disk) so the next load_model call re-downloads it.
+## Use before retrying a previously-failed URL.
+func evict(url: String) -> void:
+ _mem.erase(url)
+ var disk := _disk_path(url)
+ if FileAccess.file_exists(disk):
+ DirAccess.remove_absolute(disk)
+
+
## Request a model by CDN URL.
## callback(node: Node3D) is called on the main thread; node may be null.
## If the same URL is already downloading, callbacks are queued and all
diff --git a/Client/origin-client/scenes/game/game_screen.gd b/Client/origin-client/scenes/game/game_screen.gd
index d68de63..57aa755 100644
--- a/Client/origin-client/scenes/game/game_screen.gd
+++ b/Client/origin-client/scenes/game/game_screen.gd
@@ -183,6 +183,8 @@ var _oneshot_callbacks : Dictionary = {} # iid → Callable (animation_finishe
# Per-unit model config.
var _model_base_angles : Dictionary = {} # iid → float (base facing angle, radians)
var _needs_face_rot : Dictionary = {} # iid → bool (team-based 180° flip flag)
+# Model retry tracking (when real GLB failed to download at placement time).
+var _unit_model_retries : Dictionary = {} # iid → attempt number (1-based, capped at 10)
## Animation name aliases: maps the canonical lower-case action to fallback track names.
## The AnimationPlayer track list is matched case-insensitively against each entry.
@@ -218,6 +220,8 @@ func _ready() -> void:
Game.state_updated.connect(_on_state_updated)
Game.game_over.connect(_on_game_over)
Game.session_abandoned.connect(_on_session_abandoned)
+ Game.opponent_inactive.connect(_on_opponent_inactive)
+ Game.inactive_warning.connect(_on_inactive_warning)
if not Game.state.is_empty():
_on_state_updated(Game.state)
@@ -232,6 +236,10 @@ func _exit_tree() -> void:
Game.game_over.disconnect(_on_game_over)
if Game.session_abandoned.is_connected(_on_session_abandoned):
Game.session_abandoned.disconnect(_on_session_abandoned)
+ if Game.opponent_inactive.is_connected(_on_opponent_inactive):
+ Game.opponent_inactive.disconnect(_on_opponent_inactive)
+ if Game.inactive_warning.is_connected(_on_inactive_warning):
+ Game.inactive_warning.disconnect(_on_inactive_warning)
# Remove chat overlay added to the viewport root.
var root := get_tree().get_root()
for child in root.get_children():
@@ -703,6 +711,7 @@ func _rebuild_units(state: Dictionary) -> void:
_oneshot_callbacks.erase(iid)
_model_base_angles.erase(iid)
_needs_face_rot.erase(iid)
+ _unit_model_retries.erase(iid)
# 3. Add units not yet present (newly played, or first render after connect).
for iid : String in desired:
@@ -801,6 +810,10 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
var needs_face_rotation : bool = _local_is_p1 != is_enemy
var base_angle : float = _facing_to_base_angle(facing_dir)
+ # Pre-set facing config so _schedule_model_retry can use it even if load fails.
+ _model_base_angles[iid] = base_angle
+ _needs_face_rot[iid] = needs_face_rotation
+
var body_ref : Variant = weakref(body)
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
# Guard: body may have been freed by a state rebuild before load finished.
@@ -810,6 +823,8 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
model_node.queue_free()
return
if model_node == null:
+ # Download failed — schedule a background retry.
+ _schedule_model_retry(iid, model_url, 1)
return
# Remove the placeholder MeshInstance3D.
@@ -821,9 +836,7 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
if not is_equal_approx(model_scale, 1.0):
model_node.scale = Vector3.ONE * model_scale
- # Store per-unit model config for movement facing and idle rotation.
- _model_base_angles[iid] = base_angle
- _needs_face_rot[iid] = needs_face_rotation
+ # Facing config was already stored above; no need to repeat.
# Apply idle/team rotation (facing toward opponent).
model_node.rotation.y = _idle_rotation(iid)
@@ -851,6 +864,78 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false)
)
+## Schedule a retry to (re)download the real GLB model for a unit.
+## attempt is 1-based; retries stop after MAX_RETRIES.
+## Only schedules if no equal-or-later retry is already pending for this unit.
+func _schedule_model_retry(iid: String, model_url: String, attempt: int) -> void:
+ const MAX_RETRIES := 10
+ if attempt > MAX_RETRIES:
+ return
+ # Don't override a retry already queued at this or a higher attempt number.
+ if _unit_model_retries.get(iid, 0) >= attempt:
+ return
+ _unit_model_retries[iid] = attempt
+ print("[GameScreen] Model retry %d/%d scheduled for %s in 60s" % [attempt, MAX_RETRIES, iid])
+ get_tree().create_timer(60.0).timeout.connect(
+ func() -> void: _do_model_retry(iid, model_url, attempt),
+ CONNECT_ONE_SHOT)
+
+
+## Execute one model retry attempt. Evicts the URL so ModelCache re-downloads it.
+## If successful, swaps out the placeholder and starts idle animation.
+## If it fails again, schedules the next attempt.
+func _do_model_retry(iid: String, model_url: String, attempt: int) -> void:
+ # Was this attempt superseded by a later scheduled retry?
+ if _unit_model_retries.get(iid, -1) != attempt:
+ return
+ # Unit may have left the board while we were waiting.
+ if not _unit_bodies.has(iid):
+ _unit_model_retries.erase(iid)
+ return
+ print("[GameScreen] Model retry %d — downloading %s" % [attempt, model_url])
+ ModelCache.evict(model_url)
+ ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
+ if model_node == null:
+ # Still failing — try again later.
+ _unit_model_retries.erase(iid)
+ _schedule_model_retry(iid, model_url, attempt + 1)
+ return
+ _unit_model_retries.erase(iid)
+ # Use the CURRENT body (may differ from when the retry was first scheduled).
+ var body := _unit_bodies.get(iid) as StaticBody3D
+ if not is_instance_valid(body):
+ model_node.queue_free()
+ return
+ # Remove placeholder mesh.
+ for child in body.get_children():
+ if child is MeshInstance3D:
+ child.queue_free()
+ # Re-read card config in case ContentCache was refreshed since placement.
+ var def_id : String = _unit_def_ids.get(iid, "")
+ var def := ContentCache.get_definition(def_id)
+ var model_scale : float = float(def.get("modelScale", 1.0))
+ var tint_str : String = str(def.get("modelTintColor", ""))
+ var model_tint : Color = Color.WHITE
+ if not tint_str.is_empty() and tint_str != "null":
+ model_tint = Color(tint_str)
+ if not is_equal_approx(model_scale, 1.0):
+ model_node.scale = Vector3.ONE * model_scale
+ model_node.rotation.y = _idle_rotation(iid)
+ _apply_model_tint(model_node, model_tint)
+ var above_tile : float = body.get_meta("above_tile", 0.28)
+ body.add_child(model_node)
+ var m_aabb := _model_local_aabb(model_node)
+ if m_aabb.size != Vector3.ZERO:
+ model_node.position.y = -above_tile - model_node.scale.y * m_aabb.position.y
+ _unit_meshes[iid] = model_node
+ var ap := _find_animation_player(model_node)
+ _anim_players[iid] = ap
+ if ap != null:
+ _play_unit_anim(iid, "idle", true)
+ print("[GameScreen] Model retry %d succeeded for %s" % [attempt, iid])
+ )
+
+
## Returns the first Model3D asset dict for a card definition, or {} if none.
func _find_model3d_asset(def: Dictionary) -> Dictionary:
for asset: Variant in def.get("assets", []):
@@ -2538,6 +2623,41 @@ func _on_game_over(winner_id: String, win_condition: String,
func _on_session_abandoned(_reason: String) -> void:
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
+
+## Pushed when the opponent (active player) has been inactive ≥ 5 minutes.
+## Offer the player a choice: accept forfeit or continue waiting.
+func _on_opponent_inactive(_sid: String) -> void:
+ var dialog := ConfirmationDialog.new()
+ dialog.title = "Opponent Inactive"
+ dialog.dialog_text = (
+ "Your opponent has not acted for 5 minutes.\n"
+ + "Do you want to claim their forfeit?"
+ )
+ dialog.ok_button_text = "Accept Forfeit"
+ dialog.cancel_button_text = "Wait"
+ add_child(dialog)
+ dialog.confirmed.connect(func() -> void:
+ dialog.queue_free()
+ Game.send_force_concede()
+ )
+ dialog.canceled.connect(func() -> void:
+ dialog.queue_free()
+ )
+ dialog.popup_centered()
+
+
+## Pushed when the local player is the inactive one — warn them.
+func _on_inactive_warning(_sid: String) -> void:
+ var dialog := AcceptDialog.new()
+ dialog.title = "Inactivity Warning"
+ dialog.dialog_text = (
+ "You have been inactive for 5 minutes.\n"
+ + "Your opponent may claim a forfeit."
+ )
+ add_child(dialog)
+ dialog.confirmed.connect(func() -> void: dialog.queue_free())
+ dialog.popup_centered()
+
# ── State → scene ─────────────────────────────────────────────────────────────
func _on_state_updated(state: Dictionary) -> void:
diff --git a/Client/origin-client/scenes/init/init_screen.gd b/Client/origin-client/scenes/init/init_screen.gd
index e062c51..67f966f 100644
--- a/Client/origin-client/scenes/init/init_screen.gd
+++ b/Client/origin-client/scenes/init/init_screen.gd
@@ -113,6 +113,52 @@ func _on_sync_progress(fetched_total: int) -> void:
func _on_sync_complete(_total: int) -> void:
+ _check_active_session()
+
+
+func _check_active_session() -> void:
+ _set_status("Checking for active games…")
+ Network.request(
+ "game.get_active_session",
+ {},
+ func(_type: String, p: Variant): _on_active_session(p),
+ func(_code: String, _msg: String): _go_to_main()
+ )
+
+
+func _on_active_session(payload: Variant) -> void:
+ var p := payload as Dictionary
+ var sid : String = str(p.get("sessionId", ""))
+ # A null or zero UUID means no active session.
+ if sid.is_empty() or sid == "00000000-0000-0000-0000-000000000000":
+ _go_to_main()
+ return
+
+ var phase : String = str(p.get("phase", "unknown"))
+ var dialog := ConfirmationDialog.new()
+ dialog.title = "Active Game Found"
+ dialog.dialog_text = "You have an active game in progress (%s phase).\nWould you like to rejoin?" % phase
+ dialog.ok_button_text = "Rejoin"
+ dialog.cancel_button_text = "Concede"
+ add_child(dialog)
+
+ dialog.confirmed.connect(func() -> void:
+ Game.session_id = sid
+ get_tree().change_scene_to_file("res://scenes/game/GameScreen.tscn")
+ )
+ dialog.canceled.connect(func() -> void:
+ _set_status("Conceding game…")
+ Network.request(
+ "game.concede",
+ { "sessionId": sid },
+ func(_t: String, _rp: Variant): _go_to_main(),
+ func(_c: String, _m: String): _go_to_main()
+ )
+ )
+ dialog.popup_centered()
+
+
+func _go_to_main() -> void:
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
diff --git a/Server/src/SOR.Database/Entities/Game/GameSession.cs b/Server/src/SOR.Database/Entities/Game/GameSession.cs
index eddff6b..61aea8b 100644
--- a/Server/src/SOR.Database/Entities/Game/GameSession.cs
+++ b/Server/src/SOR.Database/Entities/Game/GameSession.cs
@@ -48,6 +48,15 @@ public sealed class GameSession
///
public string? WinCondition { get; set; }
+ // ── Inactivity tracking ──────────────────────────────────────────────────────
+
+ ///
+ /// Timestamp of the last game action (set by SaveStateAsync after every action).
+ /// Used by GameInactivityMonitorService to detect stalled games.
+ /// Null for sessions that predate this field.
+ ///
+ public DateTimeOffset? LastActionAt { get; set; }
+
// ── Live state ───────────────────────────────────────────────────────────
///
diff --git a/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.Designer.cs b/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.Designer.cs
new file mode 100644
index 0000000..a7dee20
--- /dev/null
+++ b/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.Designer.cs
@@ -0,0 +1,312 @@
+//
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
+using SOR.Database.Contexts;
+
+#nullable disable
+
+namespace SOR.Database.Migrations.Game
+{
+ [DbContext(typeof(GameDbContext))]
+ [Migration("20260317000001_AddLastActionAt")]
+ partial class AddLastActionAt
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasDefaultSchema("game")
+ .HasAnnotation("ProductVersion", "8.0.0")
+ .HasAnnotation("Relational:MaxIdentifierLength", 63);
+
+ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.CustomLobby", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DrawPerTurnOverride")
+ .HasColumnType("integer");
+
+ b.Property("FirstPlayerSkipsDrawOverride")
+ .HasColumnType("boolean");
+
+ b.Property("GameSessionId")
+ .HasColumnType("uuid");
+
+ b.Property("GuestAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("GuestDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("HostAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("HostDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSizeOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurnOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpCapOverride")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCapOverride")
+ .HasColumnType("boolean");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("HostAccountId");
+
+ b.HasIndex("Status", "CreatedAt");
+
+ b.ToTable("custom_lobbies", "game");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("ActionType")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("ActorAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("GameSessionId")
+ .HasColumnType("uuid");
+
+ b.Property("OccurredAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("PayloadJson")
+ .HasColumnType("jsonb")
+ .HasColumnName("payload");
+
+ b.Property("ResultJson")
+ .HasColumnType("jsonb")
+ .HasColumnName("result");
+
+ b.Property("SequenceNumber")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ActorAccountId");
+
+ b.HasIndex("GameSessionId", "SequenceNumber")
+ .IsUnique();
+
+ b.ToTable("action_logs", "game");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.GameRuleSet", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("BoardHeight")
+ .HasColumnType("integer");
+
+ b.Property("BoardWidth")
+ .HasColumnType("integer");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("DrawPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("FirstPlayerSkipsDraw")
+ .HasColumnType("boolean");
+
+ b.Property("IsCustomDefault")
+ .HasColumnType("boolean");
+
+ b.Property("IsRankedDefault")
+ .HasColumnType("boolean");
+
+ b.Property("LoserOpReward")
+ .HasColumnType("integer");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("OpeningHandSize")
+ .HasColumnType("integer");
+
+ b.Property("RankDiffOpMultiplierPct")
+ .HasColumnType("integer");
+
+ b.Property("SpAccumulationPerTurn")
+ .HasColumnType("integer");
+
+ b.Property("SpCap")
+ .HasColumnType("integer");
+
+ b.Property("SpHasCap")
+ .HasColumnType("boolean");
+
+ b.Property("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("WinnerOpReward")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex("IsCustomDefault");
+
+ b.HasIndex("IsRankedDefault");
+
+ b.ToTable("game_rule_sets", "game");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("EndedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("LastActionAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("PlayerOneAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("PlayerOneDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("PlayerOneReady")
+ .HasColumnType("boolean");
+
+ b.Property("PlayerTwoAccountId")
+ .HasColumnType("uuid");
+
+ b.Property("PlayerTwoDeckId")
+ .HasColumnType("uuid");
+
+ b.Property("PlayerTwoReady")
+ .HasColumnType("boolean");
+
+ b.Property("RuleSnapshotJson")
+ .HasColumnType("jsonb")
+ .HasColumnName("rule_snapshot");
+
+ b.Property("StartedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("StateJson")
+ .HasColumnType("jsonb")
+ .HasColumnName("state");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property("WinCondition")
+ .HasColumnType("text");
+
+ b.Property("WinnerAccountId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("PlayerOneAccountId");
+
+ b.HasIndex("PlayerTwoAccountId");
+
+ b.HasIndex("Status", "CreatedAt");
+
+ b.ToTable("game_sessions", "game");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.MatchmakingEntry", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property("AccountId")
+ .HasColumnType("uuid");
+
+ b.Property("DeckId")
+ .HasColumnType("uuid");
+
+ b.Property("JoinedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("MatchedGameSessionId")
+ .HasColumnType("uuid");
+
+ b.Property("RankScore")
+ .HasColumnType("integer");
+
+ b.Property("ResolvedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AccountId", "Status");
+
+ b.HasIndex("Status", "RankScore");
+
+ b.ToTable("matchmaking_entries", "game");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.GameActionLog", b =>
+ {
+ b.HasOne("SOR.Database.Entities.Game.GameSession", "Session")
+ .WithMany("ActionLog")
+ .HasForeignKey("GameSessionId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Session");
+ });
+
+ modelBuilder.Entity("SOR.Database.Entities.Game.GameSession", b =>
+ {
+ b.Navigation("ActionLog");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.cs b/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.cs
new file mode 100644
index 0000000..a6fe9be
--- /dev/null
+++ b/Server/src/SOR.Database/Migrations/Game/20260317000001_AddLastActionAt.cs
@@ -0,0 +1,31 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace SOR.Database.Migrations.Game
+{
+ ///
+ public partial class AddLastActionAt : Migration
+ {
+ ///
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn(
+ name: "LastActionAt",
+ schema: "game",
+ table: "game_sessions",
+ type: "timestamp with time zone",
+ nullable: true);
+ }
+
+ ///
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropColumn(
+ name: "LastActionAt",
+ schema: "game",
+ table: "game_sessions");
+ }
+ }
+}
diff --git a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
index 25abad5..19c966e 100644
--- a/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
+++ b/Server/src/SOR.Database/Migrations/Game/GameDbContextModelSnapshot.cs
@@ -198,6 +198,9 @@ namespace SOR.Database.Migrations.Game
b.Property("EndedAt")
.HasColumnType("timestamp with time zone");
+ b.Property("LastActionAt")
+ .HasColumnType("timestamp with time zone");
+
b.Property("PlayerOneAccountId")
.HasColumnType("uuid");
diff --git a/Server/src/SOR.Game/GameInactivityMonitorService.cs b/Server/src/SOR.Game/GameInactivityMonitorService.cs
new file mode 100644
index 0000000..8be98e4
--- /dev/null
+++ b/Server/src/SOR.Game/GameInactivityMonitorService.cs
@@ -0,0 +1,118 @@
+namespace SOR.Game;
+
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using SOR.Database.Contexts;
+using SOR.Database.Enums;
+using SOR.Networking.Abstractions.Push;
+using SOR.Shared.Networking;
+
+///
+/// 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:
+/// • Pushes game.inactive_warning to the active player (whose turn it is).
+/// • Pushes game.opponent_inactive to the waiting player (who can then
+/// choose to accept the forfeit via game.force_concede).
+///
+/// Each session is only notified once per service lifetime (tracked in
+/// _notifiedSessions). If the session later becomes Completed/Abandoned,
+/// it drops out of the Active query naturally.
+///
+internal sealed class GameInactivityMonitorService : BackgroundService
+{
+ private static readonly TimeSpan InactivityThreshold = TimeSpan.FromMinutes(5);
+ private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(60);
+
+ private readonly IServiceScopeFactory _scopeFactory;
+ private readonly ILogger _logger;
+
+ // Track which sessions we have already notified so we don't spam.
+ private readonly HashSet _notifiedSessions = new();
+
+ public GameInactivityMonitorService(
+ IServiceScopeFactory scopeFactory,
+ ILogger logger)
+ {
+ _scopeFactory = scopeFactory;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ // Wait a bit after startup so the DB is warmed up.
+ await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await CheckInactiveSessionsAsync(stoppingToken);
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex, "GameInactivityMonitor: error during poll — will retry next cycle.");
+ }
+
+ await Task.Delay(PollInterval, stoppingToken);
+ }
+ }
+
+ private async Task CheckInactiveSessionsAsync(CancellationToken ct)
+ {
+ await using var scope = _scopeFactory.CreateAsyncScope();
+ var gameDb = scope.ServiceProvider.GetRequiredService();
+ var clientPush = scope.ServiceProvider.GetRequiredService();
+
+ var threshold = DateTimeOffset.UtcNow - InactivityThreshold;
+
+ var staleSessions = await gameDb.GameSessions
+ .Where(s => s.Status == GameSessionStatus.Active
+ && s.LastActionAt != null
+ && s.LastActionAt < threshold
+ && s.StateJson != null)
+ .ToListAsync(ct);
+
+ foreach (var session in staleSessions)
+ {
+ if (_notifiedSessions.Contains(session.Id))
+ continue;
+
+ _notifiedSessions.Add(session.Id);
+
+ try
+ {
+ var state = GameEngine.Deserialize(session.StateJson!);
+ var activeId = state.ActivePlayerAccountId; // inactive (hasn't acted)
+ var otherId = session.PlayerOneAccountId.ToString() == activeId
+ ? session.PlayerTwoAccountId.ToString()
+ : session.PlayerOneAccountId.ToString();
+
+ _logger.LogInformation(
+ "GameInactivityMonitor: session {SessionId} — active player {ActiveId} inactive for >{Minutes} min.",
+ session.Id, activeId, (int)InactivityThreshold.TotalMinutes);
+
+ await Task.WhenAll(
+ clientPush.PushAsync(activeId,
+ ServerMessage.Push("game.inactive_warning",
+ new GameInactiveWarningPush(session.Id)), ct),
+ clientPush.PushAsync(otherId,
+ ServerMessage.Push("game.opponent_inactive",
+ new GameOpponentInactivePush(session.Id)), ct));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogWarning(ex,
+ "GameInactivityMonitor: could not push notifications for session {SessionId}.",
+ session.Id);
+ }
+ }
+ }
+}
diff --git a/Server/src/SOR.Game/GameMessages.cs b/Server/src/SOR.Game/GameMessages.cs
index f9ed7d0..4090923 100644
--- a/Server/src/SOR.Game/GameMessages.cs
+++ b/Server/src/SOR.Game/GameMessages.cs
@@ -80,6 +80,12 @@ public sealed record GameActivateAbilityRequest(
int AbilityIndex,
IReadOnlyList? Targets = null);
+/// Query whether the caller has an Active game session they can rejoin.
+public sealed record GameGetActiveSessionRequest();
+
+/// Force-concede a game where the opponent has been inactive.
+public sealed record GameForceConcedeRequest(Guid SessionId);
+
// ── Custom lobby requests ─────────────────────────────────────────────────────
/// Create a new custom lobby. Host provides their deck and optional rule overrides.
@@ -140,6 +146,14 @@ public sealed record GameTransitionResponse(GameStateDto State);
public sealed record GameActivateAbilityResponse(GameStateDto State);
+///
+/// Response for game.get_active_session.
+/// SessionId is null when the player has no in-progress game.
+///
+public sealed record GameGetActiveSessionResponse(Guid? SessionId, string? Phase);
+
+public sealed record GameForceConcedeResponse(GameStateDto State);
+
// ── Custom lobby responses ─────────────────────────────────────────────────────
public sealed record CreateCustomLobbyResponse(
@@ -187,6 +201,18 @@ public sealed record GameOverPush(
///
public sealed record GameSessionAbandonedPush(Guid SessionId, string Reason);
+///
+/// Pushed to the active player when they have been inactive for 5 minutes.
+/// Their opponent now has the option to accept the forfeit.
+///
+public sealed record GameInactiveWarningPush(Guid SessionId);
+
+///
+/// Pushed to the non-active player when the opponent has been inactive for 5 minutes.
+/// The client should offer "Accept forfeit" or "Wait" options.
+///
+public sealed record GameOpponentInactivePush(Guid SessionId);
+
///
/// 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.
diff --git a/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs b/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs
new file mode 100644
index 0000000..63f9f51
--- /dev/null
+++ b/Server/src/SOR.Game/Handlers/GameForceConcedeHandler.cs
@@ -0,0 +1,86 @@
+namespace SOR.Game.Handlers;
+
+using System.Text.Json;
+using SOR.Database.Contexts;
+using SOR.Networking.Abstractions.EventBus;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Push;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Shared.Networking;
+
+///
+/// game.force_concede — allows the non-inactive player to claim a win when
+/// the opponent has been inactive for at least 5 minutes.
+///
+/// Validates:
+/// 1. The caller is NOT the active player (i.e., it is the opponent's turn that is stalled).
+/// 2. The session's LastActionAt is older than 5 minutes.
+///
+/// On success: finalizes the game with the caller as winner, win condition "inactive".
+///
+internal sealed class GameForceConcedeHandler : GameHandlerBase, IMessageHandler
+{
+ private static readonly TimeSpan InactivityThreshold = TimeSpan.FromMinutes(5);
+
+ private readonly IMessageSerializer _serializer;
+ private readonly GameDbContext _gameDb;
+ private readonly SorIdentityDbContext _identityDb;
+ private readonly IClientPush _clientPush;
+ private readonly IEventBus _eventBus;
+
+ public GameForceConcedeHandler(
+ IMessageSerializer serializer,
+ GameDbContext gameDb,
+ SorIdentityDbContext identityDb,
+ IClientPush clientPush,
+ IEventBus eventBus)
+ {
+ _serializer = serializer;
+ _gameDb = gameDb;
+ _identityDb = identityDb;
+ _clientPush = clientPush;
+ _eventBus = eventBus;
+ }
+
+ public string MessageType => "game.force_concede";
+
+ public async Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken ct)
+ {
+ var req = _serializer.DeserializePayload(message.Payload);
+ var actorId = connection.UserId;
+
+ var session = await LoadActiveSessionAsync(_gameDb, req.SessionId, actorId, ct);
+ var state = GameEngine.Deserialize(session.StateJson!);
+
+ // The caller must NOT be the active player — they are the waiting player.
+ if (state.ActivePlayerAccountId == actorId)
+ throw new GameException("YOU_ARE_THE_ACTIVE_PLAYER");
+
+ // Check inactivity threshold.
+ if (session.LastActionAt == null ||
+ session.LastActionAt > DateTimeOffset.UtcNow - InactivityThreshold)
+ throw new GameException("OPPONENT_NOT_INACTIVE");
+
+ // Treat as the inactive player conceding.
+ var inactivePlayerId = state.ActivePlayerAccountId;
+ var newState = GameEngine.Concede(state, inactivePlayerId);
+ var dto = GameEngine.ToDto(newState, actorId);
+
+ await SaveStateAsync(_gameDb, session, newState, actorId, "game.force_concede",
+ JsonSerializer.Serialize(req), ct, JsonSerializer.Serialize(dto));
+
+ await FinalizeGameAsync(
+ _gameDb, _identityDb, _clientPush, _eventBus,
+ session,
+ winnerAccountId: Guid.Parse(actorId),
+ loserAccountId: Guid.Parse(inactivePlayerId),
+ winCondition: "inactive",
+ ct);
+
+ return ServerMessage.Reply("game.force_concede.ack", message.Seq,
+ new GameForceConcedeResponse(dto));
+ }
+}
diff --git a/Server/src/SOR.Game/Handlers/GameGetActiveSessionHandler.cs b/Server/src/SOR.Game/Handlers/GameGetActiveSessionHandler.cs
new file mode 100644
index 0000000..87b6469
--- /dev/null
+++ b/Server/src/SOR.Game/Handlers/GameGetActiveSessionHandler.cs
@@ -0,0 +1,55 @@
+namespace SOR.Game.Handlers;
+
+using Microsoft.EntityFrameworkCore;
+using SOR.Database.Contexts;
+using SOR.Database.Enums;
+using SOR.Networking.Abstractions.Messaging;
+using SOR.Networking.Abstractions.Transport;
+using SOR.Shared.Networking;
+
+///
+/// game.get_active_session — returns the caller's in-progress game session, if any.
+///
+/// Used by the client on startup/login to detect an active game that can be rejoined
+/// (e.g. after a crash or disconnect). No session ID is required in the request;
+/// the authenticated actor ID is used to find the session.
+///
+/// Returns GameGetActiveSessionResponse with SessionId = null when no active session exists.
+///
+internal sealed class GameGetActiveSessionHandler : IMessageHandler
+{
+ private readonly GameDbContext _gameDb;
+
+ public GameGetActiveSessionHandler(GameDbContext gameDb)
+ {
+ _gameDb = gameDb;
+ }
+
+ public string MessageType => "game.get_active_session";
+
+ public async Task HandleAsync(
+ IClientMessage message,
+ AuthenticatedConnection connection,
+ CancellationToken ct)
+ {
+ var actorId = Guid.Parse(connection.UserId);
+
+ var session = await _gameDb.GameSessions
+ .AsNoTracking()
+ .Where(s => (s.PlayerOneAccountId == actorId || s.PlayerTwoAccountId == actorId)
+ && s.Status == GameSessionStatus.Active
+ && s.StateJson != null)
+ .OrderByDescending(s => s.CreatedAt)
+ .FirstOrDefaultAsync(ct);
+
+ if (session == null)
+ return ServerMessage.Reply("game.get_active_session.ack", message.Seq,
+ new GameGetActiveSessionResponse(null, null));
+
+ // Deserialize state to extract the current phase.
+ var state = GameEngine.Deserialize(session.StateJson!);
+
+ return ServerMessage.Reply("game.get_active_session.ack", message.Seq,
+ new GameGetActiveSessionResponse(session.Id, state.Phase.ToString()));
+ }
+}
diff --git a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs
index 6377cf5..1a821cc 100644
--- a/Server/src/SOR.Game/Handlers/GameHandlerBase.cs
+++ b/Server/src/SOR.Game/Handlers/GameHandlerBase.cs
@@ -69,7 +69,8 @@ internal abstract class GameHandlerBase
string? resultJson = null)
{
var seqNum = state.NextActionSequence++; // increment before serialize so the saved JSON reflects the consumed number
- session.StateJson = GameEngine.Serialize(state);
+ session.StateJson = GameEngine.Serialize(state);
+ session.LastActionAt = DateTimeOffset.UtcNow;
gameDb.ActionLogs.Add(new GameActionLog
{
GameSessionId = session.Id,
diff --git a/Server/src/SOR.Game/ServiceRegistration.cs b/Server/src/SOR.Game/ServiceRegistration.cs
index ec8dfd7..91b11ee 100644
--- a/Server/src/SOR.Game/ServiceRegistration.cs
+++ b/Server/src/SOR.Game/ServiceRegistration.cs
@@ -24,8 +24,12 @@ public static class ServiceRegistration
// Abandons any Initializing sessions left over from a previous process (redeploy/crash).
services.AddHostedService();
+ // Monitors active sessions for player inactivity.
+ services.AddHostedService();
+
services.AddTransient();
services.AddTransient();
+ services.AddTransient();
services.AddTransient();
services.AddTransient();
services.AddTransient();
@@ -37,6 +41,7 @@ public static class ServiceRegistration
services.AddTransient();
services.AddTransient();
services.AddTransient();
+ services.AddTransient();
// Custom lobby handlers
services.AddTransient();