Commit Graph

396 Commits

Author SHA1 Message Date
12d4d7c63b feat: Add comprehensive debug information for workflow nodes
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 8s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
Backend changes:
- workflow_models.py: Add debug_prompt, debug_raw_response, debug_node_type, debug_prompt_slug, metadata fields to NodeExecutionState
- workflow_executor.py: Capture and store debug info for analysis, logic, and join nodes when enable_debug=True
  - Analysis nodes: store full prompt + raw AI response
  - Logic nodes: store expression + evaluation result
  - Join nodes: store strategy + path statistics

Frontend changes:
- Analysis.jsx: Enable debug mode by default (debug=true) for all workflow executions

This allows developers to see exactly what prompt was sent to the AI, what response was received, and how each node was processed - essential for debugging workflow issues.
2026-04-13 12:38:55 +02:00
3664f53c51 fix: Use NodeStatus.EXECUTED instead of COMPLETED
All checks were successful
Deploy Development / deploy (push) Successful in 53s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
NodeStatus enum has EXECUTED, not COMPLETED. Fixed in workflow_executor.py progress callback.
2026-04-13 11:49:31 +02:00
fb2e0803c0 fix: SSE streaming - WorkflowNode label attribute and ai_insights column name
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- workflow_executor.py: Generate node_label from prompt_slug or node.type (WorkflowNode has no label attribute)
- prompts.py: Fix INSERT statement - use 'created' column instead of 'created_at'

SSE endpoint now works correctly for workflow execution streaming.
2026-04-13 11:47:31 +02:00
bb01283727 fix: Correct except/finally indentation in SSE endpoint
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
2026-04-13 11:41:56 +02:00
bc60b9f5c9 fix: Correct indentation in SSE execute_workflow_async function
Some checks failed
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Failing after 1s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
2026-04-13 11:27:44 +02:00
fbeabcde97 fix: IndentationError in prompts.py SSE endpoint
Some checks failed
Deploy Development / deploy (push) Successful in 52s
Build Test / pytest-backend (push) Failing after 1s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 16s
2026-04-13 11:25:34 +02:00
ba474b0a57 feat: Implement Server-Sent Events (SSE) for long-running workflows
Some checks failed
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Failing after 1s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Backend:
- workflow_executor.py: Add progress_callback parameter, emit events for execution_started, node_complete, execution_complete, execution_failed
- prompt_executor.py: Thread progress_callback through execute chain
- routers/prompts.py: New /execute-stream endpoint with asyncio Queue for SSE

Frontend:
- utils/api.js: New executeUnifiedPromptStream() function with EventSource
- pages/Analysis.jsx: Use SSE with live progress display (X/Y Nodes)

Fixes:
- No more gateway timeouts for complex workflows (10+ nodes)
- Live progress feedback for users
- Unlimited workflow complexity

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-04-13 11:23:16 +02:00
790e6df8ef fix: Make debug parameter work as Query parameter in /api/prompts/execute
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 17s
Bug: debug=true in URL was ignored because FastAPI expected it in
request body (POST without Query() expects body params by default).

Result: node_states were never returned, even with ?debug=true

Fix: Changed debug and save to Query parameters:
- debug: bool = Query(False, ...)
- save: bool = Query(False, ...)

Now ?debug=true in URL correctly enables debug output with node_states.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 09:14:30 +02:00
057df0afc8 fix: Support UI-format edge routing with sourceHandle
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 24s
Logic-Nodes evaluated correctly but activated_edges was empty because
_get_edges_by_label() only checked e.label, which is null in UI format.

UI format uses:
- sourceHandle: "true" / "false" (instead of label: "then" / "else")
- targetHandle: "in" / "path_1" / etc.

Changes:
1. Added source_handle/target_handle fields to WorkflowEdge model
   - With aliases sourceHandle/targetHandle for camelCase JSON
2. Updated _get_edges_by_label() to check both formats:
   - Legacy: e.label == "then" / "else"
   - UI: e.source_handle == "true" / "false"

Now Logic-Nodes correctly activate outgoing edges → Join-Node receives
completed paths → End-Node executes → Workflow completes!

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 09:07:50 +02:00
ba04e0c0b6 fix: Add extra='forbid' to Condition for proper Union resolution
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Critical fix: Without extra='forbid', Pydantic accepted UI format
{operator: "and", operands: [...]} as valid Condition by ignoring
unknown fields, resulting in Condition(expression=None).

With extra='forbid':
- Condition rejects unknown fields → fails
- Union tries next type → LogicExpression → success

Test Results (9/9 passed):
- Simple comparisons (eq, neq, gt, lt, in) 
- AND/OR combinations 
- Deep nesting (3+ levels) 
- NOT operator 
- All operators (eq, neq, in, not_in, gt, lt, gte, lte, and, or, not) 
- Legacy format (Condition wrapper) 
- Complex real-world scenarios 

Added comprehensive test suite in:
- test_condition_parsing.py (9 test cases)
- test_condition_union.py (Union resolution verification)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 09:01:53 +02:00
f5ce1ec941 refactor: Proper type-safe condition handling with Union types
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / pytest-backend (push) Successful in 5s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Previous fix used Any type, breaking type safety and only handling
simple cases. This is the correct implementation:

Changes:
1. LogicExpression.operands: List[Any] → List['LogicExpression']
   - Enables recursive/nested expressions
   - Proper type checking for all operator combinations

2. WorkflowNode.condition: Any → Union[LogicExpression, Condition]
   - Type-safe deserialization
   - Supports both UI format (direct LogicExpression) and legacy (Condition wrapper)
   - Pydantic automatically tries LogicExpression first, then Condition

3. Executor: Simplified with isinstance() checks
   - Clean type detection without dict manipulation
   - Fallback for edge cases

This now correctly handles:
- Simple conditions: {operator: "eq", ref: "...", value: "..."}
- Combined: {operator: "and", operands: [...]}
- Nested: {operator: "or", operands: [{operator: "and", ...}, ...]}
- All operators: eq, neq, in, not_in, gt, lt, gte, lte, contains, and, or, not
- Legacy format: {expression: {...}, then_path: "...", else_path: "..."}

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:45:55 +02:00
2deb6510f8 fix: Support UI-format LogicExpression in Logic-Node condition field
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 13s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Root cause: UI saves LogicExpression directly as condition:
  {operands: [...], operator: "and"}

But Pydantic model expected Condition with wrapped expression:
  {expression: {operands: [...], operator: "and"}}

Result: Pydantic deserialized it as Condition with expression=None
→ Logic-Nodes failed with "'NoneType' object has no attribute 'operator'"

Fix:
1. Changed WorkflowNode.condition type from Condition to Any
2. Executor now handles both dict and Pydantic model formats
3. Detects UI format (operator+operands) vs legacy format (expression wrapper)
4. Converts dict to LogicExpression before evaluation

Fixes: Logic-Node execution failures in Training-Tiefenanalyse workflow

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:40:43 +02:00
0eac40abf6 fix: Add None-check for Logic-Node condition/expression
All checks were successful
Deploy Development / deploy (push) Successful in 51s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Previous fix handled hasattr() but didn't check for None values.
Now explicitly checks that operator/expression is not None before using it.

Error was: "'NoneType' object has no attribute 'operator'"

Clearer error message: "condition is None or missing"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:32:54 +02:00
e915d3fb13 fix: Support both Logic-Node condition serialization formats
All checks were successful
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 5s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Logic-Nodes were timing out because UI saves condition as:
  {operands: [...], operator: "and"}

But Backend expected:
  {expression: {operands: [...], operator: "and"}}

This caused node.condition.expression to be None, triggering:
- Logic-Node failures
- Join-Node wait_all timeout
- 504 Gateway Timeout

Fix: Accept both formats by checking for operator/operands attributes
directly on condition, falling back to condition.expression.

Fixes: 504 Gateway Timeout in Training-Tiefenanalyse workflow

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-13 08:26:43 +02:00
60f6cf3c6d fix: Add null check for logic node expression to prevent AttributeError
All checks were successful
Deploy Development / deploy (push) Successful in 58s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Problem: Logic nodes without logic_expression defined caused AttributeError
"'NoneType' object has no attribute 'operator'" when evaluating condition.

Solution: Check both node.condition AND node.condition.expression before
calling evaluate_logic_expression(). Return clear FAILED state with error
message instead of crashing.

Impact: Workflows with incomplete logic node definitions now fail gracefully
with clear error message instead of cryptic AttributeError.
2026-04-13 08:16:06 +02:00
e09cbc112e fix: Preserve case in question IDs during parsing
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Problem: Parser converted question IDs to lowercase ('qAnalyst' → 'qanalyst'),
causing normalization to fail because id_catalog lookup is case-sensitive.

Impact: All workflow question signals were lost - normalized_signals stayed empty,
so template placeholders like {{node_2.signal_qAnalyst}} remained unresolved.

Solution: Removed .lower() call in parse_decision_questions() to preserve
original case from AI response.

Root cause: Line 162 in result_container_parser.py
Fixes: Question augmentation signals not appearing in workflow end nodes
2026-04-12 14:04:14 +02:00
f6b3182a80 fix: Add wrapper in prompts.py execute endpoint for workflow signature mismatch
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Problem: Workflows executed via /api/prompts/execute (not /api/workflows/execute)
were passing call_openrouter directly to execute_prompt_with_data, which then
passes it to workflow_executor. workflow_executor expects (prompt, model) signature
but call_openrouter has (prompt, max_tokens=4096) signature.

Previous fix in workflows.py was correct but unused - workflows use prompts.py endpoint.

Solution: Added workflow_llm_call() wrapper in execute_unified_prompt() endpoint
that matches expected (prompt, model) -> str signature.

Related: cb3aa48 (workflows.py fix for different endpoint)
2026-04-12 13:44:08 +02:00
cb3aa48999 fix: Add wrapper function for workflow LLM calls to prevent max_tokens signature mismatch
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Problem: workflow_executor calls openrouter_call_func(prompt, model) but
call_openrouter expects (prompt, max_tokens=4096). This caused the model string
'anthropic/claude-sonnet-4' to be passed as max_tokens, resulting in OpenRouter
requesting 64000 tokens and failing with 402 credit errors.

Solution: Added workflow_llm_call() wrapper in workflows.py that matches the
expected (prompt, model) -> str signature and calls call_openrouter correctly.

Fixes: All workflows failing with 402 'insufficient credits' errors
2026-04-12 13:37:31 +02:00
4b6e1bed11 feat: Enhance OpenRouter API interaction and error handling
All checks were successful
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Increased the maximum token limit in the `call_openrouter` function from 1500 to 4096 to allow for more extensive responses.
- Implemented robust error handling for API requests, including timeout and request errors, with detailed HTTP exceptions for better debugging.
- Improved JSON response handling to ensure valid data is returned, with specific error messages for missing content in the response.
- Enhanced the overall reliability of the OpenRouter API integration, providing clearer feedback for users in case of issues.

These changes improve the user experience by ensuring more comprehensive responses and clearer error reporting during API interactions.
2026-04-12 11:03:07 +02:00
90a27846ca feat: Improve float parsing logic for enhanced accuracy in numeric conversions
All checks were successful
Deploy Development / deploy (push) Successful in 56s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated the `_parse_float_auto` function in `type_converter.py` to better handle various decimal and thousand separators, particularly for cases with long decimal parts from sources like Apple Health.
- Enhanced the logic for splitting and processing numeric strings to ensure correct interpretation of values, including edge cases with multiple separators.
- Added handling for cases where numeric strings may contain both commas and periods, improving overall robustness in float parsing.

These changes enhance the accuracy of numeric conversions, ensuring more reliable data processing across the application.
2026-04-12 07:28:24 +02:00
d7cefdd9e9 feat: Update Gitea issues index and enhance data layer metrics
All checks were successful
Deploy Development / deploy (push) Successful in 1m3s
Build Test / pytest-backend (push) Successful in 9s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated the Gitea issues index to reflect the latest state as of 2026-04-11, adding issue #76 to the list.
- Refined data handling in `activity_metrics.py`, `body_metrics.py`, `nutrition_metrics.py`, and `scores.py` to ensure consistent float conversions for calculations, improving accuracy in metric evaluations.
- Enhanced the calculation logic for various metrics to handle potential None values more robustly, ensuring smoother data processing and improved reliability across the application.

These changes improve the clarity of the Gitea issues documentation and enhance the overall accuracy and reliability of health and fitness metrics.
2026-04-11 22:14:45 +02:00
4868e44882 feat: Refine placeholder resolution with enhanced modifiers support
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Updated `resolve_placeholders` in `prompt_executor.py` to support combined modifiers for placeholders, allowing for more flexible output formats.
- Enhanced `build_ai_placeholder_caption` in `placeholder_registry.py` to clarify the generation of AI context captions, focusing on descriptions and explanations.
- Introduced new helper functions in `placeholder_resolver.py` to streamline the retrieval of descriptions and explanations for placeholders.
- Modified tests to cover new functionality, ensuring accurate behavior for combined modifiers and improved placeholder resolution.

These changes enhance the usability and clarity of placeholder outputs, providing users with richer contextual information.
2026-04-11 21:58:29 +02:00
a9a414b956 feat: Enhance placeholder caption generation and formatting
All checks were successful
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 8s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated `build_ai_placeholder_caption` in `placeholder_registry.py` to improve the generation of AI context captions by prioritizing descriptions and avoiding redundancy.
- Introduced `format_value_with_d_modifier` in `placeholder_resolver.py` to format values with contextual information, enhancing the clarity of exported placeholder values.
- Modified `export_placeholder_values` in `prompts.py` to utilize the new formatting function, ensuring that exported data includes both raw values and contextual descriptions.
- Added tests for the new formatting function and updated existing tests to ensure accurate caption generation.

These changes improve the contextual relevance of placeholder data and enhance the user experience when interacting with exported values.
2026-04-11 21:47:08 +02:00
baeddd7c13 feat: Enhance placeholder system with AI context support
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Introduced `build_ai_placeholder_caption` function in `placeholder_registry.py` to generate AI context captions based on placeholder metadata.
- Updated `resolve_placeholders` in `placeholder_resolver.py` to support modifiers for AI context, allowing for enhanced descriptions when placeholders are resolved.
- Modified `get_placeholder_catalog` to include AI captions in the output, improving the metadata available for placeholders.
- Adjusted `export_placeholder_values` to include AI captions in the exported data, enhancing the information provided to users.

These changes improve the flexibility and functionality of the placeholder system, enabling richer context generation for dynamic content.
2026-04-11 21:36:29 +02:00
41bf593d4c feat: Refactor sleep metrics calculations and improve error handling
All checks were successful
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 3s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated `get_sleep_avg_duration` and `get_sleep_avg_quality` functions in `placeholder_resolver.py` to provide clearer error messages when data is unavailable.
- Enhanced sleep quality calculations in `recovery_metrics.py` to handle cases with insufficient data more robustly.
- Improved data handling in various metrics files (`activity_metrics.py`, `body_metrics.py`, `nutrition_metrics.py`, `recovery_metrics.py`, and `scores.py`) to ensure consistent float conversions for calculations.
- Added utility functions in `recovery_metrics.py` for parsing and normalizing sleep segment data, enhancing the accuracy of sleep quality assessments.

These changes improve the reliability and clarity of sleep-related metrics and enhance overall data handling across the application.
2026-04-11 21:27:49 +02:00
04e23d8115 feat: Enhance placeholder resolution and error handling
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Updated `extract_value_raw` to improve JSON parsing and handle unavailable data more effectively.
- Introduced new functions in `placeholder_resolver.py` for standardized responses when data is unavailable, enhancing clarity for users and AI.
- Modified various data retrieval functions to utilize the new response format, providing detailed reasons for unavailability.
- Improved availability checks in `export_placeholder_values_extended` to account for new response formats.

These changes enhance the robustness of the placeholder system and improve user experience by providing clearer error messages and data handling.
2026-04-11 21:22:27 +02:00
052ba195cc feat: Update placeholder metadata and nutrition metrics
All checks were successful
Deploy Development / deploy (push) Successful in 54s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 15s
- Adjusted the total number of placeholders from 116 to 114 across various documentation and code files to reflect the current state of the system.
- Enhanced TDEE calculation logic in `nutrition_metrics.py` to prioritize Mifflin–St Jeor BMR with PAL when demographic data is available, with a fallback to a weight-based estimate.
- Updated placeholder registrations to ensure consistency with the new metadata structure and improved data handling.
- Revised documentation to clarify the authoritative source of placeholder metadata and the implications of the changes on existing functionalities.

These updates improve the accuracy and consistency of the placeholder system and enhance the nutritional assessment capabilities within the application.
2026-04-11 21:11:05 +02:00
2ea5f905c4 feat: Add new profile and time period placeholders in placeholder_resolver.py
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 16s
- Introduced functions to retrieve profile name, age, height, and gender for better placeholder resolution.
- Added functions for displaying current date and time period labels (last 7, 30, and 90 days).
- Updated PLACEHOLDER_MAP to utilize new functions for improved readability and maintainability.
- Enhanced placeholder registrations in __init__.py to include new modules for sleep, vital metrics, and profile time periods.

These changes enhance the flexibility and functionality of the placeholder system, allowing for more dynamic content generation.
2026-04-11 21:08:34 +02:00
e9e094c6a4 feat: Enhance nutrition and activity metrics with new data layers
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Added new functions for BMI and goal weight/body fat percentage retrieval in `body_metrics.py`.
- Introduced training frequency and inter-session gap calculations in `activity_metrics.py`.
- Updated placeholder registrations to include new metrics for nutrition and activity.
- Improved data handling in `placeholder_resolver.py` for better integration of new metrics.
- Enhanced documentation across modules to reflect the new functionalities.

These updates improve the accuracy and comprehensiveness of health and fitness assessments within the application.
2026-04-11 20:46:17 +02:00
61a5bb39ae feat: Update nutrition metrics and energy balance calculations
All checks were successful
Deploy Development / deploy (push) Successful in 59s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Introduced a single TDEE calculation based on current weight, replacing the fixed 2500 kcal value.
- Updated `get_energy_balance_data` to use daily totals for intake calculations and improved energy balance logic.
- Enhanced `get_nutrition_average_data` to calculate averages over calendar days instead of raw log entries.
- Adjusted placeholder resolution to ensure consistent metadata usage across requests.
- Fixed issues in the charts router to reflect the new energy balance logic and TDEE calculations.

These changes improve the accuracy of nutritional assessments and streamline data handling in the application.
2026-04-11 19:04:27 +02:00
10d24bbef7 fix(workflow): Duplicate - JSON-encode JSONB fields
All checks were successful
Deploy Development / deploy (push) Successful in 52s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
**Error:**
```
psycopg2.ProgrammingError: can't adapt type 'dict'
```

**Root Cause:**
- duplicate_prompt passed Python dicts directly to SQL INSERT
- JSONB fields from r2d() are already deserialized by psycopg2
- PostgreSQL expects JSON strings for JSONB columns

**Fix:**
- Added json.dumps() for all JSONB fields before INSERT:
  - stages, output_schema, question_augmentations, graph_data
- Same pattern as import function

Files changed:
- backend/routers/prompts.py: JSON-encode JSONB in duplicate_prompt

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 14:46:13 +02:00
ff8104a533 fix(workflow): Route precedence - move export/import before path param
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
**Root Cause:**
- FastAPI route matching: /{prompt_id} caught ALL requests including /export-all
- Specific routes MUST be defined BEFORE path parameter routes

**Error:**
```
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type uuid: "export-all"
LINE 1: SELECT * FROM ai_prompts WHERE id='export-all'
```

**Fix:**
- Moved /export-all and /import endpoints to line 106 (BEFORE /{prompt_id} at ~260)
- Added warning comments to both functions
- Fixed typo: for r in → for row in

**Affected:**
- /export-all: Internal Server Error → now works 
- /import: Would have had same issue → preemptively fixed 

Files changed:
- backend/routers/prompts.py: Reordered route definitions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 14:42:55 +02:00
3b7f89a214 fix(workflow): UnboundLocalError in execute_end_node - graph not defined
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Critical bug fix from pytest failures:

**Problem:**
- execute_end_node() tried to use 'graph' variable without defining it
- UnboundLocalError at line 602: "if graph:"
- Caused 2 test failures in test_end_node_template.py

**Root Cause:**
- In Issue #5 fix, added graph lookup for node labels in AUTO mode
- But forgot to get graph from context first
- TEMPLATE mode already had: graph = context.get("graph")

**Fix:**
- Added: graph = context.get("graph") at start of AUTO mode block
- Same pattern as TEMPLATE mode
- graph is optional (None if not in context), so if-check is safe

**Tests:**
- test_auto_mode_concatenates_all_analyses - should pass now
- test_auto_mode_skips_skipped_nodes - should pass now

Files changed:
- backend/workflow_executor.py: Added graph = context.get("graph") line 596

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 14:28:19 +02:00
ba773e677b fix(workflow): Test-Suite Fixes - Issues #5, #8, #9, #11, #12
Some checks failed
Deploy Development / deploy (push) Successful in 1m1s
Build Test / pytest-backend (push) Failing after 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
Addressed test results from Test_status_Wkf.md:

**Issue #5: End-Node Überschriften**
- Fixed aggregate_results to show node labels instead of "Node 10"
- Added graph lookup to get node.data.label from node objects
- Modified backend/workflow_executor.py (2 locations)

**Issue #8: Löschen-Taste funktioniert nicht**
- Added Delete key support to WorkflowCanvas
- Set deleteKeyCode={['Backspace', 'Delete']}
- Frontend: WorkflowCanvas.jsx

**Issue #9: Mehrere End-Nodes verhindern**
- Added validation error when multiple End-Nodes exist
- Backend supports only 1 End-Node (aggregate_results takes last)
- Frontend: workflowValidation.js

**Issue #11: Export Fehler "Internal Server Error"**
- Added missing fields to export-all endpoint:
  - graph_data (workflow node graph)
  - question_augmentations (analysis prompts)
- Added missing fields to import endpoint
- Proper JSON serialization for all JSONB fields
- Backend: routers/prompts.py

**Issue #12: Workflow duplizieren funktioniert nicht**
- Fixed duplicate endpoint to include all prompt fields:
  - type, stages, output_format, output_schema
  - question_augmentations, graph_data (critical for workflows!)
- Backend: routers/prompts.py

Files changed:
- backend/workflow_executor.py: Node label lookup in aggregate_results
- backend/routers/prompts.py: Export/import/duplicate fixes
- frontend/src/components/workflow/WorkflowCanvas.jsx: Delete key
- frontend/src/utils/workflowValidation.js: Max 1 End-Node validation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 14:15:57 +02:00
d803f39de3 feat: Refactor workflow result handling in prompts and analysis components
All checks were successful
Deploy Development / deploy (push) Successful in 53s
Build Test / pytest-backend (push) Successful in 8s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Introduced a new utility function to streamline the extraction of user-facing content from aggregated workflow results.
- Updated backend prompt handling to utilize the new function for improved clarity and maintainability.
- Adjusted frontend analysis component to leverage the utility for consistent content display across different workflow result formats.

These changes enhance the overall user experience by ensuring more reliable and readable output from workflow executions.
2026-04-11 12:04:35 +02:00
300d96a9d8 feat: Enhance prompt execution for workflows and analysis offers
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Added support for handling aggregated results in workflow prompts, allowing for various data formats (string, object).
- Introduced a utility function to filter active prompts for both pipeline and workflow types in the analysis page.
- Updated content handling in the analysis component to accommodate new workflow data structures.

This improves the flexibility and usability of the prompt execution process in both backend and frontend components.
2026-04-11 11:42:54 +02:00
88f0b5a0a4 fix: Add workflow node outputs as placeholders in inline templates
All checks were successful
Deploy Development / deploy (push) Successful in 46s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
ISSUE: Inline templates referencing node outputs ({{ node_id.analysis_core }},
{{ node_id.signal_xyz }}) were not resolved - AI received empty data from
previous workflow stages.

ROOT CAUSE: load_prompt_template() only loaded system placeholders
(name, age, etc.) but not node execution results from context['node_results'].

FIX:
- Extract node outputs from context['node_results']
- Add as placeholders: node_id.analysis_core, node_id.signal_xyz, node_id.question_xyz
- Format matches PlaceholderPicker extraction logic
- Debug logging shows which node placeholders are added

TESTING:
- System placeholder test:  SUCCESS (name, age, geschlecht resolved)
- Node output placeholders: Fixed (previously missing)
- User workflow: Join → Analysis → End now receives upstream data

Part 3: Inline Prompts - placeholder resolution completion
2026-04-11 10:13:03 +02:00
aeb0ee6ad9 debug: Add comprehensive placeholder resolution logging to workflow executor
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 15s
- Log placeholder loading (count, sample keys)
- Log key cleaning process (before/after)
- Log sample values (name, age, geschlecht)
- Log template before/after resolution
- Log resolved and unresolved placeholders
- Add .strip() to key cleaning to handle spaces

This will help diagnose why {{ name }}, {{ age }}, {{ geschlecht }} are not resolving in inline templates.
Issue: Part 3 Inline Prompts - placeholder resolution debugging
2026-04-11 09:38:18 +02:00
65500c899b fix: Add missing WorkflowNode import in workflow_executor
All checks were successful
Deploy Development / deploy (push) Successful in 49s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
Import war vergessen nach Umstellung von load_prompt_template() auf WorkflowNode Parameter.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 08:47:45 +02:00
a1723db387 feat: Workflow Engine Part 3 - Inline Prompts (v0.9q)
Some checks failed
Deploy Development / deploy (push) Successful in 56s
Build Test / pytest-backend (push) Failing after 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
Ermöglicht Analysis Nodes zwischen zwei Prompt-Modi zu wählen:
- Reference Mode: Basis-Prompt aus DB referenzieren (bestehend)
- Inline Mode: Template direkt im Node editieren (NEU)

Frontend:
- InlineTemplateEditor Component (~80 Zeilen)
- Radio Buttons in WorkflowEditorPage für Mode-Auswahl
- Placeholder Picker für beide Modi (End Node + Inline Template)
- Cursor-Position Tracking mit textareaRef
- Conditional Rendering basierend auf promptSource
- Validation: Entweder prompt_slug ODER inline_template

Backend:
- load_prompt_template() akzeptiert ganzen WorkflowNode (statt nur slug)
- Unterstützt inline_template (Mode 1) und prompt_slug (Mode 2)
- WorkflowNode.inline_template Feld hinzugefügt
- Validation: HTTPException wenn weder slug noch template

Serialization:
- inline_template in graph_data speichern/laden
- Backward-compatible mit bestehenden Workflows

Version: 0.9q
Module: workflow 0.7.0

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 08:45:00 +02:00
ebca44829e fix(csv_parser): Normalize header comparison in CSV template validation
All checks were successful
Deploy Development / deploy (push) Successful in 56s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Updated the `validate_csv_template` function to normalize both the column signature and field mappings for accurate comparison, preventing false warnings about mismatches.
- Enhanced warning messages to provide clearer guidance on the relationship between normalized signatures and raw field mappings.
- Added a new test to ensure that normalized signatures do not trigger false warnings when compared to raw mappings.
2026-04-11 06:52:17 +02:00
0629f88b37 feat(csv-templates): Add CSV template validation endpoint and enhance error handling
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Introduced a new endpoint for validating CSV templates without saving, allowing users to check field mappings and type conversions.
- Updated the `create_system_template` and `update_system_template` functions to include validation reports in responses.
- Enhanced error handling in CSV import processes by integrating `enrich_row_error` for more informative error messages.
- Improved the AdminCsvTemplateEditorPage to support format checking and display validation results, enhancing user experience.
- Incremented version numbers for `csv_import` and `admin_csv_templates` to reflect these updates.
2026-04-11 06:47:27 +02:00
6945b748cb feat(schema, csv_parser): Update activity log schema and parsing logic
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 3s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Increased precision for `kcal_active`, `kcal_resting`, `hr_avg`, and `hr_max` fields in the activity log schema.
- Added a new function `_activity_hr_bpm` to validate heart rate values during CSV import, ensuring they fall within plausible ranges.
- Updated the CSV parser to utilize the new heart rate validation function for improved data integrity.
- Enhanced the type converter to accommodate additional aliases for energy fields in CSV imports.
- Added a test to verify conversion of active energy from kJ to kcal, ensuring accurate data handling.
2026-04-11 06:41:23 +02:00
08a2485f43 refactor(csv_parser): Implement SAVEPOINT handling for activity import
All checks were successful
Deploy Development / deploy (push) Successful in 47s
Build Test / pytest-backend (push) Successful in 9s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 15s
- Added SAVEPOINT management to the `_import_activity` function to improve error handling during CSV imports.
- Moved the training type resolution logic to occur within a transaction block, ensuring that errors can be rolled back without affecting the entire import process.
- Enhanced error logging to capture evaluation failures, providing better insights during CSV import operations.
2026-04-11 06:31:42 +02:00
894ee1dd02 refactor(csv_parser): Update training type resolution to use existing database cursor
All checks were successful
Deploy Development / deploy (push) Successful in 48s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
- Modified `_resolve_training_type_for_activity` to accept a database cursor, improving efficiency and avoiding potential deadlocks during CSV imports.
- Introduced `get_training_type_for_activity_with_cursor` to handle training type resolution with an existing cursor, streamlining database interactions.
- Updated related calls in the activity import logic to utilize the new function, ensuring consistent behavior across the application.
2026-04-11 06:27:11 +02:00
a9bd3faabb Bug Fix für type_converter.py und executor.py
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 16s
2026-04-10 16:52:11 +02:00
5b96bd4f75 feat(csv-import): Add blood pressure and activity row diagnosis functionality
All checks were successful
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Introduced `diagnose_blood_pressure_row` and `diagnose_activity_row` functions to validate and analyze blood pressure and activity data from CSV imports.
- Updated the CSV import logic to handle combined datetime columns for blood pressure and activity, improving data integrity during import.
- Enhanced type conversion specifications to include `start_time` for blood pressure and activity, ensuring accurate data mapping.
- Added tests to validate the new diagnosis functions and their integration with existing import processes, ensuring robustness and reliability.
- Updated frontend messages to provide clearer guidance on blood pressure and activity data handling during CSV imports.
2026-04-10 16:43:00 +02:00
c5b0540b11 feat(csv-import): Add CSV import diagnosis endpoint and related functionality
All checks were successful
Deploy Development / deploy (push) Successful in 50s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 17s
- Implemented a new endpoint for diagnosing CSV imports without writing to the database, allowing users to validate mappings and type conversions.
- Introduced the `diagnose_vitals_row` function to analyze vital metrics and provide detailed feedback on data validity.
- Enhanced the CSV import logic to include alias handling for vital fields, improving compatibility with different CSV formats.
- Updated the frontend to support the new diagnosis feature, including UI elements for displaying diagnosis results and error details.
- Added tests to ensure the correctness of the new diagnosis functionality and its integration with existing import processes.
2026-04-10 16:35:31 +02:00
1855f6e57a refactor(migrations): Improve idempotency and constraint handling for vitals_baseline source
All checks were successful
Deploy Development / deploy (push) Successful in 57s
Build Test / pytest-backend (push) Successful in 4s
Build Test / lint-backend (push) Successful in 0s
Build Test / build-frontend (push) Successful in 18s
- Updated migration scripts to ensure idempotent behavior for the source CHECK constraint, allowing for consistent application even if previous migrations were partially successful.
- Enhanced SQL logic to drop existing constraints safely and re-add them, ensuring compatibility with the universal CSV import.
- Clarified comments for better understanding of migration context and functionality.
2026-04-10 16:17:35 +02:00
5a0c71dd90 feat(csv-import): Implement SAVEPOINT handling for vitals baseline import
Some checks failed
Deploy Development / deploy (push) Successful in 55s
Build Test / pytest-backend (push) Failing after 1s
Build Test / lint-backend (push) Successful in 1s
Build Test / build-frontend (push) Successful in 17s
- Updated the CSV import logic to include SAVEPOINT management, allowing for better error handling during the vitals baseline import process.
- Enhanced the SQL migration script to drop existing CHECK constraints related to the 'source' field, ensuring compatibility with the new universal CSV import.
- Incremented DB_SCHEMA_VERSION to "20260409c" to reflect these changes and improve the import process reliability.
2026-04-10 16:11:08 +02:00