-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1613 lines (1316 loc) · 62.8 KB
/
Copy pathapp.py
File metadata and controls
1613 lines (1316 loc) · 62.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Multi-Agent Development System - Streamlit Interface
This module provides a Streamlit-based web interface for the multi-agent development system,
allowing users to:
1. View and manage agents
2. Submit and monitor tasks
3. Create and execute workflows
4. Review and provide feedback on completed tasks
5. Monitor system performance
6. View context and shared memory
Usage:
streamlit run app.py
"""
import asyncio
import json
import logging
import os
import sys
import time
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple, Union
import traceback
import uuid
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import streamlit as st
import yaml
from streamlit_ace import st_ace
# Add the parent directory to the path to allow importing the system modules
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# Import system components
from config.system_config import SystemConfig, get_system_config
from config.agent_config import AgentConfig
from memory.shared_memory import SharedMemory
from memory.context_store import ContextStore, ContextType
from agents.base_agent import BaseAgent, ModelProvider, AgentRole, TaskStatus, TaskPriority
from human_interface.review_interface import ReviewInterface, ReviewStatus, FeedbackType, FeedbackItem
from human_interface.feedback_processor import FeedbackProcessor
from orchestrator.workflow_engine import WorkflowEngine
from orchestrator.task_scheduler import TaskScheduler
from main import MultiAgentSystem
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Set page config
st.set_page_config(
page_title="Multi-Agent Development System",
page_icon="🤖",
layout="wide",
initial_sidebar_state="expanded"
)
# Constants
REFRESH_INTERVAL = 10 # seconds
# Color schemes
COLORS = {
"primary": "#1E88E5",
"success": "#4CAF50",
"warning": "#FFC107",
"error": "#F44336",
"info": "#03A9F4",
"background": "#F0F2F6",
"text": "#212121",
"agent_types": {
"project_manager": "#D81B60",
"architecture_designer": "#1E88E5",
"ui_developer": "#8E24AA",
"frontend_logic": "#3949AB",
"frontend_integration": "#00ACC1",
"api_developer": "#43A047",
"database_designer": "#E53935",
"backend_logic": "#FB8C00",
"infrastructure": "#5E35B1",
"deployment": "#1E88E5",
"security": "#E53935",
"code_reviewer": "#00897B",
"test_developer": "#7CB342",
"ux_tester": "#FFB300",
"researcher": "#039BE5",
"documentation": "#8D6E63",
"human_interface": "#F06292"
}
}
# Utility Functions
def run_async(coroutine):
"""Run an async function in a sync context."""
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(coroutine)
finally:
loop.close()
def format_time(seconds):
"""Format seconds into a readable time string."""
if seconds is None:
return "N/A"
if seconds < 60:
return f"{seconds:.2f}s"
elif seconds < 3600:
minutes = seconds / 60
return f"{minutes:.2f}m"
else:
hours = seconds / 3600
return f"{hours:.2f}h"
def format_datetime(iso_string):
"""Format ISO datetime string into a readable format."""
if not iso_string:
return "N/A"
try:
dt = datetime.fromisoformat(iso_string.replace('Z', '+00:00'))
return dt.strftime("%Y-%m-%d %H:%M:%S")
except:
return iso_string
def truncate_text(text, max_length=100):
"""Truncate text and add ellipsis if needed."""
if not text:
return ""
return text if len(text) <= max_length else text[:max_length] + "..."
def init_session_state():
"""Initialize session state variables."""
if 'system' not in st.session_state:
st.session_state.system = None
if 'agent_filter' not in st.session_state:
st.session_state.agent_filter = "all"
if 'refresh_data' not in st.session_state:
st.session_state.refresh_data = True
if 'last_refresh' not in st.session_state:
st.session_state.last_refresh = datetime.now()
if 'selected_task' not in st.session_state:
st.session_state.selected_task = None
if 'task_results' not in st.session_state:
st.session_state.task_results = {}
if 'workflow_executions' not in st.session_state:
st.session_state.workflow_executions = {}
if 'feedback_items' not in st.session_state:
st.session_state.feedback_items = []
if 'system_metrics' not in st.session_state:
st.session_state.system_metrics = []
if 'context_entries' not in st.session_state:
st.session_state.context_entries = []
# Add missing debug_mode
if 'debug_mode' not in st.session_state:
st.session_state.debug_mode = False
def initialize_system():
"""Initialize the multi-agent system."""
try:
if 'system' in st.session_state and st.session_state.system:
# System already initialized
return st.session_state.system
# Get configuration path
config_path = st.session_state.get('config_path', None)
# Create and initialize the system
system = MultiAgentSystem(
config_path=config_path,
debug=st.session_state.get('debug_mode', False),
model_provider=st.session_state.get('model_provider', None)
)
# Initialize the system
run_async(system.initialize())
st.session_state.system = system
logger.info("Multi-agent system initialized")
return system
except Exception as e:
st.error(f"Error initializing system: {str(e)}")
st.error(traceback.format_exc())
return None
def shutdown_system():
"""Shut down the multi-agent system."""
if 'system' in st.session_state and st.session_state.system:
try:
run_async(st.session_state.system.shutdown())
st.session_state.system = None
logger.info("Multi-agent system shut down")
except Exception as e:
st.error(f"Error shutting down system: {str(e)}")
def refresh_data():
"""Refresh all data from the system."""
if not st.session_state.system:
return
try:
# Update last refresh time
st.session_state.last_refresh = datetime.now()
# Get system status
status = run_async(st.session_state.system.get_system_status())
st.session_state.system_status = status
# Get agent information
agents = run_async(st.session_state.system.get_agent_info())
st.session_state.agents = agents
# Get task data (from shared memory)
if st.session_state.system.shared_memory:
# Fix: Get task keys asynchronously
task_keys = run_async(st.session_state.system.shared_memory.get_keys(category="tasks"))
# Now task_keys is a list, not a coroutine
st.session_state.tasks = {}
for key in task_keys:
# Also retrieve each item asynchronously
task_data = run_async(st.session_state.system.shared_memory.retrieve(key, "tasks"))
st.session_state.tasks[key] = task_data
# Update task results - fix the same issue here
result_keys = run_async(st.session_state.system.shared_memory.get_keys(category="task_results"))
st.session_state.task_results = {}
for key in result_keys:
result_data = run_async(st.session_state.system.shared_memory.retrieve(key, "task_results"))
st.session_state.task_results[key] = result_data
# Update system metrics history
if hasattr(st.session_state, 'system_status'):
metrics = {
'timestamp': datetime.now().isoformat(),
'uptime': status.get('uptime_seconds', 0),
'agents': len(st.session_state.agents),
'tasks_total': status.get('tasks', {}).get('total', 0),
'tasks_completed': status.get('tasks', {}).get('completed', 0),
'tasks_failed': status.get('tasks', {}).get('failed', 0),
}
if 'system_metrics' not in st.session_state:
st.session_state.system_metrics = []
st.session_state.system_metrics.append(metrics)
# Keep only the last 100 metrics points
if len(st.session_state.system_metrics) > 100:
st.session_state.system_metrics = st.session_state.system_metrics[-100:]
# Schedule next refresh
st.session_state.refresh_data = True
except Exception as e:
st.error(f"Error refreshing data: {str(e)}")
st.error(traceback.format_exc())
# UI Components
def render_sidebar():
"""Render the sidebar with system controls and navigation."""
st.sidebar.title("🤖 Multi-Agent Dev System")
# System status indicator
if 'system' in st.session_state and st.session_state.system:
status = st.session_state.get('system_status', {})
status_color = "green" if status.get('status') == "running" else "red"
st.sidebar.markdown(
f"<div style='display:flex;align-items:center;'>"
f"<div style='width:12px;height:12px;border-radius:50%;background-color:{status_color};margin-right:8px;'></div>"
f"<span><strong>Status:</strong> {status.get('status', 'unknown').upper()}</span>"
f"</div>",
unsafe_allow_html=True
)
# Version and uptime
st.sidebar.markdown(f"**Version:** {status.get('version', 'unknown')}")
st.sidebar.markdown(f"**Uptime:** {format_time(status.get('uptime_seconds', 0))}")
# Divider
st.sidebar.divider()
# Navigation menu
page = st.sidebar.radio(
"Navigation",
["Dashboard", "Agents", "Tasks", "Workflows", "Context Storage", "Feedback", "Settings"]
)
# Filters for agents page
if page == "Agents":
st.sidebar.subheader("Filter Agents")
agent_types = ["all"] + [agent['type'] for agent in st.session_state.get('agents', [])]
agent_types = list(set(agent_types)) # Remove duplicates
st.session_state.agent_filter = st.sidebar.selectbox("Agent Type", agent_types)
# Filters for tasks page
elif page == "Tasks":
st.sidebar.subheader("Filter Tasks")
# Task status filter
task_statuses = ["all", "pending", "in_progress", "completed", "failed"]
status_filter = st.sidebar.selectbox("Status", task_statuses)
st.session_state.task_status_filter = status_filter
# Task agent filter
agent_names = ["all"] + [agent['name'] for agent in st.session_state.get('agents', [])]
agent_filter = st.sidebar.selectbox("Agent", agent_names)
st.session_state.task_agent_filter = agent_filter
# Actions section
st.sidebar.divider()
st.sidebar.subheader("Actions")
if 'system' not in st.session_state or st.session_state.system is None:
if st.sidebar.button("Initialize System", use_container_width=True):
initialize_system()
else:
if st.sidebar.button("Shutdown System", use_container_width=True):
shutdown_system()
# Manual refresh button
if st.sidebar.button("Refresh Data", use_container_width=True):
refresh_data()
# Last refresh time
if 'last_refresh' in st.session_state:
st.sidebar.caption(f"Last refreshed: {st.session_state.last_refresh.strftime('%H:%M:%S')}")
return page
def render_dashboard():
"""Render the main dashboard with system overview and statistics."""
st.title("🚀 Multi-Agent Development System Dashboard")
if not st.session_state.system:
st.info("System not initialized. Please initialize the system from the sidebar.")
return
# System status overview
status = st.session_state.get('system_status', {})
agents = st.session_state.get('agents', [])
# Key metrics in columns
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Active Agents", len(agents))
with col2:
tasks_total = status.get('tasks', {}).get('total', 0)
st.metric("Total Tasks", tasks_total)
with col3:
tasks_completed = status.get('tasks', {}).get('completed', 0)
completion_rate = f"{(tasks_completed / max(1, tasks_total)) * 100:.1f}%"
st.metric("Tasks Completed", f"{tasks_completed} ({completion_rate})")
with col4:
tasks_failed = status.get('tasks', {}).get('failed', 0)
failure_rate = f"{(tasks_failed / max(1, tasks_total)) * 100:.1f}%"
st.metric("Tasks Failed", f"{tasks_failed} ({failure_rate})")
# System activity charts
st.subheader("System Activity")
tab1, tab2, tab3 = st.tabs(["Tasks", "Agent Distribution", "Performance Metrics"])
with tab1:
if 'system_metrics' in st.session_state and st.session_state.system_metrics:
# Convert metrics to DataFrame
df = pd.DataFrame(st.session_state.system_metrics)
# Convert timestamp to datetime
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Create task status chart
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['tasks_total'],
mode='lines+markers',
name='Total',
line=dict(color=COLORS["primary"])
))
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['tasks_completed'],
mode='lines+markers',
name='Completed',
line=dict(color=COLORS["success"])
))
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['tasks_failed'],
mode='lines+markers',
name='Failed',
line=dict(color=COLORS["error"])
))
fig.update_layout(
title="Task Status Over Time",
xaxis_title="Time",
yaxis_title="Tasks",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
height=400,
margin=dict(l=20, r=20, t=40, b=20)
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No metrics data available yet. Wait for the system to gather more data.")
with tab2:
# Agent distribution by type
if agents:
agent_types = {}
for agent in agents:
agent_type = agent['type']
if agent_type in agent_types:
agent_types[agent_type] += 1
else:
agent_types[agent_type] = 1
# Create a bar chart
fig = px.bar(
x=list(agent_types.keys()),
y=list(agent_types.values()),
labels={'x': 'Agent Type', 'y': 'Count'},
title="Agent Distribution by Type",
color=list(agent_types.keys()),
color_discrete_map={k: COLORS["agent_types"].get(k, COLORS["primary"]) for k in agent_types.keys()}
)
fig.update_layout(
xaxis={'categoryorder': 'total descending'},
height=400,
margin=dict(l=20, r=20, t=40, b=20)
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No agents available. Initialize the system with agents.")
with tab3:
# Performance metrics
if 'task_results' in st.session_state and st.session_state.task_results:
# Get execution times
execution_times = []
for result in st.session_state.task_results.values():
if isinstance(result, dict) and 'execution_time' in result:
agent_name = result.get('agent', 'Unknown')
execution_times.append({
'agent': agent_name,
'execution_time': result['execution_time']
})
if execution_times:
df = pd.DataFrame(execution_times)
# Calculate average execution time by agent
avg_times = df.groupby('agent')['execution_time'].mean().reset_index()
# Create a bar chart
fig = px.bar(
avg_times,
x='agent',
y='execution_time',
labels={'agent': 'Agent', 'execution_time': 'Avg. Execution Time (s)'},
title="Average Task Execution Time by Agent",
color='agent',
color_discrete_sequence=[COLORS["primary"]]
)
fig.update_layout(
xaxis={'categoryorder': 'total descending'},
height=400,
margin=dict(l=20, r=20, t=40, b=20)
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No performance data available yet.")
else:
st.info("No task results available to analyze performance.")
# Recent activity
st.subheader("Recent Activity")
# Get recent tasks
recent_tasks = []
if 'tasks' in st.session_state and st.session_state.tasks:
for task_id, task in st.session_state.tasks.items():
if isinstance(task, dict):
recent_tasks.append({
'id': task_id,
'description': task.get('description', 'No description'),
'agent': task.get('agent_type', 'Unknown'),
'status': task.get('status', 'unknown'),
'timestamp': task.get('timestamp', None)
})
# Sort by timestamp (newest first)
recent_tasks.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
# Show only the 10 most recent
recent_tasks = recent_tasks[:10]
if recent_tasks:
task_df = pd.DataFrame(recent_tasks)
st.dataframe(
task_df,
column_config={
"id": "Task ID",
"description": "Description",
"agent": "Agent",
"status": st.column_config.SelectboxColumn(
"Status",
help="Task status",
options=["pending", "in_progress", "completed", "failed"],
required=True
),
"timestamp": "Timestamp"
},
hide_index=True,
use_container_width=True
)
else:
st.info("No recent tasks available.")
def render_agents_page():
"""Render the agents management page."""
st.title("👥 Agent Management")
if not st.session_state.system:
st.info("System not initialized. Please initialize the system from the sidebar.")
return
agents = st.session_state.get('agents', [])
if not agents:
st.warning("No agents found in the system.")
return
# Filter agents if needed
if st.session_state.agent_filter != "all":
agents = [a for a in agents if a['type'] == st.session_state.agent_filter]
# Display agents in an expandable format
for i, agent in enumerate(agents):
with st.expander(f"{agent['name']} ({agent['type']})", expanded=i == 0):
col1, col2 = st.columns([1, 1])
with col1:
st.write("**Agent Details:**")
st.write(f"**ID:** {agent['id']}")
st.write(f"**Type:** {agent['type']}")
st.write(f"**Model:** {agent.get('model', 'Unknown')}")
# If there are agent stats available
if 'stats' in agent:
with col2:
st.write("**Performance Stats:**")
stats = agent['stats']
st.write(f"**Tasks Completed:** {stats.get('tasks_completed', 0)}")
st.write(f"**Success Rate:** {stats.get('success_rate', 0):.1f}%")
st.write(f"**Avg. Execution Time:** {format_time(stats.get('average_execution_time', 0))}")
# Agent actions
st.write("**Actions:**")
# Task submission form
with st.form(key=f"submit_task_form_{agent['id']}"):
st.subheader("Submit a task to this agent")
task_title = st.text_input("Task Title", key=f"title_{agent['id']}")
task_desc = st.text_area("Task Description", key=f"desc_{agent['id']}")
col1, col2 = st.columns(2)
with col1:
task_action = st.selectbox(
"Action",
["generate_code", "review_code", "analyze", "design", "explain", "summarize", "other"],
key=f"action_{agent['id']}"
)
with col2:
task_priority = st.selectbox(
"Priority",
["low", "medium", "high", "critical"],
index=1,
key=f"priority_{agent['id']}"
)
task_params = st.text_area(
"Parameters (JSON format)",
'{\n "param1": "value1",\n "param2": "value2"\n}',
key=f"params_{agent['id']}"
)
submit_button = st.form_submit_button("Submit Task")
if submit_button:
try:
# Parse parameters
params = json.loads(task_params)
# Check if agent was selected
# Create task definition without workflow reference
selected_agent = next((agent for agent in agents if agent['id'] == agent['id']), None)
if not selected_agent:
raise ValueError("Selected agent not found")
# Prepare task definition
task_def = {
"title": task_title,
"description": task_desc,
"agent_id": selected_agent['id'],
"agent_type": selected_agent['type'],
"action": task_action,
"params": params,
"priority": task_priority,
"tags": [agent['type'], task_action],
"category": "default",
"status": "pending", # Add explicit status
"timestamp": datetime.now().isoformat()
}
# Submit the task
task_id = run_async(st.session_state.system.submit_task(task_def))
st.success(f"Task submitted successfully! Task ID: {task_id}")
# Refresh data after submission
refresh_data()
except json.JSONDecodeError:
st.error("Invalid JSON format for parameters")
except Exception as e:
st.error(f"Error submitting task: {str(e)}")
# Recent tasks by this agent
if 'tasks' in st.session_state and st.session_state.tasks:
agent_tasks = []
for task_id, task in st.session_state.tasks.items():
if isinstance(task, dict) and task.get('agent_id') == agent['id']:
agent_tasks.append({
'id': task_id,
'title': task.get('title', 'No title'),
'status': task.get('status', 'unknown'),
'timestamp': format_datetime(task.get('timestamp', None))
})
if agent_tasks:
st.subheader("Recent Tasks")
# Sort by timestamp (newest first)
agent_tasks.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
# Show only the 5 most recent
agent_tasks = agent_tasks[:5]
# Display as a table
task_df = pd.DataFrame(agent_tasks)
st.dataframe(task_df, hide_index=True, use_container_width=True)
else:
st.info("No recent tasks for this agent.")
def render_tasks_page():
"""Render the tasks management page."""
st.title("📋 Task Management")
if not st.session_state.system:
st.info("System not initialized. Please initialize the system from the sidebar.")
return
if st.session_state.debug_mode:
st.write("Shared memory status:", "Available" if st.session_state.system.shared_memory else "Not available")
debug_mode = st.session_state.get('debug_mode', False)
if debug_mode:
st.write("Shared memory status:", "Available" if st.session_state.system.shared_memory else "Not available")
tasks = []
if 'tasks' in st.session_state and st.session_state.tasks:
st.write(f"Task data found: {len(st.session_state.tasks)} tasks")
for task_id, task in st.session_state.tasks.items():
if st.session_state.debug_mode:
st.write(f"Task ID: {task_id}, Raw data:", task)
if isinstance(task, dict):
tasks.append({
'id': task_id,
'title': task.get('title', 'No title'),
'description': task.get('description', 'No description'),
'agent_type': task.get('agent_type', 'Unknown'),
'agent_id': task.get('agent_id', ''),
'status': task.get('status', 'unknown'),
'priority': task.get('priority', 'medium'),
'timestamp': task.get('timestamp', None),
'formatted_time': format_datetime(task.get('timestamp', None))
})
else:
st.warning("No tasks found in session state.")
if not tasks:
st.warning("No tasks found in the system.")
# New task submission form
with st.form(key="create_new_task_form"):
st.subheader("Create a New Task")
# Get agent options
agents = st.session_state.get('agents', [])
agent_options = [("", "Select an agent...")] + [(a['id'], f"{a['name']} ({a['type']})") for a in agents]
task_title = st.text_input("Task Title")
task_desc = st.text_area("Task Description")
col1, col2 = st.columns(2)
with col1:
selected_agent_id = st.selectbox(
"Agent",
[a[0] for a in agent_options],
format_func=lambda x: next((a[1] for a in agent_options if a[0] == x), x),
index=0
)
with col2:
task_priority = st.selectbox(
"Priority",
["low", "medium", "high", "critical"],
index=1
)
task_action = st.selectbox(
"Action",
["generate_code", "review_code", "analyze", "design", "explain", "summarize", "other"]
)
task_params = st.text_area(
"Parameters (JSON format)",
'{\n "param1": "value1",\n "param2": "value2"\n}'
)
submit_button = st.form_submit_button("Submit Task")
if submit_button:
if not selected_agent_id:
st.error("Please select an agent")
else:
try:
# Find selected agent
selected_agent = next((a for a in agents if a['id'] == selected_agent_id), None)
if not selected_agent:
st.error("Invalid agent selection")
else:
# Parse parameters
params = json.loads(task_params)
# Prepare task definition
task_def = {
"title": task_title,
"description": task_desc,
"agent_id": selected_agent['id'],
"agent_type": selected_agent['type'],
"action": task_action,
"params": params,
"priority": task_priority,
"tags": [selected_agent['type'], task_action],
"category": "default"
}
# Submit the task
task_id = run_async(st.session_state.system.submit_task(task_def))
st.success(f"Task submitted successfully! Task ID: {task_id}")
# Refresh data after submission
refresh_data()
except json.JSONDecodeError:
st.error("Invalid JSON format for parameters")
except Exception as e:
st.error(f"Error submitting task: {str(e)}")
return
# Apply filters
status_filter = st.session_state.get('task_status_filter', 'all')
agent_filter = st.session_state.get('task_agent_filter', 'all')
filtered_tasks = tasks
if status_filter != 'all':
filtered_tasks = [t for t in filtered_tasks if t['status'] == status_filter]
if agent_filter != 'all':
filtered_tasks = [t for t in filtered_tasks if t['agent_type'] == agent_filter]
# Sort tasks by timestamp (newest first)
filtered_tasks.sort(key=lambda x: x.get('timestamp', ''), reverse=True)
# Create a dataframe for display
task_df = pd.DataFrame([
{
'ID': t['id'],
'Title': t['title'],
'Agent': t['agent_type'],
'Status': t['status'],
'Priority': t['priority'],
'Created': t['formatted_time']
}
for t in filtered_tasks
])
# Task list
st.subheader(f"Tasks ({len(filtered_tasks)})")
if len(filtered_tasks) > 0:
# Use a dataframe with selection
selected_row = st.dataframe(
task_df,
use_container_width=True,
column_config={
"Status": st.column_config.SelectboxColumn(
"Status",
options=["pending", "in_progress", "completed", "failed"],
required=True
),
"Priority": st.column_config.SelectboxColumn(
"Priority",
options=["low", "medium", "high", "critical"],
required=True
)
},
hide_index=True
)
# If a task is selected, show details
task_id = st.selectbox("Select a task to view details:", [t['id'] for t in filtered_tasks])
if task_id:
st.session_state.selected_task = task_id
# Show selected task details
if st.session_state.selected_task:
selected_task = next((t for t in tasks if t['id'] == st.session_state.selected_task), None)
if selected_task:
st.subheader(f"Task Details: {selected_task['title']}")
# Display task details and results
col1, col2 = st.columns([3, 2])
with col1:
st.write("**Basic Information:**")
st.write(f"**ID:** {selected_task['id']}")
st.write(f"**Description:** {selected_task['description']}")
st.write(f"**Agent:** {selected_task['agent_type']}")
st.write(f"**Status:** {selected_task['status']}")
st.write(f"**Priority:** {selected_task['priority']}")
st.write(f"**Created:** {selected_task['formatted_time']}")
# Display task result if available
task_result = None
if 'task_results' in st.session_state:
task_result = st.session_state.task_results.get(selected_task['id'])
if task_result:
st.subheader("Task Result")
if isinstance(task_result, dict) and 'result' in task_result:
result = task_result['result']
# Check if result contains code
if isinstance(result, str) and (
result.strip().startswith("```") or
"</" in result or
"function " in result or
"class " in result or
"import " in result
):
st.code(result)
else:
st.write(result)
# Display execution stats
if 'execution_time' in task_result:
st.caption(f"Execution time: {format_time(task_result['execution_time'])}")
else:
st.write(task_result)
else:
st.info("No results available for this task yet.")
with col2:
# Task actions
st.subheader("Actions")
# Cancel task button (only for pending/in_progress)
if selected_task['status'] in ['pending', 'in_progress']:
if st.button("Cancel Task", key=f"cancel_{selected_task['id']}"):
try:
# Not implemented in base system, would need to add this
st.warning("Task cancellation not implemented yet.")
refresh_data()
except Exception as e:
st.error(f"Error canceling task: {str(e)}")
# Add feedback (for completed tasks)
if selected_task['status'] == 'completed':
with st.form(key=f"feedback_form_{selected_task['id']}"):
st.subheader("Provide Feedback")
feedback_status = st.selectbox(
"Review Status",
["APPROVED", "PARTIALLY_APPROVED", "NEEDS_CLARIFICATION", "REJECTED"],
index=0
)
feedback_comment = st.text_area("General Feedback")
# Specific feedback items
st.write("**Feedback Items:**")
feedback_type = st.selectbox(
"Type",
["CODE_QUALITY", "FUNCTIONALITY", "DESIGN", "DOCUMENTATION", "GENERAL"]
)
feedback_severity = st.selectbox(
"Severity",
["LOW", "MEDIUM", "HIGH", "CRITICAL"],
index=1
)
specific_comment = st.text_area("Specific Comment")
suggested_changes = st.text_area("Suggested Changes")
submit_feedback = st.form_submit_button("Submit Feedback")
if submit_feedback:
try:
# Prepare feedback data
feedback_data = {
"task_id": selected_task['id'],
"reviewer_id": "human_user",
"status": feedback_status,
"summary": feedback_comment,
"feedback_items": [
{
"id": str(uuid.uuid4()),
"feedback_type": feedback_type,
"comment": specific_comment,
"suggested_changes": suggested_changes,
"severity": feedback_severity
}
]
}
# Submit feedback
result = run_async(st.session_state.system.submit_feedback(feedback_data))
st.success(f"Feedback submitted successfully!")
# Refresh data
refresh_data()
except Exception as e:
st.error(f"Error submitting feedback: {str(e)}")
def render_workflows_page():
"""Render the workflows management page."""
st.title("🔄 Workflow Management")
if not st.session_state.system:
st.info("System not initialized. Please initialize the system from the sidebar.")
return
# Workflow tabs
tab1, tab2 = st.tabs(["Create Workflow", "View Workflows"])
with tab1:
st.subheader("Define a New Workflow")
with st.form(key="create_workflow_form"):
workflow_name = st.text_input("Workflow Name")
workflow_desc = st.text_area("Description")