Spaces:
Running
Running
Commit ·
0d9e67d
1
Parent(s): e4f56e2
feat: implement QuestSchema DTO, AutoLayoutEngine and AgentCanvasController for LLM Agent Skill integration
Browse filesFiles changed (3)
1234567891011121314151617181920using System.Collections.Generic;
namespace FlowAPI.Application.DTOs.AI{ public class QuestNodeDto { public string Id { get; set; } = string.Empty; public string Label { get; set; } = string.Empty; public string? Description { get; set; } public string? DependsOn { get; set; } public string? Condition { get; set; } }
public class QuestSchemaDto { public string Title { get; set; } = string.Empty; public string? Description { get; set; } public List<QuestNodeDto> Nodes { get; set; } = new(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143using System;using System.Collections.Generic;using System.Linq;using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;
namespace FlowAPI.Application.Services{ public static class AutoLayoutEngine { private const double StepX = 300.0; private const double StepY = 180.0;
public static FullGraphResponseDto LayoutGraph(QuestSchemaDto schema, Guid userId) { var graphId = Guid.NewGuid(); var response = new FullGraphResponseDto { Id = graphId, UserId = userId, Title = schema.Title, Description = schema.Description, CreatedAt = DateTime.UtcNow, IsShared = false, Permission = "Owner", Nodes = new List<NodeDto>(), Edges = new List<EdgeDto>() };
if (schema.Nodes == null || !schema.Nodes.Any()) return response;
// 1. Map string string-based IDs from LLM into Guids var idMap = new Dictionary<string, Guid>(); foreach (var node in schema.Nodes) { idMap[node.Id] = Guid.NewGuid(); }
// 2. Calculate logical layers (Sugiyama-like ranking) var layerMap = new Dictionary<string, int>(); foreach (var node in schema.Nodes) { layerMap[node.Id] = 0; // Default layer }
// Transitively propagate layer ranks based on dependencies (max N passes) int n = schema.Nodes.Count; for (int pass = 0; pass < n; pass++) { bool changed = false; foreach (var node in schema.Nodes) { if (!string.IsNullOrEmpty(node.DependsOn) && idMap.ContainsKey(node.DependsOn)) { int parentLayer = layerMap[node.DependsOn]; int currentLayer = layerMap[node.Id]; if (currentLayer < parentLayer + 1) { layerMap[node.Id] = parentLayer + 1; changed = true; } } } if (!changed) break; // Optimization if stabilized early }
// 3. Group nodes by layers and calculate coordinates var layers = new Dictionary<int, List<QuestNodeDto>>(); foreach (var node in schema.Nodes) { int layer = layerMap[node.Id]; if (!layers.ContainsKey(layer)) { layers[layer] = new List<QuestNodeDto>(); } layers[layer].Add(node); }
// Set coordinates symmetrically per layer foreach (var layerKvp in layers) { int layer = layerKvp.Key; var layerNodes = layerKvp.Value; int count = layerNodes.Count;
for (int i = 0; i < count; i++) { var node = layerNodes[i]; var nodeGuid = idMap[node.Id];
// Symmetric distribution vertically around Y = 0 double posX = layer * StepX; double posY = (i - (count - 1) / 2.0) * StepY;
// Determine visual properties string? nodeColor = null; if (!string.IsNullOrEmpty(node.Condition)) { if (node.Condition.Equals("Fail", StringComparison.OrdinalIgnoreCase)) { nodeColor = "#ba1a1a"; // Red for Fail paths } else if (node.Condition.Equals("Success", StringComparison.OrdinalIgnoreCase)) { nodeColor = "#45a84a"; // Green for Success paths } }
response.Nodes.Add(new NodeDto { Id = nodeGuid, Label = node.Label, PosX = posX, PosY = posY, Type = "sketch", State = 0, // Pending Decision = node.Condition, Description = node.Description, Color = nodeColor, IsPinned = false, Width = 160, Height = 80 });
// 4. Create Edges if (!string.IsNullOrEmpty(node.DependsOn) && idMap.ContainsKey(node.DependsOn)) { response.Edges.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = idMap[node.DependsOn], ToNodeId = nodeGuid, Condition = node.Condition ?? "True" }); } } }
return response; } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980using FlowAPI.Application.DTOs.AI;using FlowAPI.Application.DTOs.Graph;using FlowAPI.Application.Interfaces;using FlowAPI.Application.Services;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;using System;using System.Security.Claims;using System.Threading.Tasks;
namespace FlowAPI.Controllers{ [ApiController] [Authorize] [Route("api/agents/canvas")] public class AgentCanvasController : ControllerBase { private readonly IGraphService _graphService;
public AgentCanvasController(IGraphService graphService) { _graphService = graphService; }
private Guid CurrentUserId { get { var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; return Guid.TryParse(userIdStr, out var userId) ? userId : Guid.Empty; } }
[HttpPost("create")] public async Task<IActionResult> CreateFromAgent([FromBody] QuestSchemaDto schema) { if (CurrentUserId == Guid.Empty) return Unauthorized(new { message = "User authentication required." });
if (schema == null || schema.Nodes == null || schema.Nodes.Count == 0) { return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." }); }
try { // 1. Create the Graph record in the database var createDto = new CreateGraphDto { Title = string.IsNullOrWhiteSpace(schema.Title) ? "QuestboardAI Plan" : schema.Title.Trim(), Description = schema.Description }; var graphResponse = await _graphService.CreateAsync(createDto, CurrentUserId);
// 2. Perform Auto-Layout to assign visual coordinates PosX and PosY var fullGraph = AutoLayoutEngine.LayoutGraph(schema, CurrentUserId); fullGraph.Id = graphResponse.Id; // Sync graph ID
// 3. Save all nodes and dependency edges in the database var saveResult = await _graphService.SaveFullGraphAsync(graphResponse.Id, fullGraph, CurrentUserId); if (!saveResult) { return BadRequest(new { message = "Failed to store generated task nodes in database." }); }
// 4. Return successful response with the Canvas redirection URL return Ok(new { success = true, graphId = graphResponse.Id, canvasUrl = $"/canvas/{graphResponse.Id}" }); } catch (Exception ex) { return BadRequest(new { message = $"Internal error during plan generation: {ex.Message}" }); } } }}FlowAPI.Application/DTOs/AI/QuestSchemaDto.csAdded+20
FlowAPI.Application/Services/AutoLayoutEngine.csAdded+143
FlowAPI/Controllers/AgentCanvasController.csAdded+80