Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 64 additions & 2 deletions src/Orbit.Application/Chat/Commands/ProcessUserChatCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public record ChatResponse(
IReadOnlyList<AgentOperationResult>? Operations = null,
IReadOnlyList<PendingAgentOperation>? PendingOperations = null,
IReadOnlyList<AgentPolicyDenial>? PolicyDenials = null,
string? CorrelationId = null);
string? CorrelationId = null,
IReadOnlyList<string>? RelatedSurfaces = null);

public record ActionResult(
string Type,
Expand Down Expand Up @@ -252,7 +253,8 @@ public async Task<Result<ChatResponse>> Handle(
executionResults.OperationResults,
executionResults.PendingOperations,
executionResults.PolicyDenials,
request.CorrelationId));
request.CorrelationId,
executionResults.RelatedSurfaces.Count > 0 ? executionResults.RelatedSurfaces : null));
}

/// <summary>
Expand Down Expand Up @@ -644,11 +646,20 @@ private static bool RequiresStreakRecalculation(IEnumerable<ActionResult> action

private sealed class ToolExecutionAccumulator
{
private readonly List<string> _relatedSurfaces = [];
private readonly HashSet<string> _seenRelatedSurfaces = new(StringComparer.Ordinal);

public List<ActionResult> ActionResults { get; } = [];
public List<AgentOperationResult> OperationResults { get; } = [];
public List<PendingAgentOperation> PendingOperations { get; } = [];
public List<AgentPolicyDenial> PolicyDenials { get; } = [];

/// <summary>
/// App surface IDs (e.g. "today", "gamification") surfaced by read-only tools such as
/// describe_feature, deduplicated in first-seen order. The client maps these to deep links.
/// </summary>
public IReadOnlyList<string> RelatedSurfaces => _relatedSurfaces;

public void Add(
ActionResult? actionResult,
AgentOperationResult? operationResult,
Expand All @@ -659,14 +670,65 @@ public void Add(
ActionResults.Add(actionResult);

if (operationResult is not null)
{
OperationResults.Add(operationResult);
CollectRelatedSurfaces(operationResult);
}

if (policyDenial is not null)
PolicyDenials.Add(policyDenial);

if (pendingOperation is not null)
PendingOperations.Add(pendingOperation);
}

private void CollectRelatedSurfaces(AgentOperationResult operationResult)
{
if (operationResult.Status != AgentOperationStatus.Succeeded)
return;

foreach (var surface in ExtractRelatedSurfaces(operationResult.Payload))
{
if (_seenRelatedSurfaces.Add(surface))
_relatedSurfaces.Add(surface);
}
}
}

/// <summary>
/// Reads the optional "related_surfaces" string array from a tool's anonymous payload
/// (e.g. describe_feature) by round-tripping it through JSON. Returns an empty sequence
/// when the payload is null, not an object, or carries no usable surface IDs.
/// </summary>
private static IEnumerable<string> ExtractRelatedSurfaces(object? payload)
{
if (payload is null)
return [];

JsonElement element;
try
{
element = JsonSerializer.SerializeToElement(payload);
}
catch (NotSupportedException)
{
return [];
}

if (element.ValueKind != JsonValueKind.Object
|| !element.TryGetProperty("related_surfaces", out var surfaces)
|| surfaces.ValueKind != JsonValueKind.Array)
{
return [];
}

return surfaces
.EnumerateArray()
.Where(item => item.ValueKind == JsonValueKind.String)
.Select(item => item.GetString())
.Where(value => !string.IsNullOrWhiteSpace(value))
.Select(value => value!)
.ToList();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,78 @@ public async Task Handle_ReadOnlyToolCall_DoesNotProduceActionResult()
result.Value.Actions.Should().BeEmpty();
}

// --- Read-only tool surfacing related surfaces ---

[Fact]
public async Task Handle_ReadOnlyToolWithRelatedSurfaces_SurfacesThemOnResponse()
{
SetupUserAndPayGate();

var describeTool = Substitute.For<IAiTool>();
describeTool.Name.Returns("describe_feature");
describeTool.Description.Returns("Explains a feature");
describeTool.IsReadOnly.Returns(true);
describeTool.GetParameterSchema().Returns(new { type = "object" });
describeTool.ExecuteAsync(Arg.Any<JsonElement>(), UserId, Arg.Any<CancellationToken>())
.Returns(new ToolResult(true, Payload: new
{
key = "streaks",
related_surfaces = new[] { "gamification", "today" },
markdown = "# Streaks"
}));

var handler = CreateHandler(describeTool);

var aiResponseWithTool = new AiResponse
{
ToolCalls = [new AiToolCall("describe_feature", "call_1", JsonDocument.Parse("{}").RootElement)],
ConversationContext = TestConversationContext
};
SetupAiResponse(aiResponseWithTool);

_aiIntentService.ContinueWithToolResultsAsync(
Arg.Any<AiConversationContext>(), Arg.Any<IReadOnlyList<AiToolCallResult>>(), Arg.Any<CancellationToken>())
.Returns(Result.Success(new AiResponse { TextMessage = "Streaks work like this.", ToolCalls = null }));

var result = await handler.Handle(new ProcessUserChatCommand(UserId, "How do streaks work?"), CancellationToken.None);

result.IsSuccess.Should().BeTrue();
result.Value.Actions.Should().BeEmpty();
result.Value.RelatedSurfaces.Should().Equal("gamification", "today");
}

[Fact]
public async Task Handle_MutatingOnlyTurn_LeavesRelatedSurfacesNull()
{
SetupUserAndPayGate();

var mockTool = Substitute.For<IAiTool>();
mockTool.Name.Returns("create_habit");
mockTool.Description.Returns("Creates a habit");
mockTool.IsReadOnly.Returns(false);
mockTool.GetParameterSchema().Returns(new { type = "object" });
mockTool.ExecuteAsync(Arg.Any<JsonElement>(), UserId, Arg.Any<CancellationToken>())
.Returns(new ToolResult(true, EntityId: Guid.NewGuid().ToString(), EntityName: "Morning Run"));

var handler = CreateHandler(mockTool);

var aiResponseWithTool = new AiResponse
{
ToolCalls = [new AiToolCall("create_habit", "call_1", JsonDocument.Parse("{}").RootElement)],
ConversationContext = TestConversationContext
};
SetupAiResponse(aiResponseWithTool);

_aiIntentService.ContinueWithToolResultsAsync(
Arg.Any<AiConversationContext>(), Arg.Any<IReadOnlyList<AiToolCallResult>>(), Arg.Any<CancellationToken>())
.Returns(Result.Success(new AiResponse { TextMessage = "Created your habit!", ToolCalls = null }));

var result = await handler.Handle(new ProcessUserChatCommand(UserId, "Create a habit"), CancellationToken.None);

result.IsSuccess.Should().BeTrue();
result.Value.RelatedSurfaces.Should().BeNull();
}

// --- Multiple tool calls in sequence ---

[Fact]
Expand Down
Loading