-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
3113 lines (2784 loc) · 116 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
3113 lines (2784 loc) · 116 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;
// Yolo full-window terminal: a second WebView2 + TerminalHost dedicated
// to the per-conversation yolo CLI session. Re-attached to the active
// conversation's YoloPanel whenever SelectedConversation changes.
private TerminalHost? _yoloTerminalHost;
private bool _yoloTerminalHostReady;
private ConversationViewModel? _yoloAttachedConversation;
// @-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();
_ = InitializeYoloTerminalHostAsync();
};
Closing += (_, _) => _vm.SaveWindowBounds(Left, Top, Width, Height);
Closed += (_, _) =>
{
try { _terminalHost?.Dispose(); } catch { }
try { _yoloTerminalHost?.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. Goes straight
// through AppendStyled rather than the buffered streaming path so the
// FlowDocument is populated synchronously — the buffer's 16ms
// DispatcherTimer can sit unfired for seconds during startup while
// the UI thread is busy, which made non-selected tabs look empty
// until clicked.
var history = c.PopConsoleHistory();
if (!string.IsNullOrEmpty(history))
AppendStyled(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;
AttachYoloConversationTerminal();
}
private void OnSelectedConversationPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (!ReferenceEquals(sender, _subscribedConversation)) return;
if (e.PropertyName is nameof(ConversationViewModel.TasksText)
or nameof(ConversationViewModel.TaskPreviewMarkdown))
{
QueueScrollTasks();
}
else if (e.PropertyName == nameof(ConversationViewModel.IsTaskManagerEnabled))
{
// Toggling into yolo mode — make sure the attached panel actually
// has a session running. EnsureYoloSession is idempotent.
if (_subscribedConversation?.IsYoloModeEnabled == true)
_subscribedConversation.EnsureYoloSession();
AttachYoloConversationTerminal();
_yoloTerminalHost?.FocusActive();
}
}
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);
// User-tunable fallback shell priority for AddSession recovery; the
// host iterates this list before walking the detected default order.
_terminalHost.FallbackShellOrder = () =>
(_vm.Settings.TerminalShellFallbackOrder ?? "")
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
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;
// Drop the previous panel's header-status hooks before swapping.
if (_terminalAttachedProject?.TerminalPanel is { } previous)
{
((System.Collections.Specialized.INotifyCollectionChanged)previous.Sessions)
.CollectionChanged -= OnHeaderPanelSessionsChanged;
previous.ActiveSessionChanged -= OnHeaderPanelActiveSessionChanged;
}
_terminalAttachedProject = project;
_terminalHost.AttachPanel(project?.TerminalPanel);
if (project?.TerminalPanel is { } next)
{
((System.Collections.Specialized.INotifyCollectionChanged)next.Sessions)
.CollectionChanged += OnHeaderPanelSessionsChanged;
next.ActiveSessionChanged += OnHeaderPanelActiveSessionChanged;
}
UpdateTerminalHeaderStatus();
}
// The session whose Title we are currently mirroring into the header
// status — kept here so we can detach the PropertyChanged hook when the
// active session changes or the panel is swapped.
private TerminalSessionViewModel? _headerTitleSession;
private void OnHeaderPanelSessionsChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
=> UpdateTerminalHeaderStatus();
private void OnHeaderPanelActiveSessionChanged(object? sender, TerminalSessionViewModel s)
=> UpdateTerminalHeaderStatus();
private void OnHeaderTitleSessionPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(TerminalSessionViewModel.Title))
UpdateTerminalHeaderStatus();
}
private void UpdateTerminalHeaderStatus()
{
if (TerminalHeaderStatus == null) return;
var panel = ActiveTerminalPanel;
// Re-bind the title-tracking hook to whichever session is now active.
var active = panel?.ActiveSession;
if (!ReferenceEquals(_headerTitleSession, active))
{
if (_headerTitleSession != null)
_headerTitleSession.PropertyChanged -= OnHeaderTitleSessionPropertyChanged;
_headerTitleSession = active;
if (_headerTitleSession != null)
_headerTitleSession.PropertyChanged += OnHeaderTitleSessionPropertyChanged;
}
if (panel == null || panel.Sessions.Count == 0)
{
TerminalHeaderStatus.Text = "";
return;
}
var count = panel.Sessions.Count;
var title = active?.Title;
var shell = active?.Shell.Label ?? "—";
// "3 sessions · my-build (pwsh)" — show the user's title (or auto-
// generated default) plus the underlying shell so two `pwsh` tabs are
// distinguishable. Falls back to bare shell label if the title equals
// the auto-generated `<Shell> (N)` form to avoid `pwsh (1) (pwsh)`.
string label;
if (string.IsNullOrEmpty(title) || title == shell)
label = shell;
else if (title.Contains($"({shell.ToLowerInvariant()})", StringComparison.OrdinalIgnoreCase)
|| title.StartsWith(shell + " ", StringComparison.OrdinalIgnoreCase))
label = title; // already contains the shell
else
label = $"{title} ({shell})";
TerminalHeaderStatus.Text = count == 1
? $"1 session · {label}"
: $"{count} sessions · {label}";
}
// ---- yolo terminal panel (dedicated WebView2 for Task Manager-off mode) ----
private async Task InitializeYoloTerminalHostAsync()
{
if (_yoloTerminalHost != null) return;
_yoloTerminalHost = new TerminalHost(YoloTerminalWebView);
try
{
await _yoloTerminalHost.InitializeAsync();
_yoloTerminalHostReady = true;
AttachYoloConversationTerminal();
}
catch
{
// WebView2 runtime not installed — yolo mode will fail soft.
}
}
private void AttachYoloConversationTerminal()
{
if (!_yoloTerminalHostReady || _yoloTerminalHost == null) return;
var conv = _vm.SelectedProject?.SelectedConversation;
if (ReferenceEquals(conv, _yoloAttachedConversation)) return;
_yoloAttachedConversation = conv;
_yoloTerminalHost.AttachPanel(conv?.YoloPanel);
// First-time entry into yolo mode for this conversation kicks off the
// CLI session so the user lands in a live REPL instead of an empty
// pane. Idempotent — if a session is already running, this is a no-op.
if (conv?.IsYoloModeEnabled == true) conv.EnsureYoloSession();
}
private void YoloRestart_Click(object sender, RoutedEventArgs e)
{
var conv = _vm.SelectedProject?.SelectedConversation;
if (conv == null) return;
conv.CloseYoloSession();
conv.EnsureYoloSession();
_yoloTerminalHost?.FocusActive();
}
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.Items.Add(new Separator());
var editFallback = new MenuItem { Header = "Edit fallback order…" };
editFallback.Click += (_, _) => OpenFallbackOrderEditor();
menu.Items.Add(editFallback);
}
menu.IsOpen = true;
}
/// <summary>
/// Opens a small modal that lets the user edit
/// <c>TerminalShellFallbackOrder</c> as a comma-separated list. Lists
/// detected shells underneath the input as a hint. Saves on OK.
/// </summary>
private void OpenFallbackOrderEditor()
{
var dlg = new Window
{
Title = "Fallback shell order",
Owner = this,
Width = 500,
Height = 220,
ResizeMode = ResizeMode.NoResize,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Background = (System.Windows.Media.Brush)FindResource("BgSurface"),
Foreground = (System.Windows.Media.Brush)FindResource("FgPrimary"),
ShowInTaskbar = false,
};
var stack = new StackPanel { Margin = new Thickness(14) };
stack.Children.Add(new TextBlock
{
Text = "Comma-separated shell ids tried in order when the preferred shell fails to spawn.",
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 0, 0, 8),
});
var input = new TextBox
{
Text = _vm.TerminalShellFallbackOrder,
Margin = new Thickness(0, 0, 0, 8),
Padding = new Thickness(6, 4, 6, 4),
};
stack.Children.Add(input);
var detected = string.Join(", ", ShellDetector.Available.Select(s => s.Id));
stack.Children.Add(new TextBlock
{
Text = $"Detected: {(string.IsNullOrEmpty(detected) ? "(none)" : detected)}",
Foreground = (System.Windows.Media.Brush)FindResource("FgDim"),
FontSize = 11,
Margin = new Thickness(0, 0, 0, 12),
});
var btnRow = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = System.Windows.HorizontalAlignment.Right };
var cancel = new Button { Content = "Cancel", MinWidth = 72, Margin = new Thickness(0, 0, 8, 0), IsCancel = true };
var ok = new Button { Content = "Save", MinWidth = 72, IsDefault = true };
ok.Click += (_, _) =>
{
_vm.TerminalShellFallbackOrder = input.Text ?? "";
dlg.DialogResult = true;
};
btnRow.Children.Add(cancel);
btnRow.Children.Add(ok);
stack.Children.Add(btnRow);
dlg.Content = stack;
dlg.Loaded += (_, _) => input.Focus();
dlg.ShowDialog();
}
private void TerminalClear_Click(object sender, RoutedEventArgs e)
=> _terminalHost?.ClearActive();
private void TerminalSaveOutput_Click(object sender, RoutedEventArgs e)
{
var panel = ActiveTerminalPanel;
var session = panel?.ActiveSession;
if (session == null) return;
var snapshot = session.GetOutputHistorySnapshot();
if (snapshot.Length == 0)
{
System.Windows.MessageBox.Show(
this,
"Terminal output is empty.",
"Save terminal output",
System.Windows.MessageBoxButton.OK,
System.Windows.MessageBoxImage.Information);
return;
}
// Replace path-hostile chars in the title so users with `<git-status>`
// or similar in their tab titles don't get blocked at SaveFileDialog.
var safeTitle = string.Concat((session.Title ?? "session")
.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c));
// Default suggested filename respects `TerminalSaveOutputLocalTime`:
// local users ("when did I run this?") get `yyyyMMdd'T'HHmmss`, the
// sortable-across-machines default sticks with UTC `…Z`.
var stamp = _vm.Settings.TerminalSaveOutputLocalTime
? DateTime.Now.ToString("yyyyMMdd'T'HHmmss")
: DateTime.UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'");
var dlg = new Microsoft.Win32.SaveFileDialog
{
FileName = $"terminal-{safeTitle}-{stamp}.log",
// Filter index drives stripping: .log keeps the raw ANSI stream
// (highest fidelity); .txt strips escapes for grep-friendly output.
Filter = "Raw log with ANSI (*.log)|*.log|Plain text, ANSI stripped (*.txt)|*.txt|All files (*.*)|*.*",
DefaultExt = ".log",
};
if (dlg.ShowDialog(this) != true) return;
try
{
// FilterIndex is 1-based; 2 = "Plain text, ANSI stripped".
byte[] bytes;
if (dlg.FilterIndex == 2)
{
bytes = TerminalSessionViewModel.StripAnsi(snapshot, out var overflow);
if (overflow > 0)
{
// First-time signal that a session has ever produced a
// line longer than the 64 KiB line-buffer cap. Useful
// signal during debugging that a no-newline runaway
// stream actually exists in the wild.
System.Diagnostics.Debug.WriteLine(
$"[terminal] StripAnsi dropped {overflow} byte(s) for session '{session.Title}' (line-buffer cap)");
}
}
else
{
bytes = snapshot;
}
File.WriteAllBytes(dlg.FileName, bytes);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(
this,
$"Failed to save terminal output:\n{ex.Message}",
"Save terminal output",
System.Windows.MessageBoxButton.OK,
System.Windows.MessageBoxImage.Error);
}
}
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;
}
// Drag-drop tab reorder state. Captured on left-mouse-down, consumed by
// PreviewMouseMove once the user drags past the system threshold.
private TerminalSessionViewModel? _terminalTabDragSource;
private System.Windows.Point _terminalTabDragOrigin;
private void TerminalTab_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
if (sender is not FrameworkElement fe || fe.Tag is not TerminalSessionViewModel s) return;
// Double-click on the tab opens the inline rename editor — matches
// Windows Terminal / VS Code muscle memory. Right-click still works
// as a discoverable secondary affordance.
if (e.ClickCount == 2)
{
s.IsRenaming = true;
e.Handled = true;
return;
}
// Record drag origin so PreviewMouseMove can decide whether the user
// intended a reorder vs. a click-to-activate. Cleared on drag start
// or on the next mouse-down.
_terminalTabDragSource = s;
_terminalTabDragOrigin = e.GetPosition(this);
var panel = ActiveTerminalPanel;
if (panel != null) panel.ActiveSession = s;
_terminalHost?.FocusActive();
}
private void TerminalTab_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.LeftButton != System.Windows.Input.MouseButtonState.Pressed) return;
if (_terminalTabDragSource == null) return;
if (sender is not FrameworkElement fe) return;
var pos = e.GetPosition(this);
if (Math.Abs(pos.X - _terminalTabDragOrigin.X) < SystemParameters.MinimumHorizontalDragDistance &&
Math.Abs(pos.Y - _terminalTabDragOrigin.Y) < SystemParameters.MinimumVerticalDragDistance)
return;
var source = _terminalTabDragSource;
_terminalTabDragSource = null;
try
{
System.Windows.DragDrop.DoDragDrop(
fe,
new System.Windows.DataObject("TerminalTabSession", source),
System.Windows.DragDropEffects.Move);
}
catch { /* drag may fail mid-modal-popup; not worth surfacing */ }
}
private void TerminalTab_DragOver(object sender, System.Windows.DragEventArgs e)
{
var hasPayload = e.Data.GetDataPresent("TerminalTabSession");
e.Effects = hasPayload
? System.Windows.DragDropEffects.Move
: System.Windows.DragDropEffects.None;
// Light up the indicator on the hovered tab; choose leading vs.
// trailing edge based on whether the cursor is past the tab's center.
// Clear any other tab's flag so only one indicator shows at a time.
if (hasPayload && sender is FrameworkElement fe && fe.Tag is TerminalSessionViewModel target)
{
var source = e.Data.GetData("TerminalTabSession") as TerminalSessionViewModel;
var pos = e.GetPosition(fe);
var dropAfter = fe.ActualWidth > 0 && pos.X > fe.ActualWidth / 2.0;
var panel = ActiveTerminalPanel;
if (panel != null)
{
foreach (var s in panel.Sessions)
{
var isThis = !ReferenceEquals(s, source) && ReferenceEquals(s, target);
s.IsDropTarget = isThis;
if (isThis) s.DropAfter = dropAfter;
}
}
}
e.Handled = true;
}
private void TerminalTab_DragLeave(object sender, System.Windows.DragEventArgs e)
{
if (sender is FrameworkElement fe && fe.Tag is TerminalSessionViewModel s)
{
s.IsDropTarget = false;
s.DropAfter = false;
}
}
private void TerminalTab_Drop(object sender, System.Windows.DragEventArgs e)
{
// Capture indicator state before clearing — the leading/trailing
// decision was last computed in DragOver and lives on the target VM.
var panel = ActiveTerminalPanel;
var dropAfter = false;
if (sender is FrameworkElement feProbe && feProbe.Tag is TerminalSessionViewModel probeTarget)
dropAfter = probeTarget.DropAfter;
if (panel != null)
foreach (var s in panel.Sessions) { s.IsDropTarget = false; s.DropAfter = false; }
if (sender is not FrameworkElement fe || fe.Tag is not TerminalSessionViewModel target) return;
if (e.Data.GetData("TerminalTabSession") is not TerminalSessionViewModel source) return;
if (ReferenceEquals(source, target)) { e.Handled = true; return; }
if (panel == null) return;
var src = panel.Sessions.IndexOf(source);
var dst = panel.Sessions.IndexOf(target);
if (src < 0 || dst < 0) return;
// Trailing-edge drops mean "land after this tab". Adjust the index
// and account for the source slot's removal shifting later indices
// back by one when src < dst.
if (dropAfter) dst++;
if (src < dst) dst--;
if (src == dst) { e.Handled = true; return; }
panel.Sessions.Move(src, dst);
e.Handled = true;
}
private void TerminalTab_MiddleClick_Close(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// Chromium-tab convention: middle-click closes. The left-button
// handler runs separately, so we filter to MiddleButton only and
// mark Handled to keep the activation path from firing.
if (e.ChangedButton != System.Windows.Input.MouseButton.Middle) return;
if (sender is FrameworkElement fe && fe.Tag is TerminalSessionViewModel s)
ActiveTerminalPanel?.CloseSession(s);
e.Handled = true;
}
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 TerminalTab_TitleEdit_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// When the rename TextBox becomes visible (IsRenaming flipped on),
// grab focus and select-all so typing immediately replaces the title.
if (sender is not TextBox tb) return;
if (e.NewValue is not bool visible || !visible) return;
// Defer to after layout so Focus actually lands — the TextBox is
// newly realized and won't take focus until it's measured.
Dispatcher.BeginInvoke(new Action(() =>
{
tb.Focus();
tb.SelectAll();
}), System.Windows.Threading.DispatcherPriority.Input);
}
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);