-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathClaudeCodeControl.Terminal.cs
More file actions
2249 lines (1949 loc) · 90.7 KB
/
ClaudeCodeControl.Terminal.cs
File metadata and controls
2249 lines (1949 loc) · 90.7 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
/* *******************************************************************************************************************
* Application: ClaudeCodeExtension
*
* Autor: Daniel Carvalho Liedke
*
* Copyright © Daniel Carvalho Liedke 2026
* Usage and reproduction in any manner whatsoever without the written permission of Daniel Carvalho Liedke is strictly forbidden.
*
* Purpose: Terminal window initialization, embedding, and process management
*
* *******************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Microsoft.VisualStudio.Shell;
namespace ClaudeCodeVS
{
public partial class ClaudeCodeControl
{
#region Terminal Fields
/// <summary>
/// Windows Forms panel hosting the embedded terminal
/// </summary>
private System.Windows.Forms.Panel terminalPanel;
/// <summary>
/// The CMD process running the terminal
/// </summary>
private Process cmdProcess;
/// <summary>
/// Handle to the terminal window
/// </summary>
private IntPtr terminalHandle;
/// <summary>
/// Tracks the currently running AI provider (before any new selection)
/// </summary>
private AiProvider? _currentRunningProvider = null;
/// <summary>
/// Height of the Windows Terminal tab bar in pixels (0 for Command Prompt mode)
/// </summary>
private int _wtTabBarHeight = 0;
/// <summary>
/// Full resolved path to wt.exe (set by IsWindowsTerminalAvailableAsync)
/// </summary>
private string _wtExePath = null;
/// <summary>
/// Handle to the low-level mouse hook used for tracking Ctrl+Scroll zoom on the embedded terminal
/// </summary>
private IntPtr _mouseHookHandle = IntPtr.Zero;
/// <summary>
/// Prevent GC from collecting the hook callback delegate
/// </summary>
private LowLevelMouseProc _mouseHookProc;
/// <summary>
/// Handle to the low-level keyboard hook used for intercepting F5/Ctrl+F5 on the embedded terminal
/// </summary>
private IntPtr _keyboardHookHandle = IntPtr.Zero;
/// <summary>
/// Prevent GC from collecting the keyboard hook callback delegate
/// </summary>
private LowLevelKeyboardProc _keyboardHookProc;
/// <summary>
/// Debounce timer for saving zoom delta to settings after Ctrl+Scroll
/// </summary>
private System.Windows.Threading.DispatcherTimer _zoomSaveTimer;
/// <summary>
/// Mouse drag distance in pixels before Windows Terminal selection assist kicks in
/// </summary>
private const int WindowsTerminalSelectionDragThreshold = 4;
/// <summary>
/// Tracks a pending left-drag inside Windows Terminal
/// </summary>
private bool _windowsTerminalSelectionPending;
/// <summary>
/// Tracks when selection assist is active for the current drag
/// </summary>
private bool _windowsTerminalSelectionActive;
/// <summary>
/// True when this control injected SHIFT to force text selection in Windows Terminal
/// </summary>
private bool _windowsTerminalSelectionModifierInjected;
/// <summary>
/// Drag start point for Windows Terminal selection assist
/// </summary>
private POINT _windowsTerminalSelectionStartPoint;
/// <summary>
/// Serializes terminal stop/start transitions so provider or host switches cannot overlap.
/// </summary>
private readonly SemaphoreSlim _terminalLifecycleSemaphore = new SemaphoreSlim(1, 1);
/// <summary>
/// Monotonic session identifier used to discard deferred startup work from stale terminal instances.
/// </summary>
private int _terminalStartupSessionId = 0;
/// <summary>
/// Monotonic request identifier used to debounce repaint passes after manual Ctrl+Scroll zoom.
/// </summary>
private int _manualZoomRefreshRequestId = 0;
/// <summary>
/// Enables automatic terminal zoom behavior after startup has settled.
/// Manual Ctrl+Scroll zoom remains available regardless of this setting.
/// </summary>
private static readonly bool EnableStartupTerminalAutoZoom = true;
#endregion
#region Terminal Initialization
/// <summary>
/// Initializes the embedded terminal with the selected AI provider
/// </summary>
private async Task InitializeTerminalAsync()
{
try
{
// Determine which provider to use based on settings
bool useClaudeCodeWSL = _settings?.SelectedProvider == AiProvider.ClaudeCodeWSL;
bool useCodex = _settings?.SelectedProvider == AiProvider.Codex;
bool useCodexNative = _settings?.SelectedProvider == AiProvider.CodexNative;
bool useCursorAgent = _settings?.SelectedProvider == AiProvider.CursorAgent;
bool useCursorAgentNative = _settings?.SelectedProvider == AiProvider.CursorAgentNative;
bool useQwenCode = _settings?.SelectedProvider == AiProvider.QwenCode;
bool useOpenCode = _settings?.SelectedProvider == AiProvider.OpenCode;
bool providerAvailable = false;
if (useCursorAgentNative)
{
providerAvailable = await IsCursorAgentNativeAvailableAsync();
}
else if (useCursorAgent)
{
bool wslInstalled = await IsWslInstalledAsync();
if (wslInstalled)
{
providerAvailable = await IsCursorAgentInstalledInWslAsync();
}
}
else if (useCodexNative)
{
providerAvailable = await IsCodexNativeAvailableAsync();
}
else if (useCodex)
{
providerAvailable = await IsCodexCmdAvailableAsync();
}
else if (useClaudeCodeWSL)
{
providerAvailable = await IsClaudeCodeWSLAvailableAsync();
}
else if (useQwenCode)
{
providerAvailable = await IsQwenCodeAvailableAsync();
}
else if (useOpenCode)
{
providerAvailable = await IsOpenCodeAvailableAsync();
}
else
{
providerAvailable = await IsClaudeCmdAvailableAsync();
}
// Switch to main thread for UI operations
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
// Ensure TerminalHost is available
if (TerminalHost == null)
{
Debug.WriteLine("Error: TerminalHost is null");
return;
}
// Create the terminal panel
terminalPanel = new System.Windows.Forms.Panel
{
Dock = System.Windows.Forms.DockStyle.Fill,
BackColor = GetTerminalBackgroundColor()
};
TerminalHost.Child = terminalPanel;
if (terminalPanel?.Handle == IntPtr.Zero)
{
await Task.Delay(100);
}
terminalPanel.Resize += (s, e) => ResizeEmbeddedTerminal();
// Install low-level mouse hook to track Ctrl+Scroll zoom on the embedded terminal
// (WPF PreviewMouseWheel doesn't fire for embedded Win32 windows from other processes)
InstallMouseHook();
// Install low-level keyboard hook to intercept F5/Ctrl+F5 on the embedded terminal
// and forward them as VS debug commands (Start Debugging / Start Without Debugging)
InstallKeyboardHook();
// Wait for panel to be properly sized (not just created) - reduced timeout
int maxWaitMs = 2000; // Reduced from 5 seconds to 2 seconds
int waitedMs = 0;
while ((terminalPanel.Width < 100 || terminalPanel.Height < 100) && waitedMs < maxWaitMs)
{
await Task.Delay(50); // Reduced poll interval from 100ms to 50ms
waitedMs += 50;
}
// Start the selected provider if available, otherwise show message and use regular CMD
if (useCursorAgentNative)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.CursorAgentNative);
}
else
{
if (!_cursorAgentNativeNotificationShown)
{
_cursorAgentNativeNotificationShown = true;
ShowCursorAgentNativeInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useCursorAgent)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.CursorAgent);
}
else
{
if (!_cursorAgentNotificationShown)
{
_cursorAgentNotificationShown = true;
ShowCursorAgentInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useCodexNative)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.CodexNative);
}
else
{
if (!_codexNativeNotificationShown)
{
_codexNativeNotificationShown = true;
ShowCodexNativeInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useCodex)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.Codex);
}
else
{
if (!_codexNotificationShown)
{
_codexNotificationShown = true;
ShowCodexInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useClaudeCodeWSL)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.ClaudeCodeWSL);
}
else
{
if (!_claudeCodeWSLNotificationShown)
{
_claudeCodeWSLNotificationShown = true;
ShowClaudeCodeWSLInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useQwenCode)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.QwenCode);
}
else
{
if (!_qwenCodeNotificationShown)
{
_qwenCodeNotificationShown = true;
ShowQwenCodeInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else if (useOpenCode)
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.OpenCode);
}
else
{
if (!_openCodeNotificationShown)
{
_openCodeNotificationShown = true;
ShowOpenCodeInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
else
{
if (providerAvailable)
{
await StartEmbeddedTerminalAsync(AiProvider.ClaudeCode);
}
else
{
if (!_claudeNotificationShown)
{
_claudeNotificationShown = true;
ShowClaudeInstallationInstructions();
}
await StartEmbeddedTerminalAsync(null); // Regular CMD
}
}
}
catch (Exception ex)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
Debug.WriteLine($"Error in InitializeTerminalAsync: {ex.Message}");
Debug.WriteLine($"Stack trace: {ex.StackTrace}");
MessageBox.Show($"Failed to initialize terminal: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
/// <summary>
/// Stops the currently embedded terminal, including stale window owners left behind by wt.exe delegation.
/// </summary>
private async Task StopExistingTerminalAsync()
{
IntPtr existingTerminalHandle = terminalHandle;
Process existingProcess = cmdProcess;
int existingTerminalWindowProcessId = 0;
bool isWindowsTerminal = false;
if (existingTerminalHandle != IntPtr.Zero && IsWindow(existingTerminalHandle))
{
GetWindowThreadProcessId(existingTerminalHandle, out uint existingTerminalWindowPid);
existingTerminalWindowProcessId = (int)existingTerminalWindowPid;
isWindowsTerminal = IsWindowsTerminalProcess(existingTerminalWindowProcessId);
}
if (existingTerminalHandle != IntPtr.Zero && IsWindow(existingTerminalHandle))
{
PostMessage(existingTerminalHandle, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
// Windows Terminal needs more time to close the window and clean up
// its child processes (cmd.exe, claude, etc.) via CTRL_CLOSE_EVENT
await Task.Delay(isWindowsTerminal ? 500 : 250);
}
var terminatedProcessIds = new HashSet<int>();
// Skip killing the WindowsTerminal.exe process tree — it is a shared host
// for ALL WT windows (across VS instances). WM_CLOSE above closes only our
// specific window and lets WT terminate its child console processes.
if (existingTerminalWindowProcessId > 0 &&
existingTerminalWindowProcessId != Process.GetCurrentProcess().Id &&
!isWindowsTerminal)
{
TryTerminateProcessTree(existingTerminalWindowProcessId, terminatedProcessIds);
}
if (existingProcess != null)
{
try
{
TryTerminateProcessTree(existingProcess.Id, terminatedProcessIds);
}
catch (Exception ex)
{
Debug.WriteLine($"Error terminating previous terminal launcher: {ex.Message}");
}
finally
{
existingProcess.Dispose();
}
}
cmdProcess = null;
ResetWindowsTerminalSelectionTracking();
terminalHandle = IntPtr.Zero;
_wtTabBarHeight = 0;
_currentRunningProvider = null;
}
/// <summary>
/// Checks whether a given process ID belongs to the Windows Terminal host (WindowsTerminal.exe).
/// The WT host is a shared, single-instance process — killing it would destroy ALL WT windows
/// system-wide, including those embedded by other VS instances.
/// </summary>
private static bool IsWindowsTerminalProcess(int processId)
{
try
{
using (var process = Process.GetProcessById(processId))
{
return string.Equals(process.ProcessName, "WindowsTerminal", StringComparison.OrdinalIgnoreCase);
}
}
catch
{
return false;
}
}
/// <summary>
/// Kills a process tree once, ignoring already-terminated processes.
/// </summary>
/// <param name="processId">Root process ID to terminate</param>
/// <param name="terminatedProcessIds">Process IDs already handled in the current shutdown pass</param>
private void TryTerminateProcessTree(int processId, HashSet<int> terminatedProcessIds)
{
if (processId <= 0 ||
processId == Process.GetCurrentProcess().Id ||
terminatedProcessIds.Contains(processId))
{
return;
}
try
{
terminatedProcessIds.Add(processId);
KillProcessAndChildren(processId);
using (var process = Process.GetProcessById(processId))
{
if (!process.HasExited)
{
process.Kill();
}
}
}
catch (ArgumentException)
{
// Process already exited.
}
catch (Exception ex)
{
Debug.WriteLine($"Error terminating process tree {processId}: {ex.Message}");
}
}
/// <summary>
/// Applies the window styles required for the embedded terminal host.
/// </summary>
/// <param name="forceChildWindowStyle">
/// True for hosts that behave well as WS_CHILD windows.
/// False for classic conhost/cmd.exe, which loses input/focus when forced into child style.
/// </param>
private void ApplyEmbeddedTerminalWindowStyle(bool forceChildWindowStyle)
{
if (terminalHandle == IntPtr.Zero || !IsWindow(terminalHandle))
{
return;
}
int style = GetWindowLong(terminalHandle, GWL_STYLE);
style &= ~(WS_CAPTION | WS_THICKFRAME | WS_MINIMIZE | WS_MAXIMIZE | WS_SYSMENU);
if (forceChildWindowStyle)
{
style &= ~WS_POPUP;
style |= WS_CHILD;
}
SetWindowLong(terminalHandle, GWL_STYLE, style);
}
/// <summary>
/// Forces the embedded terminal and its host panel to repaint after layout changes.
/// </summary>
private void RefreshEmbeddedTerminalWindow()
{
if (terminalHandle == IntPtr.Zero || !IsWindow(terminalHandle))
{
return;
}
var panel = ActiveTerminalPanel;
panel?.Invalidate();
panel?.Update();
InvalidateRect(terminalHandle, IntPtr.Zero, true);
RedrawWindow(terminalHandle, IntPtr.Zero, IntPtr.Zero,
RDW_INVALIDATE | RDW_ERASE | RDW_FRAME | RDW_ALLCHILDREN | RDW_UPDATENOW);
UpdateWindow(terminalHandle);
}
/// <summary>
/// Returns true when the current embedded terminal still matches the deferred startup operation.
/// </summary>
private bool IsCurrentTerminalSession(int expectedSessionId, IntPtr expectedHandle)
{
return expectedSessionId == _terminalStartupSessionId &&
expectedHandle != IntPtr.Zero &&
terminalHandle == expectedHandle &&
IsWindow(expectedHandle);
}
/// <summary>
/// Runs a few delayed resize passes so the embedded terminal catches up after startup or zoom changes.
/// </summary>
private async Task StabilizeEmbeddedTerminalLayoutAsync(int expectedSessionId, IntPtr expectedHandle)
{
int[] delays = { 120, 250, 500 };
foreach (int delayMs in delays)
{
await Task.Delay(delayMs);
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!IsCurrentTerminalSession(expectedSessionId, expectedHandle))
{
return;
}
ResizeEmbeddedTerminal();
}
}
/// <summary>
/// Schedules a few delayed repaint/layout passes after manual Ctrl+Scroll zoom.
/// Conhost and Windows Terminal both apply font zoom asynchronously, so an immediate resize
/// is often too early and leaves stale black regions until another user action occurs.
/// </summary>
private void ScheduleManualZoomRefresh()
{
int requestId = Interlocked.Increment(ref _manualZoomRefreshRequestId);
#pragma warning disable VSSDK007 // fire-and-forget is intentional to keep wheel handling responsive
_ = ThreadHelper.JoinableTaskFactory.RunAsync(async delegate
{
int[] delays = { 80, 180, 360 };
try
{
foreach (int delayMs in delays)
{
await Task.Delay(delayMs);
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (requestId != _manualZoomRefreshRequestId ||
terminalHandle == IntPtr.Zero ||
!IsWindow(terminalHandle))
{
return;
}
ResizeEmbeddedTerminal();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error refreshing terminal after manual zoom: {ex.Message}");
}
});
#pragma warning restore VSSDK007
}
/// <summary>
/// Schedules startup-only terminal adjustments after the terminal host has fully settled.
/// This keeps initial tool window load responsive while still restoring the expected zoom.
/// </summary>
private void SchedulePostStartupTerminalAdjustments()
{
int expectedSessionId = Interlocked.Increment(ref _terminalStartupSessionId);
IntPtr expectedHandle = terminalHandle;
#pragma warning disable VSSDK007 // fire-and-forget is intentional to keep terminal startup responsive
_ = ThreadHelper.JoinableTaskFactory.RunAsync(async delegate
{
try
{
await StabilizeEmbeddedTerminalLayoutAsync(expectedSessionId, expectedHandle);
if (!EnableStartupTerminalAutoZoom)
{
return;
}
await Task.Delay(1200);
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!IsCurrentTerminalSession(expectedSessionId, expectedHandle))
{
return;
}
if (_wtTabBarHeight > 0)
{
await ApplyWindowsTerminalZoomOutAsync();
}
if (!IsCurrentTerminalSession(expectedSessionId, expectedHandle))
{
return;
}
if (_settings?.TerminalZoomDelta != 0)
{
await ApplyTerminalZoomDeltaAsync(_settings.TerminalZoomDelta, initialDelayMs: 0);
}
if (!IsCurrentTerminalSession(expectedSessionId, expectedHandle))
{
return;
}
ResizeEmbeddedTerminal();
await Task.Delay(250);
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (!IsCurrentTerminalSession(expectedSessionId, expectedHandle))
{
return;
}
ResizeEmbeddedTerminal();
}
catch (Exception ex)
{
Debug.WriteLine($"Error applying deferred startup terminal adjustments: {ex.Message}");
}
});
#pragma warning restore VSSDK007
}
/// <summary>
/// Starts and embeds the terminal process (Claude Code, Claude Code WSL, Codex, Cursor Agent, or regular CMD)
/// </summary>
/// <param name="provider">The AI provider to start (null for regular CMD)</param>
private async Task StartEmbeddedTerminalAsync(AiProvider? provider)
{
bool terminalLifecycleLockHeld = false;
try
{
await _terminalLifecycleSemaphore.WaitAsync();
terminalLifecycleLockHeld = true;
string workspaceDir = await GetWorkspaceDirectoryAsync();
if (string.IsNullOrEmpty(workspaceDir))
{
workspaceDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
_lastWorkspaceDirectory = workspaceDir;
await StopExistingTerminalAsync();
// Check if we should use Windows Terminal instead of Command Prompt
bool useWindowsTerminal = _settings?.SelectedTerminalType == TerminalType.WindowsTerminal;
if (useWindowsTerminal)
{
// Windows Terminal mode: launch wt.exe with embedded cmd.exe
// Build the command for cmd.exe that will run inside WT
string cmdCommand;
switch (provider)
{
case AiProvider.CursorAgentNative:
string cursorAgentCommand = GetCursorAgentCommand();
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {cursorAgentCommand}";
break;
case AiProvider.CursorAgent:
string wslPathCursor = ConvertToWslPath(workspaceDir);
cmdCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathCursor}' && cursor-agent\"";
break;
case AiProvider.CodexNative:
string codexCommand = GetCodexCommand();
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {codexCommand}";
break;
case AiProvider.Codex:
string wslPathCodex = ConvertToWslPath(workspaceDir);
string codexWslCommand = GetCodexCommand(isWsl: true);
cmdCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathCodex}' && {codexWslCommand}\"";
break;
case AiProvider.ClaudeCodeWSL:
string wslPathClaude = ConvertToWslPath(workspaceDir);
string claudeWslCommand = GetClaudeCommand(isWsl: true);
cmdCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathClaude}' && {claudeWslCommand}\"";
break;
case AiProvider.ClaudeCode:
string claudeCommand = GetClaudeCommand();
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {claudeCommand}";
break;
case AiProvider.QwenCode:
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && qwen";
break;
case AiProvider.OpenCode:
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && opencode";
break;
default: // null or any other value = regular CMD
cmdCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\"";
break;
}
// Snapshot existing WT windows before launching a new one
var existingWtWindows = SnapshotExistingWtWindows();
// Resolve wt.exe path if not already cached
if (string.IsNullOrEmpty(_wtExePath))
{
await IsWindowsTerminalAvailableAsync();
}
string wtFileName = !string.IsNullOrEmpty(_wtExePath) ? _wtExePath : "wt.exe";
// Start Windows Terminal with embedded cmd.exe
var wtStartInfo = new ProcessStartInfo
{
FileName = wtFileName,
Arguments = $"--window new -- cmd.exe {cmdCommand}",
UseShellExecute = false,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = workspaceDir
};
// Refresh PATH from registry
string freshPath = GetFreshPathFromRegistry();
if (!string.IsNullOrEmpty(freshPath))
{
wtStartInfo.EnvironmentVariables["PATH"] = freshPath;
}
await Task.Run(() =>
{
try
{
cmdProcess = new Process { StartInfo = wtStartInfo };
cmdProcess.Start();
}
catch (Exception ex)
{
Debug.WriteLine($"Error starting Windows Terminal process: {ex.Message}");
throw;
}
});
if (cmdProcess == null)
{
throw new InvalidOperationException("Failed to create Windows Terminal process");
}
// Find the new WT window (not in the existing snapshot)
var hwnd = await FindNewWtWindowAsync(existingWtWindows, timeoutMs: 15000);
terminalHandle = hwnd;
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (terminalHandle != IntPtr.Zero && IsWindow(terminalHandle))
{
if (terminalPanel?.Handle == null || terminalPanel.Handle == IntPtr.Zero)
{
return;
}
try
{
// Hide the window immediately to prevent blinking
ShowWindow(terminalHandle, SW_HIDE);
ApplyEmbeddedTerminalWindowStyle(forceChildWindowStyle: true);
// Embed the window
SetParent(terminalHandle, terminalPanel.Handle);
// Calculate tab bar height
_wtTabBarHeight = GetWtTabBarHeight();
// Show and resize
ShowWindow(terminalHandle, SW_SHOW);
ResizeEmbeddedTerminal();
// Track the currently running provider
_currentRunningProvider = provider;
// If terminal should be detached, re-parent to detached panel
if (_isTerminalDetached && _detachedTerminalPanel != null)
{
SetParent(terminalHandle, _detachedTerminalPanel.Handle);
ShowWindow(terminalHandle, SW_SHOW);
ResizeEmbeddedTerminal();
string wtProviderName = GetCurrentProviderName();
_detachedTerminalWindow?.UpdateCaption(wtProviderName);
}
SchedulePostStartupTerminalAdjustments();
}
catch (Exception ex)
{
Debug.WriteLine($"Error embedding Windows Terminal: {ex.Message}");
throw;
}
}
else
{
throw new InvalidOperationException("Failed to find Windows Terminal window");
}
}
else
{
// Command Prompt mode (original code path)
_wtTabBarHeight = 0;
// Build the terminal command based on provider
string terminalCommand;
switch (provider)
{
case AiProvider.CursorAgentNative:
string cursorAgentCommand = GetCursorAgentCommand();
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {cursorAgentCommand}";
break;
case AiProvider.CursorAgent:
string wslPathCursor = ConvertToWslPath(workspaceDir);
terminalCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathCursor}' && cursor-agent\"";
break;
case AiProvider.CodexNative:
string codexCommand = GetCodexCommand();
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {codexCommand}";
break;
case AiProvider.Codex:
string wslPathCodex = ConvertToWslPath(workspaceDir);
string codexWslCommand = GetCodexCommand(isWsl: true);
terminalCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathCodex}' && {codexWslCommand}\"";
break;
case AiProvider.ClaudeCodeWSL:
string wslPathClaude = ConvertToWslPath(workspaceDir);
string claudeWslCommand = GetClaudeCommand(isWsl: true);
terminalCommand = $"/k chcp 65001 >nul && cls && wsl bash -ic \"cd '{wslPathClaude}' && {claudeWslCommand}\"";
break;
case AiProvider.ClaudeCode:
string claudeCommand = GetClaudeCommand();
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && {claudeCommand}";
break;
case AiProvider.QwenCode:
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && qwen";
break;
case AiProvider.OpenCode:
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\" && ping localhost -n 3 >nul && cls && opencode";
break;
default: // null or any other value = regular CMD
terminalCommand = $"/k chcp 65001 >nul && cd /d \"{workspaceDir}\"";
break;
}
// Configure and start the process.
// Use conhost.exe explicitly to bypass Windows Terminal delegation.
var startInfo = new ProcessStartInfo
{
FileName = "conhost.exe",
Arguments = "-- cmd.exe " + terminalCommand,
UseShellExecute = false,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Minimized,
WorkingDirectory = workspaceDir
};
// Refresh PATH from registry
string freshPath = GetFreshPathFromRegistry();
if (!string.IsNullOrEmpty(freshPath))
{
startInfo.EnvironmentVariables["PATH"] = freshPath;
}
// Enable Virtual Terminal Processing
startInfo.EnvironmentVariables["VIRTUAL_TERMINAL_LEVEL"] = "1";
// Temporarily set console font
SaveAndSetConsoleFontRegistry();
await Task.Run(() =>
{
try
{
cmdProcess = new Process { StartInfo = startInfo };
cmdProcess.Start();
}
catch (Exception ex)
{
Debug.WriteLine($"Error starting process: {ex.Message}");
throw;
}
});
if (cmdProcess == null)
{
throw new InvalidOperationException("Failed to create terminal process");
}
// Find and embed the terminal window
var hwnd = await FindMainWindowHandleByConhostAsync(cmdProcess.Id, timeoutMs: 5000, pollIntervalMs: 50);
// Restore original console font
RestoreConsoleFontRegistry();
terminalHandle = hwnd;
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (terminalHandle != IntPtr.Zero && IsWindow(terminalHandle))
{
if (terminalPanel?.Handle == null || terminalPanel.Handle == IntPtr.Zero)
{
return;
}
try
{
// Hide the window immediately to prevent blinking
ShowWindow(terminalHandle, SW_HIDE);
ApplyEmbeddedTerminalWindowStyle(forceChildWindowStyle: false);
// Embed the window
SetParent(terminalHandle, terminalPanel.Handle);
// Now show it in the embedded context
ShowWindow(terminalHandle, SW_SHOW);
ResizeEmbeddedTerminal();
// Track the currently running provider
_currentRunningProvider = provider;
string providerTitle;
switch (provider)
{
case AiProvider.CursorAgentNative:
providerTitle = "Cursor Agent";
break;
case AiProvider.CursorAgent:
providerTitle = "Cursor Agent";
break;
case AiProvider.CodexNative:
providerTitle = "Codex";
break;