forked from umage-ai/CodeShellManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
5018 lines (4554 loc) · 218 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
5018 lines (4554 loc) · 218 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;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CodeShellManager.Models;
using CodeShellManager.Services;
using CodeShellManager.Terminal;
using CodeShellManager.ViewModels;
using CodeShellManager.Views;
using Microsoft.Data.Sqlite;
using Microsoft.Web.WebView2.Wpf;
// Explicit WPF aliases to avoid ambiguity with System.Windows.Forms
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using MessageBoxButton = System.Windows.MessageBoxButton;
using MessageBoxImage = System.Windows.MessageBoxImage;
using MessageBoxResult = System.Windows.MessageBoxResult;
using Color = System.Windows.Media.Color;
using ColorConverter = System.Windows.Media.ColorConverter;
using Brushes = System.Windows.Media.Brushes;
using FontFamily = System.Windows.Media.FontFamily;
using Orientation = System.Windows.Controls.Orientation;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using VerticalAlignment = System.Windows.VerticalAlignment;
using WpfButton = System.Windows.Controls.Button;
using WpfKeyEventArgs = System.Windows.Input.KeyEventArgs;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Ellipse = System.Windows.Shapes.Ellipse;
using WpfTextBox = System.Windows.Controls.TextBox;
namespace CodeShellManager;
public partial class MainWindow : Window
{
private readonly SessionManager _sessionManager = new();
private readonly StateService _stateService = new();
private readonly MainViewModel _vm;
private string? _updateReleaseUrl;
// Per-session UI: the WebView2, its persistent wrapper Border (built once, reused across layouts),
// and its sidebar item.
private readonly Dictionary<string, (WebView2 webView, Border terminalWrapper, Border sidebarItem)> _sessionUi = [];
// Sidebar items for dormant (asleep) sessions — kept here so RebuildSidebarOrder
// can re-append them to the bottom of the list after rebuilding active items.
private readonly Dictionary<string, Border> _dormantSidebarItems = [];
// Sidebar placeholders shown while a session is still launching (restore-on-startup).
// RebuildSidebarOrder weaves them into the live-session list in saved order so the
// user sees the full set of icons immediately, each with a "loading" indicator.
// Items are removed once LaunchSessionAsync registers the real sidebar item.
private readonly Dictionary<string, Border> _launchingSidebarItems = [];
/// <summary>
/// Per-session references to the run-related controls inside the terminal wrapper.
/// Used by RefreshTerminalRunControls() to update the play button / chips strip
/// when the session's RunCommands list or its RunInstances change.
/// </summary>
private readonly Dictionary<string, (
WpfButton playBtn,
WpfButton chevronBtn,
Border chipsStrip,
StackPanel chipsPanel,
Border drawer,
WpfTextBox drawerText,
TextBlock drawerHeader,
WpfButton drawerStopBtn,
WpfButton drawerCopyBtn,
WpfButton drawerSendBtn)> _runControls = new();
private readonly Dictionary<string, string> _drawerItemBySession = new();
// Per-session sidebar action button panels — kept so SettingsButton_Click
// can flip every row to a new SidebarActionIconsMode without rebuilding sidebar items.
private readonly Dictionary<string, StackPanel> _sidebarActionPanels = new();
// Per-session rename trigger — captured from BuildSidebarItem so the context menu's
// Rename action can invoke the same in-place editor as the double-click handler.
private readonly Dictionary<string, Action> _sidebarRenameActions = new();
// Anchor for shift-click range selection in the sidebar.
private string? _selectionAnchorId;
// Group-tab notification indicators (badge + text), keyed by group id (or "__ALL__"
// / GroupFilter.Ungrouped sentinels). Repopulated on every RebuildGroupStrip.
private readonly Dictionary<string, (Border badge, TextBlock badgeText)> _groupTabIndicators = [];
// Sidebar sort state — in-memory only. Re-clicking the same field reverses direction;
// clicking a new field starts in its natural direction (A→Z for text, newest-first for
// last active). After a drag-reorder the field stays remembered so subsequent toggles
// still make sense from the user's mental model.
private enum SortField { None, Name, Folder, LastActive, Branch, Dirty, Repo }
private SortField _currentSortField = SortField.None;
private bool _sortDescending;
private SqliteConnection? _db;
private SearchService? _searchService;
private LayoutMode _currentLayout = LayoutMode.Single;
private int _layoutViewportOffset = 0;
// Window state debounce
private readonly System.Windows.Threading.DispatcherTimer _windowStateTimer;
private bool _windowStateReady = false; // don't save before state is loaded
// OnClosing is async void, which WPF does not await — without these gates the window
// tears down while SaveStateAsync / claude disposal is still mid-flight. First entry
// sets _isShuttingDown, cancels the close, runs the async cleanup, sets _shutdownComplete,
// then re-invokes Close(); the second entry passes through to base.OnClosing. Any
// intermediate re-entries (e.g. user double-clicks the X) hit the _isShuttingDown gate
// and just cancel without re-running cleanup.
private bool _isShuttingDown = false;
private bool _shutdownComplete = false;
public MainWindow()
{
InitializeComponent();
_vm = new MainViewModel(_sessionManager, _stateService);
_vm.SessionClosed += OnSessionVmClosed;
// Refresh terminal layout whenever active session changes (Single mode needs this)
_vm.PropertyChanged += (_, args) =>
{
if (args.PropertyName == nameof(MainViewModel.ActiveSession))
{
if (_vm.ActiveSession != null)
_vm.ActiveSession.Session.LastActivityAt = DateTime.UtcNow;
RefreshTerminalLayout();
UpdateSidebarActiveState();
}
else if (args.PropertyName == nameof(MainViewModel.Layout))
{
// Sync local layout field (used by RefreshTerminalLayout) with VM-driven changes
// — fires both for state-restore at startup and any future programmatic changes.
_currentLayout = _vm.Layout;
_layoutViewportOffset = 0;
RefreshTerminalLayout();
}
else if (args.PropertyName == nameof(MainViewModel.ActiveGroupId))
{
RebuildSidebarOrder();
UpdateGroupStripActiveState();
}
};
_vm.GroupsChanged += () => Dispatcher.Invoke(() =>
{
RebuildGroupStrip();
UpdateGroupStripVisibility();
RebuildSidebarOrder();
});
_vm.SelectionChanged += () => Dispatcher.Invoke(UpdateSidebarActiveState);
// Re-filter the sidebar when a session's GroupId changes — otherwise the current
// filter view stays stale until the user clicks a different tab. Also refresh the
// group-tab indicators since session-to-group membership just shifted.
_vm.SessionMembershipChanged += () => Dispatcher.Invoke(() =>
{
RebuildSidebarOrder();
UpdateGroupTabIndicators();
});
_vm.Sessions.CollectionChanged += (_, e) =>
{
// Skip on Move so the in-place reordering done by RecomputeWorktreeSiblings
// (and user drag-to-reorder) doesn't recurse back into itself or fight the user.
// Add/Remove/Reset are the cases that genuinely shift the sibling landscape.
if (e.Action != System.Collections.Specialized.NotifyCollectionChangedAction.Move)
{
RecomputeWorktreeSiblings();
UpdateGroupTabIndicators();
}
};
Loaded += OnLoaded;
KeyDown += OnKeyDown;
Activated += OnWindowActivated;
// Window state persistence: debounce position/size changes
_windowStateTimer = new System.Windows.Threading.DispatcherTimer
{
Interval = TimeSpan.FromSeconds(1)
};
_windowStateTimer.Tick += (_, _) =>
{
_windowStateTimer.Stop();
SaveWindowBounds();
};
SizeChanged += (_, _) => OnWindowBoundsChanged();
LocationChanged += (_, _) => OnWindowBoundsChanged();
BuildShortcutPanel();
SetupSidebarDrop();
SetupGroupStripDrop();
AttachSidebarQuickMenus();
}
private void OnWindowBoundsChanged()
{
if (!_windowStateReady) return;
_windowStateTimer.Stop();
_windowStateTimer.Start();
}
private void SaveWindowBounds()
{
if (!_windowStateReady) return;
_vm.UpdateWindowState(WindowState, Left, Top, Width, Height);
_ = _vm.SaveStateAsync();
}
// ── Startup ───────────────────────────────────────────────────────────────
private async void OnLoaded(object sender, RoutedEventArgs e)
{
await InitDatabaseAsync();
await _vm.LoadStateAsync();
RestoreWindowState();
_windowStateReady = true;
// Build the group strip (it'll only show once there are groups + the setting is on).
RebuildGroupStrip();
UpdateGroupStripVisibility();
// Prune indexed output per retention policy (runs once at startup, after settings load)
if (_searchService != null)
{
try { await _searchService.PruneOldOutputAsync(_vm.Settings.OutputRetentionDays); }
catch { /* non-critical */ }
}
_ = CheckForUpdatesAsync(); // fire-and-forget; never blocks startup
var saved = _sessionManager.Sessions.ToList();
Log($"OnLoaded: {saved.Count} saved sessions, AutoRestore={_vm.Settings.AutoRestoreSessions}, CleanStart={App.CleanStart}");
if (App.CleanStart)
{
// --clean: skip restore and leave state.json untouched. Drop sessions,
// groups, AND the recently-closed ring from in-memory state so any new
// work this run starts from a clean slate (no leftover scaffolding from
// prior debug sessions). SaveStateAsync is a no-op in --clean mode so
// these clears don't touch the persisted file.
foreach (var s in saved)
_sessionManager.RemoveSession(s.Id);
foreach (var g in _sessionManager.Groups.ToList())
_sessionManager.RemoveGroup(g.Id);
_vm.ClearRecentlyClosed();
return;
}
if (saved.Count == 0) return;
bool doRestore;
if (_vm.Settings.AutoRestoreSessions)
{
doRestore = true;
}
else
{
var result = MessageBox.Show(
$"Restore {saved.Count} saved session(s)?",
"CodeShellManager", MessageBoxButton.YesNo, MessageBoxImage.Question);
doRestore = result == MessageBoxResult.Yes;
}
if (doRestore)
{
// Build "launching" placeholder sidebar items for every live session up-front
// so the full list of icons appears immediately, with a loading indicator on
// each row until its real sidebar item replaces it. Dormant entries are added
// at the bottom (live ones get placeholders woven in by RebuildSidebarOrder).
foreach (var s in saved)
{
if (s.IsDormant) continue;
AddLaunchingSidebarItem(s);
}
foreach (var s in saved)
{
if (s.IsDormant) AddDormantSidebarItem(s);
}
// Render the staged placeholders now. RebuildSidebarOrder weaves them into
// the saved-order list (Resolve picks them when no live item exists yet) and
// applies the active group filter so off-group placeholders are hidden.
RebuildSidebarOrder();
// Launch live sessions sequentially. Stagger consecutive claude launches:
// claude's CLI does an unlocked read-modify-write on ~/.claude.json at startup,
// so simultaneous boots can corrupt the user's profile.
int staggerMs = _vm.Settings.ClaudeLaunchStaggerMs;
bool lastWasClaude = false;
// WebView2 user-data folder access-denied is a common shared-failure
// when another instance is running. Batch these so the user gets one
// actionable dialog at the end instead of N "Restore Error" popups.
var webView2AccessDenied = new List<string>();
foreach (var s in saved)
{
if (s.IsDormant) continue;
bool isClaude = ClaudeSessionService.IsClaudeCommand(s.Command);
if (isClaude && lastWasClaude && staggerMs > 0)
await Task.Delay(staggerMs);
try { await LaunchSessionAsync(s, restoring: true); }
catch (Exception ex)
{
Log($"Restore FAILED for '{s.Name}': {ex}");
if (IsWebView2AccessDenied(ex))
webView2AccessDenied.Add(s.Name);
else
MessageBox.Show($"Failed to restore '{s.Name}': {ex.Message}",
"Restore Error", MessageBoxButton.OK, MessageBoxImage.Warning);
}
lastWasClaude = isClaude;
}
if (webView2AccessDenied.Count > 0)
{
MessageBox.Show(
$"Could not initialize WebView2 for {webView2AccessDenied.Count} session(s):\n\n" +
string.Join("\n", webView2AccessDenied.Select(n => " • " + n)) +
"\n\nThis usually means another CodeShellManager instance is running, " +
"or a previous instance didn't shut down cleanly. Close any other " +
"instances (or wait a few seconds for the WebView2 user-data folder " +
"to unlock) and reopen the affected sessions from the sidebar.",
"WebView2 unavailable", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
else
{
foreach (var s in saved)
_sessionManager.RemoveSession(s.Id);
await _vm.SaveStateAsync();
}
}
// Detects WebView2 user-data folder access-denied, which surfaces as
// UnauthorizedAccessException from CoreWebView2Environment.CreateAsync /
// CreateCoreWebView2ControllerAsync when another process is holding the
// folder. We surface a clearer message in that specific case.
private static bool IsWebView2AccessDenied(Exception ex) =>
ex is UnauthorizedAccessException
&& (ex.StackTrace?.Contains("WebView2", StringComparison.Ordinal) ?? false);
private void RestoreWindowState()
{
var bounds = _vm.GetSavedWindowBounds();
if (bounds != null)
{
// Validate bounds are at least partially on-screen
var screenWidth = SystemParameters.VirtualScreenWidth;
var screenHeight = SystemParameters.VirtualScreenHeight;
var screenLeft = SystemParameters.VirtualScreenLeft;
var screenTop = SystemParameters.VirtualScreenTop;
double left = Math.Max(screenLeft, Math.Min(bounds.Left, screenLeft + screenWidth - 100));
double top = Math.Max(screenTop, Math.Min(bounds.Top, screenTop + screenHeight - 100));
double width = Math.Max(400, Math.Min(bounds.Width, screenWidth));
double height = Math.Max(300, Math.Min(bounds.Height, screenHeight));
Left = left;
Top = top;
Width = width;
Height = height;
}
if (_vm.IsWindowMaximized())
WindowState = WindowState.Maximized;
}
private async Task InitDatabaseAsync()
{
string dbPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"CodeShellManager", "output.db");
Directory.CreateDirectory(Path.GetDirectoryName(dbPath)!);
_db = new SqliteConnection($"Data Source={dbPath}");
_db.Open();
await SearchService.InitializeSchemaAsync(_db);
_searchService = new SearchService(_db);
}
// ── New session ───────────────────────────────────────────────────────────
private void NewSession_Click(object sender, RoutedEventArgs e) => OpenNewSessionDialog();
private void BroadcastRemoteControl_Click(object sender, RoutedEventArgs e)
{
foreach (var session in _vm.Sessions)
{
session.Bridge?.SendToTerminal("/remote-control\r");
session.AlertDetector?.NotifyUserInteracted();
}
}
private void OpenNewSessionDialog(string defaultFolder = "")
=> OpenNewSessionDialogCore(defaultFolder, parent: null);
/// <summary>
/// Opens the New Session dialog pre-filled with the parent session's folder, command, args.
/// The new session lands immediately after the parent in the sidebar and inherits its
/// GroupId + profile overrides (issue #27).
/// </summary>
private void OpenNewSessionDialogFromParent(SessionViewModel parent)
=> OpenNewSessionDialogCore(parent.WorkingFolder, parent);
private void OpenNewSessionDialogCore(string defaultFolder, SessionViewModel? parent)
{
var profiles = _vm.Settings.ImportWindowsTerminalProfiles
? Services.WindowsTerminalProfileService.GetProfiles()
: null;
string folder = !string.IsNullOrEmpty(defaultFolder)
? defaultFolder
: _vm.Settings.DefaultWorkingFolder;
var dialog = new NewSessionDialog(
folder,
_vm.Settings.LaunchCommands,
profiles,
defaultCommand: parent?.Session.Command,
defaultArgs: parent?.Session.Args,
defaultName: null,
recentlyClosed: _vm.RecentlyClosed,
defaultSourceSession: parent?.Session)
{
Owner = this
};
if (dialog.ShowDialog() != true) return;
// If the user picked an entry from the "Recently closed" list, reopen that
// session directly with copied settings and skip the rest of the form.
if (dialog.SelectedRecentlyClosed != null)
{
var entry = dialog.SelectedRecentlyClosed;
// Only drop the entry from the ring after reopen succeeds — a transient
// launch failure (bad folder, SSH unavailable) would otherwise lose the
// entry permanently and the user couldn't retry.
_ = ReopenAndRemoveOnSuccessAsync(entry);
return;
}
// Group resolution priority:
// 1. Explicit selection from the dialog (currently unused — no group picker there)
// 2. Inherited from a parent session (spawn-near-parent flows)
// 3. The active group filter, when the user is currently looking at a real group
// (not All / not Ungrouped) — FilterStrip mode lands new sessions where the
// user is currently filtered.
// 4. The active session's group — InlineHeaders/None mode has no filter concept,
// so fall back to the group of the session the user was just working in.
// 5. Ungrouped
string? groupId = !string.IsNullOrEmpty(dialog.SelectedGroupId)
? dialog.SelectedGroupId
: !string.IsNullOrEmpty(parent?.Session.GroupId)
? parent!.Session.GroupId
: (_vm.ActiveGroupId != null && _vm.ActiveGroupId != GroupFilter.Ungrouped
? _vm.ActiveGroupId
: !string.IsNullOrEmpty(_vm.ActiveSession?.GroupId)
? _vm.ActiveSession!.GroupId
: null);
var session = _sessionManager.CreateSession(
dialog.SessionName,
dialog.SelectedFolder,
dialog.SelectedCommand,
dialog.SelectedArgs,
groupId,
colorOverride: null,
afterSessionId: parent?.Id);
if (dialog.IsRemote)
{
session.Kind = Models.SessionKind.Ssh;
session.SshUser = dialog.SshUser;
session.SshHost = dialog.SshHost;
session.SshPort = dialog.SshPort;
session.SshRemoteFolder = dialog.SshRemoteFolder;
}
else if (dialog.IsWsl)
{
session.Kind = Models.SessionKind.Wsl;
session.WslDistro = dialog.WslDistro;
session.WslUser = dialog.WslUser;
session.WslWorkingFolder = dialog.WslWorkingFolder;
// The session's WorkingFolder stays as a Windows UNC view of the same path
// so anything that touches the filesystem (git status, "open in Explorer")
// resolves correctly. Empty = unmounted; LaunchSessionAsync falls back.
session.WorkingFolder = Services.WslDiscoveryService.ToUncPath(
dialog.WslDistro, dialog.WslWorkingFolder);
}
// Profile overrides come from the dialog (which may have copied from a Windows Terminal
// profile). When the dialog left them blank and we have a parent, inherit the parent's.
session.ProfileFontFamily = dialog.ProfileFontFamily ?? parent?.Session.ProfileFontFamily;
session.ProfileFontSize = dialog.ProfileFontSize ?? parent?.Session.ProfileFontSize;
session.ProfileFontWeight = dialog.ProfileFontWeight ?? parent?.Session.ProfileFontWeight;
session.ProfileFontLigatures = dialog.ProfileFontLigatures ?? parent?.Session.ProfileFontLigatures;
session.ProfileCursorShape = dialog.ProfileCursorShape ?? parent?.Session.ProfileCursorShape;
session.ProfileCursorBlink = dialog.ProfileCursorBlink ?? parent?.Session.ProfileCursorBlink;
session.ProfilePadding = dialog.ProfilePadding ?? parent?.Session.ProfilePadding;
session.ProfileBackgroundOpacity = dialog.ProfileBackgroundOpacity ?? parent?.Session.ProfileBackgroundOpacity;
session.ProfileRetroEffect = dialog.ProfileRetroEffect ?? parent?.Session.ProfileRetroEffect;
session.ProfileColorSchemeJson = dialog.ProfileColorSchemeJson ?? parent?.Session.ProfileColorSchemeJson;
_ = LaunchAndFollowUpWorktreesAsync(session, dialog.AdditionalWorktreePaths);
}
/// <summary>
/// Recreates a session from a <see cref="RecentlyClosedEntry"/> snapshot. Gets a fresh
/// Id (so it's independent of the original) and goes through the normal launch path.
/// Returns the created session; callers can verify it remained in
/// <c>_sessionManager.Sessions</c> after the await to confirm launch success.
/// </summary>
private async Task<ShellSession> ReopenClosedSessionAsync(RecentlyClosedEntry entry)
{
var session = _sessionManager.CreateSession(
entry.Name,
entry.WorkingFolder,
entry.Command,
entry.Args,
string.IsNullOrEmpty(entry.GroupId) ? null : entry.GroupId,
colorOverride: entry.ColorOverride);
// Kind first so the IsRemote shim below doesn't promote a Wsl entry back
// to Ssh when its IsRemote happens to round-trip as false.
session.Kind = entry.Kind;
// Legacy entries (pre-Kind) have Kind=Local but IsRemote=true for SSH —
// the IsRemote setter on ShellSession migrates that to Kind=Ssh.
if (entry.Kind == Models.SessionKind.Local) session.IsRemote = entry.IsRemote;
session.SshUser = entry.SshUser;
session.SshHost = entry.SshHost;
session.SshPort = entry.SshPort;
session.SshRemoteFolder = entry.SshRemoteFolder;
session.WslDistro = entry.WslDistro;
session.WslUser = entry.WslUser;
session.WslWorkingFolder = entry.WslWorkingFolder;
session.ProfileFontFamily = entry.ProfileFontFamily;
session.ProfileFontSize = entry.ProfileFontSize;
session.ProfileFontWeight = entry.ProfileFontWeight;
session.ProfileFontLigatures = entry.ProfileFontLigatures;
session.ProfileCursorShape = entry.ProfileCursorShape;
session.ProfileCursorBlink = entry.ProfileCursorBlink;
session.ProfilePadding = entry.ProfilePadding;
session.ProfileBackgroundOpacity = entry.ProfileBackgroundOpacity;
session.ProfileRetroEffect = entry.ProfileRetroEffect;
session.ProfileColorSchemeJson = entry.ProfileColorSchemeJson;
// Deep-copy RunCommands so subsequent edits don't mutate any other entry
// that may still share the same list reference.
session.RunCommands = entry.RunCommands.Select(r => new RunCommandItem
{
Id = Guid.NewGuid().ToString(),
Label = r.Label,
CommandLine = r.CommandLine,
IsDefault = r.IsDefault,
Mode = r.Mode,
PostRunUrl = r.PostRunUrl,
}).ToList();
await LaunchSessionAsync(session);
return session;
}
/// <summary>
/// Reopens a recently-closed entry and only drops it from the ring if the launch
/// actually succeeded. LaunchSessionAsync's catch path removes the session it
/// created on failure, so we use SessionManager membership as the success signal.
/// </summary>
private async Task ReopenAndRemoveOnSuccessAsync(RecentlyClosedEntry entry)
{
var session = await ReopenClosedSessionAsync(entry);
if (_sessionManager.Sessions.Any(s => s.Id == session.Id))
_vm.RemoveRecentlyClosed(entry);
}
/// <summary>
/// Launches the primary session, then any opt-in sibling worktrees from the dialog —
/// each inheriting the primary's command, group, and profile overrides, and inserted
/// immediately after it so they cluster in the sidebar.
/// </summary>
private async Task LaunchAndFollowUpWorktreesAsync(ShellSession primary, IReadOnlyList<string> additionalPaths)
{
SeedRunCommandsAsync(primary);
await LaunchSessionAsync(primary);
if (additionalPaths.Count == 0) return;
// Stagger consecutive claude launches for the same reason the boot path does
// (see commit 59a7067): claude's CLI does an unlocked read-modify-write on
// ~/.claude.json at startup, and back-to-back launches can corrupt it.
int staggerMs = _vm.Settings.ClaudeLaunchStaggerMs;
string anchorId = primary.Id;
bool lastWasClaude = ClaudeSessionService.IsClaudeCommand(primary.Command);
foreach (var path in additionalPaths)
{
if (!System.IO.Directory.Exists(path)) continue;
bool isClaude = ClaudeSessionService.IsClaudeCommand(primary.Command);
if (isClaude && lastWasClaude && staggerMs > 0) await Task.Delay(staggerMs);
var sibling = _sessionManager.CreateSession(
System.IO.Path.GetFileName(path.TrimEnd('/', '\\')) ?? primary.Command,
path,
primary.Command,
primary.Args,
string.IsNullOrEmpty(primary.GroupId) ? null : primary.GroupId,
colorOverride: null,
afterSessionId: anchorId);
InheritSessionKindFrom(sibling, primary);
// Inherit profile so siblings look identical.
sibling.ProfileFontFamily = primary.ProfileFontFamily;
sibling.ProfileFontSize = primary.ProfileFontSize;
sibling.ProfileFontWeight = primary.ProfileFontWeight;
sibling.ProfileFontLigatures = primary.ProfileFontLigatures;
sibling.ProfileCursorShape = primary.ProfileCursorShape;
sibling.ProfileCursorBlink = primary.ProfileCursorBlink;
sibling.ProfilePadding = primary.ProfilePadding;
sibling.ProfileBackgroundOpacity = primary.ProfileBackgroundOpacity;
sibling.ProfileRetroEffect = primary.ProfileRetroEffect;
sibling.ProfileColorSchemeJson = primary.ProfileColorSchemeJson;
SeedRunCommandsAsync(sibling);
await LaunchSessionAsync(sibling);
anchorId = sibling.Id;
lastWasClaude = isClaude;
}
}
/// <summary>
/// Duplicates a session without a dialog: same folder, command, args, group, and
/// profile overrides; new GUID; a derived name like "<original> (2)". Lands after parent.
/// </summary>
private async Task DuplicateSessionAsync(SessionViewModel parent)
{
var p = parent.Session;
string baseName = string.IsNullOrEmpty(p.Name) ? parent.DisplayName : p.Name;
var clone = _sessionManager.CreateSession(
DeriveDuplicateName(baseName),
p.WorkingFolder,
p.Command,
p.Args,
string.IsNullOrEmpty(p.GroupId) ? null : p.GroupId,
colorOverride: null,
afterSessionId: parent.Id);
InheritSessionKindFrom(clone, p);
clone.ProfileFontFamily = p.ProfileFontFamily;
clone.ProfileFontSize = p.ProfileFontSize;
clone.ProfileFontWeight = p.ProfileFontWeight;
clone.ProfileFontLigatures = p.ProfileFontLigatures;
clone.ProfileCursorShape = p.ProfileCursorShape;
clone.ProfileCursorBlink = p.ProfileCursorBlink;
clone.ProfilePadding = p.ProfilePadding;
clone.ProfileBackgroundOpacity = p.ProfileBackgroundOpacity;
clone.ProfileRetroEffect = p.ProfileRetroEffect;
clone.ProfileColorSchemeJson = p.ProfileColorSchemeJson;
// Copy parent's run commands with fresh Ids so the duplicate has its own list.
foreach (var item in p.RunCommands)
{
clone.RunCommands.Add(new Models.RunCommandItem
{
Id = System.Guid.NewGuid().ToString(),
Label = item.Label,
CommandLine = item.CommandLine,
IsDefault = item.IsDefault,
Mode = item.Mode,
PostRunUrl = item.PostRunUrl,
});
}
// If the parent had no commands, fall back to detection.
if (clone.RunCommands.Count == 0) SeedRunCommandsAsync(clone);
await LaunchSessionAsync(clone);
}
private string DeriveDuplicateName(string baseName)
{
// If baseName already ends with " (N)", increment; otherwise append " (2)".
var match = System.Text.RegularExpressions.Regex.Match(baseName, @"^(.*) \((\d+)\)$");
string stem = match.Success ? match.Groups[1].Value : baseName;
int start = match.Success ? int.Parse(match.Groups[2].Value) + 1 : 2;
var existing = new HashSet<string>(
_vm.Sessions.Select(s => s.DisplayName), StringComparer.OrdinalIgnoreCase);
for (int n = start; n < start + 100; n++)
{
string candidate = $"{stem} ({n})";
if (!existing.Contains(candidate)) return candidate;
}
return $"{stem} ({start})";
}
/// <summary>
/// Propagates a parent session's <see cref="Models.SessionKind"/> and kind-specific
/// fields (SSH host/user/port, WSL distro/user) onto a freshly-created child
/// session. For WSL children it also derives <c>WslWorkingFolder</c> from the
/// child's <c>WorkingFolder</c>, which the worktree code paths set to a
/// <c>\\wsl$\<distro>\…</c> UNC. Without this step a new session spawned
/// from a WSL parent (Duplicate, sibling worktree, new worktree) silently falls
/// back to <see cref="Models.SessionKind.Local"/> and tries to run the parent's
/// command (e.g. <c>claude</c>) inside a Windows PowerShell at the UNC path.
/// </summary>
private static void InheritSessionKindFrom(Models.ShellSession target, Models.ShellSession source)
{
target.Kind = source.Kind;
if (source.Kind == Models.SessionKind.Ssh)
{
target.SshUser = source.SshUser;
target.SshHost = source.SshHost;
target.SshPort = source.SshPort;
target.SshRemoteFolder = source.SshRemoteFolder;
return;
}
if (source.Kind == Models.SessionKind.Wsl)
{
target.WslDistro = source.WslDistro;
target.WslUser = source.WslUser;
var (parsedDistro, parsedLinux) = Services.GitService.TryParseWslUnc(target.WorkingFolder);
if (!string.IsNullOrEmpty(parsedDistro))
{
// Common path: WorkingFolder is a WSL UNC the caller already built.
target.WslWorkingFolder = parsedLinux == "/" ? "" : parsedLinux;
}
else if (!string.IsNullOrEmpty(target.WorkingFolder) && target.WorkingFolder.StartsWith('/'))
{
// Caller passed a Linux path directly (e.g. typed into a worktree dialog).
target.WslWorkingFolder = target.WorkingFolder;
target.WorkingFolder = Services.WslDiscoveryService.ToUncPath(
source.WslDistro, target.WslWorkingFolder);
}
else
{
// Unknown shape — keep the parent's folder so the child at least lands
// somewhere usable instead of in $HOME-by-accident.
target.WslWorkingFolder = source.WslWorkingFolder;
target.WorkingFolder = source.WorkingFolder;
}
}
}
/// <summary>
/// Launches a new session in an existing sibling worktree (path resolved via
/// `git worktree list`). Inherits the source session's command, group, and profile.
/// </summary>
private async Task LaunchSessionInSiblingWorktreeAsync(SessionViewModel parent, string worktreePath)
{
if (!System.IO.Directory.Exists(worktreePath))
{
MessageBox.Show(this, $"Worktree folder '{worktreePath}' does not exist.",
"Worktree missing", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var p = parent.Session;
var sibling = _sessionManager.CreateSession(
System.IO.Path.GetFileName(worktreePath.TrimEnd('/', '\\')) ?? p.Command,
worktreePath,
p.Command,
p.Args,
string.IsNullOrEmpty(p.GroupId) ? null : p.GroupId,
colorOverride: null,
afterSessionId: parent.Id);
InheritSessionKindFrom(sibling, p);
sibling.ProfileFontFamily = p.ProfileFontFamily;
sibling.ProfileFontSize = p.ProfileFontSize;
sibling.ProfileFontWeight = p.ProfileFontWeight;
sibling.ProfileFontLigatures = p.ProfileFontLigatures;
sibling.ProfileCursorShape = p.ProfileCursorShape;
sibling.ProfileCursorBlink = p.ProfileCursorBlink;
sibling.ProfilePadding = p.ProfilePadding;
sibling.ProfileBackgroundOpacity = p.ProfileBackgroundOpacity;
sibling.ProfileRetroEffect = p.ProfileRetroEffect;
sibling.ProfileColorSchemeJson = p.ProfileColorSchemeJson;
SeedRunCommandsAsync(sibling);
await LaunchSessionAsync(sibling);
}
/// <summary>
/// Stamps the session's RunCommands list from the matching project-type template,
/// if the list is currently empty AND the session is local (not SSH). Runs on a
/// background task so the UI doesn't block on folder enumeration. No-op if the
/// folder doesn't match any template.
/// </summary>
private void SeedRunCommandsAsync(Models.ShellSession session)
{
// SSH is out of reach for the synchronous Directory.EnumerateFiles probe.
// WSL is reachable via the `\\wsl$\<distro>\…` UNC view — slow on first
// access if the distro VM is stopped, but the probe runs on a background
// task so the UI doesn't block. RunInstance already wraps run commands in
// `wsl.exe -- bash -lc` for WSL parents.
if (session.Kind == Models.SessionKind.Ssh) return;
if (session.RunCommands.Count > 0) return;
if (string.IsNullOrWhiteSpace(session.WorkingFolder)) return;
string folder = session.WorkingFolder;
_ = System.Threading.Tasks.Task.Run(() =>
{
var template = Services.RunCommandTemplatesService.SeedFor(folder);
if (template == null) return;
Dispatcher.Invoke(() =>
{
// Re-check on UI thread — the user may have edited the list manually
// while we were scanning (race with the editor dialog).
if (session.RunCommands.Count == 0)
{
foreach (var item in template.Items)
session.RunCommands.Add(item);
_ = _vm.SaveStateAsync();
RefreshTerminalRunControls(session.Id);
}
});
});
}
private static WpfButton MakeDrawerActionButton(string label) => new()
{
Content = label,
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
Foreground = new SolidColorBrush(Color.FromRgb(0xa6, 0xad, 0xc8)),
FontSize = 11,
Cursor = System.Windows.Input.Cursors.Hand,
Padding = new Thickness(8, 4, 8, 4),
};
/// <summary>
/// Rebuilds chips + play-button visibility + drawer content for one session.
/// Idempotent — safe to call from every InstancesChanged event.
/// </summary>
private void RefreshTerminalRunControls(string sessionId)
{
if (!_runControls.TryGetValue(sessionId, out var c)) return;
var vm = _vm.Sessions.FirstOrDefault(s => s.Id == sessionId);
if (vm == null) return;
// Play / chevron visibility — driven by whether the list has anything to run.
var vis = vm.Session.RunCommands.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
c.playBtn.Visibility = vis;
c.chevronBtn.Visibility = vis;
// Rebuild chips strip.
c.chipsPanel.Children.Clear();
var instances = vm.Runner.Instances;
foreach (var (_, inst) in instances)
{
var chip = BuildRunChip(vm, inst);
c.chipsPanel.Children.Add(chip);
}
c.chipsStrip.Visibility = instances.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
// Update drawer if a viewed item exists.
if (_drawerItemBySession.TryGetValue(sessionId, out var viewedItemId) &&
vm.Runner.GetInstance(viewedItemId) is { } viewedInst)
{
c.drawerHeader.Text = $"{viewedInst.Label} — {DescribeState(viewedInst)}";
c.drawerText.Text = viewedInst.SnapshotOutput();
// Auto-scroll to the end while the run is active.
if (viewedInst.State == RunState.Running)
c.drawerText.ScrollToEnd();
c.drawerStopBtn.IsEnabled = viewedInst.State == RunState.Running;
}
else
{
// Viewed item disappeared (was dismissed). Hide the drawer.
c.drawer.Visibility = Visibility.Collapsed;
_drawerItemBySession.Remove(sessionId);
}
}
private static string DescribeState(RunInstance inst) => inst.State switch
{
RunState.Idle => "idle",
RunState.Running => "running…",
RunState.ExitedOk => $"finished (exit 0, {inst.Duration?.TotalSeconds:F1}s)",
RunState.ExitedFailed => $"failed (exit {inst.ExitCode?.ToString() ?? "?"})",
_ => "?",
};
private Border BuildRunChip(SessionViewModel vm, RunInstance inst)
{
(Color fill, Color text) ColorsFor(RunState s) => s switch
{
RunState.Running => (Color.FromRgb(0x89, 0xb4, 0xfa), Color.FromRgb(0x18, 0x18, 0x25)),
RunState.ExitedOk => (Color.FromRgb(0xa6, 0xe3, 0xa1), Color.FromRgb(0x18, 0x18, 0x25)),
RunState.ExitedFailed => (Color.FromRgb(0xf3, 0x8b, 0xa8), Color.FromRgb(0x18, 0x18, 0x25)),
_ => (Color.FromRgb(0x45, 0x47, 0x5a), Color.FromRgb(0xcd, 0xd6, 0xf4)),
};
string Icon(RunState s) => s switch
{
RunState.Running => "●",
RunState.ExitedOk => "✓",
RunState.ExitedFailed => "✗",
_ => "▶",
};
var (fillC, textC) = ColorsFor(inst.State);
var chip = new Border
{
Background = new SolidColorBrush(fillC),
CornerRadius = new CornerRadius(10),
Padding = new Thickness(8, 2, 4, 2),
Margin = new Thickness(0, 0, 6, 0),
Cursor = System.Windows.Input.Cursors.Hand,
};
var sp = new StackPanel { Orientation = Orientation.Horizontal };
sp.Children.Add(new TextBlock
{
Text = $"{Icon(inst.State)} {inst.Label}",
Foreground = new SolidColorBrush(textC),
FontSize = 11,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(0, 0, 4, 0),
});
var dismiss = new WpfButton
{
Content = "✕",
Background = Brushes.Transparent,
BorderThickness = new Thickness(0),
Foreground = new SolidColorBrush(textC),
FontSize = 9,
Padding = new Thickness(2, 0, 2, 0),
Cursor = System.Windows.Input.Cursors.Hand,
ToolTip = "Dismiss",
};
dismiss.Click += (_, _) => vm.Runner.Dismiss(inst.ItemId);
sp.Children.Add(dismiss);
chip.Child = sp;
chip.MouseLeftButtonUp += (_, _) => ToggleDrawer(vm, inst.ItemId);
return chip;
}
private void ToggleDrawer(SessionViewModel vm, string itemId)
{
if (!_runControls.TryGetValue(vm.Id, out var c)) return;
if (_drawerItemBySession.TryGetValue(vm.Id, out var current) && current == itemId
&& c.drawer.Visibility == Visibility.Visible)
{
c.drawer.Visibility = Visibility.Collapsed;
_drawerItemBySession.Remove(vm.Id);
}
else
{
_drawerItemBySession[vm.Id] = itemId;
c.drawer.Visibility = Visibility.Visible;
RefreshTerminalRunControls(vm.Id);
}
}
private void RunDefaultCommand(SessionViewModel vm)
{
var def = vm.Session.RunCommands.FirstOrDefault(i => i.IsDefault);
if (def == null) return;
vm.Runner.Run(def);
}
private void ShowRunCommandsDropdown(SessionViewModel vm, WpfButton anchor)
{
var menu = new System.Windows.Controls.ContextMenu
{
PlacementTarget = anchor,
Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom,
};
foreach (var item in vm.Session.RunCommands)
{
var label = item.IsDefault ? $"▶ {item.Label} (default)" : $"▶ {item.Label}";
var mi = new System.Windows.Controls.MenuItem { Header = label };
mi.Click += (_, _) => vm.Runner.Run(item);
menu.Items.Add(mi);
}
menu.Items.Add(new System.Windows.Controls.Separator());
var edit = new System.Windows.Controls.MenuItem { Header = "Edit commands…" };
edit.Click += (_, _) => OpenRunCommandsEditor(vm);
menu.Items.Add(edit);
menu.IsOpen = true;
}
private void OpenRunCommandsEditor(SessionViewModel vm)
{
var dlg = new Views.SessionRunCommandsDialog(vm.DisplayName, vm.Session.RunCommands)
{
Owner = this,
};
if (dlg.ShowDialog() == true && dlg.Result != null)
{
vm.Session.RunCommands.Clear();
foreach (var item in dlg.Result)
vm.Session.RunCommands.Add(item);
_ = _vm.SaveStateAsync();
RefreshTerminalRunControls(vm.Id);
}
}
private void SendRunOutputToTerminal(SessionViewModel vm, WpfTextBox drawerText)
{
if (!_drawerItemBySession.TryGetValue(vm.Id, out var itemId)) return;
var inst = vm.Runner.GetInstance(itemId);
if (inst == null) return;
string text = !string.IsNullOrEmpty(drawerText.SelectedText)
? drawerText.SelectedText
: inst.SnapshotOutput();
if (string.IsNullOrWhiteSpace(text)) return;
bool isClaude = ClaudeSessionService.IsClaudeCommand(vm.Session.Command);
if (isClaude && vm.Bridge != null)
{
string exit = inst.ExitCode is { } code ? $" (exit code {code})" : "";
// No trailing \r — leave it in Claude's input box for the user to submit.
string wrapped = $"\nOutput of `{inst.CommandLine}`{exit}:\n```\n{text}\n```\n";
vm.Bridge.SendToTerminal(wrapped);
ToastHelper.Show("Sent to Claude", $"{text.Length} chars wrapped in fence");
}
else
{
// Non-Claude shell: clipboard fallback to avoid auto-execution.
try { System.Windows.Clipboard.SetText(text); } catch { }
ToastHelper.Show("Sent to clipboard", "Paste with Ctrl+V to be safe");
}
}