refactor: move AI match creation to admin-only Blazor page
Removes game.ai.create_match WebSocket handler (no longer accessible to clients) and replaces it with AiMatchService injected directly into a new admin Blazor page at /ai/matches. Admin portal gains NATS publish capability (SOR.Networking.Nats project reference + AddNats) so AiMatchService can emit GameStartedEvent to trigger AiPlayerSessionManager. AiDeckResolver is made public for admin injection. 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:
@@ -188,6 +188,11 @@
|
||||
<i class="bi bi-cpu me-2"></i>Neural Model
|
||||
</NavLink>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<NavLink class="nav-link text-white-50 py-1" href="/ai/matches">
|
||||
<i class="bi bi-play-circle me-2"></i>AI Matches
|
||||
</NavLink>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
@page "/ai/matches"
|
||||
@using SOR.Ai.Lobby
|
||||
@inject AiMatchService MatchService
|
||||
@inject ILogger<AiMatchPage> Logger
|
||||
|
||||
<PageTitle>AI Matches – SOR Admin</PageTitle>
|
||||
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1 class="mb-0">AI vs AI Matches</h1>
|
||||
</div>
|
||||
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">Create Match</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted small text-uppercase mb-2">Player 1</h6>
|
||||
<div class="row g-2">
|
||||
<div class="col-6">
|
||||
<label class="form-label">Difficulty</label>
|
||||
<select class="form-select" @bind="_diff1">
|
||||
@for (int d = 1; d <= 10; d++)
|
||||
{
|
||||
var label = $"D{d} – {DifficultyName(d)}";
|
||||
<option value="@d">@label</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<label class="form-label">Strategy</label>
|
||||
<select class="form-select" @bind="_strategy1">
|
||||
@foreach (var s in Strategies)
|
||||
{
|
||||
<option value="@s">@s</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted small text-uppercase mb-2">Player 2</h6>
|
||||
<div class="row g-2">
|
||||
<div class="col-6">
|
||||
<label class="form-label">Difficulty</label>
|
||||
<select class="form-select" @bind="_diff2">
|
||||
@for (int d = 1; d <= 10; d++)
|
||||
{
|
||||
var label = $"D{d} – {DifficultyName(d)}";
|
||||
<option value="@d">@label</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<label class="form-label">Strategy</label>
|
||||
<select class="form-select" @bind="_strategy2">
|
||||
@foreach (var s in Strategies)
|
||||
{
|
||||
<option value="@s">@s</option>
|
||||
}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_error is not null)
|
||||
{
|
||||
<div class="alert alert-danger py-2">@_error</div>
|
||||
}
|
||||
|
||||
<button class="btn btn-primary" @onclick="CreateAsync" disabled="@_busy">
|
||||
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
|
||||
Create Match
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (_recentMatches.Count > 0)
|
||||
{
|
||||
<div class="card">
|
||||
<div class="card-header">Recently Created</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm table-hover mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Session ID</th>
|
||||
<th>Player 1</th>
|
||||
<th>Player 2</th>
|
||||
<th>Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var m in _recentMatches)
|
||||
{
|
||||
<tr>
|
||||
<td>
|
||||
<a href="/game/sessions/@m.SessionId" class="font-monospace small">
|
||||
@m.SessionId.ToString()[..8]…
|
||||
</a>
|
||||
</td>
|
||||
<td>@m.Player1Name</td>
|
||||
<td>@m.Player2Name</td>
|
||||
<td class="text-muted small">@m.CreatedAt.ToString("HH:mm:ss")</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private static readonly string[] Strategies = ["Aggressive", "Control", "Balanced", "Ramp", "Swarm"];
|
||||
|
||||
private int _diff1 = 5;
|
||||
private string _strategy1 = "Balanced";
|
||||
private int _diff2 = 5;
|
||||
private string _strategy2 = "Aggressive";
|
||||
|
||||
private bool _busy;
|
||||
private string? _error;
|
||||
|
||||
private readonly List<MatchRecord> _recentMatches = [];
|
||||
|
||||
private static string DifficultyName(int d) => d switch
|
||||
{
|
||||
1 => "Novice",
|
||||
2 => "Apprentice",
|
||||
3 => "Journeyman",
|
||||
4 => "Adept",
|
||||
5 => "Expert",
|
||||
6 => "Master",
|
||||
7 => "Grandmaster",
|
||||
8 => "Champion",
|
||||
9 => "Legend",
|
||||
10 => "Mythic",
|
||||
_ => d.ToString(),
|
||||
};
|
||||
|
||||
private async Task CreateAsync()
|
||||
{
|
||||
_busy = true; _error = null; StateHasChanged();
|
||||
try
|
||||
{
|
||||
var (sessionId, p1Name, p2Name) = await MatchService.CreateMatchAsync(
|
||||
_diff1, _strategy1, _diff2, _strategy2);
|
||||
|
||||
_recentMatches.Insert(0, new MatchRecord(sessionId, p1Name, p2Name, DateTimeOffset.Now));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = ex.Message;
|
||||
Logger.LogError(ex, "AiMatchPage: failed to create AI match.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record MatchRecord(
|
||||
Guid SessionId,
|
||||
string Player1Name,
|
||||
string Player2Name,
|
||||
DateTimeOffset CreatedAt);
|
||||
}
|
||||
@@ -12,15 +12,19 @@ using Microsoft.IdentityModel.JsonWebTokens;
|
||||
using Microsoft.IdentityModel.Protocols;
|
||||
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using NATS.Client.Hosting;
|
||||
using StackExchange.Redis;
|
||||
using SOR.Admin.Components;
|
||||
using SOR.Ai.Calibration;
|
||||
using SOR.Ai.Lobby;
|
||||
using SOR.Ai.Neural;
|
||||
using SOR.Ai.Training;
|
||||
using SOR.Cdn;
|
||||
using SOR.Database;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Identity;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Networking.Nats;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
|
||||
@@ -160,10 +164,20 @@ builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
|
||||
builder.Services.AddDataProtection()
|
||||
.PersistKeysToStackExchangeRedis(redis, "SOR.Admin:DataProtection-Keys");
|
||||
|
||||
// ── NATS (publish-only: used by AiMatchService to trigger AiPlayerSessionManager) ──
|
||||
builder.Services.AddNats(configureOpts: opts =>
|
||||
opts with
|
||||
{
|
||||
Url = builder.Configuration["Nats:Url"] ?? "nats://localhost:4222"
|
||||
});
|
||||
builder.Services.AddSingleton<IEventBus, NatsEventBus>();
|
||||
|
||||
// ── AI calibration (admin-side only: self-play + calibration job) ─────────
|
||||
builder.Services.AddScoped<SelfPlayOrchestrator>();
|
||||
builder.Services.AddScoped<GameReplayExporter>();
|
||||
builder.Services.AddSingleton<AiCalibrationJob>();
|
||||
builder.Services.AddScoped<AiDeckResolver>();
|
||||
builder.Services.AddScoped<AiMatchService>();
|
||||
|
||||
// ── Neural model registry (admin-side: status + hot-swap page) ────────────
|
||||
builder.Services.AddSingleton<NeuralModelRegistry>();
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<ProjectReference Include="..\SOR.Ai\SOR.Ai.csproj" />
|
||||
<ProjectReference Include="..\SOR.Cdn\SOR.Cdn.csproj" />
|
||||
<ProjectReference Include="..\SOR.Database\SOR.Database.csproj" />
|
||||
<ProjectReference Include="..\SOR.Networking.Nats\SOR.Networking.Nats.csproj" />
|
||||
<ProjectReference Include="..\SOR.Shared\SOR.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -17,7 +17,7 @@ using SOR.Database.Entities.Collection;
|
||||
/// CollectionDbContext for the AI account so GameReadyHandler can load it
|
||||
/// via the standard LoadDeckCardsAsync path.
|
||||
/// </summary>
|
||||
internal sealed class AiDeckResolver
|
||||
public sealed class AiDeckResolver
|
||||
{
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly BazaarDbContext _bazaarDb;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
namespace SOR.Ai.Lobby;
|
||||
|
||||
using System.Text.Json;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SOR.Ai.Seeding;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Database.Entities.Game;
|
||||
using SOR.Database.Enums;
|
||||
using SOR.Game;
|
||||
using SOR.Networking.Abstractions.EventBus;
|
||||
using SOR.Shared.Nats;
|
||||
|
||||
/// <summary>
|
||||
/// Creates spectatable AI-vs-AI matches. Intended for use from the admin portal only —
|
||||
/// not exposed as a WebSocket message handler.
|
||||
///
|
||||
/// Creates a minimal CustomLobby + GameSession, then publishes GameStartedEvent so
|
||||
/// AiPlayerSessionManager starts polling loops for both AI seats.
|
||||
/// </summary>
|
||||
public sealed class AiMatchService
|
||||
{
|
||||
private readonly GameDbContext _gameDb;
|
||||
private readonly SorIdentityDbContext _identityDb;
|
||||
private readonly AiDeckResolver _deckResolver;
|
||||
private readonly IEventBus _eventBus;
|
||||
private readonly ILogger<AiMatchService> _logger;
|
||||
|
||||
public AiMatchService(
|
||||
GameDbContext gameDb,
|
||||
SorIdentityDbContext identityDb,
|
||||
AiDeckResolver deckResolver,
|
||||
IEventBus eventBus,
|
||||
ILogger<AiMatchService> logger)
|
||||
{
|
||||
_gameDb = gameDb;
|
||||
_identityDb = identityDb;
|
||||
_deckResolver = deckResolver;
|
||||
_eventBus = eventBus;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an AI-vs-AI match and publishes GameStartedEvent.
|
||||
/// Returns (sessionId, player1Name, player2Name).
|
||||
/// Throws <see cref="ArgumentException"/> for invalid difficulty or strategy values.
|
||||
/// </summary>
|
||||
public async Task<(Guid SessionId, string Player1Name, string Player2Name)> CreateMatchAsync(
|
||||
int difficulty1,
|
||||
string strategy1,
|
||||
int difficulty2,
|
||||
string strategy2,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (difficulty1 is < 1 or > 10 || difficulty2 is < 1 or > 10)
|
||||
throw new ArgumentException("Difficulty must be between 1 and 10.");
|
||||
|
||||
if (!AiAccountSeeder.Strategies.Contains(strategy1) || !AiAccountSeeder.Strategies.Contains(strategy2))
|
||||
throw new ArgumentException("Invalid strategy. Valid values: " + string.Join(", ", AiAccountSeeder.Strategies));
|
||||
|
||||
var id1 = AiAccountSeeder.AccountId(difficulty1, strategy1);
|
||||
var id2 = AiAccountSeeder.AccountId(difficulty2, strategy2);
|
||||
|
||||
var deckId1 = await _deckResolver.ResolveAsync(id1, difficulty1, ct);
|
||||
var deckId2 = await _deckResolver.ResolveAsync(id2, difficulty2, ct);
|
||||
|
||||
// AiSlotsJson is read by AiPlayerSessionManager to get difficulty/strategy per seat.
|
||||
var aiSlots = JsonSerializer.Serialize(new[]
|
||||
{
|
||||
new { AccountId = id1, SeatIndex = 0, Difficulty = difficulty1, Strategy = strategy1 },
|
||||
new { AccountId = id2, SeatIndex = 1, Difficulty = difficulty2, Strategy = strategy2 },
|
||||
});
|
||||
|
||||
// Minimal lobby — status Started so it doesn't appear in open-lobby lists.
|
||||
var lobby = new CustomLobby
|
||||
{
|
||||
Name = $"AI Match: {AiAccountSeeder.DisplayName(difficulty1, strategy1)} vs {AiAccountSeeder.DisplayName(difficulty2, strategy2)}",
|
||||
HostAccountId = id1,
|
||||
HostDeckId = deckId1,
|
||||
GuestAccountId = id2,
|
||||
GuestDeckId = deckId2,
|
||||
HostReady = true,
|
||||
GuestReady = true,
|
||||
Status = CustomLobbyStatus.Started,
|
||||
MaxPlayers = 2,
|
||||
GameMode = "FFA",
|
||||
TeamCount = 1,
|
||||
AiSlotsJson = aiSlots,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
_gameDb.CustomLobbies.Add(lobby);
|
||||
|
||||
// Randomly pick who goes first.
|
||||
var (p1Id, p2Id, p1Deck, p2Deck) = Random.Shared.Next(2) == 0
|
||||
? (id1, id2, deckId1, deckId2)
|
||||
: (id2, id1, deckId2, deckId1);
|
||||
|
||||
var rules = GameRules.Default with { PlayerCount = 2 };
|
||||
var session = new GameSession
|
||||
{
|
||||
PlayerOneAccountId = p1Id,
|
||||
PlayerOneDeckId = p1Deck,
|
||||
PlayerTwoAccountId = p2Id,
|
||||
PlayerTwoDeckId = p2Deck,
|
||||
PlayerCount = 2,
|
||||
GameMode = "FFA",
|
||||
TeamCount = 1,
|
||||
PlayerOneTeamIndex = 0,
|
||||
PlayerTwoTeamIndex = 1,
|
||||
Status = GameSessionStatus.Initializing,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
RuleSnapshotJson = JsonSerializer.Serialize(rules),
|
||||
};
|
||||
|
||||
_gameDb.GameSessions.Add(session);
|
||||
lobby.GameSessionId = session.Id;
|
||||
await _gameDb.SaveChangesAsync(ct);
|
||||
|
||||
try
|
||||
{
|
||||
await _eventBus.PublishAsync(
|
||||
NatsSubjects.GameStarted,
|
||||
new GameStartedEvent(session.Id, [p1Id, p2Id], DateTimeOffset.UtcNow),
|
||||
ct);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"AiMatchService: failed to publish GameStartedEvent for session {SessionId}.",
|
||||
session.Id);
|
||||
}
|
||||
|
||||
var ids = new[] { p1Id, p2Id };
|
||||
var names = await _identityDb.Users
|
||||
.AsNoTracking()
|
||||
.Where(u => ids.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);
|
||||
|
||||
var p1Name = names.GetValueOrDefault(p1Id, p1Id.ToString()[..8]);
|
||||
var p2Name = names.GetValueOrDefault(p2Id, p2Id.ToString()[..8]);
|
||||
|
||||
_logger.LogInformation(
|
||||
"AiMatchService: created AI match {SessionId} ({P1} vs {P2}).",
|
||||
session.Id, p1Name, p2Name);
|
||||
|
||||
return (session.Id, p1Name, p2Name);
|
||||
}
|
||||
}
|
||||
@@ -83,7 +83,9 @@ public static class ServiceRegistration
|
||||
services.AddTransient<IMessageHandler, GameAddAiHandler>();
|
||||
services.AddTransient<IMessageHandler, GameRemoveAiHandler>();
|
||||
services.AddTransient<IMessageHandler, GameConfigureAiHandler>();
|
||||
services.AddTransient<IMessageHandler, GameAiMatchHandler>();
|
||||
|
||||
// ── Admin-only services (injected by SOR.Admin Blazor pages) ─────────
|
||||
services.AddScoped<AiMatchService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -4,19 +4,6 @@ namespace SOR.Game;
|
||||
|
||||
/// <summary>Host adds an AI player to a custom lobby.</summary>
|
||||
public sealed record GameAddAiRequest(Guid LobbyId, int Difficulty, string Strategy);
|
||||
|
||||
/// <summary>Create a spectatable AI-vs-AI match.</summary>
|
||||
public sealed record GameAiMatchRequest(
|
||||
int Difficulty1,
|
||||
string Strategy1,
|
||||
int Difficulty2,
|
||||
string Strategy2);
|
||||
|
||||
/// <summary>Response after creating an AI-vs-AI match. Client sends game.spectate to watch.</summary>
|
||||
public sealed record GameAiMatchResponse(
|
||||
Guid SessionId,
|
||||
string Player1Name,
|
||||
string Player2Name);
|
||||
public sealed record GameAddAiResponse(Guid AiAccountId, string AiDisplayName, int SeatIndex);
|
||||
|
||||
/// <summary>Host removes an AI player from a custom lobby.</summary>
|
||||
|
||||
Reference in New Issue
Block a user