File size: 28,470 Bytes
ea81a05
 
 
 
 
 
 
 
 
 
 
a2d37bf
 
ea81a05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2d37bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea81a05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2d37bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea81a05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2d37bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea81a05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Combined Gradio interface with both Single Query and Chat modes."""

import asyncio
import os

import gradio as gr

from .multi_web import (
    process_query_sync,
    process_chat_message,
    AVAILABLE_MODELS,
    load_config,
    generate_plan_mode
)

PREVIEW_CHAR_LIMIT = 2000
TEXT_EXTENSIONS = {
    ".txt",
    ".md",
    ".py",
    ".json",
    ".csv",
    ".tsv",
    ".yaml",
    ".yml",
    ".log",
    ".xml",
}
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp"}


def _is_probably_binary(path: str) -> bool:
    try:
        with open(path, "rb") as f:
            chunk = f.read(2048)
    except OSError:
        return False
    if not chunk:
        return False
    printable = sum(32 <= b <= 126 or b in (9, 10, 13) for b in chunk)
    return printable / len(chunk) < 0.85


def _extract_docx_text(path: str) -> str:
    import zipfile
    from xml.etree import ElementTree

    try:
        with zipfile.ZipFile(path) as zf:
            xml_data = zf.read("word/document.xml")
    except Exception:
        return ""

    namespace = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
    try:
        root = ElementTree.fromstring(xml_data)
    except ElementTree.ParseError:
        return ""

    paragraphs = []
    for para in root.iter(f"{namespace}p"):
        texts = [node.text for node in para.iter(f"{namespace}t") if node.text]
        if texts:
            paragraphs.append("".join(texts))
    return "\n\n".join(paragraphs)


def _extract_pdf_text(path: str) -> str:
    try:
        from pypdf import PdfReader
    except ImportError:
        return ""

    try:
        reader = PdfReader(path)
    except Exception:
        return ""

    pages = []
    for page in reader.pages[:10]:  # cap for safety
        try:
            text = page.extract_text() or ""
        except Exception:
            text = ""
        if text:
            pages.append(text.strip())
    return "\n\n".join(pages)


def _extract_pptx_text(path: str) -> str:
    try:
        from pptx import Presentation
    except ImportError:
        return ""

    try:
        presentation = Presentation(path)
    except Exception:
        return ""

    slides = []
    for index, slide in enumerate(presentation.slides, start=1):
        texts = []
        for shape in slide.shapes:
            if hasattr(shape, "text") and shape.text:
                texts.append(shape.text.strip())
        if texts:
            slides.append(f"Slide {index}:\n" + "\n".join(texts))
    return "\n\n".join(slides)


def _extract_excel_text(path: str, extension: str) -> str:
    extension = extension.lower()
    rows = []

    if extension in {".xlsx", ".xlsm"}:
        try:
            from openpyxl import load_workbook
        except ImportError:
            return ""

        try:
            workbook = load_workbook(path, read_only=True, data_only=True)
        except Exception:
            return ""

        sheet_limit = 5
        row_limit = 40
        for sheet_index, sheet in enumerate(workbook.worksheets):
            if sheet_index >= sheet_limit:
                rows.append("... (additional sheets not shown)")
                break
            rows.append(f"Sheet: {sheet.title}")
            displayed = 0
            for row in sheet.iter_rows(values_only=True):
                if displayed >= row_limit:
                    rows.append("... (rows truncated)")
                    break
                cells = [str(cell) if cell is not None else "" for cell in row]
                rows.append(" | ".join(cells))
                displayed += 1
    elif extension == ".xls":
        try:
            import xlrd
        except ImportError:
            return ""

        try:
            workbook = xlrd.open_workbook(path)
        except Exception:
            return ""

        sheet_limit = 5
        row_limit = 40
        for sheet_index, sheet in enumerate(workbook.sheets()):
            if sheet_index >= sheet_limit:
                rows.append("... (additional sheets not shown)")
                break
            rows.append(f"Sheet: {sheet.name}")
            row_count = min(sheet.nrows, row_limit)
            for ridx in range(row_count):
                cells = [
                    str(sheet.cell_value(ridx, cidx))
                    for cidx in range(min(sheet.ncols, 20))
                ]
                rows.append(" | ".join(cells))
            if sheet.nrows > row_limit:
                rows.append("... (rows truncated)")

    return "\n".join(rows)


def _describe_image(path: str) -> str:
    try:
        from PIL import Image, ExifTags
    except ImportError:
        return "(Preview unavailable: Pillow is required for image metadata.)"

    try:
        with Image.open(path) as img:
            width, height = img.size
            mode = img.mode
            info_lines = [f"Dimensions: {width}x{height}px", f"Color mode: {mode}"]

            exif_data = {}
            if hasattr(img, "_getexif") and img._getexif():
                raw_exif = img._getexif() or {}
                for tag, value in raw_exif.items():
                    decoded = ExifTags.TAGS.get(tag, tag)
                    if decoded in ("Make", "Model", "Software", "DateTimeOriginal"):
                        exif_data[decoded] = value
            if exif_data:
                info_lines.append("EXIF:")
                for key, value in exif_data.items():
                    info_lines.append(f"  - {key}: {value}")

            return "\n".join(info_lines)
    except Exception:
        return "(Preview unavailable: could not read image metadata.)"


def _read_text_file(path: str) -> str:
    try:
        with open(path, "r", encoding="utf-8", errors="ignore") as f:
            return f.read(PREVIEW_CHAR_LIMIT)
    except Exception:
        return ""


def _generate_preview(path: str, extension: str) -> str:
    extension = extension.lower()

    preview_text = ""
    if extension == ".docx":
        preview_text = _extract_docx_text(path)
    elif extension == ".pdf":
        preview_text = _extract_pdf_text(path)
    elif extension in (".pptx", ".ppt"):
        preview_text = _extract_pptx_text(path)
        if not preview_text and extension == ".ppt":
            preview_text = "(Preview unavailable for legacy .ppt files. Convert to .pptx for text access.)"
    elif extension in {".xlsx", ".xlsm", ".xls"}:
        preview_text = _extract_excel_text(path, extension)
    elif extension in TEXT_EXTENSIONS:
        preview_text = _read_text_file(path)
    elif extension in IMAGE_EXTENSIONS:
        preview_text = _describe_image(path)
    elif not _is_probably_binary(path):
        preview_text = _read_text_file(path)

    if preview_text:
        if len(preview_text) > PREVIEW_CHAR_LIMIT:
            preview_text = preview_text[:PREVIEW_CHAR_LIMIT] + "\n...\n(Preview truncated)"
        return preview_text

    return "(Preview unavailable. File may be binary or unsupported for inline preview.)"


# Create Combined Gradio interface with TABS
with gr.Blocks(
    title="Heavy Multi-Model 2.0",
    theme=gr.themes.Soft()
) as demo:

    gr.Markdown("# πŸ€– Heavy Multi-Model 2.0")

    with gr.Tabs() as tabs:
        # ============================================
        # TAB 1: CHAT MODE
        # ============================================
        with gr.Tab("C", id="chat"):
            # State for conversation history and file attachments
            chat_state = gr.State([])
            chat_uploaded_file_state = gr.State(value=None)

            with gr.Row():
                with gr.Column(scale=3):
                    # API Keys
                    with gr.Group():
                        chat_api_key = gr.Textbox(
                            label="O",
                            placeholder="sk-or-v1-...",
                            type="password"
                        )
                        chat_use_tavily = gr.Checkbox(label="T", value=False)
                        chat_tavily_key = gr.Textbox(
                            label="T Key",
                            placeholder="tvly-...",
                            type="password",
                            visible=False
                        )

                    # Model Config
                    with gr.Accordion("🎯 Model Configuration", open=True):
                        chat_mode = gr.Radio(
                            choices=[
                                "S",
                                "M",
                                "Original M"
                            ],
                            value="S",
                            label="Mode"
                        )

                        with gr.Group(visible=True) as chat_single_group:
                            chat_single_model = gr.Dropdown(
                                choices=AVAILABLE_MODELS,
                                value="claude-4.5-sonnet",
                                label="Model"
                            )

                        with gr.Group(visible=False) as chat_multi_group:
                            chat_orch = gr.Dropdown(AVAILABLE_MODELS, value="claude-4.5-sonnet", label="Orchestrator")
                            chat_agent = gr.Dropdown(AVAILABLE_MODELS, value="gpt-5.1", label="Agents")
                            chat_synth = gr.Dropdown(AVAILABLE_MODELS, value="gemini-3-pro-preview", label="Synthesizer")

                    with gr.Accordion("βš™οΈ Settings", open=False):
                        chat_num_agents = gr.Slider(2, 8, 4, step=1, label="Number of Agents")
                        chat_show_thoughts = gr.Checkbox(label="Show Agent Details", value=False)

                    # Chat UI
                    gr.Markdown("### πŸ’¬ Conversation")
                    chat_display = gr.Chatbot(
                        value=[],
                        label="Chat",
                        height=400,
                        type="messages"
                    )

                    with gr.Row():
                        chat_upload = gr.UploadButton(
                            "πŸ“Ž Attach File",
                            size="sm",
                            scale=1,
                            variant="secondary",
                            file_types=["image", "video", "audio", "text", "document"],
                            file_count="single"
                        )
                        chat_input = gr.Textbox(
                            placeholder="Type your message...",
                            lines=2,
                            scale=4,
                            show_label=False
                        )
                        chat_send = gr.Button("Send πŸš€", variant="primary", scale=1)

                    chat_clear = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")
                    chat_file_info = gr.Markdown("No file uploaded yet.", visible=True)
                    chat_file_preview = gr.Textbox(
                        label="Attached File Preview (first 2000 characters)",
                        lines=6,
                        interactive=False
                    )

                with gr.Column(scale=1):
                    pass

            with gr.Accordion("πŸ“Š Analysis Details (Latest)", open=False):
                chat_model_info = gr.Markdown()
                chat_questions = gr.Textbox(label="Questions", lines=3, interactive=False)
                chat_agents = gr.Markdown(label="Agent Analyses")

        # ============================================
        # TAB 2: SINGLE QUERY MODE
        # ============================================
        with gr.Tab("Q", id="single"):
            with gr.Row():
                with gr.Column(scale=3):
                    # API Keys
                    single_api_key = gr.Textbox(
                        label="O",
                        placeholder="sk-or-v1-...",
                        type="password"
                    )
                    single_use_tavily = gr.Checkbox(label="T", value=False)
                    single_tavily_key = gr.Textbox(
                        label="T Key",
                        placeholder="tvly-...",
                        type="password",
                        visible=False
                    )

                    single_query = gr.Textbox(
                        label="Your Query",
                        placeholder="What are the implications of quantum computing?",
                        lines=3
                    )

                    # Model Config
                    with gr.Accordion("🎯 Model Configuration", open=True):
                        single_mode = gr.Radio(
                            choices=[
                                "S",
                                "M",
                                "Original M"
                            ],
                            value="S",
                            label="Mode"
                        )

                        with gr.Group(visible=True) as single_single_group:
                            single_single_model = gr.Dropdown(
                                choices=AVAILABLE_MODELS,
                                value="claude-4.5-sonnet",
                                label="Model"
                            )

                        with gr.Group(visible=False) as single_multi_group:
                            single_orch = gr.Dropdown(AVAILABLE_MODELS, value="claude-4.5-sonnet", label="Orchestrator")
                            single_agent = gr.Dropdown(AVAILABLE_MODELS, value="gpt-5.1", label="Agents")
                            single_synth = gr.Dropdown(AVAILABLE_MODELS, value="gemini-3-pro-preview", label="Synthesizer")

                    with gr.Accordion("βš™οΈ Settings", open=False):
                        single_num_agents = gr.Slider(2, 8, 4, step=1, label="Number of Agents")
                        single_show_thoughts = gr.Checkbox(label="Show Agent Thoughts", value=True)

                    single_submit = gr.Button("πŸš€ Analyze", variant="primary", size="lg")

                with gr.Column(scale=1):
                    pass

            with gr.Accordion("🎯 Model Configuration", open=True):
                single_model_info = gr.Markdown()

            with gr.Accordion("πŸ“‹ Generated Questions", open=True):
                single_questions = gr.Textbox(label="Questions", lines=6, interactive=False)

            with gr.Accordion("πŸ” Agent Analyses", open=False):
                single_agents = gr.Markdown()

            with gr.Accordion("✨ Final Response", open=True):
                single_response = gr.Markdown()

        # ============================================
        # TAB 3: PLAN MODE
        # ============================================
        with gr.Tab("Plan Mode", id="plan"):
            gr.Markdown("### 🧭 Plan Mode")
            with gr.Row():
                with gr.Column(scale=3):
                    plan_api_key = gr.Textbox(
                        label="O",
                        placeholder="sk-or-v1-...",
                        type="password"
                    )
                    plan_task = gr.Textbox(
                        label="Task / Goal to Plan",
                        placeholder="Describe the backlog item or project you want planned...",
                        lines=4
                    )

                    with gr.Accordion("🧠 Planner Settings", open=True):
                        plan_model = gr.Dropdown(
                            choices=AVAILABLE_MODELS,
                            value="claude-4.5-sonnet",
                            label="Planner Model"
                        )
                        plan_num_agents = gr.Slider(
                            3,
                            8,
                            4,
                            step=1,
                            label="Parallel Agents / Workstreams"
                        )

                    with gr.Row():
                        plan_generate = gr.Button("🧭 Generate Plan", variant="primary")
                        plan_clear = gr.Button("πŸ—‘οΈ Clear", variant="secondary")

                with gr.Column(scale=1):
                    pass

            plan_state = gr.State("")

            with gr.Accordion("πŸ“‹ Plan Output", open=True):
                plan_model_info = gr.Markdown()
                plan_output = gr.Markdown()

            with gr.Accordion("πŸš€ Execute with Heavy (uses plan as context)", open=False):
                plan_exec_query = gr.Textbox(
                    label="Execution Task (Heavy will follow the plan context)",
                    placeholder="What should Heavy execute? e.g., \"Build auth UI per plan above\"",
                    lines=3
                )
                plan_exec_mode = gr.Radio(
                    choices=[
                        "S",
                        "M",
                        "Original M"
                    ],
                    value="S",
                    label="Mode"
                )

                with gr.Group(visible=True) as plan_exec_single_group:
                    plan_exec_single_model = gr.Dropdown(
                        choices=AVAILABLE_MODELS,
                        value="claude-4.5-sonnet",
                        label="Model"
                    )

                with gr.Group(visible=False) as plan_exec_multi_group:
                    plan_exec_orch = gr.Dropdown(AVAILABLE_MODELS, value="claude-4.5-sonnet", label="Orchestrator")
                    plan_exec_agent = gr.Dropdown(AVAILABLE_MODELS, value="gpt-5.1", label="Agents")
                    plan_exec_synth = gr.Dropdown(AVAILABLE_MODELS, value="gemini-3-pro-preview", label="Synthesizer")

                plan_exec_num_agents = gr.Slider(2, 8, 4, step=1, label="Number of Agents")
                plan_exec_show_thoughts = gr.Checkbox(label="Show Agent Thoughts", value=True)
                plan_exec_use_tavily = gr.Checkbox(label="Enable Web Search (Tavily)", value=False)
                plan_exec_tavily_key = gr.Textbox(
                    label="T Key",
                    placeholder="tvly-...",
                    type="password",
                    visible=False
                )

                plan_execute = gr.Button("πŸš€ Run Heavy with Plan Context", variant="primary", size="lg")

                with gr.Accordion("Execution Output", open=True):
                    plan_exec_model_info = gr.Markdown()
                    plan_exec_questions = gr.Textbox(label="Questions", lines=6, interactive=False)
                    plan_exec_agents = gr.Markdown()
                    plan_exec_response = gr.Markdown()

        # ============================================
        # TAB 4: FILE UPLOAD TEST MODE
        # ============================================
        with gr.Tab("Upload Test", id="upload_test"):
            gr.Markdown("### πŸ“ Upload a file to quickly inspect it")

            upload_file_input = gr.File(
                label="Select a file to upload",
                file_count="single",
                type="filepath",
                file_types=["image", "video", "audio", "text", "document"]
            )
            upload_process_btn = gr.Button("Process File", variant="primary")

            upload_file_info = gr.Markdown("No file uploaded yet.")
            upload_file_preview = gr.Textbox(
                label="File Preview (first 2000 characters)",
                lines=10,
                interactive=False
            )

    # ============================================
    # EVENT HANDLERS
    # ============================================

    # Toggle functions
    def toggle_model_selection(mode):
        if mode == "S":
            return gr.update(visible=True), gr.update(visible=False)
        elif mode == "M":
            return gr.update(visible=False), gr.update(visible=True)
        else:
            return gr.update(visible=False), gr.update(visible=False)

    def toggle_tavily(use_tavily):
        return gr.update(visible=use_tavily)

    # Plan mode handlers
    def handle_plan_request(task, num_agents, model, api_key):
        model_info, plan_text = generate_plan_mode(task, num_agents, model, api_key)
        return model_info, plan_text, plan_text

    def clear_plan():
        return "", "", "", "", "", "", ""

    def handle_plan_execute(execution_task, plan_text, num_agents, show_thoughts, mode,
                            single, orch, agent, synth, api_key, use_tavily, tavily_key):
        if not plan_text.strip():
            return "⚠️ Generate a plan first.", "", "", ""
        if not execution_task.strip():
            return "⚠️ Enter an execution task for Heavy to run with the plan context.", "", "", ""

        execution_query = (
            "Follow the plan below as context. Execute the task, using the plan to guide questions and steps.\n\n"
            f"=== PLAN START ===\n{plan_text}\n=== PLAN END ===\n\n"
            f"Execution task: {execution_task.strip()}"
        )

        return process_query_sync(
            execution_query, num_agents, show_thoughts, mode,
            single, orch, agent, synth, api_key, use_tavily, tavily_key
        )

    # Chat handlers
    def handle_chat(msg, hist, num_agents, show_thoughts, mode, single, orch, agent, synth, api_key, use_tavily, tavily_key, uploaded_file):
        attachment_note = ""
        if uploaded_file and uploaded_file.get("preview"):
            attachment_note = (
                "\n\n---\nAttached file information:\n"
                f"{uploaded_file.get('info', '')}\n\n"
                "Attached file preview:\n"
                f"{uploaded_file['preview']}"
            )
        elif uploaded_file and uploaded_file.get("info"):
            attachment_note = (
                "\n\n---\nAttached file information:\n"
                f"{uploaded_file['info']}\n"
                "(Preview unavailable.)"
            )

        msg_payload = f"{msg}{attachment_note}" if attachment_note else msg

        updated_hist, model_info, questions, agents, _ = process_chat_message(
            msg_payload, hist, num_agents, show_thoughts, mode,
            single, orch, agent, synth, api_key, use_tavily, tavily_key
        )
        chat_display = [{"role": m["role"], "content": m["content"]} for m in updated_hist]
        if uploaded_file:
            reset_info = "No file uploaded yet."
            reset_preview = ""
            reset_attachment = None
        else:
            reset_info = gr.update()
            reset_preview = gr.update()
            reset_attachment = uploaded_file
        return (
            chat_display,
            updated_hist,
            "",
            model_info,
            questions,
            agents,
            reset_info,
            reset_preview,
            reset_attachment
        )

    def clear_chat():
        return [], []

    def handle_file_upload(file_path):
        """Return basic metadata and safe preview text for uploaded files."""
        if not file_path:
            return "⚠️ Please upload a file first.", ""

        file_name = os.path.basename(file_path)
        file_ext = os.path.splitext(file_name)[1].lower()
        try:
            size_bytes = os.path.getsize(file_path)
            size_info = f"{size_bytes} bytes ({size_bytes / 1024:.1f} KB)"
        except OSError:
            size_bytes = None
            size_info = "Unknown"

        preview = _generate_preview(file_path, file_ext)

        info = (
            f"**File:** {file_name}\n"
            f"- Type: {file_ext or 'unknown'}\n"
            f"- Size: {size_info}\n"
            f"- Location: `{file_path}`"
        )
        return info, preview

    def handle_chat_file_upload(file_path):
        """Extend file upload handler to store attachment metadata for chat."""
        info, preview = handle_file_upload(file_path)
        payload = None
        if file_path:
            payload = {
                "path": file_path,
                "info": info,
                "preview": preview
            }
        return info, preview, payload

    # Chat mode events
    chat_mode.change(
        fn=toggle_model_selection,
        inputs=[chat_mode],
        outputs=[chat_single_group, chat_multi_group]
    )

    chat_use_tavily.change(
        fn=toggle_tavily,
        inputs=[chat_use_tavily],
        outputs=[chat_tavily_key]
    )

    chat_send.click(
        fn=handle_chat,
        inputs=[chat_input, chat_state, chat_num_agents, chat_show_thoughts, chat_mode,
                chat_single_model, chat_orch, chat_agent, chat_synth,
                chat_api_key, chat_use_tavily, chat_tavily_key, chat_uploaded_file_state],
        outputs=[
            chat_display, chat_state, chat_input, chat_model_info,
            chat_questions, chat_agents, chat_file_info, chat_file_preview,
            chat_uploaded_file_state
        ]
    )

    chat_input.submit(
        fn=handle_chat,
        inputs=[chat_input, chat_state, chat_num_agents, chat_show_thoughts, chat_mode,
                chat_single_model, chat_orch, chat_agent, chat_synth,
                chat_api_key, chat_use_tavily, chat_tavily_key, chat_uploaded_file_state],
        outputs=[
            chat_display, chat_state, chat_input, chat_model_info,
            chat_questions, chat_agents, chat_file_info, chat_file_preview,
            chat_uploaded_file_state
        ]
    )

    chat_clear.click(fn=clear_chat, outputs=[chat_display, chat_state])
    chat_upload.upload(
        fn=handle_chat_file_upload,
        inputs=[chat_upload],
        outputs=[chat_file_info, chat_file_preview, chat_uploaded_file_state]
    )

    # Plan mode events
    plan_generate.click(
        fn=handle_plan_request,
        inputs=[plan_task, plan_num_agents, plan_model, plan_api_key],
        outputs=[plan_model_info, plan_output, plan_state]
    )

    plan_clear.click(
        fn=clear_plan,
        outputs=[
            plan_model_info,
            plan_output,
            plan_state,
            plan_exec_model_info,
            plan_exec_questions,
            plan_exec_agents,
            plan_exec_response
        ]
    )

    plan_exec_mode.change(
        fn=toggle_model_selection,
        inputs=[plan_exec_mode],
        outputs=[plan_exec_single_group, plan_exec_multi_group]
    )

    plan_exec_use_tavily.change(
        fn=toggle_tavily,
        inputs=[plan_exec_use_tavily],
        outputs=[plan_exec_tavily_key]
    )

    plan_execute.click(
        fn=handle_plan_execute,
        inputs=[
            plan_exec_query,
            plan_state,
            plan_exec_num_agents,
            plan_exec_show_thoughts,
            plan_exec_mode,
            plan_exec_single_model,
            plan_exec_orch,
            plan_exec_agent,
            plan_exec_synth,
            plan_api_key,
            plan_exec_use_tavily,
            plan_exec_tavily_key
        ],
        outputs=[
            plan_exec_model_info,
            plan_exec_questions,
            plan_exec_agents,
            plan_exec_response
        ]
    )

    # Single query mode events
    single_mode.change(
        fn=toggle_model_selection,
        inputs=[single_mode],
        outputs=[single_single_group, single_multi_group]
    )

    single_use_tavily.change(
        fn=toggle_tavily,
        inputs=[single_use_tavily],
        outputs=[single_tavily_key]
    )

    single_submit.click(
        fn=process_query_sync,
        inputs=[single_query, single_num_agents, single_show_thoughts, single_mode,
                single_single_model, single_orch, single_agent, single_synth,
                single_api_key, single_use_tavily, single_tavily_key],
        outputs=[single_model_info, single_questions, single_agents, single_response]
    )

    upload_process_btn.click(
        fn=handle_file_upload,
        inputs=[upload_file_input],
        outputs=[upload_file_info, upload_file_preview]
    )


def launch(share=True, server_port=7860):
    """Launch the combined interface."""
    demo.launch(
        share=share,
        server_port=server_port,
        server_name="0.0.0.0",
        show_error=True,
        inbrowser=True,
        prevent_thread_lock=False
    )


if __name__ == "__main__":
    launch()