Repository navigation
Expand file tree
/
Copy pathConsoleUI.cs
More file actions
1346 lines (1188 loc) · 46.2 KB
/
Copy pathConsoleUI.cs
File metadata and controls
1346 lines (1188 loc) · 46.2 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.Collections.Concurrent;
using System.Text;
using RalphController.Models;
using RalphController.Parallel;
using Spectre.Console;
namespace RalphController;
/// <summary>
/// Rich console UI using Spectre.Console
/// </summary>
public class ConsoleUI : IDisposable
{
private readonly LoopController? _controller;
private readonly FileWatcher _fileWatcher;
private readonly RalphConfig _config;
private readonly ConcurrentQueue<string> _outputLines = new();
private readonly StringBuilder _streamBuffer = new();
private readonly object _bufferLock = new();
private int _maxOutputLines = 30;
private CancellationTokenSource? _uiCts;
private Task? _inputTask;
private bool _disposed;
private int _lastConsoleWidth;
private int _lastConsoleHeight;
private bool _isInInjectMode;
private string _injectInput = "";
private int _injectStep; // 0=prompt, 1=confirm, 2=select provider, 3=select model, 4=custom model
private string _originalPrompt = "";
private List<string> _injectOptions = new();
private int _selectedOptionIndex;
private string _selectedProvider = "";
private ModelSpec? _selectedModel;
// Teams mode fields
private readonly TeamController? _teamController;
private readonly ConcurrentDictionary<string, AgentStatistics> _agentStats = new();
private TaskStoreStatistics _queueStats = new() { Total = 0 };
/// <summary>
/// Whether to automatically start the loop when RunAsync is called
/// </summary>
public bool AutoStart { get; set; }
/// <summary>
/// Whether the UI is running in teams mode
/// </summary>
public bool IsTeamsMode => _teamController != null;
public ConsoleUI(LoopController controller, FileWatcher fileWatcher, RalphConfig config)
{
_controller = controller;
_fileWatcher = fileWatcher;
_config = config;
// Subscribe to controller events - ANSI codes will be converted to Spectre markup
// Buffer streaming output and emit complete lines
_controller.OnOutput += text => AddStreamingOutput(text);
_controller.OnError += line => AddOutputLine(line, isRawOutput: true, isError: true);
_controller.OnIterationStart += (iter, modelName) =>
{
var modelSuffix = modelName != null ? $" [[{Markup.Escape(modelName)}]]" : "";
AddOutputLine($"[blue]>>> Starting iteration {iter}{modelSuffix}[/]");
};
_controller.OnIterationComplete += (iter, result) =>
{
FlushStreamBuffer(); // Flush any remaining buffered output
var status = result.Success ? "[green]SUCCESS[/]" : "[red]FAILED[/]";
AddOutputLine($"[blue]<<< Iteration {iter} complete: {status}[/]");
};
}
/// <summary>
/// Constructor for teams mode
/// </summary>
public ConsoleUI(TeamController teamController, FileWatcher fileWatcher, RalphConfig config)
{
_teamController = teamController;
_fileWatcher = fileWatcher;
_config = config;
WireTeamControllerEvents();
}
/// <summary>
/// Start the UI and run until stopped
/// </summary>
public async Task RunAsync(CancellationToken cancellationToken = default)
{
_uiCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
// Track initial console size
_lastConsoleWidth = Console.WindowWidth;
_lastConsoleHeight = Console.WindowHeight;
// Calculate initial max output lines based on available space
UpdateMaxOutputLines();
// Start input handler on background thread
_inputTask = Task.Run(() => HandleInputAsync(_uiCts.Token), _uiCts.Token);
if (IsTeamsMode)
{
// Auto-start the team controller
if (AutoStart && _teamController!.State == TeamControllerState.Idle)
{
_ = _teamController.StartAsync().ContinueWith(t =>
{
if (t.Exception != null)
AddOutputLine($"[red]ERR: Teams failed: {Markup.Escape(t.Exception.InnerException?.Message ?? t.Exception.Message)}[/]");
}, TaskContinuationOptions.OnlyOnFaulted);
AddOutputLine("[green]>>> Auto-starting teams...[/]");
}
// Run the live display with teams layout
await AnsiConsole.Live(BuildTeamsLayout())
.AutoClear(false)
.Overflow(VerticalOverflow.Ellipsis)
.StartAsync(async ctx =>
{
while (!_uiCts.Token.IsCancellationRequested)
{
if (Console.WindowWidth != _lastConsoleWidth || Console.WindowHeight != _lastConsoleHeight)
{
_lastConsoleWidth = Console.WindowWidth;
_lastConsoleHeight = Console.WindowHeight;
UpdateMaxOutputLines();
AnsiConsole.Clear();
}
ctx.UpdateTarget(BuildTeamsLayout());
ctx.Refresh();
await Task.Delay(100, _uiCts.Token).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
});
}
else
{
// Auto-start the loop if enabled
if (AutoStart && _controller!.State == LoopState.Idle)
{
_ = _controller.StartAsync();
AddOutputLine("[green]>>> Auto-starting loop...[/]");
}
// Run the live display
await AnsiConsole.Live(BuildLayout())
.AutoClear(false)
.Overflow(VerticalOverflow.Ellipsis)
.StartAsync(async ctx =>
{
while (!_uiCts.Token.IsCancellationRequested)
{
// Check for console resize
if (Console.WindowWidth != _lastConsoleWidth || Console.WindowHeight != _lastConsoleHeight)
{
_lastConsoleWidth = Console.WindowWidth;
_lastConsoleHeight = Console.WindowHeight;
// Recalculate max output lines based on available space
UpdateMaxOutputLines();
// Clear and redraw on resize
AnsiConsole.Clear();
}
ctx.UpdateTarget(BuildLayout());
ctx.Refresh();
await Task.Delay(100, _uiCts.Token).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
});
}
}
/// <summary>
/// Stop the UI
/// </summary>
public void Stop()
{
_uiCts?.Cancel();
}
/// <summary>
/// Calculate the maximum number of output lines based on available console height
/// </summary>
private void UpdateMaxOutputLines()
{
// Layout structure:
// - Header: Size(3) - includes border, ~1 line content
// - Main section:
// - Output: Ratio(4) - gets remaining space after Plan
// - Plan: Size(6) - fixed at 6 lines including border
// - Footer: Size(3) - includes border, ~1 line content
//
// Calculation:
// Main section height = TotalHeight - Header(3) - Footer(3) = TotalHeight - 6
// Output panel height = MainHeight - Plan(6) = TotalHeight - 12
// Output content area = OutputHeight - border(2) = TotalHeight - 14
var totalHeight = Console.WindowHeight;
var reservedSpace = 14; // Header(3) + Plan(6) + Footer(3) + Output border(2)
var availableForOutput = totalHeight - reservedSpace;
// Ensure minimum of 10 lines and maximum reasonable limit
_maxOutputLines = Math.Max(10, Math.Min(availableForOutput, 200));
}
private Layout BuildLayout()
{
// If in inject mode, show a special overlay layout
if (_isInInjectMode)
{
return BuildInjectLayout();
}
var layout = new Layout("Root")
.SplitRows(
new Layout("Header").Size(3),
new Layout("Main").SplitRows(
new Layout("Output").Ratio(4),
new Layout("Plan").Size(6)
),
new Layout("Footer").Size(3)
);
layout["Header"].Update(BuildHeaderPanel());
layout["Output"].Update(BuildOutputPanel());
layout["Plan"].Update(BuildPlanPanel());
layout["Footer"].Update(BuildFooterPanel());
return layout;
}
private Layout BuildInjectLayout()
{
var layout = new Layout("Root").SplitRows(
new Layout("Title").Size(8),
new Layout("Content"),
new Layout("Footer").Size(3)
);
// Title - centered INJECT text with larger display
var titleStyle = new Style(Color.Yellow, Color.Black).Decoration(Decoration.Bold);
var titlePanel = new Panel(
Align.Center(
new Text("INJECT", titleStyle).Centered(),
VerticalAlignment.Middle
)
)
.Border(BoxBorder.Double)
.BorderColor(Color.Yellow)
.Expand();
layout["Title"].Update(titlePanel);
// Content based on step
string content = _injectStep switch
{
0 => $"[bold yellow]Enter prompt to inject:[/]\n\n[yellow]> {Markup.Escape(_injectInput)}_[/]",
1 => BuildModelConfirmationContent(),
2 => BuildProviderSelectionContent(),
3 => BuildModelSelectionContent(),
4 => $"[bold yellow]Enter custom model name:[/]\n\n[yellow]Provider:[/] {Markup.Escape(_selectedProvider)}\n[yellow]> {Markup.Escape(_injectInput)}_[/]",
_ => ""
};
layout["Content"].Update(new Panel(new Markup(content)).Border(BoxBorder.Rounded).BorderColor(Color.Yellow).Expand());
// Footer with instructions
string footer = _injectStep switch
{
0 => "[dim]Type | Enter=Submit | Esc=Cancel[/]",
1 => "[dim]Y=Different model | N=Use current | Esc=Cancel[/]",
2 => "[dim]↑↓ Navigate | Enter=Select | Esc=Cancel[/]",
3 => "[dim]↑↓ Navigate | Enter=Select | Esc=Cancel[/]",
4 => "[dim]Type model name | Enter=Submit | Esc=Cancel[/]",
_ => ""
};
layout["Footer"].Update(new Panel(new Markup(footer).Centered()).Border(BoxBorder.Rounded).BorderColor(Color.Grey).Expand());
return layout;
}
private string BuildProviderSelectionContent()
{
var sb = new System.Text.StringBuilder();
sb.AppendLine("[bold yellow]Select provider:[/]");
sb.AppendLine();
for (int i = 0; i < _injectOptions.Count; i++)
{
var isSelected = i == _selectedOptionIndex;
var prefix = isSelected ? "[yellow]>[/] " : " ";
var optionText = Markup.Escape(_injectOptions[i]);
var formattedOption = isSelected ? $"[bold yellow]{optionText}[/]" : optionText;
sb.AppendLine($"{prefix}{formattedOption}");
}
return sb.ToString();
}
private string BuildModelSelectionContent()
{
var sb = new System.Text.StringBuilder();
sb.AppendLine($"[bold yellow]Select {Markup.Escape(_selectedProvider)} model:[/]");
sb.AppendLine();
int visibleStart = Math.Max(0, _selectedOptionIndex - 4);
int visibleEnd = Math.Min(_injectOptions.Count, _selectedOptionIndex + 5);
for (int i = visibleStart; i < visibleEnd; i++)
{
var isSelected = i == _selectedOptionIndex;
var prefix = isSelected ? "[yellow]>[/] " : " ";
var optionText = Markup.Escape(_injectOptions[i]);
var formattedOption = isSelected ? $"[bold yellow]{optionText}[/]" : optionText;
sb.AppendLine($"{prefix}{formattedOption}");
}
if (_injectOptions.Count > 8)
{
sb.AppendLine($"[dim]... ({_injectOptions.Count - 8} more)[/]");
}
return sb.ToString();
}
private string BuildModelConfirmationContent()
{
var currentModel = _controller!.ModelSelector.GetCurrentModel();
var modelName = currentModel?.DisplayName ?? _config.Provider.ToString();
var safePrompt = string.IsNullOrEmpty(_originalPrompt) ? "(empty)" : _originalPrompt;
var promptPreview = safePrompt.Length > 60
? safePrompt[..60] + "..."
: safePrompt;
return $"[bold yellow]Current model:[/] [green]{Markup.Escape(modelName)}[/]\n\n[yellow]Your prompt:[/] {Markup.Escape(promptPreview)}\n\n[bold]Use different model?[/] [dim](Y/N)[/]";
}
private Panel BuildHeaderPanel()
{
var state = _controller!.State;
var stats = _controller.Statistics;
var provider = _config.Provider;
// Get current model name for multi-model mode
var currentModel = _controller.ModelSelector.GetCurrentModel();
var modelDisplay = (_config.MultiModel?.IsEnabled == true && currentModel != null)
? $" [[{Markup.Escape(currentModel.DisplayName)}]]"
: "";
var stateColor = state switch
{
LoopState.Running => "green",
LoopState.Paused => "yellow",
LoopState.Stopping => "red",
_ => "grey"
};
var table = new Table()
.Border(TableBorder.None)
.HideHeaders()
.AddColumn("")
.AddColumn("")
.AddColumn("")
.AddColumn("");
table.AddRow(
$"[bold blue]RALPH CONTROLLER[/]",
$"[{stateColor}][[{state.ToString().ToUpper()}]][/]",
$"[white]Iteration #{stats.CurrentIteration}{modelDisplay}[/]",
$"[dim]{provider}[/]"
);
table.AddRow(
$"[dim]{Markup.Escape(_config.TargetDirectory)}[/]",
$"[dim]Duration: {stats.FormatDuration(stats.TotalDuration)}[/]",
$"[dim]Est: {stats.FormatCost(stats.EstimatedCost)}[/]",
_fileWatcher.PromptChanged ? "[yellow]PROMPT CHANGED[/]" : ""
);
return new Panel(table)
.Border(BoxBorder.Rounded)
.BorderColor(Color.Blue);
}
private Panel BuildOutputPanel()
{
var lines = _outputLines.ToArray();
if (lines.Length == 0)
{
return new Panel(new Markup("[dim]Waiting for output...[/]"))
.Header("[bold]Output[/]")
.Border(BoxBorder.Rounded)
.Expand();
}
// Validate each line individually - escape lines that fail markup parsing
var validatedLines = new List<string>();
foreach (var line in lines)
{
try
{
// Test if the line can be parsed as markup
_ = new Markup(line);
validatedLines.Add(line);
}
catch
{
// Line has invalid markup - escape it entirely
validatedLines.Add(Markup.Escape(line));
}
}
var content = string.Join("\n", validatedLines);
return new Panel(new Markup(content))
.Header("[bold]Output[/]")
.Border(BoxBorder.Rounded)
.Expand();
}
private Panel BuildPlanPanel()
{
var planLines = _fileWatcher.ReadPlanLinesAsync(4).GetAwaiter().GetResult();
var content = planLines.Length > 0
? string.Join("\n", planLines.Select(Markup.Escape))
: "[dim]No implementation plan found[/]";
return new Panel(new Markup(content))
.Header($"[bold]{Markup.Escape(_config.PlanFile)}[/]")
.Border(BoxBorder.Rounded);
}
private Panel BuildFooterPanel()
{
// Double brackets to escape them in Spectre.Console markup
var controls = _controller!.State switch
{
LoopState.Running => "[[P]]ause [[N]]ext [[S]]top [[F]]orce Stop [[I]]nject [[Q]]uit",
LoopState.Paused => "[[R]]esume [[S]]top [[I]]nject [[Q]]uit",
LoopState.Idle => "[[Enter]] Start [[Q]]uit",
LoopState.Stopping => "[[F]]orce Stop [[Q]]uit",
_ => "[[Q]]uit"
};
return new Panel(new Markup($"[bold]{controls}[/]"))
.Border(BoxBorder.Rounded)
.BorderColor(Color.Grey);
}
private async Task HandleInputAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(intercept: true);
await HandleKeyAsync(key);
}
await Task.Delay(50, cancellationToken).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}
}
private async Task HandleKeyAsync(ConsoleKeyInfo key)
{
// Handle inject mode input (single-agent only)
if (_isInInjectMode)
{
await HandleInjectInput(key);
return;
}
// Dispatch to teams key handler if in teams mode
if (IsTeamsMode)
{
await HandleTeamsKeyAsync(key);
return;
}
// Normal mode handling (single-agent only)
switch (char.ToLower(key.KeyChar))
{
case 'p':
if (_controller!.State == LoopState.Running)
{
_controller.Pause();
AddOutputLine("[yellow]>>> Loop paused[/]");
}
break;
case 'r':
if (_controller!.State == LoopState.Paused)
{
_controller.Resume();
AddOutputLine("[green]>>> Loop resumed[/]");
}
break;
case 'n':
if (_controller!.State == LoopState.Running)
{
_controller.SkipIteration();
AddOutputLine("[yellow]>>> Skipping to next iteration...[/]");
}
break;
case 's':
if (_controller!.State == LoopState.Running || _controller.State == LoopState.Paused)
{
_controller.Stop();
AddOutputLine("[red]>>> Stopping after current iteration...[/]");
}
break;
case 'f':
if (_controller!.State != LoopState.Idle)
{
await _controller.ForceStopAsync();
AddOutputLine("[red]>>> Force stopped![/]");
}
break;
case 'i':
StartInjectMode();
break;
case 'q':
Stop();
break;
case '\r':
case '\n':
if (_controller!.State == LoopState.Idle)
{
// Start loop in background
_ = _controller.StartAsync();
AddOutputLine("[green]>>> Starting loop...[/]");
}
break;
}
}
private void StartInjectMode()
{
_isInInjectMode = true;
_injectStep = 0;
_injectInput = "";
_originalPrompt = "";
_selectedOptionIndex = 0;
_selectedProvider = "";
_selectedModel = null;
_injectOptions = new List<string>();
}
private void EndInjectMode()
{
_isInInjectMode = false;
_injectStep = 0;
_injectInput = "";
_originalPrompt = "";
_selectedOptionIndex = 0;
_selectedProvider = "";
_selectedModel = null;
_injectOptions = new List<string>();
}
private async Task HandleInjectInput(ConsoleKeyInfo key)
{
// Handle Escape to cancel
if (key.Key == ConsoleKey.Escape)
{
EndInjectMode();
return;
}
// Handle Enter based on step
if (key.Key == ConsoleKey.Enter)
{
await SubmitInjectStep();
return;
}
// Step 0: Text input for prompt
if (_injectStep == 0)
{
if (key.Key == ConsoleKey.Backspace)
{
if (_injectInput.Length > 0)
_injectInput = _injectInput[..^1];
}
else if (!char.IsControl(key.KeyChar))
{
_injectInput += key.KeyChar;
}
return;
}
// Step 1: Y/N confirmation
if (_injectStep == 1)
{
char c = char.ToLower(key.KeyChar);
if (c == 'y')
{
// Move to provider selection
_injectStep = 2;
_selectedOptionIndex = 0;
PopulateProviderOptions();
}
else if (c == 'n')
{
// Use current model
_controller!.InjectPrompt(_originalPrompt);
AddOutputLine($"[yellow]>>> Prompt: {Markup.Escape(_originalPrompt.Length > 50 ? _originalPrompt[..50] + "..." : _originalPrompt)}[/]");
EndInjectMode();
}
return;
}
// Step 4: Custom model name input
if (_injectStep == 4)
{
if (key.Key == ConsoleKey.Backspace)
{
if (_injectInput.Length > 0)
_injectInput = _injectInput[..^1];
}
else if (!char.IsControl(key.KeyChar))
{
_injectInput += key.KeyChar;
}
return;
}
// Steps 2 & 3: Arrow key navigation
if (_injectStep == 2 || _injectStep == 3)
{
if (key.Key == ConsoleKey.UpArrow || key.Key == ConsoleKey.LeftArrow)
{
_selectedOptionIndex = Math.Max(0, _selectedOptionIndex - 1);
}
else if (key.Key == ConsoleKey.DownArrow || key.Key == ConsoleKey.RightArrow)
{
_selectedOptionIndex = Math.Min(_injectOptions.Count - 1, _selectedOptionIndex + 1);
}
return;
}
}
private void PopulateProviderOptions()
{
_injectOptions = new List<string>
{
"Claude",
"Codex",
"Copilot",
"Gemini",
"Cursor",
"OpenCode",
"Ollama"
};
}
private async Task PopulateModelOptionsAsync()
{
_injectOptions = new List<string>();
_selectedOptionIndex = 0;
switch (_selectedProvider)
{
case "Claude":
_injectOptions.AddRange(new[] { "sonnet", "opus", "haiku", "Enter custom..." });
break;
case "Codex":
_injectOptions.AddRange(new[] { "o3", "o1", "gpt-5.3-codex", "gpt-5.2-codex", "gpt-5.1-codex", "Enter custom..." });
break;
case "Copilot":
try
{
await using var sdkClient = new GitHub.Copilot.SDK.CopilotClient();
await sdkClient.StartAsync();
var sdkModels = await sdkClient.ListModelsAsync();
var ids = sdkModels.Select(m => m.Id).Where(id => !string.IsNullOrEmpty(id)).ToList();
if (ids.Count > 0)
{
_injectOptions.AddRange(ids!);
}
else
{
_injectOptions.AddRange(new[] { "gpt-5", "gpt-5-mini", "gpt-5.1", "gpt-5.2", "gpt-5.3", "claude-sonnet-4.5", "claude-opus-4.5", "claude-opus-4.6", "gemini-2.5-pro" });
}
}
catch
{
_injectOptions.AddRange(new[] { "gpt-5", "gpt-5-mini", "gpt-5.1", "gpt-5.2", "gpt-5.3", "claude-sonnet-4.5", "claude-opus-4.5", "claude-opus-4.6", "gemini-2.5-pro" });
}
_injectOptions.Add("Enter custom...");
break;
case "Gemini":
_injectOptions.AddRange(new[] { "gemini-2.5-pro", "gemini-2.0-flash", "Enter custom..." });
break;
case "Cursor":
_injectOptions.AddRange(new[] { "claude-sonnet", "claude-opus", "gpt-4o", "Enter custom..." });
break;
case "OpenCode":
_injectOptions.AddRange(new[] { "ollama/llama3.1:70b", "ollama/deepseek-r1:32b", "ollama/qwen2.5:72b", "Enter custom..." });
break;
case "Ollama":
_injectOptions.AddRange(new[] { "llama3.1:8b", "llama3.1:70b", "deepseek-r1:32b", "qwen2.5:72b", "Enter custom..." });
break;
}
}
private async Task SubmitInjectStep()
{
switch (_injectStep)
{
case 0: // Prompt entry complete
if (!string.IsNullOrWhiteSpace(_injectInput))
{
_originalPrompt = _injectInput;
_injectInput = "";
_injectStep = 1;
}
else
{
EndInjectMode();
}
break;
case 2: // Provider selected
_selectedProvider = _injectOptions[_selectedOptionIndex];
_injectStep = 3;
_selectedOptionIndex = 0;
await PopulateModelOptionsAsync();
break;
case 3: // Model selected
var modelName = _injectOptions[_selectedOptionIndex];
if (modelName == "Enter custom...")
{
// Move to custom model input
_injectStep = 4;
_injectInput = "";
}
else
{
var provider = Enum.Parse<AIProvider>(_selectedProvider, true);
_selectedModel = new ModelSpec
{
Provider = provider,
Model = modelName,
Label = modelName
};
_controller!.InjectPrompt(_originalPrompt, _selectedModel);
AddOutputLine($"[yellow]>>> Injected with model: {Markup.Escape($"{_selectedProvider}/{modelName}")}[/]");
AddOutputLine($"[yellow]>>> Prompt: {Markup.Escape(_originalPrompt.Length > 50 ? _originalPrompt[..50] + "..." : _originalPrompt)}[/]");
EndInjectMode();
}
break;
case 4: // Custom model name entered
if (!string.IsNullOrWhiteSpace(_injectInput))
{
var provider = Enum.Parse<AIProvider>(_selectedProvider, true);
_selectedModel = new ModelSpec
{
Provider = provider,
Model = _injectInput,
Label = _injectInput
};
_controller!.InjectPrompt(_originalPrompt, _selectedModel);
AddOutputLine($"[yellow]>>> Injected with model: {Markup.Escape($"{_selectedProvider}/{_injectInput}")}[/]");
AddOutputLine($"[yellow]>>> Prompt: {Markup.Escape(_originalPrompt.Length > 50 ? _originalPrompt[..50] + "..." : _originalPrompt)}[/]");
EndInjectMode();
}
break;
}
}
private void AddOutputLine(string line, bool isRawOutput = false, bool isError = false)
{
// Skip empty lines to save space
if (string.IsNullOrWhiteSpace(line))
return;
// Only process raw AI output - internal messages already have Spectre markup
if (isRawOutput)
{
// First, strip ALL ANSI escape sequences completely (including cursor movement, clear screen, etc.)
line = StripAllAnsiSequences(line);
// Escape any Spectre markup characters in the raw output
line = Markup.Escape(line);
// Prefix with "OUT:" to show it's AI output
line = $"[green]OUT:[/] {line}";
// If it's an error and doesn't have any color markup, wrap in red
if (isError)
{
line = $"[red]ERR: {Markup.Escape(line)}[/]";
}
}
// Remove control characters that can mess up the layout
line = new string(line.Where(c => !char.IsControl(c) || c == ' ').ToArray());
// Truncate long lines to prevent layout issues
var maxLineLength = Math.Max(40, Console.WindowWidth - 15);
if (line.Length > maxLineLength)
{
// Find a safe truncation point (not inside markup)
var truncated = TruncatePreservingMarkup(line, maxLineLength);
line = truncated + "...";
}
_outputLines.Enqueue(line);
// Keep only last N lines
while (_outputLines.Count > _maxOutputLines)
{
_outputLines.TryDequeue(out _);
}
}
private void AddStreamingOutput(string text)
{
if (string.IsNullOrEmpty(text))
return;
lock (_bufferLock)
{
_streamBuffer.Append(text);
// Process complete lines
var content = _streamBuffer.ToString();
var lastNewline = content.LastIndexOf('\n');
if (lastNewline >= 0)
{
// Extract complete lines
var completeLines = content.Substring(0, lastNewline);
var remainder = content.Substring(lastNewline + 1);
// Clear buffer and keep remainder
_streamBuffer.Clear();
_streamBuffer.Append(remainder);
// Add each complete line
foreach (var line in completeLines.Split('\n'))
{
AddOutputLine(line, isRawOutput: true);
}
}
else if (_streamBuffer.Length > 200)
{
// Buffer getting large without newlines - flush as partial line
var partial = _streamBuffer.ToString();
_streamBuffer.Clear();
AddOutputLine(partial, isRawOutput: true);
}
}
}
/// <summary>
/// Flush any remaining buffered streaming content
/// </summary>
public void FlushStreamBuffer()
{
lock (_bufferLock)
{
if (_streamBuffer.Length > 0)
{
AddOutputLine(_streamBuffer.ToString(), isRawOutput: true);
_streamBuffer.Clear();
}
}
}
/// <summary>
/// Strip ALL ANSI escape sequences from a string (cursor movement, colors, clear screen, etc.)
/// This is more aggressive than ConvertAnsiToMarkup and removes everything
/// </summary>
private static string StripAllAnsiSequences(string input)
{
if (string.IsNullOrEmpty(input))
return input;
var result = new System.Text.StringBuilder();
var i = 0;
while (i < input.Length)
{
// Check for ANSI escape sequence (ESC followed by [ or other control chars)
if (input[i] == '\x1B')
{
// Skip the escape character and find the end of the sequence
i++;
if (i < input.Length && input[i] == '[')
{
// CSI sequence - skip until we hit a letter (the command)
i++;
while (i < input.Length && !char.IsLetter(input[i]))
i++;
if (i < input.Length)
i++; // Skip the command letter too
}
else if (i < input.Length)
{
// Other escape sequence - skip next character
i++;
}
continue;
}
// Skip other problematic control characters
if (input[i] == '\r')
{
i++;
continue;
}
result.Append(input[i]);
i++;
}
return result.ToString();
}
private static string ConvertAnsiToMarkup(string input)
{
// Only convert ANSI escape codes to Spectre markup
// Leave everything else unchanged - BuildOutputPanel validates per-line
var result = new System.Text.StringBuilder();
var i = 0;
while (i < input.Length)
{
// Check for ANSI escape sequence (ESC[...m)
if (i < input.Length - 1 && input[i] == '\x1B' && input[i + 1] == '[')
{
var start = i + 2;
var end = start;
while (end < input.Length && !char.IsLetter(input[end]))
end++;
if (end < input.Length && input[end] == 'm')
{
var code = input[start..end];
var markup = AnsiCodeToSpectreMarkup(code);
if (markup != null)
result.Append(markup);
i = end + 1;
continue;
}
}
result.Append(input[i]);
i++;
}
return result.ToString();
}
private static string? AnsiCodeToSpectreMarkup(string code)
{
// Handle multiple codes separated by semicolon
var codes = code.Split(';');
var result = new System.Text.StringBuilder();
foreach (var c in codes)
{
if (!int.TryParse(c, out var num))
continue;
var markup = num switch
{
0 => "[/]", // Reset
1 => "[bold]",
2 => "[dim]",
3 => "[italic]",
4 => "[underline]",
30 => "[black]",
31 => "[red]",
32 => "[green]",
33 => "[yellow]",
34 => "[blue]",
35 => "[magenta]",
36 => "[cyan]",
37 => "[white]",
39 => "[/]", // Default foreground
90 => "[grey]",
91 => "[red]",
92 => "[green]",
93 => "[yellow]",
94 => "[blue]",
95 => "[magenta]",
96 => "[cyan]",
97 => "[white]",
_ => null
};
if (markup != null)
result.Append(markup);
}
return result.Length > 0 ? result.ToString() : null;
}