-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidgets.py
More file actions
1256 lines (1028 loc) · 49.9 KB
/
widgets.py
File metadata and controls
1256 lines (1028 loc) · 49.9 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
"""Custom widgets and UI helpers for Delta Tool using imgui-bundle."""
import difflib
import math
import time
import re
from pathlib import Path
from dataclasses import dataclass, field
from typing import Callable, Any
from imgui_bundle import imgui, imgui_md
# Optional Dependencies
try:
import versus # type: ignore
from versus.interfaces import Myers # type: ignore
_versus_available = True
except ImportError:
_versus_available = False
Myers = None
from core import build_tolerant_regex, parse_diffs
from pattern import code_block_pattern, plan_block_pattern
from styles import STYLE
# Generic code block pattern (match balanced backticks)
generic_code_pattern = re.compile(
r"^\s*(`{3,})([^\n]*)\n(.*?)\n^\s*\1",
re.MULTILINE | re.DOTALL
)
# Incomplete patterns for streaming
incomplete_plan_pattern = re.compile(
r"^<<<<<<< PLAN(?:\nTitle:\s*([^\n]*))?(?:\nPrompt:\s*(.*))?$",
re.MULTILINE | re.DOTALL
)
# Detect start of code block that extends to end of string (missing closing backticks)
incomplete_diff_pattern = re.compile(
r"(?:^([^\n`]+)\n)?^\s*```([^\n]*)\n(.*)$",
re.MULTILINE | re.DOTALL
)
def render_loading_spinner(text: str = "Generating...", radius: float = 6.0):
"""Render a spinner indicator."""
pos = imgui.get_cursor_screen_pos()
center = imgui.ImVec2(pos.x + radius + 4, pos.y + radius + 1)
draw_list = imgui.get_window_draw_list()
thickness = 2.0
# Background ring
color_bg = STYLE.get_u32("fg_dim", 50)
draw_list.add_circle(center, radius, color_bg, 20, thickness)
# Rotating Arc
t = time.time()
start_angle = t * 6.0
end_angle = start_angle + (math.pi / 1.5)
color_fg = STYLE.get_u32("fg_dim")
draw_list.path_clear()
draw_list.path_arc_to(center, radius, start_angle, end_angle, 20)
draw_list.path_stroke(color_fg, 0, thickness)
imgui.dummy(imgui.ImVec2(radius * 2 + 10, radius * 2 + 2))
if text:
imgui.same_line()
dots = int(t * 2) % 4
# Strip existing dots if present to avoid double dots
base = text.rstrip(".")
imgui.align_text_to_frame_padding()
imgui.text_colored(STYLE.get_imvec4("fg_dim"), f"{base}{'.' * dots}")
def render_viewer_header(
collapsed: bool,
label_func: Callable[[], None],
right_align_func: Callable[[], None] | None = None
) -> tuple[bool, bool]:
"""Render a standard viewer header with expand/collapse toggle.
Returns:
Tuple of (new_collapsed_state, toggled).
"""
toggled = False
header_height = 32
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4("diff_head"))
imgui.push_style_var(imgui.StyleVar_.window_padding, imgui.ImVec2(4, 4))
imgui.begin_child("header", imgui.ImVec2(0, header_height), child_flags=imgui.ChildFlags_.borders, window_flags=imgui.WindowFlags_.no_scrollbar | imgui.WindowFlags_.no_scroll_with_mouse)
# Vertically center content
content_height = 20
padding = (header_height - content_height) / 2 - 4
if padding > 0:
imgui.set_cursor_pos_y(imgui.get_cursor_pos_y() + padding)
# Expand/collapse arrow
arrow = ">" if collapsed else "v"
# We rely on the parent pushing an ID for the viewer
if imgui.button(f"{arrow}##expand", imgui.ImVec2(24, 20)):
collapsed = not collapsed
toggled = True
imgui.same_line()
label_func()
if right_align_func:
right_align_func()
imgui.end_child()
imgui.pop_style_var()
imgui.pop_style_color()
return collapsed, toggled
@dataclass
class DiffHunk:
"""Represents a single diff hunk."""
type: str # "context", "change", "skipped"
text: str = ""
old: str = ""
new: str = ""
content: str = "" # For skipped hunks, the hidden content
start_line: int = 0
@dataclass
class DiffViewerState:
"""State for a DiffViewer widget."""
content: str = ""
filename: str = "Unknown"
is_creation: bool = False
suppress_new_label: bool = False
hunks: list = field(default_factory=list)
collapsed: bool = True
reverted: set = field(default_factory=set)
current_change_idx: int = 0
change_indices: list = field(default_factory=list)
left_scroll_y: float = 0.0
right_scroll_y: float = 0.0
id: int = 0
incomplete: bool = False
class DiffViewer:
"""Widget to display synchronized side-by-side diffs with navigation."""
def __init__(self, content: str, block_state: dict, viewer_id: int = 0, filename_hint: str | None = None, language_hint: str | None = None, incomplete: bool = False):
self.state = DiffViewerState(
content=content,
collapsed=block_state.get("collapsed", True),
reverted=block_state.get("reverted", set()),
id=viewer_id,
incomplete=incomplete
)
self.block_state = block_state
self.filename_hint = filename_hint
self.language_hint = language_hint
self._cached_height: float | None = None
self._parse_content()
def _parse_content(self):
"""Parse the diff content into hunks."""
if self.filename_hint and self.state.filename == "Unknown":
self.state.filename = self.filename_hint
# Wrap content in dummy code block for parse_diffs logic
prefix = f"{self.filename_hint}\n" if self.filename_hint else ""
info = self.language_hint if self.language_hint else ""
wrapped = f"{prefix}```{info}\n{self.state.content}\n```"
parsed = parse_diffs(wrapped)
if not parsed:
return
# Infer filename from first hunk (all hunks in block belong to one file)
self.state.filename = parsed[0]["filename"]
diff_hunks = [(d["original"], d["new"]) for d in parsed]
# Try to match against actual file for full context
full_content_found = False
if self.state.filename != "Unknown":
try:
# parse_diffs already reconciles path
real_path = Path.cwd() / self.state.filename
if not real_path.exists():
# Check if creation (file missing and search block empty)
if diff_hunks and all(orig.strip() == "" for orig, _ in diff_hunks):
self.state.is_creation = True
if real_path.exists() and real_path.is_file():
original_file_content = real_path.read_text("utf-8")
if diff_hunks:
full_hunks = []
current_pos = 0
all_matched = True
for i, (search, replace) in enumerate(diff_hunks):
if search == "":
all_matched = False
break
pattern = re.compile(build_tolerant_regex(search))
match = pattern.search(original_file_content, current_pos)
if match:
start, end = match.span()
if start > current_pos:
ctx = original_file_content[current_pos:start]
full_hunks.extend(self._compress_context(ctx, i == 0, False))
full_hunks.extend(self._refine_diff(original_file_content[start:end], replace))
current_pos = end
else:
all_matched = False
break
if all_matched:
if current_pos < len(original_file_content):
ctx = original_file_content[current_pos:]
full_hunks.extend(self._compress_context(ctx, False, True))
self.state.hunks = full_hunks
full_content_found = True
except Exception:
pass
if not full_content_found:
for original, new in diff_hunks:
self.state.hunks.extend(self._refine_diff(original, new))
# Build change indices
self.state.change_indices = [i for i, h in enumerate(self.state.hunks) if h.type == "change"]
self._cached_height = None
def _compress_context(self, text: str, is_first: bool, is_last: bool) -> list:
"""Compress large context sections."""
lines = text.splitlines(keepends=True)
limit, keep = 12, 4
if len(lines) <= limit:
return [DiffHunk(type="context", text=text)]
res = []
if is_first:
skipped = "".join(lines[:-keep])
res.append(DiffHunk(type="skipped", text=f"... ({len(lines)-keep} lines skipped) ...\n", content=skipped))
res.append(DiffHunk(type="context", text="".join(lines[-keep:])))
elif is_last:
res.append(DiffHunk(type="context", text="".join(lines[:keep])))
skipped = "".join(lines[keep:])
res.append(DiffHunk(type="skipped", text=f"... ({len(lines)-keep} lines skipped) ...\n", content=skipped))
else:
mid_skip = len(lines) - 2 * keep
res.append(DiffHunk(type="context", text="".join(lines[:keep])))
skipped = "".join(lines[keep:-keep])
res.append(DiffHunk(type="skipped", text=f"... ({mid_skip} lines skipped) ...\n", content=skipped))
res.append(DiffHunk(type="context", text="".join(lines[-keep:])))
return res
def _refine_diff(self, old_text: str, new_text: str) -> list:
"""Refine diff between old and new text."""
old_lines = old_text.splitlines(keepends=True)
new_lines = new_text.splitlines(keepends=True)
hunks = []
if _versus_available:
try:
hunks = self._refine_diff_versus(old_lines, new_lines)
except Exception:
hunks = []
if not hunks:
hunks = self._refine_diff_difflib(old_lines, new_lines)
return hunks
def _refine_diff_versus(self, old_lines, new_lines) -> list:
"""Use Myers diff algorithm."""
hunks = []
diffs = Myers.diff(old_lines, new_lines)
current_op = None
old_buf: list[str] = []
new_buf: list[str] = []
for op, line in diffs:
if op == 'equal':
if current_op == 'diff':
hunks.append(DiffHunk(type="change", old="".join(old_buf), new="".join(new_buf)))
old_buf, new_buf = [], []
current_op = 'equal'
old_buf.append(line)
else:
if current_op == 'equal':
hunks.append(DiffHunk(type="context", text="".join(old_buf)))
old_buf = []
current_op = 'diff'
if op == 'delete':
old_buf.append(line)
elif op == 'insert':
new_buf.append(line)
if current_op == 'equal':
hunks.append(DiffHunk(type="context", text="".join(old_buf)))
elif current_op == 'diff':
hunks.append(DiffHunk(type="change", old="".join(old_buf), new="".join(new_buf)))
return hunks
def _refine_diff_difflib(self, old_lines, new_lines) -> list:
"""Fallback to difflib."""
hunks = []
matcher = difflib.SequenceMatcher(None, old_lines, new_lines)
for tag, i1, i2, j1, j2 in matcher.get_opcodes():
if tag == 'equal':
hunks.append(DiffHunk(type="context", text="".join(old_lines[i1:i2])))
else:
hunks.append(DiffHunk(type="change", old="".join(old_lines[i1:i2]), new="".join(new_lines[j1:j2])))
return hunks
def update_content(self, new_content: str, incomplete: bool = False):
"""Update the diff content."""
self.state.incomplete = incomplete
if self.state.content == new_content:
return
self.state.content = new_content
self.state.hunks = []
self._cached_height = None
self._parse_content()
def render(self) -> bool:
"""Render the diff viewer. Returns True if clicked to expand/collapse."""
imgui.push_id(f"diff_{self.state.id}")
def render_label():
if self.state.is_creation:
label = f"{self.state.filename} (New File)" if not self.state.suppress_new_label else self.state.filename
imgui.text_colored(STYLE.get_imvec4("txt_suc"), label)
else:
imgui.text(f"{self.state.filename}")
if self.state.incomplete:
imgui.same_line()
render_loading_spinner("")
def render_right():
# Apply button
imgui.same_line(imgui.get_window_width() - 190)
if imgui.button(f"Reapply##apply_{self.state.id}", imgui.ImVec2(0, 20)):
try:
import core
import application_state
# Reconstruct wrappable content
prefix = f"{self.filename_hint}\n" if self.filename_hint else ""
info = self.language_hint if self.language_hint else ""
wrapped = f"{prefix}```{info}\n{self.state.content}\n```"
core.apply_diffs(wrapped)
application_state.log_message(f"Manually applied diff to {self.state.filename}")
# Refresh
core.file_cache.invalidate(self.state.filename)
if hasattr(application_state, 'state'):
application_state.state.stats_dirty = True
except Exception as e:
import application_state
application_state.log_message(f"Failed to apply diff: {e}")
if imgui.is_item_hovered():
imgui.set_tooltip("Attempt to apply this diff again")
# Navigation controls on the right
num_changes = len(self.state.change_indices)
if num_changes > 0:
imgui.same_line(imgui.get_window_width() - 120)
if self.state.collapsed:
imgui.text(f"{num_changes} change{'s' if num_changes != 1 else ''}")
else:
imgui.text(f"{self.state.current_change_idx + 1}/{num_changes}")
imgui.same_line()
if imgui.button(f"^##prev_{self.state.id}", imgui.ImVec2(20, 20)):
self._prev_change()
if imgui.is_item_hovered():
imgui.set_tooltip("Previous change")
imgui.same_line()
if imgui.button(f"v##next_{self.state.id}", imgui.ImVec2(20, 20)):
self._next_change()
if imgui.is_item_hovered():
imgui.set_tooltip("Next change")
new_collapsed, changed = render_viewer_header(
self.state.collapsed,
render_label,
render_right
)
if changed:
self.state.collapsed = new_collapsed
self.block_state["collapsed"] = self.state.collapsed
# Content area (if expanded)
if not self.state.collapsed:
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4("diff_txt"))
imgui.begin_child("diff_content", imgui.ImVec2(0, 0), child_flags=imgui.ChildFlags_.borders | imgui.ChildFlags_.auto_resize_y, window_flags=imgui.WindowFlags_.no_scrollbar | imgui.WindowFlags_.no_scroll_with_mouse)
if self.state.is_creation:
# Single column for new files
self._render_pane(is_left=False)
else:
# Two columns for side-by-side
imgui.columns(2, "diff_cols", borders=True)
# Left pane (old)
self._render_pane(is_left=True)
imgui.next_column()
# Right pane (new)
self._render_pane(is_left=False)
imgui.columns(1)
imgui.end_child()
imgui.pop_style_color()
imgui.pop_id()
return changed
def _render_pane(self, is_left: bool):
"""Render one side of the diff."""
imgui.push_id("left" if is_left else "right")
for i, hunk in enumerate(self.state.hunks):
imgui.push_id(i)
if hunk.type == "context":
# Render context line by line to keep columns in sync
lines = hunk.text.rstrip('\n').split('\n')
for line in lines:
imgui.text_colored(STYLE.get_imvec4("fg_dim"), line)
elif hunk.type == "skipped":
imgui.push_style_color(imgui.Col_.text, STYLE.get_imvec4("fg_dim"))
if imgui.selectable(f"{hunk.text.rstrip()}##skip_{i}", False)[0]:
# Expand skipped section
self.state.hunks[i] = DiffHunk(type="context", text=hunk.content)
imgui.pop_style_color()
elif hunk.type == "change":
text = hunk.old if is_left else hunk.new
other_text = hunk.new if is_left else hunk.old
# Get line counts for both sides to sync
lines = text.rstrip('\n').split('\n') if text else []
other_lines = other_text.rstrip('\n').split('\n') if other_text else []
max_lines = max(len(lines), len(other_lines), 1)
# Pad to match line count
while len(lines) < max_lines:
lines.append("")
draw_list = imgui.get_window_draw_list()
line_height = imgui.get_text_line_height()
bg_key = "diff_del" if is_left else "diff_add"
for line in lines:
pos = imgui.get_cursor_screen_pos()
draw_list.add_rect_filled(
imgui.ImVec2(pos.x - 2, pos.y),
imgui.ImVec2(pos.x + imgui.get_content_region_avail().x, pos.y + line_height),
STYLE.get_u32(bg_key)
)
imgui.text(line if line else " ")
imgui.pop_id()
imgui.pop_id()
def _calc_content_height(self) -> float:
"""Calculate appropriate content height."""
if self._cached_height is not None:
return self._cached_height
line_count = 0
for hunk in self.state.hunks:
if hunk.type == "context":
line_count += hunk.text.count('\n') + 1
elif hunk.type == "skipped":
line_count += 1
elif hunk.type == "change":
line_count += max(hunk.old.count('\n'), hunk.new.count('\n')) + 1
self._cached_height = line_count * imgui.get_text_line_height() + 20
return self._cached_height
def _prev_change(self):
"""Navigate to previous change."""
if not self.state.change_indices:
return
self.state.current_change_idx = (self.state.current_change_idx - 1) % len(self.state.change_indices)
def _next_change(self):
"""Navigate to next change."""
if not self.state.change_indices:
return
self.state.current_change_idx = (self.state.current_change_idx + 1) % len(self.state.change_indices)
@dataclass
class PlanViewerState:
"""State for a PlanViewer widget."""
title: str = "Unknown Plan"
prompt: str = ""
collapsed: bool = True
id: int = 0
incomplete: bool = False
class PlanViewer:
"""Widget to display an implementation plan item."""
def __init__(self, content: str, block_state: dict, viewer_id: int, incomplete: bool = False):
self.state = PlanViewerState(
title="Unknown Plan",
prompt="",
collapsed=block_state.get("collapsed", True),
id=viewer_id,
incomplete=incomplete
)
self.block_state = block_state
self._parse_content(content)
def _parse_content(self, content: str):
"""Parse the plan content into title and prompt."""
lines = content.split('\n')
title = "Untitled"
prompt_lines = []
mode = "header"
for line in lines:
if line.startswith("Title:"):
title = line[6:].strip()
mode = "prompt_search"
elif line.startswith("Prompt:") and (mode == "prompt_search" or mode == "header"):
prompt_content = line[7:].strip()
if prompt_content:
prompt_lines.append(prompt_content)
mode = "prompt"
elif mode == "prompt":
prompt_lines.append(line)
self.state.title = title
self.state.prompt = "\n".join(prompt_lines).strip()
def update_content(self, new_content: str, incomplete: bool = False):
"""Update the plan content."""
self.state.incomplete = incomplete
self._parse_content(new_content)
def render(self):
"""Render the plan viewer."""
imgui.push_id(f"plan_{self.state.id}")
def render_label():
# Draw "PLAN" badge
imgui.text_colored(STYLE.get_imvec4("btn_run"), "[PLAN]")
imgui.same_line()
imgui.text(self.state.title)
if self.state.incomplete:
imgui.same_line()
render_loading_spinner("")
new_collapsed, changed = render_viewer_header(self.state.collapsed, render_label)
if changed:
self.state.collapsed = new_collapsed
self.block_state["collapsed"] = self.state.collapsed
# Content area
if not self.state.collapsed:
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4("bg_cont"))
imgui.begin_child("plan_content", imgui.ImVec2(0, 0), child_flags=imgui.ChildFlags_.borders | imgui.ChildFlags_.auto_resize_y, window_flags=imgui.WindowFlags_.no_scrollbar | imgui.WindowFlags_.no_scroll_with_mouse)
imgui.begin_group()
imgui.push_text_wrap_pos(0.0)
imgui_md.render(self.state.prompt)
imgui.pop_text_wrap_pos()
imgui.end_group()
imgui.end_child()
imgui.pop_style_color()
imgui.pop_id()
@dataclass
class ChatMessage:
"""Represents a single chat message."""
role: str # "user", "assistant", "system", "error"
content: str = ""
backup_id: str | None = None
diff_viewers: dict = field(default_factory=dict)
block_states: dict = field(default_factory=dict)
plan_viewers: dict = field(default_factory=dict)
plan_states: dict = field(default_factory=dict)
anchors: list = field(default_factory=list)
error_data: tuple[str, str] | None = None # (error_summary, raw_content)
class ChatBubble:
"""Renders a chat message bubble with markdown and embedded diffs."""
def __init__(self, role: str, message_id: int = 0):
self.message = ChatMessage(role=role)
self.message_id = message_id
self.pre_viewers: list[Any] = []
self._line_buffer = ""
self._in_code_block = False
self._current_block_content: list[str] = []
self._current_block_counter = 0
self._in_plan_block = False
self._current_plan_content: list[str] = []
self._current_plan_counter = 0
self._show_raw = False
self._filename_candidate = None
self._current_block_info = None
self._cached_segments = None
self._content_dirty = True
@property
def role(self) -> str:
return self.message.role
@property
def content(self) -> str:
return self.message.content
@property
def anchors(self) -> list:
return self.message.anchors
@property
def diff_viewers(self) -> dict:
return self.message.diff_viewers
def update(self, text: str):
"""Stream text into the bubble."""
self.message.content += text
self._content_dirty = True
def flush(self):
"""Flush any remaining buffered content (No-op with new parser)."""
self._content_dirty = True
def set_error_details(self, summary: str, raw_content: str):
"""Attach error details to this bubble."""
self.message.error_data = (summary, raw_content)
def render(self, is_loading: bool = False) -> str | None:
"""Render the chat bubble. Returns action string ('debug', 'revert') or None."""
action = None
if self.message.role == "tool":
# Specialized rendering for tool/agent output
raw_txt = self.message.content.strip()
summary = raw_txt.replace('\n', ' ')
if len(summary) > 80:
summary = summary[:77] + "..."
if not summary:
summary = "Agent Activity"
imgui.push_style_color(imgui.Col_.header, STYLE.get_imvec4("bg_cont"))
is_open = imgui.collapsing_header(f"{summary}##{self.message_id}")
imgui.pop_style_color()
if is_open:
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4("code_bg"))
imgui.begin_child(f"tool_{self.message_id}", imgui.ImVec2(0, 0), child_flags=imgui.ChildFlags_.auto_resize_y | imgui.ChildFlags_.borders, window_flags=imgui.WindowFlags_.no_scrollbar | imgui.WindowFlags_.no_scroll_with_mouse)
imgui.push_style_color(imgui.Col_.text, STYLE.get_imvec4("fg_dim"))
if raw_txt:
imgui.text_unformatted(raw_txt)
else:
imgui.text_unformatted("(No output)")
imgui.pop_style_color()
imgui.end_child()
imgui.pop_style_color()
return None
# Background color based on role
bg_colors = {
"user": "msg_u",
"assistant": "msg_a",
"system": "msg_a",
"error": "msg_e"
}
bg_key = bg_colors.get(self.message.role, "msg_a")
if self.message.role == "system" and "Validation Passed" in self.message.content:
bg_key = "msg_s"
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4(bg_key))
imgui.begin_child(
f"bubble_{self.message_id}",
imgui.ImVec2(0, 0),
child_flags=imgui.ChildFlags_.auto_resize_y | imgui.ChildFlags_.borders
)
# Header
header = self._get_header_text()
imgui.text_colored(STYLE.get_imvec4("fg"), header)
# Buttons on the right
imgui.same_line()
# Calculate widths
md_label = "Markdown" if not self._show_raw else "Raw"
md_w = imgui.calc_text_size(md_label).x + 20
revert_label = "<<"
revert_w = imgui.calc_text_size(revert_label).x + 20
undo_label = "Undo"
undo_w = imgui.calc_text_size(undo_label).x + 20
spacing = 8
total_btn_w = md_w
show_revert = (self.message.role != "error")
show_undo = show_revert and self.message.backup_id
if show_revert:
total_btn_w += revert_w + spacing
if show_undo:
total_btn_w += undo_w + spacing
avail_w = imgui.get_content_region_avail().x
current_x = imgui.get_cursor_pos_x()
if avail_w > total_btn_w:
imgui.set_cursor_pos_x(current_x + avail_w - total_btn_w)
if show_undo:
imgui.push_style_color(imgui.Col_.button, STYLE.get_imvec4("btn_small"))
if imgui.small_button(f"{undo_label}##undo_{self.message_id}"):
imgui.open_popup(f"ConfirmUndo_{self.message_id}")
imgui.pop_style_color()
if imgui.is_item_hovered():
imgui.set_tooltip(f"Rollback files to state before this step (Backup: {self.message.backup_id})")
if imgui.begin_popup_modal(f"ConfirmUndo_{self.message_id}", None, imgui.WindowFlags_.always_auto_resize)[0]:
imgui.text("Rollback files from this point?")
imgui.text_colored(STYLE.get_imvec4("btn_cncl"), "This will undo changes and revert chat history.")
imgui.separator()
if imgui.button("Yes, Undo", imgui.ImVec2(120, 0)):
action = "undo"
imgui.close_current_popup()
imgui.same_line()
if imgui.button("Cancel", imgui.ImVec2(120, 0)):
imgui.close_current_popup()
imgui.end_popup()
imgui.same_line(0, spacing)
if show_revert:
imgui.push_style_color(imgui.Col_.button, STYLE.get_imvec4("btn_small"))
popup_id = f"Confirm Revert?###ConfirmRevert_{self.message_id}"
if imgui.small_button(f"{revert_label}##rev_{self.message_id}"):
imgui.open_popup(popup_id)
imgui.pop_style_color()
if imgui.is_item_hovered():
imgui.set_tooltip("Revert session to this point (undoing subsequent messages)\nRight-click to fork")
if imgui.begin_popup_context_item(f"ctx_rev_{self.message_id}"):
if imgui.menu_item("Fork in new tab", "", False)[0]:
action = "fork"
imgui.end_popup()
imgui.same_line(0, spacing)
center = imgui.get_main_viewport().get_center()
imgui.set_next_window_pos(center, imgui.Cond_.appearing, imgui.ImVec2(0.5, 0.5))
if imgui.begin_popup_modal(popup_id, None, imgui.WindowFlags_.always_auto_resize)[0]:
imgui.text("Are you sure you want to revert the session to this message?")
imgui.text_colored(STYLE.get_imvec4("btn_cncl"), "All subsequent messages and history will be lost.")
imgui.separator()
if imgui.button("Yes, Revert", imgui.ImVec2(120, 0)):
action = "revert"
imgui.close_current_popup()
imgui.same_line()
if imgui.button("Cancel", imgui.ImVec2(120, 0)):
imgui.close_current_popup()
imgui.end_popup()
imgui.push_style_color(imgui.Col_.button, STYLE.get_imvec4("btn_small"))
if imgui.small_button(f"{md_label}##{self.message_id}"):
self._show_raw = not self._show_raw
imgui.pop_style_color()
imgui.separator()
# Content - render markdown and embedded diffs
if self._show_raw:
# Use InputTextMultiline to allow selection and copying
avail_width = imgui.get_content_region_avail().x
display_content = self.message.content.rstrip()
# Calculate height needed for content including wrapping
# Reduce wrap width slightly to account for InputText internal padding
text_size = imgui.calc_text_size(display_content, wrap_width=avail_width - 25.0)
style = imgui.get_style()
height = text_size.y + style.frame_padding.y * 4 + 20.0
# Render with transparent background to preserve bubble styling
imgui.push_style_color(imgui.Col_.frame_bg, imgui.ImVec4(0, 0, 0, 0))
imgui.push_style_var(imgui.StyleVar_.frame_border_size, 0.0)
imgui.input_text_multiline(
f"##raw_{self.message_id}",
display_content,
imgui.ImVec2(-1, height),
imgui.InputTextFlags_.read_only | imgui.InputTextFlags_.word_wrap
)
imgui.pop_style_var()
imgui.pop_style_color()
if imgui.begin_popup_context_item(f"ctx_raw_{self.message_id}"):
if imgui.menu_item("Copy All", "", False)[0]:
imgui.set_clipboard_text(self.message.content)
imgui.end_popup()
else:
for v in self.pre_viewers:
v.render()
imgui.spacing()
self._render_content()
# Render Loading Spinner
if is_loading:
self._render_loading_indicator()
# Render error details button if data is present
if self.message.error_data:
imgui.spacing()
imgui.separator()
imgui.push_style_color(imgui.Col_.button, STYLE.get_imvec4("btn_war"))
if imgui.button(f"View Debug Details##err_{self.message_id}"):
action = "debug"
imgui.pop_style_color()
imgui.same_line()
imgui.text_colored(STYLE.get_imvec4("fg_dim"), "(Opens new tab)")
imgui.end_child()
imgui.pop_style_color()
return action
def _render_loading_indicator(self):
"""Render a spinner indicator at the bottom of the bubble."""
imgui.spacing()
imgui.separator()
imgui.spacing()
render_loading_spinner("Generating...", radius=7.0)
def _get_header_text(self) -> str:
"""Get the header text for the bubble."""
headers = {
"user": "User",
"assistant": "Assistant",
"system": "System",
"error": "System Alert"
}
return headers.get(self.message.role, self.message.role.capitalize())
def _render_content(self):
"""Render the message content with markdown."""
# Parse content into segments (text vs diff blocks)
if self._content_dirty or self._cached_segments is None:
self._cached_segments = self._parse_content_segments()
self._content_dirty = False
segments = self._cached_segments
for idx, segment in enumerate(segments):
if segment["type"] == "text":
# Render markdown text with context menu
imgui.begin_group()
# Force hard line breaks for single newlines
text_content = segment["content"].replace("\n", " \n")
# Tables render weird, but we don't have any control over the internals of imgui_md afaik
imgui_md.render(text_content)
imgui.end_group()
if imgui.begin_popup_context_item(f"ctx_txt_{self.message_id}_{idx}"):
if imgui.menu_item("Copy text", "", False)[0]:
imgui.set_clipboard_text(segment["content"])
imgui.end_popup()
elif segment["type"] == "diff":
# Render diff viewer
dv_id = segment["dv_id"]
if dv_id in self.message.diff_viewers:
self.message.diff_viewers[dv_id].render()
elif segment["type"] == "plan":
# Render plan viewer
pv_id = segment["pv_id"]
if pv_id in self.message.plan_viewers:
self.message.plan_viewers[pv_id].render()
elif segment["type"] == "code":
# Render code block without diff
imgui.push_style_color(imgui.Col_.child_bg, STYLE.get_imvec4("code_bg"))
imgui.begin_child(f"code_{segment['id']}", imgui.ImVec2(0, 0),
child_flags=imgui.ChildFlags_.auto_resize_y, window_flags=imgui.WindowFlags_.no_scrollbar | imgui.WindowFlags_.no_scroll_with_mouse)
imgui.push_style_color(imgui.Col_.text, STYLE.get_imvec4("code_fg"))
imgui.text(segment["content"])
imgui.pop_style_color()
imgui.end_child()
imgui.pop_style_color()
if imgui.begin_popup_context_item(f"ctx_code_{self.message_id}_{segment['id']}"):
if imgui.menu_item("Copy code", "", False)[0]:
imgui.set_clipboard_text(segment["content"])
imgui.end_popup()
def _parse_content_segments(self) -> list:
"""Parse content into renderable segments using regex."""
segments: list[dict[str, Any]] = []
text = self.message.content
pos = 0
dv_idx = 0
pv_idx = 0
code_idx = 0
# We need to preserve viewers across potential re-parses during streaming
# but also handle structure changes. We rely on index stability.
while pos < len(text):
m_plan = plan_block_pattern.search(text, pos)
m_diff = code_block_pattern.search(text, pos)
m_code = generic_code_pattern.search(text, pos)
candidates = []
if m_plan: candidates.append((m_plan.start(), m_plan.end(), "plan", m_plan))
if m_diff: candidates.append((m_diff.start(), m_diff.end(), "diff", m_diff))
if m_code: candidates.append((m_code.start(), m_code.end(), "code", m_code))
candidates.sort(key=lambda x: x[0])
if not candidates:
remaining = text[pos:]
if remaining:
# Check for incomplete blocks being streamed
m_inc_plan = incomplete_plan_pattern.search(remaining)
if m_inc_plan:
if m_inc_plan.start() > 0:
segments.append({"type": "text", "content": remaining[:m_inc_plan.start()]})
if pv_idx not in self.message.plan_states:
self.message.plan_states[pv_idx] = {"collapsed": True}
title = m_inc_plan.group(1) or "..."
prompt = m_inc_plan.group(2) or ""
content = f"Title: {title}\nPrompt: {prompt}"
if pv_idx not in self.message.plan_viewers:
self.message.plan_viewers[pv_idx] = PlanViewer(content, self.message.plan_states[pv_idx], pv_idx, incomplete=True)
else:
self.message.plan_viewers[pv_idx].update_content(content, incomplete=True)
segments.append({"type": "plan", "pv_id": pv_idx})
break
m_inc_diff = incomplete_diff_pattern.search(remaining)
if m_inc_diff:
if m_inc_diff.start() > 0:
segments.append({"type": "text", "content": remaining[:m_inc_diff.start()]})
if dv_idx not in self.message.block_states:
self.message.block_states[dv_idx] = {"collapsed": True, "reverted": set()}
filename = m_inc_diff.group(1)
lang = m_inc_diff.group(2)
body = m_inc_diff.group(3)
if filename: filename = filename.strip()
if lang: lang = lang.strip()