Compare commits
40
Commits
caeed3fbaa
...
ench.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
19a88e4f97 | ||
|
|
1b01f5e6d0 | ||
|
|
424270f0e8 | ||
|
|
df8e732709 | ||
|
|
d5325acee6 | ||
|
|
b7062d32bf | ||
|
|
5fa2ea2e6b | ||
|
|
f97d15288d | ||
|
|
736dc58d81 | ||
|
|
0a27533262 | ||
|
|
7388776b29 | ||
|
|
a515a5d563 | ||
|
|
12d4d7c63b | ||
|
|
f34e46b04f | ||
|
|
3664f53c51 | ||
|
|
fb2e0803c0 | ||
|
|
bb01283727 | ||
|
|
bc60b9f5c9 | ||
|
|
fbeabcde97 | ||
|
|
ba474b0a57 | ||
|
|
790e6df8ef | ||
|
|
057df0afc8 | ||
|
|
ba04e0c0b6 | ||
|
|
f5ce1ec941 | ||
|
|
2deb6510f8 | ||
|
|
0eac40abf6 | ||
|
|
e915d3fb13 | ||
|
|
60f6cf3c6d | ||
|
|
46b703e5a2 | ||
|
|
e09cbc112e | ||
|
|
f6b3182a80 | ||
|
|
cb3aa48999 | ||
|
|
77f1ed14c5 | ||
|
|
25c4ecfd48 | ||
|
|
08c9cccdcc | ||
|
|
4b6e1bed11 | ||
|
|
72eb94d186 | ||
|
|
90a27846ca | ||
|
|
4d81ea2cf3 | ||
|
|
d7cefdd9e9 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# Gitea Issues – Landkarte (Auswertung)
|
||||
|
||||
**Quelle:** Gitea `Lars/mitai-jinkendo`, Stand **2026-04-09** (Abfrage `state=all`, ergänzt: #71).
|
||||
**Quelle:** Gitea `Lars/mitai-jinkendo`, Stand **2026-04-11** (Abfrage `state=all`, ergänzt: #71, #76).
|
||||
**URL:** http://192.168.2.144:3000/Lars/mitai-jinkendo/issues
|
||||
|
||||
Dieses Dokument ist ein **Orientierungs-Index** für Agenten und Entwickler. Verbindliches Tracking bleibt **in Gitea**; hier: Kategorien, Dubletten-Hinweise, grobe Prioritätseinschätzung.
|
||||
@@ -88,6 +88,7 @@ Dieses Dokument ist ein **Orientierungs-Index** für Agenten und Entwickler. Ver
|
||||
| # | Titel |
|
||||
|---|--------|
|
||||
| 15 | [FEAT-002] Quality-Filter für KI-Auswertungen & Charts integrieren |
|
||||
| 76 | Trainings-Qualität: zielbezogene Logik + Listen-Filter statt globalem „Hochwertig“-Hide |
|
||||
| 36 | BUG-009: Trainingstyp-Erstellung führt zu Internal Server Error |
|
||||
|
||||
---
|
||||
|
||||
@@ -66,7 +66,13 @@ def _parse_float_auto(s: str) -> float:
|
||||
"""
|
||||
Heuristik ohne festes Locale: Punkt/Komma als Tausender vs. Dezimal,
|
||||
basierend auf der letzten erkannten Trennstelle und Gruppierung.
|
||||
|
||||
Apple Health u. a. liefern berechnete Mittelwerte mit vielen Nachkommastellen
|
||||
(z. B. «96.874937…») und Energie als «596.668904…» — dabei ist der Punkt
|
||||
immer Dezimaltrenner. Früher wurden lange Nachkommateile fälschlich so
|
||||
behandelt, dass der Punkt entfernt wurde (Tausender-Heuristik).
|
||||
"""
|
||||
raw = s
|
||||
s = _normalize_num_token(s)
|
||||
if not s or s in ("-", "—", "–"):
|
||||
raise ValueError("leer")
|
||||
@@ -90,18 +96,35 @@ def _parse_float_auto(s: str) -> float:
|
||||
s = s.replace(",", "")
|
||||
elif last_comma >= 0:
|
||||
parts = s.split(",")
|
||||
if len(parts) == 2 and len(parts[1]) <= 2:
|
||||
s = parts[0].replace(".", "") + "." + parts[1]
|
||||
elif len(parts) == 2 and len(parts[1]) == 3 and len(parts[0]) <= 3:
|
||||
s = parts[0] + parts[1]
|
||||
if len(parts) == 2:
|
||||
left, right = parts[0], parts[1]
|
||||
if not right:
|
||||
raise ValueError("leer")
|
||||
left_digits = left.replace(".", "")
|
||||
# Langer Nachkommateil → Dezimalkomma; «1.234,56»-Fälle oben mit Punkt+Komma
|
||||
if len(right) > 3 or len(right) <= 2:
|
||||
s = left_digits + "." + right.replace(".", "")
|
||||
elif len(right) == 3 and len(left_digits) <= 3:
|
||||
s = left_digits + right
|
||||
else:
|
||||
s = left_digits + "." + right.replace(".", "")
|
||||
else:
|
||||
s = s.replace(",", "")
|
||||
elif last_dot >= 0:
|
||||
parts = s.split(".")
|
||||
if len(parts) == 2 and len(parts[1]) <= 2:
|
||||
s = parts[0].replace(",", "") + "." + parts[1]
|
||||
elif len(parts) == 2 and len(parts[1]) == 3 and len(parts[0]) <= 3:
|
||||
s = parts[0] + parts[1]
|
||||
if len(parts) == 2:
|
||||
left, right = parts[0], parts[1]
|
||||
if not right:
|
||||
raise ValueError("leer")
|
||||
left_digits = left.replace(",", "")
|
||||
# Genau ein Punkt: viele Nachkommastellen → Apple/US-Dezimalpunkt (nicht „.“ streichen)
|
||||
if len(right) > 3 or len(right) <= 2:
|
||||
s = left_digits + "." + right
|
||||
elif len(right) == 3:
|
||||
if len(left_digits) == 1 and left_digits != "0" and left_digits.isdigit():
|
||||
s = left_digits + right
|
||||
else:
|
||||
s = left_digits + "." + right
|
||||
elif len(parts) > 2:
|
||||
if len(parts[-1]) <= 2:
|
||||
s = "".join(parts[:-1]) + "." + parts[-1]
|
||||
@@ -345,6 +368,18 @@ def _parse_int(raw: str, spec: Mapping[str, Any]) -> int:
|
||||
raise ValueError("leer")
|
||||
v = int(digits)
|
||||
return -v if neg else v
|
||||
# Ohne flexible: «108.0» / «96,8» trotzdem als Zahl mit Nachkommastellen
|
||||
s2 = _normalize_num_token(s)
|
||||
if "," in s2 or "." in s2:
|
||||
dec = spec.get("decimal_separator", ".")
|
||||
try:
|
||||
if dec in (None, "auto"):
|
||||
fv = _parse_float_auto(s2)
|
||||
else:
|
||||
fv = _parse_float(raw, str(dec))
|
||||
return int(round(fv))
|
||||
except (ValueError, InvalidOperation):
|
||||
pass
|
||||
s = re.sub(r"[^\d-]", "", s)
|
||||
if not s:
|
||||
raise ValueError("leer")
|
||||
|
||||
@@ -604,26 +604,23 @@ def calculate_activity_score(profile_id: str, focus_weights: Optional[Dict] = No
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Activity-related focus areas (English keys from DB)
|
||||
# Strength training
|
||||
strength = focus_weights.get('strength', 0)
|
||||
strength_endurance = focus_weights.get('strength_endurance', 0)
|
||||
power = focus_weights.get('power', 0)
|
||||
# Activity-related focus areas (English keys from DB); Gewichte float (kein Decimal×float)
|
||||
strength = float(focus_weights.get('strength', 0) or 0)
|
||||
strength_endurance = float(focus_weights.get('strength_endurance', 0) or 0)
|
||||
power = float(focus_weights.get('power', 0) or 0)
|
||||
total_strength = strength + strength_endurance + power
|
||||
|
||||
# Endurance training
|
||||
aerobic = focus_weights.get('aerobic_endurance', 0)
|
||||
anaerobic = focus_weights.get('anaerobic_endurance', 0)
|
||||
cardiovascular = focus_weights.get('cardiovascular_health', 0)
|
||||
aerobic = float(focus_weights.get('aerobic_endurance', 0) or 0)
|
||||
anaerobic = float(focus_weights.get('anaerobic_endurance', 0) or 0)
|
||||
cardiovascular = float(focus_weights.get('cardiovascular_health', 0) or 0)
|
||||
total_cardio = aerobic + anaerobic + cardiovascular
|
||||
|
||||
# Mobility/Coordination
|
||||
flexibility = focus_weights.get('flexibility', 0)
|
||||
mobility = focus_weights.get('mobility', 0)
|
||||
balance = focus_weights.get('balance', 0)
|
||||
reaction = focus_weights.get('reaction', 0)
|
||||
rhythm = focus_weights.get('rhythm', 0)
|
||||
coordination = focus_weights.get('coordination', 0)
|
||||
flexibility = float(focus_weights.get('flexibility', 0) or 0)
|
||||
mobility = float(focus_weights.get('mobility', 0) or 0)
|
||||
balance = float(focus_weights.get('balance', 0) or 0)
|
||||
reaction = float(focus_weights.get('reaction', 0) or 0)
|
||||
rhythm = float(focus_weights.get('rhythm', 0) or 0)
|
||||
coordination = float(focus_weights.get('coordination', 0) or 0)
|
||||
total_ability = flexibility + mobility + balance + reaction + rhythm + coordination
|
||||
|
||||
total_activity_weight = total_strength + total_cardio + total_ability
|
||||
|
||||
@@ -445,12 +445,16 @@ def calculate_weight_7d_median(profile_id: str) -> Optional[float]:
|
||||
ORDER BY date DESC
|
||||
""", (profile_id,))
|
||||
|
||||
weights = [row['weight'] for row in cur.fetchall()]
|
||||
weights = [
|
||||
safe_float(row['weight'])
|
||||
for row in cur.fetchall()
|
||||
if row['weight'] is not None
|
||||
]
|
||||
|
||||
if len(weights) < 4: # Need at least 4 measurements
|
||||
return None
|
||||
|
||||
return round(statistics.median(weights), 1)
|
||||
return round(float(statistics.median(weights)), 1)
|
||||
|
||||
|
||||
def calculate_weight_28d_slope(profile_id: str) -> Optional[float]:
|
||||
@@ -478,7 +482,11 @@ def _calculate_weight_slope(profile_id: str, days: int) -> Optional[float]:
|
||||
ORDER BY date
|
||||
""", (profile_id, days))
|
||||
|
||||
data = [(row['date'], row['weight']) for row in cur.fetchall()]
|
||||
data = [
|
||||
(row['date'], safe_float(row['weight']))
|
||||
for row in cur.fetchall()
|
||||
if row['weight'] is not None
|
||||
]
|
||||
|
||||
# Need minimum data points based on period
|
||||
min_points = max(18, int(days * 0.6)) # 60% coverage
|
||||
@@ -488,21 +496,21 @@ def _calculate_weight_slope(profile_id: str, days: int) -> Optional[float]:
|
||||
# Convert dates to days since start
|
||||
start_date = data[0][0]
|
||||
x_values = [(date - start_date).days for date, _ in data]
|
||||
y_values = [weight for _, weight in data]
|
||||
y_values = [w for _, w in data]
|
||||
|
||||
# Linear regression
|
||||
# Linear regression (alles float: PostgreSQL numeric → Decimal in Python)
|
||||
n = len(data)
|
||||
x_mean = sum(x_values) / n
|
||||
y_mean = sum(y_values) / n
|
||||
x_mean = float(sum(x_values)) / n
|
||||
y_mean = float(sum(y_values)) / n
|
||||
|
||||
numerator = sum((x - x_mean) * (y - y_mean) for x, y in zip(x_values, y_values))
|
||||
denominator = sum((x - x_mean) ** 2 for x in x_values)
|
||||
numerator = sum(float(x - x_mean) * float(y - y_mean) for x, y in zip(x_values, y_values))
|
||||
denominator = float(sum((x - x_mean) ** 2 for x in x_values))
|
||||
|
||||
if denominator == 0:
|
||||
return None
|
||||
|
||||
slope = numerator / denominator
|
||||
return round(slope, 4) # kg/day
|
||||
return round(float(slope), 4) # kg/day
|
||||
|
||||
|
||||
def calculate_goal_projection_date(profile_id: str, goal_id: str) -> Optional[str]:
|
||||
@@ -594,19 +602,24 @@ def _calculate_body_composition_change(profile_id: str, metric: str, days: int)
|
||||
recent = data[0]
|
||||
oldest = data[-1]
|
||||
|
||||
# Calculate FM and LBM
|
||||
recent_fm = recent['weight'] * (recent['bf_pct'] / 100)
|
||||
recent_lbm = recent['weight'] - recent_fm
|
||||
# Calculate FM and LBM (DB numeric → Decimal; für Regression/Scores nur float)
|
||||
rw = float(safe_float(recent['weight']) or 0)
|
||||
ob = float(safe_float(recent['bf_pct']) or 0)
|
||||
ow = float(safe_float(oldest['weight']) or 0)
|
||||
obf = float(safe_float(oldest['bf_pct']) or 0)
|
||||
|
||||
oldest_fm = oldest['weight'] * (oldest['bf_pct'] / 100)
|
||||
oldest_lbm = oldest['weight'] - oldest_fm
|
||||
recent_fm = rw * (ob / 100)
|
||||
recent_lbm = rw - recent_fm
|
||||
|
||||
oldest_fm = ow * (obf / 100)
|
||||
oldest_lbm = ow - oldest_fm
|
||||
|
||||
if metric == 'fm':
|
||||
change = recent_fm - oldest_fm
|
||||
else:
|
||||
change = recent_lbm - oldest_lbm
|
||||
|
||||
return round(change, 2)
|
||||
return round(float(change), 2)
|
||||
|
||||
|
||||
# ── Circumference Calculations ──────────────────────────────────────────────
|
||||
@@ -731,9 +744,9 @@ def calculate_body_progress_score(profile_id: str, focus_weights: Optional[Dict]
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
weight_loss = focus_weights.get('weight_loss', 0)
|
||||
muscle_gain = focus_weights.get('muscle_gain', 0)
|
||||
body_recomp = focus_weights.get('body_recomposition', 0)
|
||||
weight_loss = float(focus_weights.get('weight_loss', 0) or 0)
|
||||
muscle_gain = float(focus_weights.get('muscle_gain', 0) or 0)
|
||||
body_recomp = float(focus_weights.get('body_recomposition', 0) or 0)
|
||||
|
||||
total_body_weight = weight_loss + muscle_gain + body_recomp
|
||||
|
||||
|
||||
@@ -844,14 +844,16 @@ def calculate_nutrition_score(profile_id: str, focus_weights: Optional[Dict] = N
|
||||
from data_layer.scores import get_user_focus_weights
|
||||
focus_weights = get_user_focus_weights(profile_id)
|
||||
|
||||
# Nutrition-related focus areas (English keys from DB)
|
||||
protein_intake = focus_weights.get('protein_intake', 0)
|
||||
calorie_balance = focus_weights.get('calorie_balance', 0)
|
||||
macro_consistency = focus_weights.get('macro_consistency', 0)
|
||||
meal_timing = focus_weights.get('meal_timing', 0)
|
||||
hydration = focus_weights.get('hydration', 0)
|
||||
# Nutrition-related focus areas (English keys from DB; Gewichte immer float)
|
||||
protein_intake = float(focus_weights.get('protein_intake', 0) or 0)
|
||||
calorie_balance = float(focus_weights.get('calorie_balance', 0) or 0)
|
||||
macro_consistency = float(focus_weights.get('macro_consistency', 0) or 0)
|
||||
meal_timing = float(focus_weights.get('meal_timing', 0) or 0)
|
||||
hydration = float(focus_weights.get('hydration', 0) or 0)
|
||||
|
||||
total_nutrition_weight = protein_intake + calorie_balance + macro_consistency + meal_timing + hydration
|
||||
total_nutrition_weight = (
|
||||
protein_intake + calorie_balance + macro_consistency + meal_timing + hydration
|
||||
)
|
||||
|
||||
if total_nutrition_weight == 0:
|
||||
return None # No nutrition goals
|
||||
|
||||
@@ -224,8 +224,8 @@ def calculate_goal_progress_score(profile_id: str) -> Optional[int]:
|
||||
if total_weight == 0:
|
||||
return None
|
||||
|
||||
# Normalize to 0-100
|
||||
final_score = total_score / total_weight
|
||||
# Normalize to 0-100 (Explizit float: Zwischensummen können Decimal aus DB sein)
|
||||
final_score = float(total_score) / float(total_weight)
|
||||
|
||||
return int(final_score)
|
||||
|
||||
@@ -533,11 +533,19 @@ def calculate_focus_area_progress(profile_id: str, focus_area_id: str) -> Option
|
||||
if not goals:
|
||||
return None
|
||||
|
||||
# Weighted average by contribution_weight (Numeric → float)
|
||||
total_progress = sum(
|
||||
float(g['progress_pct']) * float(g['contribution_weight']) for g in goals
|
||||
)
|
||||
total_weight = sum(float(g['contribution_weight']) for g in goals)
|
||||
# Weighted average; progress_pct darf NULL sein (Ziele ohne quantitative Berechnung)
|
||||
parts: List[tuple] = []
|
||||
for g in goals:
|
||||
pct = g['progress_pct']
|
||||
if pct is None:
|
||||
continue
|
||||
parts.append((float(pct), float(g['contribution_weight'])))
|
||||
|
||||
if not parts:
|
||||
return None
|
||||
|
||||
total_progress = sum(p * w for p, w in parts)
|
||||
total_weight = sum(w for _, w in parts)
|
||||
|
||||
return int(total_progress / total_weight) if total_weight > 0 else None
|
||||
|
||||
|
||||
@@ -167,7 +167,8 @@ async def execute_prompt(
|
||||
prompt_slug: str,
|
||||
variables: Dict[str, Any],
|
||||
openrouter_call_func,
|
||||
enable_debug: bool = False
|
||||
enable_debug: bool = False,
|
||||
progress_callback = None # NEW: Optional callback für SSE Progress-Updates
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute a single prompt (base or pipeline type).
|
||||
@@ -217,7 +218,7 @@ async def execute_prompt(
|
||||
|
||||
elif prompt_type == 'workflow':
|
||||
# Workflow prompt: graph-based execution (Phase 0: Foundation)
|
||||
return await execute_workflow_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog)
|
||||
return await execute_workflow_prompt(prompt, variables, openrouter_call_func, enable_debug, catalog, progress_callback)
|
||||
|
||||
else:
|
||||
raise HTTPException(400, f"Unknown prompt type: {prompt_type}")
|
||||
@@ -278,7 +279,11 @@ async def execute_base_prompt(
|
||||
|
||||
if enable_debug:
|
||||
debug_info['template'] = template
|
||||
debug_info['final_prompt'] = prompt_text[:500] + ('...' if len(prompt_text) > 500 else '')
|
||||
# Volltext für Test-UI (Admin); sehr große Prompts nur weich begrenzen
|
||||
_max = 512 * 1024
|
||||
debug_info['final_prompt'] = (
|
||||
prompt_text if len(prompt_text) <= _max else prompt_text[:_max] + "\n… [gekürzt, >512KB]"
|
||||
)
|
||||
debug_info['available_variables'] = list(variables.keys())
|
||||
|
||||
# Call AI
|
||||
@@ -397,7 +402,10 @@ async def execute_pipeline_prompt(
|
||||
if enable_debug:
|
||||
prompt_debug['source'] = 'inline'
|
||||
prompt_debug['template'] = template
|
||||
prompt_debug['final_prompt'] = prompt_text[:500] + ('...' if len(prompt_text) > 500 else '')
|
||||
_max = 512 * 1024
|
||||
prompt_debug['final_prompt'] = (
|
||||
prompt_text if len(prompt_text) <= _max else prompt_text[:_max] + "\n… [gekürzt, >512KB]"
|
||||
)
|
||||
prompt_debug.update(placeholder_debug)
|
||||
|
||||
response = await openrouter_call_func(prompt_text)
|
||||
@@ -462,7 +470,8 @@ async def execute_prompt_with_data(
|
||||
modules: Optional[Dict[str, bool]] = None,
|
||||
timeframes: Optional[Dict[str, int]] = None,
|
||||
openrouter_call_func = None,
|
||||
enable_debug: bool = False
|
||||
enable_debug: bool = False,
|
||||
progress_callback = None # NEW: Optional callback für SSE Progress-Updates
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute prompt with data loaded from database.
|
||||
@@ -598,7 +607,7 @@ async def execute_prompt_with_data(
|
||||
variables['goals_data'] = []
|
||||
|
||||
# Execute prompt
|
||||
return await execute_prompt(prompt_slug, variables, openrouter_call_func, enable_debug)
|
||||
return await execute_prompt(prompt_slug, variables, openrouter_call_func, enable_debug, progress_callback)
|
||||
|
||||
|
||||
async def execute_workflow_prompt(
|
||||
@@ -606,7 +615,8 @@ async def execute_workflow_prompt(
|
||||
variables: Dict[str, Any],
|
||||
openrouter_call_func,
|
||||
enable_debug: bool = False,
|
||||
catalog: Optional[Dict] = None
|
||||
catalog: Optional[Dict] = None,
|
||||
progress_callback = None # NEW: Optional callback für SSE Progress-Updates
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute a workflow-type prompt (graph-based execution).
|
||||
@@ -645,7 +655,8 @@ async def execute_workflow_prompt(
|
||||
profile_id=variables.get('profile_id', 'unknown'), # From context
|
||||
variables=variables,
|
||||
openrouter_call_func=openrouter_call_func,
|
||||
enable_debug=enable_debug
|
||||
enable_debug=enable_debug,
|
||||
progress_callback=progress_callback # NEW: Progress-Callbacks durchreichen
|
||||
)
|
||||
|
||||
# Convert ExecutionResult to dict for API response
|
||||
|
||||
@@ -158,7 +158,8 @@ def parse_decision_questions(section_text: str) -> Dict[str, str]:
|
||||
for pattern in patterns:
|
||||
matches = re.finditer(pattern, section_text, re.MULTILINE | re.IGNORECASE)
|
||||
for match in matches:
|
||||
question_type = match.group(1).strip().lower()
|
||||
# Preserve original case for question IDs (e.g., "qAnalyst" not "qanalyst")
|
||||
question_type = match.group(1).strip()
|
||||
answer = match.group(2).strip()
|
||||
|
||||
# Entferne Klammern und Whitespace
|
||||
|
||||
@@ -699,6 +699,12 @@ def get_goals_grouped(session: dict = Depends(require_auth)):
|
||||
grouped[cat] = []
|
||||
|
||||
goal_dict = r2d(goal)
|
||||
# Keep in sync with GET /goals/list: derive current_value & progress from live data
|
||||
try:
|
||||
_update_goal_progress(conn, pid, goal_dict)
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Failed to update progress for goal {goal_dict.get('id')}: {e}")
|
||||
|
||||
goal_dict['focus_contributions'] = focus_map.get(goal['id'], [])
|
||||
grouped[cat].append(goal_dict)
|
||||
|
||||
|
||||
+224
-20
@@ -937,27 +937,60 @@ def export_placeholder_catalog_zip(
|
||||
|
||||
# ── KI-Assisted Prompt Engineering ───────────────────────────────────────────
|
||||
|
||||
async def call_openrouter(prompt: str, max_tokens: int = 1500) -> str:
|
||||
async def call_openrouter(prompt: str, max_tokens: int = 4096) -> str:
|
||||
"""Call OpenRouter API to get AI response."""
|
||||
if not OPENROUTER_KEY:
|
||||
raise HTTPException(status_code=500, detail="OpenRouter API key not configured")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||
json={
|
||||
"model": OPENROUTER_MODEL,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": max_tokens
|
||||
},
|
||||
timeout=60.0
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||
json={
|
||||
"model": OPENROUTER_MODEL,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": max_tokens
|
||||
},
|
||||
timeout=120.0
|
||||
)
|
||||
except httpx.TimeoutException as e:
|
||||
raise HTTPException(status_code=504, detail=f"OpenRouter-Zeitüberschreitung: {e}") from e
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter-Verbindungsfehler: {e}") from e
|
||||
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status_code,
|
||||
detail=f"OpenRouter API error ({resp.status_code}): {resp.text[:2000]}",
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=resp.status_code, detail=f"OpenRouter API error: {resp.text}")
|
||||
try:
|
||||
data = resp.json()
|
||||
except json.JSONDecodeError:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter lieferte kein JSON: {resp.text[:800]}",
|
||||
)
|
||||
|
||||
return resp.json()['choices'][0]['message']['content'].strip()
|
||||
choices = data.get("choices") or []
|
||||
if not choices:
|
||||
err_snip = json.dumps(data.get("error") or data, ensure_ascii=False)[:1200]
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter ohne choices in der Antwort: {err_snip}",
|
||||
)
|
||||
|
||||
message = choices[0].get("message") or {}
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="OpenRouter-Antwort ohne message.content (z. B. Tool-Calls oder abweichendes Schema).",
|
||||
)
|
||||
if not isinstance(content, str):
|
||||
content = str(content)
|
||||
return content.strip()
|
||||
|
||||
|
||||
def collect_example_data(profile_id: str, data_categories: list[str]) -> dict:
|
||||
@@ -1412,13 +1445,176 @@ from prompt_executor import execute_prompt_with_data
|
||||
from models import UnifiedPromptCreate, UnifiedPromptUpdate
|
||||
|
||||
|
||||
@router.post("/execute")
|
||||
async def execute_unified_prompt(
|
||||
prompt_slug: str,
|
||||
@router.post("/execute-stream")
|
||||
async def execute_unified_prompt_stream(
|
||||
prompt_slug: str = Query(..., description="Slug of prompt to execute"),
|
||||
token: Optional[str] = Query(None, description="Auth token (temporary solution for SSE)"),
|
||||
modules: Optional[dict] = None,
|
||||
timeframes: Optional[dict] = None,
|
||||
debug: bool = False,
|
||||
save: bool = False,
|
||||
debug: bool = Query(False, description="Include debug information (node_states, etc.)"),
|
||||
save: bool = Query(False, description="Save result to ai_insights")
|
||||
):
|
||||
"""
|
||||
Execute a unified prompt with Server-Sent Events (SSE) streaming.
|
||||
|
||||
Returns live progress updates during workflow execution:
|
||||
- execution_started: Workflow has begun
|
||||
- node_complete: Each node completes
|
||||
- execution_complete: Final result ready
|
||||
- execution_failed: Error occurred
|
||||
|
||||
Use this endpoint for long-running workflows (>30s) to avoid gateway timeouts.
|
||||
"""
|
||||
# Manual auth: verify token and get profile_id
|
||||
if not token:
|
||||
raise HTTPException(401, "Missing auth token")
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT profile_id FROM sessions WHERE token = %s", (token,))
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(401, "Invalid or expired token")
|
||||
profile_id = row['profile_id']
|
||||
|
||||
# Use default modules/timeframes if not provided
|
||||
if not modules:
|
||||
modules = {
|
||||
'körper': True,
|
||||
'ernährung': True,
|
||||
'training': True,
|
||||
'schlaf': True,
|
||||
'vitalwerte': True
|
||||
}
|
||||
|
||||
if not timeframes:
|
||||
timeframes = {
|
||||
'körper': 30,
|
||||
'ernährung': 30,
|
||||
'training': 14,
|
||||
'schlaf': 14,
|
||||
'vitalwerte': 7
|
||||
}
|
||||
|
||||
# Wrapper function for OpenRouter calls
|
||||
async def workflow_llm_call(prompt: str, model: str = None) -> str:
|
||||
return await call_openrouter(prompt)
|
||||
|
||||
# SSE Event Generator
|
||||
async def event_stream():
|
||||
"""Generate Server-Sent Events during workflow execution."""
|
||||
import asyncio
|
||||
from asyncio import Queue
|
||||
|
||||
# Event queue for progress updates
|
||||
event_queue = Queue()
|
||||
|
||||
# Flag to track execution completion
|
||||
execution_complete = False
|
||||
|
||||
# Define progress callback for streaming updates
|
||||
async def progress_callback(event_type: str, data: dict):
|
||||
"""Queue SSE event for streaming to client."""
|
||||
event_data = {
|
||||
"type": event_type,
|
||||
**data
|
||||
}
|
||||
await event_queue.put(event_data)
|
||||
|
||||
# Start workflow execution in background task
|
||||
async def execute_workflow_async():
|
||||
nonlocal execution_complete
|
||||
try:
|
||||
# Execute workflow with progress callbacks
|
||||
result = await execute_prompt_with_data(
|
||||
prompt_slug=prompt_slug,
|
||||
profile_id=profile_id,
|
||||
modules=modules,
|
||||
timeframes=timeframes,
|
||||
openrouter_call_func=workflow_llm_call,
|
||||
enable_debug=debug or save,
|
||||
progress_callback=progress_callback
|
||||
)
|
||||
|
||||
# Save to ai_insights if requested (same logic as /execute)
|
||||
if save:
|
||||
if result['type'] == 'pipeline':
|
||||
final_output = result.get('output', {})
|
||||
if isinstance(final_output, dict) and len(final_output) == 1:
|
||||
content = list(final_output.values())[0]
|
||||
else:
|
||||
content = json.dumps(final_output, ensure_ascii=False)
|
||||
elif result['type'] == 'workflow':
|
||||
content = _workflow_user_facing_content(result.get('aggregated_result'))
|
||||
else:
|
||||
content = result.get('output', '')
|
||||
if isinstance(content, dict):
|
||||
content = json.dumps(content, ensure_ascii=False)
|
||||
|
||||
# Save to database (minimal metadata for now)
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"""INSERT INTO ai_insights (profile_id, scope, content, metadata, created)
|
||||
VALUES (%s, %s, %s, %s, CURRENT_TIMESTAMP)""",
|
||||
(profile_id, prompt_slug, content, json.dumps({"prompt_type": result['type']}))
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
except Exception as e:
|
||||
# Queue error event
|
||||
await event_queue.put({
|
||||
"type": "execution_failed",
|
||||
"error": str(e)
|
||||
})
|
||||
finally:
|
||||
execution_complete = True
|
||||
|
||||
# Start workflow execution in background
|
||||
import asyncio
|
||||
execution_task = asyncio.create_task(execute_workflow_async())
|
||||
|
||||
# Stream events from queue
|
||||
try:
|
||||
while not execution_complete or not event_queue.empty():
|
||||
try:
|
||||
# Wait for event with timeout
|
||||
event = await asyncio.wait_for(event_queue.get(), timeout=0.5)
|
||||
yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
except asyncio.TimeoutError:
|
||||
# Send keepalive ping
|
||||
yield f": keepalive\n\n"
|
||||
continue
|
||||
|
||||
# Wait for execution task to complete
|
||||
await execution_task
|
||||
|
||||
except Exception as e:
|
||||
# Send final error event
|
||||
error_event = {
|
||||
"type": "execution_failed",
|
||||
"error": str(e)
|
||||
}
|
||||
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no" # Disable nginx buffering
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.post("/execute")
|
||||
async def execute_unified_prompt(
|
||||
prompt_slug: str = Query(..., description="Slug of prompt to execute"),
|
||||
modules: Optional[dict] = None,
|
||||
timeframes: Optional[dict] = None,
|
||||
debug: bool = Query(False, description="Include debug information (node_states, etc.)"),
|
||||
save: bool = Query(False, description="Save result to ai_insights"),
|
||||
session: dict = Depends(require_auth)
|
||||
):
|
||||
"""
|
||||
@@ -1455,6 +1651,14 @@ async def execute_unified_prompt(
|
||||
'vitalwerte': 7
|
||||
}
|
||||
|
||||
# Wrapper function to match workflow_executor's expected signature: (prompt, model) -> str
|
||||
# workflow_executor calls: openrouter_call_func(prompt, "anthropic/claude-sonnet-4")
|
||||
# but call_openrouter expects: call_openrouter(prompt, max_tokens=4096)
|
||||
async def workflow_llm_call(prompt: str, model: str = None) -> str:
|
||||
# Ignore model parameter (already set in OPENROUTER_MODEL env var)
|
||||
# Use default max_tokens=4096 from call_openrouter
|
||||
return await call_openrouter(prompt)
|
||||
|
||||
# Execute with prompt_executor
|
||||
# Always enable debug when saving to collect metadata for value table
|
||||
result = await execute_prompt_with_data(
|
||||
@@ -1462,7 +1666,7 @@ async def execute_unified_prompt(
|
||||
profile_id=profile_id,
|
||||
modules=modules,
|
||||
timeframes=timeframes,
|
||||
openrouter_call_func=call_openrouter,
|
||||
openrouter_call_func=workflow_llm_call, # Use wrapper with correct signature
|
||||
enable_debug=debug or save # Enable debug if saving for metadata collection
|
||||
)
|
||||
|
||||
|
||||
@@ -86,11 +86,19 @@ async def execute_workflow_endpoint(
|
||||
"type": "workflow"
|
||||
}
|
||||
|
||||
# Wrapper function to match workflow_executor's expected signature: (prompt, model) -> str
|
||||
# workflow_executor calls: openrouter_call_func(prompt, "anthropic/claude-sonnet-4")
|
||||
# but call_openrouter expects: call_openrouter(prompt, max_tokens=4096)
|
||||
async def workflow_llm_call(prompt: str, model: str) -> str:
|
||||
# Ignore model parameter (already set in OPENROUTER_MODEL env var)
|
||||
# Use default max_tokens=4096 from call_openrouter
|
||||
return await call_openrouter(prompt)
|
||||
|
||||
try:
|
||||
result = await execute_workflow_prompt(
|
||||
prompt=workflow_prompt,
|
||||
variables=variables,
|
||||
openrouter_call_func=call_openrouter,
|
||||
openrouter_call_func=workflow_llm_call, # Use wrapper with correct signature
|
||||
enable_debug=request.enable_debug
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -81,6 +81,25 @@ def test_convert_kcal_via_source_unit_kj():
|
||||
assert abs(k - 1000.0) < 0.05
|
||||
|
||||
|
||||
def test_apple_health_long_decimal_dot_preserved():
|
||||
"""Apple: Mittel-HF u. Energie mit vielen Nachkommastellen; Punkt ist Dezimaltrenner."""
|
||||
hr_spec = {"type": "int", "flexible": True}
|
||||
r = convert_value("96.8749374730629", "hr_avg", hr_spec, module="activity")
|
||||
assert r == 97
|
||||
|
||||
rest_spec = {"type": "float", "decimal_separator": ".", "flexible": True, "source_unit": "kj"}
|
||||
kcal = convert_value("596.6689047323086", "kcal_resting", rest_spec, module="activity")
|
||||
assert 140.0 < kcal < 145.0
|
||||
|
||||
|
||||
def test_parse_float_auto_us_thousands_comma():
|
||||
"""«12,345» ohne Dezimalpunkt weiter als Tausender möglich."""
|
||||
v = convert_value("12345", "x", {"type": "float", "decimal_separator": "auto"})
|
||||
assert v == 12345.0
|
||||
v2 = convert_value("12,345", "x", {"type": "float", "decimal_separator": "auto"})
|
||||
assert abs(v2 - 12345.0) < 0.01
|
||||
|
||||
|
||||
def test_convert_protein_kg_to_g():
|
||||
spec = {"type": "float", "source_unit": "kg", "decimal_separator": "."}
|
||||
g = convert_value("0.1", "protein_g", spec, module="nutrition")
|
||||
|
||||
+138
-11
@@ -42,7 +42,8 @@ async def execute_workflow(
|
||||
profile_id: str = None,
|
||||
variables: Dict[str, Any] = None,
|
||||
openrouter_call_func = None, # Callback für LLM-Calls: async (prompt, model) -> str
|
||||
enable_debug: bool = False
|
||||
enable_debug: bool = False,
|
||||
progress_callback = None # NEW: Optional callback für Progress-Updates: async (event_type, data) -> None
|
||||
) -> ExecutionResult:
|
||||
"""
|
||||
Führt einen Workflow aus (mit conditional branching und path consolidation).
|
||||
@@ -76,6 +77,13 @@ async def execute_workflow(
|
||||
|
||||
logger.info(f"Starting workflow execution: {execution_id}")
|
||||
|
||||
# NEW: Progress-Callback für Start
|
||||
if progress_callback:
|
||||
await progress_callback("execution_started", {
|
||||
"execution_id": execution_id,
|
||||
"started_at": started_at
|
||||
})
|
||||
|
||||
try:
|
||||
# 1. Lade Workflow-Definition
|
||||
if graph_data:
|
||||
@@ -158,9 +166,29 @@ async def execute_workflow(
|
||||
enable_debug=enable_debug
|
||||
)
|
||||
|
||||
# Add human-readable label to node_state for debug UI
|
||||
# Priority: node.label (user-defined) > prompt_slug > node_type-id
|
||||
node_label = node.label if hasattr(node, 'label') and node.label else (
|
||||
node.prompt_slug if hasattr(node, 'prompt_slug') and node.prompt_slug else f"{node.type.value}-{node_id[:8]}"
|
||||
)
|
||||
if not node_state.debug_prompt_slug:
|
||||
node_state.debug_prompt_slug = node_label
|
||||
|
||||
node_states.append(node_state)
|
||||
context["node_results"][node_id] = node_state
|
||||
|
||||
# NEW: Progress-Callback aufrufen (für SSE Streaming)
|
||||
if progress_callback:
|
||||
await progress_callback("node_complete", {
|
||||
"node_id": node_id,
|
||||
"node_type": node.type,
|
||||
"node_label": node_label,
|
||||
"status": node_state.status.value,
|
||||
"total_nodes": len(graph.nodes),
|
||||
"completed_nodes": len([ns for ns in node_states if ns.status in [NodeStatus.EXECUTED, NodeStatus.SKIPPED]]),
|
||||
"error": node_state.error if node_state.status == NodeStatus.FAILED else None
|
||||
})
|
||||
|
||||
# Füge Nachfolger zur Queue hinzu
|
||||
outgoing_edges = [e for e in graph.edges if e.from_node == node_id]
|
||||
for edge in outgoing_edges:
|
||||
@@ -185,6 +213,19 @@ async def execute_workflow(
|
||||
|
||||
logger.info(f"Workflow execution completed: {execution_id}")
|
||||
|
||||
# NEW: Progress-Callback für erfolgreiche Fertigstellung
|
||||
if progress_callback:
|
||||
await progress_callback("execution_complete", {
|
||||
"execution_id": execution_id,
|
||||
"status": "completed",
|
||||
"aggregated_result": aggregated,
|
||||
"total_nodes": len(node_states),
|
||||
"completed_nodes": len([ns for ns in node_states if ns.status == NodeStatus.EXECUTED]),
|
||||
"skipped_nodes": len([ns for ns in node_states if ns.status == NodeStatus.SKIPPED]),
|
||||
"failed_nodes": len([ns for ns in node_states if ns.status == NodeStatus.FAILED]),
|
||||
"completed_at": completed_at
|
||||
})
|
||||
|
||||
return ExecutionResult(
|
||||
execution_id=execution_id,
|
||||
workflow_id=workflow_id or "N/A", # Placeholder when graph_data is used directly
|
||||
@@ -198,6 +239,15 @@ async def execute_workflow(
|
||||
except Exception as e:
|
||||
logger.error(f"Workflow execution failed: {e}", exc_info=True)
|
||||
|
||||
# NEW: Progress-Callback für Fehler
|
||||
if progress_callback:
|
||||
await progress_callback("execution_failed", {
|
||||
"execution_id": execution_id,
|
||||
"status": "failed",
|
||||
"error": str(e),
|
||||
"completed_at": datetime.utcnow().isoformat()
|
||||
})
|
||||
|
||||
# Speichere Failed State
|
||||
completed_at = datetime.utcnow().isoformat()
|
||||
save_execution_state(
|
||||
@@ -270,11 +320,11 @@ async def execute_node(
|
||||
|
||||
# Logic Nodes (Phase 3)
|
||||
if node.type == "logic":
|
||||
return execute_logic_node(node, context, graph)
|
||||
return execute_logic_node(node, context, graph, enable_debug)
|
||||
|
||||
# Join Nodes (Phase 4)
|
||||
if node.type == "join":
|
||||
return execute_join_node(node, context, graph)
|
||||
return execute_join_node(node, context, graph, enable_debug)
|
||||
|
||||
# Analysis Nodes
|
||||
if node.type == "analysis":
|
||||
@@ -354,6 +404,11 @@ async def execute_node(
|
||||
decision_signals=parsed["decision_signals"],
|
||||
normalized_signals=normalized_signals,
|
||||
reasoning_anchors=parsed.get("reasoning_anchors"),
|
||||
# Debug information (nur wenn enable_debug=True)
|
||||
debug_prompt=augmented_prompt if enable_debug else None,
|
||||
debug_raw_response=llm_response if enable_debug else None,
|
||||
debug_node_type="analysis",
|
||||
debug_prompt_slug=node.prompt_slug if enable_debug else None,
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
@@ -375,7 +430,8 @@ async def execute_node(
|
||||
def execute_logic_node(
|
||||
node,
|
||||
context: Dict[str, Any],
|
||||
graph: WorkflowGraph
|
||||
graph: WorkflowGraph,
|
||||
enable_debug: bool = False
|
||||
) -> NodeExecutionState:
|
||||
"""
|
||||
Führt Logic Node aus (Phase 3).
|
||||
@@ -399,10 +455,49 @@ def execute_logic_node(
|
||||
|
||||
try:
|
||||
if not node.condition:
|
||||
raise ValueError(f"Logic node {node.id} has no condition")
|
||||
error_msg = f"Logic node {node.id} has no condition defined"
|
||||
logger.error(error_msg)
|
||||
return NodeExecutionState(
|
||||
node_id=node.id,
|
||||
status=NodeStatus.FAILED,
|
||||
error=error_msg,
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
|
||||
# Handle both formats (thanks to Union[LogicExpression, Condition] type):
|
||||
# 1. Direct LogicExpression (UI format): node.condition is LogicExpression
|
||||
# 2. Wrapped in Condition (legacy): node.condition is Condition with .expression
|
||||
from workflow_models import LogicExpression, Condition
|
||||
|
||||
expression = None
|
||||
|
||||
if isinstance(node.condition, LogicExpression):
|
||||
# UI format: direct LogicExpression
|
||||
expression = node.condition
|
||||
elif isinstance(node.condition, Condition):
|
||||
# Legacy format: wrapped in Condition
|
||||
expression = node.condition.expression
|
||||
else:
|
||||
# Fallback: try to detect format manually
|
||||
if hasattr(node.condition, 'operator') and hasattr(node.condition, 'operands'):
|
||||
expression = node.condition # Looks like LogicExpression
|
||||
elif hasattr(node.condition, 'expression'):
|
||||
expression = node.condition.expression # Looks like Condition
|
||||
|
||||
if expression is None:
|
||||
error_msg = f"Logic node {node.id} has no valid condition/expression defined"
|
||||
logger.error(error_msg)
|
||||
return NodeExecutionState(
|
||||
node_id=node.id,
|
||||
status=NodeStatus.FAILED,
|
||||
error=error_msg,
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
)
|
||||
|
||||
# 1. Evaluiere Bedingung
|
||||
result, error = evaluate_logic_expression(node.condition.expression, context)
|
||||
result, error = evaluate_logic_expression(expression, context)
|
||||
|
||||
if error:
|
||||
# Fehler bei Evaluation → Fallback anwenden
|
||||
@@ -436,7 +531,15 @@ def execute_logic_node(
|
||||
"evaluation_result": result if not error else None,
|
||||
"error": error,
|
||||
"activated_edges": activated_edges
|
||||
})
|
||||
}),
|
||||
# Debug information
|
||||
debug_prompt=json.dumps(expression.model_dump() if hasattr(expression, 'model_dump') else str(expression), ensure_ascii=False) if enable_debug and expression else None,
|
||||
debug_raw_response=json.dumps({
|
||||
"result": result,
|
||||
"error": error,
|
||||
"activated_edges": activated_edges
|
||||
}, ensure_ascii=False) if enable_debug else None,
|
||||
debug_node_type="logic"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -453,7 +556,8 @@ def execute_logic_node(
|
||||
def execute_join_node(
|
||||
node,
|
||||
context: Dict[str, Any],
|
||||
graph: WorkflowGraph
|
||||
graph: WorkflowGraph,
|
||||
enable_debug: bool = False
|
||||
) -> NodeExecutionState:
|
||||
"""
|
||||
Führt Join Node aus (Phase 4).
|
||||
@@ -525,7 +629,16 @@ def execute_join_node(
|
||||
normalized_signals=consolidated_signals_list,
|
||||
metadata=join_result.metadata,
|
||||
started_at=started_at,
|
||||
completed_at=datetime.utcnow().isoformat()
|
||||
completed_at=datetime.utcnow().isoformat(),
|
||||
# Debug information
|
||||
debug_prompt=f"Join Strategy: {node.join_strategy.value if node.join_strategy else 'wait_all'}\nPaths: {total_count}\nMinimum Required: {node.min_paths if node.min_paths else 'all'}" if enable_debug else None,
|
||||
debug_raw_response=json.dumps({
|
||||
"executed_paths": executed_count,
|
||||
"total_paths": total_count,
|
||||
"strategy": node.join_strategy.value if node.join_strategy else 'wait_all',
|
||||
"consolidated_nodes": list(join_result.consolidated_analysis_core.keys())
|
||||
}, ensure_ascii=False) if enable_debug else None,
|
||||
debug_node_type="join"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -777,17 +890,31 @@ def _get_edges_by_label(node_id: str, label: str, graph: WorkflowGraph) -> List[
|
||||
"""
|
||||
Findet alle ausgehenden Edges mit bestimmtem Label.
|
||||
|
||||
Unterstützt beide Formate:
|
||||
- Legacy: e.label == label (z.B. "then", "else")
|
||||
- UI: e.source_handle == label (z.B. "true", "false")
|
||||
|
||||
Args:
|
||||
node_id: Node-ID
|
||||
label: Edge-Label (z.B. "then", "else", "uncertainty")
|
||||
label: Edge-Label oder sourceHandle (z.B. "then"/"true", "else"/"false")
|
||||
graph: WorkflowGraph
|
||||
|
||||
Returns:
|
||||
Liste von Edge-IDs
|
||||
"""
|
||||
# Map label to sourceHandle equivalents
|
||||
label_to_handle = {
|
||||
"then": "true",
|
||||
"else": "false"
|
||||
}
|
||||
handle_equivalent = label_to_handle.get(label, label)
|
||||
|
||||
matching_edges = [
|
||||
e.id for e in graph.edges
|
||||
if e.from_node == node_id and e.label == label
|
||||
if e.from_node == node_id and (
|
||||
e.label == label or # Legacy format
|
||||
(hasattr(e, 'source_handle') and e.source_handle == handle_equivalent) # UI format
|
||||
)
|
||||
]
|
||||
return matching_edges
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ Data validation schemas for Workflow-Graph, Knoten, Kanten, Bedingungen.
|
||||
Konzept-Basis: konzept_workflow_engine_konsolidated.md
|
||||
Anforderungsanalyse: anforderungsanalyse_umsetzungsplan.md
|
||||
"""
|
||||
from typing import Optional, List, Dict, Any
|
||||
from typing import Optional, List, Dict, Any, Union
|
||||
from pydantic import BaseModel, Field
|
||||
from enum import Enum
|
||||
|
||||
@@ -148,18 +148,27 @@ class LogicExpression(BaseModel):
|
||||
}
|
||||
"""
|
||||
operator: LogicOperator = Field(..., description="Logischer Operator (and, or, not) oder Vergleichsoperator")
|
||||
operands: Optional[List[Any]] = Field(None, description="Liste von Operanden (LogicOperand oder verschachtelte LogicExpression)")
|
||||
operands: Optional[List['LogicExpression']] = Field(None, description="Liste von Operanden (LogicOperand oder verschachtelte LogicExpression)")
|
||||
# Bei einfachem Vergleich:
|
||||
ref: Optional[str] = Field(None, description="Signal-Referenz (nur bei Vergleichsoperatoren)")
|
||||
value: Optional[Any] = Field(None, description="Vergleichswert (nur bei Vergleichsoperatoren)")
|
||||
|
||||
# Enable forward reference resolution for recursive model
|
||||
LogicExpression.model_rebuild()
|
||||
|
||||
|
||||
class Condition(BaseModel):
|
||||
"""
|
||||
Bedingung für einen Logik-Knoten.
|
||||
|
||||
Unterstützt if/else-if/else-Logik.
|
||||
|
||||
Note: Uses extra='forbid' to ensure proper Union resolution with LogicExpression.
|
||||
If unknown fields are present (like 'operator', 'operands'), deserialization fails
|
||||
and Pydantic tries LogicExpression instead.
|
||||
"""
|
||||
model_config = {'extra': 'forbid'}
|
||||
|
||||
type: str = Field(default="if", description="Bedingungstyp: if, else-if, else")
|
||||
expression: Optional[LogicExpression] = Field(None, description="Logischer Ausdruck (null bei 'else')")
|
||||
then_path: Optional[str] = Field(None, description="Edge-ID für 'then'-Pfad")
|
||||
@@ -187,6 +196,7 @@ class WorkflowNode(BaseModel):
|
||||
"""
|
||||
id: str = Field(..., description="Eindeutige Knoten-ID")
|
||||
type: NodeType = Field(..., description="Knotentyp")
|
||||
label: Optional[str] = Field(None, description="Node-Label (vom Editor, z.B. 'Qualitätseinschätzung')")
|
||||
position: Optional[Position] = Field(None, description="Position im visuellen Editor")
|
||||
|
||||
# ANALYSIS-Knoten
|
||||
@@ -195,7 +205,8 @@ class WorkflowNode(BaseModel):
|
||||
question_augmentations: Optional[List[QuestionAugmentation]] = Field(None, description="Fragenergänzungen (knotengebunden, überschreiben Prompt-Defaults)")
|
||||
|
||||
# LOGIC-Knoten
|
||||
condition: Optional[Condition] = Field(None, description="Bedingung für Pfad-Routing")
|
||||
# Support both formats: direct LogicExpression (UI) or wrapped in Condition (legacy)
|
||||
condition: Optional[Union[LogicExpression, Condition]] = Field(None, description="Bedingung für Pfad-Routing")
|
||||
fallback: Optional[FallbackConfig] = Field(None, description="Fallback-Konfiguration")
|
||||
|
||||
# JOIN-Knoten (Phase 4)
|
||||
@@ -220,6 +231,10 @@ class WorkflowEdge(BaseModel):
|
||||
to_node: str = Field(..., alias="to", description="Ziel-Knoten-ID")
|
||||
label: Optional[str] = Field(None, description="Label für visuelle Darstellung (z.B. 'then', 'else')")
|
||||
|
||||
# UI-Format fields (React Flow)
|
||||
source_handle: Optional[str] = Field(None, alias="sourceHandle", description="Source handle ID (UI format: 'true', 'false', 'out')")
|
||||
target_handle: Optional[str] = Field(None, alias="targetHandle", description="Target handle ID (UI format: 'in', 'path_1', etc.)")
|
||||
|
||||
|
||||
class WorkflowGraph(BaseModel):
|
||||
"""
|
||||
@@ -335,6 +350,15 @@ class NodeExecutionState(BaseModel):
|
||||
normalized_signals: List[NormalizedSignal] = Field(default_factory=list, description="Normalisierte Signale (Phase 2)")
|
||||
reasoning_anchors: Optional[str] = Field(None, description="Begründungsanker aus ## Begründung")
|
||||
|
||||
# Debug Information (nur wenn enable_debug=True)
|
||||
debug_prompt: Optional[str] = Field(None, description="Vollständiger Prompt der an die KI gesendet wurde")
|
||||
debug_raw_response: Optional[str] = Field(None, description="Rohe KI-Antwort (ungeparst)")
|
||||
debug_node_type: Optional[str] = Field(None, description="Node-Typ (analysis, logic, join, etc.)")
|
||||
debug_prompt_slug: Optional[str] = Field(None, description="Verwendeter Prompt-Slug (bei ANALYSIS nodes)")
|
||||
|
||||
# Metadata (für Join Nodes und andere Zusatzinfos)
|
||||
metadata: Optional[Dict[str, Any]] = Field(None, description="Zusätzliche Metadaten (z.B. Join-Statistiken)")
|
||||
|
||||
# Error & Timing
|
||||
error: Optional[str] = Field(None, description="Fehlermeldung bei failed")
|
||||
started_at: Optional[str] = Field(None, description="Start-Timestamp (ISO)")
|
||||
|
||||
@@ -29,6 +29,7 @@ Dieser Ordner ist **immer mit Git versioniert**. Er ergänzt **`.claude/docs/`**
|
||||
| `issue-53-phase-0c-multi-layer-architecture.md` |
|
||||
| `issue-54-dynamic-placeholder-system.md` |
|
||||
| `issue-55-dynamic-aggregation-methods.md` |
|
||||
| `issue-76-training-quality-goal-list-filter.md` |
|
||||
| `PHASE_PLAN_RESPONSIVE_UI.md` |
|
||||
| `REVIEW_OPEN_ISSUES_2026-04-04.md` |
|
||||
| `UMSETZUNGSPLAN_TRAININGSPROFILE_SPORTSPEZIFISCH_2026-04-05.md` |
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Issue #76: Trainings-Qualität – Zielbezug + Listen-Filter
|
||||
|
||||
**Gitea:** http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/76
|
||||
**Status:** OFFEN
|
||||
**Erstellt:** 11.04.2026
|
||||
**Typ:** Enhancement (Backend, Frontend, Produkt)
|
||||
**Verwandt:** #31 (globaler Quality-Filter), #15 (Quality-Filter KI/Charts – historisch)
|
||||
|
||||
---
|
||||
|
||||
## Kurzfassung
|
||||
|
||||
Die heutige **`quality_label` / `quality_filter_level`**-Logik soll überdacht werden: nicht nur **Akzeptanz** (formales Label), sondern langfristig **Nutzen für die Zielerreichung**. Parallel: der **globale Profil-Filter** in der **Aktivitätsliste** versteckt u. a. **fehlende Einstufungen** (`NULL`) – das erschwert Datenpflege und Transparenz.
|
||||
|
||||
---
|
||||
|
||||
## Ist-Zustand (technisch)
|
||||
|
||||
| Bereich | Filter nach `quality_filter_level`? |
|
||||
|---------|--------------------------------------|
|
||||
| `GET` Aktivitätsliste (`routers/activity.py`) | Ja (`get_quality_filter_sql`) |
|
||||
| KI-Rohkontext (`routers/insights.py`, `_get_profile_data`) | Ja (letzte 90 Zeilen `activity_log`) |
|
||||
| Data-Layer / Platzhalter / Chart-Aggregate (`data_layer/activity_metrics.py`) | Nein – alle Einträge im Zeitfenster |
|
||||
|
||||
Bei Stufen ≠ `all` schließt SQL-`IN` typischerweise **`NULL`** und nicht erlaubte Labels aus.
|
||||
|
||||
---
|
||||
|
||||
## Ziele
|
||||
|
||||
1. **Konzept „Qualität“:** Richtung Ziel-/Focus-/Phasenbezug; Umsetzung kann in Folge-Issues zerlegt werden.
|
||||
2. **Listendarstellung:** Standard soll **alle** relevanten Einträge zeigen; **optionale lokale** Filter (inkl. „ohne Einstufung“), kein unbemerktes globales Ausblenden.
|
||||
3. **KI/Insights:** Klarstellen, ob gefilterte vs. vollständige Aktivitätsmenge; ggf. konfigurierbar oder im Prompt kenntlich.
|
||||
4. **Dokumentation:** Kurz festhalten, wo `get_quality_filter_sql` greift und wie das zu den Aggregationen passt.
|
||||
|
||||
---
|
||||
|
||||
## Code-Referenzen
|
||||
|
||||
- `backend/quality_filter.py`
|
||||
- `backend/routers/activity.py` (`list_activity`)
|
||||
- `backend/routers/insights.py` (`_get_profile_data`)
|
||||
- `backend/data_layer/activity_metrics.py`
|
||||
|
||||
---
|
||||
|
||||
## Akzeptanz (aus Gitea, Checkliste)
|
||||
|
||||
Siehe Issue-Body in Gitea #76; bei Umsetzung dort Häkchen setzen und diese Datei ggf. um **Umsetzungsnotizen / Abnahme** ergänzen.
|
||||
@@ -1,7 +1,264 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useState, useEffect, useRef, useLayoutEffect } from 'react'
|
||||
import { api } from '../utils/api'
|
||||
import { X, Plus, Trash2, MoveUp, MoveDown, Code } from 'lucide-react'
|
||||
import PlaceholderPicker from './PlaceholderPicker'
|
||||
import Markdown from '../utils/Markdown'
|
||||
|
||||
/** Debug aus erfolgreicher Ausführung oder aus FastAPI-Fehlerdetail */
|
||||
function extractExecutionDebug(testResult) {
|
||||
if (!testResult) return null
|
||||
const raw = testResult.debug ?? testResult
|
||||
if (raw && typeof raw === 'object' && raw.detail && raw.detail.debug) {
|
||||
return { ...raw.detail.debug, ...raw.detail }
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
/** Vollständiger Prompt-Text für die Anzeige (Basis oder Pipeline-Stufen) */
|
||||
function buildPromptTextForDisplay(testResult) {
|
||||
if (!testResult || testResult.error) return ''
|
||||
const dbg = extractExecutionDebug(testResult)
|
||||
const t = testResult.type
|
||||
if (t === 'base' && dbg?.final_prompt) return dbg.final_prompt
|
||||
if (t === 'pipeline' && dbg?.stages?.length) {
|
||||
const parts = []
|
||||
for (const st of dbg.stages) {
|
||||
for (const p of st.prompts || []) {
|
||||
const label =
|
||||
p.source === 'reference'
|
||||
? `Stage ${st.stage} · Ref: ${p.ref_slug || '?'}`
|
||||
: `Stage ${st.stage} · Inline`
|
||||
const text =
|
||||
p.final_prompt ||
|
||||
(p.ref_debug && typeof p.ref_debug === 'object' ? p.ref_debug.final_prompt : '') ||
|
||||
''
|
||||
if (text) parts.push(`── ${label} ──\n${text}`)
|
||||
}
|
||||
}
|
||||
return parts.join('\n\n')
|
||||
}
|
||||
return dbg?.final_prompt || ''
|
||||
}
|
||||
|
||||
function sanitizeDebugForPanel(dbg, resultType) {
|
||||
if (!dbg) return {}
|
||||
const o = { ...dbg }
|
||||
delete o.final_prompt
|
||||
delete o.template
|
||||
delete o.ai_response_preview
|
||||
if (o.stages && resultType === 'pipeline') {
|
||||
o.stages = o.stages.map((s) => ({
|
||||
stage: s.stage,
|
||||
available_variables: s.available_variables,
|
||||
output: s.output,
|
||||
prompts: (s.prompts || []).map((p) => ({
|
||||
source: p.source,
|
||||
ref_slug: p.ref_slug,
|
||||
output_key: p.output_key,
|
||||
context_var_key: p.context_var_key,
|
||||
resolved_placeholders: p.resolved_placeholders || p.ref_debug?.resolved_placeholders,
|
||||
unresolved_placeholders: p.unresolved_placeholders || p.ref_debug?.unresolved_placeholders,
|
||||
warnings: p.warnings || p.ref_debug?.warnings,
|
||||
ai_response_length: p.ai_response_length
|
||||
}))
|
||||
}))
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
/** Langer Inhalt: zunächst auf maxRem eingeklappt, „Mehr/Weniger anzeigen“ */
|
||||
function ExpandableCollapsible({ children, contentKey, maxRem = 28 }) {
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const wrapRef = useRef(null)
|
||||
const [showToggle, setShowToggle] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
setExpanded(false)
|
||||
}, [contentKey])
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = wrapRef.current
|
||||
if (!el) return
|
||||
if (expanded) {
|
||||
setShowToggle(true)
|
||||
return
|
||||
}
|
||||
setShowToggle(el.scrollHeight > el.clientHeight + 2)
|
||||
}, [contentKey, expanded])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
ref={wrapRef}
|
||||
style={{
|
||||
maxHeight: expanded ? 'none' : `${maxRem}rem`,
|
||||
overflow: expanded ? 'visible' : 'hidden'
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
{showToggle && (
|
||||
<div style={{ marginTop: 10, textAlign: 'center' }}>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
style={{ fontSize: 12, padding: '6px 14px' }}
|
||||
onClick={() => setExpanded((e) => !e)}
|
||||
>
|
||||
{expanded ? 'Weniger anzeigen' : 'Mehr anzeigen'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function renderTestOutput(testResult) {
|
||||
if (!testResult) return null
|
||||
if (testResult.error) {
|
||||
const d = testResult.debug?.detail
|
||||
const msg =
|
||||
typeof d === 'string'
|
||||
? d
|
||||
: d?.error || d?.message || testResult.error_message || 'Unbekannter Fehler'
|
||||
return (
|
||||
<div style={{ color: 'var(--danger)', fontSize: 14, lineHeight: 1.5 }}>
|
||||
{typeof msg === 'string' ? msg : JSON.stringify(msg, null, 2)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const out = testResult.output
|
||||
const fmt = testResult.output_format
|
||||
const typ = testResult.type
|
||||
|
||||
if (out == null) {
|
||||
return <span style={{ color: 'var(--text3)' }}>Keine Ausgabe</span>
|
||||
}
|
||||
|
||||
const proseBox = (content, contentKey) => (
|
||||
<div
|
||||
style={{
|
||||
padding: 16,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
fontSize: 14,
|
||||
lineHeight: 1.55,
|
||||
color: 'var(--text1)',
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{contentKey != null ? (
|
||||
<ExpandableCollapsible contentKey={contentKey}>{content}</ExpandableCollapsible>
|
||||
) : (
|
||||
content
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
if (typ === 'pipeline' && out && typeof out === 'object' && !Array.isArray(out)) {
|
||||
return (
|
||||
<div style={{ display: 'grid', gap: 16 }}>
|
||||
{Object.entries(out).map(([key, val]) => (
|
||||
<div key={key}>
|
||||
<div
|
||||
style={{
|
||||
fontSize: 12,
|
||||
fontWeight: 600,
|
||||
color: 'var(--text2)',
|
||||
marginBottom: 8,
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{key}
|
||||
</div>
|
||||
{typeof val === 'string' ? (
|
||||
proseBox(
|
||||
<Markdown text={val} />,
|
||||
`pipe-${key}-${val.length}-${val.slice(0, 120)}`
|
||||
)
|
||||
) : (
|
||||
<ExpandableCollapsible contentKey={`pipe-json-${key}-${JSON.stringify(val).slice(0, 200)}`} maxRem={22}>
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 12,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
fontSize: 12,
|
||||
overflow: 'auto',
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{JSON.stringify(val, null, 2)}
|
||||
</pre>
|
||||
</ExpandableCollapsible>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (typeof out === 'string') {
|
||||
if (fmt === 'json') {
|
||||
try {
|
||||
const parsed = JSON.parse(out)
|
||||
const jsonStr = JSON.stringify(parsed, null, 2)
|
||||
return (
|
||||
<ExpandableCollapsible contentKey={`json-out-${jsonStr.length}-${jsonStr.slice(0, 80)}`} maxRem={26}>
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 12,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
fontSize: 12,
|
||||
overflow: 'auto',
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{jsonStr}
|
||||
</pre>
|
||||
</ExpandableCollapsible>
|
||||
)
|
||||
} catch {
|
||||
return proseBox(
|
||||
<pre style={{ margin: 0, whiteSpace: 'pre-wrap' }}>{out}</pre>,
|
||||
`json-fail-${out.length}-${out.slice(0, 80)}`
|
||||
)
|
||||
}
|
||||
}
|
||||
return proseBox(<Markdown text={out} />, `text-out-${out.length}-${out.slice(0, 120)}`)
|
||||
}
|
||||
|
||||
if (typeof out === 'object') {
|
||||
const jsonStr = JSON.stringify(out, null, 2)
|
||||
return (
|
||||
<ExpandableCollapsible contentKey={`obj-out-${jsonStr.length}-${jsonStr.slice(0, 120)}`} maxRem={26}>
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
padding: 12,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
fontSize: 12,
|
||||
overflow: 'auto',
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{jsonStr}
|
||||
</pre>
|
||||
</ExpandableCollapsible>
|
||||
)
|
||||
}
|
||||
|
||||
return <span>{String(out)}</span>
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified Prompt Editor Modal (Issue #28 Phase 3)
|
||||
@@ -47,6 +304,8 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
const [testing, setTesting] = useState(false)
|
||||
const [testResult, setTestResult] = useState(null)
|
||||
const [showDebug, setShowDebug] = useState(false)
|
||||
/** 'response' | 'prompt' | 'debug' */
|
||||
const [testResultTab, setTestResultTab] = useState('response')
|
||||
|
||||
useEffect(() => {
|
||||
loadAvailablePrompts()
|
||||
@@ -280,6 +539,7 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
try {
|
||||
const result = await api.executeUnifiedPrompt(prompt.slug, null, null, true)
|
||||
setTestResult(result)
|
||||
setTestResultTab('response')
|
||||
setShowDebug(true)
|
||||
} catch (e) {
|
||||
// Show error AND try to extract debug info from error
|
||||
@@ -290,7 +550,12 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
try {
|
||||
const parsed = JSON.parse(errorMsg)
|
||||
if (parsed.detail) {
|
||||
setError('Test-Fehler: ' + parsed.detail)
|
||||
const d = parsed.detail
|
||||
const msg =
|
||||
typeof d === 'string'
|
||||
? d
|
||||
: d.error || d.message || d.msg || JSON.stringify(d).slice(0, 500)
|
||||
setError('Test-Fehler: ' + msg)
|
||||
debugData = parsed
|
||||
} else {
|
||||
setError('Test-Fehler: ' + errorMsg)
|
||||
@@ -305,6 +570,7 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
error_message: errorMsg,
|
||||
debug: debugData || { error: errorMsg }
|
||||
})
|
||||
setTestResultTab('response')
|
||||
setShowDebug(true) // ALWAYS show debug on test, even on error
|
||||
} finally {
|
||||
setTesting(false)
|
||||
@@ -315,7 +581,12 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
if (!testResult) return
|
||||
|
||||
// Extract all placeholder data from test result
|
||||
const debug = testResult.debug || testResult
|
||||
const raw = testResult.debug || testResult
|
||||
// API-Fehler: FastAPI liefert { detail: { error, debug: { resolved_placeholders, ... } } }
|
||||
const debug =
|
||||
raw && typeof raw === 'object' && raw.detail && raw.detail.debug
|
||||
? { ...raw.detail.debug, ...raw.detail }
|
||||
: raw
|
||||
const exportData = {
|
||||
export_date: new Date().toISOString(),
|
||||
prompt_slug: prompt?.slug || 'unknown',
|
||||
@@ -711,7 +982,7 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Debug Output */}
|
||||
{/* Test-Ergebnis: Antwort · Prompt · Debug */}
|
||||
{showDebug && testResult && (
|
||||
<div style={{
|
||||
marginTop: 16,
|
||||
@@ -724,12 +995,14 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: 12
|
||||
marginBottom: 12,
|
||||
flexWrap: 'wrap',
|
||||
gap: 8
|
||||
}}>
|
||||
<h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>
|
||||
🔬 Debug-Info
|
||||
Test-Ergebnis
|
||||
</h3>
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<button
|
||||
className="btn"
|
||||
onClick={handleExportPlaceholders}
|
||||
@@ -739,31 +1012,120 @@ export default function UnifiedPromptModal({ prompt, onSave, onClose }) {
|
||||
background: 'var(--accent)',
|
||||
color: 'white'
|
||||
}}
|
||||
title="Exportiere alle Platzhalter mit Werten als JSON"
|
||||
title="Exportiere Platzhalter / Kontext als JSON"
|
||||
>
|
||||
📋 Platzhalter exportieren
|
||||
📋 Kontext exportieren
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setShowDebug(false)}
|
||||
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 4 }}
|
||||
aria-label="Schließen"
|
||||
>
|
||||
<X size={16} color="var(--text3)" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<pre style={{
|
||||
fontSize: 11,
|
||||
fontFamily: 'monospace',
|
||||
background: 'var(--bg)',
|
||||
padding: 12,
|
||||
borderRadius: 6,
|
||||
overflow: 'auto',
|
||||
maxHeight: 400,
|
||||
lineHeight: 1.5,
|
||||
color: 'var(--text2)'
|
||||
}}>
|
||||
{JSON.stringify(testResult.debug || testResult, null, 2)}
|
||||
</pre>
|
||||
|
||||
<div
|
||||
role="tablist"
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: 6,
|
||||
marginBottom: 12,
|
||||
flexWrap: 'wrap',
|
||||
borderBottom: '1px solid var(--border)',
|
||||
paddingBottom: 8
|
||||
}}
|
||||
>
|
||||
{[
|
||||
{ id: 'response', label: 'Antwort' },
|
||||
{ id: 'prompt', label: 'Prompt (an LLM)' },
|
||||
{ id: 'debug', label: 'Debug' }
|
||||
].map((tab) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={testResultTab === tab.id}
|
||||
onClick={() => setTestResultTab(tab.id)}
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: 12,
|
||||
borderRadius: 6,
|
||||
border: '1px solid var(--border)',
|
||||
background: testResultTab === tab.id ? 'var(--accent)' : 'var(--surface)',
|
||||
color: testResultTab === tab.id ? '#fff' : 'var(--text2)',
|
||||
cursor: 'pointer',
|
||||
fontWeight: testResultTab === tab.id ? 600 : 400
|
||||
}}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div
|
||||
role="tabpanel"
|
||||
style={{
|
||||
minHeight: 120,
|
||||
maxHeight: testResultTab === 'prompt' ? 480 : 420,
|
||||
overflow: 'auto',
|
||||
textAlign: 'left'
|
||||
}}
|
||||
>
|
||||
{testResultTab === 'response' && (
|
||||
<div style={{ paddingRight: 4 }}>
|
||||
{renderTestOutput(testResult)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{testResultTab === 'prompt' && (
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: 12,
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
lineHeight: 1.45,
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
color: 'var(--text1)',
|
||||
padding: 12,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
{buildPromptTextForDisplay(testResult) || '(Kein Prompt-Text in der Antwort — evtl. Fehler vor Ausführung.)'}
|
||||
</pre>
|
||||
)}
|
||||
|
||||
{testResultTab === 'debug' && (
|
||||
<pre
|
||||
style={{
|
||||
margin: 0,
|
||||
fontSize: 11,
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
lineHeight: 1.45,
|
||||
padding: 12,
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
color: 'var(--text2)',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word'
|
||||
}}
|
||||
>
|
||||
{JSON.stringify(
|
||||
sanitizeDebugForPanel(
|
||||
extractExecutionDebug(testResult),
|
||||
testResult.error ? null : testResult.type
|
||||
),
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,356 @@
|
||||
import React, { useState } from 'react'
|
||||
import { ChevronDown, ChevronUp } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* WorkflowDebugPanel - Zeigt Debug-Informationen für jeden Node eines Workflows
|
||||
*
|
||||
* @param {Object} props
|
||||
* @param {Array} props.nodeStates - Array von NodeExecutionState Objekten
|
||||
*/
|
||||
export default function WorkflowDebugPanel({ nodeStates }) {
|
||||
const [expandedNodes, setExpandedNodes] = useState(new Set())
|
||||
const [showAll, setShowAll] = useState(false)
|
||||
|
||||
if (!nodeStates || nodeStates.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Filter nodes that have debug information
|
||||
const debugNodes = nodeStates.filter(ns =>
|
||||
ns.debug_prompt || ns.debug_raw_response || ns.debug_node_type
|
||||
)
|
||||
|
||||
if (debugNodes.length === 0) {
|
||||
return (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
marginTop: '16px'
|
||||
}}>
|
||||
<p style={{ margin: 0, color: 'var(--text2)', fontSize: '13px' }}>
|
||||
Keine Debug-Informationen verfügbar. Führe den Workflow mit debug=true aus.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const toggleNode = (nodeId) => {
|
||||
const newExpanded = new Set(expandedNodes)
|
||||
if (newExpanded.has(nodeId)) {
|
||||
newExpanded.delete(nodeId)
|
||||
} else {
|
||||
newExpanded.add(nodeId)
|
||||
}
|
||||
setExpandedNodes(newExpanded)
|
||||
}
|
||||
|
||||
const toggleAll = () => {
|
||||
if (showAll) {
|
||||
setExpandedNodes(new Set())
|
||||
} else {
|
||||
setExpandedNodes(new Set(debugNodes.map(n => n.node_id)))
|
||||
}
|
||||
setShowAll(!showAll)
|
||||
}
|
||||
|
||||
const getStatusColor = (status) => {
|
||||
switch (status) {
|
||||
case 'executed': return '#1D9E75'
|
||||
case 'failed': return '#D85A30'
|
||||
case 'skipped': return '#888'
|
||||
default: return 'var(--text2)'
|
||||
}
|
||||
}
|
||||
|
||||
const getNodeLabel = (node) => {
|
||||
if (node.debug_prompt_slug) return node.debug_prompt_slug
|
||||
if (node.debug_node_type) return `${node.debug_node_type}-${node.node_id.substring(0, 8)}`
|
||||
return node.node_id
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
marginTop: '24px',
|
||||
padding: '16px',
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
<h3 style={{
|
||||
margin: 0,
|
||||
fontSize: '16px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--text1)'
|
||||
}}>
|
||||
🔍 Debug-Informationen ({debugNodes.length} Nodes)
|
||||
</h3>
|
||||
<button
|
||||
onClick={toggleAll}
|
||||
className="btn"
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
fontSize: '13px',
|
||||
minWidth: 'auto'
|
||||
}}
|
||||
>
|
||||
{showAll ? 'Alle zuklappen' : 'Alle aufklappen'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
{debugNodes.map((node, idx) => {
|
||||
const isExpanded = expandedNodes.has(node.node_id)
|
||||
const label = getNodeLabel(node)
|
||||
const statusColor = getStatusColor(node.status)
|
||||
|
||||
const hasFailed = node.status === 'failed'
|
||||
const hasError = node.error != null
|
||||
|
||||
return (
|
||||
<div
|
||||
key={node.node_id}
|
||||
style={{
|
||||
border: hasFailed ? '2px solid #D85A30' : '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
background: hasFailed ? '#D85A3010' : 'var(--bg)',
|
||||
overflow: 'hidden',
|
||||
boxShadow: hasFailed ? '0 0 0 2px #D85A3020' : 'none'
|
||||
}}
|
||||
>
|
||||
{/* Node Header */}
|
||||
<div
|
||||
onClick={() => toggleNode(node.node_id)}
|
||||
style={{
|
||||
padding: '12px',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
cursor: 'pointer',
|
||||
background: isExpanded ? 'var(--surface)' : 'transparent',
|
||||
transition: 'background 0.2s'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
|
||||
<span style={{
|
||||
fontSize: '13px',
|
||||
color: 'var(--text3)',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
#{idx + 1}
|
||||
</span>
|
||||
<span style={{
|
||||
fontWeight: 500,
|
||||
color: 'var(--text1)',
|
||||
fontSize: '14px'
|
||||
}}>
|
||||
{label}
|
||||
</span>
|
||||
<span style={{
|
||||
fontSize: '12px',
|
||||
padding: '2px 8px',
|
||||
borderRadius: '4px',
|
||||
background: statusColor,
|
||||
color: 'white',
|
||||
fontWeight: 500
|
||||
}}>
|
||||
{node.status}
|
||||
</span>
|
||||
{node.debug_node_type && (
|
||||
<span style={{
|
||||
fontSize: '11px',
|
||||
padding: '2px 6px',
|
||||
borderRadius: '4px',
|
||||
background: 'var(--surface2)',
|
||||
color: 'var(--text2)',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
{node.debug_node_type}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{isExpanded ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
|
||||
</div>
|
||||
|
||||
{/* Node Debug Content */}
|
||||
{isExpanded && (
|
||||
<div style={{ padding: '0 12px 12px 12px' }}>
|
||||
{node.error && (
|
||||
<div style={{
|
||||
padding: '12px',
|
||||
background: '#D85A3015',
|
||||
border: '1px solid #D85A30',
|
||||
borderRadius: '6px',
|
||||
marginBottom: '12px'
|
||||
}}>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color: '#D85A30',
|
||||
marginBottom: '6px'
|
||||
}}>
|
||||
Error:
|
||||
</div>
|
||||
<pre style={{
|
||||
margin: 0,
|
||||
fontSize: '12px',
|
||||
color: '#D85A30',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word'
|
||||
}}>
|
||||
{node.error}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.debug_prompt && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--text2)',
|
||||
marginBottom: '6px',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px'
|
||||
}}>
|
||||
Prompt:
|
||||
</div>
|
||||
<pre style={{
|
||||
margin: 0,
|
||||
padding: '12px',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: '6px',
|
||||
fontSize: '12px',
|
||||
lineHeight: '1.6',
|
||||
color: 'var(--text1)',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
maxHeight: '400px',
|
||||
overflowY: 'auto',
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
{node.debug_prompt}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.debug_raw_response && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--text2)',
|
||||
marginBottom: '6px',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px'
|
||||
}}>
|
||||
Rohe Antwort:
|
||||
</div>
|
||||
<pre style={{
|
||||
margin: 0,
|
||||
padding: '12px',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: '6px',
|
||||
fontSize: '12px',
|
||||
lineHeight: '1.6',
|
||||
color: 'var(--text1)',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
maxHeight: '400px',
|
||||
overflowY: 'auto',
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
{node.debug_raw_response}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.analysis_core && (
|
||||
<div>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--text2)',
|
||||
marginBottom: '6px',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px'
|
||||
}}>
|
||||
Geparste Ergebnisse:
|
||||
</div>
|
||||
<pre style={{
|
||||
margin: 0,
|
||||
padding: '12px',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: '6px',
|
||||
fontSize: '12px',
|
||||
lineHeight: '1.6',
|
||||
color: 'var(--text1)',
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-word',
|
||||
maxHeight: '300px',
|
||||
overflowY: 'auto',
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
{node.analysis_core}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{node.normalized_signals && node.normalized_signals.length > 0 && (
|
||||
<div style={{ marginTop: '12px' }}>
|
||||
<div style={{
|
||||
fontSize: '12px',
|
||||
fontWeight: 600,
|
||||
color: 'var(--text2)',
|
||||
marginBottom: '6px',
|
||||
textTransform: 'uppercase',
|
||||
letterSpacing: '0.5px'
|
||||
}}>
|
||||
Signale ({node.normalized_signals.length}):
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '6px' }}>
|
||||
{node.normalized_signals.map((sig, i) => (
|
||||
<div
|
||||
key={i}
|
||||
style={{
|
||||
padding: '8px',
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: '4px',
|
||||
fontSize: '12px',
|
||||
border: '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
<span style={{ color: 'var(--text2)' }}>{sig.question_type}:</span>{' '}
|
||||
<span style={{ fontWeight: 500, color: 'var(--text1)' }}>
|
||||
"{sig.raw_value}" → "{sig.normalized_value}"
|
||||
</span>{' '}
|
||||
<span style={{
|
||||
fontSize: '11px',
|
||||
padding: '2px 6px',
|
||||
borderRadius: '3px',
|
||||
background: sig.status === 'valid' ? '#1D9E7520' : '#D85A3020',
|
||||
color: sig.status === 'valid' ? '#1D9E75' : '#D85A30'
|
||||
}}>
|
||||
{sig.status}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -47,7 +47,7 @@ export function QuestionAugmentationPanel({ node, onChange }) {
|
||||
|
||||
{questions.map((q, idx) => (
|
||||
<QuestionEditor
|
||||
key={q.id}
|
||||
key={idx}
|
||||
question={q}
|
||||
index={idx}
|
||||
onChange={(field, value) => handleQuestionChange(idx, field, value)}
|
||||
|
||||
@@ -192,13 +192,17 @@ export function WorkflowResultViewer({ result, onClose }) {
|
||||
Node States (Debug)
|
||||
</h3>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
{nodeStates.map((node) => (
|
||||
{nodeStates.map((node) => {
|
||||
const hasFailed = node.status === 'failed'
|
||||
return (
|
||||
<div
|
||||
key={node.node_id}
|
||||
style={{
|
||||
border: '1px solid var(--border)',
|
||||
border: hasFailed ? '2px solid #D85A30' : '1px solid var(--border)',
|
||||
borderRadius: '8px',
|
||||
overflow: 'hidden'
|
||||
background: hasFailed ? '#D85A3010' : 'transparent',
|
||||
overflow: 'hidden',
|
||||
boxShadow: hasFailed ? '0 0 0 2px #D85A3020' : 'none'
|
||||
}}
|
||||
>
|
||||
{/* Node Header */}
|
||||
@@ -216,13 +220,13 @@ export function WorkflowResultViewer({ result, onClose }) {
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
{node.node_type === 'start' && '🚀'}
|
||||
{node.node_type === 'analysis' && '🤖'}
|
||||
{node.node_type === 'logic' && '⚡'}
|
||||
{node.node_type === 'join' && '🔀'}
|
||||
{node.node_type === 'end' && '🏁'}
|
||||
{(node.debug_node_type || node.node_type) === 'start' && '🚀'}
|
||||
{(node.debug_node_type || node.node_type) === 'analysis' && '🤖'}
|
||||
{(node.debug_node_type || node.node_type) === 'logic' && '⚡'}
|
||||
{(node.debug_node_type || node.node_type) === 'join' && '🔀'}
|
||||
{(node.debug_node_type || node.node_type) === 'end' && '🏁'}
|
||||
{' '}
|
||||
{node.node_label || node.node_id}
|
||||
{node.debug_prompt_slug || node.node_label || ((node.debug_node_type || node.node_type) ? `${node.debug_node_type || node.node_type}-${node.node_id.substring(0, 8)}` : node.node_id)}
|
||||
{node.status === 'skipped' && (
|
||||
<span style={{ color: 'var(--text3)', marginLeft: '8px' }}>
|
||||
(skipped)
|
||||
@@ -237,45 +241,65 @@ export function WorkflowResultViewer({ result, onClose }) {
|
||||
{/* Node Details */}
|
||||
{expandedNodes[node.node_id] && (
|
||||
<div style={{ padding: '12px', fontSize: '12px' }}>
|
||||
{node.output && (
|
||||
{/* Error (show first) */}
|
||||
{node.error && (
|
||||
<div style={{ marginBottom: '12px', padding: '12px', background: '#D85A3015', border: '1px solid #D85A30', borderRadius: '6px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: 600, color: '#D85A30', marginBottom: '6px' }}>Error:</div>
|
||||
<pre style={{ margin: 0, fontSize: '12px', color: '#D85A30', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{node.error}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Debug Prompt */}
|
||||
{node.debug_prompt && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: 600, color: 'var(--text2)', marginBottom: '6px', textTransform: 'uppercase' }}>Prompt:</div>
|
||||
<pre style={{ margin: 0, padding: '12px', background: 'var(--surface2)', borderRadius: '6px', fontSize: '11px', color: 'var(--text1)', whiteSpace: 'pre-wrap', maxHeight: '300px', overflowY: 'auto', border: '1px solid var(--border)' }}>{node.debug_prompt}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Debug Raw Response */}
|
||||
{node.debug_raw_response && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: 600, color: 'var(--text2)', marginBottom: '6px', textTransform: 'uppercase' }}>Rohe Antwort:</div>
|
||||
<pre style={{ margin: 0, padding: '12px', background: 'var(--surface2)', borderRadius: '6px', fontSize: '11px', color: 'var(--text1)', whiteSpace: 'pre-wrap', maxHeight: '300px', overflowY: 'auto', border: '1px solid var(--border)' }}>{node.debug_raw_response}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Analysis Core */}
|
||||
{node.analysis_core && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: 600, color: 'var(--text2)', marginBottom: '6px', textTransform: 'uppercase' }}>Ergebnis:</div>
|
||||
<pre style={{ margin: 0, padding: '12px', background: 'var(--surface2)', borderRadius: '6px', fontSize: '11px', color: 'var(--text1)', whiteSpace: 'pre-wrap', maxHeight: '300px', overflowY: 'auto', border: '1px solid var(--border)' }}>{node.analysis_core}</pre>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Normalized Signals */}
|
||||
{node.normalized_signals && node.normalized_signals.length > 0 && (
|
||||
<div style={{ marginBottom: '12px' }}>
|
||||
<div style={{ fontSize: '12px', fontWeight: 600, color: 'var(--text2)', marginBottom: '6px', textTransform: 'uppercase' }}>Signale ({node.normalized_signals.length}):</div>
|
||||
{node.normalized_signals.map((sig, i) => (
|
||||
<div key={i} style={{ padding: '6px', background: 'var(--surface2)', borderRadius: '4px', fontSize: '11px', marginBottom: '4px', border: '1px solid var(--border)' }}>
|
||||
<span style={{ color: 'var(--text2)' }}>{sig.question_type}:</span> <span style={{ fontWeight: 500 }}>"{sig.raw_value}" → "{sig.normalized_value}"</span> <span style={{ fontSize: '10px', padding: '2px 4px', borderRadius: '2px', background: sig.status === 'valid' ? '#1D9E7520' : '#D85A3020', color: sig.status === 'valid' ? '#1D9E75' : '#D85A30' }}>{sig.status}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Output (fallback) */}
|
||||
{node.output && !node.analysis_core && (
|
||||
<div style={{ marginBottom: '8px' }}>
|
||||
<strong>Output:</strong>
|
||||
<pre
|
||||
style={{
|
||||
marginTop: '4px',
|
||||
padding: '8px',
|
||||
background: 'var(--bg)',
|
||||
borderRadius: '4px',
|
||||
fontSize: '11px',
|
||||
overflowX: 'auto',
|
||||
maxHeight: '200px',
|
||||
overflowY: 'auto'
|
||||
}}
|
||||
>
|
||||
{typeof node.output === 'string'
|
||||
? node.output
|
||||
: JSON.stringify(node.output, null, 2)}
|
||||
<pre style={{ marginTop: '4px', padding: '8px', background: 'var(--bg)', borderRadius: '4px', fontSize: '11px', overflowX: 'auto', maxHeight: '200px', overflowY: 'auto' }}>
|
||||
{typeof node.output === 'string' ? node.output : JSON.stringify(node.output, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
{node.error && (
|
||||
<div style={{ color: 'var(--danger)', marginBottom: '8px' }}>
|
||||
<strong>Error:</strong> {node.error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Metadata */}
|
||||
{node.metadata && (
|
||||
<div style={{ marginTop: '8px' }}>
|
||||
<strong>Metadata:</strong>
|
||||
<pre
|
||||
style={{
|
||||
marginTop: '4px',
|
||||
padding: '8px',
|
||||
background: 'var(--bg)',
|
||||
borderRadius: '4px',
|
||||
fontSize: '11px',
|
||||
overflowX: 'auto'
|
||||
}}
|
||||
>
|
||||
<pre style={{ marginTop: '4px', padding: '8px', background: 'var(--bg)', borderRadius: '4px', fontSize: '11px', overflowX: 'auto' }}>
|
||||
{JSON.stringify(node.metadata, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
@@ -283,7 +307,7 @@ export function WorkflowResultViewer({ result, onClose }) {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
)})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import Markdown from '../utils/Markdown'
|
||||
import UsageBadge from '../components/UsageBadge'
|
||||
import WorkflowDebugPanel from '../components/WorkflowDebugPanel'
|
||||
import dayjs from 'dayjs'
|
||||
import 'dayjs/locale/de'
|
||||
dayjs.locale('de')
|
||||
@@ -338,6 +339,8 @@ export default function Analysis() {
|
||||
/** Kategorie-Schlüssel aus `buildPipelineGroups` (Navigation); Detail = alle Pipelines dieser Kategorie */
|
||||
const [activeCategoryKey, setActiveCategoryKey] = useState(null)
|
||||
const [historyScopePick, setHistoryScopePick] = useState(null)
|
||||
// NEW: Progress tracking for SSE workflows
|
||||
const [progress, setProgress] = useState(null) // { total_nodes, completed_nodes, current_node_label }
|
||||
|
||||
const loadAll = async () => {
|
||||
const [p, i] = await Promise.all([
|
||||
@@ -377,10 +380,21 @@ export default function Analysis() {
|
||||
}, [newResult?.scope, prompts])
|
||||
|
||||
const runPrompt = async (slug) => {
|
||||
setLoading(slug); setError(null); setNewResult(null)
|
||||
setLoading(slug); setError(null); setNewResult(null); setProgress(null)
|
||||
try {
|
||||
// Use new unified executor with save=true
|
||||
const result = await api.executeUnifiedPrompt(slug, null, null, false, true)
|
||||
// Use SSE-based executor for long-running workflows
|
||||
const result = await api.executeUnifiedPromptStream(slug, null, null, true, true, (event) => {
|
||||
// Progress callback: update UI in real-time
|
||||
if (event.type === 'execution_started') {
|
||||
setProgress({ total_nodes: 0, completed_nodes: 0, current_node_label: 'Starte...' })
|
||||
} else if (event.type === 'node_complete') {
|
||||
setProgress({
|
||||
total_nodes: event.total_nodes || 0,
|
||||
completed_nodes: event.completed_nodes || 0,
|
||||
current_node_label: event.node_label || `Node ${event.node_id}`
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// Transform result to match old format for InsightCard
|
||||
let content = ''
|
||||
@@ -429,12 +443,22 @@ export default function Analysis() {
|
||||
}
|
||||
}
|
||||
|
||||
setNewResult({ scope: slug, content, metadata })
|
||||
setNewResult({
|
||||
scope: slug,
|
||||
content,
|
||||
metadata,
|
||||
node_states: result.node_states, // For workflow debug panel
|
||||
result_type: result.type,
|
||||
aggregated_result: result.aggregated_result
|
||||
})
|
||||
await loadAll()
|
||||
setTab('run')
|
||||
} catch(e) {
|
||||
setError('Fehler: ' + e.message)
|
||||
} finally { setLoading(null) }
|
||||
} finally {
|
||||
setLoading(null)
|
||||
setProgress(null) // Clear progress
|
||||
}
|
||||
}
|
||||
|
||||
const deleteInsight = async (id) => {
|
||||
@@ -518,6 +542,9 @@ export default function Analysis() {
|
||||
defaultOpen={true}
|
||||
prompts={prompts}
|
||||
/>
|
||||
{newResult.node_states && (
|
||||
<WorkflowDebugPanel nodeStates={newResult.node_states} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -575,6 +602,9 @@ export default function Analysis() {
|
||||
defaultOpen={true}
|
||||
prompts={prompts}
|
||||
/>
|
||||
{newResult.node_states && (
|
||||
<WorkflowDebugPanel nodeStates={newResult.node_states} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{activeCategoryKey && (() => {
|
||||
@@ -618,7 +648,9 @@ export default function Analysis() {
|
||||
disabled={!!loading||!canUseAI||(aiUsage && !aiUsage.allowed)}
|
||||
>
|
||||
{loading===p.slug
|
||||
? <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>
|
||||
? (progress
|
||||
? <><div className="spinner" style={{width:13,height:13}}/> {progress.completed_nodes}/{progress.total_nodes} Nodes</>
|
||||
: <><div className="spinner" style={{width:13,height:13}}/> Läuft…</>)
|
||||
: (aiUsage && !aiUsage.allowed) ? '🔒 Limit'
|
||||
: <><Brain size={13}/> Starten</>}
|
||||
</button>
|
||||
|
||||
@@ -55,6 +55,28 @@ const getCategoryForGoalType = (goalType) => {
|
||||
return mapping[goalType] || 'other'
|
||||
}
|
||||
|
||||
/** Fortschritt in % von Start zum Ziel; bevorzugt `progress_pct` vom Server, sonst aus Ist-Werten. */
|
||||
function getGoalProgressPercent(goal) {
|
||||
const apiVal = goal?.progress_pct
|
||||
if (apiVal !== null && apiVal !== undefined && Number.isFinite(Number(apiVal))) {
|
||||
return Number(apiVal)
|
||||
}
|
||||
const s = goal?.start_value != null ? Number(goal.start_value) : NaN
|
||||
const t = goal?.target_value != null ? Number(goal.target_value) : NaN
|
||||
const c =
|
||||
goal?.current_value != null && goal.current_value !== ''
|
||||
? Number(goal.current_value)
|
||||
: NaN
|
||||
if (!Number.isFinite(s) || !Number.isFinite(t) || !Number.isFinite(c)) return null
|
||||
const span = Math.abs(t - s)
|
||||
if (span < 1e-9) {
|
||||
if (Math.abs(c - s) < 1e-9) return 100
|
||||
return null
|
||||
}
|
||||
if (t > s) return ((c - s) / (t - s)) * 100
|
||||
return ((s - c) / (s - t)) * 100
|
||||
}
|
||||
|
||||
export default function GoalsPage() {
|
||||
const [goalMode, setGoalMode] = useState(null)
|
||||
const [userFocusWeights, setUserFocusWeights] = useState([]) // v2.0: User's focus area weights
|
||||
@@ -613,6 +635,17 @@ export default function GoalsPage() {
|
||||
{categoryGoals.map(goal => {
|
||||
const typeInfo = goalTypesMap[goal.goal_type] || { label_de: goal.goal_type, unit: '', icon: '📊' }
|
||||
const priorityInfo = PRIORITY_LEVELS[goal.priority] || PRIORITY_LEVELS[2]
|
||||
const progressPct = getGoalProgressPercent(goal)
|
||||
const progressLabel =
|
||||
progressPct != null
|
||||
? (Math.abs(progressPct - Math.round(progressPct)) < 0.05
|
||||
? `${Math.round(progressPct)}`
|
||||
: `${Math.round(progressPct * 10) / 10}`.replace('.', ','))
|
||||
: null
|
||||
const progressBarWidth =
|
||||
progressPct != null
|
||||
? Math.min(100, Math.max(0, progressPct))
|
||||
: 0
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -719,30 +752,40 @@ export default function GoalsPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{goal.progress_pct !== null && (
|
||||
<div>
|
||||
{progressPct != null && (
|
||||
<div style={{ marginTop: 4 }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
fontSize: 12,
|
||||
marginBottom: 4,
|
||||
color: 'var(--text2)'
|
||||
marginBottom: 6,
|
||||
color: 'var(--text2)',
|
||||
alignItems: 'baseline',
|
||||
gap: 8
|
||||
}}>
|
||||
<span>Fortschritt</span>
|
||||
<span style={{ fontWeight: 600, color: 'var(--text1)' }}>{goal.progress_pct}%</span>
|
||||
<span>Fortschritt (Start → Ziel)</span>
|
||||
<span style={{ fontWeight: 600, color: 'var(--text1)' }}>
|
||||
{progressLabel}%
|
||||
{progressPct > 100 && (
|
||||
<span style={{ fontWeight: 500, color: 'var(--text3)', marginLeft: 4 }}>
|
||||
(über Ziel)
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{
|
||||
width: '100%',
|
||||
height: 8,
|
||||
height: 10,
|
||||
background: 'var(--surface)',
|
||||
borderRadius: 4,
|
||||
overflow: 'hidden'
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
border: '1px solid var(--border)'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${Math.min(100, Math.max(0, goal.progress_pct))}%`,
|
||||
width: `${progressBarWidth}%`,
|
||||
height: '100%',
|
||||
background: catInfo.color,
|
||||
transition: 'width 0.3s ease'
|
||||
background: getProgressColor(Math.min(100, Math.max(0, progressPct))),
|
||||
transition: 'width 0.35s ease'
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Lightweight Markdown renderer – handles the subset used by the AI:
|
||||
// ## Headings, **bold**, bullet lists, numbered lists, line breaks
|
||||
// ## Headings, **bold**, bullet lists, numbered lists, fenced ``` code ```, line breaks
|
||||
|
||||
export default function Markdown({ text }) {
|
||||
if (!text) return null
|
||||
@@ -7,6 +7,19 @@ export default function Markdown({ text }) {
|
||||
const lines = text.split('\n')
|
||||
const elements = []
|
||||
let i = 0
|
||||
let blockId = 0
|
||||
|
||||
const codeBlockStyle = {
|
||||
margin: '10px 0',
|
||||
padding: 12,
|
||||
background: 'var(--surface2)',
|
||||
borderRadius: 8,
|
||||
border: '1px solid var(--border)',
|
||||
overflow: 'auto',
|
||||
fontSize: 12,
|
||||
lineHeight: 1.5,
|
||||
fontFamily: 'ui-monospace, Consolas, monospace'
|
||||
}
|
||||
|
||||
const parseLine = (line) => {
|
||||
// Parse inline **bold** and *italic*
|
||||
@@ -39,6 +52,44 @@ export default function Markdown({ text }) {
|
||||
while (i < lines.length) {
|
||||
const line = lines[i]
|
||||
|
||||
// Fenced code block: ``` or ```lang
|
||||
const trimmedStart = line.trimStart()
|
||||
if (trimmedStart.startsWith('```')) {
|
||||
const lang = trimmedStart.slice(3).trim() || null
|
||||
i++
|
||||
const codeLines = []
|
||||
while (i < lines.length) {
|
||||
if (lines[i].trim().startsWith('```')) {
|
||||
i++
|
||||
break
|
||||
}
|
||||
codeLines.push(lines[i])
|
||||
i++
|
||||
}
|
||||
const code = codeLines.join('\n')
|
||||
elements.push(
|
||||
<div key={`code-${blockId++}`} style={{ margin: '10px 0' }}>
|
||||
{lang && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 10,
|
||||
color: 'var(--text3)',
|
||||
marginBottom: 6,
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
letterSpacing: 0.02
|
||||
}}
|
||||
>
|
||||
{lang}
|
||||
</div>
|
||||
)}
|
||||
<pre style={codeBlockStyle}>
|
||||
<code style={{ color: 'var(--text1)', whiteSpace: 'pre', display: 'block' }}>{code}</code>
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
// Skip empty lines (add spacing)
|
||||
if (line.trim() === '') {
|
||||
elements.push(<div key={i} style={{ height: 8 }} />)
|
||||
|
||||
@@ -402,6 +402,72 @@ export const api = {
|
||||
return req('/prompts/execute?' + params, json(body))
|
||||
},
|
||||
|
||||
// NEW: SSE-based execution for long-running workflows
|
||||
executeUnifiedPromptStream: (slug, modules=null, timeframes=null, debug=false, save=false, onProgress=null) => {
|
||||
const params = new URLSearchParams({ prompt_slug: slug })
|
||||
if (debug) params.append('debug', 'true')
|
||||
if (save) params.append('save', 'true')
|
||||
|
||||
// TODO: Security improvement - use session cookie instead of token in URL
|
||||
// For now, send token as query param since EventSource doesn't support custom headers
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) params.append('token', token)
|
||||
|
||||
if (modules) {
|
||||
Object.entries(modules).forEach(([k, v]) => params.append(`modules[${k}]`, v))
|
||||
}
|
||||
if (timeframes) {
|
||||
Object.entries(timeframes).forEach(([k, v]) => params.append(`timeframes[${k}]`, v))
|
||||
}
|
||||
|
||||
// Return a Promise that resolves with final result
|
||||
return new Promise((resolve, reject) => {
|
||||
const url = `${BASE_URL}/prompts/execute-stream?${params}`
|
||||
|
||||
const eventSource = new EventSource(url)
|
||||
|
||||
let finalResult = null
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data)
|
||||
|
||||
// Call progress callback if provided
|
||||
if (onProgress) {
|
||||
onProgress(data)
|
||||
}
|
||||
|
||||
// Check for final result
|
||||
if (data.type === 'execution_complete') {
|
||||
// Transform SSE result to match regular execute format
|
||||
finalResult = {
|
||||
type: 'workflow',
|
||||
execution_id: data.execution_id,
|
||||
status: data.status,
|
||||
aggregated_result: data.aggregated_result,
|
||||
debug: {
|
||||
node_states: [] // TODO: collect from progress events if needed
|
||||
}
|
||||
}
|
||||
eventSource.close()
|
||||
resolve(finalResult)
|
||||
} else if (data.type === 'execution_failed') {
|
||||
eventSource.close()
|
||||
reject(new Error(data.error || 'Workflow execution failed'))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Error parsing SSE event:', e)
|
||||
}
|
||||
}
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
console.error('SSE connection error:', error)
|
||||
eventSource.close()
|
||||
reject(new Error('Connection to server lost'))
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
// Workflow Execution (Part 2: Frontend Execute Integration)
|
||||
executeWorkflow: (slug, variables=null, debug=true, save=false) => {
|
||||
const params = new URLSearchParams({ prompt_slug: slug })
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"""
|
||||
Test Condition Parsing - Alle Formate und Verschachtelungen
|
||||
|
||||
Testet ob Pydantic die verschiedenen Condition-Formate korrekt deserialisiert.
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Force UTF-8 encoding on Windows
|
||||
if sys.platform == 'win32':
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, 'backend')
|
||||
|
||||
from workflow_models import LogicExpression, Condition, WorkflowNode, LogicOperator
|
||||
from pydantic import ValidationError
|
||||
import json
|
||||
|
||||
def test_case(name, data, expected_type, should_fail=False):
|
||||
"""Test a single condition format"""
|
||||
print(f"\n{'='*60}")
|
||||
print(f"TEST: {name}")
|
||||
print(f"{'='*60}")
|
||||
print(f"Input: {json.dumps(data, indent=2)}")
|
||||
|
||||
try:
|
||||
# Test 1: Direct deserialization
|
||||
if expected_type == LogicExpression:
|
||||
result = LogicExpression(**data)
|
||||
elif expected_type == Condition:
|
||||
result = Condition(**data)
|
||||
|
||||
if should_fail:
|
||||
print("❌ FAILED: Should have raised ValidationError but didn't")
|
||||
return False
|
||||
|
||||
print(f"✅ PASSED: Deserialized as {type(result).__name__}")
|
||||
print(f"Result: {result.model_dump()}")
|
||||
|
||||
# Test 2: As part of WorkflowNode
|
||||
node_data = {
|
||||
"id": "test_node",
|
||||
"type": "logic",
|
||||
"condition": data
|
||||
}
|
||||
node = WorkflowNode(**node_data)
|
||||
print(f"✅ PASSED: WorkflowNode.condition type: {type(node.condition).__name__}")
|
||||
|
||||
return True
|
||||
|
||||
except ValidationError as e:
|
||||
if should_fail:
|
||||
print(f"✅ PASSED: Correctly raised ValidationError")
|
||||
return True
|
||||
else:
|
||||
print(f"❌ FAILED: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"❌ FAILED: Unexpected error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test Cases
|
||||
# ============================================================================
|
||||
|
||||
test_results = []
|
||||
|
||||
# Test 1: Simple comparison (UI format - einfachster Fall)
|
||||
test_results.append(test_case(
|
||||
"Simple comparison (eq)",
|
||||
{
|
||||
"operator": "eq",
|
||||
"ref": "node_1.q1",
|
||||
"value": "ja"
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 2: Simple AND (UI format - wie im Workflow)
|
||||
test_results.append(test_case(
|
||||
"Simple AND with 2 operands",
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_5.qTiefananalyseRecovery", "value": "ja"},
|
||||
{"operator": "neq", "ref": "node_6.qKonsistenz", "value": "nein"}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 3: Simple OR
|
||||
test_results.append(test_case(
|
||||
"Simple OR with 3 operands",
|
||||
{
|
||||
"operator": "or",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.q1", "value": "ja"},
|
||||
{"operator": "eq", "ref": "node_1.q2", "value": "nein"},
|
||||
{"operator": "eq", "ref": "node_1.q3", "value": "unklar"}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 4: Nested AND/OR
|
||||
test_results.append(test_case(
|
||||
"Nested: OR with nested AND",
|
||||
{
|
||||
"operator": "or",
|
||||
"operands": [
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.q1", "value": "ja"},
|
||||
{"operator": "neq", "ref": "node_1.q2", "value": "nein"}
|
||||
]
|
||||
},
|
||||
{"operator": "eq", "ref": "node_2.q1", "value": "hoch"}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 5: Deep nesting (3 levels)
|
||||
test_results.append(test_case(
|
||||
"Deep nesting (3 levels)",
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{
|
||||
"operator": "or",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.q1", "value": "ja"},
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_2.q1", "value": "hoch"},
|
||||
{"operator": "neq", "ref": "node_2.q2", "value": "niedrig"}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{"operator": "eq", "ref": "node_3.q1", "value": "aktiv"}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 6: Different operators
|
||||
test_results.append(test_case(
|
||||
"Different comparison operators (gt, lt, in)",
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "gt", "ref": "node_1.score", "value": 50},
|
||||
{"operator": "lt", "ref": "node_1.score", "value": 100},
|
||||
{"operator": "in", "ref": "node_1.category", "value": ["high", "medium"]}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 7: Legacy format (wrapped in Condition)
|
||||
test_results.append(test_case(
|
||||
"Legacy format: Condition with expression",
|
||||
{
|
||||
"type": "if",
|
||||
"expression": {
|
||||
"operator": "eq",
|
||||
"ref": "node_1.q1",
|
||||
"value": "ja"
|
||||
},
|
||||
"then_path": "edge_1",
|
||||
"else_path": "edge_2"
|
||||
},
|
||||
Condition
|
||||
))
|
||||
|
||||
# Test 8: NOT operator
|
||||
test_results.append(test_case(
|
||||
"NOT operator",
|
||||
{
|
||||
"operator": "not",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.q1", "value": "nein"}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# Test 9: Complex real-world scenario
|
||||
test_results.append(test_case(
|
||||
"Complex real-world: Multiple nested conditions",
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{
|
||||
"operator": "or",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.relevance", "value": "high"},
|
||||
{
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_1.relevance", "value": "medium"},
|
||||
{"operator": "gt", "ref": "node_1.priority", "value": 5}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{"operator": "neq", "ref": "node_2.status", "value": "blocked"},
|
||||
{
|
||||
"operator": "in",
|
||||
"ref": "node_3.category",
|
||||
"value": ["training", "nutrition", "recovery"]
|
||||
}
|
||||
]
|
||||
},
|
||||
LogicExpression
|
||||
))
|
||||
|
||||
# ============================================================================
|
||||
# Results Summary
|
||||
# ============================================================================
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("TEST RESULTS SUMMARY")
|
||||
print("="*60)
|
||||
|
||||
passed = sum(test_results)
|
||||
total = len(test_results)
|
||||
failed = total - passed
|
||||
|
||||
print(f"\n✅ Passed: {passed}/{total}")
|
||||
if failed > 0:
|
||||
print(f"❌ Failed: {failed}/{total}")
|
||||
print(f"\n⚠️ CRITICAL: Some tests failed! Do NOT deploy until fixed.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print(f"\n🎉 All tests passed! Safe to deploy.")
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
Test Union[LogicExpression, Condition] type resolution
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
if sys.platform == 'win32':
|
||||
import io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, 'backend')
|
||||
|
||||
from workflow_models import LogicExpression, Condition, WorkflowNode
|
||||
import json
|
||||
|
||||
# Test 1: UI format (should be LogicExpression)
|
||||
print("\n" + "="*60)
|
||||
print("TEST 1: UI Format (direct LogicExpression)")
|
||||
print("="*60)
|
||||
|
||||
ui_format = {
|
||||
"operator": "and",
|
||||
"operands": [
|
||||
{"operator": "eq", "ref": "node_5.qTiefananalyseRecovery", "value": "ja"},
|
||||
{"operator": "neq", "ref": "node_6.qKonsistenz", "value": "nein"}
|
||||
]
|
||||
}
|
||||
|
||||
node = WorkflowNode(
|
||||
id="test_node",
|
||||
type="logic",
|
||||
condition=ui_format
|
||||
)
|
||||
|
||||
print(f"Input: {json.dumps(ui_format, indent=2)}")
|
||||
print(f"node.condition type: {type(node.condition).__name__}")
|
||||
print(f"Expected: LogicExpression")
|
||||
|
||||
if isinstance(node.condition, LogicExpression):
|
||||
print("✅ CORRECT: Deserialized as LogicExpression")
|
||||
print(f"Has operator: {hasattr(node.condition, 'operator')} = {node.condition.operator if hasattr(node.condition, 'operator') else 'N/A'}")
|
||||
print(f"Has operands: {hasattr(node.condition, 'operands')} = {len(node.condition.operands) if hasattr(node.condition, 'operands') and node.condition.operands else 'N/A'}")
|
||||
elif isinstance(node.condition, Condition):
|
||||
print("❌ WRONG: Deserialized as Condition (should be LogicExpression)")
|
||||
print(f"Has expression: {hasattr(node.condition, 'expression')} = {type(node.condition.expression).__name__ if hasattr(node.condition, 'expression') and node.condition.expression else 'N/A'}")
|
||||
if hasattr(node.condition, 'expression') and node.condition.expression:
|
||||
print(f"expression.operator: {node.condition.expression.operator}")
|
||||
print(f"expression.operands: {len(node.condition.expression.operands) if node.condition.expression.operands else 0}")
|
||||
else:
|
||||
print(f"❌ UNEXPECTED TYPE: {type(node.condition)}")
|
||||
|
||||
# Test 2: Legacy format (should be Condition)
|
||||
print("\n" + "="*60)
|
||||
print("TEST 2: Legacy Format (Condition with expression)")
|
||||
print("="*60)
|
||||
|
||||
legacy_format = {
|
||||
"type": "if",
|
||||
"expression": {
|
||||
"operator": "eq",
|
||||
"ref": "node_1.q1",
|
||||
"value": "ja"
|
||||
},
|
||||
"then_path": "edge_1",
|
||||
"else_path": "edge_2"
|
||||
}
|
||||
|
||||
node2 = WorkflowNode(
|
||||
id="test_node2",
|
||||
type="logic",
|
||||
condition=legacy_format
|
||||
)
|
||||
|
||||
print(f"Input: {json.dumps(legacy_format, indent=2)}")
|
||||
print(f"node.condition type: {type(node2.condition).__name__}")
|
||||
print(f"Expected: Condition")
|
||||
|
||||
if isinstance(node2.condition, Condition):
|
||||
print("✅ CORRECT: Deserialized as Condition")
|
||||
print(f"Has expression: {hasattr(node2.condition, 'expression')}")
|
||||
print(f"Has then_path: {hasattr(node2.condition, 'then_path')} = {node2.condition.then_path}")
|
||||
elif isinstance(node2.condition, LogicExpression):
|
||||
print("❌ WRONG: Deserialized as LogicExpression (should be Condition)")
|
||||
else:
|
||||
print(f"❌ UNEXPECTED TYPE: {type(node2.condition)}")
|
||||
|
||||
# Test 3: Check what executor would do
|
||||
print("\n" + "="*60)
|
||||
print("TEST 3: Executor Logic Simulation")
|
||||
print("="*60)
|
||||
|
||||
from workflow_models import LogicExpression, Condition
|
||||
|
||||
for test_name, node in [("UI Format", node), ("Legacy Format", node2)]:
|
||||
print(f"\n{test_name}:")
|
||||
print(f" condition type: {type(node.condition).__name__}")
|
||||
|
||||
if isinstance(node.condition, LogicExpression):
|
||||
print(" ✅ Executor would use: node.condition directly")
|
||||
expression = node.condition
|
||||
elif isinstance(node.condition, Condition):
|
||||
print(" ✅ Executor would use: node.condition.expression")
|
||||
expression = node.condition.expression if node.condition.expression else None
|
||||
else:
|
||||
print(f" ❌ Executor would fail: Unknown type {type(node.condition)}")
|
||||
expression = None
|
||||
|
||||
if expression:
|
||||
print(f" Expression type: {type(expression).__name__}")
|
||||
print(f" Expression operator: {expression.operator}")
|
||||
print(f" Expression has operands: {expression.operands is not None}")
|
||||
else:
|
||||
print(f" ❌ No expression found!")
|
||||
Reference in new issue
Block a user