Skip to content

Desktop API Reference

desktop.main_window

Main Window — PySide6 desktop GUI entry point.

Classes

MainWindow

Bases: QMainWindow

Source code in desktop/main_window.py
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Morphix")
        self.setMinimumSize(1200, 750)
        self._init_task = None

        self._apply_dark_theme()
        self._build_menu()
        self._build_content_area()
        self._build_status_bar()

    def _build_content_area(self):
        central = QWidget()
        layout = QHBoxLayout(central)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # Sidebar
        sidebar_widget = QWidget()
        sidebar_widget.setFixedWidth(200)
        sidebar_widget.setMinimumWidth(140)
        sidebar_layout = QVBoxLayout(sidebar_widget)
        sidebar_layout.setContentsMargins(0, 0, 0, 0)
        sidebar_layout.setSpacing(0)

        logo = QLabel("Morphix")
        logo.setAlignment(Qt.AlignmentFlag.AlignCenter)
        logo.setStyleSheet(
            f"font-size: 18px; font-weight: bold; color: {ACCENT}; " f"padding: 16px 8px 12px 8px;"
        )
        sidebar_layout.addWidget(logo)

        self._sidebar = QListWidget()
        self._sidebar.setStyleSheet(StyleFactory.sidebar())
        for label, icon in _SIDEBAR_ITEMS:
            item = QListWidgetItem(f"  {icon}  {label}")
            item.setToolTip(f"Ver {label}")
            self._sidebar.addItem(item)
        self._sidebar.setCurrentRow(0)
        sidebar_layout.addWidget(self._sidebar, 1)

        # Workspace indicator at sidebar bottom
        self._sidebar_ws_label = QLabel("ws: main")
        self._sidebar_ws_label.setStyleSheet(
            f"color: {COLORS['text_secondary']}; font-size: 10px; " f"padding: 8px 16px 12px 16px;"
        )
        sidebar_layout.addWidget(self._sidebar_ws_label)
        layout.addWidget(sidebar_widget)

        # Content (stacked widget)
        self._stacked = QStackedWidget()
        self.tabs = _StackedShim(self._stacked)

        loading = QLabel("Inicializando...")
        loading.setAlignment(Qt.AlignmentFlag.AlignCenter)
        loading.setStyleSheet("color: #A0A0A0; font-size: 16px;")
        self._loading_label = loading
        self.tabs.addTab(loading, "Maestro")
        self._stacked.setCurrentIndex(0)
        layout.addWidget(self._stacked, 1)

        # Sidebar navigation
        self._sidebar.currentRowChanged.connect(self._stacked.setCurrentIndex)
        self.setCentralWidget(central)

    def _apply_dark_theme(self):
        from core.config import settings

        if not settings.dark_mode:
            return
        palette = self.palette()
        for role, color in get_dark_palette().items():
            palette.setColor(QPalette.ColorGroup.All, role, QColor(color))
        self.setPalette(palette)
        self.setStyleSheet(
            StyleFactory.tab_widget() + StyleFactory.menu_bar() + StyleFactory.status_bar()
        )

    def _build_menu(self):
        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu("Archivo")
        exit_action = QAction("Salir", self)
        exit_action.setShortcut(QKeySequence("Ctrl+Q"))
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)

        help_menu = menu_bar.addMenu("Ayuda")
        about_action = QAction("Acerca de", self)
        about_action.triggered.connect(self._show_about)

        shortcuts_action = QAction("Atajos de teclado", self)
        shortcuts_action.triggered.connect(self._show_shortcuts)

        help_menu.addAction(about_action)
        help_menu.addAction(shortcuts_action)

    def _show_about(self):
        from PySide6.QtWidgets import QMessageBox

        QMessageBox.about(
            self,
            "Acerca de Morphix",
            "Morphix v1.0.0\n\n"
            "Sistema de Razonamiento y Coordinación con IA.\n"
            "Arquitectura: PySide6 Desktop + CLI.\n"
            "Motor LLM: DeepSeek v4 + Ollama (offline).\n\n"
            "© 2026 MorphiLab",
        )

    def _show_shortcuts(self):
        from PySide6.QtWidgets import QMessageBox

        QMessageBox.information(
            self,
            "Atajos de teclado",
            "Ctrl+Q       — Salir\n"
            "Ctrl+Enter   — Enviar mensaje en Maestro\n"
            "Shift+Enter  — Nueva línea en Maestro\n",
        )

    def _build_status_bar(self):
        self.status = QStatusBar()
        self.workspace_label = QLabel("Workspace: main")
        self.workspace_label.setStyleSheet("color: #A0A0A0;")
        self.status.addPermanentWidget(self.workspace_label)
        self.setStatusBar(self.status)

    async def init_backend(self):
        """Inicializa el backend y carga las pestañas reales."""
        from core.bootstrap import init_backend as do_init
        from core.bootstrap import start_daemons

        success = await do_init(
            workspace="main",
            on_progress=lambda msg: self.status.showMessage(msg, 3000),
        )
        if not success:
            self.status.showMessage("Error de inicialización", 0)
            return

        from desktop.events import _get_signals

        async def _on_offline_changed(offline: bool):
            _get_signals().offline_changed.emit(offline)

        await start_daemons(on_offline_changed=_on_offline_changed)

        # Load real tabs
        self._load_real_tabs()

    def _load_real_tabs(self):
        # Liberar el QLabel de carga
        if hasattr(self, "_loading_label") and self._loading_label is not None:
            self._loading_label.deleteLater()
            self._loading_label = None
        self.tabs.clear()

        from desktop.analytics_tab import AnalyticsTab
        from desktop.config_tab import ConfigTab
        from desktop.dashboard_tab import DashboardTab
        from desktop.editor_tab import EditorTab
        from desktop.history_tab import HistoryTab
        from desktop.maestro_tab import MaestroTab

        self.tabs.addTab(DashboardTab(), "Dashboard")  # index 0
        maestro = MaestroTab()
        self.maestro = maestro
        self.tabs.addTab(maestro, "Maestro")  # index 1
        history = HistoryTab()
        self.history = history
        self.tabs.addTab(history, "Historial")  # index 2
        history.conversation_selected.connect(self._on_resume_conversation)
        editor = EditorTab()
        self.editor = editor
        self.tabs.addTab(editor, "Editor")  # index 3
        self.tabs.addTab(ConfigTab(), "Config")  # index 4
        self.tabs.addTab(AnalyticsTab(), "Analytics")  # index 5

        # Sync sidebar → content
        self._sidebar.setCurrentRow(0)

        from core.workspaces import get_global_workspaces

        ws_name = get_global_workspaces().current
        self.workspace_label.setText(f"Workspace: {ws_name}")
        if hasattr(self, "_sidebar_ws_label"):
            self._sidebar_ws_label.setText(f"ws: {ws_name}")
        self.status.showMessage("✅ Morphix listo", 5000)

        from desktop.events import get_signals

        get_signals().offline_changed.connect(
            lambda offline: self.status.showMessage(
                f"⚠️ Modo offline {'activado' if offline else 'desactivado'}", 8000
            )
        )

        def _on_ws_change(ws):
            self.workspace_label.setText(f"Workspace: {ws}")
            if hasattr(self, "_sidebar_ws_label"):
                self._sidebar_ws_label.setText(f"ws: {ws}")

        get_signals().workspace_changed.connect(_on_ws_change)
        get_signals().project_changed.connect(
            lambda root: self.editor.set_project(root or None, get_global_workspaces().current)
        )
        editor.set_project(maestro._current_project_root, get_global_workspaces().current)

    def _on_resume_conversation(self, conv_id: int):
        """Load conversation into Maestro tab and switch to it."""
        run_async(self.maestro.load_conversation(conv_id))
        self._stacked.setCurrentWidget(self.maestro)
        self._sidebar.setCurrentRow(1)  # Maestro sidebar index

    def closeEvent(self, event):
        """Shutdown limpio: cancelar tareas, daemons, cerrar pool de BD."""
        import time

        from PySide6.QtCore import QTimer

        if getattr(self, "_shutting_down", False):
            event.accept()
            return
        self._shutting_down = True

        logger.info("Cerrando aplicación...")
        if hasattr(self, "_init_task") and self._init_task is not None:
            self._init_task.cancel()
        try:
            from core.bootstrap import stop_daemons
            from core.database import dispose_engine

            try:
                loop = asyncio.get_running_loop()
            except RuntimeError:
                loop = asyncio.get_event_loop()
            if loop.is_running():
                t_stop = run_async(stop_daemons(), loop=loop)
                t_dispose = run_async(dispose_engine(), loop=loop)
                _deadline = [time.monotonic() + 3]

                def _check_shutdown():
                    if t_stop.done() and t_dispose.done():
                        event.accept()
                    elif time.monotonic() < _deadline[0]:
                        QTimer.singleShot(10, _check_shutdown)
                    else:
                        logger.warning("Shutdown timed out, forzando cierre")
                        event.accept()

                _check_shutdown()
                return  # closeEvent completes asynchronously via _check_shutdown
        except RuntimeError:
            logger.debug("Event loop ya cerrado, omitiendo shutdown asíncrono")
        except Exception as e:
            logger.debug(f"Error en shutdown: {e}")
        event.accept()
Functions
init_backend async
init_backend()

Inicializa el backend y carga las pestañas reales.

Source code in desktop/main_window.py
async def init_backend(self):
    """Inicializa el backend y carga las pestañas reales."""
    from core.bootstrap import init_backend as do_init
    from core.bootstrap import start_daemons

    success = await do_init(
        workspace="main",
        on_progress=lambda msg: self.status.showMessage(msg, 3000),
    )
    if not success:
        self.status.showMessage("Error de inicialización", 0)
        return

    from desktop.events import _get_signals

    async def _on_offline_changed(offline: bool):
        _get_signals().offline_changed.emit(offline)

    await start_daemons(on_offline_changed=_on_offline_changed)

    # Load real tabs
    self._load_real_tabs()
closeEvent
closeEvent(event)

Shutdown limpio: cancelar tareas, daemons, cerrar pool de BD.

Source code in desktop/main_window.py
def closeEvent(self, event):
    """Shutdown limpio: cancelar tareas, daemons, cerrar pool de BD."""
    import time

    from PySide6.QtCore import QTimer

    if getattr(self, "_shutting_down", False):
        event.accept()
        return
    self._shutting_down = True

    logger.info("Cerrando aplicación...")
    if hasattr(self, "_init_task") and self._init_task is not None:
        self._init_task.cancel()
    try:
        from core.bootstrap import stop_daemons
        from core.database import dispose_engine

        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:
            loop = asyncio.get_event_loop()
        if loop.is_running():
            t_stop = run_async(stop_daemons(), loop=loop)
            t_dispose = run_async(dispose_engine(), loop=loop)
            _deadline = [time.monotonic() + 3]

            def _check_shutdown():
                if t_stop.done() and t_dispose.done():
                    event.accept()
                elif time.monotonic() < _deadline[0]:
                    QTimer.singleShot(10, _check_shutdown)
                else:
                    logger.warning("Shutdown timed out, forzando cierre")
                    event.accept()

            _check_shutdown()
            return  # closeEvent completes asynchronously via _check_shutdown
    except RuntimeError:
        logger.debug("Event loop ya cerrado, omitiendo shutdown asíncrono")
    except Exception as e:
        logger.debug(f"Error en shutdown: {e}")
    event.accept()

Functions

desktop.maestro_tab

Maestro Tab — chat, streaming, diagrama, agentes, y stats.

Classes

MaestroTab

Bases: QWidget

Source code in desktop/maestro_tab.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
class MaestroTab(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._streaming_bubble = None
        self._streaming_text = ""
        self._typing_label = None
        self._history: list[dict] = []
        self._selected_agent: str | None = None
        self._force_agent: str | None = None
        self._workflow_running = False
        self._paused_session: Session | None = None
        self._scroll_pending = False
        self._current_project_root: str | None = None
        self._mode: str = "chat"
        self._conversation_id: int | None = None

        # Perf: differential-update caches to avoid redundant widget writes
        self._last_stats: dict[str, str] = {}
        self._last_progress: int = -1
        self._last_subtasks: list | None = None
        self._last_files: list | None = None
        self._last_diagram_html: str | None = None
        self._status_log_started: bool = False

        # Widgets set by panel builders (declared for mypy)
        self._toggle_style_active: str = ""
        self._toggle_style_inactive: str = ""
        self.mode_label: QLabel
        self.ws_label: QLabel
        self._chat_toggle: QPushButton
        self._orchestrate_toggle: QPushButton
        self._project_label: QLabel
        self._project_combo: QComboBox
        self._new_proj_btn: QPushButton
        self._import_proj_btn: QPushButton
        self._agent_combo: QComboBox
        self._preload_btn: QPushButton
        self._preload_status: QLabel
        self._preload_progress: QProgressBar
        self.offline_btn: QPushButton
        self.clear_btn: QPushButton
        self.download_btn: QPushButton
        self.download_format: QComboBox
        self._new_conv_btn: QPushButton
        self.chat_scroll: QScrollArea
        self.chat_container: QWidget
        self.chat_layout: QVBoxLayout
        self.input_field: QTextEdit
        self.pdf_path_field: QLineEdit
        self.pdf_load_btn: QPushButton
        self.send_btn: QPushButton
        self._detail_tabs: QTabWidget
        self._diagram_view: QTextBrowser
        self._status_log_view: QTextBrowser
        self.status_log: QTextBrowser  # backward-compat alias
        self._subtask_list: QListWidget
        self._files_written_list: QListWidget
        self._progress_bar: QProgressBar
        self.stat_labels: dict = {}
        self._current_pdf_text: str = ""

        self._build_ui()
        self._connect_maestro()

    def _build_ui(self):
        from desktop.panels import (
            build_chat_panel,
            build_detail_panel,
            build_execution_panel,
            build_top_bar,
        )
        from desktop.widgets.agent_panel import AgentPanel
        from desktop.widgets.bash_panel import BashPanel

        self.agent_panel = AgentPanel()
        self.bash_panel = BashPanel()

        root = QVBoxLayout(self)
        root.setContentsMargins(0, 0, 0, 0)
        root.setSpacing(0)
        root.addWidget(build_top_bar(self))

        columns = QSplitter(Qt.Orientation.Horizontal)
        columns.setContentsMargins(6, 6, 6, 6)

        execution = build_execution_panel(self)
        execution.setMinimumWidth(200)
        columns.addWidget(execution)

        chat = build_chat_panel(self)
        chat.setMinimumWidth(300)
        columns.addWidget(chat)

        detail = build_detail_panel(self)
        detail.setMinimumWidth(280)
        columns.addWidget(detail)

        columns.setStretchFactor(0, 1)
        columns.setStretchFactor(1, 3)
        columns.setStretchFactor(2, 1)

        root.addWidget(columns, 1)

    def eventFilter(self, obj, event):
        """Ctrl+Enter para enviar desde el QTextEdit multilínea."""
        if obj is self.input_field and event.type() == QEvent.Type.KeyPress:
            if (
                event.key() == Qt.Key.Key_Return
                and event.modifiers() == Qt.KeyboardModifier.ControlModifier
            ):
                self.send_message()
                return True
        elif obj is self.chat_scroll.viewport() and event.type() == QEvent.Type.Resize:
            w = obj.width()
            if w > 0:
                self.chat_container.setFixedWidth(w)
        return super().eventFilter(obj, event)

    def _populate_agents(self, allowed: list[str] | None):
        """Fill the agent selector combo, optionally filtered by an allowlist."""
        combo = self._agent_combo
        combo.blockSignals(True)
        combo.clear()
        combo.addItem("🤖 Auto", None)
        registered = agents_registry.list_agents()
        for name in sorted(registered.keys()):
            if allowed is not None and name not in allowed:
                continue
            combo.addItem(name.capitalize(), name)
        target = self._force_agent or self._selected_agent
        idx = combo.findData(target) if target else 0
        combo.setCurrentIndex(idx if idx >= 0 else 0)
        combo.blockSignals(False)
        self._update_agent_detail()

    def _on_agent_combo_changed(self, _index: int):
        name = self._agent_combo.currentData()
        if name:
            self._select_agent(name)
        else:
            self._force_agent = None
            self._selected_agent = None
            self._update_agent_detail()

    def _select_agent(self, name: str):
        self._selected_agent = name
        self._update_agent_detail()
        # In chat mode: activate agent for direct conversation
        if self._mode == "chat":
            self._force_agent = name
            self._on_system(f"Conversación directa con: **{name.capitalize()}**")

    def _update_agent_detail(self):
        """Show the selected agent's profile as the combo tooltip."""
        if not self._selected_agent:
            self._agent_combo.setToolTip("Selecciona un agente (o Auto)")
            return
        profile = agents_registry.get_profile(self._selected_agent)
        if profile:
            prompt = profile.get("system_prompt", "Sin prompt")[:200]
            tools = profile.get("tools", [])
            self._agent_combo.setToolTip(
                f"{prompt}...\nHerramientas: {', '.join(tools) if tools else 'Ninguna'}"
            )
        else:
            self._agent_combo.setToolTip("Sin perfil definido")

    def _build_stats_panel(self) -> QGroupBox:
        group = QGroupBox("Estado en tiempo real")
        group.setStyleSheet(StyleFactory.group_box())
        layout = QVBoxLayout(group)
        layout.setSpacing(6)

        self._progress_bar = QProgressBar()
        self._progress_bar.setRange(0, 100)
        self._progress_bar.setValue(0)
        self._progress_bar.setFormat("—")
        self._progress_bar.setStyleSheet(StyleFactory.progress_bar())
        layout.addWidget(self._progress_bar)

        self.stat_labels = {}
        for key in ["subtasks_total", "elapsed_time", "tokens_used", "current_agent", "status"]:
            row = QHBoxLayout()
            label = QLabel(key.replace("_", " ").capitalize())
            label.setStyleSheet(f"color: {COLORS['text_secondary']}; font-size: 12px;")
            value = QLabel("—")
            value.setStyleSheet(
                f"color: {COLORS['text_primary']}; font-size: 12px; font-weight: bold;"
            )
            row.addWidget(label)
            row.addStretch()
            row.addWidget(value)
            layout.addLayout(row)
            self.stat_labels[key] = value
        return group

    def _connect_maestro(self):
        from desktop.events import get_signals

        signals = get_signals()
        signals.system_message.connect(self._on_system)
        signals.assistant_message.connect(self._on_assistant)
        signals.agent_message.connect(self._on_agent_message)
        signals.user_message.connect(self._on_user)
        signals.stream_chunk.connect(self._on_stream)
        signals.stats_update.connect(self._on_stats)
        signals.diagram_update.connect(self._on_diagram)
        signals.workspace_changed.connect(self._on_workspace_switch)
        signals.offline_changed.connect(lambda offline: self._refresh_offline_indicator())
        signals.indexing_progress.connect(self._on_indexing_progress)

    # ── Public methods for Dashboard ──

    def launch_workflow(self, workflow_name: str):
        """Called from Dashboard when a workflow card is clicked."""
        from core.workflow_state import set_active_workflow
        from core.workspaces import get_global_workspaces
        from orchestration.loader import load_workflow_template

        set_active_workflow(workflow_name)
        ws = get_global_workspaces().current
        template = load_workflow_template(workspace_name=ws, workflow_name=workflow_name)
        self._force_agent = None
        self._selected_agent = None
        self._set_mode("orchestrate", silent=True)
        self._orchestrate_toggle.setEnabled(True)

        desc = template.get("description", "") if template else ""
        self._on_system(f"Workflow activated: **{workflow_name}**\n{desc}")

    def _on_workspace_switch(self, ws_name: str):
        """Refresh agent panel when workspace changes from dashboard."""
        self.ws_label.setText(ws_name)
        self._force_agent = None
        self._selected_agent = None
        self._set_mode(self._mode)  # Refresh agent panel for current mode

    def launch_agent(self, agent_name: str):
        """Llamado desde el Dashboard al hacer clic en una card de agente."""
        normalized = agent_name.lower()
        self._force_agent = normalized
        self._selected_agent = normalized
        self._set_mode("chat", silent=True)
        self._orchestrate_toggle.setEnabled(False)

        self._on_system(f"Conversación directa con: **{agent_name}**")

    # ── Qt signal callbacks ──

    def _on_system(self, msg: str):
        if "[bash_manager]" in msg:
            self.bash_panel.set_output(msg[-3000:])
        self._append_status(msg, "#888888")

    def _on_assistant(self, msg: str):
        self._add_bubble(msg, "assistant")

    def _on_user(self, msg: str):
        self._add_bubble(msg, "user")

    def _on_agent_message(self, agent_name: str, label: str, text: str):
        self.agent_panel.add_response(agent_name, label, text)
        # Store with agent metadata for export, and formatted content for DB
        content = f"[{agent_name.capitalize()} - {label}]\n{text}"
        self._history.append(
            {"role": "agent", "agent": agent_name, "label": label, "content": content}
        )

    def _append_status(self, msg: str, color: str = "#888888"):
        """Append a line to the status log (O(1) — no full-document reparse)."""
        timestamp = datetime.now(UTC).strftime("%H:%M:%S")
        entry = (
            f"<span style='color:{color}; font-size:12px;'>"
            f"<span style='color:#555'>{timestamp}</span>  {msg}</span>"
        )
        if not self._status_log_started:
            self.status_log.clear()
            self._status_log_started = True
        self.status_log.append(entry)

    def _on_stream(self, text: str):
        if self._streaming_bubble is None:
            self._hide_typing()
            self._streaming_text = ""
            self._streaming_bubble = self._add_bubble("", "assistant")
        self._streaming_text += text
        self._streaming_bubble.update_text(self._streaming_text)
        if not self._scroll_pending:
            self._scroll_pending = True
            QTimer.singleShot(100, self._throttled_scroll)

    def _on_stats(self, data: dict):
        for key, label in self.stat_labels.items():
            if key not in data:
                continue
            value = str(data[key])
            if key == "subtasks_total":
                completed = data.get("subtasks_completed", 0)
                total = data[key]
                value = f"{completed} / {total}"
                if total > 0:
                    pct = int(completed / total * 100)
                    if pct != self._last_progress:
                        self._progress_bar.setValue(pct)
                        self._progress_bar.setFormat(f"{completed}/{total} subtareas")
                        self._last_progress = pct
            if self._last_stats.get(key) != value:
                label.setText(value)
                self._last_stats[key] = value
                if key == "status":
                    label.setStyleSheet(
                        "color: #22C55E; font-size: 12px; font-weight: bold;"
                        if "completado" in value.lower()
                        else "color: #F59E0B; font-size: 12px; font-weight: bold;"
                    )

        subtask_list = data.get("subtask_list")
        if subtask_list is not None and subtask_list != self._last_subtasks:
            self._last_subtasks = list(subtask_list)
            self._subtask_list.clear()
            for item in subtask_list:
                name = item.get("name", "")
                status = item.get("status", "pending")
                icon = {"completed": "✅", "running": "🔵", "failed": "❌", "pending": "⏳"}.get(
                    status, "⏳"
                )
                self._subtask_list.addItem(f"{icon}  {name}")

        files_written = data.get("files_written")
        if isinstance(files_written, list) and files_written and files_written != self._last_files:
            self._last_files = list(files_written)
            self._files_written_list.clear()
            for f in files_written:
                self._files_written_list.addItem(f"  {f}")

    def _on_diagram(self, html: str, graph=None):
        if html != self._last_diagram_html:
            self._diagram_view.setHtml(html)
            self._last_diagram_html = html

    # ── Chat ──

    def _add_bubble(self, text: str, role: str):
        from desktop.widgets.chat_bubble import ChatBlock

        bubble = ChatBlock(text, role)
        self.chat_layout.addWidget(bubble)
        self.chat_container.adjustSize()
        QTimer.singleShot(50, self._scroll_to_bottom)
        if role == "system" and self._is_internal_message(text):
            return None
        if text.strip() or role == "system":
            self._history.append({"role": role, "content": text})
        return bubble

    @staticmethod
    def _is_internal_message(text: str) -> bool:
        internal = (
            "[bash_manager]",
            "Eres Morphix",
            "Reglas anti-frustración",
            "Mantén siempre esta identidad",
            "Soy Morphix, un asistente experto",
        )
        return any(p in text for p in internal)

    def _show_typing(self):
        if self._typing_label is None:
            self._typing_label = QLabel("Generando")
            self._typing_label.setStyleSheet("color: #A0A0A0; font-style: italic; padding: 8px;")
            self.chat_layout.addWidget(self._typing_label)
            self.chat_container.adjustSize()
            self._typing_dots = 0
        if hasattr(self, "_typing_timer") and self._typing_timer is not None:
            self._typing_timer.stop()
        self._typing_timer = QTimer(self)
        self._typing_timer.timeout.connect(self._animate_typing)
        self._typing_timer.start(400)

    def _animate_typing(self):
        if self._typing_label is None:
            return
        self._typing_dots = (self._typing_dots + 1) % 4
        self._typing_label.setText("Generando" + "." * self._typing_dots)

    def _hide_typing(self):
        if self._typing_label is not None:
            if self._typing_timer:
                self._typing_timer.stop()
            self.chat_layout.removeWidget(self._typing_label)
            self._typing_label.deleteLater()
            self._typing_label = None
            self.chat_container.adjustSize()

    def clear_chat(self):
        self._hide_typing()
        while self.chat_layout.count() > 0:
            item = self.chat_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
        self._history.clear()
        self._streaming_bubble = None
        self._streaming_text = ""
        self.chat_container.adjustSize()
        self.agent_panel.clear()
        self._subtask_list.clear()
        self._files_written_list.clear()
        self._last_stats.clear()
        self._last_progress = -1
        self._last_subtasks = None
        self._last_files = None
        self._last_diagram_html = None
        self._status_log_started = False
        self.status_log.setHtml(
            "<p style='color:#888; text-align:center'>Listo. Envía una consulta</p>"
        )
        self._on_system("Chat limpiado")

    def _new_conversation(self):
        self.clear_chat()
        self._conversation_id = None
        self._on_system("✨ Nueva conversación iniciada")

    async def load_conversation(self, conv_id: int):
        """Load all messages from a conversation and prepare to continue it."""
        from core.repositories.conversation_repository import ConversationRepository

        try:
            messages = await ConversationRepository.get_messages(conv_id)
            if not messages:
                self._on_system(f"⚠️ Conversación #{conv_id} no tiene mensajes")
                return

            self.clear_chat()
            for m in messages:
                role = m["role"]
                content = m["content"]
                if role in ("user", "assistant", "system", "agent", "tool"):
                    self._add_bubble(content, role)

            self._conversation_id = conv_id
            self._on_system(f"📖 Conversación #{conv_id} cargada ({len(messages)} mensajes)")
        except Exception as e:
            logger.error(f"Error loading conversation #{conv_id}: {e}", exc_info=True)
            self._on_system(f"❌ Error al cargar conversación #{conv_id}: {e}")

    def _scroll_to_bottom(self):
        sb = self.chat_scroll.verticalScrollBar()
        if sb:
            sb.setValue(sb.maximum())

    def _throttled_scroll(self):
        self._scroll_pending = False
        self._scroll_to_bottom()

    # ── Actions ──

    def _toggle_offline(self):
        from desktop.services.config_service import ConfigService

        ConfigService.toggle_offline_mode()
        self._refresh_offline_indicator()
        from desktop.events import get_signals

        get_signals().offline_changed.emit(settings.offline_mode)

    def _refresh_offline_indicator(self):
        """Actualiza los indicadores locales de modo offline."""
        is_off = settings.offline_mode
        self.offline_btn.setText("Desactivar Offline" if is_off else "Activar Offline")
        self.mode_label.setText("Offline" if is_off else "Online")
        self.mode_label.setStyleSheet(
            f"color: {'#F59E0B' if is_off else '#22C55E'}; font-size: 11px; font-weight: bold;"
        )

    def _load_pdf(self):
        path = self.pdf_path_field.text().strip()
        if not path:
            return
        try:
            from tools.pdf_reader import PDFReader

            text = PDFReader.read_pdf(path)
            if text and not text.startswith("Error"):
                self._current_pdf_text = text
                self._on_system(
                    f"📄 PDF cargado ({len(text)} caracteres): {os.path.basename(path)}"
                )
            else:
                self._on_system(f"❌ {text}")
        except Exception as e:
            logger.debug(f"Error cargando PDF: {e}", exc_info=True)
            self._on_system(f"❌ Error cargando PDF: {e}")

    def _download_conversation(self):
        if not self._history:
            return
        if self._workflow_running:
            self._on_system("⚠️ Espera a que termine el workflow antes de exportar.")
            return

        fmt = self.download_format.currentText()
        from core.path_resolver import paths

        exports_dir = paths.exports_dir()
        exports_dir.mkdir(parents=True, exist_ok=True)

        # If we have a conversation_id, delegate to repository
        if self._conversation_id is not None:
            run_async(self._export_via_repository(self._conversation_id, fmt))
            return

        # No conversation_id — write from in-memory history
        export_ts = datetime.now(UTC).strftime("%Y-%m-%d_%H-%M-%S")
        internal = (
            "Eres Morphix",
            "Reglas anti-frustración",
            "Mantén siempre esta identidad",
            "Soy Morphix, un asistente experto",
        )

        try:
            filename = str(exports_dir / f"morphix_conversacion_nueva_{export_ts}.{fmt}")

            if fmt == "json":
                import json

                data = [
                    {
                        "role": m.get("role", "?"),
                        "content": m.get("content", ""),
                        "agent": m.get("agent"),
                        "label": m.get("label"),
                    }
                    for m in self._history
                    if not (
                        m.get("role") == "system"
                        and any(p in m.get("content", "") for p in internal)
                    )
                ]
                with open(filename, "w", encoding="utf-8") as f:
                    json.dump(data, f, indent=4, ensure_ascii=False)
                self._on_system(f"✅ Exportado: **{filename}**")

            elif fmt == "md":
                with open(filename, "w", encoding="utf-8") as f:
                    f.write("# Conversación Morphix\n")
                    f.write(
                        f"**Fecha:** {datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S')}\n\n---\n\n"
                    )
                    for msg in self._history:
                        role = msg.get("role", "?")
                        content = msg.get("content", "")
                        if role == "system" and any(p in content for p in internal):
                            continue
                        if role == "assistant":
                            f.write(f"**🤖 Maestro:**\n{content}\n\n---\n\n")
                        elif role == "user":
                            f.write(f"**👤 Usuario:**\n{content}\n\n---\n\n")
                        elif role == "agent":
                            agent = msg.get("agent", "agente")
                            label = msg.get("label", "")
                            f.write(f"**🧠 {agent.capitalize()} ({label}):**\n{content}\n\n---\n\n")
                        elif role == "tool":
                            f.write(f"**🔧 Herramienta:**\n{content}\n\n---\n\n")
                        else:
                            f.write(f"**⚙️ {role}:**\n{content}\n\n---\n\n")
                self._on_system(f"✅ Guardado: **{filename}**")

            elif fmt == "pdf":
                from reportlab.lib.pagesizes import letter
                from reportlab.lib.styles import getSampleStyleSheet
                from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer

                data = [
                    m
                    for m in self._history
                    if not (
                        m.get("role") == "system"
                        and any(p in m.get("content", "") for p in internal)
                    )
                ]

                doc = SimpleDocTemplate(filename, pagesize=letter)
                styles = getSampleStyleSheet()
                story = []
                story.append(Paragraph("Conversación Morphix", styles["Title"]))
                story.append(Spacer(1, 12))
                for msg in data:
                    role = msg.get("role", "?")
                    content = msg.get("content", "")
                    label = {
                        "assistant": "🤖 Maestro",
                        "user": "👤 Usuario",
                        "agent": f"🧠 {msg.get('agent', 'agente').capitalize()}",
                        "tool": "🔧 Herramienta",
                    }.get(role, f"⚙️ {role}")
                    story.append(Paragraph(f"<b>{label}:</b> {content}", styles["Normal"]))
                    story.append(Spacer(1, 12))
                doc.build(story)

            elif fmt == "html":
                from html import escape

                try:
                    from pygments import highlight
                    from pygments.formatters import HtmlFormatter
                    from pygments.lexers import get_lexer_by_name, guess_lexer
                    from pygments.util import ClassNotFound

                    formatter = HtmlFormatter(style="default", noclasses=True)

                    def _hl_code(text: str) -> str:
                        import re

                        def _repl(m):
                            lang = m.group(1) or "python"
                            code = m.group(2)
                            try:
                                lexer = get_lexer_by_name(lang, stripall=True)
                            except ClassNotFound:
                                try:
                                    lexer = guess_lexer(code)
                                except ClassNotFound:
                                    lexer = get_lexer_by_name("text")
                            return highlight(code, lexer, formatter)

                        return re.sub(r"```(\w*)\n(.*?)```", _repl, text, flags=re.DOTALL)

                except ImportError:

                    def _hl_code(text: str) -> str:
                        return f"<pre><code>{escape(text)}</code></pre>"

                with open(filename, "w", encoding="utf-8") as f:
                    f.write('<!DOCTYPE html>\n<html lang="es">\n<head>\n')
                    f.write('<meta charset="utf-8">\n')
                    f.write("<title>Conversación Morphix</title>\n")
                    f.write("<style>")
                    f.write(
                        "body{font-family:Arial,sans-serif;max-width:900px;margin:40px auto;"
                        "padding:20px;background:#fafafa;color:#222}"
                        "h1{color:#333;border-bottom:2px solid #ddd;padding-bottom:8px}"
                        ".msg{margin:12px 0;padding:12px;border-radius:6px;background:#fff;"
                        "box-shadow:0 1px 3px rgba(0,0,0,.1)}"
                        ".role{font-weight:bold;font-size:.9em;color:#555}"
                        ".content{margin-top:6px;line-height:1.5}"
                        "hr{border:0;border-top:1px solid #eee;margin:20px 0}"
                        ".highlight{background:#f4f4f4;border-radius:4px;padding:10px;"
                        "overflow-x:auto;font-size:.9em}"
                    )
                    f.write("</style>\n</head>\n<body>\n")
                    f.write("<h1>Conversación Morphix</h1>\n")
                    f.write(
                        f"<p><strong>Fecha:</strong> "
                        f"{datetime.now(UTC).strftime('%Y-%m-%d %H:%M:%S')}</p>\n"
                        "<hr>\n"
                    )
                    for msg in self._history:
                        role = msg.get("role", "unknown")
                        content = msg.get("content", "")
                        role_label = {
                            "assistant": "Maestro",
                            "user": "Usuario",
                            "agent": "Agente",
                            "tool": "Herramienta",
                        }.get(role, role.capitalize())
                        f.write(f'<div class="msg">\n<p class="role">{role_label}:</p>\n')
                        f.write(f'<div class="content">{_hl_code(content)}</div>\n')
                        f.write("</div>\n<hr>\n")
                    f.write("</body>\n</html>")

            self._on_system(f"✅ Exportado: **{filename}**")

        except Exception as e:
            logger.error(f"Error guardando conversación: {e}", exc_info=True)
            self._on_system(f"❌ Error al guardar: {e}")

    async def _export_via_repository(self, conv_id: int, fmt: str):
        """Export a saved conversation via the repository."""
        from core.path_resolver import paths
        from core.repositories.conversation_repository import ConversationRepository

        project_path = None
        if self._current_project_root:
            proj_dir = paths.memory_dir("main") / self._current_project_root
            if proj_dir.exists():
                project_path = str(proj_dir)
        filename = await ConversationRepository.export(conv_id, fmt, project_path=project_path)
        if filename:
            self._on_system(f"✅ Exportado: **{filename}**")
        else:
            self._on_system(f"❌ Error al exportar conversación #{conv_id}")

    def _set_mode(self, mode: str, silent: bool = False):
        previous_mode = self._mode
        self._mode = mode
        if mode != previous_mode:
            self._conversation_id = None  # reset on mode switch
        if mode == "chat":
            self._chat_toggle.setStyleSheet(self._toggle_style_active)
            self._orchestrate_toggle.setStyleSheet(self._toggle_style_inactive)
        else:
            self._chat_toggle.setStyleSheet(self._toggle_style_inactive)
            self._orchestrate_toggle.setStyleSheet(self._toggle_style_active)

        # Panel de agentes: dictado por _force_agent o por el modo
        if self._force_agent:
            self._populate_agents([self._force_agent])
        elif mode == "orchestrate":
            from core.workflow_state import get_active_workflow
            from core.workspaces import get_global_workspaces
            from orchestration.loader import load_workflow_template

            ws = get_global_workspaces().current
            template = load_workflow_template(
                workspace_name=ws, workflow_name=get_active_workflow()
            )
            allowed = template.get("agents", {}).get("allowed") if template else None
            self._populate_agents(allowed)
        else:
            self._populate_agents(None)

        self._update_agent_detail()

        # Show message when entering chat mode
        if mode == "chat" and not silent:
            agent = self._force_agent or "conversacional"
            if self._force_agent:
                self._on_system(f"Conversación directa con: **{agent.capitalize()}**")
            else:
                self._on_system(
                    f"Conversación directa con: **{agent.capitalize()}** "
                    "(por defecto — selecciona un agente)"
                )

        # Reset agent forcing + show message when entering orchestrate mode
        if mode == "orchestrate" and not silent:
            self._force_agent = None
            self._selected_agent = None
            self._on_system(
                "⚙️ Modo Orquestar activado — el sistema elegirá el mejor agente por tarea"
            )

    def _create_project(self):
        from PySide6.QtWidgets import QInputDialog

        from core.path_resolver import paths

        name, ok = QInputDialog.getText(self, "Nuevo proyecto", "Nombre del proyecto:", text="")
        if not ok or not name:
            return
        name = name.strip().lower().replace(" ", "_")
        if not name or not name.isidentifier():
            self._on_system("❌ Nombre inválido. Usa solo letras, números y _")
            return
        root = f"code_projects/{name}"
        proj_dir = paths.memory_dir("main") / root
        proj_dir.mkdir(parents=True, exist_ok=True)
        self._current_project_root = root
        self._update_project_display(name)
        self._refresh_project_list()
        self._on_system(f"✅ Proyecto '{name}' creado y activado.")
        self._preload_btn.setEnabled(True)
        self._preload_status.setText("")
        if self._mode == "chat":
            self._set_mode("orchestrate")
            self._on_system("⚙️ Modo cambiado a Orquestar automáticamente.")

    def _import_project(self):
        import shutil
        from pathlib import Path

        from core.path_resolver import paths

        src = QFileDialog.getExistingDirectory(self, "Seleccionar proyecto para importar")
        if not src:
            return

        src_path = Path(src)
        name = src_path.name.lower().replace(" ", "_")
        dst = paths.memory_dir("main") / "code_projects" / name

        if dst.exists():
            self._on_system(f"❌ Ya existe un proyecto llamado '{name}'")
            return

        try:
            self._on_system(f"📂 Copiando '{src_path.name}' → code_projects/{name}...")
            shutil.copytree(str(src_path), str(dst))
        except Exception as e:
            logger.warning("Unhandled exception in MaestroTab", exc_info=True)
            self._on_system(f"❌ Error copiando proyecto: {e}")
            return

        self._current_project_root = f"code_projects/{name}"
        self._update_project_display(name)
        self._refresh_project_list()
        self._preload_btn.setEnabled(True)
        self._preload_status.setText("")
        file_count = sum(1 for _ in dst.rglob("*") if _.is_file())
        self._on_system(f"✅ Proyecto '{name}' importado ({file_count} archivos)")

    def _preload_project(self):
        if not self._current_project_root:
            self._on_system("❌ Selecciona un proyecto primero")
            return
        self._preload_btn.setEnabled(False)
        self.input_field.setEnabled(False)
        self._preload_progress.setVisible(True)
        self._preload_progress.setValue(0)
        self._preload_status.setText("⏳ Indexando...")
        run_async(self._do_preload())

    async def _do_preload(self):
        from asyncio import CancelledError

        from core.codebase_indexer import CodebaseIndexer
        from desktop.events import get_signals

        indexer = CodebaseIndexer(workspace="main", project_root=self._current_project_root)

        def _on_progress(data: dict):
            try:
                get_signals().indexing_progress.emit(data)
            except Exception:
                logger.warning("Unhandled exception in MaestroTab", exc_info=True)

        try:
            chunks = await asyncio.to_thread(
                indexer.index_project, force=True, progress_callback=_on_progress
            )
        except CancelledError:
            return  # app cerrada durante indexing, ignorar

        self._preload_btn.setEnabled(True)
        self.input_field.setEnabled(True)
        self._preload_progress.setVisible(False)
        self._preload_status.setText(f"✅ {chunks} chunks en FAISS")

    def _on_indexing_progress(self, data: dict):
        pct = data.get("pct", 0)
        self._preload_progress.setValue(pct)
        self._preload_status.setText(
            f"⏳ {data.get('current_file', '')} ({data.get('files_scanned', 0)} archivos)"
        )

    def _on_project_combo_changed(self, _index):
        name = self._project_combo.currentData()
        if name:
            self._switch_project(name)
        elif self._current_project_root is not None:
            self._current_project_root = None
            self._project_label.setText("Proyecto: —")
            self._project_label.setStyleSheet("color: #A0A0A0; font-size: 10px; padding: 2px 4px;")
            from desktop.events import get_signals

            get_signals().project_changed.emit("")

    def _switch_project(self, name: str):
        if not name:
            return
        root = f"code_projects/{name}"
        self._current_project_root = root
        self._update_project_display(name)
        self._on_system(f"✅ Cambiado a proyecto '{name}'.")
        self._preload_btn.setEnabled(True)
        self._preload_status.setText("")

    def _update_project_display(self, name: str):
        self._project_label.setText(f"Proyecto: {name}")
        self._project_label.setStyleSheet("color: #22C55E; font-size: 10px; padding: 2px 4px;")
        idx = self._project_combo.findData(name)
        if idx >= 0:
            self._project_combo.blockSignals(True)
            self._project_combo.setCurrentIndex(idx)
            self._project_combo.blockSignals(False)
        from desktop.events import get_signals

        get_signals().project_changed.emit(self._current_project_root or "")

    def _refresh_project_list(self):
        """Escanea code_projects/ y llena el dropdown de proyectos."""
        from core.path_resolver import paths

        base = paths.memory_dir("main") / "code_projects"
        self._project_combo.blockSignals(True)
        self._project_combo.clear()
        self._project_combo.addItem("— sin proyecto —", None)
        if base.exists():
            for d in sorted(base.iterdir()):
                if d.is_dir() and not d.name.startswith("."):
                    self._project_combo.addItem(d.name, d.name)
        # Restore selection to the current project
        if self._current_project_root:
            current_name = (
                self._current_project_root.split("/")[-1]
                if "/" in self._current_project_root
                else self._current_project_root
            )
            idx = self._project_combo.findData(current_name)
            if idx >= 0:
                self._project_combo.setCurrentIndex(idx)
        self._project_combo.blockSignals(False)

    def send_message(self):
        if self._paused_session is not None:
            answer = self.input_field.toPlainText().strip()
            if not answer:
                return
            self._add_bubble(answer, "user")
            self.input_field.clear()
            self._show_typing()
            self._streaming_bubble = None
            self._streaming_text = ""
            session = self._paused_session
            self._paused_session = None
            run_async(self._resume_workflow(session, answer))
            return

        if self._workflow_running:
            return
        query = self.input_field.toPlainText().strip()
        if not query:
            return

        # Guard: Orquestar requiere proyecto (excepto workflows que no lo necesitan)
        if self._mode == "orchestrate" and not self._current_project_root:
            from core.workflow_state import get_active_workflow
            from core.workspaces import get_global_workspaces
            from orchestration.loader import load_workflow_template

            template = load_workflow_template(
                workspace_name=get_global_workspaces().current,
                workflow_name=get_active_workflow(),
            )
            if template.get("type") != "collaborative":
                self._on_system(
                    "❌ Modo Orquestar requiere un proyecto. Crea uno con el botón ➕ Nuevo proyecto."
                )
                self.input_field.clear()
                return

        # Chat mode: always direct conversation with an agent
        if self._mode == "chat":
            agent = self._force_agent or "conversacional"
            self._workflow_running = True
            self._add_bubble(query, "user")
            self.input_field.clear()
            self._show_typing()
            self._streaming_bubble = None
            self._streaming_text = ""
            run_async(self._run_direct_agent(query, agent))
            return

        self._workflow_running = True
        self._add_bubble(query, "user")
        self.input_field.clear()
        self._show_typing()
        self._streaming_bubble = None
        self._streaming_text = ""

        enc = get_encoding()

        from core.workflow_state import get_active_workflow
        from core.workspaces import get_global_workspaces
        from orchestration.context import Session

        ctx = WorkflowContext(
            query=query,
            mode=self._mode,
            conversation_history=list(self._history),
            current_pdf_text=self._current_pdf_text,
            workspace=get_global_workspaces().current,
            project_root=self._current_project_root,
            active_workflow=get_active_workflow(),
            force_agent=self._force_agent,
            settings=settings,
            agents_registry=agents_registry,
            enc=enc,
            conversation_id=self._conversation_id,
            is_follow_up=self._conversation_id is not None,
        )

        from desktop.events import build_workflow_events

        events = build_workflow_events()
        session = Session(context=ctx, events=events)

        run_async(self._run_workflow(session))

    async def _run_workflow(self, session):
        from orchestration.workflows.orchestrator import WorkflowOrchestrator

        try:
            final = await WorkflowOrchestrator.run_full_workflow(session=session)
            ctx = session.context

            if final == "[PAUSED:clarification_needed]":
                question = ctx.last_clarification or "¿Podrías clarificar?"
                self._on_system(f"⏸️ Pausa: {question}")
                self._paused_session = session
                self._workflow_running = False
                self._hide_typing()
                self.input_field.setPlaceholderText(f"Responde: {question[:60]}...")
                return

            if ctx.project_root:
                self._current_project_root = ctx.project_root
            streaming_text = self._streaming_text

            had_streaming = self._streaming_bubble is not None
            had_content = bool(streaming_text.strip())

            self._streaming_bubble = None
            self._streaming_text = ""

            # Show final result: prefer streaming bubble (already visible),
            # fall back to explicit return value
            if had_streaming and had_content:
                self._history.append({"role": "assistant", "content": streaming_text.strip()})
            elif final:
                self._on_assistant(final)
            elif not had_content:
                self._on_system("⚠️ El workflow no produjo respuesta.")

            # Track conversation_id for follow-up messages in same session
            if self._conversation_id is None:
                try:
                    from core.repositories.conversation_repository import ConversationRepository

                    recent = await ConversationRepository.list_all(limit=1)
                    if recent:
                        self._conversation_id = recent[0]["id"]
                except Exception:
                    logger.warning("Unhandled exception in MaestroTab", exc_info=True)

            # Persist agent/tool messages to DB (these arrive during workflow
            # execution via emit_agent and are in self._history but NOT in
            # the conversation_history snapshot passed to finalize_workflow).
            if self._conversation_id is not None:
                try:
                    # Find agent/tool entries added to history during workflow
                    snapshot_len = len(ctx.conversation_history)
                    new_entries = self._history[snapshot_len:]
                    agent_tool_entries = [
                        m for m in new_entries if m.get("role") in ("agent", "tool")
                    ]
                    if agent_tool_entries:
                        from core.repositories.conversation_repository import ConversationRepository

                        await ConversationRepository.add_messages(
                            self._conversation_id, agent_tool_entries
                        )
                except Exception:
                    logger.warning("Unhandled exception in MaestroTab", exc_info=True)
        except Exception as e:
            logger.error(f"Error en workflow: {e}", exc_info=True)
            self._on_system(f"❌ Error: {e}")
        finally:
            self._hide_typing()
            self._workflow_running = False

    async def _resume_workflow(self, session, answer: str):
        """Reanuda un workflow pausado tras recibir respuesta de clarificación."""
        from orchestration.workflows.orchestrator import WorkflowOrchestrator

        try:
            final = await WorkflowOrchestrator.resume_workflow(session=session, answer=answer)
            ctx = session.context

            if final == "[PAUSED:clarification_needed]":
                question = ctx.last_clarification or "¿Podrías clarificar?"
                self._on_system(f"⏸️ Pausa adicional: {question}")
                self._paused_session = session
                self._hide_typing()
                self.input_field.setPlaceholderText(f"Responde: {question[:60]}...")
                return

            streaming_text = self._streaming_text
            had_streaming = self._streaming_bubble is not None
            had_content = bool(streaming_text.strip())
            self._streaming_bubble = None
            self._streaming_text = ""

            if had_streaming and had_content:
                self._history.append({"role": "assistant", "content": streaming_text.strip()})
            elif final:
                self._on_assistant(final)

            if self._conversation_id is None:
                try:
                    from core.repositories.conversation_repository import ConversationRepository

                    recent = await ConversationRepository.list_all(limit=1)
                    if recent:
                        self._conversation_id = recent[0]["id"]
                except Exception:
                    logger.warning("Unhandled exception in MaestroTab", exc_info=True)
        except Exception as e:
            logger.error(f"Error resumiendo workflow: {e}", exc_info=True)
            self._on_system(f"❌ Error: {e}")
        finally:
            self._hide_typing()
            self._workflow_running = False
            self.input_field.setPlaceholderText("Escribe tu mensaje...")

    async def _run_direct_agent(self, query: str, agent: str | None = None):
        """Ejecuta conversación directa 1:1 con un agente (con function-calling nativo)."""
        agent = agent or self._force_agent or "conversacional"
        from desktop.events import build_workflow_events

        # Events so bash/system/stats reach the GUI also in chat mode.
        events = build_workflow_events()
        try:

            async def _stream(text: str):
                self._on_stream(text)

            current_history = list(self._history)

            # Get agent profile + tools with workflow template filtering
            from agents.registry import agents_registry as _reg
            from core.workflow_state import get_active_workflow
            from core.workspaces import get_global_workspaces
            from orchestration.loader import load_workflow_template
            from orchestration.loop import execute_agent_loop
            from tools.specs import expand_allowed_tools

            agent_profile = _reg.get_profile(agent)
            agent_tools = agent_profile.get("tools", []) if agent_profile else []
            workspace = get_global_workspaces().current

            # Filter tools against active workflow template if available
            effective_tools = None
            if agent_tools:
                expanded_tools = expand_allowed_tools(agent_tools) or []
                try:
                    template = load_workflow_template(
                        workspace_name=workspace, workflow_name=get_active_workflow()
                    )
                    workflow_allowed = (
                        template.get("tools", {}).get("allowed") if template else None
                    )
                    if workflow_allowed:
                        from tools.specs import (
                            tool_matches_allowlist,
                        )

                        allowed_list: list[str] = workflow_allowed  # type: ignore[assignment]
                        effective_tools = [
                            t for t in expanded_tools if tool_matches_allowlist(t, allowed_list)
                        ]
                except Exception:
                    logger.warning("Unhandled exception in MaestroTab", exc_info=True)
                if not effective_tools:
                    effective_tools = expanded_tools

                loop_result = await execute_agent_loop(
                    task=query,
                    agent_type=agent,
                    history=current_history,
                    allowed_tools=effective_tools,
                    workspace=workspace,
                    project_root=self._current_project_root,
                    on_stream_chunk=_stream,
                    events=events,
                )
                response = (
                    loop_result.get("result", str(loop_result))
                    if isinstance(loop_result, dict)
                    else str(loop_result)
                )
            else:
                # Agent has no tools — use text-only fallback
                from agents.service import AgentsService

                response = await AgentsService.execute_agent(
                    agent, query, current_history, on_stream_chunk=_stream
                )

            if self._streaming_bubble is not None:
                had_streaming = True
                had_content = bool(self._streaming_text.strip())
            else:
                had_streaming = False
                had_content = False

            self._streaming_bubble = None
            streaming_text = self._streaming_text
            self._streaming_text = ""

            if had_streaming and had_content:
                self._history.append({"role": "assistant", "content": streaming_text.strip()})
            elif response and response.strip():
                self._on_assistant(response)
            elif streaming_text.strip():
                if not self._history or self._history[-1].get("content") != streaming_text:
                    self._history.append({"role": "assistant", "content": streaming_text})
                self._on_assistant(streaming_text)
            elif not response or not response.strip():
                self._on_system(
                    f"⚠️ El agente no produjo respuesta. Estado: {loop_result.get('status', '?') if isinstance(loop_result, dict) else 'desconocido'}"
                )

            final_output = response or streaming_text
            if final_output:
                # Save conversation to database
                try:
                    from core.repositories.conversation_repository import ConversationRepository

                    messages_to_save = list(current_history)
                    messages_to_save.append({"role": "assistant", "content": final_output.strip()})

                    conv_id = await ConversationRepository.save(
                        title=query[:100],
                        user_message=query,
                        tags="chat",
                        workflow_id=None,
                        conversation_history=messages_to_save,
                        conversation_id=self._conversation_id,
                    )
                    if self._conversation_id is None:
                        self._conversation_id = conv_id
                    logger.info(f"Chat guardado: conversation_id={conv_id}")
                except Exception as e:
                    logger.warning(f"Error saving chat conversation: {e}")

                try:
                    from core.memory.manager import memory as memory_manager
                    from orchestration.finalizer import (
                        _extract_personal_facts,
                    )

                    facts = await _extract_personal_facts(final_output, query)
                    if facts:
                        await memory_manager.update_user_profile(facts)
                        logger.info(f"Perfil actualizado: {list(facts.keys())}")
                except Exception:
                    logger.warning("Unhandled exception in MaestroTab", exc_info=True)
        except Exception as e:
            logger.error(f"Error en agente directo: {e}", exc_info=True)
            self._on_system(f"❌ Error: {e}")
        finally:
            self._hide_typing()
            self._workflow_running = False
Functions
eventFilter
eventFilter(obj, event)

Ctrl+Enter para enviar desde el QTextEdit multilínea.

Source code in desktop/maestro_tab.py
def eventFilter(self, obj, event):
    """Ctrl+Enter para enviar desde el QTextEdit multilínea."""
    if obj is self.input_field and event.type() == QEvent.Type.KeyPress:
        if (
            event.key() == Qt.Key.Key_Return
            and event.modifiers() == Qt.KeyboardModifier.ControlModifier
        ):
            self.send_message()
            return True
    elif obj is self.chat_scroll.viewport() and event.type() == QEvent.Type.Resize:
        w = obj.width()
        if w > 0:
            self.chat_container.setFixedWidth(w)
    return super().eventFilter(obj, event)
launch_workflow
launch_workflow(workflow_name: str)

Called from Dashboard when a workflow card is clicked.

Source code in desktop/maestro_tab.py
def launch_workflow(self, workflow_name: str):
    """Called from Dashboard when a workflow card is clicked."""
    from core.workflow_state import set_active_workflow
    from core.workspaces import get_global_workspaces
    from orchestration.loader import load_workflow_template

    set_active_workflow(workflow_name)
    ws = get_global_workspaces().current
    template = load_workflow_template(workspace_name=ws, workflow_name=workflow_name)
    self._force_agent = None
    self._selected_agent = None
    self._set_mode("orchestrate", silent=True)
    self._orchestrate_toggle.setEnabled(True)

    desc = template.get("description", "") if template else ""
    self._on_system(f"Workflow activated: **{workflow_name}**\n{desc}")
launch_agent
launch_agent(agent_name: str)

Llamado desde el Dashboard al hacer clic en una card de agente.

Source code in desktop/maestro_tab.py
def launch_agent(self, agent_name: str):
    """Llamado desde el Dashboard al hacer clic en una card de agente."""
    normalized = agent_name.lower()
    self._force_agent = normalized
    self._selected_agent = normalized
    self._set_mode("chat", silent=True)
    self._orchestrate_toggle.setEnabled(False)

    self._on_system(f"Conversación directa con: **{agent_name}**")
load_conversation async
load_conversation(conv_id: int)

Load all messages from a conversation and prepare to continue it.

Source code in desktop/maestro_tab.py
async def load_conversation(self, conv_id: int):
    """Load all messages from a conversation and prepare to continue it."""
    from core.repositories.conversation_repository import ConversationRepository

    try:
        messages = await ConversationRepository.get_messages(conv_id)
        if not messages:
            self._on_system(f"⚠️ Conversación #{conv_id} no tiene mensajes")
            return

        self.clear_chat()
        for m in messages:
            role = m["role"]
            content = m["content"]
            if role in ("user", "assistant", "system", "agent", "tool"):
                self._add_bubble(content, role)

        self._conversation_id = conv_id
        self._on_system(f"📖 Conversación #{conv_id} cargada ({len(messages)} mensajes)")
    except Exception as e:
        logger.error(f"Error loading conversation #{conv_id}: {e}", exc_info=True)
        self._on_system(f"❌ Error al cargar conversación #{conv_id}: {e}")

Functions

desktop.dashboard_tab

Dashboard Tab — workspace, workflow, navegación, métricas, offline, self-reflection.

Classes

DashboardTab

Bases: QWidget

Source code in desktop/dashboard_tab.py
 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
class DashboardTab(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._build_ui()
        self._connect_signals()
        run_async(self._load_data())

    def _build_ui(self):
        main = QVBoxLayout(self)
        main.setContentsMargins(20, 16, 20, 16)
        main.setSpacing(12)

        title = QLabel("Bienvenido a Morphix")
        title.setStyleSheet(f"font-size: 22px; font-weight: bold; color: {ACCENT};")
        main.addWidget(title)
        main.addSpacing(8)

        # System info group
        sys_group = QGroupBox("Sistema")
        sys_group.setStyleSheet(StyleFactory.group_box())
        sys_layout = QVBoxLayout(sys_group)

        # Mode indicator
        mode_row = QHBoxLayout()
        self.mode_icon = QLabel("☁")
        self.mode_icon.setStyleSheet("font-size: 18px;")
        self.mode_text = QLabel("Online")
        self.mode_text.setStyleSheet(
            f"color: {COLORS['success']}; font-size: 13px; font-weight: bold;"
        )
        mode_row.addWidget(self.mode_icon)
        mode_row.addWidget(self.mode_text)
        mode_row.addStretch()

        self.offline_btn = QPushButton("Activar Offline")
        self.offline_btn.setStyleSheet(
            f"QPushButton {{ background: {ACCENT}; color: #FFF; border-radius: 6px; padding: 6px 12px; font-size: 11px; }}"
        )
        self.offline_btn.clicked.connect(self._toggle_offline)
        mode_row.addWidget(self.offline_btn)
        sys_layout.addLayout(mode_row)

        sys_layout.addWidget(QLabel("Workspace activo"))
        ws_row = QHBoxLayout()
        ws_row.setSpacing(6)
        self.workspace_combo = QComboBox()
        self.workspace_combo.setStyleSheet(
            f"QComboBox {{ background: {COLORS['bg_surface']}; "
            f"color: {COLORS['text_primary']}; border: 1px solid {COLORS['border_default']}; "
            f"border-radius: 4px; padding: 6px; }}"
        )
        ws_row.addWidget(self.workspace_combo, 1)
        self.new_ws_btn = QPushButton("+ Nuevo")
        self.new_ws_btn.setStyleSheet(StyleFactory.secondary_button())
        self.new_ws_btn.clicked.connect(self._create_workspace)
        ws_row.addWidget(self.new_ws_btn)
        sys_layout.addLayout(ws_row)

        # Self-reflection toggle
        self.self_reflection_cb = QCheckBox("Self-Reflection (agentes se auto-revisan)")
        self.self_reflection_cb.setStyleSheet(
            f"color: {COLORS['text_secondary']}; font-size: 12px;"
        )
        self.self_reflection_cb.toggled.connect(self._toggle_self_reflection)
        sys_layout.addWidget(self.self_reflection_cb)

        # Plugin count + metrics
        self.info_label = QLabel("Cargando...")
        self.info_label.setStyleSheet(f"color: {COLORS['text_secondary']}; font-size: 12px;")
        self.info_label.setWordWrap(True)
        sys_layout.addWidget(self.info_label)

        # Navigation cards — Workflows + Dynamic agents
        modules_group = QGroupBox("Módulos")
        modules_group.setStyleSheet(sys_group.styleSheet())
        modules_layout = QVBoxLayout(modules_group)
        modules_layout.setSpacing(12)

        # Workflows
        wf_group = QGroupBox("Workflows")
        wf_group.setStyleSheet(
            "QGroupBox { color: #E5E5E5; font-weight: bold; border: none;"
            "margin-top: 4px; padding-top: 8px; }"
            "QGroupBox::title { subcontrol-origin: margin; left: 0px; }"
        )
        self.workflows_layout = QVBoxLayout(wf_group)
        self.workflows_layout.setSpacing(4)
        modules_layout.addWidget(wf_group)

        # Agentes
        ag_group = QGroupBox("Agentes")
        ag_group.setStyleSheet(wf_group.styleSheet())
        self.dash_agents_layout = QGridLayout(ag_group)
        self.dash_agents_layout.setSpacing(6)
        modules_layout.addWidget(ag_group)

        row = QHBoxLayout()
        row.addWidget(sys_group, 1)
        row.addWidget(modules_group, 2)
        main.addLayout(row, 1)

        # Botones de logs
        log_btn_style = StyleFactory.secondary_button()
        log_row = QHBoxLayout()
        open_logs_btn = QPushButton("Abrir Logs")
        open_logs_btn.setStyleSheet(log_btn_style)
        open_logs_btn.clicked.connect(self._open_logs)
        open_lnav_btn = QPushButton("lnav")
        open_lnav_btn.setStyleSheet(log_btn_style)
        open_lnav_btn.clicked.connect(self._open_logs_lnav)
        dark_btn = QPushButton("Tema")
        dark_btn.setStyleSheet(log_btn_style)
        dark_btn.clicked.connect(self._toggle_theme)
        restart_btn = QPushButton("Reiniciar")
        restart_btn.setStyleSheet(log_btn_style)
        restart_btn.clicked.connect(self._restart_app)
        log_row.addStretch()
        log_row.addWidget(open_logs_btn)
        log_row.addWidget(open_lnav_btn)
        log_row.addWidget(dark_btn)
        log_row.addWidget(restart_btn)
        main.addLayout(log_row)

        main.addStretch()

    def _connect_signals(self):
        self.workspace_combo.currentTextChanged.connect(self._on_workspace_changed)
        from desktop.events import get_signals

        get_signals().offline_changed.connect(lambda offline: self._refresh_offline_indicators())
        get_signals().workspace_changed.connect(self._on_external_workspace_change)

    async def _load_data(self):
        try:
            from core.metrics import metrics as m
            from core.workspaces import get_global_workspaces

            ws = get_global_workspaces()
            schemas = await ws.list_workspaces()

            self.workspace_combo.blockSignals(True)
            self.workspace_combo.clear()
            self.workspace_combo.addItems(schemas)
            self.workspace_combo.setCurrentText(ws.current)
            self.workspace_combo.blockSignals(False)

            from core.feature_flags import kairos

            self.self_reflection_cb.blockSignals(True)
            self.self_reflection_cb.setChecked(kairos.get("AGENT_SELF_REFLECTION", False))
            self.self_reflection_cb.blockSignals(False)

            self._refresh_offline_indicators()

            data = m.to_dict()
            self.info_label.setText(
                f"Tokens: {data['total_tokens']} | "
                f"Workflows: {data['completed_workflows']}/{data['total_workflows']} | "
                f"Uptime: {data['uptime_seconds']}s"
            )

            self._refresh_modules()

        except Exception as e:
            logger.exception("Error cargando datos del dashboard")
            self.info_label.setText(f"Error: {e}")

    def _refresh_modules(self):
        """Repuebla las cards de Workflows y Agentes dinámicamente."""
        from agents.registry import agents_registry
        from core.workspaces import get_global_workspaces
        from orchestration.loader import list_workflows, load_workflow_template

        ws = get_global_workspaces().current

        card_style = StyleFactory.card_button()

        # Repopulate Workflows
        while self.workflows_layout.count():
            item = self.workflows_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()

        workflows = list_workflows(ws)
        for wf_name in workflows:
            template = load_workflow_template(ws, wf_name)
            desc = template.get("description", "") if template else ""
            label = f"{wf_name}"
            if desc:
                label += f"  —  {desc[:80]}{'...' if len(desc) > 80 else ''}"

            btn = QPushButton(label)
            btn.setStyleSheet(card_style)
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            if desc:
                btn.setToolTip(desc[:200])
            btn.clicked.connect(
                lambda checked, n=wf_name: self._navigate("maestro", {"workflow": n})
            )
            self.workflows_layout.addWidget(btn)

        # Repopulate Agentes
        while self.dash_agents_layout.count():
            item = self.dash_agents_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()

        registered = agents_registry.list_agents()
        col = 0
        row = 0
        for agent_name in sorted(registered.keys()):
            profile = agents_registry.get_profile(agent_name)
            tools = profile.get("tools", []) if profile else []
            tool_info = f" ({len(tools)} tools)" if tools else ""
            label = f"{agent_name.capitalize()}{tool_info}"

            btn = QPushButton(label)
            btn.setStyleSheet(StyleFactory.card_button())
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            btn.clicked.connect(
                lambda checked, n=agent_name: self._navigate("maestro", {"agent": n})
            )
            self.dash_agents_layout.addWidget(btn, row, col)

            col += 1
            if col >= 2:
                col = 0
                row += 1

    def _create_workspace(self):
        from PySide6.QtWidgets import QInputDialog, QMessageBox

        name, ok = QInputDialog.getText(
            self,
            "Nuevo Workspace",
            "Nombre del workspace (minúsculas, números, _):",
            text="",
        )
        if not ok or not name:
            return
        name = name.strip().lower().replace(" ", "_")
        if not name or not name[0].isalpha():
            QMessageBox.warning(self, "Inválido", "El nombre debe empezar con letra (a-z).")
            return

        import re

        if not re.match(r"^[a-z][a-z0-9_]*$", name):
            QMessageBox.warning(self, "Inválido", "Solo minúsculas, números y guiones bajos.")
            return

        async def _create():
            from core.workspaces import get_global_workspaces, switch_workspace_handler

            ws = get_global_workspaces()
            schemas = await ws.list_workspaces()

            if name in schemas:
                self.new_ws_btn.setEnabled(False)
                self.new_ws_btn.setText("Cargando...")
                await switch_workspace_handler(name)
                await self._load_data()
                from desktop.events import get_signals

                get_signals().workspace_changed.emit(name)
                self.new_ws_btn.setEnabled(True)
                self.new_ws_btn.setText("+ Nuevo")
                return

            self.new_ws_btn.setEnabled(False)
            self.new_ws_btn.setText("Creando...")
            await ws.create_workspace(name)
            await self._load_data()
            from desktop.events import get_signals

            get_signals().workspace_changed.emit(name)
            self.new_ws_btn.setEnabled(True)
            self.new_ws_btn.setText("+ Nuevo")

        run_async(_create())

    def _on_workspace_changed(self, name: str):
        if not name:
            return

        async def _switch():
            from core.workspaces import switch_workspace_handler

            await switch_workspace_handler(name)
            await self._load_data()
            from desktop.events import get_signals

            get_signals().workspace_changed.emit(name)

        run_async(_switch())

    def _on_external_workspace_change(self, name: str):
        """Refresh dashboard when workspace changes from another tab."""
        if name and name != self.workspace_combo.currentText():
            self.workspace_combo.blockSignals(True)
            self.workspace_combo.setCurrentText(name)
            self.workspace_combo.blockSignals(False)
            run_async(self._load_data())

    def _toggle_offline(self):
        from core.config import settings
        from desktop.services.config_service import ConfigService

        ConfigService.toggle_offline_mode()
        self._refresh_offline_indicators()
        from desktop.events import get_signals

        get_signals().offline_changed.emit(settings.offline_mode)

    def _refresh_offline_indicators(self):
        """Actualiza los indicadores de estado offline sin recargar todo."""
        from core.config import settings as s

        is_off = s.offline_mode
        self.mode_icon.setText("☁" if not is_off else "⛔")
        self.mode_text.setText("Online" if not is_off else "Offline")
        self.mode_icon.setStyleSheet(
            f"font-size: 18px; color: {'#22C55E' if not is_off else '#F59E0B'};"
        )
        self.mode_text.setStyleSheet(
            f"color: {'#22C55E' if not is_off else '#F59E0B'}; font-size: 13px; font-weight: bold;"
        )
        self.offline_btn.setText("Desactivar Offline" if is_off else "Activar Offline")

    def _toggle_self_reflection(self, enabled: bool):
        from core.feature_flags import kairos

        kairos.set("AGENT_SELF_REFLECTION", enabled)

    def _open_logs(self):
        from desktop.services.dashboard_service import DashboardService

        result = DashboardService.open_logs()
        if not result.get("success"):
            parent = self.window()
            if parent and hasattr(parent, "status"):
                parent.status.showMessage(f"Error abriendo logs: {result.get('message', '')}", 5000)

    def _open_logs_lnav(self):
        from desktop.services.dashboard_service import DashboardService

        result = DashboardService.open_logs_lnav()
        if not result.get("success"):
            parent = self.window()
            if parent and hasattr(parent, "status"):
                parent.status.showMessage(f"Error con lnav: {result.get('message', '')}", 5000)

    def _toggle_theme(self):
        from core.config import settings
        from desktop.services.config_service import ConfigService

        ConfigService.toggle_dark_mode(not settings.dark_mode)
        parent = self.window()
        if parent and hasattr(parent, "status"):
            parent.status.showMessage(
                f"Tema {'oscuro' if settings.dark_mode else 'claro'} (reinicia para aplicar)", 5000
            )

    def _restart_app(self):
        from desktop.services.config_service import ConfigService

        result = ConfigService.restart_application()
        if not result.get("success"):
            parent = self.window()
            if parent and hasattr(parent, "status"):
                parent.status.showMessage(f"Error al reiniciar: {result.get('message', '')}", 5000)

    def _navigate(self, route: str, context: dict | None = None):
        parent = self.window()
        if parent and hasattr(parent, "tabs"):
            tabs = parent.tabs
            tab_map = {
                "maestro": "Maestro",
                "historial": "Historial",
                "integraciones": "Integraciones",
                "configuración": "Config",
                "analytics": "Analytics",
            }
            target = tab_map.get(route)
            if target:
                for i in range(tabs.count()):
                    if tabs.tabText(i) == target:
                        widget = tabs.widget(i)
                        if route == "maestro" and context and hasattr(widget, "launch_workflow"):
                            if "workflow" in context:
                                widget.launch_workflow(context["workflow"])
                            elif "agent" in context:
                                widget.launch_agent(context["agent"])
                        tabs.setCurrentIndex(i)
                        break

Functions

desktop.editor_tab

Editor Tab — visualizador/editor de archivos del proyecto activo.

Detecta el proyecto activado en Maestro, muestra su directorio (estructurado) en un árbol, permite visualizar y editar el contenido de los archivos, y crear, renombrar o eliminar archivos/carpetas.

Classes

EditorTab

Bases: QWidget

Árbol de archivos del proyecto + editor de texto.

Source code in desktop/editor_tab.py
class EditorTab(QWidget):
    """Árbol de archivos del proyecto + editor de texto."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self._workspace = "main"
        self._project_root: str | None = None
        self._project_dir: Path | None = None
        self._current_file: Path | None = None
        self._dirty = False
        self._build_ui()

    # ── UI ──────────────────────────────────────────────────────────

    def _build_ui(self):
        splitter = QSplitter(Qt.Orientation.Horizontal, self)

        # ── Left column: tree ──
        left = QWidget()
        left.setMinimumWidth(200)
        left_layout = QVBoxLayout(left)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(4)

        self._project_label = QLabel("Proyecto: —")
        self._project_label.setStyleSheet("color: #A0A0A0; font-size: 11px; padding: 2px;")
        self._project_label.setWordWrap(True)
        left_layout.addWidget(self._project_label)

        btn_row = QHBoxLayout()
        btn_row.setSpacing(4)
        btn_style = StyleFactory.small_button()
        self._new_file_btn = QPushButton("➕ Archivo")
        self._new_file_btn.setStyleSheet(btn_style)
        self._new_file_btn.clicked.connect(lambda: self._new_file(self._project_dir))
        self._new_dir_btn = QPushButton("📁 Carpeta")
        self._new_dir_btn.setStyleSheet(btn_style)
        self._new_dir_btn.clicked.connect(lambda: self._new_folder(self._project_dir))
        self._refresh_btn = QPushButton("⟳")
        self._refresh_btn.setStyleSheet(btn_style)
        self._refresh_btn.clicked.connect(self._refresh)
        btn_row.addWidget(self._new_file_btn)
        btn_row.addWidget(self._new_dir_btn)
        btn_row.addWidget(self._refresh_btn)
        left_layout.addLayout(btn_row)

        self._fs_model = QFileSystemModel()
        self._proxy = _NoiseFilter(self)
        self._proxy.setSourceModel(self._fs_model)

        self._tree = QTreeView()
        self._tree.setModel(self._proxy)
        for col in (1, 2, 3):  # hide size/type/date → show only Name
            self._tree.hideColumn(col)
        self._tree.setHeaderHidden(True)
        self._tree.setStyleSheet(StyleFactory.tree_view())
        self._tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self._tree.customContextMenuRequested.connect(self._on_context_menu)
        self._tree.clicked.connect(self._on_tree_clicked)
        left_layout.addWidget(self._tree, 1)
        splitter.addWidget(left)

        # ── Columna derecha: editor (flexible) ──
        right = QWidget()
        right_layout = QVBoxLayout(right)
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(4)

        head = QHBoxLayout()
        self._path_label = QLabel("Selecciona un archivo del árbol")
        self._path_label.setStyleSheet("color: #A0A0A0; font-size: 11px; padding: 2px;")
        self._save_btn = QPushButton("💾 Guardar")
        self._save_btn.setStyleSheet(
            f"QPushButton {{ background: {ACCENT}; color: #FFFFFF; border-radius: 6px; "
            "padding: 4px 12px; font-size: 11px; font-weight: bold; }}"
            "QPushButton:disabled { background: #2A2A2A; color: #666; }"
        )
        self._save_btn.clicked.connect(self._save)
        self._save_btn.setEnabled(False)
        head.addWidget(self._path_label, 1)
        head.addWidget(self._save_btn)
        right_layout.addLayout(head)

        self._editor = QPlainTextEdit()
        self._editor.setReadOnly(True)
        self._editor.setFont(QFont("monospace", 11))
        self._editor.setStyleSheet(StyleFactory.text_editor())
        self._editor.textChanged.connect(self._on_text_changed)
        right_layout.addWidget(self._editor, 1)

        self._status_label = QLabel("")
        self._status_label.setStyleSheet("color: #888; font-size: 11px; padding: 2px;")
        right_layout.addWidget(self._status_label)

        right.setMinimumWidth(300)
        splitter.addWidget(right)
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 3)

        main_layout = QHBoxLayout(self)
        main_layout.setContentsMargins(6, 6, 6, 6)
        main_layout.addWidget(splitter)
        self._set_project(None)

    # ── Proyecto activo ─────────────────────────────────────────────

    def set_project(self, project_root: str | None, workspace: str = "main"):
        """Llamado por MaestroTab/MainWindow cuando cambia el proyecto activo."""
        self._workspace = workspace or "main"
        self._set_project(project_root or None)

    def _set_project(self, project_root: str | None):
        if not self._maybe_discard_changes():
            return
        self._project_root = project_root
        self._current_file = None
        self._editor.blockSignals(True)
        self._editor.clear()
        self._editor.blockSignals(False)
        self._editor.setReadOnly(True)
        self._save_btn.setEnabled(False)
        self._dirty = False
        self._path_label.setText("Selecciona un archivo del árbol")
        self._status_label.setText("")

        if not project_root:
            self._project_dir = None
            self._project_label.setText("Proyecto: — (crea/selecciona uno en Maestro)")
            self._tree.setRootIndex(QModelIndex())
            self._set_ops_enabled(False)
            return

        self._project_dir = paths.code_projects_dir(self._workspace, project_root)
        self._project_dir.mkdir(parents=True, exist_ok=True)
        name = Path(project_root).name
        self._project_label.setText(f"Proyecto: {name}")
        self._fs_model.setRootPath(str(self._project_dir))
        src = self._fs_model.index(str(self._project_dir))
        self._tree.setRootIndex(self._proxy.mapFromSource(src))
        self._set_ops_enabled(True)

    def _set_ops_enabled(self, enabled: bool):
        self._new_file_btn.setEnabled(enabled)
        self._new_dir_btn.setEnabled(enabled)
        self._refresh_btn.setEnabled(enabled)

    def _refresh(self):
        if self._project_dir:
            self._fs_model.setRootPath("")
            self._fs_model.setRootPath(str(self._project_dir))
            src = self._fs_model.index(str(self._project_dir))
            self._tree.setRootIndex(self._proxy.mapFromSource(src))

    # ── Tree → editor ──────────────────────────────────────────────

    def _path_from_index(self, proxy_idx: QModelIndex) -> Path | None:
        if not proxy_idx.isValid():
            return None
        src = self._proxy.mapToSource(proxy_idx)
        return Path(self._fs_model.filePath(src))

    def _on_tree_clicked(self, proxy_idx: QModelIndex):
        path = self._path_from_index(proxy_idx)
        if path and path.is_file():
            self._open_file(path)

    def _open_file(self, path: Path):
        if not self._maybe_discard_changes():
            return
        try:
            if path.stat().st_size > MAX_FILE_SIZE:
                self._show_readonly(f"[Archivo demasiado grande para editar: {path.name}]")
                return
            data = path.read_bytes()
            if b"\x00" in data[:4096]:
                self._show_readonly(f"[Archivo binario — no editable: {path.name}]")
                return
            text = data.decode("utf-8", errors="replace")
        except Exception as e:
            self._status_label.setText(f"❌ No se pudo abrir: {e}")
            return

        self._current_file = path
        self._editor.blockSignals(True)
        self._editor.setPlainText(text)
        self._editor.blockSignals(False)
        self._editor.setReadOnly(False)
        self._dirty = False
        self._save_btn.setEnabled(False)
        self._path_label.setText(self._rel(path))
        self._status_label.setText("")

    def _show_readonly(self, msg: str):
        self._current_file = None
        self._editor.blockSignals(True)
        self._editor.setPlainText(msg)
        self._editor.blockSignals(False)
        self._editor.setReadOnly(True)
        self._save_btn.setEnabled(False)
        self._dirty = False

    def _rel(self, path: Path) -> str:
        try:
            return str(path.relative_to(self._project_dir)) if self._project_dir else str(path)
        except ValueError:
            return str(path)

    def _on_text_changed(self):
        if self._current_file is not None and not self._editor.isReadOnly():
            self._dirty = True
            self._save_btn.setEnabled(True)

    # ── Guardar ─────────────────────────────────────────────────────

    def _inside_project(self, path: Path) -> bool:
        if self._project_dir is None:
            return False
        try:
            path.resolve().relative_to(self._project_dir.resolve())
            return True
        except ValueError:
            return False

    def _save(self):
        if self._current_file is None:
            return
        if not self._inside_project(self._current_file):
            self._status_label.setText("❌ Ruta fuera del proyecto")
            return
        try:
            self._current_file.write_text(self._editor.toPlainText(), encoding="utf-8")
            self._dirty = False
            self._save_btn.setEnabled(False)
            self._status_label.setText(f"✅ Guardado: {self._current_file.name}")
        except Exception as e:
            self._status_label.setText(f"❌ Error al guardar: {e}")

    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_S and event.modifiers() == Qt.KeyboardModifier.ControlModifier:
            self._save()
            return
        super().keyPressEvent(event)

    def _maybe_discard_changes(self) -> bool:
        """Devuelve True si se puede continuar (guardó/descartó), False si canceló."""
        if not self._dirty or self._current_file is None:
            return True
        reply = QMessageBox.question(
            self,
            "Cambios sin guardar",
            f"'{self._current_file.name}' tiene cambios sin guardar. ¿Guardar?",
            QMessageBox.StandardButton.Save
            | QMessageBox.StandardButton.Discard
            | QMessageBox.StandardButton.Cancel,
            QMessageBox.StandardButton.Save,
        )
        if reply == QMessageBox.StandardButton.Cancel:
            return False
        if reply == QMessageBox.StandardButton.Save:
            self._save()
        self._dirty = False
        return True

    # ── Operaciones de archivo ──────────────────────────────────────

    def _on_context_menu(self, point):
        proxy_idx = self._tree.indexAt(point)
        path = self._path_from_index(proxy_idx)
        target_dir = self._project_dir
        if path is not None:
            target_dir = path if path.is_dir() else path.parent

        menu = QMenu(self)
        menu.addAction("➕ Nuevo archivo", lambda: self._new_file(target_dir))
        menu.addAction("📁 Nueva carpeta", lambda: self._new_folder(target_dir))
        if path is not None:
            menu.addSeparator()
            menu.addAction("✏️ Renombrar", lambda: self._rename(path))
            menu.addAction("🗑️ Eliminar", lambda: self._delete(path))
        menu.exec(self._tree.viewport().mapToGlobal(point))

    def _new_file(self, target_dir: Path | None):
        if not target_dir:
            return
        name, ok = QInputDialog.getText(self, "Nuevo archivo", "Nombre del archivo:")
        if not ok or not name.strip():
            return
        dest = target_dir / name.strip()
        if not self._inside_project(dest):
            self._status_label.setText("❌ Ruta fuera del proyecto")
            return
        if dest.exists():
            self._status_label.setText("❌ Ya existe")
            return
        try:
            dest.write_text("", encoding="utf-8")
            self._open_file(dest)
        except Exception as e:
            self._status_label.setText(f"❌ Error: {e}")

    def _new_folder(self, target_dir: Path | None):
        if not target_dir:
            return
        name, ok = QInputDialog.getText(self, "Nueva carpeta", "Nombre de la carpeta:")
        if not ok or not name.strip():
            return
        dest = target_dir / name.strip()
        if not self._inside_project(dest):
            self._status_label.setText("❌ Ruta fuera del proyecto")
            return
        try:
            dest.mkdir(parents=True, exist_ok=True)
        except Exception as e:
            self._status_label.setText(f"❌ Error: {e}")

    def _rename(self, path: Path):
        new_name, ok = QInputDialog.getText(self, "Renombrar", "Nuevo nombre:", text=path.name)
        if not ok or not new_name.strip() or new_name.strip() == path.name:
            return
        dest = path.parent / new_name.strip()
        if not self._inside_project(dest):
            self._status_label.setText("❌ Ruta fuera del proyecto")
            return
        if dest.exists():
            self._status_label.setText("❌ Ya existe")
            return
        try:
            path.rename(dest)
            if self._current_file == path:
                self._open_file(dest) if dest.is_file() else self._show_readonly("")
        except Exception as e:
            self._status_label.setText(f"❌ Error: {e}")

    def _delete(self, path: Path):
        reply = QMessageBox.question(
            self,
            "Eliminar",
            f"¿Eliminar '{path.name}'?" + (" (y su contenido)" if path.is_dir() else ""),
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No,
        )
        if reply != QMessageBox.StandardButton.Yes:
            return
        if not self._inside_project(path):
            self._status_label.setText("❌ Ruta fuera del proyecto")
            return
        try:
            if path.is_dir():
                shutil.rmtree(path)
            else:
                path.unlink()
            if self._current_file == path:
                self._current_file = None
                self._editor.blockSignals(True)
                self._editor.clear()
                self._editor.blockSignals(False)
                self._editor.setReadOnly(True)
                self._save_btn.setEnabled(False)
                self._dirty = False
                self._path_label.setText("Selecciona un archivo del árbol")
            self._status_label.setText(f"🗑️ Eliminado: {path.name}")
        except Exception as e:
            self._status_label.setText(f"❌ Error: {e}")
Functions
set_project
set_project(
    project_root: str | None, workspace: str = "main"
)

Llamado por MaestroTab/MainWindow cuando cambia el proyecto activo.

Source code in desktop/editor_tab.py
def set_project(self, project_root: str | None, workspace: str = "main"):
    """Llamado por MaestroTab/MainWindow cuando cambia el proyecto activo."""
    self._workspace = workspace or "main"
    self._set_project(project_root or None)

desktop.analytics_tab

Analytics Tab — métricas del sistema en tiempo real.

Classes

Functions

desktop.config_tab

Config Tab — modelos, herramientas, sistema.

Classes

Functions

desktop.history_tab

History Tab — lista de conversaciones y detalle.

Classes

Functions

desktop.events

Event bridge — señales Qt ↔ WorkflowEvents (core).

Thread-safe: las señales Qt pueden emitirse desde cualquier hilo. Los slots se ejecutan en el hilo principal de Qt automáticamente.

Classes

DesktopSignals

Bases: QObject

Señales Qt emitidas durante la ejecución de un workflow.

Source code in desktop/events.py
class DesktopSignals(QObject):
    """Señales Qt emitidas durante la ejecución de un workflow."""

    stream_chunk = Signal(str)
    system_message = Signal(str)
    assistant_message = Signal(str)
    user_message = Signal(str)
    agent_message = Signal(str, str, str)  # agent_name, label, text
    stats_update = Signal(dict)
    diagram_update = Signal(str, object)
    offline_changed = Signal(bool)
    workspace_changed = Signal(str)
    project_changed = Signal(str)  # project_root activo ("" = sin proyecto)
    indexing_progress = Signal(dict)  # {phase, current_file, files_scanned, pct}

Functions

reset_approval_state

reset_approval_state() -> None

Clear session approval memory (e.g. on workspace switch).

Source code in desktop/events.py
def reset_approval_state() -> None:
    """Clear session approval memory (e.g. on workspace switch)."""
    _always_allowed.clear()

build_workflow_events

build_workflow_events() -> WorkflowEvents

Construye WorkflowEvents conectados a señales Qt.

Source code in desktop/events.py
def build_workflow_events() -> WorkflowEvents:
    """Construye WorkflowEvents conectados a señales Qt."""
    from orchestration.context import WorkflowEvents

    async def _stream(text: str) -> None:
        _get_signals().stream_chunk.emit(text)

    async def _system(text: str) -> None:
        _get_signals().system_message.emit(text)

    async def _assistant(text: str) -> None:
        _get_signals().assistant_message.emit(text)

    async def _user(text: str) -> None:
        _get_signals().user_message.emit(text)

    async def _agent(agent_name: str, label: str, text: str) -> None:
        _get_signals().agent_message.emit(agent_name, label, text)

    async def _stats(data: dict) -> None:
        _get_signals().stats_update.emit(data)

    async def _diagram(code: str, graph=None) -> None:
        _get_signals().diagram_update.emit(code, graph)

    async def _approval(tool_name: str, params: dict) -> bool:
        if tool_name in _always_allowed:
            return True

        params_text = _format_params(params)
        msg = (
            f"Allow execution of:\n\n"
            f"Tool: {tool_name}\n"
            f"Parameters:\n{params_text}\n\n"
            f"This tool can modify files or execute commands."
        )
        reply = QMessageBox.question(
            None,
            "Approve Tool Execution",
            msg,
            QMessageBox.StandardButton.Yes
            | QMessageBox.StandardButton.YesToAll
            | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No,
        )
        if reply == QMessageBox.StandardButton.YesToAll:
            _always_allowed.add(tool_name)
            return True
        return reply == QMessageBox.StandardButton.Yes

    async def _noop() -> None:
        pass

    return WorkflowEvents(
        on_stream_chunk=_stream,
        on_system_message=_system,
        on_assistant_message=_assistant,
        on_user_message=_user,
        on_agent_message=_agent,
        on_stats_update=_stats,
        on_diagram_update=_diagram,
        on_ui_refresh=_noop,
        on_approval_required=_approval,
    )

get_signals

get_signals() -> DesktopSignals

Retorna la instancia global de señales para conectar slots.

Source code in desktop/events.py
def get_signals() -> DesktopSignals:
    """Retorna la instancia global de señales para conectar slots."""
    return _get_signals()

desktop.async_helpers

Helpers para integración asyncio + Qt — seguro ante errores silenciosos.

Functions

run_async

run_async(coro, loop=None)

Ejecuta una corrutina en el event loop de forma segura.

A diferencia de asyncio.run_coroutine_threadsafe(), este helper registra un callback de error para que las excepciones no se pierdan silenciosamente.

Source code in desktop/async_helpers.py
def run_async(coro, loop=None):
    """Ejecuta una corrutina en el event loop de forma segura.

    A diferencia de asyncio.run_coroutine_threadsafe(), este helper
    registra un callback de error para que las excepciones no se pierdan
    silenciosamente.
    """
    try:
        loop = loop or asyncio.get_running_loop()
    except RuntimeError:
        loop = loop or asyncio.get_event_loop()
    future = asyncio.run_coroutine_threadsafe(coro, loop)

    def _log_error(fut):
        exc = fut.exception()
        if exc is None:
            return
        if isinstance(exc, asyncio.CancelledError):
            pass
        else:
            logger.error("Error en corrutina de fondo (Qt→asyncio): %s", exc)

    future.add_done_callback(_log_error)
    return future

desktop.services.config_service

Classes

ConfigService

Servicio centralizado para la lógica de configuración.

Source code in desktop/services/config_service.py
class ConfigService:
    """Servicio centralizado para la lógica de configuración."""

    @staticmethod
    def toggle_offline_mode():
        """Activa/desactiva modo offline (toggle)."""
        offline_manager.toggle_offline()
        logger.info(f"ConfigService: toggle_offline_mode → {settings.offline_mode}")
        return {"success": True, "offline_mode": settings.offline_mode}

    @staticmethod
    def restart_application():
        """Reinicia la aplicación de forma segura."""
        try:
            logging.info("Iniciando reinicio de aplicación...")
            python = os.sys.executable
            script = "run.py"

            if platform.system() == "Windows":
                subprocess.Popen([python, script], creationflags=subprocess.CREATE_NEW_CONSOLE)
            else:
                subprocess.Popen(
                    ["nohup", python, script],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.STDOUT,
                    preexec_fn=os.setpgrp,
                )

            threading.Timer(1.0, lambda: sys.exit(0)).start()
            return {"success": True}
        except Exception as e:
            logging.error(f"Error en restart: {e}")
            return {"success": False, "message": str(e)}

    @staticmethod
    def toggle_dark_mode(enabled: bool):
        """Cambia el tema dark/light."""
        settings.dark_mode = enabled
        return {"success": True}
Functions
toggle_offline_mode staticmethod
toggle_offline_mode()

Activa/desactiva modo offline (toggle).

Source code in desktop/services/config_service.py
@staticmethod
def toggle_offline_mode():
    """Activa/desactiva modo offline (toggle)."""
    offline_manager.toggle_offline()
    logger.info(f"ConfigService: toggle_offline_mode → {settings.offline_mode}")
    return {"success": True, "offline_mode": settings.offline_mode}
restart_application staticmethod
restart_application()

Reinicia la aplicación de forma segura.

Source code in desktop/services/config_service.py
@staticmethod
def restart_application():
    """Reinicia la aplicación de forma segura."""
    try:
        logging.info("Iniciando reinicio de aplicación...")
        python = os.sys.executable
        script = "run.py"

        if platform.system() == "Windows":
            subprocess.Popen([python, script], creationflags=subprocess.CREATE_NEW_CONSOLE)
        else:
            subprocess.Popen(
                ["nohup", python, script],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.STDOUT,
                preexec_fn=os.setpgrp,
            )

        threading.Timer(1.0, lambda: sys.exit(0)).start()
        return {"success": True}
    except Exception as e:
        logging.error(f"Error en restart: {e}")
        return {"success": False, "message": str(e)}
toggle_dark_mode staticmethod
toggle_dark_mode(enabled: bool)

Cambia el tema dark/light.

Source code in desktop/services/config_service.py
@staticmethod
def toggle_dark_mode(enabled: bool):
    """Cambia el tema dark/light."""
    settings.dark_mode = enabled
    return {"success": True}

desktop.services.dashboard_service

Classes

DashboardService

Servicio para la lógica de negocio del Dashboard.

Source code in desktop/services/dashboard_service.py
class DashboardService:
    """Servicio para la lógica de negocio del Dashboard."""

    @staticmethod
    def open_logs() -> dict:
        """Abre el archivo de logs con el visor por defecto del sistema."""
        try:
            log_path = str(paths.log_file())
            if platform.system() == "Windows":
                os.startfile(log_path)  # type: ignore[attr-defined]
            elif platform.system() == "Linux":
                subprocess.run(["xdg-open", log_path], check=False)
            else:
                subprocess.run(["open", log_path], check=False)
            return {"success": True}
        except Exception as e:
            logger.error("Error abriendo logs: %s", e)
            return {"success": False, "message": str(e)}

    @staticmethod
    def open_logs_lnav() -> dict:
        """Abre el archivo de logs con lnav (visor de logs en tiempo real)."""
        log_path = str(paths.log_file())
        if not os.path.exists(log_path):
            return {"success": False, "message": "Archivo de log no encontrado"}

        try:
            if platform.system() == "Linux":
                try:
                    subprocess.Popen(
                        ["x-terminal-emulator", "-e", f"lnav {log_path}"],
                        stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL,
                    )
                except FileNotFoundError:
                    subprocess.Popen(
                        ["gnome-terminal", "--", "lnav", log_path],
                        stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL,
                    )
            elif platform.system() == "Windows":
                subprocess.Popen(
                    ["cmd", "/c", "start", "lnav", log_path],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
            else:
                subprocess.Popen(
                    ["open", log_path],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
            return {"success": True}
        except FileNotFoundError:
            return {"success": False, "message": "lnav no encontrado"}
        except Exception as e:
            logger.error("Error abriendo logs con lnav: %s", e)
            return {"success": False, "message": str(e)}
Functions
open_logs staticmethod
open_logs() -> dict

Abre el archivo de logs con el visor por defecto del sistema.

Source code in desktop/services/dashboard_service.py
@staticmethod
def open_logs() -> dict:
    """Abre el archivo de logs con el visor por defecto del sistema."""
    try:
        log_path = str(paths.log_file())
        if platform.system() == "Windows":
            os.startfile(log_path)  # type: ignore[attr-defined]
        elif platform.system() == "Linux":
            subprocess.run(["xdg-open", log_path], check=False)
        else:
            subprocess.run(["open", log_path], check=False)
        return {"success": True}
    except Exception as e:
        logger.error("Error abriendo logs: %s", e)
        return {"success": False, "message": str(e)}
open_logs_lnav staticmethod
open_logs_lnav() -> dict

Abre el archivo de logs con lnav (visor de logs en tiempo real).

Source code in desktop/services/dashboard_service.py
@staticmethod
def open_logs_lnav() -> dict:
    """Abre el archivo de logs con lnav (visor de logs en tiempo real)."""
    log_path = str(paths.log_file())
    if not os.path.exists(log_path):
        return {"success": False, "message": "Archivo de log no encontrado"}

    try:
        if platform.system() == "Linux":
            try:
                subprocess.Popen(
                    ["x-terminal-emulator", "-e", f"lnav {log_path}"],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
            except FileNotFoundError:
                subprocess.Popen(
                    ["gnome-terminal", "--", "lnav", log_path],
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.DEVNULL,
                )
        elif platform.system() == "Windows":
            subprocess.Popen(
                ["cmd", "/c", "start", "lnav", log_path],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
        else:
            subprocess.Popen(
                ["open", log_path],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
            )
        return {"success": True}
    except FileNotFoundError:
        return {"success": False, "message": "lnav no encontrado"}
    except Exception as e:
        logger.error("Error abriendo logs con lnav: %s", e)
        return {"success": False, "message": str(e)}

desktop.services.analytics_service

Classes

AnalyticsService

Servicio completo de Analytics - versión asíncrona.

Source code in desktop/services/analytics_service.py
class AnalyticsService:
    """Servicio completo de Analytics - versión asíncrona."""

    @staticmethod
    async def load_analytics_data():  # <-- Ahora es async
        """Carga y procesa todas las conversaciones de forma asíncrona."""
        async with get_async_session() as session:
            # Consulta de conversaciones
            stmt = select(Conversation)
            result = await session.execute(stmt)
            convs = result.scalars().all()

            if not convs:
                return None, None

            data = []
            for c in convs:
                # Get messages from the conversation
                stmt_msgs = select(Message).where(Message.conversation_id == c.id)
                result_msgs = await session.execute(stmt_msgs)
                msgs = result_msgs.scalars().all()

                content_str = " ".join([m.content for m in msgs])
                tags_str = c.tags or ""
                parse_str = tags_str + " " + content_str

                # Extraer tokens
                tokens_match = re.search(
                    r"[\•*]\s*\*\*Tokens reales:\*\*\s*(\d+)", parse_str, re.IGNORECASE
                )
                tokens = int(tokens_match.group(1)) if tokens_match else 0

                # Extraer calidad
                quality_llm_match = re.search(r"\(LLM:\s*(\d+)/10\)", parse_str, re.IGNORECASE)
                if quality_llm_match:
                    quality = int(quality_llm_match.group(1))
                else:
                    quality_str_match = re.search(
                        r"[\•*]\s*\*\*Calidad:\*\*\s*(Alta|Media)", parse_str, re.IGNORECASE
                    )
                    quality = (
                        8
                        if quality_str_match and "alta" in quality_str_match.group(0).lower()
                        else 5
                    )

                data.append(
                    {
                        "id": c.id,
                        "title": c.title,
                        "created_at": c.created_at,
                        "tags": tags_str,
                        "tokens": tokens,
                        "quality": quality,
                    }
                )

            import pandas as pd

            df = pd.DataFrame(data)
            logger.info(f"Analytics cargados: {len(df)} conversaciones")
            return df, convs

    @staticmethod
    def generate_charts(df):
        """Genera los gráficos y devuelve las rutas (sin cambios)."""
        import matplotlib.pyplot as plt

        if df is None or df.empty:
            return None, None

        timestamp = int(time.time())

        # Token chart
        tokens_path = None
        if df["tokens"].sum() > 0:
            plt.figure(figsize=(12, 6))
            plt.plot(
                df["created_at"],
                df["tokens"],
                marker="o",
                linestyle="-",
                linewidth=3,
                markersize=10,
                color="royalblue",
            )
            plt.title("Uso de Tokens por Conversación", fontsize=18, fontweight="bold")
            plt.xlabel("Fecha")
            plt.ylabel("Tokens")
            plt.grid(True, alpha=0.4)
            plt.tight_layout()
            tokens_path = f"{CHARTS_DIR}/tokens_{timestamp}.png"
            plt.savefig(tokens_path, dpi=200)
            plt.close()

        # Quality chart
        quality_path = None
        avg_quality = df.groupby("tags")["quality"].mean()
        if avg_quality.sum() > 0:
            plt.figure(figsize=(12, 6))
            bars = avg_quality.plot(kind="bar", color="lightcoral", edgecolor="black", width=0.6)
            plt.title("Calidad Promedio por Tipo de Conversación", fontsize=18, fontweight="bold")
            plt.ylabel("Puntuación")
            plt.xticks(rotation=45, ha="right")
            plt.grid(True, alpha=0.4, axis="y")
            plt.tight_layout()

            for bar in bars.patches:
                height = bar.get_height()
                plt.text(
                    bar.get_x() + bar.get_width() / 2,
                    height + 0.2,
                    f"{height:.1f}",
                    ha="center",
                    fontsize=12,
                    fontweight="bold",
                )

            quality_path = f"{CHARTS_DIR}/quality_{timestamp}.png"
            plt.savefig(quality_path, dpi=200)
            plt.close()

        return tokens_path, quality_path
Functions
load_analytics_data async staticmethod
load_analytics_data()

Carga y procesa todas las conversaciones de forma asíncrona.

Source code in desktop/services/analytics_service.py
@staticmethod
async def load_analytics_data():  # <-- Ahora es async
    """Carga y procesa todas las conversaciones de forma asíncrona."""
    async with get_async_session() as session:
        # Consulta de conversaciones
        stmt = select(Conversation)
        result = await session.execute(stmt)
        convs = result.scalars().all()

        if not convs:
            return None, None

        data = []
        for c in convs:
            # Get messages from the conversation
            stmt_msgs = select(Message).where(Message.conversation_id == c.id)
            result_msgs = await session.execute(stmt_msgs)
            msgs = result_msgs.scalars().all()

            content_str = " ".join([m.content for m in msgs])
            tags_str = c.tags or ""
            parse_str = tags_str + " " + content_str

            # Extraer tokens
            tokens_match = re.search(
                r"[\•*]\s*\*\*Tokens reales:\*\*\s*(\d+)", parse_str, re.IGNORECASE
            )
            tokens = int(tokens_match.group(1)) if tokens_match else 0

            # Extraer calidad
            quality_llm_match = re.search(r"\(LLM:\s*(\d+)/10\)", parse_str, re.IGNORECASE)
            if quality_llm_match:
                quality = int(quality_llm_match.group(1))
            else:
                quality_str_match = re.search(
                    r"[\•*]\s*\*\*Calidad:\*\*\s*(Alta|Media)", parse_str, re.IGNORECASE
                )
                quality = (
                    8
                    if quality_str_match and "alta" in quality_str_match.group(0).lower()
                    else 5
                )

            data.append(
                {
                    "id": c.id,
                    "title": c.title,
                    "created_at": c.created_at,
                    "tags": tags_str,
                    "tokens": tokens,
                    "quality": quality,
                }
            )

        import pandas as pd

        df = pd.DataFrame(data)
        logger.info(f"Analytics cargados: {len(df)} conversaciones")
        return df, convs
generate_charts staticmethod
generate_charts(df)

Genera los gráficos y devuelve las rutas (sin cambios).

Source code in desktop/services/analytics_service.py
@staticmethod
def generate_charts(df):
    """Genera los gráficos y devuelve las rutas (sin cambios)."""
    import matplotlib.pyplot as plt

    if df is None or df.empty:
        return None, None

    timestamp = int(time.time())

    # Token chart
    tokens_path = None
    if df["tokens"].sum() > 0:
        plt.figure(figsize=(12, 6))
        plt.plot(
            df["created_at"],
            df["tokens"],
            marker="o",
            linestyle="-",
            linewidth=3,
            markersize=10,
            color="royalblue",
        )
        plt.title("Uso de Tokens por Conversación", fontsize=18, fontweight="bold")
        plt.xlabel("Fecha")
        plt.ylabel("Tokens")
        plt.grid(True, alpha=0.4)
        plt.tight_layout()
        tokens_path = f"{CHARTS_DIR}/tokens_{timestamp}.png"
        plt.savefig(tokens_path, dpi=200)
        plt.close()

    # Quality chart
    quality_path = None
    avg_quality = df.groupby("tags")["quality"].mean()
    if avg_quality.sum() > 0:
        plt.figure(figsize=(12, 6))
        bars = avg_quality.plot(kind="bar", color="lightcoral", edgecolor="black", width=0.6)
        plt.title("Calidad Promedio por Tipo de Conversación", fontsize=18, fontweight="bold")
        plt.ylabel("Puntuación")
        plt.xticks(rotation=45, ha="right")
        plt.grid(True, alpha=0.4, axis="y")
        plt.tight_layout()

        for bar in bars.patches:
            height = bar.get_height()
            plt.text(
                bar.get_x() + bar.get_width() / 2,
                height + 0.2,
                f"{height:.1f}",
                ha="center",
                fontsize=12,
                fontweight="bold",
            )

        quality_path = f"{CHARTS_DIR}/quality_{timestamp}.png"
        plt.savefig(quality_path, dpi=200)
        plt.close()

    return tokens_path, quality_path

desktop.services.history_service

Classes

HistoryService

Source code in desktop/services/history_service.py
class HistoryService:
    _redis_client = None

    @staticmethod
    async def _get_redis():
        if HistoryService._redis_client is None:
            try:
                from core.config import settings

                redis_url = settings.redis_url
                import redis.asyncio as aioredis

                HistoryService._redis_client = aioredis.from_url(
                    redis_url, socket_connect_timeout=2, socket_timeout=2
                )
                logger.info(f"Redis cache conectado: {redis_url}")
            except Exception as e:
                logger.warning(f"Redis no disponible: {e}")
                HistoryService._redis_client = None
        return HistoryService._redis_client

    @staticmethod
    async def load_conversations(query: str = "") -> list[Conversation]:
        async with get_async_session() as session:
            stmt = select(Conversation).order_by(Conversation.created_at.desc())  # type: ignore[attr-defined]

            if query:
                keyword = query.lower().strip()
                date_match = re.search(r"date:(\d{4}-\d{2}-\d{2})", keyword)
                tag_match = re.search(r"tag:(\w+)", keyword)

                if date_match:
                    target_date = datetime.datetime.strptime(date_match.group(1), "%Y-%m-%d").date()
                    stmt = stmt.where(Conversation.created_at.cast(datetime.date) == target_date)  # type: ignore[attr-defined]
                elif tag_match:
                    stmt = stmt.where(
                        Conversation.tags.ilike(  # type: ignore[union-attr]
                            func.concat("%", tag_match.group(1), "%")
                        )
                    )
                else:
                    keyword_escaped = keyword.replace("%", "\\%").replace("_", "\\_")
                    stmt = stmt.where(
                        Conversation.title.ilike(  # type: ignore[attr-defined]
                            func.concat("%", keyword_escaped, "%")
                        )
                        | Conversation.tags.ilike(  # type: ignore[union-attr]
                            func.concat("%", keyword_escaped, "%")
                        )
                    )

            result = await session.execute(stmt)
            conversations = result.scalars().all()

            if not conversations and query and not date_match and not tag_match:
                conversations = await HistoryService.semantic_search(query, session)
                conversations.sort(key=lambda c: c.created_at, reverse=True)

            return conversations

    @staticmethod
    async def semantic_search(query: str, session: AsyncSession) -> list[Conversation]:
        """Búsqueda semántica con FAISS + caché Redis (ejecuta encode en thread)."""
        import asyncio

        embed_model = _get_embed_model()
        query_emb = await asyncio.to_thread(embed_model.encode, query)

        stmt = select(Message).order_by(Message.id.desc()).limit(200)  # type: ignore[union-attr]
        result = await session.execute(stmt)
        all_msgs = result.scalars().all()

        if not all_msgs:
            return []

        import faiss
        import numpy as np

        r = await HistoryService._get_redis()
        embeddings = []
        for msg in all_msgs:
            cache_key = f"emb:{msg.id}"
            cached_emb = None
            if r:
                cached_emb = await r.get(cache_key)
            if cached_emb:
                emb = np.frombuffer(cached_emb, dtype=np.float32)
            else:
                emb = await asyncio.to_thread(embed_model.encode, msg.content)
                if r:
                    await r.set(cache_key, emb.tobytes(), ex=3600)
            embeddings.append(emb)

        embeddings_arr = np.array(embeddings).astype("float32")  # type: ignore[assignment]
        index = faiss.IndexFlatL2(embeddings_arr.shape[1])  # type: ignore[attr-defined]
        index.add(embeddings_arr)

        distances, indices = index.search(np.array([query_emb]).astype("float32"), 10)

        matched_ids = [
            all_msgs[idx].conversation_id
            for idx, dist in zip(indices[0], distances[0], strict=False)
            if dist < 0.4
        ]

        if not matched_ids:
            return []

        stmt2 = select(Conversation).where(Conversation.id.in_(matched_ids))  # type: ignore[union-attr]
        result2 = await session.execute(stmt2)
        return result2.scalars().all()  # type: ignore[return-value]

    @staticmethod
    async def perform_rag_search(query: str, limit: int = 6) -> list[dict]:
        async with get_async_session() as session:
            relevant_convs = await HistoryService.semantic_search(query, session)
            results = []

            for conv in relevant_convs[:limit]:
                stmt = (
                    select(Message)
                    .where(Message.conversation_id == conv.id)  # type: ignore[arg-type]
                    .order_by(Message.timestamp)  # type: ignore[arg-type]
                    .limit(5)
                )
                result = await session.execute(stmt)
                messages = result.scalars().all()

                snippet_parts = []
                for msg in messages:
                    preview = msg.content.strip()
                    if len(preview) > 200:
                        preview = preview[:200] + "..."
                    snippet_parts.append(f"{msg.role.capitalize()}: {preview}")

                snippet = "\n".join(snippet_parts) or "(Sin contenido)"

                results.append(
                    {
                        "title": conv.title or "Sin título",
                        "created_at": conv.created_at,
                        "snippet": snippet,
                        "id": conv.id,
                    }
                )
            return results

    @staticmethod
    async def rag_query(query: str) -> dict:
        if not query.strip():
            return {"success": False, "message": "La pregunta está vacía"}

        results = await HistoryService.perform_rag_search(query)
        if not results:
            return {
                "success": False,
                "message": "No encontré conversaciones relevantes en tu historial.",
            }

        context = "\n\n".join(
            [
                f"Conversación: {r['title']} ({r['created_at'].strftime('%d/%m/%Y %H:%M')})\n"
                f"{r['snippet']}\n{'─' * 40}"
                for r in results
            ]
        )

        prompt = f"""Eres un asistente personal que conoce todo el historial del usuario.

Pregunta del usuario: {query}

Contexto relevante de su historial (más reciente primero):
{context}

Responde de forma natural, útil y conversacional. Usa el contexto para dar respuestas precisas y personales."""

        try:
            response = await models.call(
                messages=[{"role": "user", "content": prompt}],
                role="default",
                temperature=0.7,
            )
            answer = response.choices[0].message.content.strip()
            return {"success": True, "answer": answer, "sources": len(results)}
        except Exception as e:
            logging.error(f"Error en RAG query: {e}")
            return {"success": False, "message": f"Error al procesar la pregunta: {e!s}"}

    # === CRUD delegation (all async now) ===
    @staticmethod
    async def edit_conversation(conv_id: int, new_title: str) -> bool:
        return await ConversationRepository.update_title(conv_id, new_title)

    @staticmethod
    async def delete_conversation(conv_id: int) -> bool:
        return await ConversationRepository.delete(conv_id)

    @staticmethod
    async def clone_conversation(conv_id: int) -> bool:
        return await ConversationRepository.clone(conv_id)

    @staticmethod
    async def create_branch(conv_id: int, branch_point: int = 0) -> bool:
        return await ConversationRepository.create_branch(conv_id, branch_point)

    @staticmethod
    async def analyze_conversation(conv_id: int) -> str:
        return await ConversationRepository.analyze(conv_id)

    @staticmethod
    async def get_messages(conv_id: int) -> list[dict]:
        """Obtiene todos los mensajes de una conversación."""
        return await ConversationRepository.get_messages(conv_id)

    @staticmethod
    async def get_conversation(conv_id: int) -> dict | None:
        """Get conversation metadata with message count."""
        return await ConversationRepository.get_conversation(conv_id)

    @staticmethod
    async def list_conversations(limit: int = 50, offset: int = 0) -> list[dict]:
        """List conversations with pagination, newest first."""
        return await ConversationRepository.list_all(limit=limit, offset=offset)

    @staticmethod
    async def count_conversations() -> int:
        """Total number of conversations in the current workspace."""
        return await ConversationRepository.count_all()

    @staticmethod
    async def export_conversation(conv_id: int, format: str = "md"):
        return await ConversationRepository.export(conv_id, format)
Functions
semantic_search(
    query: str, session: AsyncSession
) -> list[Conversation]

Búsqueda semántica con FAISS + caché Redis (ejecuta encode en thread).

Source code in desktop/services/history_service.py
@staticmethod
async def semantic_search(query: str, session: AsyncSession) -> list[Conversation]:
    """Búsqueda semántica con FAISS + caché Redis (ejecuta encode en thread)."""
    import asyncio

    embed_model = _get_embed_model()
    query_emb = await asyncio.to_thread(embed_model.encode, query)

    stmt = select(Message).order_by(Message.id.desc()).limit(200)  # type: ignore[union-attr]
    result = await session.execute(stmt)
    all_msgs = result.scalars().all()

    if not all_msgs:
        return []

    import faiss
    import numpy as np

    r = await HistoryService._get_redis()
    embeddings = []
    for msg in all_msgs:
        cache_key = f"emb:{msg.id}"
        cached_emb = None
        if r:
            cached_emb = await r.get(cache_key)
        if cached_emb:
            emb = np.frombuffer(cached_emb, dtype=np.float32)
        else:
            emb = await asyncio.to_thread(embed_model.encode, msg.content)
            if r:
                await r.set(cache_key, emb.tobytes(), ex=3600)
        embeddings.append(emb)

    embeddings_arr = np.array(embeddings).astype("float32")  # type: ignore[assignment]
    index = faiss.IndexFlatL2(embeddings_arr.shape[1])  # type: ignore[attr-defined]
    index.add(embeddings_arr)

    distances, indices = index.search(np.array([query_emb]).astype("float32"), 10)

    matched_ids = [
        all_msgs[idx].conversation_id
        for idx, dist in zip(indices[0], distances[0], strict=False)
        if dist < 0.4
    ]

    if not matched_ids:
        return []

    stmt2 = select(Conversation).where(Conversation.id.in_(matched_ids))  # type: ignore[union-attr]
    result2 = await session.execute(stmt2)
    return result2.scalars().all()  # type: ignore[return-value]
get_messages async staticmethod
get_messages(conv_id: int) -> list[dict]

Obtiene todos los mensajes de una conversación.

Source code in desktop/services/history_service.py
@staticmethod
async def get_messages(conv_id: int) -> list[dict]:
    """Obtiene todos los mensajes de una conversación."""
    return await ConversationRepository.get_messages(conv_id)
get_conversation async staticmethod
get_conversation(conv_id: int) -> dict | None

Get conversation metadata with message count.

Source code in desktop/services/history_service.py
@staticmethod
async def get_conversation(conv_id: int) -> dict | None:
    """Get conversation metadata with message count."""
    return await ConversationRepository.get_conversation(conv_id)
list_conversations async staticmethod
list_conversations(
    limit: int = 50, offset: int = 0
) -> list[dict]

List conversations with pagination, newest first.

Source code in desktop/services/history_service.py
@staticmethod
async def list_conversations(limit: int = 50, offset: int = 0) -> list[dict]:
    """List conversations with pagination, newest first."""
    return await ConversationRepository.list_all(limit=limit, offset=offset)
count_conversations async staticmethod
count_conversations() -> int

Total number of conversations in the current workspace.

Source code in desktop/services/history_service.py
@staticmethod
async def count_conversations() -> int:
    """Total number of conversations in the current workspace."""
    return await ConversationRepository.count_all()

desktop.widgets.chat_bubble

Chat Block — full-width dense message blocks (no bubbles, no copy button).

Classes

ChatBlock

Bases: QWidget

Full-width message block with role header and markdown content.

Source code in desktop/widgets/chat_bubble.py
class ChatBlock(QWidget):
    """Full-width message block with role header and markdown content."""

    def __init__(self, text: str, role: str = "assistant", parent=None):
        super().__init__(parent)
        self._text = text
        self._timestamp = datetime.now(UTC).strftime("%H:%M")
        self._role = role

        role_name, role_color = _ROLE_CONFIG.get(role, ("", COLORS["text_dim"]))

        # --- Header row: role label + timestamp ---
        header = QHBoxLayout()
        header.setContentsMargins(0, 0, 0, 2)
        header.setSpacing(6)

        if role_name:
            role_label = QLabel(role_name)
            role_label.setFont(self._header_font())
            role_label.setStyleSheet(f"color: {role_color}; font-weight: bold; font-size: 10px;")
            header.addWidget(role_label)

        ts = QLabel(self._timestamp)
        ts.setStyleSheet(f"color: {COLORS['text_timestamp']}; font-size: 9px;")
        header.addWidget(ts)
        header.addStretch()

        # --- Content: QTextBrowser (markdown, no bubble styling) ---
        content = QTextBrowser()
        content.setOpenExternalLinks(True)
        content.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        content.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        content.setWordWrapMode(QTextOption.WrapMode.WordWrap)
        content.setMarkdown(text)
        content.document().setDocumentMargin(4)
        content.setStyleSheet(
            f"QTextBrowser {{ background: transparent; color: {COLORS['text_primary']}; "
            f"border: none; font-size: 14px; }}"
            f"QTextBrowser a {{ color: {COLORS['accent_light']}; }}"
            f"QTextBrowser code {{ background: {COLORS['bg_code']}; "
            f"padding: 2px 4px; border-radius: 4px; }}"
            f"QTextBrowser pre {{ background: {COLORS['bg_code']}; "
            f"padding: 8px; border-radius: 6px; }}"
        )
        content.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self._browser = content

        # Streaming debounce state
        self._pending_text: str | None = None
        self._stream_timer: QTimer | None = None

        # --- Assembly ---
        col = QVBoxLayout(self)
        col.setContentsMargins(6, 6, 6, 4)
        col.setSpacing(2)
        col.addLayout(header)
        col.addWidget(content)

        # Fit height to content after layout
        QTimer.singleShot(0, self._update_text_width)

    @staticmethod
    def _header_font() -> QFont:
        f = QFont()
        f.setBold(True)
        f.setPointSize(9)
        return f

    def _update_text_width(self):
        browser = self._browser
        if browser:
            w = browser.viewport().width()
            if w > 50:
                browser.document().setTextWidth(max(w - 16, 100))
            doc_h = int(browser.document().size().height() + 12)
            browser.setFixedHeight(max(doc_h, 22))

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self._update_text_width()

    # ── Streaming API (same signature as ChatBubble) ──

    def update_text(self, text: str):
        """Debounced streaming update — coalesces tokens every ~70ms."""
        self._text = text
        self._pending_text = text
        if self._stream_timer is None:
            self._stream_timer = QTimer(self)
            self._stream_timer.setSingleShot(True)
            self._stream_timer.timeout.connect(self._flush_stream)
        if not self._stream_timer.isActive():
            self._stream_timer.start(70)

    def _flush_stream(self):
        if self._pending_text is None or self._browser is None:
            return
        self._browser.setMarkdown(self._pending_text)
        self._pending_text = None
        self._update_text_width()

    def flush_stream(self):
        """Render pending text immediately (e.g. at stream end)."""
        if self._stream_timer is not None and self._stream_timer.isActive():
            self._stream_timer.stop()
        self._flush_stream()
Functions
update_text
update_text(text: str)

Debounced streaming update — coalesces tokens every ~70ms.

Source code in desktop/widgets/chat_bubble.py
def update_text(self, text: str):
    """Debounced streaming update — coalesces tokens every ~70ms."""
    self._text = text
    self._pending_text = text
    if self._stream_timer is None:
        self._stream_timer = QTimer(self)
        self._stream_timer.setSingleShot(True)
        self._stream_timer.timeout.connect(self._flush_stream)
    if not self._stream_timer.isActive():
        self._stream_timer.start(70)
flush_stream
flush_stream()

Render pending text immediately (e.g. at stream end).

Source code in desktop/widgets/chat_bubble.py
def flush_stream(self):
    """Render pending text immediately (e.g. at stream end)."""
    if self._stream_timer is not None and self._stream_timer.isActive():
        self._stream_timer.stop()
    self._flush_stream()

desktop.widgets.agent_panel

Agent Panel — dynamically shows per-agent responses grouped by name.

Classes

AgentPanel

Bases: QWidget

Dynamic panel with per-agent responses, grouped by agent name.

Each agent gets a QGroupBox with rotating color. Responses are appended as QLabels inside the group.

Source code in desktop/widgets/agent_panel.py
class AgentPanel(QWidget):
    """Dynamic panel with per-agent responses, grouped by agent name.

    Each agent gets a QGroupBox with rotating color. Responses are
    appended as QLabels inside the group.
    """

    def __init__(self, parent=None):
        super().__init__(parent)
        self._groups: dict[str, tuple[QGroupBox, QVBoxLayout, str]] = {}
        self._palette = list(AGENT_PALETTE)
        self._color_idx = 0

        outer = QVBoxLayout(self)
        outer.setContentsMargins(0, 0, 0, 0)
        outer.setSpacing(0)

        self._scroll = QScrollArea()
        self._scroll.setWidgetResizable(True)
        self._scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self._scroll.setStyleSheet(
            f"QScrollArea {{ background: {COLORS['bg_deepest']}; border: none; }}"
        )

        self._container = QWidget()
        self._layout = QVBoxLayout(self._container)
        self._layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self._layout.setSpacing(6)
        self._layout.setContentsMargins(4, 4, 4, 4)
        self._layout.addStretch()

        self._scroll.setWidget(self._container)
        outer.addWidget(self._scroll)

    def _get_color(self, agent_name: str) -> str:
        """Return consistent color for an agent. First-seen gets next palette slot."""
        if agent_name in self._groups:
            return self._groups[agent_name][2]
        color = self._palette[self._color_idx % len(self._palette)]
        self._color_idx += 1
        return color

    def add_response(self, agent_name: str, label: str, text: str):
        """Add a response entry for an agent. Creates the group if new."""
        if agent_name not in self._groups:
            color = self._get_color(agent_name)
            group = QGroupBox(agent_name.capitalize())
            group.setStyleSheet(
                f"QGroupBox {{ color: {color}; font-weight: bold; border: 1px solid {color}44; "
                f"border-radius: 6px; margin-top: 8px; padding-top: 12px; font-size: 12px; }}"
                f"QGroupBox::title {{ subcontrol-origin: margin; left: 8px; padding: 0 4px; }}"
            )
            inner = QVBoxLayout(group)
            inner.setSpacing(4)
            inner.setContentsMargins(8, 8, 8, 8)

            # Insert before the stretch
            self._layout.insertWidget(self._layout.count() - 1, group)
            self._groups[agent_name] = (group, inner, color)

        _, inner, _ = self._groups[agent_name]
        entry = QLabel(f"<b>{label}:</b> {text}")
        entry.setWordWrap(True)
        entry.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
        entry.setStyleSheet(f"color: {COLORS['text_primary']}; font-size: 12px; padding: 2px 0;")
        inner.addWidget(entry)

        self._scroll_to_bottom()

    def clear(self):
        """Remove all agent groups."""
        for group, _, _ in self._groups.values():
            self._layout.removeWidget(group)
            group.deleteLater()
        self._groups.clear()

    def is_empty(self) -> bool:
        return len(self._groups) == 0

    def update_files_written(self, files: list[str]):
        """Update the files-written indicator at the top of the panel."""
        if not hasattr(self, "_files_label"):
            from PySide6.QtWidgets import QListWidget

            self._files_list = QListWidget()
            self._files_list.setMaximumHeight(80)
            self._files_list.setStyleSheet(
                f"QListWidget {{ background: {COLORS['bg_deepest']}; "
                f"border: 1px solid {COLORS['border_default']}; "
                f"border-radius: 4px; font-size: 11px; color: {COLORS['success']}; }}"
            )
            self._layout.insertWidget(0, self._files_list)
        self._files_list.clear()
        for f in files[:10]:
            self._files_list.addItem(f"  {f}")

    def _scroll_to_bottom(self):
        sb = self._scroll.verticalScrollBar()
        if sb:
            sb.setValue(sb.maximum())
Functions
add_response
add_response(agent_name: str, label: str, text: str)

Add a response entry for an agent. Creates the group if new.

Source code in desktop/widgets/agent_panel.py
def add_response(self, agent_name: str, label: str, text: str):
    """Add a response entry for an agent. Creates the group if new."""
    if agent_name not in self._groups:
        color = self._get_color(agent_name)
        group = QGroupBox(agent_name.capitalize())
        group.setStyleSheet(
            f"QGroupBox {{ color: {color}; font-weight: bold; border: 1px solid {color}44; "
            f"border-radius: 6px; margin-top: 8px; padding-top: 12px; font-size: 12px; }}"
            f"QGroupBox::title {{ subcontrol-origin: margin; left: 8px; padding: 0 4px; }}"
        )
        inner = QVBoxLayout(group)
        inner.setSpacing(4)
        inner.setContentsMargins(8, 8, 8, 8)

        # Insert before the stretch
        self._layout.insertWidget(self._layout.count() - 1, group)
        self._groups[agent_name] = (group, inner, color)

    _, inner, _ = self._groups[agent_name]
    entry = QLabel(f"<b>{label}:</b> {text}")
    entry.setWordWrap(True)
    entry.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
    entry.setStyleSheet(f"color: {COLORS['text_primary']}; font-size: 12px; padding: 2px 0;")
    inner.addWidget(entry)

    self._scroll_to_bottom()
clear
clear()

Remove all agent groups.

Source code in desktop/widgets/agent_panel.py
def clear(self):
    """Remove all agent groups."""
    for group, _, _ in self._groups.values():
        self._layout.removeWidget(group)
        group.deleteLater()
    self._groups.clear()
update_files_written
update_files_written(files: list[str])

Update the files-written indicator at the top of the panel.

Source code in desktop/widgets/agent_panel.py
def update_files_written(self, files: list[str]):
    """Update the files-written indicator at the top of the panel."""
    if not hasattr(self, "_files_label"):
        from PySide6.QtWidgets import QListWidget

        self._files_list = QListWidget()
        self._files_list.setMaximumHeight(80)
        self._files_list.setStyleSheet(
            f"QListWidget {{ background: {COLORS['bg_deepest']}; "
            f"border: 1px solid {COLORS['border_default']}; "
            f"border-radius: 4px; font-size: 11px; color: {COLORS['success']}; }}"
        )
        self._layout.insertWidget(0, self._files_list)
    self._files_list.clear()
    for f in files[:10]:
        self._files_list.addItem(f"  {f}")

desktop.widgets.bash_panel

Bash Panel — visor de salida de comandos shell.

Classes

BashPanel

Bases: QWidget

Panel de salida bash con fuente monoespaciada.

Source code in desktop/widgets/bash_panel.py
class BashPanel(QWidget):
    """Panel de salida bash con fuente monoespaciada."""

    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(2)

        title = QLabel("Salida Bash")
        title.setStyleSheet(f"font-size: 11px; color: {COLORS['text_secondary']};")

        self.output = QTextEdit()
        self.output.setReadOnly(True)
        self.output.setFont(QFont("monospace", 10))
        self.output.setStyleSheet(
            f"QTextEdit {{ background: {COLORS['bg_bash']}; color: {COLORS['success']}; "
            f"border: 1px solid {COLORS['border_default']}; "
            f"border-radius: 4px; padding: 4px; }}"
        )
        self.output.setPlaceholderText("(sin comandos ejecutados aún)")

        layout.addWidget(title)
        layout.addWidget(self.output)

    def set_output(self, text: str) -> None:
        """Actualiza la salida del panel."""
        self.output.setPlainText(text[-5000:])
        # Scroll al final
        cursor = self.output.textCursor()
        cursor.movePosition(cursor.MoveOperation.End)
        self.output.setTextCursor(cursor)
Functions
set_output
set_output(text: str) -> None

Actualiza la salida del panel.

Source code in desktop/widgets/bash_panel.py
def set_output(self, text: str) -> None:
    """Actualiza la salida del panel."""
    self.output.setPlainText(text[-5000:])
    # Scroll al final
    cursor = self.output.textCursor()
    cursor.movePosition(cursor.MoveOperation.End)
    self.output.setTextCursor(cursor)