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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
# app_integration.py
"""
Integration script to add Process Flow Visualization to the Research Assistant UI
This script modifies the existing app.py to include the process flow tab
"""

import gradio as gr
import logging
from typing import Dict, Any, List, Tuple
import time
from process_flow_visualizer import (
    create_process_flow_tab,
    update_process_flow_visualization,
    clear_flow_history,
    export_flow_data
)

logger = logging.getLogger(__name__)

def integrate_process_flow_into_app():
    """
    Integrate process flow visualization into the existing app structure
    """
    
    # Modified create_mobile_optimized_interface function
    def create_mobile_optimized_interface_with_flow():
        """Create the mobile-optimized Gradio interface with Process Flow tab"""
        
        interface_components = {}
        
        with gr.Blocks(
            title="AI Research Assistant MVP",
            theme=gr.themes.Soft(
                primary_hue="blue",
                secondary_hue="gray",
                font=("Inter", "system-ui", "sans-serif")
            ),
            css="""
            /* Mobile-first responsive CSS */
            .mobile-container {
                max-width: 100vw;
                margin: 0 auto;
                padding: 0 12px;
            }
            
            /* Touch-friendly button sizing */
            .gradio-button {
                min-height: 44px !important;
                min-width: 44px !important;
                font-size: 16px !important;
            }
            
            /* Mobile-optimized chat interface */
            .chatbot-container {
                height: 60vh !important;
                max-height: 60vh !important;
                overflow-y: auto !important;
                -webkit-overflow-scrolling: touch !important;
            }
            
            /* Process Flow specific styles */
            .process-flow-container {
                font-family: 'Inter', system-ui, sans-serif;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                border-radius: 12px;
                padding: 20px;
                margin: 10px 0;
                box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            }
            
            .flow-step {
                display: flex;
                align-items: center;
                margin: 15px 0;
                padding: 12px;
                background: rgba(255, 255, 255, 0.8);
                border-radius: 8px;
                border-left: 4px solid #4CAF50;
                transition: all 0.3s ease;
            }
            
            .flow-step:hover {
                transform: translateX(5px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
            }
            
            .metrics-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
                gap: 15px;
                margin-top: 20px;
            }
            
            .metric-card {
                background: rgba(255, 255, 255, 0.9);
                padding: 15px;
                border-radius: 8px;
                text-align: center;
                border-top: 3px solid #3498db;
            }
            
            /* Mobile input enhancements */
            .textbox-input {
                font-size: 16px !important;
                min-height: 44px !important;
                padding: 12px !important;
            }
            
            /* Responsive grid adjustments */
            @media (max-width: 768px) {
                .gradio-row {
                    flex-direction: column !important;
                    gap: 8px !important;
                }
                
                .gradio-column {
                    width: 100% !important;
                }
                
                .chatbot-container {
                    height: 50vh !important;
                }
                
                .flow-step {
                    flex-direction: column;
                    text-align: center;
                }
                
                .metrics-grid {
                    grid-template-columns: 1fr;
                }
            }
            
            /* Dark mode support */
            @media (prefers-color-scheme: dark) {
                body {
                    background: #1a1a1a;
                    color: #ffffff;
                }
            }
            
            /* Hide scrollbars but maintain functionality */
            .chatbot-container::-webkit-scrollbar {
                width: 4px;
            }
            
            /* Loading states */
            .loading-indicator {
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 20px;
            }
            
            /* Mobile menu enhancements */
            .accordion-content {
                max-height: 200px !important;
                overflow-y: auto !important;
            }
            """
        ) as demo:
            
            # Session Management (Mobile-Optimized)
            with gr.Column(elem_classes="mobile-container"):
                gr.Markdown("""
                # 🧠 Research Assistant
                *Academic AI with transparent reasoning*
                """)
                
                # Session Header Bar (Mobile-Friendly)
                with gr.Row():
                    session_info = gr.Textbox(
                        label="Session ID",
                        value=str(uuid.uuid4())[:8],
                        max_lines=1,
                        show_label=False,
                        container=False,
                        scale=3
                    )
                    interface_components['session_info'] = session_info
                    
                    new_session_btn = gr.Button(
                        "πŸ”„ New",
                        size="sm",
                        variant="secondary",
                        scale=1,
                        min_width=60
                    )
                    interface_components['new_session_btn'] = new_session_btn
                    
                    menu_toggle = gr.Button(
                        "βš™οΈ",
                        size="sm",
                        variant="secondary",
                        scale=1,
                        min_width=60
                    )
                    interface_components['menu_toggle'] = menu_toggle
                
                # Main Chat Area (Mobile-Optimized) - MODIFIED TO INCLUDE PROCESS FLOW TAB
                with gr.Tabs() as main_tabs:
                    with gr.TabItem("πŸ’¬ Chat", id="chat_tab"):
                        chatbot = gr.Chatbot(
                            label="",
                            show_label=False,
                            height="60vh",
                            elem_classes="chatbot-container",
                            type="messages"
                        )
                        interface_components['chatbot'] = chatbot
                        
                        # Mobile Input Area
                        with gr.Row():
                            message_input = gr.Textbox(
                                placeholder="Ask me anything...",
                                show_label=False,
                                max_lines=3,
                                container=False,
                                scale=4,
                                autofocus=True
                            )
                            interface_components['message_input'] = message_input
                            
                            send_btn = gr.Button(
                                "↑ Send",
                                variant="primary",
                                scale=1,
                                min_width=80
                            )
                            interface_components['send_btn'] = send_btn
                    
                    # Technical Details Tab (Collapsible for Mobile)
                    with gr.TabItem("πŸ” Details", id="details_tab"):
                        with gr.Accordion("Reasoning Chain", open=False):
                            reasoning_display = gr.JSON(
                                label="",
                                show_label=False
                            )
                            interface_components['reasoning_display'] = reasoning_display
                        
                        with gr.Accordion("Agent Performance", open=False):
                            performance_display = gr.JSON(
                                label="",
                                show_label=False
                            )
                            interface_components['performance_display'] = performance_display
                        
                        with gr.Accordion("Session Context", open=False):
                            context_display = gr.JSON(
                                label="",
                                show_label=False
                            )
                            interface_components['context_display'] = context_display
                    
                    # NEW: Process Flow Tab
                    process_flow_tab = create_process_flow_tab(interface_components)
                    interface_components['process_flow_tab'] = process_flow_tab
                
                # Mobile Bottom Navigation - MODIFIED TO INCLUDE PROCESS FLOW
                with gr.Row(visible=False, elem_id="mobile_nav") as mobile_navigation:
                    chat_nav_btn = gr.Button("πŸ’¬ Chat", variant="secondary", size="sm", min_width=0)
                    details_nav_btn = gr.Button("πŸ” Details", variant="secondary", size="sm", min_width=0)
                    flow_nav_btn = gr.Button("πŸ”„ Flow", variant="secondary", size="sm", min_width=0)
                    settings_nav_btn = gr.Button("βš™οΈ Settings", variant="secondary", size="sm", min_width=0)
                
                interface_components['mobile_navigation'] = mobile_navigation
                interface_components['flow_nav_btn'] = flow_nav_btn
            
            # Settings Panel (Modal for Mobile)
            with gr.Column(visible=False, elem_id="settings_panel") as settings:
                interface_components['settings_panel'] = settings
                
                with gr.Accordion("Display Options", open=True):
                    show_reasoning = gr.Checkbox(
                        label="Show reasoning chain",
                        value=True,
                        info="Display step-by-step reasoning"
                    )
                    interface_components['show_reasoning'] = show_reasoning
                    
                    show_agent_trace = gr.Checkbox(
                        label="Show agent execution trace",
                        value=False,
                        info="Display which agents processed your request"
                    )
                    interface_components['show_agent_trace'] = show_agent_trace
                    
                    show_process_flow = gr.Checkbox(
                        label="Show process flow visualization",
                        value=True,
                        info="Display detailed LLM inference and agent execution flow"
                    )
                    interface_components['show_process_flow'] = show_process_flow
                    
                    compact_mode = gr.Checkbox(
                        label="Compact mode",
                        value=False,
                        info="Optimize for smaller screens"
                    )
                    interface_components['compact_mode'] = compact_mode
                
                with gr.Accordion("Performance Options", open=False):
                    response_speed = gr.Radio(
                        choices=["Fast", "Balanced", "Thorough"],
                        value="Balanced",
                        label="Response Speed Preference"
                    )
                    interface_components['response_speed'] = response_speed
                    
                    cache_enabled = gr.Checkbox(
                        label="Enable context caching",
                        value=True,
                        info="Faster responses using session memory"
                    )
                    interface_components['cache_enabled'] = cache_enabled
                
                save_prefs_btn = gr.Button("Save Preferences", variant="primary")
                interface_components['save_prefs_btn'] = save_prefs_btn
        
        return demo, interface_components
    
    return create_mobile_optimized_interface_with_flow

def create_enhanced_chat_handler():
    """
    Create enhanced chat handler that includes process flow visualization
    """
    
    async def enhanced_chat_handler(message: str, history: List, session_id: str, 
                                  show_reasoning: bool, show_agent_trace: bool, 
                                  show_process_flow: bool, request: gr.Request) -> Tuple:
        """
        Enhanced chat handler with process flow visualization
        """
        start_time = time.time()
        
        try:
            # Import the existing process_message_async function
            from app import process_message_async
            
            # Process the message using existing logic
            result = await process_message_async(message, history, session_id)
            
            # Extract results
            updated_history, empty_string, reasoning_data, performance_data, context_data, session_id = result
            
            # Calculate processing time
            processing_time = time.time() - start_time
            
            # Prepare process flow data if enabled
            flow_updates = {}
            if show_process_flow:
                # Extract agent results from the processing
                intent_result = {
                    "primary_intent": "information_request",  # Default, would be extracted from actual processing
                    "confidence_scores": {"information_request": 0.8},
                    "secondary_intents": [],
                    "reasoning_chain": ["Step 1: Analyze user input", "Step 2: Determine intent"],
                    "context_tags": ["general"],
                    "processing_time": 0.15,
                    "agent_id": "INTENT_REC_001"
                }
                
                synthesis_result = {
                    "final_response": updated_history[-1]["content"] if updated_history else "",
                    "draft_response": "",
                    "source_references": ["INTENT_REC_001"],
                    "coherence_score": 0.85,
                    "synthesis_method": "llm_enhanced",
                    "intent_alignment": {"intent_detected": "information_request", "alignment_score": 0.8},
                    "processing_time": processing_time - 0.15,
                    "agent_id": "RESP_SYNTH_001"
                }
                
                safety_result = {
                    "original_response": updated_history[-1]["content"] if updated_history else "",
                    "safety_checked_response": updated_history[-1]["content"] if updated_history else "",
                    "warnings": [],
                    "safety_analysis": {
                        "toxicity_score": 0.1,
                        "bias_indicators": [],
                        "privacy_concerns": [],
                        "overall_safety_score": 0.9,
                        "confidence_scores": {"safety": 0.9}
                    },
                    "blocked": False,
                    "processing_time": 0.1,
                    "agent_id": "SAFETY_BIAS_001"
                }
                
                # Update process flow visualization
                flow_updates = update_process_flow_visualization(
                    user_input=message,
                    intent_result=intent_result,
                    synthesis_result=synthesis_result,
                    safety_result=safety_result,
                    final_response=updated_history[-1]["content"] if updated_history else "",
                    session_id=session_id,
                    processing_time=processing_time
                )
            
            # Return all updates
            return (
                updated_history,  # chatbot
                empty_string,    # message_input
                reasoning_data,  # reasoning_display
                performance_data, # performance_display
                context_data,    # context_display
                session_id,      # session_info
                flow_updates.get("flow_display", ""),  # flow_display
                flow_updates.get("flow_stats", {}),   # flow_stats
                flow_updates.get("performance_metrics", {}), # performance_metrics
                flow_updates.get("intent_details", {}), # intent_details
                flow_updates.get("synthesis_details", {}), # synthesis_details
                flow_updates.get("safety_details", {}) # safety_details
            )
            
        except Exception as e:
            logger.error(f"Error in enhanced chat handler: {e}")
            # Return error state
            error_history = list(history) if history else []
            error_history.append({"role": "user", "content": message})
            error_history.append({"role": "assistant", "content": f"Error: {str(e)}"})
            
            return (
                error_history,  # chatbot
                "",             # message_input
                {"error": str(e)}, # reasoning_display
                {"error": str(e)}, # performance_display
                {"error": str(e)}, # context_display
                session_id,     # session_info
                "",             # flow_display
                {"error": str(e)}, # flow_stats
                {"error": str(e)}, # performance_metrics
                {},             # intent_details
                {},             # synthesis_details
                {}              # safety_details
            )
    
    return enhanced_chat_handler

def setup_process_flow_event_handlers(interface_components: Dict[str, Any]):
    """
    Setup event handlers for process flow components
    """
    
    # Clear flow history button
    if 'clear_flow_btn' in interface_components:
        interface_components['clear_flow_btn'].click(
            fn=clear_flow_history,
            outputs=[
                interface_components.get('flow_display'),
                interface_components.get('flow_stats'),
                interface_components.get('performance_metrics'),
                interface_components.get('intent_details'),
                interface_components.get('synthesis_details'),
                interface_components.get('safety_details')
            ]
        )
    
    # Export flow data button
    if 'export_flow_btn' in interface_components:
        interface_components['export_flow_btn'].click(
            fn=export_flow_data,
            outputs=[gr.File(label="Download Flow Data")]
        )
    
    # Share flow button (placeholder)
    if 'share_flow_btn' in interface_components:
        interface_components['share_flow_btn'].click(
            fn=lambda: gr.Info("Flow sharing feature coming soon!"),
            outputs=[]
        )

# Main integration function
def integrate_process_flow():
    """
    Main function to integrate process flow visualization
    """
    logger.info("Integrating Process Flow Visualization into Research Assistant UI")
    
    # This would be called from your main app.py file
    # The integration modifies the existing interface to include the process flow tab
    
    return {
        "create_interface": integrate_process_flow_into_app(),
        "create_handler": create_enhanced_chat_handler(),
        "setup_handlers": setup_process_flow_event_handlers
    }

if __name__ == "__main__":
    # Test the integration
    integration = integrate_process_flow()
    print("Process Flow Visualization integration ready!")
    print("Available functions:")
    print("- create_interface: Modified interface creation")
    print("- create_handler: Enhanced chat handler")
    print("- setup_handlers: Event handler setup")