Spaces:
Running
Running
Commit ·
ecea7e2
1
Parent(s): 26471a0
fix: optimized Dockerfile, backend AI service, and gitignore
Browse filesFiles changed (3)
15 unmodified lines16171819202115 unmodified linesgemini_profile_bridge/*.sqlite-shm*.sqlite-wal# Ignore SQLite database files to avoid checking them intaskflow.db/app/data/19 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455232425596061262719 unmodified linesEXPOSE 8080EXPOSE 8081
# Install Python, pip, and system dependencies for Camoufox (Playwright/Firefox)RUN apt-get update && apt-get install -y \ python3 \ python3-pip \ python3-venv \ curl \ libgtk-3-0 \ libasound2 \ libdbus-1-3 \ libx11-xcb1 \ libxcomposite1 \ libxdamage1 \ libxrandr2 \ libxtst6 \ libnss3 \ libatk1.0-0 \ libatk-bridge2.0-0 \ libdrm2 \ libgbm1 \ libxkbcommon0 \ libpango-1.0-0 \ libcairo2 \ && rm -rf /var/lib/apt/lists/*
# Set up python virtual environment to install packages cleanlyRUN python3 -m venv /opt/venvENV PATH="/opt/venv/bin:$PATH"
# Install camoufox python library and its dependenciesRUN pip3 install --no-cache-dir camoufox# Pre-download Camoufox/Playwright browser engines so they are readyRUN python3 -m camoufox fetch
# Copy published .NET appCOPY --from=build /app/publish .
# Explicitly copy the python bridge script to ensure it is in the run directoryCOPY --from=build /src/FlowAPI/gemini_bridge.py .
# Set entrypointENTRYPOINT ["dotnet", "FlowAPI.dll"]34 unmodified lines35363738394041424344454647484950515253545556575859603839404142656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624743444546472522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105114849505134 unmodified lines
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request) { // 1. Fetch graph to get user context var graph = await _graphRepo.GetByIdAsync(request.GraphId); if (graph == null) throw new Exception("Graph not found.");
// 2. Check Premium Status (REQ-03) - Bypassed for regular users for now var user = await _userRepo.GetByIdAsync(graph.UserId); if (user == null) { throw new Exception("User not found."); }
// 3. Prepare AI Prompt string prompt = $"Given a goal graph '{graph.Title}', the node {request.FailedNodeId} is blocked. " + "Generate an alternative sequence of 3-5 steps to bypass this obstacle."; return new AIPathResponseDto { SuggestedNodes = new() { new() { Id = Guid.NewGuid(), Label = "AI: Search for alternative resources", PosX = 100, PosY = 100 }, new() { Id = Guid.NewGuid(), Label = "AI: Contact external consultant", PosX = 200, PosY = 150 } } }; throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); }
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request) { var serializeOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) }; // 1. Check User Premium Status or just allow AI generation var user = await _userRepo.GetByIdAsync(request.UserId); if (user == null) throw new Exception("User not found.");
// 2. Formulate Prompt for Gemini string promptText = $"You are an expert strategist and goal decomposition AI. Your task is to break down the user's goal into a sequential, logical tree or path of actionable tasks in Ukrainian.\n\n" + $"User Goal: \"{request.Goal}\"\n\n" + $"Create a structured, detailed roadmap of 6 to 12 sequential tasks (nodes) and their directed connections (edges) that lead the user to their goal.\n\n" + $"Guidelines:\n" + $"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" + $"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" + $"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" + $"- Use \"condition\" nodes appropriately and dynamically when the path requires making a choice, evaluating options, or taking a different approach depending on criteria (e.g. \"Чи є досвід у програмуванні?\" or \"Вибір платформи\").\n" + $"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" + $"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" + $" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" + $" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" + $" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" + $" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" + $"- For coordinates, lay out the nodes visually flowing from top to bottom. Increase 'posY' by approximately 200-240 units for each sequential step. Vary 'posX' (e.g., between 200 and 700) if there are parallel branches or decision paths.\n" + $"- Every node must have a unique string 'id' (like \"node_1\", \"node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" + $"- All nodes must be reachable via edges starting from the initial steps.\n\n" + $"Provide the output strictly in a valid JSON format following this schema, with no additional explanation, no markdown text outside the JSON, and no other content:\n" + $"{{\n" + $" \"title\": \"Коротка та приваблива назва дорожньої карти\",\n" + $" \"description\": \"Короткий опис стратегії\",\n" + $" \"nodes\": [\n" + $" {{ \"id\": \"node_1\", \"label\": \"Детальний перший крок\", \"posX\": 450, \"posY\": 100, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"node_2\", \"label\": \"Оберіть платформу для розробки\", \"posX\": 450, \"posY\": 300, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-web\", \"label\": \"Web\" }}, {{ \"id\": \"opt-mobile\", \"label\": \"Mobile\" }}, {{ \"id\": \"opt-desktop\", \"label\": \"Desktop\" }} ] }},\n" + $" {{ \"id\": \"node_3\", \"label\": \"Освоєння HTML, CSS та JavaScript\", \"posX\": 200, \"posY\": 520, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"node_4\", \"label\": \"Вивчення Swift або Kotlin\", \"posX\": 450, \"posY\": 520, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"node_5\", \"label\": \"Вивчення C# та .NET для настільних вікон\", \"posX\": 700, \"posY\": 520, \"type\": \"sketch\" }}\n" + $" ],\n" + $" \"edges\": [\n" + $" {{ \"from\": \"node_1\", \"to\": \"node_2\", \"condition\": \"True\" }},\n" + $" {{ \"from\": \"node_2\", \"to\": \"node_3\", \"condition\": \"True\" }},\n" + $" {{ \"from\": \"node_2\", \"to\": \"node_4\", \"condition\": \"False\" }},\n" + $" {{ \"from\": \"node_2\", \"to\": \"node_5\", \"condition\": \"Blocked\" }}\n" + $" ]\n" + $"}}";
// 3. Send Prompt via Persistent Bridge string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120);
// 7. Parse Bridge Message using var jsonDoc = JsonDocument.Parse(rawResponseJson); var root = jsonDoc.RootElement; if (root.GetProperty("status").GetString() != "success") { string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed"; throw new Exception("AI bridge returned error: " + errMsg); }
string aiContent = root.GetProperty("content").GetString() ?? string.Empty; string cleanJson = CleanJson(aiContent);
if (string.IsNullOrWhiteSpace(cleanJson)) { throw new Exception("The AI bridge returned empty content. Please try generating again."); }
// 8. Deserialize AI Roadmap Structure AIGoalGraphResponse? parsedData; try { parsedData = JsonSerializer.Deserialize<AIGoalGraphResponse>(cleanJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (JsonException ex) { string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent; throw new Exception($"Failed to parse AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex); }
if (parsedData == null || parsedData.Nodes == null || parsedData.Nodes.Count == 0) { throw new Exception("The AI response did not contain a valid nodes list."); }
// 9. Map temporary String IDs to Database GUIDs var guidMap = new Dictionary<string, Guid>(); var nodeDtos = new List<NodeDto>();
for (int i = 0; i < parsedData.Nodes.Count; i++) { var aiNode = parsedData.Nodes[i]; var newGuid = Guid.NewGuid(); guidMap[aiNode.Id] = newGuid;
// Coordinate layout will be handled by the layout engine later double finalX = aiNode.PosX; double finalY = aiNode.PosY;
string? decisionJson = null; if (aiNode.Type == "condition") { var optionsList = new List<object>(); if (aiNode.Options != null && aiNode.Options.Count > 0) { foreach (var opt in aiNode.Options) { optionsList.Add(new { id = opt.Id, label = opt.Label }); } } else { optionsList.Add(new { id = "opt-yes", label = "Так" }); optionsList.Add(new { id = "opt-no", label = "Ні" }); }
decisionJson = JsonSerializer.Serialize(new { options = optionsList, selected = new string[] { }, multiSelect = false }, serializeOptions); }
nodeDtos.Add(new NodeDto { Id = newGuid, Label = aiNode.Label, PosX = finalX, PosY = finalY, Type = aiNode.Type ?? "sketch", State = 0, Decision = decisionJson }); }
var edgeDtos = new List<EdgeDto>(); if (parsedData.Edges != null) { foreach (var aiEdge in parsedData.Edges) { if (guidMap.TryGetValue(aiEdge.From, out var fromGuid) && guidMap.TryGetValue(aiEdge.To, out var toGuid)) { edgeDtos.Add(new EdgeDto { Id = Guid.NewGuid(), FromNodeId = fromGuid, ToNodeId = toGuid, Condition = aiEdge.Condition ?? "True" }); } } }
// 10. Apply Automated Beautiful Layout ApplyBeautifulLayout(nodeDtos, edgeDtos);
// 11. Persist using existing GraphService var createDto = new CreateGraphDto { UserId = request.UserId, Title = string.IsNullOrWhiteSpace(parsedData.Title) ? request.Goal : parsedData.Title, Description = string.IsNullOrWhiteSpace(parsedData.Description) ? "AI generated roadmap" : parsedData.Description };
var createdGraph = await _graphService.CreateAsync(createDto, request.UserId);
var fullGraphDto = new FullGraphResponseDto { Id = createdGraph.Id, UserId = createdGraph.UserId, Title = createdGraph.Title, Description = createdGraph.Description, CreatedAt = createdGraph.CreatedAt, Nodes = nodeDtos, Edges = edgeDtos };
bool saveSuccess = await _graphService.SaveFullGraphAsync(createdGraph.Id, fullGraphDto, request.UserId); if (!saveSuccess) { throw new Exception("Graph was created, but failed to save the sequential roadmap steps."); }
return fullGraphDto; throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); }
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request) { // 1. Fetch graph with all details var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId); if (graph == null) throw new Exception("Graph not found.");
// 2. Prepare serialization of active nodes and edges var currentNodesList = graph.Nodes.Select(n => new { id = n.Id.ToString(), label = n.Label, posX = n.PosX, posY = n.PosY, type = n.Type, state = n.State.ToString() }).ToList();
var currentEdgesList = graph.Edges.Select(e => new { id = e.Id.ToString(), from = e.FromNodeId.ToString(), to = e.ToNodeId.ToString(), condition = e.Condition.ToString() }).ToList();
var serializeOptions = new JsonSerializerOptions { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) };
// 4. Formulate Prompt for Gemini string promptText = $"You are an expert strategist and goal decomposition AI.\n" + $"The user has an active strategy roadmap titled \"{graph.Title}\" with the description \"{graph.Description}\" in Ukrainian.\n\n" + $"Current Canvas Structure (in Ukrainian):\n" + $"- Nodes: {JsonSerializer.Serialize(currentNodesList, serializeOptions)}\n" + $"- Edges: {JsonSerializer.Serialize(currentEdgesList, serializeOptions)}\n\n" + $"User Request: \"{request.UserPrompt}\"\n\n" + $"Analyze the current roadmap, and satisfy the user's request. Suggest adding new steps, alternative/branching paths, or decision conditions.\n" + $"Create a list of NEW nodes and edges that should be added/merged into the canvas to satisfy the request.\n\n" + $"Guidelines:\n" + $"- Ensure all labels and description text are written in clear, natural Ukrainian.\n" + $"- Avoid short, basic, generic titles. Write detailed, rich, and highly actionable labels for each node.\n" + $"- Do NOT use the \"habit\" type under any circumstances. It is strictly forbidden. The allowed node types are \"sketch\" (standard task/goal) and \"condition\" (a decision/choice branch).\n" + $"- Use \"condition\" nodes appropriately and dynamically when the user request or alternative path requires a choice, criteria evaluation, or conditional gate.\n" + $"- A \"condition\" node can have custom choices (options) instead of just simple binary branches! To specify custom choices/branches for a condition node, include an \"options\" array containing option objects with custom \"id\" and \"label\" properties (e.g. \"options\": [ {{ \"id\": \"opt-ios\", \"label\": \"iOS\" }}, {{ \"id\": \"opt-android\", \"label\": \"Android\" }}, {{ \"id\": \"opt-web\", \"label\": \"Web\" }} ]).\n" + $"- Outgoing edges from a \"condition\" node MUST map to the choice options by using the option's index inside the edge's \"condition\" field:\n" + $" * The first option (index 0) corresponds to edge \"condition\": \"True\".\n" + $" * The second option (index 1) corresponds to edge \"condition\": \"False\".\n" + $" * The third option (index 2) corresponds to edge \"condition\": \"Blocked\".\n" + $" * Any subsequent options (indices i >= 3) correspond to edge \"condition\": \"i\" (as a string, e.g. \"3\", \"4\", etc.).\n" + $"- For coordinates of new nodes, calculate 'posX' and 'posY' relative to nearby nodes so they flow nicely. Use values that don't directly overlap existing coordinates.\n" + $"- Every new node must have a unique string 'id' starting with \"new_node_\" (like \"new_node_1\", \"new_node_2\") and a dynamic 'type' property (defaults to \"sketch\").\n" + $"- You can also use existing node IDs (from the current structure) in the 'from' and 'to' fields of the new edges to link the new nodes into the existing flow!\n" + $"- All new edges should connect new nodes to each other, or to existing nodes.\n\n" + $"Provide the output strictly in a valid JSON format following this schema, with no explanation, no markdown text outside the JSON, and no other content:\n" + $"{{\n" + $" \"newNodes\": [\n" + $" {{ \"id\": \"new_node_1\", \"label\": \"Детальний новий крок для розширення\", \"posX\": 450, \"posY\": 300, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"new_node_2\", \"label\": \"Нова умова вибору середовища\", \"posX\": 450, \"posY\": 520, \"type\": \"condition\", \"options\": [ {{ \"id\": \"opt-react\", \"label\": \"React\" }}, {{ \"id\": \"opt-vue\", \"label\": \"Vue\" }}, {{ \"id\": \"opt-angular\", \"label\": \"Angular\" }} ] }},\n" + $" {{ \"id\": \"new_node_3\", \"label\": \"Вивчення React hooks та JSX\", \"posX\": 200, \"posY\": 740, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"new_node_4\", \"label\": \"Вивчення Composition API у Vue\", \"posX\": 450, \"posY\": 740, \"type\": \"sketch\" }},\n" + $" {{ \"id\": \"new_node_5\", \"label\": \"Вивчення TypeScript та RxJS в Angular\", \"posX\": 700, \"posY\": 740, \"type\": \"sketch\" }}\n" + $" ],\n" + $" \"newEdges\": [\n" + $" {{ \"from\": \"existing_node_id_here\", \"to\": \"new_node_1\" }},\n" + $" {{ \"from\": \"new_node_1\", \"to\": \"new_node_2\" }},\n" + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_3\", \"condition\": \"True\" }},\n" + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_4\", \"condition\": \"False\" }},\n" + $" {{ \"from\": \"new_node_2\", \"to\": \"new_node_5\", \"condition\": \"Blocked\" }}\n" + $" ]\n" + $"}}";
// 3. Send Prompt via Persistent Bridge string rawResponseJson = await _bridgeManager.SendPromptAsync(promptText, isNewChat: true, timeoutSeconds: 120); if (string.IsNullOrEmpty(rawResponseJson)) { throw new Exception("Did not receive a valid response block from the Gemini Bridge."); }
// Parse Bridge Message using var jsonDoc = JsonDocument.Parse(rawResponseJson); var root = jsonDoc.RootElement;
if (root.GetProperty("status").GetString() != "success") { string errMsg = root.TryGetProperty("error", out var errVal) ? errVal.GetString() ?? "Unknown error" : "Bridge generation failed"; throw new Exception("AI bridge returned error: " + errMsg); }
string aiContent = root.GetProperty("content").GetString() ?? string.Empty; string cleanJson = CleanJson(aiContent);
if (string.IsNullOrWhiteSpace(cleanJson)) { throw new Exception("The AI bridge returned empty canvas assist content. Please try generating again."); }
// Deserialize AI Assist Response Structure AICanvasAssistResponseInternal? parsedData; try { parsedData = JsonSerializer.Deserialize<AICanvasAssistResponseInternal>(cleanJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (JsonException ex) { string preview = aiContent.Length > 200 ? aiContent.Substring(0, 200) + "..." : aiContent; throw new Exception($"Failed to parse Canvas Assist AI response as JSON. Content: '{preview}'. Error: {ex.Message}", ex); }
if (parsedData == null || parsedData.NewNodes == null) { throw new Exception("The AI response did not contain a valid newNodes list."); }
// Map temporary IDs to database GUIDs var guidMap = new Dictionary<string, Guid>(); var newNodesEntities = new List<FlowAPI.Domain.Entities.TaskNode>(); var nodeDtos = new List<NodeDto>();
for (int i = 0; i < parsedData.NewNodes.Count; i++) { var aiNode = parsedData.NewNodes[i]; var newGuid = Guid.NewGuid(); guidMap[aiNode.Id] = newGuid;
string? decisionJson = null; if (aiNode.Type == "condition") { var optionsList = new List<object>(); if (aiNode.Options != null && aiNode.Options.Count > 0) { foreach (var opt in aiNode.Options) { optionsList.Add(new { id = opt.Id, label = opt.Label }); } } else { optionsList.Add(new { id = "opt-yes", label = "Так" }); optionsList.Add(new { id = "opt-no", label = "Ні" }); }
decisionJson = JsonSerializer.Serialize(new { options = optionsList, selected = new string[] { }, multiSelect = false }, serializeOptions); }
var nodeEntity = new FlowAPI.Domain.Entities.TaskNode { Id = newGuid, GraphId = request.GraphId, Label = aiNode.Label, PosX = aiNode.PosX, PosY = aiNode.PosY, Type = aiNode.Type ?? "sketch", State = FlowAPI.Domain.Enums.NodeState.Pending, Decision = decisionJson, CreatedAt = DateTime.UtcNow }; newNodesEntities.Add(nodeEntity);
nodeDtos.Add(new NodeDto { Id = newGuid, Label = aiNode.Label, PosX = aiNode.PosX, PosY = aiNode.PosY, Type = aiNode.Type ?? "sketch", State = 0, Decision = decisionJson }); }
var newEdgesEntities = new List<FlowAPI.Domain.Entities.Edge>(); var edgeDtos = new List<EdgeDto>();
if (parsedData.NewEdges != null) { foreach (var aiEdge in parsedData.NewEdges) { Guid fromGuid; if (Guid.TryParse(aiEdge.From, out var fromParsed)) { fromGuid = fromParsed; } else if (guidMap.TryGetValue(aiEdge.From, out var mappedFrom)) { fromGuid = mappedFrom; } else { continue; }
Guid toGuid; if (Guid.TryParse(aiEdge.To, out var toParsed)) { toGuid = toParsed; } else if (guidMap.TryGetValue(aiEdge.To, out var mappedTo)) { toGuid = mappedTo; } else { continue; }
var edgeGuid = Guid.NewGuid(); var edgeEntity = new FlowAPI.Domain.Entities.Edge { Id = edgeGuid, GraphId = request.GraphId, FromNodeId = fromGuid, ToNodeId = toGuid, Condition = Enum.TryParse<FlowAPI.Domain.Enums.EdgeCondition>(aiEdge.Condition, true, out var conditionEnum) ? conditionEnum : FlowAPI.Domain.Enums.EdgeCondition.True }; newEdgesEntities.Add(edgeEntity);
edgeDtos.Add(new EdgeDto { Id = edgeGuid, FromNodeId = fromGuid, ToNodeId = toGuid, Condition = aiEdge.Condition ?? "True" }); } }
// Apply Automated Beautiful Layout to the entire combined graph var allNodes = graph.Nodes.Concat(newNodesEntities).ToList(); var allEdges = graph.Edges.Concat(newEdgesEntities).ToList();
ApplyBeautifulLayout(allNodes, allEdges);
// Update the DTOs with the beautifully laid out coordinates so the frontend places them perfectly foreach (var dto in nodeDtos) { var entity = allNodes.FirstOrDefault(n => n.Id == dto.Id); if (entity != null) { dto.PosX = entity.PosX; dto.PosY = entity.PosY; } }
// Persist directly using repository bool saveSuccess = await _graphRepo.UpsertFullGraphAsync(request.GraphId, allNodes, allEdges); if (!saveSuccess) { throw new Exception("Failed to persist newly suggested AI canvas elements to database."); }
return new AICanvasAssistResponseDto { NewNodes = nodeDtos, NewEdges = edgeDtos }; throw new Exception("Функція ШІ тимчасово недоступна. Ми працюємо над її покращенням!"); }
private string CleanJson(string text).gitignore-3
Dockerfile-36
FlowAPI.Application/Services/AIService.cs+3-466