1use crate::cli::display_utils::{
2 TextAlignment, format_token_for_display, get_terminal_width, pad_text_to_width,
3 text_display_width,
4};
5use crate::config::EnvironmentConfig;
6use crate::config::types::{ClaudeSettings, ConfigStorage, Configuration};
7use crate::platform::resolve_npm_cli;
8use anyhow::{Context, Result};
9use colored::*;
10use crossterm::{
11 event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
12 execute, terminal,
13};
14use std::io::{self, Write};
15use std::process::Command;
16
17pub(crate) fn char_display_width(c: char) -> usize {
20 match c as u32 {
21 0x00..=0x7F => 1,
22 0x80..=0x2FF => 1,
23 0x2190..=0x21FF => 2,
24 0x3000..=0x303F => 2,
25 0x3040..=0x309F => 2,
26 0x30A0..=0x30FF => 2,
27 0x4E00..=0x9FFF => 2,
28 0xAC00..=0xD7AF => 2,
29 0x3400..=0x4DBF => 2,
30 0xFF01..=0xFF60 => 2,
31 _ => 1,
32 }
33}
34
35pub(crate) fn truncate_text_to_width(text: &str, available_width: usize) -> (String, usize) {
37 let mut current_width = 0;
38 let truncated: String = text
39 .chars()
40 .take_while(|&c| {
41 let char_width = char_display_width(c);
42 if current_width + char_width <= available_width {
43 current_width += char_width;
44 true
45 } else {
46 false
47 }
48 })
49 .collect();
50 let truncated_width = text_display_width(&truncated);
51 (truncated, truncated_width)
52}
53
54pub(crate) fn cleanup_terminal(stdout: &mut io::Stdout) {
56 let _ = execute!(stdout, terminal::LeaveAlternateScreen);
57 let _ = terminal::disable_raw_mode();
58}
59
60pub(crate) struct BorderDrawing {
62 pub unicode_supported: bool,
64}
65
66impl BorderDrawing {
67 pub(crate) fn new() -> Self {
69 let unicode_supported = Self::detect_unicode_support();
70 Self { unicode_supported }
71 }
72
73 fn detect_unicode_support() -> bool {
75 crate::platform::unicode_support_enabled()
76 }
77
78 pub(crate) fn draw_top_border(&self, title: &str, width: usize) -> String {
80 if self.unicode_supported {
81 let title_padded = format!(" {title} ");
82 let title_len = text_display_width(&title_padded);
83
84 if title_len >= width.saturating_sub(2) {
85 format!("╔{}╗", "═".repeat(width.saturating_sub(2)))
87 } else {
88 let inner_width = width.saturating_sub(2); let padding_total = inner_width.saturating_sub(title_len);
90 let padding_left = padding_total / 2;
91 let padding_right = padding_total - padding_left;
92 format!(
93 "╔{}{}{}╗",
94 "═".repeat(padding_left),
95 title_padded,
96 "═".repeat(padding_right)
97 )
98 }
99 } else {
100 let title_padded = format!(" {title} ");
102 let title_len = title_padded.len();
103
104 if title_len >= width.saturating_sub(2) {
105 format!("+{}+", "-".repeat(width.saturating_sub(2)))
106 } else {
107 let inner_width = width.saturating_sub(2);
108 let padding_total = inner_width.saturating_sub(title_len);
109 let padding_left = padding_total / 2;
110 let padding_right = padding_total - padding_left;
111 format!(
112 "+{}{}{}+",
113 "-".repeat(padding_left),
114 title_padded,
115 "-".repeat(padding_right)
116 )
117 }
118 }
119 }
120
121 pub(crate) fn draw_middle_line(&self, text: &str, width: usize) -> String {
123 let text_len = text_display_width(text);
124 let available_width = width.saturating_sub(4);
126
127 let (left_border, right_border) = if self.unicode_supported {
128 ("║", "║")
129 } else {
130 ("|", "|")
131 };
132
133 if text_len > available_width {
134 let (truncated, truncated_width) = truncate_text_to_width(text, available_width);
136 let padding_spaces = available_width.saturating_sub(truncated_width);
137 format!(
138 "{left_border} {}{} {right_border}",
139 truncated,
140 " ".repeat(padding_spaces)
141 )
142 } else {
143 let padded_text = pad_text_to_width(text, available_width, TextAlignment::Left, ' ');
144 format!("{left_border} {padded_text} {right_border}")
145 }
146 }
147
148 pub(crate) fn draw_bottom_border(&self, width: usize) -> String {
150 if self.unicode_supported {
151 format!("╚{}╝", "═".repeat(width - 2))
152 } else {
153 format!("+{}+", "-".repeat(width - 2))
154 }
155 }
156}
157
158pub fn handle_current_command() -> Result<()> {
168 let storage = ConfigStorage::load()?;
169
170 println!("\n{}", "Current Configuration:".green().bold());
171 println!("Environment variable mode: configurations are set per-command execution");
172 println!("Select a configuration from the menu below to launch Claude");
173 println!("Select 'cc' to launch Claude with default settings");
174
175 let raw_mode_enabled = terminal::enable_raw_mode().is_ok();
177
178 if raw_mode_enabled {
179 let mut stdout = io::stdout();
180 if execute!(
181 stdout,
182 terminal::EnterAlternateScreen,
183 terminal::Clear(terminal::ClearType::All)
184 )
185 .is_ok()
186 {
187 let result = handle_main_menu_interactive(&mut stdout, &storage);
189
190 let _ = execute!(stdout, terminal::LeaveAlternateScreen);
192 let _ = terminal::disable_raw_mode();
193
194 return result;
195 } else {
196 let _ = terminal::disable_raw_mode();
198 }
199 }
200
201 handle_main_menu_simple(&storage)
203}
204
205fn handle_main_menu_interactive(stdout: &mut io::Stdout, storage: &ConfigStorage) -> Result<()> {
207 let menu_items = [
208 "Execute claude --dangerously-skip-permissions",
209 "Switch configuration",
210 "Exit",
211 ];
212 let mut selected_index = 0;
213
214 loop {
215 execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
217 execute!(stdout, crossterm::cursor::MoveTo(0, 0))?;
218
219 let border = BorderDrawing::new();
221 const MAIN_MENU_WIDTH: usize = 68;
222
223 println!(
224 "\r{}",
225 border.draw_top_border("Main Menu", MAIN_MENU_WIDTH).green()
226 );
227 println!(
228 "\r{}",
229 border
230 .draw_middle_line(
231 "↑↓/jk导航,1-9快选,E-编辑,R-官方,Q-退出,Enter确认,Esc取消",
232 MAIN_MENU_WIDTH
233 )
234 .green()
235 );
236 println!("\r{}", border.draw_bottom_border(MAIN_MENU_WIDTH).green());
237 println!();
238
239 for (index, item) in menu_items.iter().enumerate() {
241 if index == selected_index {
242 println!("\r> {} {}", "●".blue().bold(), item.blue().bold());
243 } else {
244 println!("\r {} {}", "○".dimmed(), item.dimmed());
245 }
246 }
247
248 stdout.flush()?;
250
251 let event = match event::read() {
253 Ok(event) => event,
254 Err(e) => {
255 cleanup_terminal(stdout);
257 return Err(e.into());
258 }
259 };
260
261 match event {
262 Event::Key(KeyEvent {
263 code,
264 kind: KeyEventKind::Press,
265 ..
266 }) => {
267 match code {
268 KeyCode::Up => {
269 selected_index = selected_index.saturating_sub(1);
270 }
271 KeyCode::Down if selected_index < menu_items.len() - 1 => {
272 selected_index += 1;
273 }
274 KeyCode::Down => {}
275 KeyCode::Enter => {
276 cleanup_terminal(stdout);
278
279 return handle_main_menu_action(selected_index, storage);
280 }
281 KeyCode::Esc => {
282 cleanup_terminal(stdout);
284
285 println!("\nExiting...");
286 return Ok(());
287 }
288 _ => {}
289 }
290 }
291 Event::Key(_) => {} _ => {}
293 }
294 }
295}
296
297fn handle_main_menu_simple(storage: &ConfigStorage) -> Result<()> {
299 loop {
300 println!("\n{}", "Available Actions:".blue().bold());
301 println!("1. Execute claude --dangerously-skip-permissions");
302 println!("2. Switch configuration");
303 println!("3. Exit");
304
305 print!("\nPlease select an option (1-3): ");
306 io::stdout().flush().context("Failed to flush stdout")?;
307
308 let mut input = String::new();
309 io::stdin()
310 .read_line(&mut input)
311 .context("Failed to read input")?;
312
313 let choice = input.trim();
314
315 match choice {
316 "1" => return handle_main_menu_action(0, storage),
317 "2" => return handle_main_menu_action(1, storage),
318 "3" => return handle_main_menu_action(2, storage),
319 _ => {
320 println!("Invalid option. Please select 1-3.");
321 }
322 }
323 }
324}
325
326fn handle_main_menu_action(selected_index: usize, storage: &ConfigStorage) -> Result<()> {
328 match selected_index {
329 0 => {
330 println!("\nExecuting: claude --dangerously-skip-permissions");
331 execute_claude_command(true)?;
332 }
333 1 => {
334 handle_interactive_selection(storage)?;
336 }
337 2 => {
338 println!("Exiting...");
339 }
340 _ => {
341 println!("Invalid selection");
342 }
343 }
344 Ok(())
345}
346
347pub fn handle_interactive_selection(storage: &ConfigStorage) -> Result<()> {
355 if storage.configurations.is_empty() {
356 println!("No configurations available. Use 'add' command to create configurations first.");
357 return Ok(());
358 }
359
360 let mut configs: Vec<Configuration> = storage.configurations.values().cloned().collect();
361 configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
362
363 let mut selected_index = 0;
364
365 let raw_mode_enabled = terminal::enable_raw_mode().is_ok();
367
368 if raw_mode_enabled {
369 let mut stdout = io::stdout();
370 if execute!(
371 stdout,
372 terminal::EnterAlternateScreen,
373 terminal::Clear(terminal::ClearType::All)
374 )
375 .is_ok()
376 {
377 let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
379 let result = handle_full_interactive_menu(
380 &mut stdout,
381 &mut configs,
382 &mut selected_index,
383 storage,
384 storage_mode,
385 );
386
387 let _ = execute!(stdout, terminal::LeaveAlternateScreen);
389 let _ = terminal::disable_raw_mode();
390
391 return result;
392 } else {
393 let _ = terminal::disable_raw_mode();
395 }
396 }
397
398 handle_simple_interactive_menu(&configs.iter().collect::<Vec<_>>(), storage)
400}
401
402fn handle_full_interactive_menu(
404 stdout: &mut io::Stdout,
405 configs: &mut Vec<Configuration>,
406 selected_index: &mut usize,
407 storage: &ConfigStorage,
408 storage_mode: crate::config::types::StorageMode,
409) -> Result<()> {
410 if configs.is_empty() {
412 println!("\r{}", "No configurations available".yellow());
413 println!(
414 "\r{}",
415 "Use 'cc-switch add <alias> <token> <url>' to add configurations first.".dimmed()
416 );
417 println!("\r{}", "Press any key to continue...".dimmed());
418 let _ = event::read(); return Ok(());
420 }
421
422 const PAGE_SIZE: usize = 9; let total_pages = if configs.len() <= PAGE_SIZE {
426 1
427 } else {
428 configs.len().div_ceil(PAGE_SIZE)
429 };
430 let mut current_page = 0;
431
432 loop {
433 let start_idx = current_page * PAGE_SIZE;
435 let end_idx = std::cmp::min(start_idx + PAGE_SIZE, configs.len());
436 let page_configs = &configs[start_idx..end_idx];
437
438 execute!(stdout, terminal::Clear(terminal::ClearType::All))?;
440 execute!(stdout, crossterm::cursor::MoveTo(0, 0))?;
441
442 let border = BorderDrawing::new();
444 const CONFIG_MENU_WIDTH: usize = 80;
447
448 println!(
449 "\r{}",
450 border
451 .draw_top_border("Select Configuration", CONFIG_MENU_WIDTH)
452 .green()
453 );
454 if total_pages > 1 {
455 println!(
456 "\r{}",
457 border
458 .draw_middle_line(
459 &format!("第 {} 页,共 {} 页", current_page + 1, total_pages),
460 CONFIG_MENU_WIDTH
461 )
462 .green()
463 );
464 println!(
465 "\r{}",
466 border
467 .draw_middle_line(
468 "↑↓/jk导航,1-9快选,E-编辑,N/P翻页,R-官方,Q-退出,Enter确认",
469 CONFIG_MENU_WIDTH
470 )
471 .green()
472 );
473 } else {
474 println!(
475 "\r{}",
476 border
477 .draw_middle_line(
478 "↑↓/jk导航,1-9快选,E-编辑,R-官方,Q-退出,Enter确认,Esc取消",
479 CONFIG_MENU_WIDTH
480 )
481 .green()
482 );
483 }
484 println!("\r{}", border.draw_bottom_border(CONFIG_MENU_WIDTH).green());
485 println!();
486
487 let official_index = 0;
489 if *selected_index == official_index {
490 println!(
491 "\r> {} {} {}",
492 "●".red().bold(),
493 "[R]".red().bold(),
494 "official".red().bold()
495 );
496 println!("\r Use official Claude API (no custom configuration)");
497 println!();
498 } else {
499 println!("\r {} {} {}", "○".red(), "[R]".red(), "official".red());
500 }
501
502 for (page_index, config) in page_configs.iter().enumerate() {
504 let actual_config_index = start_idx + page_index;
505 let display_number = page_index + 1; let actual_index = actual_config_index + 1; let number_label = format!("[{display_number}]");
508
509 if *selected_index == actual_index {
510 println!(
511 "\r> {} {} {}",
512 "●".blue().bold(),
513 number_label.blue().bold(),
514 config.alias_name.blue().bold()
515 );
516
517 let details = format_config_details(config, "\r ", false);
519 for detail_line in details {
520 println!("{detail_line}");
521 }
522 println!();
523 } else {
524 println!(
525 "\r {} {} {}",
526 "○".dimmed(),
527 number_label.dimmed(),
528 config.alias_name.dimmed()
529 );
530 }
531 }
532
533 let exit_index = configs.len() + 1;
535 if *selected_index == exit_index {
536 println!(
537 "\r> {} {} {}",
538 "●".yellow().bold(),
539 "[Q]".yellow().bold(),
540 "Exit".yellow().bold()
541 );
542 println!("\r Exit without making changes");
543 println!();
544 } else {
545 println!(
546 "\r {} {} {}",
547 "○".dimmed(),
548 "[Q]".dimmed(),
549 "Exit".dimmed()
550 );
551 }
552
553 if total_pages > 1 {
555 println!(
556 "\r{}",
557 format!(
558 "Page Navigation: [N]ext, [P]revious (第 {} 页,共 {} 页)",
559 current_page + 1,
560 total_pages
561 )
562 .dimmed()
563 );
564 }
565
566 stdout.flush()?;
568
569 let event = match event::read() {
571 Ok(event) => event,
572 Err(e) => {
573 cleanup_terminal(stdout);
575 return Err(e.into());
576 }
577 };
578
579 match event {
580 Event::Key(KeyEvent {
581 code,
582 kind: KeyEventKind::Press,
583 ..
584 }) => match code {
585 KeyCode::Up | KeyCode::Char('k') | KeyCode::Char('K') => {
586 *selected_index = selected_index.saturating_sub(1);
587 }
588 KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J')
589 if *selected_index < configs.len() + 1 =>
590 {
591 *selected_index += 1;
592 }
593 KeyCode::Down | KeyCode::Char('j') | KeyCode::Char('J') => {}
594 KeyCode::PageDown | KeyCode::Char('n') | KeyCode::Char('N')
595 if total_pages > 1 && current_page < total_pages - 1 =>
596 {
597 current_page += 1;
598 let new_page_start_idx = current_page * PAGE_SIZE;
599 *selected_index = new_page_start_idx + 1;
600 }
601 KeyCode::PageDown | KeyCode::Char('n') | KeyCode::Char('N') => {}
602 KeyCode::PageUp | KeyCode::Char('p') | KeyCode::Char('P')
603 if total_pages > 1 && current_page > 0 =>
604 {
605 current_page -= 1;
606 let new_page_start_idx = current_page * PAGE_SIZE;
607 *selected_index = new_page_start_idx + 1;
608 }
609 KeyCode::PageUp | KeyCode::Char('p') | KeyCode::Char('P') => {}
610 KeyCode::Enter => {
611 cleanup_terminal(stdout);
613
614 return handle_selection_action(
615 &configs.iter().collect::<Vec<_>>(),
616 *selected_index,
617 storage,
618 storage_mode,
619 );
620 }
621 KeyCode::Esc => {
622 cleanup_terminal(stdout);
624
625 println!("\nSelection cancelled");
626 return Ok(());
627 }
628 KeyCode::Char(c) if c.is_ascii_digit() => {
629 let digit = c.to_digit(10).unwrap() as usize;
630 if digit >= 1 && digit <= page_configs.len() {
632 let actual_config_index = start_idx + (digit - 1);
633 let selection_index = actual_config_index + 1; cleanup_terminal(stdout);
637
638 return handle_selection_action(
639 &configs.iter().collect::<Vec<_>>(),
640 selection_index,
641 storage,
642 storage_mode,
643 );
644 }
645 }
647 KeyCode::Char('r') | KeyCode::Char('R') => {
648 cleanup_terminal(stdout);
650
651 return handle_selection_action(
652 &configs.iter().collect::<Vec<_>>(),
653 0,
654 storage,
655 storage_mode,
656 );
657 }
658 KeyCode::Char('e') | KeyCode::Char('E')
659 if *selected_index > 0 && *selected_index <= configs.len() =>
660 {
661 cleanup_terminal(stdout);
662 let config_index = *selected_index - 1;
663 let edit_result = handle_config_edit(&configs[config_index]);
664 if execute!(
665 stdout,
666 terminal::EnterAlternateScreen,
667 terminal::Clear(terminal::ClearType::All)
668 )
669 .is_ok()
670 && terminal::enable_raw_mode().is_ok()
671 {
672 match edit_result {
673 Ok(_) => {
674 if let Ok(reloaded_storage) = ConfigStorage::load() {
675 *configs =
676 reloaded_storage.configurations.values().cloned().collect();
677 configs.sort_by(|a, b| a.alias_name.cmp(&b.alias_name));
678 if *selected_index > configs.len() + 1 {
679 *selected_index = configs.len() + 1;
680 }
681 }
682 continue;
683 }
684 Err(e) => {
685 if e.downcast_ref::<EditModeError>()
686 == Some(&EditModeError::ReturnToMenu)
687 {
688 continue;
689 }
690 cleanup_terminal(stdout);
691 return Err(e);
692 }
693 }
694 }
695 }
696 KeyCode::Char('e') | KeyCode::Char('E') => {}
697 KeyCode::Char('q') | KeyCode::Char('Q') => {
698 cleanup_terminal(stdout);
700
701 return handle_selection_action(
702 &configs.iter().collect::<Vec<_>>(),
703 configs.len() + 1,
704 storage,
705 storage_mode,
706 );
707 }
708 _ => {}
709 },
710 Event::Key(_) => {} _ => {}
712 }
713 }
714}
715
716fn handle_simple_interactive_menu(
718 configs: &[&Configuration],
719 storage: &ConfigStorage,
720) -> Result<()> {
721 const PAGE_SIZE: usize = 9; if configs.len() <= PAGE_SIZE {
725 return handle_simple_single_page_menu(configs, storage);
726 }
727
728 let total_pages = configs.len().div_ceil(PAGE_SIZE);
730 let mut current_page = 0;
731
732 loop {
733 let start_idx = current_page * PAGE_SIZE;
735 let end_idx = std::cmp::min(start_idx + PAGE_SIZE, configs.len());
736 let page_configs = &configs[start_idx..end_idx];
737
738 println!("\n{}", "Available Configurations:".blue().bold());
739 if total_pages > 1 {
740 println!("第 {} 页,共 {} 页", current_page + 1, total_pages);
741 println!("使用 'n' 下一页, 'p' 上一页, 'r' 官方配置, 'q' 退出");
742 }
743 println!();
744
745 println!("{} {}", "[r]".red().bold(), "official".red());
747 println!(" Use official Claude API (no custom configuration)");
748 println!();
749
750 for (page_index, config) in page_configs.iter().enumerate() {
752 let display_number = page_index + 1;
753
754 println!(
755 "{}. {}",
756 format!("[{display_number}]").green().bold(),
757 config.alias_name.green()
758 );
759
760 let details = format_config_details(config, " ", true);
762 for detail_line in details {
763 println!("{detail_line}");
764 }
765 println!();
766 }
767
768 println!("{} {}", "[q]".yellow().bold(), "Exit".yellow());
770
771 if total_pages > 1 {
772 println!(
773 "\n页面导航: [n]下页, [p]上页 | 配置选择: [1-{}] | [e]编辑 | [r]官方 | [q]退出",
774 page_configs.len()
775 );
776 }
777
778 print!("\n请输入选择: ");
779 io::stdout().flush()?;
780
781 let mut input = String::new();
782 io::stdin().read_line(&mut input)?;
783 let choice = input.trim().to_lowercase();
784
785 match choice.as_str() {
786 "r" => {
787 println!("{}", "Using official Claude configuration".blue());
789
790 let mut settings = crate::config::types::ClaudeSettings::load(
792 storage.get_claude_settings_dir().map(|s| s.as_str()),
793 )?;
794 settings.remove_anthropic_env();
795 settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
796
797 return launch_claude_with_env(
798 EnvironmentConfig::empty().with_alias("official"),
799 None,
800 None,
801 false,
802 );
803 }
804 "e" => {
805 println!("编辑功能在交互式菜单中可用");
808 }
809 "q" => {
810 println!("Exiting...");
811 return Ok(());
812 }
813 "n" if total_pages > 1 && current_page < total_pages - 1 => {
814 current_page += 1;
815 continue;
816 }
817 "p" if total_pages > 1 && current_page > 0 => {
818 current_page -= 1;
819 continue;
820 }
821 digit_str => {
822 if let Ok(digit) = digit_str.parse::<usize>()
823 && digit >= 1
824 && digit <= page_configs.len()
825 {
826 let actual_config_index = start_idx + (digit - 1);
827 let selection_index = actual_config_index + 1; let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
829 return handle_selection_action(
830 configs,
831 selection_index,
832 storage,
833 storage_mode,
834 );
835 }
836 println!("无效选择,请重新输入");
837 }
838 }
839 }
840}
841
842fn handle_simple_single_page_menu(
844 configs: &[&Configuration],
845 storage: &ConfigStorage,
846) -> Result<()> {
847 println!("\n{}", "Available Configurations:".blue().bold());
848
849 println!("1. {}", "official".red());
851 println!(" Use official Claude API (no custom configuration)");
852 println!();
853
854 for (index, config) in configs.iter().enumerate() {
855 println!(
856 "{}. {}",
857 index + 2, config.alias_name.green()
859 );
860
861 let details = format_config_details(config, " ", true);
863 for detail_line in details {
864 println!("{detail_line}");
865 }
866 println!();
867 }
868
869 println!("{}. {}", configs.len() + 2, "Exit".yellow());
870
871 print!("\nSelect configuration (1-{}): ", configs.len() + 2);
872 io::stdout().flush()?;
873
874 let mut input = String::new();
875 io::stdin().read_line(&mut input)?;
876
877 match input.trim().parse::<usize>() {
878 Ok(1) => {
879 println!("{}", "Using official Claude configuration".blue());
881
882 let mut settings = crate::config::types::ClaudeSettings::load(
884 storage.get_claude_settings_dir().map(|s| s.as_str()),
885 )?;
886 settings.remove_anthropic_env();
887 settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
888
889 launch_claude_with_env(
890 EnvironmentConfig::empty().with_alias("official"),
891 None,
892 None,
893 false,
894 )
895 }
896 Ok(num) if num >= 2 && num <= configs.len() + 1 => {
897 let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
898 handle_selection_action(configs, num - 1, storage, storage_mode) }
900 Ok(num) if num == configs.len() + 2 => {
901 println!("Exiting...");
902 Ok(())
903 }
904 _ => {
905 println!("Invalid selection");
906 Ok(())
907 }
908 }
909}
910
911fn handle_selection_action(
913 configs: &[&Configuration],
914 selected_index: usize,
915 storage: &ConfigStorage,
916 storage_mode: crate::config::types::StorageMode,
917) -> Result<()> {
918 if selected_index == 0 {
919 println!("{}", "\nUsing official Claude configuration".blue());
921
922 let mut settings = crate::config::types::ClaudeSettings::load(
924 storage.get_claude_settings_dir().map(|s| s.as_str()),
925 )?;
926 settings.remove_anthropic_env();
927 settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
928
929 launch_claude_with_env(
930 EnvironmentConfig::empty().with_alias("official"),
931 None,
932 None,
933 false,
934 )
935 } else if selected_index <= configs.len() {
936 let config_index = selected_index - 1; let selected_config = configs[config_index].clone();
939
940 let env_config = EnvironmentConfig::from_config(&selected_config)
941 .with_alias(&selected_config.alias_name);
942
943 println!(
944 "\nSwitched to configuration '{}'",
945 selected_config.alias_name.green().bold()
946 );
947
948 let details = format_config_details(&selected_config, "", false);
949 for detail_line in details {
950 println!("{detail_line}");
951 }
952
953 let mut settings = crate::config::types::ClaudeSettings::load(
955 storage.get_claude_settings_dir().map(|s| s.as_str()),
956 )?;
957 settings.switch_to_config_with_mode(
958 &selected_config,
959 storage_mode,
960 storage.get_claude_settings_dir().map(|s| s.as_str()),
961 )?;
962
963 launch_claude_with_env(env_config, None, None, false)
964 } else {
965 println!("\nExiting...");
967 Ok(())
968 }
969}
970
971pub fn launch_claude_with_env(
973 env_config: EnvironmentConfig,
974 prompt: Option<&str>,
975 resume: Option<&str>,
976 continue_session: bool,
977) -> Result<()> {
978 println!("\nLaunching Claude CLI...");
979
980 let _ = ClaudeSettings::cleanup_orphan_alias_files();
982
983 if let Some(alias) = env_config.env_vars.get("CC_SWITCH_CURRENT_ALIAS") {
987 ClaudeSettings::write_current_alias_for_pid(alias)?;
988 }
989
990 #[cfg(unix)]
992 {
993 use std::os::unix::process::CommandExt;
994 let mut command = Command::new(resolve_npm_cli("claude"));
995 command.envs(env_config.as_env_tuples());
997 command.arg("--dangerously-skip-permissions");
998 if let Some(session_id) = resume {
999 command.args(["--resume", session_id]);
1000 }
1001 if continue_session {
1002 command.arg("--continue");
1003 }
1004 if let Some(p) = prompt {
1005 command.arg(p);
1006 }
1007 let error = command.exec();
1008 let _ = ClaudeSettings::clear_current_alias_for_pid();
1011 anyhow::bail!("Failed to exec claude: {}", error);
1012 }
1013
1014 #[cfg(not(unix))]
1016 {
1017 use std::process::Stdio;
1018 let mut command = Command::new(resolve_npm_cli("claude"));
1019 command.envs(env_config.as_env_tuples());
1021 command.arg("--dangerously-skip-permissions");
1022 if let Some(session_id) = resume {
1023 command.args(["--resume", session_id]);
1024 }
1025 if continue_session {
1026 command.arg("--continue");
1027 }
1028 if let Some(p) = prompt {
1029 command.arg(p);
1030 }
1031 command
1032 .stdin(Stdio::inherit())
1033 .stdout(Stdio::inherit())
1034 .stderr(Stdio::inherit());
1035
1036 let mut child = command.spawn().context(
1037 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1038 )?;
1039
1040 let status = child.wait()?;
1041
1042 let _ = ClaudeSettings::clear_current_alias_for_pid();
1044
1045 if !status.success() {
1046 anyhow::bail!("Claude CLI exited with error status: {}", status);
1047 }
1048 Ok(())
1049 }
1050}
1051
1052fn execute_claude_command(skip_permissions: bool) -> Result<()> {
1057 println!("Launching Claude CLI...");
1058
1059 #[cfg(unix)]
1061 {
1062 use std::os::unix::process::CommandExt;
1063 let mut command = Command::new(resolve_npm_cli("claude"));
1064 if skip_permissions {
1065 command.arg("--dangerously-skip-permissions");
1066 }
1067
1068 let error = command.exec();
1069 anyhow::bail!("Failed to exec claude: {}", error);
1071 }
1072
1073 #[cfg(not(unix))]
1075 {
1076 use std::process::Stdio;
1077 let mut command = Command::new(resolve_npm_cli("claude"));
1078 if skip_permissions {
1079 command.arg("--dangerously-skip-permissions");
1080 }
1081
1082 command
1083 .stdin(Stdio::inherit())
1084 .stdout(Stdio::inherit())
1085 .stderr(Stdio::inherit());
1086
1087 let mut child = command.spawn().context(
1088 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1089 )?;
1090
1091 let status = child
1092 .wait()
1093 .context("Failed to wait for Claude CLI process")?;
1094
1095 if !status.success() {
1096 anyhow::bail!("Claude CLI exited with error status: {}", status);
1097 }
1098 Ok(())
1099 }
1100}
1101
1102pub fn read_input(prompt: &str) -> Result<String> {
1110 print!("{prompt}");
1111 io::stdout().flush().context("Failed to flush stdout")?;
1112 let mut input = String::new();
1113 io::stdin()
1114 .read_line(&mut input)
1115 .context("Failed to read input")?;
1116 Ok(input.trim().to_string())
1117}
1118
1119pub fn read_sensitive_input(prompt: &str) -> Result<String> {
1127 print!("{prompt}");
1128 io::stdout().flush().context("Failed to flush stdout")?;
1129 let mut input = String::new();
1130 io::stdin()
1131 .read_line(&mut input)
1132 .context("Failed to read input")?;
1133 Ok(input.trim().to_string())
1134}
1135
1136fn format_config_details(config: &Configuration, indent: &str, _compact: bool) -> Vec<String> {
1149 let mut lines = Vec::new();
1150
1151 let terminal_width = get_terminal_width();
1153 let _available_width = terminal_width.saturating_sub(text_display_width(indent) + 8);
1154
1155 let token_label = if config.api_key.is_some() {
1157 "API Key:"
1158 } else {
1159 "Token:"
1160 };
1161 let url_label = "URL:";
1162 let model_label = "Model:";
1163 let small_model_label = "Small Fast Model:";
1164 let max_thinking_tokens_label = "Max Thinking Tokens:";
1165 let api_timeout_ms_label = "API Timeout (ms):";
1166 let disable_nonessential_traffic_label = "Disable Nonessential Traffic:";
1167 let default_sonnet_model_label = "Default Sonnet Model:";
1168 let default_opus_model_label = "Default Opus Model:";
1169 let default_haiku_model_label = "Default Haiku Model:";
1170 let subagent_model_label = "Subagent Model:";
1171 let disable_nonstreaming_fallback_label = "Disable Nonstreaming Fallback:";
1172 let effort_level_label = "Effort Level:";
1173 let disable_prompt_caching_label = "Disable Prompt Caching:";
1174 let disable_experimental_betas_label = "Disable Experimental Betas:";
1175 let disable_autoupdater_label = "Disable Auto-Updater:";
1176
1177 let max_label_width = [
1179 token_label,
1180 url_label,
1181 model_label,
1182 small_model_label,
1183 max_thinking_tokens_label,
1184 api_timeout_ms_label,
1185 disable_nonessential_traffic_label,
1186 default_sonnet_model_label,
1187 default_opus_model_label,
1188 default_haiku_model_label,
1189 subagent_model_label,
1190 disable_nonstreaming_fallback_label,
1191 effort_level_label,
1192 disable_prompt_caching_label,
1193 disable_experimental_betas_label,
1194 disable_autoupdater_label,
1195 ]
1196 .iter()
1197 .map(|label| text_display_width(label))
1198 .max()
1199 .unwrap_or(0);
1200
1201 let (_, auth_value) = config.auth_env_pair();
1203 let token_line = format!(
1204 "{}{} {}",
1205 indent,
1206 pad_text_to_width(token_label, max_label_width, TextAlignment::Left, ' '),
1207 format_token_for_display(auth_value).dimmed()
1208 );
1209 lines.push(token_line);
1210
1211 let url_line = format!(
1213 "{}{} {}",
1214 indent,
1215 pad_text_to_width(url_label, max_label_width, TextAlignment::Left, ' '),
1216 config.url.cyan()
1217 );
1218 lines.push(url_line);
1219
1220 if let Some(model) = &config.model {
1222 let model_line = format!(
1223 "{}{} {}",
1224 indent,
1225 pad_text_to_width(model_label, max_label_width, TextAlignment::Left, ' '),
1226 model.yellow()
1227 );
1228 lines.push(model_line);
1229 }
1230
1231 if let Some(small_fast_model) = &config.small_fast_model {
1233 let small_model_line = format!(
1234 "{}{} {}",
1235 indent,
1236 pad_text_to_width(small_model_label, max_label_width, TextAlignment::Left, ' '),
1237 small_fast_model.yellow()
1238 );
1239 lines.push(small_model_line);
1240 }
1241
1242 if let Some(max_thinking_tokens) = config.max_thinking_tokens {
1244 let tokens_line = format!(
1245 "{}{} {}",
1246 indent,
1247 pad_text_to_width(
1248 max_thinking_tokens_label,
1249 max_label_width,
1250 TextAlignment::Left,
1251 ' '
1252 ),
1253 format!("{}", max_thinking_tokens).yellow()
1254 );
1255 lines.push(tokens_line);
1256 }
1257
1258 if let Some(api_timeout_ms) = config.api_timeout_ms {
1260 let timeout_line = format!(
1261 "{}{} {}",
1262 indent,
1263 pad_text_to_width(
1264 api_timeout_ms_label,
1265 max_label_width,
1266 TextAlignment::Left,
1267 ' '
1268 ),
1269 format!("{}", api_timeout_ms).yellow()
1270 );
1271 lines.push(timeout_line);
1272 }
1273
1274 if let Some(disable_flag) = config.claude_code_disable_nonessential_traffic {
1276 let flag_line = format!(
1277 "{}{} {}",
1278 indent,
1279 pad_text_to_width(
1280 disable_nonessential_traffic_label,
1281 max_label_width,
1282 TextAlignment::Left,
1283 ' '
1284 ),
1285 format!("{}", disable_flag).yellow()
1286 );
1287 lines.push(flag_line);
1288 }
1289
1290 if let Some(sonnet_model) = &config.anthropic_default_sonnet_model {
1292 let sonnet_line = format!(
1293 "{}{} {}",
1294 indent,
1295 pad_text_to_width(
1296 default_sonnet_model_label,
1297 max_label_width,
1298 TextAlignment::Left,
1299 ' '
1300 ),
1301 sonnet_model.yellow()
1302 );
1303 lines.push(sonnet_line);
1304 }
1305
1306 if let Some(opus_model) = &config.anthropic_default_opus_model {
1308 let opus_line = format!(
1309 "{}{} {}",
1310 indent,
1311 pad_text_to_width(
1312 default_opus_model_label,
1313 max_label_width,
1314 TextAlignment::Left,
1315 ' '
1316 ),
1317 opus_model.yellow()
1318 );
1319 lines.push(opus_line);
1320 }
1321
1322 if let Some(haiku_model) = &config.anthropic_default_haiku_model {
1324 let haiku_line = format!(
1325 "{}{} {}",
1326 indent,
1327 pad_text_to_width(
1328 default_haiku_model_label,
1329 max_label_width,
1330 TextAlignment::Left,
1331 ' '
1332 ),
1333 haiku_model.yellow()
1334 );
1335 lines.push(haiku_line);
1336 }
1337
1338 if let Some(subagent_model) = &config.claude_code_subagent_model {
1340 let subagent_line = format!(
1341 "{}{} {}",
1342 indent,
1343 pad_text_to_width(
1344 subagent_model_label,
1345 max_label_width,
1346 TextAlignment::Left,
1347 ' '
1348 ),
1349 subagent_model.yellow()
1350 );
1351 lines.push(subagent_line);
1352 }
1353
1354 if let Some(disable_flag) = config.claude_code_disable_nonstreaming_fallback {
1356 let flag_line = format!(
1357 "{}{} {}",
1358 indent,
1359 pad_text_to_width(
1360 disable_nonstreaming_fallback_label,
1361 max_label_width,
1362 TextAlignment::Left,
1363 ' '
1364 ),
1365 format!("{}", disable_flag).yellow()
1366 );
1367 lines.push(flag_line);
1368 }
1369
1370 if let Some(effort_level) = &config.claude_code_effort_level {
1372 let effort_line = format!(
1373 "{}{} {}",
1374 indent,
1375 pad_text_to_width(
1376 effort_level_label,
1377 max_label_width,
1378 TextAlignment::Left,
1379 ' '
1380 ),
1381 effort_level.yellow()
1382 );
1383 lines.push(effort_line);
1384 }
1385
1386 if let Some(disable_flag) = config.disable_prompt_caching {
1388 let flag_line = format!(
1389 "{}{} {}",
1390 indent,
1391 pad_text_to_width(
1392 disable_prompt_caching_label,
1393 max_label_width,
1394 TextAlignment::Left,
1395 ' '
1396 ),
1397 format!("{}", disable_flag).yellow()
1398 );
1399 lines.push(flag_line);
1400 }
1401
1402 if let Some(disable_flag) = config.claude_code_disable_experimental_betas {
1404 let flag_line = format!(
1405 "{}{} {}",
1406 indent,
1407 pad_text_to_width(
1408 disable_experimental_betas_label,
1409 max_label_width,
1410 TextAlignment::Left,
1411 ' '
1412 ),
1413 format!("{}", disable_flag).yellow()
1414 );
1415 lines.push(flag_line);
1416 }
1417
1418 if let Some(disable_flag) = config.disable_autoupdater {
1420 let flag_line = format!(
1421 "{}{} {}",
1422 indent,
1423 pad_text_to_width(
1424 disable_autoupdater_label,
1425 max_label_width,
1426 TextAlignment::Left,
1427 ' '
1428 ),
1429 format!("{}", disable_flag).yellow()
1430 );
1431 lines.push(flag_line);
1432 }
1433
1434 lines
1435}
1436
1437#[cfg(test)]
1438mod border_drawing_tests {
1439 use super::*;
1440
1441 #[test]
1442 fn test_border_drawing_unicode_support() {
1443 let _border = BorderDrawing::new();
1444 }
1446
1447 #[test]
1448 fn test_border_drawing_top_border() {
1449 let border = BorderDrawing {
1450 unicode_supported: true,
1451 };
1452 let result = border.draw_top_border("Test", 20);
1453 assert!(!result.is_empty());
1454 assert!(result.contains("Test"));
1455 }
1456
1457 #[test]
1458 fn test_border_drawing_ascii_fallback() {
1459 let border = BorderDrawing {
1460 unicode_supported: false,
1461 };
1462 let result = border.draw_top_border("Test", 20);
1463 assert!(!result.is_empty());
1464 assert!(result.contains("Test"));
1465 assert!(result.contains("+"));
1466 assert!(result.contains("-"));
1467 }
1468
1469 #[test]
1470 fn test_border_drawing_middle_line() {
1471 let border = BorderDrawing {
1472 unicode_supported: true,
1473 };
1474 let result = border.draw_middle_line("Test message", 30);
1475 assert!(!result.is_empty());
1476 assert!(result.contains("Test message"));
1477 }
1478
1479 #[test]
1480 fn test_border_drawing_bottom_border() {
1481 let border = BorderDrawing {
1482 unicode_supported: true,
1483 };
1484 let result = border.draw_bottom_border(20);
1485 assert!(!result.is_empty());
1486 }
1487
1488 #[test]
1489 fn test_border_drawing_width_consistency() {
1490 let border = BorderDrawing {
1491 unicode_supported: true,
1492 };
1493 let width = 30;
1494 let top = border.draw_top_border("Title", width);
1495 let middle = border.draw_middle_line("Content", width);
1496 let bottom = border.draw_bottom_border(width);
1497
1498 assert!(top.chars().count() >= width - 2);
1500 assert!(middle.chars().count() >= width - 2);
1501 assert!(bottom.chars().count() >= width - 2);
1502 }
1503}
1504
1505#[cfg(test)]
1506mod pagination_tests {
1507
1508 #[test]
1510 fn test_pagination_calculation() {
1511 const PAGE_SIZE: usize = 9;
1512
1513 assert_eq!(1_usize.div_ceil(PAGE_SIZE), 1); assert_eq!(9_usize.div_ceil(PAGE_SIZE), 1); assert_eq!(10_usize.div_ceil(PAGE_SIZE), 2); assert_eq!(18_usize.div_ceil(PAGE_SIZE), 2); assert_eq!(19_usize.div_ceil(PAGE_SIZE), 3); assert_eq!(27_usize.div_ceil(PAGE_SIZE), 3); assert_eq!(28_usize.div_ceil(PAGE_SIZE), 4); }
1524
1525 #[test]
1527 fn test_page_range_calculation() {
1528 const PAGE_SIZE: usize = 9;
1529
1530 let current_page = 0;
1532 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 0);
1535 assert_eq!(end_idx, 9);
1536 assert_eq!(end_idx - start_idx, 9); let current_page = 1;
1540 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 9);
1543 assert_eq!(end_idx, 15);
1544 assert_eq!(end_idx - start_idx, 6); let current_page = 0;
1548 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, PAGE_SIZE); assert_eq!(start_idx, 0);
1551 assert_eq!(end_idx, 9);
1552 assert_eq!(end_idx - start_idx, 9); }
1554
1555 #[test]
1557 fn test_digit_mapping_to_config_index() {
1558 const PAGE_SIZE: usize = 9;
1559
1560 let current_page = 0;
1562 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1566 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 0);
1568
1569 let digit = 9;
1571 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 8);
1573
1574 let current_page = 1;
1576 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1580 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 9);
1582
1583 let digit = 5;
1585 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 13);
1587 }
1588
1589 #[test]
1591 fn test_selection_index_conversion() {
1592 const PAGE_SIZE: usize = 9;
1599
1600 let current_page = 0;
1602 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1604 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 1);
1607
1608 let current_page = 1;
1610 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1612 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 10);
1615 }
1616
1617 #[test]
1619 fn test_page_navigation_bounds() {
1620 const PAGE_SIZE: usize = 9;
1621 let total_configs: usize = 25; let total_pages = total_configs.div_ceil(PAGE_SIZE); assert_eq!(total_pages, 3);
1624
1625 let mut current_page = 0;
1627 if current_page > 0 {
1628 current_page -= 1;
1629 }
1630 assert_eq!(current_page, 0); let mut current_page = total_pages - 1; if current_page < total_pages - 1 {
1635 current_page += 1;
1636 }
1637 assert_eq!(current_page, 2); let mut current_page = 1;
1641
1642 if current_page < total_pages - 1 {
1644 current_page += 1;
1645 }
1646 assert_eq!(current_page, 2);
1647
1648 if current_page > 0 {
1650 current_page = current_page.saturating_sub(1);
1651 }
1652 assert_eq!(current_page, 1);
1653 }
1654
1655 #[test]
1657 fn test_digit_key_boundary_conditions() {
1658 const PAGE_SIZE: usize = 9;
1659
1660 let digit = 0;
1662 assert!(digit < 1, "Digit 0 should be less than 1 and ignored");
1663
1664 let configs_len = 5; let page_configs_len = std::cmp::min(PAGE_SIZE, configs_len); let digit = 9; assert!(
1669 digit > page_configs_len,
1670 "Digit 9 should be beyond available configs (5) and ignored"
1671 );
1672
1673 for digit in 1..=page_configs_len {
1675 assert!(
1676 digit >= 1 && digit <= page_configs_len,
1677 "Digit {} should be valid",
1678 digit
1679 );
1680 }
1681 }
1682
1683 #[test]
1685 fn test_empty_configs_handling() {
1686 let empty_configs: Vec<String> = Vec::new();
1687 assert!(
1688 empty_configs.is_empty(),
1689 "Empty config list should be properly detected"
1690 );
1691
1692 let configs_len = empty_configs.len(); assert_eq!(configs_len, 0, "Empty configs should have length 0");
1695
1696 }
1699
1700 #[test]
1702 fn test_page_navigation_boundaries() {
1703 const PAGE_SIZE: usize = 9;
1704 let total_configs: usize = 20; let total_pages = total_configs.div_ceil(PAGE_SIZE); let mut current_page = 0;
1709 let original_page = current_page;
1710
1711 if current_page > 0 {
1713 current_page -= 1;
1714 }
1715 assert_eq!(
1716 current_page, original_page,
1717 "First page should not navigate to previous"
1718 );
1719
1720 let mut current_page = total_pages - 1; let original_page = current_page;
1723
1724 if current_page < total_pages - 1 {
1726 current_page += 1;
1727 }
1728 assert_eq!(
1729 current_page, original_page,
1730 "Last page should not navigate to next"
1731 );
1732
1733 let mut current_page = 1; if current_page < total_pages - 1 {
1738 current_page += 1;
1739 }
1740 assert_eq!(current_page, 2, "Should navigate to next page");
1741
1742 if current_page > 0 {
1744 current_page = current_page.saturating_sub(1);
1745 }
1746 assert_eq!(current_page, 1, "Should navigate to previous page");
1747 }
1748
1749 #[test]
1751 fn test_j_key_navigation() {
1752 let mut selected_index: usize = 0;
1753 let configs_len = 5; if selected_index < configs_len + 1 {
1758 selected_index += 1;
1759 }
1760 assert_eq!(selected_index, 1, "j key should move selection down by one");
1761
1762 selected_index = configs_len + 1;
1764 let original_index = selected_index;
1765 if selected_index < configs_len + 1 {
1766 selected_index += 1;
1767 }
1768 assert_eq!(
1769 selected_index, original_index,
1770 "j key should not move beyond bottom boundary"
1771 );
1772 }
1773
1774 #[test]
1776 fn test_k_key_navigation() {
1777 let mut selected_index: usize = 5;
1778
1779 selected_index = selected_index.saturating_sub(1);
1782 assert_eq!(selected_index, 4, "k key should move selection up by one");
1783
1784 selected_index = 0;
1786 let original_index = selected_index;
1787 selected_index = selected_index.saturating_sub(1);
1788 assert_eq!(
1789 selected_index, original_index,
1790 "k key should not move beyond top boundary"
1791 );
1792 }
1793
1794 #[test]
1796 fn test_jk_key_boundary_conditions() {
1797 const CONFIGS_LEN: usize = 5;
1798
1799 let mut selected_index: usize = CONFIGS_LEN + 1; let original_index = selected_index;
1802 if selected_index < CONFIGS_LEN + 1 {
1803 selected_index += 1; }
1805 assert_eq!(
1806 selected_index, original_index,
1807 "j key should respect bottom boundary like Down arrow"
1808 );
1809
1810 let mut selected_index: usize = 0; let original_index = selected_index;
1813 selected_index = selected_index.saturating_sub(1); assert_eq!(
1815 selected_index, original_index,
1816 "k key should respect top boundary like Up arrow"
1817 );
1818 }
1819}
1820
1821#[derive(Debug, PartialEq)]
1823pub(crate) enum EditModeError {
1824 ReturnToMenu,
1825}
1826
1827impl std::fmt::Display for EditModeError {
1828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1829 match self {
1830 EditModeError::ReturnToMenu => write!(f, "return_to_menu"),
1831 }
1832 }
1833}
1834
1835impl std::error::Error for EditModeError {}
1836
1837fn handle_config_edit(config: &Configuration) -> Result<()> {
1839 println!("\n{}", "配置编辑模式".green().bold());
1840 println!("{}", "===================".green());
1841 println!("正在编辑配置: {}", config.alias_name.cyan().bold());
1842 println!();
1843
1844 let mut editing_config = config.clone();
1846 let original_alias = config.alias_name.clone();
1847
1848 loop {
1849 display_edit_menu(&editing_config);
1851
1852 println!("\n{}", "提示: 可使用大小写字母".dimmed());
1854 print!("请选择要编辑的字段 (1-9, A-H), 或输入 S 保存, Q 返回上一级菜单: ");
1855 io::stdout().flush()?;
1856
1857 let mut input = String::new();
1858 io::stdin().read_line(&mut input)?;
1859 let input = input.trim();
1860
1861 match input {
1863 "1" => edit_field_alias(&mut editing_config)?,
1864 "2" => edit_field_token(&mut editing_config)?,
1865 "3" => edit_field_url(&mut editing_config)?,
1866 "4" => edit_field_model(&mut editing_config)?,
1867 "5" => edit_field_small_fast_model(&mut editing_config)?,
1868 "6" => edit_field_max_thinking_tokens(&mut editing_config)?,
1869 "7" => edit_field_api_timeout_ms(&mut editing_config)?,
1870 "8" => edit_field_claude_code_disable_nonessential_traffic(&mut editing_config)?,
1871 "9" => edit_field_anthropic_default_sonnet_model(&mut editing_config)?,
1872 "10" | "a" | "A" => edit_field_anthropic_default_opus_model(&mut editing_config)?,
1873 "11" | "b" | "B" => edit_field_anthropic_default_haiku_model(&mut editing_config)?,
1874 "12" | "c" | "C" => edit_field_claude_code_subagent_model(&mut editing_config)?,
1875 "13" | "d" | "D" => {
1876 edit_field_claude_code_disable_nonstreaming_fallback(&mut editing_config)?
1877 }
1878 "14" | "e" | "E" => edit_field_claude_code_effort_level(&mut editing_config)?,
1879 "15" | "f" | "F" => edit_field_disable_prompt_caching(&mut editing_config)?,
1880 "16" | "g" | "G" => {
1881 edit_field_claude_code_disable_experimental_betas(&mut editing_config)?
1882 }
1883 "17" | "h" | "H" => edit_field_disable_autoupdater(&mut editing_config)?,
1884 "s" | "S" => {
1885 return save_configuration_changes(&original_alias, &editing_config);
1887 }
1888 "q" | "Q" => {
1889 println!("\n{}", "返回上一级菜单".blue());
1890 return Err(EditModeError::ReturnToMenu.into());
1891 }
1892 _ => {
1893 println!("{}", "无效选择,请重试".red());
1894 }
1895 }
1896 }
1897}
1898
1899fn display_edit_menu(config: &Configuration) {
1901 println!("\n{}", "当前配置值:".blue().bold());
1902 println!("{}", "─────────────────────────".blue());
1903
1904 println!("1. 别名 (alias_name): {}", config.alias_name.green());
1905
1906 let (auth_label, auth_value) = config.auth_env_pair();
1907 println!(
1908 "2. 令牌 ({}): {}",
1909 auth_label,
1910 format_token_for_display(auth_value).green()
1911 );
1912
1913 println!("3. URL (ANTHROPIC_BASE_URL): {}", config.url.green());
1914
1915 println!(
1916 "4. 模型 (ANTHROPIC_MODEL): {}",
1917 config.model.as_deref().unwrap_or("[未设置]").green()
1918 );
1919
1920 println!(
1921 "5. 快速模型 (ANTHROPIC_SMALL_FAST_MODEL): {}",
1922 config
1923 .small_fast_model
1924 .as_deref()
1925 .unwrap_or("[未设置]")
1926 .green()
1927 );
1928
1929 println!(
1930 "6. 最大思考令牌数 (ANTHROPIC_MAX_THINKING_TOKENS): {}",
1931 config
1932 .max_thinking_tokens
1933 .map(|t| t.to_string())
1934 .unwrap_or("[未设置]".to_string())
1935 .green()
1936 );
1937
1938 println!(
1939 "7. API超时时间 (API_TIMEOUT_MS): {}",
1940 config
1941 .api_timeout_ms
1942 .map(|t| t.to_string())
1943 .unwrap_or("[未设置]".to_string())
1944 .green()
1945 );
1946
1947 println!(
1948 "8. 禁用非必要流量 (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC): {}",
1949 config
1950 .claude_code_disable_nonessential_traffic
1951 .map(|t| t.to_string())
1952 .unwrap_or("[未设置]".to_string())
1953 .green()
1954 );
1955
1956 println!(
1957 "9. 默认 Sonnet 模型 (ANTHROPIC_DEFAULT_SONNET_MODEL): {}",
1958 config
1959 .anthropic_default_sonnet_model
1960 .as_deref()
1961 .unwrap_or("[未设置]")
1962 .green()
1963 );
1964
1965 println!(
1966 "A. 默认 Opus 模型 (ANTHROPIC_DEFAULT_OPUS_MODEL): {}",
1967 config
1968 .anthropic_default_opus_model
1969 .as_deref()
1970 .unwrap_or("[未设置]")
1971 .green()
1972 );
1973
1974 println!(
1975 "B. 默认 Haiku 模型 (ANTHROPIC_DEFAULT_HAIKU_MODEL): {}",
1976 config
1977 .anthropic_default_haiku_model
1978 .as_deref()
1979 .unwrap_or("[未设置]")
1980 .green()
1981 );
1982
1983 println!(
1984 "C. 子代理模型 (CLAUDE_CODE_SUBAGENT_MODEL): {}",
1985 config
1986 .claude_code_subagent_model
1987 .as_deref()
1988 .unwrap_or("[未设置]")
1989 .green()
1990 );
1991
1992 println!(
1993 "D. 禁用非流式回退 (CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK): {}",
1994 config
1995 .claude_code_disable_nonstreaming_fallback
1996 .map(|t| t.to_string())
1997 .unwrap_or("[未设置]".to_string())
1998 .green()
1999 );
2000
2001 println!(
2002 "E. 努力级别 (CLAUDE_CODE_EFFORT_LEVEL): {}",
2003 config
2004 .claude_code_effort_level
2005 .as_deref()
2006 .unwrap_or("[未设置]")
2007 .green()
2008 );
2009
2010 println!(
2011 "F. 禁用提示缓存 (DISABLE_PROMPT_CACHING): {}",
2012 config
2013 .disable_prompt_caching
2014 .map(|t| t.to_string())
2015 .unwrap_or("[未设置]".to_string())
2016 .green()
2017 );
2018
2019 println!(
2020 "G. 禁用实验性功能 (CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS): {}",
2021 config
2022 .claude_code_disable_experimental_betas
2023 .map(|t| t.to_string())
2024 .unwrap_or("[未设置]".to_string())
2025 .green()
2026 );
2027
2028 println!(
2029 "H. 禁用自动更新 (DISABLE_AUTOUPDATER): {}",
2030 config
2031 .disable_autoupdater
2032 .map(|t| t.to_string())
2033 .unwrap_or("[未设置]".to_string())
2034 .green()
2035 );
2036
2037 println!("{}", "─────────────────────────".blue());
2038 println!(
2039 "S. {} | Q. {}",
2040 "保存更改".green().bold(),
2041 "返回上一级菜单".blue()
2042 );
2043}
2044
2045pub(crate) fn edit_string_field(
2047 field_name: &str,
2048 current_value: &str,
2049 validator: impl Fn(&str) -> Result<()>,
2050) -> Result<Option<String>> {
2051 println!("\n编辑{field_name}:");
2052 println!("当前值: {}", current_value.cyan());
2053 print!("新值 (回车保持不变): ");
2054 io::stdout().flush()?;
2055
2056 let mut input = String::new();
2057 io::stdin().read_line(&mut input)?;
2058 let input = input.trim();
2059
2060 if !input.is_empty() {
2061 validator(input)?;
2062 println!("{field_name}已更新为: {}", input.green());
2063 Ok(Some(input.to_string()))
2064 } else {
2065 Ok(None)
2066 }
2067}
2068
2069pub(crate) type OptionalStringResult = Result<Option<Option<String>>>;
2071
2072pub(crate) fn edit_optional_string_field(
2074 field_name: &str,
2075 current_value: Option<&str>,
2076) -> OptionalStringResult {
2077 println!("\n编辑{field_name}:");
2078 println!("当前值: {}", current_value.unwrap_or("[未设置]").cyan());
2079 print!("新值 (回车保持不变,输入空格清除): ");
2080 io::stdout().flush()?;
2081
2082 let mut input = String::new();
2083 io::stdin().read_line(&mut input)?;
2084 let input = input.trim();
2085
2086 if !input.is_empty() {
2087 if input == " " {
2088 println!("{}", format!("{field_name}已清除").green());
2089 Ok(Some(None))
2090 } else {
2091 println!("{field_name}已更新为: {}", input.green());
2092 Ok(Some(Some(input.to_string())))
2093 }
2094 } else {
2095 Ok(None)
2096 }
2097}
2098
2099type OptionalU32Result = Result<Option<Option<u32>>>;
2101
2102fn edit_optional_u32_field(field_name: &str, current_value: Option<u32>) -> OptionalU32Result {
2104 println!("\n编辑{field_name}:");
2105 println!(
2106 "当前值: {}",
2107 current_value
2108 .map(|t| t.to_string())
2109 .unwrap_or("[未设置]".to_string())
2110 .cyan()
2111 );
2112 print!("新值 (回车保持不变,输入 0 清除): ");
2113 io::stdout().flush()?;
2114
2115 let mut input = String::new();
2116 io::stdin().read_line(&mut input)?;
2117 let input = input.trim();
2118
2119 if !input.is_empty() {
2120 if input == "0" {
2121 println!("{}", format!("{field_name}已清除").green());
2122 Ok(Some(None))
2123 } else if let Ok(value) = input.parse::<u32>() {
2124 println!("{field_name}已更新为: {}", value.to_string().green());
2125 Ok(Some(Some(value)))
2126 } else {
2127 println!("{}", "错误: 请输入有效的数字".red());
2128 Ok(None)
2129 }
2130 } else {
2131 Ok(None)
2132 }
2133}
2134
2135fn edit_field_alias(config: &mut Configuration) -> Result<()> {
2137 let validator = |input: &str| -> Result<()> {
2138 if input.contains(char::is_whitespace) {
2139 anyhow::bail!("错误: 别名不能包含空白字符");
2140 }
2141 if input == "cc" {
2142 anyhow::bail!("错误: 'cc' 是保留名称");
2143 }
2144 if input == "official" {
2145 anyhow::bail!("错误: 'official' 是保留名称");
2146 }
2147 Ok(())
2148 };
2149
2150 match edit_string_field("别名", &config.alias_name, validator) {
2151 Ok(Some(new_value)) => config.alias_name = new_value,
2152 Ok(None) => {}
2153 Err(e) => println!("{}", e.to_string().red()),
2154 }
2155 Ok(())
2156}
2157
2158fn edit_field_token(config: &mut Configuration) -> Result<()> {
2160 let (auth_label, auth_value) = config.auth_env_pair();
2161 let label = format!("令牌 ({})", auth_label);
2162 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2163
2164 let auth_type = read_input("切换认证类型? (1) AUTH_TOKEN (2) API_KEY (Enter 保持不变): ")?;
2165 match auth_type.as_str() {
2166 "2" => {
2167 if let Some(new_value) =
2168 edit_string_field(&label, &format_token_for_display(auth_value), no_validator)?
2169 {
2170 config.api_key = Some(new_value);
2171 config.token = String::new();
2172 println!("{}", "已切换到 ANTHROPIC_API_KEY 并更新".green());
2173 }
2174 }
2175 "1" => {
2176 if let Some(new_value) =
2177 edit_string_field(&label, &format_token_for_display(auth_value), no_validator)?
2178 {
2179 config.token = new_value;
2180 config.api_key = None;
2181 println!("{}", "已切换到 ANTHROPIC_AUTH_TOKEN 并更新".green());
2182 }
2183 }
2184 _ => {
2185 if let Some(new_value) =
2186 edit_string_field(&label, &format_token_for_display(auth_value), no_validator)?
2187 {
2188 if config.api_key.is_some() {
2189 config.api_key = Some(new_value);
2190 } else {
2191 config.token = new_value;
2192 }
2193 println!("{}", "令牌已更新".green());
2194 }
2195 }
2196 }
2197 Ok(())
2198}
2199
2200fn edit_field_url(config: &mut Configuration) -> Result<()> {
2202 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2203 if let Some(new_value) = edit_string_field("URL", &config.url, no_validator)? {
2204 config.url = new_value;
2205 }
2206 Ok(())
2207}
2208
2209fn edit_field_model(config: &mut Configuration) -> Result<()> {
2211 if let Some(result) = edit_optional_string_field("模型", config.model.as_deref())? {
2212 config.model = result;
2213 }
2214 Ok(())
2215}
2216
2217fn edit_field_small_fast_model(config: &mut Configuration) -> Result<()> {
2219 if let Some(result) =
2220 edit_optional_string_field("快速模型", config.small_fast_model.as_deref())?
2221 {
2222 config.small_fast_model = result;
2223 }
2224 Ok(())
2225}
2226
2227fn edit_field_max_thinking_tokens(config: &mut Configuration) -> Result<()> {
2229 if let Some(result) = edit_optional_u32_field("最大思考令牌数", config.max_thinking_tokens)?
2230 {
2231 config.max_thinking_tokens = result;
2232 }
2233 Ok(())
2234}
2235
2236fn edit_field_api_timeout_ms(config: &mut Configuration) -> Result<()> {
2238 if let Some(result) = edit_optional_u32_field("API超时时间 (毫秒)", config.api_timeout_ms)?
2239 {
2240 config.api_timeout_ms = result;
2241 }
2242 Ok(())
2243}
2244
2245fn edit_field_claude_code_disable_nonessential_traffic(config: &mut Configuration) -> Result<()> {
2247 if let Some(result) = edit_optional_u32_field(
2248 "禁用非必要流量标志",
2249 config.claude_code_disable_nonessential_traffic,
2250 )? {
2251 config.claude_code_disable_nonessential_traffic = result;
2252 }
2253 Ok(())
2254}
2255
2256fn edit_field_anthropic_default_sonnet_model(config: &mut Configuration) -> Result<()> {
2258 if let Some(result) = edit_optional_string_field(
2259 "默认 Sonnet 模型",
2260 config.anthropic_default_sonnet_model.as_deref(),
2261 )? {
2262 config.anthropic_default_sonnet_model = result;
2263 }
2264 Ok(())
2265}
2266
2267fn edit_field_anthropic_default_opus_model(config: &mut Configuration) -> Result<()> {
2269 if let Some(result) = edit_optional_string_field(
2270 "默认 Opus 模型",
2271 config.anthropic_default_opus_model.as_deref(),
2272 )? {
2273 config.anthropic_default_opus_model = result;
2274 }
2275 Ok(())
2276}
2277
2278fn edit_field_anthropic_default_haiku_model(config: &mut Configuration) -> Result<()> {
2280 if let Some(result) = edit_optional_string_field(
2281 "默认 Haiku 模型",
2282 config.anthropic_default_haiku_model.as_deref(),
2283 )? {
2284 config.anthropic_default_haiku_model = result;
2285 }
2286 Ok(())
2287}
2288
2289fn edit_field_claude_code_subagent_model(config: &mut Configuration) -> Result<()> {
2291 if let Some(result) =
2292 edit_optional_string_field("子代理模型", config.claude_code_subagent_model.as_deref())?
2293 {
2294 config.claude_code_subagent_model = result;
2295 }
2296 Ok(())
2297}
2298
2299fn edit_field_claude_code_disable_nonstreaming_fallback(config: &mut Configuration) -> Result<()> {
2301 if let Some(result) = edit_optional_u32_field(
2302 "禁用非流式回退标志",
2303 config.claude_code_disable_nonstreaming_fallback,
2304 )? {
2305 config.claude_code_disable_nonstreaming_fallback = result;
2306 }
2307 Ok(())
2308}
2309
2310fn edit_field_claude_code_effort_level(config: &mut Configuration) -> Result<()> {
2312 if let Some(result) =
2313 edit_optional_string_field("努力级别", config.claude_code_effort_level.as_deref())?
2314 {
2315 config.claude_code_effort_level = result;
2316 }
2317 Ok(())
2318}
2319
2320fn edit_field_disable_prompt_caching(config: &mut Configuration) -> Result<()> {
2322 if let Some(result) =
2323 edit_optional_u32_field("禁用提示缓存标志", config.disable_prompt_caching)?
2324 {
2325 config.disable_prompt_caching = result;
2326 }
2327 Ok(())
2328}
2329
2330fn edit_field_claude_code_disable_experimental_betas(config: &mut Configuration) -> Result<()> {
2332 if let Some(result) = edit_optional_u32_field(
2333 "禁用实验性功能标志",
2334 config.claude_code_disable_experimental_betas,
2335 )? {
2336 config.claude_code_disable_experimental_betas = result;
2337 }
2338 Ok(())
2339}
2340
2341fn edit_field_disable_autoupdater(config: &mut Configuration) -> Result<()> {
2343 if let Some(result) = edit_optional_u32_field("禁用自动更新标志", config.disable_autoupdater)?
2344 {
2345 config.disable_autoupdater = result;
2346 }
2347 Ok(())
2348}
2349
2350fn save_configuration_changes(original_alias: &str, new_config: &Configuration) -> Result<()> {
2352 let mut storage = ConfigStorage::load()?;
2354
2355 if original_alias != new_config.alias_name
2357 && storage.get_configuration(&new_config.alias_name).is_some()
2358 {
2359 println!("\n{}", "别名冲突!".red().bold());
2360 println!("配置 '{}' 已存在", new_config.alias_name.yellow());
2361 print!("是否覆盖现有配置? (y/N): ");
2362 io::stdout().flush()?;
2363
2364 let mut input = String::new();
2365 io::stdin().read_line(&mut input)?;
2366 let input = input.trim().to_lowercase();
2367
2368 if input != "y" && input != "yes" {
2369 println!("{}", "编辑已取消".yellow());
2370 return Ok(());
2371 }
2372 }
2373
2374 storage.update_configuration(original_alias, new_config.clone())?;
2376 storage.save()?;
2377
2378 println!("\n{}", "配置已成功保存!".green().bold());
2379
2380 Ok(())
2381}