-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrinity_classic.py
More file actions
2214 lines (2071 loc) · 89.7 KB
/
Copy pathtrinity_classic.py
File metadata and controls
2214 lines (2071 loc) · 89.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Traditional desktop UI for Trinity with transcript, results and text input."""
import glob
import html
import json
import os
import platform
import re
import sys
import threading
import time
import uuid
from datetime import datetime
from pathlib import Path
from PySide6.QtCore import Qt, QTimer, QUrl, Signal
from PySide6.QtGui import QColor, QDesktopServices, QIcon, QKeyEvent, QPixmap, QTextCursor
from PySide6.QtWidgets import (
QApplication,
QFileDialog,
QHBoxLayout,
QComboBox,
QInputDialog,
QLabel,
QLineEdit,
QMainWindow,
QMessageBox,
QPushButton,
QStackedWidget,
QTabWidget,
QTextEdit,
QVBoxLayout,
QWidget,
)
from PySide6.QtWebEngineCore import QWebEngineSettings
from PySide6.QtWebEngineWidgets import QWebEngineView
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CORE_DIR = os.path.join(BASE_DIR, "core")
MEMORY_DIR = os.path.join(BASE_DIR, "memory")
if CORE_DIR not in sys.path:
sys.path.insert(0, CORE_DIR)
from settings_ui import SettingsWindow
from agent_catalog import build_agent_catalog
from chat_attachments import stage_attachment
from chat_protocol import (
append_chat_event,
build_chat_request,
enqueue_chat_request,
load_chat_events,
)
from memory_store import MemoryStore, render_graph_html
from runtime_reset import delete_session_summary
from remote_client import RemoteTrinityClient
from configuration import load_config, save_config
from trinity_bridge import TrinityBridge
from workspace_manager import INBOX_WORKSPACE_ID, TrinityWorkspaceManager
from unified_session import UnifiedSessionStore
CHAT_HISTORY_FILE = os.path.join(MEMORY_DIR, "classic_chat_history.jsonl")
CHAT_UPLOAD_DIR = os.path.join(MEMORY_DIR, "chat_uploads")
CONFIG_FILE = os.path.join(CORE_DIR, "config.json")
LOGS_DIR = os.path.join(BASE_DIR, "logs")
THEMES = {
"dark": {
"app_bg": "#09090b",
"panel_bg": "#121214",
"raised_bg": "#18181b",
"hover_bg": "#27272a",
"text": "#f4f4f5",
"muted": "#a1a1aa",
"border": "#27272a",
"strong_border": "#3f3f46",
"user_bg": "#1d2838",
"user_border": "#334155",
"primary_bg": "#f4f4f5",
"primary_text": "#09090b",
"link": "#38bdf8",
"selection": "#3f3f46",
},
"light": {
"app_bg": "#f8fafc",
"panel_bg": "#ffffff",
"raised_bg": "#eef2f7",
"hover_bg": "#e2e8f0",
"text": "#0f172a",
"muted": "#64748b",
"border": "#d7dde7",
"strong_border": "#cbd5e1",
"user_bg": "#e0f2fe",
"user_border": "#7dd3fc",
"primary_bg": "#0f172a",
"primary_text": "#ffffff",
"link": "#0369a1",
"selection": "#bfdbfe",
},
}
def _latest_transcript(memory_dir=MEMORY_DIR):
candidates = glob.glob(os.path.join(memory_dir, "raw_session_*.md"))
return max(candidates, key=os.path.getmtime) if candidates else None
def _default_session_name_prefix():
return datetime.now().strftime("%Y%m%d_%H%M_")
def _format_size(size):
value = float(size or 0)
for unit in ("B", "KB", "MB", "GB"):
if value < 1024 or unit == "GB":
return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"
value /= 1024
def _attachment_html(attachment):
name = html.escape(str(attachment.get("name", "Anlage")))
kind = attachment.get("kind", "file")
size = html.escape(_format_size(attachment.get("size", 0)))
path = Path(str(attachment.get("path", "")))
media_url = str(attachment.get("media_url", ""))
preview = ""
if kind == "image" and (path.is_file() or media_url):
source = media_url or path.resolve().as_uri()
preview = (
f'<img class="attachment-preview" src="{html.escape(source)}" '
f'alt="{name}">'
)
labels = {"image": "Bild", "pdf": "PDF", "text": "Text"}
return (
'<div class="attachment">'
f"{preview}<strong>{name}</strong>"
f'<span>{labels.get(kind, "Datei")} · {size}</span>'
"</div>"
)
def _tail_file(path, max_lines=240):
try:
lines = Path(path).read_text(
encoding="utf-8",
errors="replace",
).splitlines()
except OSError:
return ""
return "\n".join(lines[-max_lines:])
def _build_live_log_text(transcript_path, logs_dir=LOGS_DIR):
sections = []
if transcript_path:
try:
transcript = Path(transcript_path).read_text(
encoding="utf-8",
errors="replace",
).strip()
except OSError:
transcript = ""
if transcript:
sections.append(f"## Live-Mitschrift\n\n{transcript}")
runtime = _tail_file(os.path.join(logs_dir, "runtime.log"))
if runtime:
sections.append(
"## Laufzeitlog / Agenten\n\n"
"Hier erscheinen geladene Agenten, aktivierte Skills, Tool-Ausgaben "
"und Fehlermeldungen aus dem Trinity-Kernprozess.\n\n"
f"{runtime}"
)
launcher = _tail_file(os.path.join(logs_dir, "launcher.log"), max_lines=80)
if launcher:
sections.append(f"## Launcher\n\n{launcher}")
return "\n\n---\n\n".join(sections) or (
"Noch keine Live-Mitschrift oder Laufzeitlogs vorhanden."
)
def _render_chat_html(events, theme="dark"):
colors = THEMES.get(theme, THEMES["dark"])
message_html = []
for event in events:
role = event.get("role", "assistant")
text = html.escape(str(event.get("text", ""))).replace("\n", "<br>")
timestamp = event.get("timestamp")
try:
time_label = datetime.fromtimestamp(float(timestamp)).strftime("%H:%M")
except (TypeError, ValueError, OSError):
time_label = ""
attachments = "".join(
_attachment_html(item) for item in event.get("attachments", [])
)
payload = event.get("payload_html", "")
payload_frame = ""
if payload:
cleaned = payload.replace("<!-- FULLPAGE -->", "")
payload_frame = (
'<div class="payload-card"><div class="payload-title">'
"Agenten- oder Medienergebnis</div>"
f'<iframe srcdoc="{html.escape(cleaned, quote=True)}">'
"</iframe></div>"
)
sender = "Du" if role == "user" else "Trinity"
body = f"<div class=\"message-text\">{text}</div>" if text else ""
message_html.append(
f'<article class="message {html.escape(role)}">'
f'<div class="message-meta">{sender}<span>{time_label}</span></div>'
f"{body}{attachments}{payload_frame}</article>"
)
empty = (
'<div class="empty"><h2>Chat mit Trinity</h2>'
"<p>Schreibe eine Nachricht oder füge Texte, PDFs und Bilder hinzu.</p></div>"
)
content = "".join(message_html) or empty
return f"""<!DOCTYPE html>
<html><head><meta charset="UTF-8"><style>
html, body {{ background:{colors["app_bg"]}; color:{colors["text"]}; font-family:-apple-system,
BlinkMacSystemFont,"Segoe UI",sans-serif; margin:0; }}
body {{ padding:18px; }}
.empty {{ color:{colors["muted"]}; text-align:center; padding:80px 20px; }}
.message {{ max-width:86%; margin:0 0 16px; padding:13px 15px;
border:1px solid {colors["border"]}; border-radius:14px; background:{colors["panel_bg"]}; }}
.message.user {{ margin-left:auto; background:{colors["user_bg"]}; border-color:{colors["user_border"]}; }}
.message-meta {{ display:flex; justify-content:space-between; gap:20px;
font-size:11px; font-weight:700; color:{colors["muted"]}; margin-bottom:8px; }}
.message-text {{ white-space:normal; line-height:1.55; overflow-wrap:anywhere; }}
.attachment {{ display:inline-flex; vertical-align:top; flex-direction:column;
gap:4px; max-width:220px; margin:10px 8px 0 0; padding:9px;
border:1px solid {colors["strong_border"]}; border-radius:10px; background:{colors["raised_bg"]}; }}
.attachment span {{ color:{colors["muted"]}; font-size:11px; }}
.attachment-preview {{ width:200px; max-height:150px; object-fit:cover;
border-radius:7px; margin-bottom:4px; }}
.payload-card {{ margin-top:12px; border-top:1px solid {colors["border"]}; padding-top:12px; }}
.payload-title {{ color:{colors["muted"]}; font-size:11px; font-weight:700; margin-bottom:8px; }}
iframe {{ width:100%; min-height:360px; border:1px solid {colors["border"]};
border-radius:10px; background:{colors["app_bg"]}; }}
a {{ color:{colors["link"]}; }}
</style></head><body>{content}<script>
window.scrollTo(0, document.body.scrollHeight);
</script></body></html>"""
class ChatInput(QTextEdit):
submit_requested = Signal()
def keyPressEvent(self, event: QKeyEvent):
if (
event.key() in (Qt.Key_Return, Qt.Key_Enter)
and not event.modifiers() & Qt.ShiftModifier
):
self.submit_requested.emit()
event.accept()
return
super().keyPressEvent(event)
class ClassicWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Trinity Assistant")
self.resize(1100, 760)
self.setMinimumSize(760, 520)
self._transcript_path = None
self._transcript_signature = None
self._chat_signature = None
self._memory_signature = None
self._last_state = ""
self._workspace_payload_signature = None
self._lecture_path = ""
self.session_id = ""
self.session_name = ""
self.session_started_at = time.time()
self.pending_attachments = []
self.remote_client = self._load_remote_client()
self.remote_events = []
self.remote_after = 0.0
self._remote_next_poll = 0.0
self._speaker_next_refresh = 0.0
self._workspace_sidebar_signature = None
self._workspace_sidebar_next_refresh = 0.0
self.memory_store = MemoryStore(os.path.join(MEMORY_DIR, "trinity_memory.sqlite3"))
self.workspace_manager = TrinityWorkspaceManager(BASE_DIR, load_config(CONFIG_FILE))
self.session_store = UnifiedSessionStore(BASE_DIR, load_config(CONFIG_FILE))
active_session = self.session_store.current()
self.session_id = active_session.id
self.session_name = active_session.title
self.selected_workspace_id = INBOX_WORKSPACE_ID
self.selected_workspace_title = "Schnellsessions"
self.theme = self._load_theme()
self.workspace_sidebar_visible = True
self.setAcceptDrops(True)
self.pages = QStackedWidget()
self.chat_page = QWidget()
layout = QVBoxLayout(self.chat_page)
layout.setContentsMargins(18, 16, 18, 16)
layout.setSpacing(12)
header = QHBoxLayout()
self.logo = QLabel()
self.logo.setObjectName("logo")
logo_path = self._logo_path()
if logo_path:
pixmap = QPixmap(logo_path)
if not pixmap.isNull():
self.logo.setPixmap(
pixmap.scaled(
40,
40,
Qt.KeepAspectRatio,
Qt.SmoothTransformation,
)
)
self.logo.setFixedSize(46, 42)
title = QLabel("Trinity Assistant")
title.setObjectName("title")
self.status = QLabel("Bereit")
self.status.setObjectName("status")
self.workspace_sidebar_button = QPushButton("▥")
self.workspace_sidebar_button.setObjectName("subtle")
self.workspace_sidebar_button.setFixedSize(46, 38)
self.workspace_sidebar_button.setToolTip("Arbeitsorganisation ein- oder ausklappen")
self.workspace_sidebar_button.clicked.connect(self.toggle_workspace_sidebar)
self.listen_button = QPushButton()
self.listen_button.setObjectName("subtle")
self.listen_button.setFixedSize(46, 38)
self.listen_button.clicked.connect(self.toggle_microphone)
self.new_session_button = QPushButton()
self.new_session_button.setObjectName("subtle")
self.new_session_button.setFixedSize(46, 38)
self.new_session_button.setToolTip("Neue Session")
self.new_session_button.clicked.connect(self.start_new_session)
self.mode_combo = QComboBox()
self.mode_combo.setObjectName("toolbarCombo")
self.mode_combo.addItems(["lecture", "office"])
self.mode_combo.setFixedWidth(96)
self.mode_combo.setToolTip("Trinity-Betriebsmodus")
self.mode_combo.currentTextChanged.connect(self.set_runtime_mode)
self.audio_source_button = QPushButton()
self.audio_source_button.setObjectName("subtle")
self.audio_source_button.setFixedSize(46, 38)
self.audio_source_button.clicked.connect(self.toggle_audio_capture_mode)
self.speaker_button = QPushButton()
self.speaker_button.setObjectName("subtle")
self.speaker_button.setFixedSize(46, 38)
self.speaker_button.setToolTip(
"Diesen Desktop als einzige Trinity-Sprachausgabe auswählen"
)
self.speaker_button.clicked.connect(self.toggle_desktop_speaker)
self.theme_button = QPushButton()
self.theme_button.setObjectName("theme")
self.theme_button.setFixedSize(46, 38)
self.theme_button.setToolTip("Zwischen Dark Mode und Hell Mode wechseln")
self.theme_button.clicked.connect(self.toggle_theme)
settings_button = QPushButton("⚙")
settings_button.setObjectName("gear")
settings_button.setFixedSize(42, 38)
settings_button.setToolTip("Einstellungen öffnen")
settings_button.clicked.connect(self.show_settings)
header.addWidget(self.logo)
header.addWidget(title)
header.addSpacing(10)
left_cluster = QWidget()
left_cluster.setObjectName("toolbarCluster")
left_cluster_layout = QHBoxLayout(left_cluster)
left_cluster_layout.setContentsMargins(6, 4, 6, 4)
left_cluster_layout.setSpacing(4)
left_cluster_layout.addWidget(self.workspace_sidebar_button)
left_cluster_layout.addWidget(self.listen_button)
left_cluster_layout.addWidget(self.new_session_button)
header.addWidget(left_cluster)
header.addStretch()
header.addWidget(self.status)
right_cluster = QWidget()
right_cluster.setObjectName("toolbarCluster")
right_cluster_layout = QHBoxLayout(right_cluster)
right_cluster_layout.setContentsMargins(6, 4, 6, 4)
right_cluster_layout.setSpacing(4)
right_cluster_layout.addWidget(self.mode_combo)
right_cluster_layout.addWidget(self.audio_source_button)
right_cluster_layout.addWidget(self.speaker_button)
right_cluster_layout.addWidget(self.theme_button)
right_cluster_layout.addWidget(settings_button)
header.addWidget(right_cluster)
layout.addLayout(header)
self.main_tabs = QTabWidget()
self.main_tabs.setObjectName("workspaceTabs")
daily_tab = QWidget()
daily_layout = QVBoxLayout(daily_tab)
daily_layout.setContentsMargins(0, 0, 0, 0)
self.daily_workspace = QWebEngineView()
self._configure_web_view(self.daily_workspace)
daily_layout.addWidget(self.daily_workspace)
lecture_tab = QWidget()
lecture_layout = QVBoxLayout(lecture_tab)
lecture_layout.setContentsMargins(0, 0, 0, 0)
lecture_toolbar = QHBoxLayout()
self.lecture_label = QLabel("Noch kein Foliensatz geöffnet")
self.lecture_label.setObjectName("section")
lecture_open_button = QPushButton("PDF öffnen")
lecture_open_button.setObjectName("subtle")
lecture_open_button.clicked.connect(self.choose_lecture_pdf)
lecture_external_button = QPushButton("Extern öffnen")
lecture_external_button.setObjectName("subtle")
lecture_external_button.clicked.connect(self.open_lecture_externally)
lecture_toolbar.addWidget(self.lecture_label, 1)
lecture_toolbar.addWidget(lecture_open_button)
lecture_toolbar.addWidget(lecture_external_button)
self.lecture_workspace = QWebEngineView()
self._configure_web_view(self.lecture_workspace)
lecture_layout.addLayout(lecture_toolbar)
lecture_layout.addWidget(self.lecture_workspace, 1)
web_tab = QWidget()
web_layout = QVBoxLayout(web_tab)
web_layout.setContentsMargins(0, 0, 0, 0)
web_toolbar = QHBoxLayout()
self.web_address = QLineEdit("https://www.google.com")
self.web_address.setPlaceholderText("https://…")
self.web_address.returnPressed.connect(self.open_web_address)
web_back_button = QPushButton("←")
web_back_button.setObjectName("subtle")
web_back_button.clicked.connect(lambda: self.web_workspace.back())
web_forward_button = QPushButton("→")
web_forward_button.setObjectName("subtle")
web_forward_button.clicked.connect(lambda: self.web_workspace.forward())
web_reload_button = QPushButton("Neu laden")
web_reload_button.setObjectName("subtle")
web_reload_button.clicked.connect(lambda: self.web_workspace.reload())
web_open_button = QPushButton("Öffnen")
web_open_button.setObjectName("subtle")
web_open_button.clicked.connect(self.open_web_address)
web_external_button = QPushButton("Extern")
web_external_button.setObjectName("subtle")
web_external_button.clicked.connect(self.open_web_externally)
for widget in (
web_back_button, web_forward_button, self.web_address, web_reload_button,
web_open_button, web_external_button,
):
web_toolbar.addWidget(widget, 1 if widget is self.web_address else 0)
self.web_workspace = QWebEngineView()
self._configure_web_view(self.web_workspace)
self.web_workspace.setUrl(QUrl("https://www.google.com"))
web_layout.addLayout(web_toolbar)
web_layout.addWidget(self.web_workspace, 1)
agents_tab = QWidget()
agents_layout = QVBoxLayout(agents_tab)
agents_layout.setContentsMargins(0, 0, 0, 0)
self.agents_workspace = QWebEngineView()
self._configure_web_view(self.agents_workspace)
agents_layout.addWidget(self.agents_workspace)
control_tab = QWidget()
control_layout = QVBoxLayout(control_tab)
control_layout.setContentsMargins(0, 0, 0, 0)
self.control_workspace = QWebEngineView()
self._configure_web_view(self.control_workspace)
control_layout.addWidget(self.control_workspace)
chat_tab = QWidget()
chat_tab_layout = QVBoxLayout(chat_tab)
chat_tab_layout.setContentsMargins(0, 0, 0, 0)
chat_tab_layout.setSpacing(8)
self.chat_history = QWebEngineView()
self._configure_web_view(self.chat_history)
self.chat_history.setHtml(_render_chat_html([], self.theme))
chat_tab_layout.addWidget(self.chat_history, 1)
transcript_tab = QWidget()
transcript_layout = QVBoxLayout(transcript_tab)
transcript_layout.setContentsMargins(0, 0, 0, 0)
transcript_layout.setSpacing(8)
self.transcript = QTextEdit()
self.transcript.setObjectName("transcript")
self.transcript.setReadOnly(True)
self.transcript.setPlaceholderText(
"Live-Mitschrift, Agentenstarts und Laufzeitlog erscheinen hier."
)
transcript_layout.addWidget(self.transcript)
memory_tab = QWidget()
memory_layout = QVBoxLayout(memory_tab)
memory_layout.setContentsMargins(0, 0, 0, 0)
memory_layout.setSpacing(8)
memory_header = QHBoxLayout()
self.memory_status = QLabel("Memory bereit")
self.memory_status.setObjectName("section")
bake_button = QPushButton("Memory backen")
bake_button.setObjectName("subtle")
bake_button.clicked.connect(self.bake_memory)
refresh_memory_button = QPushButton("Graph aktualisieren")
refresh_memory_button.setObjectName("subtle")
refresh_memory_button.clicked.connect(self.refresh_memory_graph)
reset_memory_button = QPushButton("Memory auf 0 setzen")
reset_memory_button.setObjectName("subtle")
reset_memory_button.setToolTip("Sessions, Summaries und Memory nach Sicherung vollständig zurücksetzen")
reset_memory_button.clicked.connect(self.request_memory_reset)
delete_memory_button = QPushButton("Einzelnes Memory löschen")
delete_memory_button.setObjectName("subtle")
delete_memory_button.clicked.connect(self.delete_memory_from_panel)
memory_header.addWidget(self.memory_status, 1)
memory_header.addWidget(bake_button)
memory_header.addWidget(refresh_memory_button)
memory_header.addWidget(delete_memory_button)
memory_header.addWidget(reset_memory_button)
self.memory_graph = QWebEngineView()
self._configure_web_view(self.memory_graph)
self.memory_graph.setHtml(
render_graph_html({"nodes": [], "links": []}, self.theme)
)
memory_layout.addLayout(memory_header)
memory_layout.addWidget(self.memory_graph, 1)
self.memory_panel = memory_tab
live_tab = QWidget()
live_layout = QVBoxLayout(live_tab)
live_layout.setContentsMargins(0, 0, 0, 0)
live_layout.addWidget(transcript_tab)
self.main_tabs.addTab(daily_tab, "Talk")
self.main_tabs.addTab(lecture_tab, "Vortrag")
self.main_tabs.addTab(web_tab, "Web")
self.main_tabs.addTab(agents_tab, "Agents")
self.main_tabs.addTab(control_tab, "Control")
self.main_tabs.addTab(chat_tab, "Chat")
self.main_tabs.addTab(live_tab, "Live")
self.main_tabs.currentChanged.connect(lambda _index: self._refresh_workspace_views(force=True))
workspace_shell = QWidget()
workspace_shell_layout = QHBoxLayout(workspace_shell)
workspace_shell_layout.setContentsMargins(0, 0, 0, 0)
workspace_shell_layout.setSpacing(10)
self.workspace_sidebar = self._build_workspace_sidebar()
workspace_shell_layout.addWidget(self.workspace_sidebar)
workspace_shell_layout.addWidget(self.main_tabs, 1)
layout.addWidget(workspace_shell, 1)
attachment_row = QHBoxLayout()
self.attachment_summary = QLabel("")
self.attachment_summary.setObjectName("attachments")
self.attachment_summary.setVisible(False)
clear_attachments = QPushButton("Anlagen entfernen")
clear_attachments.setObjectName("subtle")
clear_attachments.clicked.connect(self.clear_attachments)
self.clear_attachments_button = clear_attachments
clear_attachments.setVisible(False)
attachment_row.addWidget(self.attachment_summary, 1)
attachment_row.addWidget(clear_attachments)
layout.addLayout(attachment_row)
command_row = QHBoxLayout()
attach_button = QPushButton("Anlage")
attach_button.setToolTip("Text, PDF oder Bild hinzufügen")
attach_button.clicked.connect(self.choose_attachments)
self.command = ChatInput()
self.command.setObjectName("composerInput")
self.command.setFixedHeight(68)
self.command.setPlaceholderText(
"Mit Trinity schreiben ... Enter sendet, Shift+Enter macht eine neue Zeile"
)
self.command.submit_requested.connect(self.send_command)
send_button = QPushButton("Senden")
send_button.setObjectName("primary")
send_button.clicked.connect(self.send_command)
command_row.addWidget(attach_button)
command_row.addWidget(self.command, 1)
command_row.addWidget(send_button)
layout.addLayout(command_row)
self.settings_page = SettingsWindow(
os.path.join(CORE_DIR, "config.json"),
embedded=True,
on_return=self.return_to_chat,
)
self.pages.addWidget(self.chat_page)
self.pages.addWidget(self.settings_page)
self.setCentralWidget(self.pages)
self._apply_style()
self._update_theme_button()
self._sync_runtime_controls()
self._refresh_workspace_views(force=True)
self.timer = QTimer(self)
self.timer.timeout.connect(self.refresh)
self.timer.start(400)
self.refresh()
def request_memory_reset(self):
confirmation, accepted = QInputDialog.getText(
self,
"Trinity-Memory zurücksetzen",
"Sessions, Summaries, Arbeitsräume und Memory werden nach einer "
"Wiederherstellungskopie gelöscht. Vault, RAG-Quellen, Soul und "
"Konfiguration bleiben erhalten.\n\nZum Bestätigen RESET eingeben:",
)
if not accepted or confirmation.strip() != "RESET":
self.status.setText("Memory-Reset abgebrochen")
return
full_reset = QMessageBox.question(
self,
"Auch Testmedien und Canvas leeren?",
"Sollen zusätzlich lokal erzeugte Medien und alle Canvas-"
"Laufzeitdaten gesichert und geleert werden?\n\n"
"Ja = vollständiger Test-Neustart\nNein = nur Sessions, Summaries, "
"Arbeitsräume und Memory",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)
request_path = self.workspace_manager.paths.runtime_root / "reset-request.json"
request_path.parent.mkdir(parents=True, exist_ok=True)
request_path.write_text(
json.dumps(
{
"backup": True,
"include_generated": full_reset == QMessageBox.Yes,
"include_canvas": full_reset == QMessageBox.Yes,
},
ensure_ascii=False,
indent=2,
)
+ "\n",
encoding="utf-8",
)
QMessageBox.information(
self,
"Reset vorgemerkt",
"Trinity wird jetzt beendet, sichert den Betriebszustand und startet "
"beim nächsten Öffnen mit einem leeren Memory.",
)
QApplication.instance().quit()
def _build_workspace_sidebar(self):
sidebar = QWidget()
sidebar.setObjectName("workspaceSidebar")
sidebar.setFixedWidth(245)
layout = QVBoxLayout(sidebar)
layout.setContentsMargins(12, 12, 12, 12)
layout.setSpacing(8)
title = QLabel("Arbeitsräume")
title.setObjectName("sidebarTitle")
title_row = QHBoxLayout()
title_row.setContentsMargins(0, 0, 0, 0)
title_row.setSpacing(4)
title_row.addWidget(title, 1)
title_row.addWidget(
self._sidebar_icon_button("+", "Neuen Arbeitsraum anlegen", self.create_workspace_from_sidebar)
)
title_row.addWidget(
self._sidebar_icon_button("◰", "Neue Session im gewählten Arbeitsraum", self.start_new_session)
)
title_row.addWidget(
self._sidebar_icon_button("✎", "Neue Notiz im gewählten Arbeitsraum", self.create_note_for_selected_workspace)
)
layout.addLayout(title_row)
self.sidebar_dynamic_layout = QVBoxLayout()
self.sidebar_dynamic_layout.setContentsMargins(0, 0, 0, 0)
self.sidebar_dynamic_layout.setSpacing(4)
layout.addLayout(self.sidebar_dynamic_layout)
self._refresh_workspace_sidebar()
layout.addStretch()
return sidebar
def _clear_sidebar_dynamic_layout(self):
while self.sidebar_dynamic_layout.count():
item = self.sidebar_dynamic_layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
child_layout = item.layout()
if child_layout is not None:
self._clear_layout(child_layout)
def _clear_layout(self, layout):
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
child_layout = item.layout()
if child_layout is not None:
self._clear_layout(child_layout)
def _refresh_workspace_sidebar(self):
if not hasattr(self, "sidebar_dynamic_layout"):
return
self._clear_sidebar_dynamic_layout()
try:
workspaces = self.workspace_manager.list_workspaces()
selected_workspace = self.workspace_manager.get_workspace(self.selected_workspace_id)
self.selected_workspace_title = selected_workspace.title
sessions = self.workspace_manager.list_sessions(self.selected_workspace_id, limit=8)
notes = self.workspace_manager.list_notes(self.selected_workspace_id, limit=5)
except (OSError, ValueError) as exc:
self._add_sidebar_group(
self.sidebar_dynamic_layout,
"Fehler",
[(f"Nicht geladen: {exc}", self._show_sidebar_placeholder)],
)
return
workspace_items = workspaces[:8]
pinned_workspaces = [item for item in workspaces if item.pinned]
pinned_sessions = [item for item in self.workspace_manager.list_sessions(limit=20) if item.pinned]
session_items = [
item
for item in sessions[:8]
]
note_items = [
(
item.title,
lambda checked=False, record=item: self._open_note_sidebar_item(record),
)
for item in notes
]
self._add_pinned_sidebar_group(self.sidebar_dynamic_layout, "Angeheftet", pinned_workspaces, pinned_sessions)
self._add_workspace_sidebar_group(self.sidebar_dynamic_layout, "", workspace_items)
if note_items:
self._add_sidebar_group(self.sidebar_dynamic_layout, "Notizen", note_items)
if session_items:
self._add_session_sidebar_group(self.sidebar_dynamic_layout, "Sessions", session_items)
def _select_workspace_sidebar_item(self, record):
self.selected_workspace_id = record.id
self.selected_workspace_title = record.title
self.status.setText(f"Arbeitsraum: {record.title}")
self._refresh_workspace_sidebar()
def _select_session_sidebar_item(self, record):
if self.remote_client:
try:
self.remote_client.activate_session(record.id)
except RuntimeError as exc:
self.status.setText(f"Session konnte nicht gemeinsam geöffnet werden: {exc}")
return
else:
self.session_store.activate(record, source="classic-desktop")
self.session_id = record.id
self.session_name = record.title
self._chat_signature = None
if self.remote_client:
self.remote_after = 0
self.remote_events = []
self._remote_next_poll = 0
self._refresh_remote_chat()
else:
self._refresh_chat_history()
self.status.setText(f"Session geöffnet: {record.title}")
def _workspace_label(self, record):
marker = "▾ " if record.id == self.selected_workspace_id else ""
return f"{marker}{record.title}"
def _open_note_sidebar_item(self, record):
QDesktopServices.openUrl(QUrl.fromLocalFile(str(record.path)))
self.status.setText(f"Notiz geöffnet: {record.title}")
def create_note_for_selected_workspace(self):
suggested = _default_session_name_prefix() + "Notiz"
title, accepted = QInputDialog.getText(
self,
"Neue Notiz",
f"Notiz fuer {self.selected_workspace_title}:",
text=suggested,
)
if not accepted:
return
try:
note = self.workspace_manager.create_note(
self.selected_workspace_id,
title.strip() or suggested,
)
except (OSError, ValueError) as exc:
self.status.setText(f"Notiz konnte nicht erstellt werden: {exc}")
return
self._refresh_workspace_sidebar()
QDesktopServices.openUrl(QUrl.fromLocalFile(str(note.path)))
self.status.setText(f"Notiz erstellt: {note.title}")
def create_workspace_from_sidebar(self):
title, accepted = QInputDialog.getText(
self,
"Neuer Arbeitsraum",
"Name:",
text="",
)
if not accepted:
return
title = title.strip()
if not title:
self.status.setText("Arbeitsraum braucht einen Namen.")
return
try:
workspace = self.workspace_manager.create_workspace(title)
except (OSError, ValueError) as exc:
self.status.setText(f"Arbeitsraum konnte nicht erstellt werden: {exc}")
return
self.selected_workspace_id = workspace.id
self.selected_workspace_title = workspace.title
self._refresh_workspace_sidebar()
self.status.setText(f"Arbeitsraum erstellt: {workspace.title}")
def summarize_session_from_sidebar(self, record):
try:
record = self.workspace_manager.update_session_summary_status(record.id, "queued")
started_at = self._session_started_timestamp(record)
display_session_id = self.session_id or record.id
display_session_name = self.session_name or record.title
self._summarize_previous_session_in_background(
record.id,
record.title,
started_at,
time.time(),
display_session_id,
display_session_name,
)
except (OSError, ValueError) as exc:
self.status.setText(f"Summary konnte nicht gestartet werden: {exc}")
return
self._refresh_workspace_sidebar()
self.status.setText(f"Zusammenfassung gestartet: {record.title}")
def start_session_for_workspace(self, record):
self.selected_workspace_id = record.id
self.selected_workspace_title = record.title
self._refresh_workspace_sidebar()
self.start_new_session()
def toggle_workspace_pinned(self, record):
try:
updated = self.workspace_manager.update_workspace_pinned(record.id, not record.pinned)
except (OSError, ValueError) as exc:
self.status.setText(f"Anheften fehlgeschlagen: {exc}")
return
self._refresh_workspace_sidebar()
self.status.setText(
f"Arbeitsraum angeheftet: {updated.title}"
if updated.pinned
else f"Arbeitsraum gelöst: {updated.title}"
)
def toggle_session_pinned(self, record):
try:
updated = self.workspace_manager.update_session_pinned(record.id, not record.pinned)
except (OSError, ValueError) as exc:
self.status.setText(f"Anheften fehlgeschlagen: {exc}")
return
self._refresh_workspace_sidebar()
self.status.setText(
f"Session angeheftet: {updated.title}"
if updated.pinned
else f"Session gelöst: {updated.title}"
)
def assign_session_to_workspace(self, record):
try:
workspaces = self.workspace_manager.list_workspaces()
except OSError as exc:
self.status.setText(f"Arbeitsräume konnten nicht geladen werden: {exc}")
return
labels = [item.title for item in workspaces]
if not labels:
self.status.setText("Noch kein Arbeitsraum vorhanden.")
return
current_index = next(
(index for index, item in enumerate(workspaces) if item.id == record.workspace_id),
0,
)
selected, accepted = QInputDialog.getItem(
self,
"Session zuordnen",
"Projekt oder Vorlesungsmodul:",
labels,
current_index,
False,
)
if not accepted:
return
target = workspaces[labels.index(selected)]
try:
if self.remote_client:
self.remote_client.update_session(record.id, workspace_id=target.id)
else:
self.workspace_manager.move_session(record.id, target.id)
except (OSError, RuntimeError, ValueError) as exc:
self.status.setText(f"Session konnte nicht zugeordnet werden: {exc}")
return
self.selected_workspace_id = target.id
self.selected_workspace_title = target.title
self._refresh_workspace_sidebar()
self.status.setText(
f"Session samt Summary und Medien zugeordnet: {target.title}"
)
def delete_session_from_sidebar(self, record):
answer = QMessageBox.question(
self,
"Session löschen",
f"Session wirklich löschen?\n\n{record.title}",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)
if answer != QMessageBox.Yes:
return
try:
if self.remote_client:
result = self.remote_client.delete_session(record.id)
else:
delete_session_summary(BASE_DIR, record.id)
result = self.workspace_manager.delete_session(record.id)
result["memory"] = self.memory_store.delete_session(record.id)
if self.session_id == record.id:
self.session_store.pointer_path.unlink(missing_ok=True)
replacement = self.session_store.current(create=True)
result["active_session"] = replacement.as_dict()
except (OSError, RuntimeError, ValueError) as exc:
self.status.setText(f"Session konnte nicht gelöscht werden: {exc}")
return
if self.session_id == record.id:
active = result.get("active_session") or {}
self.session_id = str(active.get("id") or "")
self.session_name = str(active.get("title") or "")
self._chat_signature = None
self.chat_history.setHtml(_render_chat_html([], self.theme))
self._refresh_workspace_sidebar()
self.status.setText(f"Session gelöscht: {result.get('title') or record.title}")
def delete_summary_from_sidebar(self, record):
answer = QMessageBox.question(
self,
"Zusammenfassung löschen",
f"Nur die Zusammenfassung dieser Session löschen?\n\n{record.title}",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)
if answer != QMessageBox.Yes:
return
try:
if self.remote_client:
self.remote_client.delete_session_summary(record.id)
else:
delete_session_summary(BASE_DIR, record.id)
except (OSError, RuntimeError, ValueError) as exc:
self.status.setText(f"Zusammenfassung konnte nicht gelöscht werden: {exc}")
return
self._refresh_workspace_sidebar()
self.status.setText(f"Zusammenfassung gelöscht: {record.title}")
def delete_memory_from_panel(self):
try:
if self.remote_client:
records = self.remote_client.list_memories(limit=100).get("memories", [])
else:
records = self.memory_store.list_memories(limit=100)
except (OSError, RuntimeError, ValueError) as exc:
self.memory_status.setText(f"Memory-Liste konnte nicht geladen werden: {exc}")
return
if not records:
self.memory_status.setText("Keine Memory-Inhalte zum Löschen vorhanden.")
return
labels = [
f"{item.get('kind') or 'memory'} · {item.get('summary') or item.get('id')}"
for item in records
]
selected, accepted = QInputDialog.getItem(
self,
"Einzelnes Memory löschen",
"Memory auswählen:",
labels,
0,
False,
)
if not accepted:
return
item = records[labels.index(selected)]
answer = QMessageBox.question(
self,
"Memory löschen",
f"Dieses Memory endgültig aus der aktiven Datenbank löschen?\n\n{selected}",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)
if answer != QMessageBox.Yes:
return
try:
if self.remote_client: