From cdbcf5e2d1c0e8565fdb9cecb1750bd3a8b64515 Mon Sep 17 00:00:00 2001 From: dingo Date: Tue, 14 Apr 2026 23:27:46 -0400 Subject: [PATCH] feat(admin): end AI matches from admin portal AiMatchService: - GetActiveMatchesAsync: queries CustomLobbies joined to GameSessions to return all running AI vs AI sessions with display names. - ForceEndMatchAsync: marks session Abandoned + lobby Completed; the AI polling loops detect the status change within ~1 s and exit cleanly. - ActiveAiMatch DTO returned by both methods. AiMatchPage: - Active AI Matches section loads on page init and has a Refresh button; each row has an End button that calls ForceEndMatchAsync and refreshes. - Created This Session table also gets an End button per row. - Spinner shown on the End button while the request is in flight. Generated with [Claude Code](https://claude.ai/code) via [Happy](https://happy.engineering) Co-Authored-By: Claude Co-Authored-By: Happy --- .../Components/Pages/Ai/AiMatchPage.razor | 103 ++++++++++++++++-- Server/src/SOR.Ai/Lobby/AiMatchService.cs | 88 +++++++++++++++ 2 files changed, 184 insertions(+), 7 deletions(-) diff --git a/Server/src/SOR.Admin/Components/Pages/Ai/AiMatchPage.razor b/Server/src/SOR.Admin/Components/Pages/Ai/AiMatchPage.razor index 68f9cb7..6e1dc58 100644 --- a/Server/src/SOR.Admin/Components/Pages/Ai/AiMatchPage.razor +++ b/Server/src/SOR.Admin/Components/Pages/Ai/AiMatchPage.razor @@ -228,7 +228,60 @@ - + +
+
+ Active AI Matches + +
+ @if (_activeMatches.Count == 0) + { +
No active AI matches.
+ } + else + { +
+ + + + + + + + + + + + + @foreach (var m in _activeMatches) + { + + + + + + + + + } + +
Session IDPlayer 1Player 2StatusStarted
@m.SessionId.ToString()[..8]…@m.Player1Name@m.Player2Name@m.Status@m.CreatedAt.ToString("HH:mm:ss") + +
+
+ } +
+ + @if (_recentMatches.Count > 0) {
@@ -241,20 +294,26 @@ Player 1 Player 2 Created + @foreach (var m in _recentMatches) { - - - @m.SessionId.ToString()[..8]… - - + @m.SessionId.ToString()[..8]… @m.Player1Name @m.Player2Name @m.CreatedAt.ToString("HH:mm:ss") + + + } @@ -276,7 +335,37 @@ private bool _busy; private string? _error; - private readonly List _recentMatches = []; + private readonly List _recentMatches = []; + private List _activeMatches = []; + private readonly HashSet _endingSessionIds = []; + private bool _loadingActive; + + protected override async Task OnInitializedAsync() + => await RefreshActiveAsync(); + + private async Task RefreshActiveAsync() + { + _loadingActive = true; StateHasChanged(); + try { _activeMatches = (await MatchService.GetActiveMatchesAsync()).ToList(); } + catch (Exception ex) { _error = "Failed to load active matches: " + ex.Message; } + finally { _loadingActive = false; StateHasChanged(); } + } + + private async Task EndMatchAsync(Guid sessionId) + { + _endingSessionIds.Add(sessionId); StateHasChanged(); + try + { + await MatchService.ForceEndMatchAsync(sessionId); + await RefreshActiveAsync(); + } + catch (Exception ex) { _error = ex.Message; } + finally + { + _endingSessionIds.Remove(sessionId); + StateHasChanged(); + } + } private static string DifficultyName(int d) => d switch { diff --git a/Server/src/SOR.Ai/Lobby/AiMatchService.cs b/Server/src/SOR.Ai/Lobby/AiMatchService.cs index 51392db..2e647b8 100644 --- a/Server/src/SOR.Ai/Lobby/AiMatchService.cs +++ b/Server/src/SOR.Ai/Lobby/AiMatchService.cs @@ -40,6 +40,94 @@ public sealed class AiMatchService _logger = logger; } + // ── Active match query ──────────────────────────────────────────────────── + + /// + /// Returns all game sessions that were started from an AI-vs-AI lobby + /// (i.e. the linked CustomLobby has AiSlotsJson set) and are still active. + /// + public async Task> GetActiveMatchesAsync( + CancellationToken ct = default) + { + // Find active sessions linked to lobbies that have AiSlotsJson populated. + var rows = await _gameDb.CustomLobbies + .AsNoTracking() + .Where(l => l.AiSlotsJson != null + && l.GameSessionId != null + && l.Status == CustomLobbyStatus.Started) + .Join(_gameDb.GameSessions.AsNoTracking() + .Where(s => s.Status == GameSessionStatus.Active + || s.Status == GameSessionStatus.Initializing), + l => l.GameSessionId, + s => (Guid?)s.Id, + (l, s) => new { Lobby = l, Session = s }) + .ToListAsync(ct); + + if (rows.Count == 0) return []; + + // Resolve display names from identity DB. + var allIds = rows.SelectMany(r => new[] { r.Session.PlayerOneAccountId, r.Session.PlayerTwoAccountId }) + .Distinct().ToList(); + var names = await _identityDb.Users + .AsNoTracking() + .Where(u => allIds.Contains(u.Id)) + .Select(u => new { u.Id, Name = u.DisplayName ?? u.UserName ?? u.Id.ToString().Substring(0, 8) }) + .ToDictionaryAsync(u => u.Id, u => u.Name, ct); + + return rows.Select(r => new ActiveAiMatch( + r.Session.Id, + r.Session.PlayerOneAccountId, + names.GetValueOrDefault(r.Session.PlayerOneAccountId, r.Session.PlayerOneAccountId.ToString()[..8]), + r.Session.PlayerTwoAccountId, + names.GetValueOrDefault(r.Session.PlayerTwoAccountId, r.Session.PlayerTwoAccountId.ToString()[..8]), + r.Session.Status, + r.Session.CreatedAt, + r.Lobby.Name ?? "AI Match")).ToList(); + } + + // ── Force-end ───────────────────────────────────────────────────────────── + + /// + /// Immediately terminates an active AI match by marking the session Abandoned + /// and the linked lobby Completed. The AI polling loops will detect the status + /// change on their next poll (within ~1 s) and exit cleanly. + /// + public async Task ForceEndMatchAsync(Guid sessionId, CancellationToken ct = default) + { + var session = await _gameDb.GameSessions + .FirstOrDefaultAsync(s => s.Id == sessionId, ct) + ?? throw new InvalidOperationException($"Session {sessionId} not found."); + + if (session.Status is GameSessionStatus.Completed or GameSessionStatus.Abandoned) + throw new InvalidOperationException("Session is already finished."); + + session.Status = GameSessionStatus.Abandoned; + session.EndedAt = DateTimeOffset.UtcNow; + + var lobby = await _gameDb.CustomLobbies + .FirstOrDefaultAsync(l => l.GameSessionId == sessionId, ct); + if (lobby != null) + lobby.Status = CustomLobbyStatus.Completed; + + await _gameDb.SaveChangesAsync(ct); + + _logger.LogInformation("AiMatchService: force-ended session {SessionId}.", sessionId); + } + + // ── DTOs ────────────────────────────────────────────────────────────────── + + public sealed record ActiveAiMatch( + Guid SessionId, + Guid Player1Id, + string Player1Name, + Guid Player2Id, + string Player2Name, + GameSessionStatus Status, + DateTimeOffset CreatedAt, + string LobbyName); + + // ── Match creation ──────────────────────────────────────────────────────── + /// /// Creates an AI-vs-AI match and publishes GameStartedEvent. /// Returns (sessionId, player1Name, player2Name).