File size: 27,041 Bytes
672aa93
 
 
 
 
7a06434
a3169f8
672aa93
 
 
a72ab2b
672aa93
7a29eba
70bc965
 
 
 
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70bc965
 
672aa93
 
 
 
 
 
70bc965
 
672aa93
70bc965
 
672aa93
 
a10b590
7a06434
a10b590
 
 
 
 
 
 
 
 
672aa93
70bc965
 
 
 
 
 
 
f02beae
70bc965
 
 
f02beae
70bc965
 
 
 
a10b590
 
 
 
 
 
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1d8b79
a10b590
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a06434
672aa93
 
 
 
 
 
 
a10b590
672aa93
 
 
 
a10b590
 
672aa93
a10b590
 
 
 
 
 
 
 
 
672aa93
 
 
 
 
 
a10b590
a1d8b79
7a29eba
 
 
 
a1d8b79
 
7a29eba
 
672aa93
 
 
 
 
 
 
 
 
 
 
a1d8b79
a3169f8
672aa93
7a29eba
672aa93
 
 
 
 
a1d8b79
a10b590
672aa93
 
 
 
 
 
 
 
a3169f8
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a10b590
7a29eba
 
 
672aa93
 
 
 
 
 
 
 
 
 
a10b590
672aa93
a3169f8
 
672aa93
 
 
 
 
 
 
a3169f8
672aa93
 
a3169f8
672aa93
 
 
 
 
 
 
7a06434
672aa93
 
 
 
 
 
 
 
 
 
 
 
a10b590
 
 
 
 
7a06434
a10b590
 
672aa93
 
a10b590
7a29eba
 
 
 
 
 
 
 
 
 
672aa93
 
 
 
a3169f8
 
 
7a06434
 
 
 
 
 
a3169f8
 
7a06434
 
a3169f8
7a06434
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3169f8
a10b590
 
7a06434
a10b590
 
 
 
 
 
7a06434
 
 
 
 
 
 
 
a10b590
a3169f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a29eba
672aa93
 
 
 
 
a10b590
 
672aa93
 
 
 
 
 
 
 
 
 
 
a1d8b79
a10b590
7a06434
a3169f8
 
672aa93
 
a72ab2b
672aa93
 
 
a3169f8
a10b590
a3169f8
a10b590
7a29eba
672aa93
 
 
 
 
70bc965
672aa93
 
 
 
 
a10b590
7a06434
672aa93
 
 
 
 
 
9a4c86a
672aa93
 
 
 
987b6b5
a72ab2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
672aa93
 
 
 
 
70bc965
672aa93
 
 
 
 
a10b590
7a06434
672aa93
 
 
 
 
 
9a4c86a
672aa93
 
 
 
 
 
 
a10b590
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
a3169f8
 
 
 
 
 
 
 
 
 
 
 
a10b590
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a10b590
672aa93
 
 
a1d8b79
672aa93
 
a10b590
672aa93
 
 
 
 
 
a1d8b79
a3169f8
672aa93
 
a3169f8
 
a10b590
 
a3169f8
 
a10b590
 
a3169f8
 
 
 
 
 
 
672aa93
 
 
 
 
 
 
 
 
a3169f8
672aa93
 
 
 
 
 
 
 
 
 
 
 
 
a1d8b79
a10b590
7a06434
a3169f8
 
672aa93
 
 
 
7a29eba
672aa93
 
 
 
 
 
a10b590
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
import gradio as gr
import requests
import json
import os
import time
import tempfile
import re
from configparser import ConfigParser
from typing import List, Dict, Any

MCP_SERVER_URL = "https://mcp-1st-birthday-project-conductor-core-mcp.hf.space/execute"

# HARDCODED PROVIDER MAPPING
PROVIDER_MODEL_MAPPING = {
    "Google Gemini": [],
    "Anthropic": [],
    "OpenAI": [],
    "Custom": []
}

def classify_model_by_provider(model_label: str) -> str:
    """Classify a model label into a provider category using keyword matching"""
    label_lower = model_label.lower()
    
    if 'gemini' in label_lower:
        return "Google Gemini"
    elif 'claude' in label_lower or 'anthropic' in label_lower:
        return "Anthropic"
    elif 'gpt' in label_lower or 'openai' in label_lower:
        return "OpenAI"
    else:
        return "Custom"

def load_client_config():
    config = {}
    coder_models = {}
    strategist_models = {}
    
    if os.path.exists('config.ini'):
        parser = ConfigParser()
        parser.read('config.ini')
        try:
            if 'CODER_MODELS' in parser:
                for label, entry in parser['CODER_MODELS'].items():
                    coder_models[label] = label
            if 'STRATEGIST_MODELS' in parser:
                for label, entry in parser['STRATEGIST_MODELS'].items():
                    strategist_models[label] = label
        except Exception as e:
            print(f"Config parsing warning: {e}")
        
        # Read defaults from config.ini [API] section
        if 'API' in parser:
            config['coder_default'] = parser['API'].get('coder_model_default_label', '').strip()
            config['strategist_default'] = parser['API'].get('strategist_model_default_label', '').strip()
        else:
            config['coder_default'] = ''
            config['strategist_default'] = ''
    else:
        config['coder_default'] = ''
        config['strategist_default'] = ''

    # Build provider-grouped structure
    coder_by_provider = {p: [] for p in PROVIDER_MODEL_MAPPING.keys()}
    strategist_by_provider = {p: [] for p in PROVIDER_MODEL_MAPPING.keys()}
    
    for label in coder_models.keys():
        provider = classify_model_by_provider(label)
        coder_by_provider[provider].append(label)
    
    for label in strategist_models.keys():
        provider = classify_model_by_provider(label)
        strategist_by_provider[provider].append(label)
    
    config['coder_by_provider'] = coder_by_provider
    config['strategist_by_provider'] = strategist_by_provider
    config['coder_models'] = list(coder_models.keys())
    config['strategist_models'] = list(strategist_models.keys())
    
    # Fallback to environment variables only if config.ini didn't provide values
    if not config['coder_default']:
        config['coder_default'] = os.getenv('CODER_MODEL_DEFAULT_LABEL', '')
    if not config['strategist_default']:
        config['strategist_default'] = os.getenv('STRATEGIST_MODEL_DEFAULT_LABEL', '')
    
    return config

CLIENT_CONFIG = load_client_config()

def format_conversation_log(history: List[Dict[str, Any]]) -> str:
    log_lines = []
    for i, msg in enumerate(history):
        role_label = msg.get('role', 'UNKNOWN').upper()
        text_content = ""
        if 'parts' in msg and isinstance(msg['parts'], list):
            text_content = msg['parts'][0].get('text', '')

        log_lines.append(f"{'='*80}")
        log_lines.append(f"[{i}] {role_label}")
        log_lines.append(f"{'='*80}")
        log_lines.append(text_content)
        log_lines.append("")
    return "\n".join(log_lines)

def build_master_log(system_log_list, coder_log_list, strategist_log_list, audit_log_list, start_time, final_code_block=None):
    """Build master log with enhanced tool failure reporting"""
    actor_styles = {
        'SYSTEM': {'icon': '๐Ÿ”ง', 'color': '#ef4444'},
        'CODER': {'icon': '๐Ÿ’ป', 'color': '#3b82f6'},
        'STRATEGIST': {'icon': '๐ŸŽฏ', 'color': '#a855f7'},
        'TOOL': {'icon': '๐Ÿ› ๏ธ', 'color': '#f97316'}
    }
    
    master_entries = []
    seq_counter = 1
    
    for entry in system_log_list:
        elapsed = time.time() - start_time
        minutes = int(elapsed // 60)
        seconds = int(elapsed % 60)
        milliseconds = int((elapsed % 1) * 1000)
        timestamp = f"{minutes:02d}:{seconds:02d}:{milliseconds:03d}"
        
        style = actor_styles['SYSTEM']
        html_entry = f'<div style="margin-bottom: 8px; font-family: monospace;"><span style="color: {style["color"]}; font-weight: bold;">{style["icon"]} [SEQ-{seq_counter:02d}] [{timestamp}] SYSTEM:</span> {entry}</div>'
        master_entries.append(html_entry)
        seq_counter += 1
    
    for msg in coder_log_list:
        elapsed = time.time() - start_time
        minutes = int(elapsed // 60)
        seconds = int(elapsed % 60)
        milliseconds = int((elapsed % 1) * 1000)
        timestamp = f"{minutes:02d}:{seconds:02d}:{milliseconds:03d}"
        
        role = msg.get('role', 'UNKNOWN').upper()
        actor = f"CODER ({role})"
        
        text_content = ""
        if 'parts' in msg and isinstance(msg['parts'], list):
            text_content = msg['parts'][0].get('text', '')
        
        style = actor_styles['CODER']
        html_entry = f'<div style="margin-bottom: 8px; font-family: monospace;"><span style="color: {style["color"]}; font-weight: bold;">{style["icon"]} [SEQ-{seq_counter:02d}] [{timestamp}] {actor}:</span> {text_content}</div>'
        master_entries.append(html_entry)
        seq_counter += 1
    
    for msg in strategist_log_list:
        elapsed = time.time() - start_time
        minutes = int(elapsed // 60)
        seconds = int(elapsed % 60)
        milliseconds = int((elapsed % 1) * 1000)
        timestamp = f"{minutes:02d}:{seconds:02d}:{milliseconds:03d}"
        
        role = msg.get('role', 'UNKNOWN').upper()
        actor = f"STRATEGIST ({role})"
        
        text_content = ""
        if 'parts' in msg and isinstance(msg['parts'], list):
            text_content = msg['parts'][0].get('text', '')
        
        style = actor_styles['STRATEGIST']
        html_entry = f'<div style="margin-bottom: 8px; font-family: monospace;"><span style="color: {style["color"]}; font-weight: bold;">{style["icon"]} [SEQ-{seq_counter:02d}] [{timestamp}] {actor}:</span> {text_content}</div>'
        master_entries.append(html_entry)
        seq_counter += 1
    
    # Enhanced tool failure logging
    for diagnostic in audit_log_list:
        elapsed = time.time() - start_time
        minutes = int(elapsed // 60)
        seconds = int(elapsed % 60)
        milliseconds = int((elapsed % 1) * 1000)
        timestamp = f"{minutes:02d}:{seconds:02d}:{milliseconds:03d}"
        
        tool_name = diagnostic.get('tool_name', 'UNKNOWN')
        status = diagnostic.get('status', 'UNKNOWN')
        latency = diagnostic.get('latency', 'N/A')
        transaction_id = diagnostic.get('transaction_id', 'N/A')
        
        request_payload = diagnostic.get('request_payload', {})
        response_payload = diagnostic.get('response_payload', None)
        
        # Format based on status
        if status == 'FAILURE':
            request_str = json.dumps(request_payload, indent=2)
            error_msg = diagnostic.get('error_message', 'Unknown error')
            tool_entry = f"TOOL: {tool_name} | STATUS: FAILURE | ATTEMPTED PARAMS: {request_str}<br>ERROR: {error_msg}"
        else:
            request_str = json.dumps(request_payload, indent=2)
            response_str = json.dumps(response_payload, indent=2) if response_payload else "None"
            tool_entry = f"TOOL: {tool_name} | TRANSACTION: {transaction_id} | STATUS: {status} | LATENCY: {latency}s<br>[REQUEST]<br><pre>{request_str}</pre><br>[RESPONSE]<br><pre>{response_str}</pre>"
        
        style = actor_styles['TOOL']
        html_entry = f'<div style="margin-bottom: 8px; font-family: monospace;"><span style="color: {style["color"]}; font-weight: bold;">{style["icon"]} [SEQ-{seq_counter:02d}] [{timestamp}] TOOL:</span> {tool_entry}</div>'
        master_entries.append(html_entry)
        seq_counter += 1
    
    # Append final code block if provided
    if final_code_block:
        code_html = f'''
        <div style="margin-top: 20px; padding: 16px; background-color: #0d1117; border: 2px solid #10b981; border-radius: 8px;">
            <h3 style="color: #10b981; margin-top: 0;">๐ŸŽฏ GENERATED CODE:</h3>
            <pre style="background-color: #1e1e1e; padding: 12px; border-radius: 4px; overflow-x: auto; color: #e0e0e0;"><code>{final_code_block}</code></pre>
        </div>
        '''
        master_entries.append(code_html)
    
    if not master_entries:
        return '<div style="font-family: monospace; color: #6b7280;">No log data captured.</div>'
    
    html_output = f'''
    <div style="background-color: #1e1e1e; padding: 16px; border-radius: 8px; max-height: 600px; overflow-y: auto; color: #e0e0e0;">
        {"".join(master_entries)}
    </div>
    '''
    
    return html_output

def execute_remote_workflow(blueprint, intent, coder_model_label, strategist_model_label, enable_audit):
    """Execute workflow with final_code and master_log tracking"""
    mission_start_time = time.time()
    final_code = None
    
    payload = {
        "blueprint": blueprint,
        "intent": intent,
        "coder_model_label": coder_model_label,
        "strategist_model_label": strategist_model_label,
        "enable_audit": enable_audit
    }

    try:
        target_url = MCP_SERVER_URL.replace("/execute", "/execute_stream")
        print(f"DEBUG: Connecting to streaming endpoint: {target_url}")
        
        with requests.post(target_url, json=payload, stream=True, timeout=300) as response:
            if response.status_code == 404:
                yield f"ERROR 404: Streaming endpoint not found at {target_url}. Check server version.", "", "", "", None, None
                return
            
            response.raise_for_status()
            
            for line in response.iter_lines():
                if not line:
                    continue
                
                decoded = line.decode('utf-8')
                if not decoded.startswith('data: '):
                    continue
                
                data_str = decoded[6:]
                
                try:
                    data = json.loads(data_str)
                except json.JSONDecodeError:
                    continue
                
                if data.get("status") == "complete":
                    break
                
                # Watch for final_code key
                if "final_code" in data:
                    final_code = data["final_code"]
                
                system_log_list = data.get("system_log", [])
                coder_log_list = data.get("coder_log", [])
                strategist_log_list = data.get("strategist_log", [])
                audit_log_list = data.get("audit_log", [])
                
                sys_log = "\n".join(system_log_list)
                cod_log = format_conversation_log(coder_log_list)
                strat_log = format_conversation_log(strategist_log_list)
                master_log = build_master_log(system_log_list, coder_log_list, 
                                               strategist_log_list, audit_log_list, 
                                               mission_start_time, final_code)
                
                # DIRECTIVE #3: Update both master_log_output AND master_log_state
                yield sys_log, cod_log, strat_log, master_log, final_code, master_log
        
    except requests.exceptions.RequestException as e:
        error_detail = str(e)
        if hasattr(e, 'response') and e.response is not None:
            error_detail += f"\nServer Response: {e.response.text}"
            
        error_msg = f"CONNECTION ERROR: Could not connect to MCP Server.\nDetails: {error_detail}"
        yield error_msg, "", "", "", None, None
    except Exception as e:
        error_msg = f"CLIENT ERROR: {str(e)}"
        yield error_msg, "", "", "", None, None

def create_interface():
    DEMO_BLUEPRINT = """# Gradio Application Blueprint

Produce a pro level styled and tuned them GUI that has 1 button that when pressed displays a celebration announcement "Happy Birthday MCP!". USE specified colors or themes appropriate for the event. You must incorporate specific colors for design pieces and thematic layouts providing a fun and exciting announcement."""
    DEMO_INTENT = """A simple test button with a clean look. That when pressed creates a simple happy birthday MCP response on the screen. The gui should be gradio and contain colors that are used in professional builds and match the Gradio, MCP or other color theme or as close as possible."""

    # Use config defaults explicitly
    coder_default = CLIENT_CONFIG['coder_default']
    strategist_default = CLIENT_CONFIG['strategist_default']
    
    # Determine initial provider for each agent
    initial_coder_provider = "Google Gemini"
    initial_strategist_provider = "Google Gemini"
    
    if coder_default:
        initial_coder_provider = classify_model_by_provider(coder_default)
    
    if strategist_default:
        initial_strategist_provider = classify_model_by_provider(strategist_default)
    
    # Get initial model lists for providers
    initial_coder_models = CLIENT_CONFIG['coder_by_provider'].get(initial_coder_provider, [])
    initial_strategist_models = CLIENT_CONFIG['strategist_by_provider'].get(initial_strategist_provider, [])
    
    # Ensure default value is set or fallback to first available
    coder_initial_value = coder_default if coder_default and coder_default in initial_coder_models else (initial_coder_models[0] if initial_coder_models else None)
    strategist_initial_value = strategist_default if strategist_default and strategist_default in initial_strategist_models else (initial_strategist_models[0] if initial_strategist_models else None)

    def load_demo_data():
        """Switch Coder to gemini 2.5 pro when demo loaded"""
        demo_coder_model = None
        for model_label in CLIENT_CONFIG['coder_models']:
            if '2.5' in model_label and 'pro' in model_label.lower():
                demo_coder_model = model_label
                break
        
        if demo_coder_model:
            return DEMO_BLUEPRINT, DEMO_INTENT, gr.update(value=demo_coder_model)
        else:
            return DEMO_BLUEPRINT, DEMO_INTENT, gr.update()

    def start_execution_sequence():
        return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)

    # DIRECTIVE #3: Button visibility control in end sequence
    def end_execution_sequence(sys_log, cod_log, strat_log, master_log, final_code, master_log_html):
        # Buttons become visible only when final_code exists
        button_visibility = final_code is not None and final_code.strip() != ""
        return (
            sys_log, 
            cod_log, 
            strat_log, 
            master_log, 
            final_code,
            master_log_html,
            gr.update(visible=False),  # working_video
            gr.update(visible=True),   # celebrate_video
            gr.update(visible=button_visibility)  # download_buttons_row
        )

    def reset_to_default():
        return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
    
    # Cascading selector update functions
    def update_coder_models(provider):
        models = CLIENT_CONFIG['coder_by_provider'].get(provider, [])
        if not models:
            return gr.update(choices=[], value=None)
        return gr.update(choices=models, value=models[0])
    
    def update_strategist_models(provider):
        models = CLIENT_CONFIG['strategist_by_provider'].get(provider, [])
        if not models:
            return gr.update(choices=[], value=None)
        return gr.update(choices=models, value=models[0])
    
    # DIRECTIVE #1: NO LOGIC CHANGE - Existing download_code function preserved
    def download_code(final_code_content):
        """Generate downloadable Python file from final code"""
        if not final_code_content or final_code_content.strip() == "":
            return None
        
        # Create temporary file with timestamp
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"generated_code_{timestamp}.py"
        
        # Write to temporary file and return filepath
        temp_dir = tempfile.gettempdir()
        filepath = os.path.join(temp_dir, filename)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(final_code_content)
        
        return filepath
    
    # DIRECTIVE #2: NEW FUNCTION - Download master log
    def download_master_log(master_log_html):
        """Generate downloadable text file from master log HTML"""
        if not master_log_html or master_log_html.strip() == "":
            return None
        
        # Strip all HTML tags using regex
        clean_text = re.sub(r'<[^>]+>', '', master_log_html)
        
        # Decode HTML entities
        clean_text = clean_text.replace('&lt;', '<').replace('&gt;', '>').replace('&amp;', '&')
        
        # Clean up extra whitespace
        clean_text = re.sub(r'\n\s*\n', '\n\n', clean_text)
        clean_text = clean_text.strip()
        
        # Create temporary file with timestamp
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        filename = f"master_log_{timestamp}.txt"
        
        # Write to temporary file and return filepath
        temp_dir = tempfile.gettempdir()
        filepath = os.path.join(temp_dir, filename)
        
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(clean_text)
        
        return filepath
    
    # RESET MISSION function
    def reset_mission():
        """Total system reset: clear all fields and reset to defaults"""
        coder_models_for_reset = CLIENT_CONFIG['coder_by_provider'].get(initial_coder_provider, [])
        strategist_models_for_reset = CLIENT_CONFIG['strategist_by_provider'].get(initial_strategist_provider, [])
        
        coder_reset_value = coder_initial_value
        strategist_reset_value = strategist_initial_value
        
        return (
            "",  # blueprint_input
            "",  # intent_input
            "",  # system_terminal
            "",  # coder_log
            "",  # strategist_log
            '<div style="font-family: monospace; color: #6b7280;">*Mission reset complete. All systems cleared.*</div>',  # master_log
            gr.update(value=initial_coder_provider),  # coder_provider
            gr.update(choices=coder_models_for_reset, value=coder_reset_value),  # coder_model
            gr.update(value=initial_strategist_provider),  # strategist_provider
            gr.update(choices=strategist_models_for_reset, value=strategist_reset_value),  # strategist_model
            gr.update(value=False),  # audit_checkbox
            None,  # final_code_state
            None,  # master_log_state
            gr.update(visible=False)  # DIRECTIVE #3: Hide download buttons row on reset
        )

    with gr.Blocks(title="Project: Conductor V4.0 Client") as interface:
        gr.Markdown("# Project: Conductor V4.0 (Client Mode)")
        gr.Markdown(f"### The Command Center: Connected to MCP Server at `{MCP_SERVER_URL}`")
        
        # DIRECTIVE #3: Hidden states for final code and master log
        final_code_state = gr.State(value=None)
        master_log_state = gr.State(value=None)
        
        # PRIMARY INTERFACE ROW - Three Columns
        with gr.Row():
            # COLUMN 1 - CODER (Left Flank)
            with gr.Column():
                gr.Markdown("### Coder Agent")
                coder_provider = gr.Dropdown(
                    choices=list(PROVIDER_MODEL_MAPPING.keys()),
                    value=initial_coder_provider,
                    label="Provider",
                    interactive=True
                )
                coder_model = gr.Dropdown(
                    choices=initial_coder_models,
                    value=coder_initial_value,
                    label="Model",
                    interactive=True
                )
                blueprint_input = gr.Textbox(
                    label="Architect's Blueprint",
                    placeholder="Enter detailed technical specifications...",
                    lines=12
                )
            
            # COLUMN 2 - MEDIA BOX (Center Stage)
            with gr.Column():
                gr.Markdown("### Media Box")
                default_image = gr.Image(
                    value="ai_creative_tech .png", 
                    show_label=False, 
                    visible=True, 
                    interactive=False,
                    type="filepath",
                    height=450
                )
                working_video = gr.Video(
                    value="ai_ct_working.mp4", 
                    show_label=False, 
                    visible=False, 
                    autoplay=True, 
                    loop=True,
                    height=450
                )
                celebrate_video = gr.Video(
                    value="ai_creative_tech_celebrate.mp4", 
                    show_label=False, 
                    visible=False, 
                    autoplay=True, 
                    loop=False,
                    height=450
                )
            
            # COLUMN 3 - STRATEGIST (Right Flank)
            with gr.Column():
                gr.Markdown("### Strategist Agent")
                strategist_provider = gr.Dropdown(
                    choices=list(PROVIDER_MODEL_MAPPING.keys()),
                    value=initial_strategist_provider,
                    label="Provider",
                    interactive=True
                )
                strategist_model = gr.Dropdown(
                    choices=initial_strategist_models,
                    value=strategist_initial_value,
                    label="Model",
                    interactive=True
                )
                intent_input = gr.Textbox(
                    label="Architect's Intent",
                    placeholder="Enter project goals and context...",
                    lines=12
                )
        
        # ACTION ROW - Buttons
        with gr.Row():
            demo_btn = gr.Button("LOAD DEMO MODE", variant="secondary")
            execute_btn = gr.Button("EXECUTE VIA MCP", variant="primary")
            reset_btn = gr.Button("RESET MISSION", variant="secondary")
            audit_checkbox = gr.Checkbox(label="AUDIT", value=False)
        
        # LOG ROWS
        with gr.Row():
            system_terminal = gr.Textbox(label="SYSTEM LOG", interactive=False, lines=15, max_lines=15)
            coder_log = gr.Textbox(label="CODER LOG", interactive=False, lines=15, max_lines=15)
            strategist_log = gr.Textbox(label="STRATEGIST LOG", interactive=False, lines=15, max_lines=15)
        
        with gr.Row():
            master_log_output = gr.HTML(
                value='<div style="font-family: monospace; color: #6b7280;">No mission log data available.</div>',
                label="MASTER LOG WINDOW"
            )
        
        # DIRECTIVE #3: Two-button layout with clean, constrained width
        with gr.Row(visible=False) as download_buttons_row:
            with gr.Column():
                download_code_btn = gr.DownloadButton(
                    label="DOWNLOAD GENERATED CODE", 
                    variant="primary"
                )
            with gr.Column():
                download_log_btn = gr.DownloadButton(
                    label="DOWNLOAD MASTER LOG",
                    variant="secondary"
                )
        
        # EVENT HANDLERS
        
        # Cascading model selector logic
        coder_provider.change(
            fn=update_coder_models,
            inputs=[coder_provider],
            outputs=[coder_model]
        )
        
        strategist_provider.change(
            fn=update_strategist_models,
            inputs=[strategist_provider],
            outputs=[strategist_model]
        )
        
        # Demo button
        demo_btn.click(
            fn=load_demo_data,
            inputs=None,
            outputs=[blueprint_input, intent_input, coder_model]
        )
        
        # Execute button
        execute_btn.click(
            fn=start_execution_sequence,
            inputs=None,
            outputs=[default_image, working_video, celebrate_video]
        ).then(
            fn=execute_remote_workflow,
            inputs=[blueprint_input, intent_input, coder_model, strategist_model, audit_checkbox],
            outputs=[system_terminal, coder_log, strategist_log, master_log_output, final_code_state, master_log_state]
        ).then(
            fn=end_execution_sequence,
            inputs=[system_terminal, coder_log, strategist_log, master_log_output, final_code_state, master_log_state],
            outputs=[system_terminal, coder_log, strategist_log, master_log_output, final_code_state, master_log_state, working_video, celebrate_video, download_buttons_row]
        )
        
        # DIRECTIVE #1 & #2: Download button handlers
        download_code_btn.click(
            fn=download_code,
            inputs=[final_code_state],
            outputs=[download_code_btn]
        )
        
        download_log_btn.click(
            fn=download_master_log,
            inputs=[master_log_state],
            outputs=[download_log_btn]
        )
        
        # Celebrate video auto-reset
        celebrate_video.stop(
            fn=reset_to_default,
            inputs=None,
            outputs=[default_image, working_video, celebrate_video]
        )
        
        # RESET MISSION button with download buttons row visibility control
        reset_btn.click(
            fn=reset_mission,
            inputs=[],
            outputs=[
                blueprint_input,
                intent_input,
                system_terminal,
                coder_log,
                strategist_log,
                master_log_output,
                coder_provider,
                coder_model,
                strategist_provider,
                strategist_model,
                audit_checkbox,
                final_code_state,
                master_log_state,
                download_buttons_row
            ]
        )
        
        gr.Markdown("---")
        gr.Markdown("**Note:** This client requires the Conductor MCP Server V4.0 with streaming support. Logs now update in real-time with color-coded visual differentiation. **AUDIT mode will loop code back to Strategist for review.**")

    return interface

if __name__ == "__main__":
    app = create_interface()
    app.queue()
    app.launch()