forked from liminalbardo/liminal_backrooms
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgui.py
More file actions
6446 lines (5427 loc) · 262 KB
/
gui.py
File metadata and controls
6446 lines (5427 loc) · 262 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
# gui.py
"""
Main GUI module for Liminal Backrooms application.
All styling is imported from styles.py - the single source of truth for colors/fonts.
"""
import os
import json
import requests
import threading
import math
import random
from datetime import datetime
from io import BytesIO
from PIL import Image
import time
from pathlib import Path
import uuid
import shutil
import networkx as nx
import re
import sys
import webbrowser
import subprocess
import base64
from PyQt6.QtCore import Qt, QRect, QTimer, QRectF, QPointF, QSize, pyqtSignal, QEvent, QPropertyAnimation, QEasingCurve
from PyQt6.QtGui import QFont, QColor, QPainter, QPen, QBrush, QFontDatabase, QTextCursor, QAction, QKeySequence, QTextCharFormat, QLinearGradient, QRadialGradient, QPainterPath, QImage, QPixmap, QShortcut
from PyQt6.QtWidgets import QWidget, QApplication, QMainWindow, QSplitter, QVBoxLayout, QHBoxLayout, QTextEdit, QFrame, QLineEdit, QPushButton, QLabel, QComboBox, QMenu, QFileDialog, QMessageBox, QScrollArea, QToolTip, QSizePolicy, QCheckBox, QGraphicsDropShadowEffect
from config import (
AI_MODELS,
SYSTEM_PROMPT_PAIRS,
SHOW_CHAIN_OF_THOUGHT_IN_CONTEXT,
OUTPUTS_DIR,
DEVELOPER_TOOLS,
TURN_DELAY
)
# Import centralized styling - single source of truth for colors and widget styles
from styles import COLORS, FONTS, get_combobox_style, get_button_style, get_checkbox_style, get_scrollbar_style
# Import shared utilities - with fallback for open_html_in_browser
from shared_utils import generate_image_from_text, get_visible_messages
try:
from shared_utils import open_html_in_browser
except ImportError:
open_html_in_browser = None
# Add import for grouped model selector functionality
from grouped_model_selector import GroupedModelComboBox
# =============================================================================
# MESSAGE WIDGET CHAT SYSTEM - Each message is a separate widget
# =============================================================================
# This solves scroll jumping because adding/updating messages doesn't destroy
# existing widgets. QScrollArea naturally preserves scroll position.
# =============================================================================
class MessageWidget(QFrame):
"""
A single message in the chat - renders as a styled frame with content.
Styling rules:
- No rounded corners (retro CRT theme)
- bg_medium background on message blocks
- Transparent backgrounds on text labels (no black text boxes)
- Left-aligned borders for all messages (including human)
- AI colors applied per AI number
"""
# AI color mapping - matches styles.py COLORS
AI_COLORS = {
1: COLORS['ai_1'], # Bright phosphor green
2: COLORS['ai_2'], # Lighter green
3: COLORS['ai_3'], # Mint green
4: COLORS['ai_4'], # Pale green
5: COLORS['ai_5'], # Near-white green
}
HUMAN_COLOR = COLORS['human'] # Amber
TIMESTAMP_COLOR = '#7a8899' # Subtle readable gray
def __init__(self, message_data, parent=None):
super().__init__(parent)
self.message_data = message_data
self._content_label = None # Reference to content label for updates
self._creation_time = datetime.now()
self._setup_ui()
self._setup_tooltip()
def _setup_tooltip(self):
"""Set up hover tooltip showing message timestamp and metadata."""
# Try to get timestamp from message data, fallback to creation time
ts = self.message_data.get('timestamp') or self.message_data.get('_timestamp')
if ts:
if isinstance(ts, str):
try:
dt = datetime.fromisoformat(ts)
time_str = dt.strftime('%H:%M:%S')
date_str = dt.strftime('%Y-%m-%d')
except (ValueError, TypeError):
time_str = ts
date_str = ''
elif isinstance(ts, (int, float)):
dt = datetime.fromtimestamp(ts)
time_str = dt.strftime('%H:%M:%S')
date_str = dt.strftime('%Y-%m-%d')
else:
time_str = str(ts)
date_str = ''
else:
time_str = self._creation_time.strftime('%H:%M:%S')
date_str = self._creation_time.strftime('%Y-%m-%d')
# Build tooltip parts
role = self.message_data.get('role', '')
ai_name = self.message_data.get('ai_name', '')
model = self.message_data.get('model', '')
tooltip_parts = []
if date_str:
tooltip_parts.append(f"{date_str} {time_str}")
else:
tooltip_parts.append(time_str)
if model:
tooltip_parts.append(f"Model: {model}")
# Estimate token count for this message
content = self.message_data.get('content', '')
if isinstance(content, str):
char_count = len(content)
elif isinstance(content, list):
char_count = sum(len(p.get('text', '')) for p in content if isinstance(p, dict) and p.get('type') == 'text')
else:
char_count = 0
if char_count > 0:
est_tokens = char_count // 4
tooltip_parts.append(f"~{est_tokens} tokens ({char_count} chars)")
self.setToolTip('\n'.join(tooltip_parts))
def _setup_ui(self):
"""Build the widget UI based on message data."""
layout = QVBoxLayout(self)
layout.setContentsMargins(8, 6, 8, 6)
layout.setSpacing(4)
layout.setAlignment(Qt.AlignmentFlag.AlignTop)
role = self.message_data.get('role', 'user')
content = self.message_data.get('content', '')
msg_type = self.message_data.get('_type', '')
# Extract text from structured content
text_content = self._extract_text(content)
# Style based on role/type
if msg_type == 'typing_indicator':
self._setup_typing_indicator()
elif msg_type == 'branch_indicator':
self._setup_branch_indicator(text_content)
elif msg_type == 'agent_notification':
self._setup_notification(text_content)
elif msg_type == 'generated_image':
self._setup_generated_image()
elif msg_type == 'generated_video':
self._setup_generated_video()
elif role == 'user':
self._setup_user_message(text_content)
elif role == 'assistant':
self._setup_assistant_message(text_content)
elif role == 'system':
self._setup_system_message(text_content)
else:
self._setup_default_message(text_content)
def _extract_text(self, content):
"""Extract text from content (handles structured content with images)."""
if isinstance(content, list):
text_parts = []
for part in content:
if isinstance(part, dict) and part.get('type') == 'text':
text_parts.append(part.get('text', ''))
return ''.join(text_parts)
return str(content) if content else ''
def _format_code_blocks(self, text):
"""
Convert markdown code blocks and inline code to HTML for Qt RichText.
Uses table-based HTML structure that Qt renders properly.
"""
import re
import html
# Split by code blocks first (```...```)
code_block_pattern = r'```(\w*)\n?(.*?)```'
parts = []
last_end = 0
for match in re.finditer(code_block_pattern, text, re.DOTALL):
# Text before this code block
before_text = text[last_end:match.start()]
parts.append(('text', before_text))
# The code block
lang = match.group(1) or ''
code = match.group(2)
parts.append(('code_block', code, lang))
last_end = match.end()
# Remaining text
if last_end < len(text):
parts.append(('text', text[last_end:]))
# Process each part
result = []
# Colors for code blocks
code_bg = '#001100'
header_bg = '#002200'
border_color = COLORS.get('border', '#0D3B0D')
code_text_color = '#E0E0E0'
for part in parts:
if part[0] == 'code_block':
code = html.escape(part[1].rstrip())
lang = part[2].lower()
# Language header row
lang_row = ''
if lang:
lang_row = (
f'<tr><td style="background-color: {header_bg}; '
f'padding: 4px 10px; border-bottom: 1px solid {border_color};">'
f'<span style="color: {COLORS["text_dim"]}; font-size: 9pt; '
f'font-family: Consolas, Monaco, monospace; font-weight: bold;">'
f'{lang.upper()}</span></td></tr>'
)
# Code block with subtle border
result.append(
f'<table cellspacing="0" cellpadding="0" '
f'style="margin: 8px 0 8px 10px; border: 1px solid {border_color};">'
f'<tr><td style="background-color: {code_bg}; padding: 0;">'
f'<table cellspacing="0" cellpadding="0" width="100%">'
f'{lang_row}'
f'<tr><td style="background-color: {code_bg}; padding: 10px 12px;">'
f'<pre style="margin: 0; font-family: Consolas, Monaco, monospace; '
f'font-size: 9pt; white-space: pre-wrap; color: {code_text_color};">{code}</pre>'
f'</td></tr></table></td></tr></table>'
)
else:
# Regular text - escape and process inline code
text_part = html.escape(part[1])
# Replace inline code `...` with styled spans
inline_pattern = r'`([^`]+)`'
text_part = re.sub(
inline_pattern,
f'<span style="background-color: {code_bg}; color: {COLORS["accent_cyan"]}; '
f'border: 1px solid {border_color}; '
f'padding: 1px 4px; font-family: Consolas, Monaco, monospace; font-size: 9pt;">'
f'\\1</span>',
text_part
)
# Convert newlines to <br>
text_part = text_part.replace('\n', '<br/>')
result.append(text_part)
return ''.join(result)
def _create_header_widget(self, name_text, color):
"""Create a header widget with name."""
header_widget = QWidget()
header_widget.setStyleSheet("background-color: transparent;")
header_layout = QHBoxLayout(header_widget)
header_layout.setContentsMargins(0, 0, 0, 0)
header_layout.setSpacing(8)
# Name label (left)
name_label = QLabel(name_text)
name_label.setStyleSheet(f"background-color: transparent; color: {color}; font-weight: bold; font-size: 9pt;")
header_layout.addWidget(name_label)
header_layout.addStretch()
return header_widget
def _get_ai_color(self):
"""Get the color for this AI based on _ai_number or extracted from ai_name."""
ai_num = self.message_data.get('_ai_number')
# If no _ai_number, try to extract from ai_name (e.g., "AI-1", "AI-2")
if ai_num is None:
ai_name = self.message_data.get('ai_name', '')
if ai_name:
import re
match = re.search(r'AI-?(\d+)', ai_name, re.IGNORECASE)
if match:
ai_num = int(match.group(1))
# Default to 1 if still not found
if ai_num is None:
ai_num = 1
return self.AI_COLORS.get(ai_num, self.AI_COLORS[1])
def _setup_typing_indicator(self):
"""Setup typing indicator style."""
ai_name = self.message_data.get('ai_name', 'AI')
model = self.message_data.get('model', '')
border_color = self._get_ai_color()
display_name = f"{ai_name} ({model})" if model else ai_name
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {border_color};
border-radius: 0px;
}}
""")
header = self._create_header_widget(display_name, border_color)
self.layout().addWidget(header)
dots = QLabel("thinking...")
dots.setStyleSheet(f"background-color: transparent; color: {COLORS['text_dim']}; font-style: italic;")
self.layout().addWidget(dots)
def _setup_branch_indicator(self, text):
"""Setup branch indicator style."""
if "Rabbitholing" in text:
color = COLORS.get('accent_magenta', '#ff00ff')
else:
color = COLORS.get('accent_cyan', '#00ffff')
self.setStyleSheet(f"""
MessageWidget {{
background-color: transparent;
border: 1px dashed {color};
border-radius: 0px;
padding: 4px;
}}
""")
label = QLabel(text)
label.setStyleSheet(f"background-color: transparent; color: {color}; font-size: 9pt;")
label.setWordWrap(True)
self.layout().addWidget(label)
def _setup_notification(self, text):
"""Setup agent notification style with color-matching backgrounds."""
command_success = self.message_data.get('_command_success')
if command_success is False:
bg_color = "#1A0000" # Dark red tint
border_color = "#ff4444" # Bright red (distinct from human pink)
elif command_success is True:
bg_color = "#001A00" # Dark green tint
border_color = COLORS.get('notify_success', '#5DFF44')
else:
bg_color = "#1A1A00" # Dark yellow tint
border_color = COLORS.get('notify_info', '#FFFF48')
self.setStyleSheet(f"""
MessageWidget {{
background-color: {bg_color};
border-left: 3px solid {border_color};
border-radius: 0px;
}}
""")
label = QLabel(text)
label.setStyleSheet(f"background-color: transparent; color: {COLORS['text_normal']}; font-size: 9pt;")
label.setWordWrap(True)
label.setTextFormat(Qt.TextFormat.PlainText)
self.layout().addWidget(label)
def _setup_generated_image(self):
"""Setup generated image display with AI-matching colors."""
ai_name = self.message_data.get('ai_name', 'AI')
model = self.message_data.get('model', '')
# Try multiple field names for image model
image_model = (self.message_data.get('_image_model') or
self.message_data.get('image_model') or
'image model')
image_path = self.message_data.get('generated_image_path', '')
# Try multiple field names for prompt, including extracting from content
image_prompt = (self.message_data.get('_prompt') or
self.message_data.get('image_prompt') or '')
# If no prompt found, try extracting from content (e.g., !image "prompt here")
if not image_prompt:
content = self.message_data.get('content', '')
if isinstance(content, list):
for part in content:
if isinstance(part, dict) and part.get('type') == 'text':
text = part.get('text', '')
import re
match = re.search(r'!image\s+"([^"]+)"', text)
if match:
image_prompt = match.group(1)
break
elif isinstance(content, str) and '!image' in content:
import re
match = re.search(r'!image\s+"([^"]+)"', content)
if match:
image_prompt = match.group(1)
border_color = self._get_ai_color()
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {border_color};
border-radius: 0px;
}}
""")
# Header: "AI-X (model) generated an image using <image_model>"
display_name = f"{ai_name} ({model})" if model else ai_name
header_text = f"{display_name} generated an image using {image_model}"
header = self._create_header_widget(header_text, border_color)
self.layout().addWidget(header)
# Show prompt if available
if image_prompt:
prompt_label = QLabel(f"Prompt: {image_prompt}")
prompt_label.setStyleSheet(f"background-color: transparent; color: {self.TIMESTAMP_COLOR}; font-size: 9pt; font-style: italic;")
prompt_label.setWordWrap(True)
self.layout().addWidget(prompt_label)
# Display image - scales to fill available width
if image_path and os.path.exists(image_path):
img_label = QLabel()
img_label.setStyleSheet("background-color: transparent;")
pixmap = QPixmap(image_path)
if not pixmap.isNull():
img_label._original_pixmap = pixmap
# Scale to available width (with padding margin)
avail_width = max(400, self.width() - 40)
if pixmap.width() > avail_width:
scaled = pixmap.scaledToWidth(avail_width, Qt.TransformationMode.SmoothTransformation)
else:
scaled = pixmap
img_label.setPixmap(scaled)
# Re-scale on resize
orig_resize = img_label.resizeEvent
def _on_resize(event, lbl=img_label):
pm = getattr(lbl, '_original_pixmap', None)
if pm and not pm.isNull():
w = lbl.parent().width() - 40 if lbl.parent() else lbl.width()
w = max(200, w)
if pm.width() > w:
lbl.setPixmap(pm.scaledToWidth(w, Qt.TransformationMode.SmoothTransformation))
else:
lbl.setPixmap(pm)
if orig_resize:
orig_resize(event)
img_label.resizeEvent = _on_resize
self.layout().addWidget(img_label)
def _setup_generated_video(self):
"""Setup generated video display with AI-matching colors."""
ai_name = self.message_data.get('ai_name', 'AI')
model = self.message_data.get('model', '')
video_model = self.message_data.get('video_model', 'unknown model')
video_path = self.message_data.get('generated_video_path', '')
video_prompt = self.message_data.get('video_prompt', '')
border_color = self._get_ai_color()
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {border_color};
border-radius: 0px;
}}
""")
# Header: "AI-X (model) generated a video using <video_model>"
display_name = f"{ai_name} ({model})" if model else ai_name
header_text = f"{display_name} generated a video using {video_model}"
header = self._create_header_widget(header_text, border_color)
self.layout().addWidget(header)
# Show prompt if available
if video_prompt:
prompt_label = QLabel(f"Prompt: {video_prompt}")
prompt_label.setStyleSheet(f"background-color: transparent; color: {self.TIMESTAMP_COLOR}; font-size: 9pt; font-style: italic;")
prompt_label.setWordWrap(True)
self.layout().addWidget(prompt_label)
# Display video path info
if video_path:
path_label = QLabel(f"Video: {os.path.basename(video_path)}")
path_label.setStyleSheet(f"background-color: transparent; color: {COLORS['text_normal']}; font-size: 9pt;")
self.layout().addWidget(path_label)
def _setup_user_message(self, text):
"""Setup human user message style - left-aligned like AI messages."""
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {self.HUMAN_COLOR};
border-radius: 0px;
}}
""")
display_name = self.message_data.get('_user_name', 'Human User')
header = self._create_header_widget(display_name, self.HUMAN_COLOR)
self.layout().addWidget(header)
# Format code blocks and use RichText
formatted_text = self._format_code_blocks(text)
content = QLabel(formatted_text)
content.setStyleSheet(f"background-color: transparent; color: {COLORS['text_normal']};")
content.setWordWrap(True)
content.setTextFormat(Qt.TextFormat.RichText)
content.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.layout().addWidget(content)
self._content_label = content
def _setup_assistant_message(self, text):
"""Setup AI assistant message style."""
ai_name = self.message_data.get('ai_name', 'AI')
model = self.message_data.get('model', '')
border_color = self._get_ai_color()
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {border_color};
border-radius: 0px;
}}
""")
display_name = f"{ai_name} ({model})" if model else ai_name
header = self._create_header_widget(display_name, border_color)
self.layout().addWidget(header)
# Format code blocks and use RichText
formatted_text = self._format_code_blocks(text)
content = QLabel(formatted_text)
content.setStyleSheet(f"background-color: transparent; color: {COLORS['text_normal']};")
content.setWordWrap(True)
content.setTextFormat(Qt.TextFormat.RichText)
content.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.layout().addWidget(content)
self._content_label = content
def _setup_system_message(self, text):
"""Setup system message style."""
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-left: 3px solid {COLORS['text_dim']};
border-radius: 0px;
}}
""")
# Format code blocks and use RichText
formatted_text = self._format_code_blocks(text)
content = QLabel(formatted_text)
content.setStyleSheet(f"background-color: transparent; color: {COLORS['text_dim']}; font-style: italic;")
content.setWordWrap(True)
content.setTextFormat(Qt.TextFormat.RichText)
self.layout().addWidget(content)
self._content_label = content
def _setup_default_message(self, text):
"""Default message style."""
self.setStyleSheet(f"""
MessageWidget {{
background-color: {COLORS['bg_medium']};
border-radius: 0px;
}}
""")
# Format code blocks and use RichText
formatted_text = self._format_code_blocks(text)
content = QLabel(formatted_text)
content.setStyleSheet(f"background-color: transparent; color: {COLORS['text_normal']};")
content.setWordWrap(True)
content.setTextFormat(Qt.TextFormat.RichText)
self.layout().addWidget(content)
self._content_label = content
def mouseDoubleClickEvent(self, event):
"""Copy message text to clipboard on double-click."""
content = self.message_data.get('content', '')
if isinstance(content, list):
text = ' '.join(p.get('text', '') for p in content if isinstance(p, dict) and p.get('type') == 'text')
else:
text = str(content)
if text.strip():
QApplication.clipboard().setText(text)
# Brief visual feedback - flash the border
original_style = self.styleSheet()
self.setStyleSheet(original_style + f"\nMessageWidget {{ border: 1px solid {COLORS['accent_cyan']}; }}")
QTimer.singleShot(300, lambda: self.setStyleSheet(original_style))
super().mouseDoubleClickEvent(event)
def update_content(self, new_text):
"""Update the content of this message (for streaming).
For streaming, we use the simple HTML approach since widgets can't be
efficiently updated incrementally. Full code block widgets are used
for final rendered messages.
"""
if self._content_label:
# Format code blocks for RichText display (HTML-based for streaming)
formatted_text = self._format_code_blocks(new_text)
self._content_label.setText(formatted_text)
class SearchOverlay(QWidget):
"""Search bar overlay for finding text in conversation."""
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(36)
self.match_indices = [] # List of (widget_index, text_position) for matches
self.current_match = -1
self._setup_ui()
self.hide() # Hidden by default
def _setup_ui(self):
layout = QHBoxLayout(self)
layout.setContentsMargins(8, 4, 8, 4)
layout.setSpacing(6)
self.setStyleSheet(f"""
QWidget {{
background-color: {COLORS['bg_medium']};
border-bottom: 1px solid {COLORS['border_glow']};
}}
""")
# Search icon label
icon_label = QLabel("\U0001f50d")
icon_label.setStyleSheet(f"background-color: transparent; color: {COLORS['text_dim']}; font-size: 12px; border: none;")
layout.addWidget(icon_label)
# Search input
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search conversation...")
self.search_input.setStyleSheet(f"""
QLineEdit {{
background-color: {COLORS['bg_dark']};
color: {COLORS['text_bright']};
border: 1px solid {COLORS['border_glow']};
border-radius: 0px;
padding: 4px 8px;
font-size: 10px;
}}
QLineEdit:focus {{
border-color: {COLORS['accent_cyan']};
}}
""")
self.search_input.textChanged.connect(self._on_search_changed)
self.search_input.returnPressed.connect(self._next_match)
layout.addWidget(self.search_input)
# Match counter
self.match_label = QLabel("")
self.match_label.setStyleSheet(f"background-color: transparent; color: {COLORS['text_dim']}; font-size: 9px; border: none; min-width: 60px;")
layout.addWidget(self.match_label)
# Navigation buttons
prev_btn = QPushButton("\u25b2")
prev_btn.setFixedSize(24, 24)
prev_btn.setStyleSheet(f"""
QPushButton {{
background-color: {COLORS['bg_dark']};
color: {COLORS['accent_cyan']};
border: 1px solid {COLORS['border_glow']};
border-radius: 0px;
font-size: 10px;
}}
QPushButton:hover {{
background-color: {COLORS['accent_cyan']};
color: {COLORS['bg_dark']};
}}
""")
prev_btn.clicked.connect(self._prev_match)
layout.addWidget(prev_btn)
next_btn = QPushButton("\u25bc")
next_btn.setFixedSize(24, 24)
next_btn.setStyleSheet(prev_btn.styleSheet())
next_btn.clicked.connect(self._next_match)
layout.addWidget(next_btn)
# Close button
close_btn = QPushButton("\u2715")
close_btn.setFixedSize(24, 24)
close_btn.setStyleSheet(f"""
QPushButton {{
background-color: transparent;
color: {COLORS['text_dim']};
border: none;
font-size: 12px;
}}
QPushButton:hover {{
color: {COLORS['accent_pink']};
}}
""")
close_btn.clicked.connect(self.close_search)
layout.addWidget(close_btn)
def toggle(self):
"""Toggle search bar visibility."""
if self.isVisible():
self.close_search()
else:
self.show()
self.search_input.setFocus()
self.search_input.selectAll()
def close_search(self):
"""Close search and clear highlights."""
self.hide()
self.search_input.clear()
self.match_indices = []
self.current_match = -1
self.match_label.setText("")
self._clear_highlights()
def _on_search_changed(self, text):
"""Search text changed - find all matches."""
self.match_indices = []
self.current_match = -1
self._clear_highlights()
if not text or len(text) < 2:
self.match_label.setText("")
return
# Find matches in parent's chat scroll area
chat_area = self._get_chat_area()
if not chat_area:
return
search_lower = text.lower()
container = chat_area.widget()
if not container:
return
layout = container.layout()
if not layout:
return
for i in range(layout.count()):
item = layout.itemAt(i)
if not item or not item.widget():
continue
widget = item.widget()
if not isinstance(widget, MessageWidget):
continue
# Check message content
msg_text = widget.message_data.get('content', '')
if isinstance(msg_text, list):
msg_text = ' '.join(p.get('text', '') for p in msg_text if isinstance(p, dict) and p.get('type') == 'text')
if search_lower in str(msg_text).lower():
self.match_indices.append(i)
if self.match_indices:
self.current_match = 0
self.match_label.setText(f"1/{len(self.match_indices)}")
self._highlight_current()
else:
self.match_label.setText("0 results")
def _next_match(self):
"""Go to next match."""
if not self.match_indices:
return
self.current_match = (self.current_match + 1) % len(self.match_indices)
self.match_label.setText(f"{self.current_match + 1}/{len(self.match_indices)}")
self._highlight_current()
def _prev_match(self):
"""Go to previous match."""
if not self.match_indices:
return
self.current_match = (self.current_match - 1) % len(self.match_indices)
self.match_label.setText(f"{self.current_match + 1}/{len(self.match_indices)}")
self._highlight_current()
def _highlight_current(self):
"""Highlight and scroll to current match."""
if self.current_match < 0 or not self.match_indices:
return
chat_area = self._get_chat_area()
if not chat_area:
return
widget_idx = self.match_indices[self.current_match]
container = chat_area.widget()
if not container:
return
layout = container.layout()
if not layout:
return
item = layout.itemAt(widget_idx)
if not item or not item.widget():
return
target = item.widget()
# Clear all highlights first
self._clear_highlights()
# Add highlight border to matching widgets
for idx in self.match_indices:
match_item = layout.itemAt(idx)
if match_item and match_item.widget():
w = match_item.widget()
# Store original style
if not hasattr(w, '_original_border_style'):
w._original_border_style = w.styleSheet()
current_style = w.styleSheet()
if idx == widget_idx:
# Current match - bright highlight
w.setStyleSheet(current_style + f"\nMessageWidget {{ border-right: 3px solid {COLORS['accent_cyan']}; }}")
else:
# Other matches - dim highlight
w.setStyleSheet(current_style + f"\nMessageWidget {{ border-right: 2px solid {COLORS['text_dim']}; }}")
# Scroll to the target widget
chat_area.ensureWidgetVisible(target, 50, 50)
def _clear_highlights(self):
"""Clear all search highlights."""
chat_area = self._get_chat_area()
if not chat_area:
return
container = chat_area.widget()
if not container:
return
layout = container.layout()
if not layout:
return
for i in range(layout.count()):
item = layout.itemAt(i)
if not item or not item.widget():
continue
w = item.widget()
if hasattr(w, '_original_border_style'):
w.setStyleSheet(w._original_border_style)
del w._original_border_style
def _get_chat_area(self):
"""Get the ChatScrollArea from parent hierarchy."""
parent = self.parent()
if hasattr(parent, 'conversation_display'):
return parent.conversation_display
return None
class ChatScrollArea(QScrollArea):
"""
Scroll area for chat messages with smart auto-scroll behavior.
═══════════════════════════════════════════════════════════════════════════
SCROLL SYSTEM ARCHITECTURE
═══════════════════════════════════════════════════════════════════════════
This widget solves the "chat scroll problem": auto-scroll to bottom for new
messages, BUT respect when user scrolls up to read history.
KEY CONCEPTS:
─────────────
• _should_follow: True = auto-scroll to bottom on new content
False = user scrolled away, DON'T auto-scroll
• _programmatic_scroll: True = WE are scrolling (ignore in _on_scroll)
False = User might be scrolling (track intent)
• Debouncing: Multiple rapid add_message() calls → single scroll after 50ms
STATE TRANSITIONS:
──────────────────
User scrolls UP (away from bottom):
→ _should_follow = False
→ New messages appear but scroll stays put
User scrolls DOWN to bottom:
→ _should_follow = True
→ New messages trigger auto-scroll
Rebuild (typing indicator → real message):
→ Save _should_follow
→ Block _on_scroll with _programmatic_scroll=True
→ Rebuild widgets
→ Restore _should_follow
→ Only scroll if was following
═══════════════════════════════════════════════════════════════════════════
DEBUG OUTPUT GUIDE
═══════════════════════════════════════════════════════════════════════════
Enable debugging: Set config.DEVELOPER_TOOLS = True
- ChatScrollArea._debug (for [CHAT-SCROLL] messages)
- ConversationPane._SCROLL_DEBUG (for [SCROLL] messages)
Filter logs: grep "SCROLL" to see all scroll-related output
───────────────────────────────────────────────────────────────────────────
LOG MESSAGE REFERENCE
───────────────────────────────────────────────────────────────────────────
[CHAT-SCROLL] User scrolled UP → auto-follow OFF (pos=X/Y)
✓ HEALTHY: User scrolled away from bottom to read history.
• X = current scroll position, Y = maximum scroll position
• _should_follow is now False
• New messages will NOT trigger auto-scroll
[CHAT-SCROLL] User scrolled to BOTTOM → auto-follow ON (pos=X/Y)
✓ HEALTHY: User returned to bottom of chat.
• _should_follow is now True
• New messages WILL trigger auto-scroll
[CHAT-SCROLL] Auto-scrolled to bottom (max=Z)
✓ HEALTHY: Programmatic scroll executed successfully.
• Z = new maximum scroll position
• Only logs when position changes by >100px (reduces spam)
[CHAT-SCROLL] ⚠ Scroll retry limit reached (layout still empty)
⚠ WARNING: Tried to scroll 5 times but layout never became ready.
• Usually means widgets aren't being added properly
• Check if add_message() is being called
[CHAT-SCROLL] Cleared N messages (scroll intent X: _should_follow=Y)
• N = number of messages removed
• X = "RESET to follow" or "preserved"
• If X="preserved" but Y changed unexpectedly, that's a BUG
[SCROLL] Rebuild starting: N messages, _should_follow=X
• A full widget rebuild is starting (e.g., typing indicator → message)
• N = message count, X = scroll state being preserved
[SCROLL] Rebuild complete: ACTION
• Rebuild finished
• ACTION = "will scroll" or "NO scroll (user scrolled away)"
• If user had scrolled away but ACTION="will scroll", that's a BUG
───────────────────────────────────────────────────────────────────────────
DEBUGGING COMMON ISSUES
───────────────────────────────────────────────────────────────────────────
SYMPTOM: Scroll jumps to bottom unexpectedly
1. Look for "User scrolled UP → auto-follow OFF" - did it fire?
2. After that, look for any "_should_follow=True"
3. Check "Rebuild complete" - should say "NO scroll (user scrolled away)"
4. Look for "scroll intent RESET" - that resets to following mode!
SYMPTOM: Scroll doesn't follow new messages
1. Look for "User scrolled to BOTTOM" - is user actually at bottom?
2. Check for "Auto-scrolled to bottom" - is it firing?
3. If you see "⚠ Scroll retry limit reached", layout isn't becoming ready
SYMPTOM: Too much log spam
1. Normal: One "Auto-scrolled" per significant scroll change
2. If seeing rapid repeated messages, debouncing may be broken
3. Check _scroll_timer.setInterval(50) is set
═══════════════════════════════════════════════════════════════════════════
"""
ZOOM_MIN = 50
ZOOM_MAX = 200
ZOOM_STEP = 10
ZOOM_DEFAULT = 100
def __init__(self, parent=None):
super().__init__(parent)
# ─── Scroll State ───────────────────────────────────────────────────
self._should_follow = True # True = auto-scroll to bottom on new content
self._programmatic_scroll = False # True = ignore _on_scroll (we're scrolling)
self._zoom_level = self.ZOOM_DEFAULT # Current zoom level (50-200%)