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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
//! Main application state and logic
use crate::events::{Action, Event, EventHandler, key_to_action};
use crate::panels::PanelId;
use crate::shell::ShellExecutor;
use crate::theme::Theme;
use crate::ui;
use anyhow::Result;
use arct_core::{CommandAnalyzer, Context, ContextDetector, Educator, Session};
use crossterm::{
event::{KeyCode, KeyEvent, KeyModifiers},
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
backend::{Backend, CrosstermBackend},
Terminal,
};
use std::collections::HashMap;
use std::io;
/// Main application state
pub struct App {
/// Whether the application should quit
pub should_quit: bool,
/// Currently active panel
pub active_panel: PanelId,
/// User session
pub session: Session,
/// Current context (project detection, etc.)
pub context: Context,
/// Command analyzer
pub analyzer: CommandAnalyzer,
/// Educator for explanations
pub educator: Educator,
/// Current theme
pub theme: Theme,
/// Event handler
event_handler: EventHandler,
/// Show help overlay
pub show_help: bool,
/// Command buffer for shell input
pub command_buffer: String,
/// Last command explanation
pub last_explanation: Option<arct_core::Explanation>,
/// Shell executor
shell_executor: ShellExecutor,
/// Last command output
pub last_output: String,
/// Output panel scroll offset
pub output_scroll: usize,
/// Command history
command_history: Vec<String>,
/// Current position in history (0 = most recent, None = not browsing)
history_position: Option<usize>,
/// Environment variables set by export command
pub environment_vars: HashMap<String, String>,
/// Command aliases (name -> command)
pub aliases: HashMap<String, String>,
/// Application configuration
pub config: arct_config::Config,
/// Autocompleter
autocompleter: crate::autocomplete::Autocompleter,
/// Current completion suggestions (shown below shell input)
pub completion_suggestions: Vec<String>,
/// AI assistant provider (if enabled)
ai_provider: Option<Box<dyn arct_ai::AIProvider>>,
/// AI conversation history
pub ai_conversation: Vec<arct_ai::Message>,
/// AI input buffer (when in AI mode)
pub ai_input_buffer: String,
/// Last AI response
pub ai_response: Option<String>,
/// AI loading state
pub ai_loading: bool,
/// AI mode enabled (toggle between shell and AI)
pub ai_mode: bool,
/// Onboarding wizard (shown on first run)
pub onboarding: Option<crate::panels::onboarding::OnboardingWizard>,
/// Settings panel (interactive)
pub settings_panel: Option<crate::panels::settings::SettingsPanel>,
/// Analytics tracker
pub analytics: Option<crate::analytics::Analytics>,
/// Current session ID
session_id: String,
/// Lesson panel for interactive lessons
pub lesson_panel: Option<crate::panels::lesson::LessonPanel>,
/// Lesson mode enabled (toggle between explanation and lesson)
pub lesson_mode: bool,
/// Virtual filesystem for lesson sandboxing
pub virtual_fs: Option<arct_core::VirtualFileSystem>,
}
impl App {
/// Create a new application
pub fn new() -> Result<Self> {
let session = Session::new();
let working_dir = session.state.working_directory.clone();
let context = ContextDetector::detect(&working_dir)?;
// Load configuration
let config = arct_config::Config::load().unwrap_or_else(|e| {
tracing::warn!("Failed to load config, using defaults: {}", e);
arct_config::Config::default()
});
// Load command history from disk
let command_history = match crate::persistence::load_session() {
Ok(session_data) => {
tracing::info!("Loaded {} commands from history", session_data.command_history.len());
session_data.command_history
}
Err(e) => {
tracing::warn!("Failed to load session history: {}", e);
Vec::new()
}
};
// Load aliases and environment variables from config
let aliases = config.shell.aliases.clone();
let environment_vars = config.shell.environment.clone();
// Select theme based on config
let theme = Theme::from_name(&config.theme.default_theme);
// Initialize AI provider if enabled
let ai_provider = if config.ai.enabled {
match Self::create_ai_provider(&config.ai) {
Ok(provider) => {
tracing::info!("AI provider initialized: {}", provider.name());
Some(provider)
}
Err(e) => {
tracing::warn!("Failed to initialize AI provider: {}", e);
None
}
}
} else {
None
};
// Check if first run (show onboarding)
let onboarding = if !config.general.setup_complete {
Some(crate::panels::onboarding::OnboardingWizard::new())
} else {
None
};
// Create welcome message for returning users
let welcome_message = if config.general.setup_complete {
let name = config.general.user_name.as_deref().unwrap_or("there");
let mut msg = format!("👋 Welcome back, {}!\n\n", name);
// Add quick tips
msg.push_str("Quick reminders:\n");
if config.ai.enabled {
msg.push_str(" • Press Ctrl+A to ask the AI for help\n");
}
msg.push_str(" • Press ? for help\n");
msg.push_str(" • Press Ctrl+S for settings\n");
msg.push_str(" • Tab to autocomplete commands\n\n");
msg.push_str("Start typing a command to begin!\n");
msg
} else {
String::new()
};
Ok(Self {
should_quit: false,
active_panel: PanelId::Shell,
session,
context,
analyzer: CommandAnalyzer::new(),
educator: Educator::new(),
theme,
event_handler: EventHandler::new(),
show_help: false,
command_buffer: String::new(),
last_explanation: None,
shell_executor: ShellExecutor::new()?,
last_output: welcome_message,
output_scroll: 0,
command_history,
history_position: None,
environment_vars,
aliases,
config,
autocompleter: crate::autocomplete::Autocompleter::new(),
completion_suggestions: Vec::new(),
ai_provider,
ai_conversation: Vec::new(),
ai_input_buffer: String::new(),
ai_response: None,
ai_loading: false,
ai_mode: false,
onboarding,
settings_panel: None,
analytics: crate::analytics::Analytics::new().ok(),
session_id: uuid::Uuid::new_v4().to_string(),
lesson_panel: Self::initialize_lesson_panel(),
lesson_mode: false,
virtual_fs: None,
})
}
/// Initialize lesson panel with first lesson loaded
fn initialize_lesson_panel() -> Option<crate::panels::lesson::LessonPanel> {
use arct_core::LessonLibrary;
let library = LessonLibrary::new();
let mut panel = crate::panels::lesson::LessonPanel::new();
// Auto-load the first lesson (Navigation Basics)
if let Some(lesson) = library.get("nav-basics") {
panel.load_lesson(lesson.clone());
Some(panel)
} else {
Some(panel) // Return empty panel if lesson not found
}
}
/// Create AI provider from configuration
fn create_ai_provider(config: &arct_config::AIConfig) -> Result<Box<dyn arct_ai::AIProvider>> {
let ai_config = match config.provider.as_str() {
"anthropic" => {
let api_key = config.api_key.clone()
.ok_or_else(|| anyhow::anyhow!("Anthropic API key not set"))?;
let model = config.model.clone()
.unwrap_or_else(|| "claude-3-5-sonnet-20241022".to_string());
arct_ai::AIConfig::Anthropic { api_key, model }
}
"openai" => {
let api_key = config.api_key.clone()
.ok_or_else(|| anyhow::anyhow!("OpenAI API key not set"))?;
let model = config.model.clone()
.unwrap_or_else(|| "gpt-4-turbo-preview".to_string());
arct_ai::AIConfig::OpenAI { api_key, model }
}
"local" => {
let endpoint = config.endpoint.clone()
.unwrap_or_else(|| "http://localhost:11434".to_string());
let model = config.model.clone();
arct_ai::AIConfig::Local { endpoint, model }
}
"managed" => {
let auth_token = config.api_key.clone()
.ok_or_else(|| anyhow::anyhow!("Managed API token not set"))?;
arct_ai::AIConfig::Managed { auth_token }
}
"claude-cli" => {
// Claude Code CLI - no API key needed
let model = config.model.clone();
arct_ai::AIConfig::ClaudeCLI { model }
}
_ => arct_ai::AIConfig::Disabled,
};
arct_ai::AIFactory::create(&ai_config)
.map_err(|e| anyhow::anyhow!("Failed to create AI provider: {}", e))
}
/// Show ASCII art splash screen
fn show_splash_screen() -> Result<()> {
use crossterm::{
cursor,
style::{Color, Print, SetForegroundColor, ResetColor},
terminal::{Clear, ClearType},
};
use std::io::Write;
let mut stdout = io::stdout();
// Clear screen
execute!(stdout, Clear(ClearType::All), cursor::MoveTo(0, 0))?;
// ASCII art logo
let logo = r#"
▄▄▄ ██▀███ ▄████▄ ▄▄▄ ▄████▄ ▄▄▄ ▓█████▄ ▓█████ ███▄ ▄███▓▓██ ██▓
▒████▄ ▓██ ▒ ██▒▒██▀ ▀█ ▒████▄ ▒██▀ ▀█ ▒████▄ ▒██▀ ██▌▓█ ▀ ▓██▒▀█▀ ██▒ ▒██ ██▒
▒██ ▀█▄ ▓██ ░▄█ ▒▒▓█ ▄ ▒██ ▀█▄ ▒▓█ ▄ ▒██ ▀█▄ ░██ █▌▒███ ▓██ ▓██░ ▒██ ██░
░██▄▄▄▄██ ▒██▀▀█▄ ▒▓▓▄ ▄██▒ ░██▄▄▄▄██ ▒▓▓▄ ▄██▒░██▄▄▄▄██ ░▓█▄ ▌▒▓█ ▄ ▒██ ▒██ ░ ▐██▓░
▓█ ▓██▒░██▓ ▒██▒▒ ▓███▀ ░ ▓█ ▓██▒▒ ▓███▀ ░ ▓█ ▓██▒░▒████▓ ░▒████▒▒██▒ ░██▒ ░ ██▒▓░
▒▒ ▓▒█░░ ▒▓ ░▒▓░░ ░▒ ▒ ░ ▒▒ ▓▒█░░ ░▒ ▒ ░ ▒▒ ▓▒█░ ▒▒▓ ▒ ░░ ▒░ ░░ ▒░ ░ ░ ██▒▒▒
▒ ▒▒ ░ ░▒ ░ ▒░ ░ ▒ ▒ ▒▒ ░ ░ ▒ ▒ ▒▒ ░ ░ ▒ ▒ ░ ░ ░░ ░ ░ ▓██ ░▒░
░ ▒ ░░ ░ ░ ░ ▒ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ▒ ▒ ░░
░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░
"#;
let tagline = "Λ° Learn Shell Commands Interactively with AI";
let version = "v0.1.0-alpha";
// Get terminal size for centering
let (width, height) = crossterm::terminal::size()?;
let start_row = (height / 2).saturating_sub(7); // Center vertically
// Calculate logo width (longest line is ~92 chars)
let logo_width = 92;
let logo_col = (width / 2).saturating_sub(logo_width / 2);
// Print logo with orange color, centered
for (i, line) in logo.lines().enumerate() {
let row = start_row + i as u16;
execute!(
stdout,
cursor::MoveTo(logo_col, row),
SetForegroundColor(Color::Rgb { r: 255, g: 140, b: 0 }), // Arc Academy Orange
Print(line),
ResetColor
)?;
}
// Print tagline centered below logo
let tagline_row = start_row + 11;
let tagline_col = (width / 2).saturating_sub((tagline.len() / 2) as u16);
execute!(
stdout,
cursor::MoveTo(tagline_col, tagline_row),
SetForegroundColor(Color::White),
Print(tagline),
ResetColor
)?;
// Print version
let version_row = tagline_row + 1;
let version_col = (width / 2).saturating_sub((version.len() / 2) as u16);
execute!(
stdout,
cursor::MoveTo(version_col, version_row),
SetForegroundColor(Color::DarkGrey),
Print(version),
ResetColor
)?;
stdout.flush()?;
// Pause for 1.5 seconds
std::thread::sleep(std::time::Duration::from_millis(1500));
// Clear screen before entering TUI
execute!(stdout, Clear(ClearType::All), cursor::MoveTo(0, 0))?;
Ok(())
}
/// Run the application
pub async fn run(&mut self) -> Result<()> {
// Show splash screen
Self::show_splash_screen()?;
// Setup terminal
enable_raw_mode()?;
let mut stdout = io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
// Start event handler
self.event_handler.start().await;
// Main loop
let result = self.main_loop(&mut terminal).await;
// Save history before exiting
self.save_history();
// Restore terminal
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
result
}
/// Main application loop
async fn main_loop<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<()> {
loop {
// Draw UI
terminal.draw(|f| ui::draw(f, self))?;
// Handle events
if let Some(event) = self.event_handler.next().await {
self.handle_event(event).await?;
}
// Check for quit
if self.should_quit {
break;
}
}
Ok(())
}
/// Handle an event
async fn handle_event(&mut self, event: Event) -> Result<()> {
match event {
Event::Key(key) => {
// If onboarding is active, handle onboarding events
if let Some(ref mut wizard) = self.onboarding {
return self.handle_onboarding_event(key).await;
}
// If settings panel is open, handle settings events
if self.settings_panel.is_some() {
return self.handle_settings_event(key).await;
}
// If in AI mode and in Shell panel, handle AI input
if self.ai_mode && self.active_panel == PanelId::Shell && !self.show_help {
match key.code {
KeyCode::Char(c) if key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT => {
self.ai_input_buffer.push(c);
return Ok(());
}
KeyCode::Backspace => {
self.ai_input_buffer.pop();
return Ok(());
}
KeyCode::Enter => {
if !self.ai_input_buffer.is_empty() {
let question = self.ai_input_buffer.clone();
self.ai_input_buffer.clear();
self.ask_ai(question).await?;
}
return Ok(());
}
_ => {}
}
}
// If in shell panel and not a special action, handle as text input or history
if self.active_panel == PanelId::Shell && !self.show_help && !self.ai_mode {
match key.code {
KeyCode::Char(c) if key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT => {
self.command_buffer.push(c);
// Reset history position when typing
self.history_position = None;
// Clear completion suggestions when typing
self.completion_suggestions.clear();
return Ok(());
}
KeyCode::Backspace => {
self.command_buffer.pop();
// Reset history position when editing
self.history_position = None;
// Clear completion suggestions when editing
self.completion_suggestions.clear();
return Ok(());
}
KeyCode::Tab if key.modifiers == KeyModifiers::NONE => {
// Tab in shell panel triggers autocomplete
self.handle_autocomplete()?;
return Ok(());
}
KeyCode::Up => {
// Navigate backward in history (older commands)
self.history_previous();
return Ok(());
}
KeyCode::Down => {
// Navigate forward in history (newer commands)
self.history_next();
return Ok(());
}
_ => {}
}
}
// Handle as action
let action = key_to_action(key);
self.handle_action(action).await?;
}
Event::Resize(_, _) => {
// Terminal will automatically redraw on next iteration
}
Event::Tick => {
// Update any time-based state here
}
Event::Quit => {
self.should_quit = true;
}
}
Ok(())
}
/// Handle an action
async fn handle_action(&mut self, action: Action) -> Result<()> {
match action {
Action::Quit => {
if self.show_help {
self.show_help = false;
} else {
self.should_quit = true;
}
}
Action::NextPanel => {
self.active_panel = self.active_panel.next();
// Reset scroll when switching panels
self.output_scroll = 0;
}
Action::PreviousPanel => {
self.active_panel = self.active_panel.previous();
// Reset scroll when switching panels
self.output_scroll = 0;
}
Action::ScrollUp => {
// Only scroll when Output panel is focused
if self.active_panel == PanelId::Output {
self.output_scroll = self.output_scroll.saturating_sub(1);
}
}
Action::ScrollDown => {
// Only scroll when Output panel is focused
if self.active_panel == PanelId::Output {
let total_lines = self.last_output.lines().count();
if self.output_scroll < total_lines.saturating_sub(1) {
self.output_scroll += 1;
}
}
}
Action::PageUp => {
// Only scroll when Output panel is focused
if self.active_panel == PanelId::Output {
self.output_scroll = self.output_scroll.saturating_sub(10);
}
}
Action::PageDown => {
// Only scroll when Output panel is focused
if self.active_panel == PanelId::Output {
let total_lines = self.last_output.lines().count();
self.output_scroll = (self.output_scroll + 10).min(total_lines.saturating_sub(1));
}
}
Action::Help => {
self.show_help = !self.show_help;
}
Action::ToggleTheme => {
self.theme = self.theme.cycle_next();
}
Action::ToggleAI => {
self.toggle_ai_mode();
}
Action::ToggleSettings => {
if self.settings_panel.is_some() {
self.settings_panel = None;
} else {
self.settings_panel = Some(crate::panels::settings::SettingsPanel::new());
}
}
Action::ToggleLesson => {
self.toggle_lesson_mode();
}
Action::Escape => {
if self.show_help {
self.show_help = false;
} else if self.settings_panel.is_some() {
self.settings_panel = None;
} else if self.ai_mode {
self.ai_mode = false;
}
}
Action::Enter => {
if !self.ai_mode {
self.execute_command().await?;
}
}
_ => {}
}
Ok(())
}
/// Execute the current command
async fn execute_command(&mut self) -> Result<()> {
if self.command_buffer.is_empty() {
return Ok(());
}
let mut command_str = self.command_buffer.clone();
// Parse command
let cmd = self.analyzer.parse(&command_str)?;
// If in lesson mode and command is pwd, show virtual FS location
if self.lesson_mode && cmd.program == "pwd" {
if let Some(ref vfs) = self.virtual_fs {
let current = vfs.get_current_dir().display().to_string();
self.last_output = format!("{}\n\n💡 Virtual lesson filesystem\n", current);
self.command_buffer.clear();
self.add_to_history(command_str.clone());
// Still validate for lessons
if let Some(ref mut lesson_panel) = self.lesson_panel {
let validation = lesson_panel.validate_current_step("pwd");
if validation.is_success() && !lesson_panel.next_step() {
self.last_output.push_str("\n🎉 Lesson complete! Press Ctrl+L to exit.\n");
}
}
return Ok(());
}
}
// If in lesson mode and command is ls, show virtual FS contents
if self.lesson_mode && cmd.program == "ls" {
if let Some(ref vfs) = self.virtual_fs {
match vfs.list_directory(None) {
Ok(entries) => {
let mut output = String::new();
// Format entries with colors
for entry in entries {
if entry.is_dir {
output.push_str(&format!("📁 {}/\n", entry.name));
} else {
output.push_str(&format!("📄 {}\n", entry.name));
}
}
if output.is_empty() {
output = "Empty directory\n".to_string();
}
output.push_str("\n💡 Virtual lesson filesystem\n");
self.last_output = output;
self.command_buffer.clear();
self.add_to_history(command_str.clone());
// Still validate for lessons
if let Some(ref mut lesson_panel) = self.lesson_panel {
let validation = lesson_panel.validate_current_step(&command_str);
if validation.is_success() && !lesson_panel.next_step() {
self.last_output.push_str("\n🎉 Lesson complete! Press Ctrl+L to exit.\n");
}
}
return Ok(());
}
Err(e) => {
self.last_output = format!("❌ ls: {}\n", e);
return Ok(());
}
}
}
}
// If in lesson mode, validate against current lesson step
if self.lesson_mode {
if let Some(ref mut lesson_panel) = self.lesson_panel {
let validation = lesson_panel.validate_current_step(&command_str);
if validation.is_success() {
// Success! Move to next step
self.last_output = format!("✅ {}\n\nMoving to next step...\n",
match &validation {
arct_core::ValidationResult::Success { message } => message,
_ => "Success!",
}
);
if !lesson_panel.next_step() {
// Lesson complete!
self.last_output.push_str("\n🎉 Congratulations! You've completed this lesson!\n\nPress Ctrl+L to exit lesson mode.\n");
}
} else {
// Show validation failure
self.last_output = match validation {
arct_core::ValidationResult::Failure { message, hint } => {
let mut output = format!("❌ {}\n", message);
if let Some(h) = hint {
output.push_str(&format!("\n💡 Hint: {}\n", h));
}
output.push_str("\nTry again!\n");
output
}
arct_core::ValidationResult::Partial { message, progress } => {
format!("⚠️ {} ({:.0}% correct)\n\nKeep trying!\n", message, progress)
}
_ => "Try again!\n".to_string(),
};
}
self.command_buffer.clear();
self.add_to_history(command_str.clone());
return Ok(());
}
}
// Generate explanation
let explanation = self.educator.explain(&cmd)?;
self.last_explanation = Some(explanation);
// Check if this is a shell builtin command
match cmd.program.as_str() {
"cd" => {
// Add to history before clearing buffer
self.add_to_history(command_str.clone());
self.handle_cd_command(&cmd)?;
self.command_buffer.clear();
return Ok(());
}
"history" => {
// Add to history before clearing buffer
self.add_to_history(command_str.clone());
self.handle_history_command(&cmd)?;
self.command_buffer.clear();
return Ok(());
}
"export" => {
// Add to history before clearing buffer
self.add_to_history(command_str.clone());
self.handle_export_command(&cmd)?;
self.command_buffer.clear();
return Ok(());
}
"alias" => {
// Add to history before clearing buffer
self.add_to_history(command_str.clone());
self.handle_alias_command(&cmd)?;
self.command_buffer.clear();
return Ok(());
}
_ => {
// Check if the command is an alias and expand it
if let Some(aliased_command) = self.aliases.get(cmd.program.as_str()) {
// Replace the alias with the full command
let args_str = if !cmd.args.is_empty() {
format!(" {}", cmd.args.join(" "))
} else {
String::new()
};
command_str = format!("{}{}", aliased_command, args_str);
}
}
}
// Show executing status
self.last_output = format!("⏳ Executing: {}\n", command_str);
// Execute the command for real with timeout
let start_time = std::time::Instant::now();
// Use tokio timeout to prevent hanging
let timeout_duration = std::time::Duration::from_secs(5);
let env_vars = self.environment_vars.clone();
let output_result = tokio::time::timeout(
timeout_duration,
self.shell_executor.execute(command_str.clone(), env_vars)
).await;
let output = match output_result {
Ok(Ok(output)) => output,
Ok(Err(e)) => format!("❌ Error: {}", e),
Err(_) => format!("⏱️ Command timed out after {} seconds", timeout_duration.as_secs()),
};
let duration = start_time.elapsed();
// Store output
self.last_output = output.clone();
// Determine if command was successful
let success = !output.starts_with("❌") && !output.contains("timed out");
// Reset scroll to top for new output
self.output_scroll = 0;
// Record in session
self.session.record_command(
command_str.clone(),
Some(0),
Some(duration.as_millis() as u64),
);
// Track in analytics database
if let Some(ref analytics) = self.analytics {
let working_dir = self.session.state.working_directory.to_string_lossy().to_string();
let _ = analytics.record_command(
&command_str,
success,
&working_dir,
&self.session_id,
);
}
// Add to history
self.add_to_history(command_str);
// Clear buffer
self.command_buffer.clear();
Ok(())
}
/// Handle cd command specially (it's a shell builtin)
fn handle_cd_command(&mut self, cmd: &arct_core::Command) -> Result<()> {
use std::path::PathBuf;
// If in lesson mode, use virtual filesystem
if self.lesson_mode {
if let Some(ref mut vfs) = self.virtual_fs {
let target_str = if cmd.args.is_empty() {
"~"
} else {
&cmd.args[0]
};
match vfs.change_directory(target_str) {
Ok(new_path) => {
self.last_output = format!(
"✓ Changed directory to:\n {}\n\n💡 You're in the virtual lesson filesystem\n",
new_path
);
self.output_scroll = 0;
return Ok(());
}
Err(e) => {
self.last_output = format!("❌ cd: {}\n", e);
self.output_scroll = 0;
return Ok(());
}
}
}
}
// Normal mode - use real filesystem
// Determine target directory
let target = if cmd.args.is_empty() {
// cd with no args goes to home directory
dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Could not find home directory"))?
} else {
let target_str = &cmd.args[0];
// Expand ~ to home directory
if target_str == "~" {
dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Could not find home directory"))?
} else if target_str.starts_with("~/") {
let home = dirs::home_dir().ok_or_else(|| anyhow::anyhow!("Could not find home directory"))?;
home.join(&target_str[2..])
} else {
PathBuf::from(target_str)
}
};
// Try to change directory
match std::env::set_current_dir(&target) {
Ok(_) => {
// Update session working directory
self.session.state.working_directory = std::env::current_dir()?;
// Update context
self.update_context()?;
// Show success message
let new_dir = std::env::current_dir()?;
self.last_output = format!(
"✓ Changed directory to:\n {}\n",
new_dir.display()
);
// Reset scroll
self.output_scroll = 0;
// Record in session
self.session.record_command(
format!("cd {}", cmd.args.join(" ")),
Some(0),
Some(0),
);
Ok(())
}
Err(e) => {
// Show error message
self.last_output = format!(
"❌ cd: {}\n Cannot change to: {}\n",
e,
target.display()
);
self.output_scroll = 0;
// Record in session as failed
self.session.record_command(
format!("cd {}", cmd.args.join(" ")),
Some(1),
Some(0),
);
Ok(())
}
}
}
/// Update context (e.g., when directory changes)
pub fn update_context(&mut self) -> Result<()> {
let working_dir = &self.session.state.working_directory;
self.context = ContextDetector::detect(working_dir)?;
Ok(())
}
/// Navigate to previous command in history (Up arrow)
fn history_previous(&mut self) {
if self.command_history.is_empty() {
return;
}
match self.history_position {
None => {
// Start browsing history from most recent
self.history_position = Some(0);
self.command_buffer = self.command_history[0].clone();
}
Some(pos) => {
// Move to older command if possible
if pos < self.command_history.len() - 1 {
let new_pos = pos + 1;
self.history_position = Some(new_pos);
self.command_buffer = self.command_history[new_pos].clone();
}
}
}
}
/// Navigate to next command in history (Down arrow)
fn history_next(&mut self) {
match self.history_position {
None => {
// Not browsing history, do nothing
}
Some(0) => {
// At most recent, clear buffer
self.history_position = None;
self.command_buffer.clear();
}
Some(pos) => {
// Move to newer command
let new_pos = pos - 1;
self.history_position = Some(new_pos);
self.command_buffer = self.command_history[new_pos].clone();
}
}
}
/// Add a command to history
fn add_to_history(&mut self, command: String) {
if command.trim().is_empty() {
return;
}
// Don't add duplicate of most recent command
if let Some(last) = self.command_history.first() {
if last == &command {
return;
}
}
// Add to beginning (most recent first)
self.command_history.insert(0, command);
// Limit history size to 1000 commands
if self.command_history.len() > 1000 {
self.command_history.truncate(1000);
}
// Save to disk
self.save_history();
}
/// Save command history to disk
fn save_history(&self) {
let session_data = crate::persistence::SessionData {
command_history: self.command_history.clone(),
last_updated: chrono::Local::now().to_rfc3339(),
};
if let Err(e) = crate::persistence::save_session(&session_data) {
tracing::warn!("Failed to save session history: {}", e);
}
}
/// Handle history command (show command history)
fn handle_history_command(&mut self, cmd: &arct_core::Command) -> Result<()> {
// Parse optional argument for number of commands to show
let limit = if cmd.args.is_empty() {
50 // Default: show last 50 commands
} else {
cmd.args[0].parse::<usize>().unwrap_or(50)
};
if self.command_history.is_empty() {
self.last_output = "No commands in history yet.\n".to_string();
} else {
let mut output = String::new();
let total = self.command_history.len();
// Show commands in reverse chronological order (oldest to newest on screen)
// but numbered from oldest to newest (like bash)
for (i, cmd) in self.command_history.iter().rev().enumerate().take(limit) {
let index = total - self.command_history.len() + i + 1;
output.push_str(&format!("{:5} {}\n", index, cmd));
}
self.last_output = output;
}
// Reset scroll
self.output_scroll = 0;
// Record in session
self.session.record_command(
format!("history {}", if cmd.args.is_empty() { String::new() } else { cmd.args.join(" ") }),
Some(0),
Some(0),
);
Ok(())
}
/// Handle export command (set environment variables)
fn handle_export_command(&mut self, cmd: &arct_core::Command) -> Result<()> {
if cmd.args.is_empty() {
// No arguments - show all exported variables
if self.environment_vars.is_empty() {
self.last_output = "No environment variables set.\n".to_string();
} else {
let mut output = String::new();
output.push_str("Exported environment variables:\n\n");
let mut vars: Vec<_> = self.environment_vars.iter().collect();
vars.sort_by_key(|(k, _)| *k);
for (key, value) in vars {
output.push_str(&format!(" {}={}\n", key, value));
}
self.last_output = output;
}
} else {
// Parse VAR=value format
for arg in &cmd.args {
if let Some((key, value)) = arg.split_once('=') {
let key = key.trim().to_string();
let value = value.trim().to_string();
// Remove quotes if present
let value = if (value.starts_with('"') && value.ends_with('"')) ||
(value.starts_with('\'') && value.ends_with('\'')) {
value[1..value.len()-1].to_string()
} else {
value
};
self.environment_vars.insert(key.clone(), value.clone());
self.last_output = format!("✓ Exported: {}={}\n", key, value);
// Save to config
self.config.shell.environment = self.environment_vars.clone();
if let Err(e) = self.config.save() {
tracing::warn!("Failed to save config: {}", e);
}
} else {
self.last_output = format!("❌ Invalid export syntax: {}\n Usage: export VAR=value\n", arg);
break;
}
}
}
// Reset scroll
self.output_scroll = 0;
// Record in session
self.session.record_command(
format!("export {}", cmd.args.join(" ")),
Some(0),
Some(0),
);
Ok(())
}
/// Handle alias command (create command shortcuts)
fn handle_alias_command(&mut self, cmd: &arct_core::Command) -> Result<()> {
if cmd.args.is_empty() {
// No arguments - show all aliases
if self.aliases.is_empty() {
self.last_output = "No aliases defined.\n".to_string();
} else {
let mut output = String::new();
output.push_str("Defined aliases:\n\n");
let mut aliases: Vec<_> = self.aliases.iter().collect();
aliases.sort_by_key(|(k, _)| *k);
for (name, command) in aliases {
output.push_str(&format!(" {}='{}'\n", name, command));
}
self.last_output = output;
}
} else {
// Parse name=command format
let arg = cmd.args.join(" ");
if let Some((name, command)) = arg.split_once('=') {
let name = name.trim().to_string();
let command = command.trim().to_string();
// Remove quotes if present
let command = if (command.starts_with('"') && command.ends_with('"')) ||
(command.starts_with('\'') && command.ends_with('\'')) {
command[1..command.len()-1].to_string()
} else {
command
};
self.aliases.insert(name.clone(), command.clone());
self.last_output = format!("✓ Alias created: {}='{}'\n", name, command);
// Save to config
self.config.shell.aliases = self.aliases.clone();
if let Err(e) = self.config.save() {
tracing::warn!("Failed to save config: {}", e);
}
} else {
self.last_output = format!("❌ Invalid alias syntax: {}\n Usage: alias name='command'\n", arg);
}
}
// Reset scroll
self.output_scroll = 0;
// Record in session
self.session.record_command(
format!("alias {}", cmd.args.join(" ")),
Some(0),
Some(0),
);
Ok(())
}
/// Handle Tab key autocompletion
fn handle_autocomplete(&mut self) -> Result<()> {
if self.command_buffer.is_empty() {
return Ok(());
}
// Get completion results
let working_dir = &self.session.state.working_directory;
let result = self.autocompleter.complete(&self.command_buffer, working_dir)?;
// If there's a unique completion or common prefix, apply it
if !result.common_prefix.is_empty() && result.common_prefix != self.command_buffer {
// Update the buffer with the common prefix
// We need to replace the last token with the completion
let tokens: Vec<&str> = self.command_buffer.split_whitespace().collect();
if tokens.is_empty() {
self.command_buffer = result.common_prefix.clone();
} else if tokens.len() == 1 && !self.command_buffer.ends_with(' ') {
// Completing first token (command)
self.command_buffer = result.common_prefix.clone();
} else {
// Completing a path - replace last token
let last_token = tokens.last().unwrap_or(&"");
if let Some(idx) = self.command_buffer.rfind(last_token) {
self.command_buffer.truncate(idx);
self.command_buffer.push_str(&result.common_prefix);
}
}
}
// Store suggestions for display (limit to 10)
self.completion_suggestions = result.completions.into_iter().take(10).collect();
Ok(())
}
/// Toggle AI assistant mode
pub fn toggle_ai_mode(&mut self) {
if self.ai_provider.is_some() {
self.ai_mode = !self.ai_mode;
if self.ai_mode {
// Clear AI input when entering AI mode
self.ai_input_buffer.clear();
self.ai_loading = false;
}
} else {
self.last_output = "❌ AI is not enabled. Configure it in ~/.config/arct/config.toml\n".to_string();
}
}
/// Toggle lesson mode
pub fn toggle_lesson_mode(&mut self) {
self.lesson_mode = !self.lesson_mode;
if self.lesson_mode {
// Initialize virtual filesystem
match arct_core::VirtualFileSystem::new("nav-basics", &self.session_id) {
Ok(vfs) => {
self.virtual_fs = Some(vfs);
self.last_output = "📖 Lesson mode activated! You're now in a safe virtual filesystem.\n\nPress Ctrl+L again to return to normal mode.\n\nNavigate through lessons using the Learning panel on the right.\n".to_string();
}
Err(e) => {
self.last_output = format!("❌ Failed to initialize lesson environment: {}\n", e);
self.lesson_mode = false;
return;
}
}
// Initialize lesson panel if not already done
if self.lesson_panel.is_none() {
self.lesson_panel = Self::initialize_lesson_panel();
}
} else {
// Clean up virtual filesystem
self.virtual_fs = None;
self.last_output = "📚 Lesson mode deactivated. Back to normal shell mode and real filesystem.\n".to_string();
}
}
/// Ask the AI assistant a question
pub async fn ask_ai(&mut self, question: String) -> Result<()> {
if self.ai_provider.is_none() {
return Ok(());
}
if question.trim().is_empty() {
return Ok(());
}
self.ai_loading = true;
// Add user message to conversation
self.ai_conversation.push(arct_ai::Message::user(question.clone()));
// Build conversation with system prompt
let user_name = self.config.general.user_name.as_deref().unwrap_or("there");
let system_prompt = format!(
"You are an AI teaching assistant integrated into Arc Academy Terminal, \
an interactive terminal learning application. Your role is to help users \
learn shell commands and terminal skills.\n\n\
You're helping {}, so address them by name occasionally to make the \
interaction personal and engaging.\n\n\
Guidelines:\n\
- Teach shell commands with clear, executable examples\n\
- Explain concepts in beginner-friendly language\n\
- Provide commands the user can type themselves in the terminal\n\
- Keep responses concise (3-4 sentences or a short example)\n\
- Focus on common Linux/Unix commands (bash, grep, find, etc.)\n\
- Suggest safer alternatives when appropriate\n\
- You are NOT Claude Code - you cannot execute commands or use tools\n\
- You are a teaching assistant helping someone learn the terminal\n\
- Be encouraging and supportive in your teaching approach",
user_name
);
let mut messages = vec![
arct_ai::Message::system(system_prompt),
];
messages.extend(self.ai_conversation.clone());
// Get response from AI
let provider = self.ai_provider.as_ref().unwrap();
let response = provider.complete(&messages, None).await;
self.ai_loading = false;
match response {
Ok(ai_response) => {
// Strip markdown formatting for terminal display
let cleaned_content = Self::strip_markdown(&ai_response.content);
// Add assistant response to conversation
self.ai_conversation.push(arct_ai::Message::assistant(ai_response.content.clone()));
self.ai_response = Some(cleaned_content);
Ok(())
}
Err(e) => {
self.ai_response = Some(format!("❌ Error: {}", e));
Err(anyhow::anyhow!("AI request failed: {}", e))
}
}
}
/// Clear AI conversation
pub fn clear_ai_conversation(&mut self) {
self.ai_conversation.clear();
self.ai_response = None;
self.ai_input_buffer.clear();
}
/// Strip markdown formatting from text for plain terminal display
fn strip_markdown(text: &str) -> String {
let mut result = String::new();
let mut in_code_block = false;
let mut skip_line = false;
for line in text.lines() {
// Toggle code block state
if line.trim().starts_with("```") {
in_code_block = !in_code_block;
skip_line = true;
}
if skip_line {
skip_line = false;
continue;
}
// Clean the line
let mut cleaned = line.to_string();
// Remove headers (## Header -> Header)
if cleaned.trim_start().starts_with('#') {
cleaned = cleaned.trim_start().trim_start_matches('#').trim().to_string();
}
// Remove bold/italic markers
cleaned = cleaned.replace("**", "").replace("*", "");
// Remove inline code backticks (but not the content)
cleaned = cleaned.replace('`', "");
// Remove list markers (- item -> item, but keep indentation)
if let Some(stripped) = cleaned.trim_start().strip_prefix("- ") {
let indent = cleaned.len() - cleaned.trim_start().len();
cleaned = format!("{}{}", " ".repeat(indent), stripped);
}
result.push_str(&cleaned);
result.push('\n');
}
result.trim_end().to_string()
}
/// Handle onboarding wizard events
async fn handle_onboarding_event(&mut self, key: KeyEvent) -> Result<()> {
if let Some(wizard) = self.onboarding.as_mut() {
match key.code {
KeyCode::Char(c) if key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT => {
wizard.handle_char(c);
}
KeyCode::Backspace => {
wizard.handle_backspace();
}
KeyCode::Up => {
wizard.handle_up();
}
KeyCode::Down => {
let max_options = match wizard.step {
crate::panels::onboarding::OnboardingStep::AskAI => 3,
crate::panels::onboarding::OnboardingStep::AskAIProvider => 3,
_ => 1,
};
wizard.handle_down(max_options);
}
KeyCode::Enter => {
wizard.handle_enter();
// Check if onboarding is complete
if wizard.step == crate::panels::onboarding::OnboardingStep::Complete {
// Save settings to config
if let Some(wizard) = self.onboarding.take() {
self.complete_onboarding(wizard).await?;
}
}
}
_ => {}
}
}
Ok(())
}
/// Complete onboarding and save settings
async fn complete_onboarding(&mut self, wizard: crate::panels::onboarding::OnboardingWizard) -> Result<()> {
// Update config with onboarding results
if !wizard.user_name.is_empty() {
self.config.general.user_name = Some(wizard.user_name.clone());
}
if let Some(ai_enabled) = wizard.ai_enabled {
self.config.ai.enabled = ai_enabled;
if ai_enabled {
// Configure AI provider based on user selection
if wizard.ai_provider.as_deref() == Some("claude-code") {
// Claude Code CLI for Max subscribers
self.config.ai.provider = "claude-cli".to_string();
self.config.ai.model = Some("claude-sonnet-4".to_string());
// No API key needed - uses Claude Code authentication
} else if wizard.ai_provider.as_deref() == Some("own") {
// User has their own API key - default to local LLM
self.config.ai.provider = "local".to_string();
self.config.ai.endpoint = Some("http://localhost:11434".to_string());
self.config.ai.model = Some("llama3.2".to_string());
} else if wizard.ai_provider.as_deref() == Some("managed") {
// Arc Academy managed service
self.config.ai.provider = "managed".to_string();
}
}
}
// Mark setup as complete
self.config.general.setup_complete = true;
// Save config
self.config.save()?;
// Reinitialize AI provider with new settings
if self.config.ai.enabled {
match Self::create_ai_provider(&self.config.ai) {
Ok(provider) => {
self.ai_provider = Some(provider);
}
Err(e) => {
// Log error but don't fail onboarding
self.last_output = format!("⚠️ AI provider initialization failed: {}\n", e);
}
}
}
// Remove onboarding
self.onboarding = None;
// Show greeting in output
let name = self.config.general.user_name.as_deref().unwrap_or("there");
let mut welcome_msg = format!(
"🎉 Welcome, {}!\n\n\
You're all set to start learning shell commands!\n\n",
name
);
// Add provider-specific setup notes if AI is enabled
if self.config.ai.enabled {
match self.config.ai.provider.as_str() {
"claude-cli" => {
welcome_msg.push_str(
"✨ Using Claude Code CLI - your Max subscription is ready!\n\
Press Ctrl+A to ask Claude for help.\n\n"
);
}
"anthropic" | "openai" => {
welcome_msg.push_str(
"📝 To use AI features, set your API key:\n\
export ARCT_AI_API_KEY=\"your-api-key-here\"\n\n"
);
}
"local" => {
welcome_msg.push_str(
"🏠 Using local LLM - make sure your server is running!\n\n"
);
}
_ => {}
}
}
welcome_msg.push_str("Press ? for help, or just start typing commands.\n");
self.last_output = welcome_msg;
Ok(())
}
/// Handle settings panel events
async fn handle_settings_event(&mut self, key: KeyEvent) -> Result<()> {
// Determine what action to take
let (action, selected_field) = {
let panel = match self.settings_panel.as_ref() {
Some(p) => p,
None => return Ok(()),
};
let action = if panel.editing {
// In edit mode
match key.code {
KeyCode::Char(c) if key.modifiers == KeyModifiers::NONE || key.modifiers == KeyModifiers::SHIFT => {
SettingsAction::PushChar(c)
}
KeyCode::Backspace => SettingsAction::PopChar,
KeyCode::Enter => SettingsAction::SaveEdit,
KeyCode::Esc => SettingsAction::CancelEdit,
_ => SettingsAction::None,
}
} else {
// In navigation mode
match key.code {
KeyCode::Up | KeyCode::Char('k') if key.modifiers == KeyModifiers::NONE => {
SettingsAction::PreviousField
}
KeyCode::Down | KeyCode::Char('j') if key.modifiers == KeyModifiers::NONE => {
SettingsAction::NextField
}
KeyCode::Enter => SettingsAction::StartEdit,
KeyCode::Esc | KeyCode::Char('s') if key.modifiers == KeyModifiers::CONTROL => {
SettingsAction::Close
}
_ => SettingsAction::None,
}
};
(action, panel.selected_field)
};
// Execute the action
match action {
SettingsAction::PushChar(c) => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.push_char(c);
}
}
SettingsAction::PopChar => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.pop_char();
}
}
SettingsAction::SaveEdit => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.save_edit(&mut self.config)?;
// If theme was changed, reload it
if selected_field == crate::panels::settings::SettingField::Theme {
self.theme = Theme::from_name(&self.config.theme.default_theme);
}
// If AI was toggled, reload provider
if selected_field == crate::panels::settings::SettingField::AIEnabled {
if self.config.ai.enabled {
// Try to initialize AI provider
match Self::create_ai_provider(&self.config.ai) {
Ok(provider) => {
self.ai_provider = Some(provider);
}
Err(e) => {
tracing::warn!("Failed to initialize AI provider: {}", e);
self.ai_provider = None;
}
}
} else {
self.ai_provider = None;
self.ai_mode = false;
}
}
}
}
SettingsAction::CancelEdit => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.cancel_editing();
}
}
SettingsAction::PreviousField => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.previous_field();
}
}
SettingsAction::NextField => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.next_field();
}
}
SettingsAction::StartEdit => {
if let Some(panel) = self.settings_panel.as_mut() {
panel.start_editing(&self.config);
}
}
SettingsAction::Close => {
self.settings_panel = None;
}
SettingsAction::None => {}
}
Ok(())
}
}
/// Actions that can be performed in the settings panel
enum SettingsAction {
PushChar(char),
PopChar,
SaveEdit,
CancelEdit,
PreviousField,
NextField,
StartEdit,
Close,
None,
}