-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
2558 lines (2277 loc) · 93.4 KB
/
MainWindow.xaml.cs
File metadata and controls
2558 lines (2277 loc) · 93.4 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
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using JustCode.Services;
using JustCode.ViewModels;
using Microsoft.Win32;
namespace JustCode;
public partial class MainWindow : Window
{
/// Window-scoped RoutedCommand for Ctrl+Shift+K. Wired in the Window
/// constructor to invoke ClearQueue on the active conversation.
public static readonly RoutedCommand ClearQueueCommand = new("ClearQueue", typeof(MainWindow));
private readonly MainViewModel _vm;
private ProjectViewModel? _subscribedProject;
private ConversationViewModel? _subscribedConversation;
private System.Windows.Threading.DispatcherTimer? _wordWrapTimer;
private TerminalHost? _terminalHost;
private bool _terminalHostReady;
private ProjectViewModel? _terminalAttachedProject;
// @-mention state
private readonly Dictionary<string, FileMentionIndex> _mentionIndexes = new(StringComparer.OrdinalIgnoreCase);
private int _mentionTokenStart = -1; // position of '@' in the PromptBox when popup is active
private static readonly Regex MentionRef = new(
@"@(?:""([^""]+)""|([^\s""]+))", RegexOptions.Compiled);
public MainWindow()
{
InitializeComponent();
_vm = new MainViewModel();
DataContext = _vm;
CommandBindings.Add(new CommandBinding(
ClearQueueCommand,
(_, _) => _vm.SelectedProject?.SelectedConversation?.ClearQueue(),
(_, e) =>
{
e.CanExecute = _vm.SelectedProject?.SelectedConversation?.HasQueuedMessages == true;
e.Handled = true;
}));
RestoreWindowBounds();
_vm.PropertyChanged += OnVmPropertyChanged;
_vm.ProjectAdded += (_, p) => HookProject(p);
_vm.ProjectRemoved += (_, p) => UnhookProject(p);
// SizeChanged fires on every animation frame during a resize. Throttle
// to a DispatcherTimer so we only recompute PageWidth once per burst
// — otherwise FlowDocument re-layouts thrash the UI thread.
HookConsoleBoxSizeChanged(ConsoleAllBox);
HookConsoleBoxSizeChanged(ConsoleConversationBox);
HookConsoleBoxSizeChanged(ConsoleToolsBox);
Loaded += (_, _) =>
{
// Kick icon warmup off the UI thread before any tree renders —
// SharpVectors class init is otherwise paid on the first render.
FileIconService.Prewarm();
_vm.InitializeTabs(Directory.GetCurrentDirectory());
foreach (var p in _vm.Projects) HookProject(p);
SubscribeToSelectedProject();
SubscribeToSelectedConversation();
AttachSelectedConversationDocuments();
ApplyWordWrap();
AttachMentionHighlightAdorner();
UpdateActivityBarStyles();
_ = InitializeTerminalHostAsync();
};
Closing += (_, _) => _vm.SaveWindowBounds(Left, Top, Width, Height);
Closed += (_, _) =>
{
try { _terminalHost?.Dispose(); } catch { }
_vm.Shutdown();
};
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
TryEnableImmersiveDarkMode();
TryPaintInitialDarkBackground();
}
// ---- hooking projects and their conversations ----
private void HookProject(ProjectViewModel p)
{
p.ConversationAdded -= OnConversationAdded;
p.ConversationAdded += OnConversationAdded;
p.ConversationRemoved -= OnConversationRemoved;
p.ConversationRemoved += OnConversationRemoved;
foreach (var c in p.Conversations) HookConversation(c);
}
private void UnhookProject(ProjectViewModel p)
{
p.ConversationAdded -= OnConversationAdded;
p.ConversationRemoved -= OnConversationRemoved;
foreach (var c in p.Conversations) UnhookConversation(c);
}
private void OnConversationAdded(object? sender, ConversationViewModel c) => HookConversation(c);
private void OnConversationRemoved(object? sender, ConversationViewModel c) => UnhookConversation(c);
private void HookConversation(ConversationViewModel c)
{
c.ConsoleAppend -= OnConversationConsoleAppend;
c.ConsoleAppend += OnConversationConsoleAppend;
// Replay persisted console history once, on first hook, through the
// styling pipeline so it looks like the rest of the stream.
var history = c.PopConsoleHistory();
if (!string.IsNullOrEmpty(history))
OnConversationConsoleAppend(c, history);
}
private void UnhookConversation(ConversationViewModel c)
{
c.ConsoleAppend -= OnConversationConsoleAppend;
if (_consoleFlushTimers.TryGetValue(c, out var timer))
{
timer.Stop();
_consoleFlushTimers.Remove(c);
}
_consoleBuffers.Remove(c);
}
/// Per-conversation buffer of pending chunks. Rapidly-streaming models
/// (Claude, Codex, pi) can emit hundreds of deltas per second. Appending
/// each to the FlowDocument separately forces a re-layout per delta;
/// coalescing into a single ~60 Hz flush cuts render time dramatically.
private readonly Dictionary<ConversationViewModel, System.Text.StringBuilder> _consoleBuffers = new();
private readonly Dictionary<ConversationViewModel, System.Windows.Threading.DispatcherTimer> _consoleFlushTimers = new();
private const int ConsoleFlushIntervalMs = 16;
private void OnConversationConsoleAppend(object? sender, string chunk)
{
if (sender is not ConversationViewModel c || string.IsNullOrEmpty(chunk)) return;
if (!_consoleBuffers.TryGetValue(c, out var sb))
{
sb = new System.Text.StringBuilder();
_consoleBuffers[c] = sb;
}
sb.Append(chunk);
if (!_consoleFlushTimers.TryGetValue(c, out var timer))
{
timer = new System.Windows.Threading.DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(ConsoleFlushIntervalMs),
};
timer.Tick += (_, _) => FlushConsoleBuffer(c);
_consoleFlushTimers[c] = timer;
}
if (!timer.IsEnabled) timer.Start();
}
private void FlushConsoleBuffer(ConversationViewModel c)
{
if (_consoleFlushTimers.TryGetValue(c, out var timer)) timer.Stop();
if (!_consoleBuffers.TryGetValue(c, out var sb) || sb.Length == 0) return;
var pending = sb.ToString();
sb.Clear();
AppendStyled(c, pending);
if (ReferenceEquals(c, _vm.SelectedProject?.SelectedConversation)
&& _vm.AutoScrollConsole)
{
GetActiveConsoleBox()?.ScrollToEnd();
}
}
// ---- selection changes ----
private void OnVmPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MainViewModel.SelectedProject))
{
CloseInlineGitDiff();
SubscribeToSelectedProject();
SubscribeToSelectedConversation();
AttachSelectedConversationDocuments();
ApplyWordWrap();
QueueScrollTasks();
UpdateActivityBarStyles();
}
else if (e.PropertyName == nameof(MainViewModel.WordWrapConsole))
{
ApplyWordWrap();
}
else if (e.PropertyName == nameof(MainViewModel.AutoScrollTasks))
{
QueueScrollTasks();
}
}
private void SubscribeToSelectedProject()
{
if (_subscribedProject != null)
_subscribedProject.PropertyChanged -= OnProjectPropertyChanged;
_subscribedProject = _vm.SelectedProject;
if (_subscribedProject != null)
_subscribedProject.PropertyChanged += OnProjectPropertyChanged;
AttachActiveProjectTerminal();
}
private void OnProjectPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(ProjectViewModel.SelectedConversation))
{
CloseInlineGitDiff();
SubscribeToSelectedConversation();
AttachSelectedConversationDocuments();
ApplyWordWrap();
QueueScrollTasks();
CloseMentionPopup();
HideMentionTooltip();
}
}
private void SubscribeToSelectedConversation()
{
if (_subscribedConversation != null)
_subscribedConversation.PropertyChanged -= OnSelectedConversationPropertyChanged;
_subscribedConversation = _vm.SelectedProject?.SelectedConversation;
if (_subscribedConversation != null)
_subscribedConversation.PropertyChanged += OnSelectedConversationPropertyChanged;
}
private void OnSelectedConversationPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (!ReferenceEquals(sender, _subscribedConversation)) return;
if (e.PropertyName is nameof(ConversationViewModel.TasksText)
or nameof(ConversationViewModel.TaskPreviewMarkdown))
{
QueueScrollTasks();
}
}
private void AttachSelectedConversationDocuments()
{
var c = _vm.SelectedProject?.SelectedConversation;
if (c == null)
{
ConsoleAllBox.Document = new FlowDocument();
ConsoleConversationBox.Document = new FlowDocument();
ConsoleToolsBox.Document = new FlowDocument();
return;
}
if (!ReferenceEquals(ConsoleAllBox.Document, c.ConsoleDocument))
ConsoleAllBox.Document = c.ConsoleDocument;
if (!ReferenceEquals(ConsoleConversationBox.Document, c.ConversationConsoleDocument))
ConsoleConversationBox.Document = c.ConversationConsoleDocument;
if (!ReferenceEquals(ConsoleToolsBox.Document, c.ToolConsoleDocument))
ConsoleToolsBox.Document = c.ToolConsoleDocument;
}
private void QueueScrollTasks()
{
Dispatcher.BeginInvoke(new Action(MaybeScrollTasks),
System.Windows.Threading.DispatcherPriority.Background);
}
private void MaybeScrollTasks()
{
if (!_vm.AutoScrollTasks) return;
if (TasksTabs == null) return;
if (TasksTabs.SelectedIndex == 0)
{
TasksBox?.ScrollToEnd();
return;
}
var fdsv = FindVisualChild<FlowDocumentScrollViewer>(TasksMarkdown);
if (fdsv != null)
{
fdsv.ApplyTemplate();
var sv = FindVisualChild<ScrollViewer>(fdsv);
if (sv != null) { sv.ScrollToEnd(); return; }
}
var direct = FindVisualChild<ScrollViewer>(TasksMarkdown);
direct?.ScrollToEnd();
}
private void ApplyWordWrap()
{
ApplyWordWrap(ConsoleAllBox);
ApplyWordWrap(ConsoleConversationBox);
ApplyWordWrap(ConsoleToolsBox);
}
private void HookConsoleBoxSizeChanged(RichTextBox box)
{
box.SizeChanged += (_, _) =>
{
if (_wordWrapTimer == null)
{
_wordWrapTimer = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(60) };
_wordWrapTimer.Tick += (_, _) => { _wordWrapTimer!.Stop(); ApplyWordWrap(); };
}
_wordWrapTimer.Stop();
_wordWrapTimer.Start();
};
}
private void ApplyWordWrap(RichTextBox box)
{
if (box?.Document == null) return;
if (_vm.WordWrapConsole)
{
var w = Math.Max(100, box.ViewportWidth - 8);
box.Document.PageWidth = w;
box.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
box.Document.PageWidth = 6000;
box.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
}
}
private RichTextBox? GetActiveConsoleBox()
=> ConsoleTabs?.SelectedIndex switch
{
1 => ConsoleConversationBox,
2 => ConsoleToolsBox,
_ => ConsoleAllBox,
};
private void ConsoleTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!IsLoaded || sender is not TabControl) return;
ApplyWordWrap();
if (_vm.AutoScrollConsole)
GetActiveConsoleBox()?.ScrollToEnd();
if (ConsoleTabs.SelectedIndex == 3)
{
// First time the user opens the Terminal tab in this project,
// auto-spawn a session so they land in a usable shell instead of
// the empty-state screen.
var panel = ActiveTerminalPanel;
if (panel != null && !panel.HasAnySessions && _terminalHostReady)
panel.AddSession();
_terminalHost?.FocusActive();
}
}
// ---- terminal panel (xterm.js + ConPTY) ----
private async Task InitializeTerminalHostAsync()
{
if (_terminalHost != null) return;
_terminalHost = new TerminalHost(TerminalWebView);
try
{
await _terminalHost.InitializeAsync();
_terminalHostReady = true;
AttachActiveProjectTerminal();
}
catch
{
// WebView2 runtime not installed — fail quiet; user will see an
// empty Terminal tab. We could surface a message here in a follow-up.
}
}
private void AttachActiveProjectTerminal()
{
if (!_terminalHostReady || _terminalHost == null) return;
var project = _vm.SelectedProject;
if (ReferenceEquals(project, _terminalAttachedProject)) return;
_terminalAttachedProject = project;
_terminalHost.AttachPanel(project?.TerminalPanel);
}
private TerminalPanelViewModel? ActiveTerminalPanel =>
_vm.SelectedProject?.TerminalPanel;
private void TerminalAddSession_Click(object sender, RoutedEventArgs e)
{
ActiveTerminalPanel?.AddSession();
_terminalHost?.FocusActive();
}
private void TerminalPickShell_Click(object sender, RoutedEventArgs e)
{
if (sender is not Button btn) return;
var panel = ActiveTerminalPanel;
if (panel == null) return;
var menu = new ContextMenu
{
PlacementTarget = btn,
Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom,
};
var shells = ShellDetector.Available;
if (shells.Count == 0)
{
menu.Items.Add(new MenuItem { Header = "No shells detected", IsEnabled = false });
}
else
{
var defaultId = _vm.DefaultShellId;
foreach (var shell in shells)
{
var item = new MenuItem { Header = shell.Label, Tag = shell.Id };
item.Click += (_, _) => panel.AddSession(shell.Id);
menu.Items.Add(item);
}
menu.Items.Add(new Separator());
var header = new MenuItem
{
Header = "Default shell",
IsEnabled = false,
FontWeight = FontWeights.SemiBold,
};
menu.Items.Add(header);
foreach (var shell in shells)
{
var item = new MenuItem
{
Header = shell.Label,
IsCheckable = true,
IsChecked = string.Equals(defaultId, shell.Id, StringComparison.OrdinalIgnoreCase)
|| (string.IsNullOrEmpty(defaultId) && ReferenceEquals(shell, shells[0])),
StaysOpenOnClick = true,
};
item.Click += (_, _) => _vm.DefaultShellId = shell.Id;
menu.Items.Add(item);
}
}
menu.IsOpen = true;
}
private void TerminalClear_Click(object sender, RoutedEventArgs e)
=> _terminalHost?.ClearActive();
private void TerminalCloseSession_Click(object sender, RoutedEventArgs e)
{
var panel = ActiveTerminalPanel;
if (panel?.ActiveSession != null) panel.CloseSession(panel.ActiveSession);
}
private void TerminalCloseTab_Click(object sender, RoutedEventArgs e)
{
if (sender is Button { Tag: TerminalSessionViewModel s })
ActiveTerminalPanel?.CloseSession(s);
e.Handled = true;
}
private void TerminalTab_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (sender is FrameworkElement fe && fe.Tag is TerminalSessionViewModel s)
{
var panel = ActiveTerminalPanel;
if (panel != null) panel.ActiveSession = s;
_terminalHost?.FocusActive();
}
}
private void TerminalTab_Rename_RightClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (sender is FrameworkElement fe && fe.Tag is TerminalSessionViewModel s)
{
s.IsRenaming = true;
e.Handled = true;
}
}
private void TerminalTab_TitleEdit_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (sender is not TextBox tb) return;
if (e.Key == System.Windows.Input.Key.Enter || e.Key == System.Windows.Input.Key.Escape)
{
if (tb.Tag is TerminalSessionViewModel s) s.IsRenaming = false;
e.Handled = true;
}
}
private void TerminalTab_TitleEdit_LostFocus(object sender, RoutedEventArgs e)
{
if (sender is TextBox tb && tb.Tag is TerminalSessionViewModel s)
s.IsRenaming = false;
}
private void RestoreWindowBounds()
{
var s = _vm.Settings;
if (s.WindowWidth is > 200 && s.WindowHeight is > 200)
{
Width = s.WindowWidth.Value;
Height = s.WindowHeight.Value;
}
if (s.WindowLeft is not null && s.WindowTop is not null)
{
Left = s.WindowLeft.Value;
Top = s.WindowTop.Value;
WindowStartupLocation = WindowStartupLocation.Manual;
}
}
private static bool IsPlainText(string s)
{
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (char.IsLetterOrDigit(c) || c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\'' || c == ',' || c == '.' || c == ';') continue;
if (_stylingTriggerChars.Contains(c)) return false;
// Anything non-ASCII (emoji/arrows/box drawing) is treated as a
// potential match — styling rules DO use 🧠 ⎿ ▸ etc. for block
// markers, so we can't short-circuit when those appear.
if (c > 127) return false;
}
return true;
}
private void AppendStyled(ConversationViewModel c, string chunk)
{
int allLines = 0, conversationLines = 0, toolLines = 0;
foreach (var line in SplitConsoleLines(ApplyCollapse(chunk)))
{
var cls = ConsoleLineClassifier.Classify(line);
AppendStyledToParagraph(c.ConsoleParagraph, line);
if (cls.IsCounted) allLines++;
if (cls.IsTool)
{
AppendStyledToParagraph(c.ToolConsoleParagraph, line);
if (cls.IsCounted) toolLines++;
}
else
{
var decision = c.RouteConversationLine(line);
if (decision == ConversationViewModel.ConversationLineDecision.AppendBlankThenLine)
AppendStyledToParagraph(c.ConversationConsoleParagraph, "\n");
if (decision != ConversationViewModel.ConversationLineDecision.Skip)
{
AppendStyledToParagraph(c.ConversationConsoleParagraph, line);
if (cls.IsCounted) conversationLines++;
}
}
}
c.RecordConsoleLineCounts(allLines, conversationLines, toolLines);
}
private static IEnumerable<string> SplitConsoleLines(string chunk)
{
int i = 0;
while (i < chunk.Length)
{
var nl = chunk.IndexOf('\n', i);
if (nl < 0)
{
yield return chunk.Substring(i);
yield break;
}
yield return chunk.Substring(i, nl - i + 1);
i = nl + 1;
}
}
private void AppendStyledToParagraph(Paragraph paragraph, string chunk)
{
var inlines = paragraph.Inlines;
foreach (var (text, rule) in Tokenize(chunk))
{
var run = new Run(text);
if (rule?.ForegroundBrush is not null) run.Foreground = rule.ForegroundBrush;
if (rule?.BackgroundBrush is not null) run.Background = rule.BackgroundBrush;
if (rule?.WeightValue is { } w) run.FontWeight = w;
if (rule?.StyleValue is { } fs) run.FontStyle = fs;
if (rule?.Underline == true) run.TextDecorations = TextDecorations.Underline;
inlines.Add(run);
}
FlowDocumentInlineLimiter.Apply(inlines);
}
private string ApplyCollapse(string chunk)
{
if (!_vm.CollapseToolCalls || string.IsNullOrEmpty(chunk)) return chunk;
var sb = new System.Text.StringBuilder(chunk.Length);
int i = 0;
while (i < chunk.Length)
{
var nl = chunk.IndexOf('\n', i);
int segEnd = nl < 0 ? chunk.Length : nl + 1;
var line = chunk.Substring(i, segEnd - i);
i = segEnd;
var cls = ConsoleLineClassifier.Classify(line);
bool hasNewline = line.Length > 0 && line[^1] == '\n';
if (cls.IsToolResult)
{
sb.Append("⎿ …");
if (hasNewline) sb.Append('\n');
}
else if (cls.IsToolHeader)
{
var open = cls.Trimmed.IndexOf('(');
if (open > 0)
sb.Append(cls.Trimmed, 0, open + 1).Append('…').Append(')');
else
sb.Append(cls.Trimmed);
if (hasNewline) sb.Append('\n');
}
else
{
sb.Append(line);
}
}
return sb.ToString();
}
/// ASCII characters that nearly every styling regex depends on. A chunk
/// with only letters/digits/whitespace can't possibly match any rule, so
/// we skip the O(rules × length) regex loop entirely for that common
/// case. Kept to ASCII for cheap scanning — the few Unicode-glyph rules
/// (▸⎿🧠 etc.) always co-occur with ASCII structural chars, so we don't
/// miss anything in practice.
private static readonly System.Collections.Generic.HashSet<char> _stylingTriggerChars = new()
{
'[', ']', '{', '}', '(', ')', '<', '>', '/', '\\', '#', '@',
'=', '!', '"', '*', ':', '|', '-', '+', '?'
};
private IEnumerable<(string text, StylingRule? rule)> Tokenize(string chunk)
{
var rules = _vm.Settings.StylingRules;
if (rules.Count == 0 || string.IsNullOrEmpty(chunk))
{
yield return (chunk, null);
yield break;
}
// Fast path: pure alphanumeric + whitespace text can't match any rule.
// Saves 20-30 regex invocations on every plain-text streaming delta.
if (IsPlainText(chunk))
{
yield return (chunk, null);
yield break;
}
var startIdx = 0;
while (startIdx < chunk.Length)
{
var nl = chunk.IndexOf('\n', startIdx);
int segEnd = nl < 0 ? chunk.Length : nl + 1;
var originalSeg = chunk.Substring(startIdx, segEnd - startIdx);
startIdx = segEnd;
if (originalSeg.Length == 0) break;
var (segment, hard) = ApplyReplacements(originalSeg, rules);
var styleSpans = new List<(int start, int len, StylingRule rule, int idx)>();
for (int i = 0; i < rules.Count; i++)
{
var r = rules[i];
if (r.Replacement != null) continue;
if (r.CompiledRegex is null) continue;
foreach (Match m in r.CompiledRegex.Matches(segment))
{
if (m.Length == 0) continue;
styleSpans.Add((m.Index, m.Length, r, i));
}
}
styleSpans.Sort((a, b) =>
{
if (a.start != b.start) return a.start.CompareTo(b.start);
if (a.len != b.len) return b.len.CompareTo(a.len);
return a.idx.CompareTo(b.idx);
});
var acceptedStyle = new List<(int start, int len, StylingRule rule)>();
int sCursor = 0;
foreach (var s in styleSpans)
{
if (s.start < sCursor) continue;
acceptedStyle.Add((s.start, s.len, s.rule));
sCursor = s.start + s.len;
}
int pos = 0;
int hIdx = 0;
int stIdx = 0;
while (pos < segment.Length)
{
while (hIdx < hard.Count && hard[hIdx].start + hard[hIdx].len <= pos) hIdx++;
while (stIdx < acceptedStyle.Count && acceptedStyle[stIdx].start + acceptedStyle[stIdx].len <= pos) stIdx++;
if (hIdx < hard.Count && hard[hIdx].start == pos)
{
var h = hard[hIdx];
yield return (segment.Substring(h.start, h.len), h.rule);
pos = h.start + h.len;
continue;
}
int hardBoundary = hIdx < hard.Count ? hard[hIdx].start : segment.Length;
if (stIdx < acceptedStyle.Count && acceptedStyle[stIdx].start <= pos)
{
var s = acceptedStyle[stIdx];
int sEnd = Math.Min(s.start + s.len, hardBoundary);
yield return (segment.Substring(pos, sEnd - pos), s.rule);
pos = sEnd;
continue;
}
int nextStyleStart = stIdx < acceptedStyle.Count ? acceptedStyle[stIdx].start : segment.Length;
int end = Math.Min(hardBoundary, nextStyleStart);
if (end <= pos) break;
yield return (segment.Substring(pos, end - pos), null);
pos = end;
}
}
}
private static (string segment, List<(int start, int len, StylingRule rule)> hard)
ApplyReplacements(string seg, IList<StylingRule> rules)
{
var matches = new List<(Match m, StylingRule rule, int idx)>();
for (int i = 0; i < rules.Count; i++)
{
var r = rules[i];
if (r.Replacement == null || r.CompiledRegex == null) continue;
foreach (Match m in r.CompiledRegex.Matches(seg))
{
if (m.Length == 0) continue;
matches.Add((m, r, i));
}
}
if (matches.Count == 0) return (seg, new List<(int, int, StylingRule)>());
matches.Sort((a, b) =>
{
if (a.m.Index != b.m.Index) return a.m.Index.CompareTo(b.m.Index);
if (a.m.Length != b.m.Length) return b.m.Length.CompareTo(a.m.Length);
return a.idx.CompareTo(b.idx);
});
var sb = new System.Text.StringBuilder();
var hard = new List<(int, int, StylingRule)>();
int pos = 0;
int cursor = 0;
foreach (var mm in matches)
{
if (mm.m.Index < cursor) continue;
if (mm.m.Index > pos) sb.Append(seg, pos, mm.m.Index - pos);
var rep = mm.m.Result(mm.rule.Replacement!);
int newStart = sb.Length;
sb.Append(rep);
hard.Add((newStart, rep.Length, mm.rule));
pos = mm.m.Index + mm.m.Length;
cursor = pos;
}
if (pos < seg.Length) sb.Append(seg, pos, seg.Length - pos);
return (sb.ToString(), hard);
}
private void AttachMentionHighlightAdorner()
{
try
{
var layer = System.Windows.Documents.AdornerLayer.GetAdornerLayer(PromptBox);
if (layer == null) return;
// Don't double-add.
var existing = layer.GetAdorners(PromptBox);
if (existing != null && existing.Any(a => a is MentionHighlightAdorner)) return;
layer.Add(new MentionHighlightAdorner(PromptBox));
}
catch { }
}
// ---------- prompt @-mention ----------
private FileMentionIndex? GetIndexForCurrentProject()
{
var dir = _vm.SelectedProject?.WorkingDirectory;
if (string.IsNullOrEmpty(dir)) return null;
if (!_mentionIndexes.TryGetValue(dir, out var idx))
{
idx = new FileMentionIndex(dir);
_mentionIndexes[dir] = idx;
}
return idx;
}
private TextBox? _activeMentionBox;
private bool _suppressMentionUpdate;
private static (int start, int end, string token)? CurrentCaretToken(TextBox box)
{
var text = box.Text ?? "";
var caret = box.CaretIndex;
if (caret < 0 || caret > text.Length) return null;
int start = caret;
while (start > 0 && !char.IsWhiteSpace(text[start - 1])) start--;
int end = caret;
while (end < text.Length && !char.IsWhiteSpace(text[end])) end++;
return (start, end, text.Substring(start, end - start));
}
private void PromptBox_TextChanged(object sender, TextChangedEventArgs e)
=> UpdateMentionPopup(PromptBox);
private void PromptBox_SelectionChanged(object sender, RoutedEventArgs e)
{
UpdateMentionPopup(PromptBox);
AutoSelectMentionIfCaretInside(PromptBox);
}
/// If the caret lands inside an @ref token and nothing is yet selected,
/// select the whole token so it behaves as an atomic chip (type/delete
/// replaces the whole thing rather than editing the hidden full path).
private bool _autoSelecting;
private void AutoSelectMentionIfCaretInside(TextBox box)
{
if (_autoSelecting) return;
if (box.SelectionLength > 0) return;
var text = box.Text ?? "";
if (string.IsNullOrEmpty(text)) return;
var caret = box.CaretIndex;
foreach (Match m in MentionRef.Matches(text))
{
if (caret > m.Index && caret < m.Index + m.Length)
{
_autoSelecting = true;
try
{
box.Select(m.Index, m.Length);
}
finally { _autoSelecting = false; }
break;
}
}
}
private void PromptBox_LostFocus(object sender, RoutedEventArgs e)
{
// Popup's StaysOpen="False" already closes on outside-click;
// this backs it up if focus moves via keyboard.
if (_activeMentionBox == PromptBox && MentionPopup.IsOpen && !MentionList.IsKeyboardFocusWithin)
CloseMentionPopup();
}
private void UpdateMentionPopup(TextBox box)
{
if (_suppressMentionUpdate) return;
var tok = CurrentCaretToken(box);
if (tok is null)
{
if (_activeMentionBox == box) CloseMentionPopup();
return;
}
var (start, _, token) = tok.Value;
// Only trigger when the token starts with '@' AND has at least one
// character after it (codex parity).
if (token.Length < 2 || token[0] != '@')
{
if (_activeMentionBox == box) CloseMentionPopup();
return;
}
var query = token.Substring(1).Trim('"');
var idx = GetIndexForCurrentProject();
if (idx == null)
{
if (_activeMentionBox == box) CloseMentionPopup();
return;
}
var results = idx.Search(query);
if (results.Count == 0)
{
if (_activeMentionBox == box) CloseMentionPopup();
return;
}
MentionList.ItemsSource = results;
if (MentionList.SelectedIndex < 0) MentionList.SelectedIndex = 0;
_mentionTokenStart = start;
_activeMentionBox = box;
MentionPopup.PlacementTarget = box;
PositionMentionPopup();
MentionPopup.IsOpen = true;
}
private void PositionMentionPopup()
{
var box = _activeMentionBox;
if (box == null) return;
try
{
var rect = box.GetRectFromCharacterIndex(_mentionTokenStart);
if (rect.IsEmpty) return;
MentionPopup.HorizontalOffset = rect.X;
MentionPopup.VerticalOffset = rect.Y + rect.Height + 2;
}
catch { }
}
private void CloseMentionPopup()
{
if (MentionPopup.IsOpen) MentionPopup.IsOpen = false;
_mentionTokenStart = -1;
_activeMentionBox = null;
}
private void AcceptMentionSelection()
{
var box = _activeMentionBox;
if (box == null) return;
if (!MentionPopup.IsOpen) return;
if (MentionList.SelectedItem is not string fullPath) return;
if (_mentionTokenStart < 0) return;
var conv = _vm.SelectedProject?.SelectedConversation;
if (conv == null) return;
// Register the full path and use a short label in the visible prompt.
var shortLabel = conv.RegisterMention(fullPath);
var text = box.Text ?? "";
int start = _mentionTokenStart;
int end = start;
while (end < text.Length && !char.IsWhiteSpace(text[end])) end++;
var insert = "@" + FileMentionIndex.QuoteIfNeeded(shortLabel) + " ";
var newText = text.Substring(0, start) + insert + text.Substring(end);
var newCaret = start + insert.Length;
_suppressMentionUpdate = true;
try
{
box.Text = newText;
box.CaretIndex = newCaret;
}
finally { _suppressMentionUpdate = false; }
box.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
CloseMentionPopup();
}
private void PromptBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
// Ctrl+Enter submits regardless of popup state — always takes
// precedence so a pending @-mention popup doesn't swallow it.
if (e.Key == System.Windows.Input.Key.Enter &&
(System.Windows.Input.Keyboard.Modifiers & System.Windows.Input.ModifierKeys.Control)
== System.Windows.Input.ModifierKeys.Control)
{
e.Handled = true;
CloseMentionPopup();
// Flush the binding so the VM has the latest prompt before running.
PromptBox.GetBindingExpression(TextBox.TextProperty)?.UpdateSource();
StartStop_Click(this, new RoutedEventArgs());
return;
}
if (_activeMentionBox == PromptBox && MentionPopup.IsOpen)
HandleMentionPopupKey(e);
}
/// Shared Up/Down/Tab/Enter/Escape navigation for the mention popup.
private void HandleMentionPopupKey(System.Windows.Input.KeyEventArgs e)
{
int count = MentionList.Items.Count;
if (count == 0) return;
switch (e.Key)
{
case System.Windows.Input.Key.Up:
MentionList.SelectedIndex = (MentionList.SelectedIndex - 1 + count) % count;
MentionList.ScrollIntoView(MentionList.SelectedItem);
e.Handled = true;
break;
case System.Windows.Input.Key.Down:
MentionList.SelectedIndex = (MentionList.SelectedIndex + 1) % count;
MentionList.ScrollIntoView(MentionList.SelectedItem);
e.Handled = true;
break;
case System.Windows.Input.Key.Tab:
case System.Windows.Input.Key.Enter:
AcceptMentionSelection();
e.Handled = true;
break;
case System.Windows.Input.Key.Escape:
CloseMentionPopup();
e.Handled = true;
break;
}
}
// ---------- hover tooltip for @refs ----------