using FluentAssertions;
using IBKRTrader.Modules.Supervisor.Agent;
namespace IBKRTrader.Tests.Modules.Supervisor;
[Trait("cat", "unit")]
public class SupervisorAgentTests
{
/// Fake-Client: gibt vorab definierte Antworten der Reihe nach zurück.
private sealed class FakeChat : IChatCompletionClient
{
private readonly Queue _responses;
public List SeenToolResults { get; } = new();
public FakeChat(params ChatResponse[] responses) => _responses = new(responses);
public Task CompleteAsync(string model, IReadOnlyList messages,
IReadOnlyList tools, CancellationToken ct)
{
foreach (var m in messages)
if (m.Role == "tool" && m.Content != null) SeenToolResults.Add(m.Content);
return Task.FromResult(_responses.Dequeue());
}
}
private static SupervisorToolRegistry EchoRegistry()
{
var reg = new SupervisorToolRegistry();
reg.Register(new SupervisorTool("get_kpis", "KPIs", """{"type":"object"}""", _ => "{\"NetPnl\":42}"));
return reg;
}
[Fact]
public async Task RunsToolThenReturnsFinalAnswer()
{
var chat = new FakeChat(
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
new ChatResponse { Content = "Netto-PnL ist 42." });
var agent = new SupervisorAgent(chat, EchoRegistry());
var result = await agent.AskAsync("Wie ist die Performance?");
result.Answer.Should().Be("Netto-PnL ist 42.");
result.ToolInvocations.Should().ContainSingle();
result.ToolInvocations[0].Tool.Should().Be("get_kpis");
chat.SeenToolResults.Should().Contain(s => s.Contains("42")); // Tool-Ergebnis ging ans Modell zurück
}
[Fact]
public async Task ProfileFilter_DeniesUnlistedTool()
{
var chat = new FakeChat(
new ChatResponse { ToolCalls = { new ToolCall("c1", "get_kpis", "{}") } },
new ChatResponse { Content = "fertig" });
// Technik-Profil listet get_kpis NICHT → Ausführung verweigert.
var agent = new SupervisorAgent(chat, EchoRegistry());
var result = await agent.AskAsync("test", profile: SupervisorProfiles.Technik);
result.ToolInvocations[0].Result.Should().Contain("nicht freigegeben");
}
[Fact]
public async Task StopsAfterMaxIterations()
{
// Modell fordert IMMER ein Tool an → harte Iterationsgrenze greift.
var always = Enumerable.Range(0, SupervisorAgent.MaxIterations + 2)
.Select(_ => new ChatResponse { ToolCalls = { new ToolCall("c", "get_kpis", "{}") } })
.ToArray();
var agent = new SupervisorAgent(new FakeChat(always), EchoRegistry());
var result = await agent.AskAsync("Endlosschleife?");
result.Answer.Should().Contain("maximale Tool-Iterationen");
}
}