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");
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(EnvironmentConfig::empty(), None, None, false);
798 }
799 "e" => {
800 println!("编辑功能在交互式菜单中可用");
803 }
804 "q" => {
805 println!("Exiting...");
806 return Ok(());
807 }
808 "n" if total_pages > 1 && current_page < total_pages - 1 => {
809 current_page += 1;
810 continue;
811 }
812 "p" if total_pages > 1 && current_page > 0 => {
813 current_page -= 1;
814 continue;
815 }
816 digit_str => {
817 if let Ok(digit) = digit_str.parse::<usize>()
818 && digit >= 1
819 && digit <= page_configs.len()
820 {
821 let actual_config_index = start_idx + (digit - 1);
822 let selection_index = actual_config_index + 1; let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
824 return handle_selection_action(
825 configs,
826 selection_index,
827 storage,
828 storage_mode,
829 );
830 }
831 println!("无效选择,请重新输入");
832 }
833 }
834 }
835}
836
837fn handle_simple_single_page_menu(
839 configs: &[&Configuration],
840 storage: &ConfigStorage,
841) -> Result<()> {
842 println!("\n{}", "Available Configurations:".blue().bold());
843
844 println!("1. {}", "official".red());
846 println!(" Use official Claude API (no custom configuration)");
847 println!();
848
849 for (index, config) in configs.iter().enumerate() {
850 println!(
851 "{}. {}",
852 index + 2, config.alias_name.green()
854 );
855
856 let details = format_config_details(config, " ", true);
858 for detail_line in details {
859 println!("{detail_line}");
860 }
861 println!();
862 }
863
864 println!("{}. {}", configs.len() + 2, "Exit".yellow());
865
866 print!("\nSelect configuration (1-{}): ", configs.len() + 2);
867 io::stdout().flush()?;
868
869 let mut input = String::new();
870 io::stdin().read_line(&mut input)?;
871
872 match input.trim().parse::<usize>() {
873 Ok(1) => {
874 println!("Using official Claude configuration");
876
877 let mut settings = crate::config::types::ClaudeSettings::load(
879 storage.get_claude_settings_dir().map(|s| s.as_str()),
880 )?;
881 settings.remove_anthropic_env();
882 settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
883
884 launch_claude_with_env(EnvironmentConfig::empty(), None, None, false)
885 }
886 Ok(num) if num >= 2 && num <= configs.len() + 1 => {
887 let storage_mode = storage.default_storage_mode.clone().unwrap_or_default();
888 handle_selection_action(configs, num - 1, storage, storage_mode) }
890 Ok(num) if num == configs.len() + 2 => {
891 println!("Exiting...");
892 Ok(())
893 }
894 _ => {
895 println!("Invalid selection");
896 Ok(())
897 }
898 }
899}
900
901fn handle_selection_action(
903 configs: &[&Configuration],
904 selected_index: usize,
905 storage: &ConfigStorage,
906 storage_mode: crate::config::types::StorageMode,
907) -> Result<()> {
908 if selected_index == 0 {
909 println!("\nUsing official Claude configuration");
911
912 let mut settings = crate::config::types::ClaudeSettings::load(
914 storage.get_claude_settings_dir().map(|s| s.as_str()),
915 )?;
916 settings.remove_anthropic_env();
917 settings.save(storage.get_claude_settings_dir().map(|s| s.as_str()))?;
918
919 launch_claude_with_env(
920 EnvironmentConfig::empty().with_alias("official"),
921 None,
922 None,
923 false,
924 )
925 } else if selected_index <= configs.len() {
926 let config_index = selected_index - 1; let selected_config = configs[config_index].clone();
929 let env_config = EnvironmentConfig::from_config(&selected_config)
930 .with_alias(&selected_config.alias_name);
931
932 println!(
933 "\nSwitched to configuration '{}'",
934 selected_config.alias_name.green().bold()
935 );
936
937 let details = format_config_details(&selected_config, "", false);
939 for detail_line in details {
940 println!("{detail_line}");
941 }
942
943 let mut settings = crate::config::types::ClaudeSettings::load(
945 storage.get_claude_settings_dir().map(|s| s.as_str()),
946 )?;
947 settings.switch_to_config_with_mode(
948 &selected_config,
949 storage_mode,
950 storage.get_claude_settings_dir().map(|s| s.as_str()),
951 )?;
952
953 launch_claude_with_env(env_config, None, None, false)
954 } else {
955 println!("\nExiting...");
957 Ok(())
958 }
959}
960
961pub fn launch_claude_with_env(
963 env_config: EnvironmentConfig,
964 prompt: Option<&str>,
965 resume: Option<&str>,
966 continue_session: bool,
967) -> Result<()> {
968 println!("\nLaunching Claude CLI...");
969
970 let _ = ClaudeSettings::cleanup_orphan_alias_files();
972
973 if let Some(alias) = env_config.env_vars.get("CC_SWITCH_CURRENT_ALIAS") {
977 ClaudeSettings::write_current_alias_for_pid(alias)?;
978 }
979
980 #[cfg(unix)]
982 {
983 use std::os::unix::process::CommandExt;
984 let mut command = Command::new(resolve_npm_cli("claude"));
985 command.envs(env_config.as_env_tuples());
987 command.arg("--dangerously-skip-permissions");
988 if let Some(session_id) = resume {
989 command.args(["--resume", session_id]);
990 }
991 if continue_session {
992 command.arg("--continue");
993 }
994 if let Some(p) = prompt {
995 command.arg(p);
996 }
997 let error = command.exec();
998 let _ = ClaudeSettings::clear_current_alias_for_pid();
1001 anyhow::bail!("Failed to exec claude: {}", error);
1002 }
1003
1004 #[cfg(not(unix))]
1006 {
1007 use std::process::Stdio;
1008 let mut command = Command::new(resolve_npm_cli("claude"));
1009 command.envs(env_config.as_env_tuples());
1011 command.arg("--dangerously-skip-permissions");
1012 if let Some(session_id) = resume {
1013 command.args(["--resume", session_id]);
1014 }
1015 if continue_session {
1016 command.arg("--continue");
1017 }
1018 if let Some(p) = prompt {
1019 command.arg(p);
1020 }
1021 command
1022 .stdin(Stdio::inherit())
1023 .stdout(Stdio::inherit())
1024 .stderr(Stdio::inherit());
1025
1026 let mut child = command.spawn().context(
1027 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1028 )?;
1029
1030 let status = child.wait()?;
1031
1032 let _ = ClaudeSettings::clear_current_alias_for_pid();
1034
1035 if !status.success() {
1036 anyhow::bail!("Claude CLI exited with error status: {}", status);
1037 }
1038 Ok(())
1039 }
1040}
1041
1042fn execute_claude_command(skip_permissions: bool) -> Result<()> {
1047 println!("Launching Claude CLI...");
1048
1049 #[cfg(unix)]
1051 {
1052 use std::os::unix::process::CommandExt;
1053 let mut command = Command::new(resolve_npm_cli("claude"));
1054 if skip_permissions {
1055 command.arg("--dangerously-skip-permissions");
1056 }
1057
1058 let error = command.exec();
1059 anyhow::bail!("Failed to exec claude: {}", error);
1061 }
1062
1063 #[cfg(not(unix))]
1065 {
1066 use std::process::Stdio;
1067 let mut command = Command::new(resolve_npm_cli("claude"));
1068 if skip_permissions {
1069 command.arg("--dangerously-skip-permissions");
1070 }
1071
1072 command
1073 .stdin(Stdio::inherit())
1074 .stdout(Stdio::inherit())
1075 .stderr(Stdio::inherit());
1076
1077 let mut child = command.spawn().context(
1078 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1079 )?;
1080
1081 let status = child
1082 .wait()
1083 .context("Failed to wait for Claude CLI process")?;
1084
1085 if !status.success() {
1086 anyhow::bail!("Claude CLI exited with error status: {}", status);
1087 }
1088 Ok(())
1089 }
1090}
1091
1092pub fn read_input(prompt: &str) -> Result<String> {
1100 print!("{prompt}");
1101 io::stdout().flush().context("Failed to flush stdout")?;
1102 let mut input = String::new();
1103 io::stdin()
1104 .read_line(&mut input)
1105 .context("Failed to read input")?;
1106 Ok(input.trim().to_string())
1107}
1108
1109pub fn read_sensitive_input(prompt: &str) -> Result<String> {
1117 print!("{prompt}");
1118 io::stdout().flush().context("Failed to flush stdout")?;
1119 let mut input = String::new();
1120 io::stdin()
1121 .read_line(&mut input)
1122 .context("Failed to read input")?;
1123 Ok(input.trim().to_string())
1124}
1125
1126fn format_config_details(config: &Configuration, indent: &str, _compact: bool) -> Vec<String> {
1139 let mut lines = Vec::new();
1140
1141 let terminal_width = get_terminal_width();
1143 let _available_width = terminal_width.saturating_sub(text_display_width(indent) + 8);
1144
1145 let token_label = "Token:";
1147 let url_label = "URL:";
1148 let model_label = "Model:";
1149 let small_model_label = "Small Fast Model:";
1150 let max_thinking_tokens_label = "Max Thinking Tokens:";
1151 let api_timeout_ms_label = "API Timeout (ms):";
1152 let disable_nonessential_traffic_label = "Disable Nonessential Traffic:";
1153 let default_sonnet_model_label = "Default Sonnet Model:";
1154 let default_opus_model_label = "Default Opus Model:";
1155 let default_haiku_model_label = "Default Haiku Model:";
1156 let subagent_model_label = "Subagent Model:";
1157 let disable_nonstreaming_fallback_label = "Disable Nonstreaming Fallback:";
1158 let effort_level_label = "Effort Level:";
1159 let disable_prompt_caching_label = "Disable Prompt Caching:";
1160 let disable_experimental_betas_label = "Disable Experimental Betas:";
1161 let disable_autoupdater_label = "Disable Auto-Updater:";
1162
1163 let max_label_width = [
1165 token_label,
1166 url_label,
1167 model_label,
1168 small_model_label,
1169 max_thinking_tokens_label,
1170 api_timeout_ms_label,
1171 disable_nonessential_traffic_label,
1172 default_sonnet_model_label,
1173 default_opus_model_label,
1174 default_haiku_model_label,
1175 subagent_model_label,
1176 disable_nonstreaming_fallback_label,
1177 effort_level_label,
1178 disable_prompt_caching_label,
1179 disable_experimental_betas_label,
1180 disable_autoupdater_label,
1181 ]
1182 .iter()
1183 .map(|label| text_display_width(label))
1184 .max()
1185 .unwrap_or(0);
1186
1187 let token_line = format!(
1189 "{}{} {}",
1190 indent,
1191 pad_text_to_width(token_label, max_label_width, TextAlignment::Left, ' '),
1192 format_token_for_display(&config.token).dimmed()
1193 );
1194 lines.push(token_line);
1195
1196 let url_line = format!(
1198 "{}{} {}",
1199 indent,
1200 pad_text_to_width(url_label, max_label_width, TextAlignment::Left, ' '),
1201 config.url.cyan()
1202 );
1203 lines.push(url_line);
1204
1205 if let Some(model) = &config.model {
1207 let model_line = format!(
1208 "{}{} {}",
1209 indent,
1210 pad_text_to_width(model_label, max_label_width, TextAlignment::Left, ' '),
1211 model.yellow()
1212 );
1213 lines.push(model_line);
1214 }
1215
1216 if let Some(small_fast_model) = &config.small_fast_model {
1218 let small_model_line = format!(
1219 "{}{} {}",
1220 indent,
1221 pad_text_to_width(small_model_label, max_label_width, TextAlignment::Left, ' '),
1222 small_fast_model.yellow()
1223 );
1224 lines.push(small_model_line);
1225 }
1226
1227 if let Some(max_thinking_tokens) = config.max_thinking_tokens {
1229 let tokens_line = format!(
1230 "{}{} {}",
1231 indent,
1232 pad_text_to_width(
1233 max_thinking_tokens_label,
1234 max_label_width,
1235 TextAlignment::Left,
1236 ' '
1237 ),
1238 format!("{}", max_thinking_tokens).yellow()
1239 );
1240 lines.push(tokens_line);
1241 }
1242
1243 if let Some(api_timeout_ms) = config.api_timeout_ms {
1245 let timeout_line = format!(
1246 "{}{} {}",
1247 indent,
1248 pad_text_to_width(
1249 api_timeout_ms_label,
1250 max_label_width,
1251 TextAlignment::Left,
1252 ' '
1253 ),
1254 format!("{}", api_timeout_ms).yellow()
1255 );
1256 lines.push(timeout_line);
1257 }
1258
1259 if let Some(disable_flag) = config.claude_code_disable_nonessential_traffic {
1261 let flag_line = format!(
1262 "{}{} {}",
1263 indent,
1264 pad_text_to_width(
1265 disable_nonessential_traffic_label,
1266 max_label_width,
1267 TextAlignment::Left,
1268 ' '
1269 ),
1270 format!("{}", disable_flag).yellow()
1271 );
1272 lines.push(flag_line);
1273 }
1274
1275 if let Some(sonnet_model) = &config.anthropic_default_sonnet_model {
1277 let sonnet_line = format!(
1278 "{}{} {}",
1279 indent,
1280 pad_text_to_width(
1281 default_sonnet_model_label,
1282 max_label_width,
1283 TextAlignment::Left,
1284 ' '
1285 ),
1286 sonnet_model.yellow()
1287 );
1288 lines.push(sonnet_line);
1289 }
1290
1291 if let Some(opus_model) = &config.anthropic_default_opus_model {
1293 let opus_line = format!(
1294 "{}{} {}",
1295 indent,
1296 pad_text_to_width(
1297 default_opus_model_label,
1298 max_label_width,
1299 TextAlignment::Left,
1300 ' '
1301 ),
1302 opus_model.yellow()
1303 );
1304 lines.push(opus_line);
1305 }
1306
1307 if let Some(haiku_model) = &config.anthropic_default_haiku_model {
1309 let haiku_line = format!(
1310 "{}{} {}",
1311 indent,
1312 pad_text_to_width(
1313 default_haiku_model_label,
1314 max_label_width,
1315 TextAlignment::Left,
1316 ' '
1317 ),
1318 haiku_model.yellow()
1319 );
1320 lines.push(haiku_line);
1321 }
1322
1323 if let Some(subagent_model) = &config.claude_code_subagent_model {
1325 let subagent_line = format!(
1326 "{}{} {}",
1327 indent,
1328 pad_text_to_width(
1329 subagent_model_label,
1330 max_label_width,
1331 TextAlignment::Left,
1332 ' '
1333 ),
1334 subagent_model.yellow()
1335 );
1336 lines.push(subagent_line);
1337 }
1338
1339 if let Some(disable_flag) = config.claude_code_disable_nonstreaming_fallback {
1341 let flag_line = format!(
1342 "{}{} {}",
1343 indent,
1344 pad_text_to_width(
1345 disable_nonstreaming_fallback_label,
1346 max_label_width,
1347 TextAlignment::Left,
1348 ' '
1349 ),
1350 format!("{}", disable_flag).yellow()
1351 );
1352 lines.push(flag_line);
1353 }
1354
1355 if let Some(effort_level) = &config.claude_code_effort_level {
1357 let effort_line = format!(
1358 "{}{} {}",
1359 indent,
1360 pad_text_to_width(
1361 effort_level_label,
1362 max_label_width,
1363 TextAlignment::Left,
1364 ' '
1365 ),
1366 effort_level.yellow()
1367 );
1368 lines.push(effort_line);
1369 }
1370
1371 if let Some(disable_flag) = config.disable_prompt_caching {
1373 let flag_line = format!(
1374 "{}{} {}",
1375 indent,
1376 pad_text_to_width(
1377 disable_prompt_caching_label,
1378 max_label_width,
1379 TextAlignment::Left,
1380 ' '
1381 ),
1382 format!("{}", disable_flag).yellow()
1383 );
1384 lines.push(flag_line);
1385 }
1386
1387 if let Some(disable_flag) = config.claude_code_disable_experimental_betas {
1389 let flag_line = format!(
1390 "{}{} {}",
1391 indent,
1392 pad_text_to_width(
1393 disable_experimental_betas_label,
1394 max_label_width,
1395 TextAlignment::Left,
1396 ' '
1397 ),
1398 format!("{}", disable_flag).yellow()
1399 );
1400 lines.push(flag_line);
1401 }
1402
1403 if let Some(disable_flag) = config.disable_autoupdater {
1405 let flag_line = format!(
1406 "{}{} {}",
1407 indent,
1408 pad_text_to_width(
1409 disable_autoupdater_label,
1410 max_label_width,
1411 TextAlignment::Left,
1412 ' '
1413 ),
1414 format!("{}", disable_flag).yellow()
1415 );
1416 lines.push(flag_line);
1417 }
1418
1419 lines
1420}
1421
1422#[cfg(test)]
1423mod border_drawing_tests {
1424 use super::*;
1425
1426 #[test]
1427 fn test_border_drawing_unicode_support() {
1428 let _border = BorderDrawing::new();
1429 }
1431
1432 #[test]
1433 fn test_border_drawing_top_border() {
1434 let border = BorderDrawing {
1435 unicode_supported: true,
1436 };
1437 let result = border.draw_top_border("Test", 20);
1438 assert!(!result.is_empty());
1439 assert!(result.contains("Test"));
1440 }
1441
1442 #[test]
1443 fn test_border_drawing_ascii_fallback() {
1444 let border = BorderDrawing {
1445 unicode_supported: false,
1446 };
1447 let result = border.draw_top_border("Test", 20);
1448 assert!(!result.is_empty());
1449 assert!(result.contains("Test"));
1450 assert!(result.contains("+"));
1451 assert!(result.contains("-"));
1452 }
1453
1454 #[test]
1455 fn test_border_drawing_middle_line() {
1456 let border = BorderDrawing {
1457 unicode_supported: true,
1458 };
1459 let result = border.draw_middle_line("Test message", 30);
1460 assert!(!result.is_empty());
1461 assert!(result.contains("Test message"));
1462 }
1463
1464 #[test]
1465 fn test_border_drawing_bottom_border() {
1466 let border = BorderDrawing {
1467 unicode_supported: true,
1468 };
1469 let result = border.draw_bottom_border(20);
1470 assert!(!result.is_empty());
1471 }
1472
1473 #[test]
1474 fn test_border_drawing_width_consistency() {
1475 let border = BorderDrawing {
1476 unicode_supported: true,
1477 };
1478 let width = 30;
1479 let top = border.draw_top_border("Title", width);
1480 let middle = border.draw_middle_line("Content", width);
1481 let bottom = border.draw_bottom_border(width);
1482
1483 assert!(top.chars().count() >= width - 2);
1485 assert!(middle.chars().count() >= width - 2);
1486 assert!(bottom.chars().count() >= width - 2);
1487 }
1488}
1489
1490#[cfg(test)]
1491mod pagination_tests {
1492
1493 #[test]
1495 fn test_pagination_calculation() {
1496 const PAGE_SIZE: usize = 9;
1497
1498 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); }
1509
1510 #[test]
1512 fn test_page_range_calculation() {
1513 const PAGE_SIZE: usize = 9;
1514
1515 let current_page = 0;
1517 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 0);
1520 assert_eq!(end_idx, 9);
1521 assert_eq!(end_idx - start_idx, 9); let current_page = 1;
1525 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 9);
1528 assert_eq!(end_idx, 15);
1529 assert_eq!(end_idx - start_idx, 6); let current_page = 0;
1533 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, PAGE_SIZE); assert_eq!(start_idx, 0);
1536 assert_eq!(end_idx, 9);
1537 assert_eq!(end_idx - start_idx, 9); }
1539
1540 #[test]
1542 fn test_digit_mapping_to_config_index() {
1543 const PAGE_SIZE: usize = 9;
1544
1545 let current_page = 0;
1547 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1551 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 0);
1553
1554 let digit = 9;
1556 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 8);
1558
1559 let current_page = 1;
1561 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1565 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 9);
1567
1568 let digit = 5;
1570 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 13);
1572 }
1573
1574 #[test]
1576 fn test_selection_index_conversion() {
1577 const PAGE_SIZE: usize = 9;
1584
1585 let current_page = 0;
1587 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1589 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 1);
1592
1593 let current_page = 1;
1595 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1597 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 10);
1600 }
1601
1602 #[test]
1604 fn test_page_navigation_bounds() {
1605 const PAGE_SIZE: usize = 9;
1606 let total_configs: usize = 25; let total_pages = total_configs.div_ceil(PAGE_SIZE); assert_eq!(total_pages, 3);
1609
1610 let mut current_page = 0;
1612 if current_page > 0 {
1613 current_page -= 1;
1614 }
1615 assert_eq!(current_page, 0); let mut current_page = total_pages - 1; if current_page < total_pages - 1 {
1620 current_page += 1;
1621 }
1622 assert_eq!(current_page, 2); let mut current_page = 1;
1626
1627 if current_page < total_pages - 1 {
1629 current_page += 1;
1630 }
1631 assert_eq!(current_page, 2);
1632
1633 if current_page > 0 {
1635 current_page = current_page.saturating_sub(1);
1636 }
1637 assert_eq!(current_page, 1);
1638 }
1639
1640 #[test]
1642 fn test_digit_key_boundary_conditions() {
1643 const PAGE_SIZE: usize = 9;
1644
1645 let digit = 0;
1647 assert!(digit < 1, "Digit 0 should be less than 1 and ignored");
1648
1649 let configs_len = 5; let page_configs_len = std::cmp::min(PAGE_SIZE, configs_len); let digit = 9; assert!(
1654 digit > page_configs_len,
1655 "Digit 9 should be beyond available configs (5) and ignored"
1656 );
1657
1658 for digit in 1..=page_configs_len {
1660 assert!(
1661 digit >= 1 && digit <= page_configs_len,
1662 "Digit {} should be valid",
1663 digit
1664 );
1665 }
1666 }
1667
1668 #[test]
1670 fn test_empty_configs_handling() {
1671 let empty_configs: Vec<String> = Vec::new();
1672 assert!(
1673 empty_configs.is_empty(),
1674 "Empty config list should be properly detected"
1675 );
1676
1677 let configs_len = empty_configs.len(); assert_eq!(configs_len, 0, "Empty configs should have length 0");
1680
1681 }
1684
1685 #[test]
1687 fn test_page_navigation_boundaries() {
1688 const PAGE_SIZE: usize = 9;
1689 let total_configs: usize = 20; let total_pages = total_configs.div_ceil(PAGE_SIZE); let mut current_page = 0;
1694 let original_page = current_page;
1695
1696 if current_page > 0 {
1698 current_page -= 1;
1699 }
1700 assert_eq!(
1701 current_page, original_page,
1702 "First page should not navigate to previous"
1703 );
1704
1705 let mut current_page = total_pages - 1; let original_page = current_page;
1708
1709 if current_page < total_pages - 1 {
1711 current_page += 1;
1712 }
1713 assert_eq!(
1714 current_page, original_page,
1715 "Last page should not navigate to next"
1716 );
1717
1718 let mut current_page = 1; if current_page < total_pages - 1 {
1723 current_page += 1;
1724 }
1725 assert_eq!(current_page, 2, "Should navigate to next page");
1726
1727 if current_page > 0 {
1729 current_page = current_page.saturating_sub(1);
1730 }
1731 assert_eq!(current_page, 1, "Should navigate to previous page");
1732 }
1733
1734 #[test]
1736 fn test_j_key_navigation() {
1737 let mut selected_index: usize = 0;
1738 let configs_len = 5; if selected_index < configs_len + 1 {
1743 selected_index += 1;
1744 }
1745 assert_eq!(selected_index, 1, "j key should move selection down by one");
1746
1747 selected_index = configs_len + 1;
1749 let original_index = selected_index;
1750 if selected_index < configs_len + 1 {
1751 selected_index += 1;
1752 }
1753 assert_eq!(
1754 selected_index, original_index,
1755 "j key should not move beyond bottom boundary"
1756 );
1757 }
1758
1759 #[test]
1761 fn test_k_key_navigation() {
1762 let mut selected_index: usize = 5;
1763
1764 selected_index = selected_index.saturating_sub(1);
1767 assert_eq!(selected_index, 4, "k key should move selection up by one");
1768
1769 selected_index = 0;
1771 let original_index = selected_index;
1772 selected_index = selected_index.saturating_sub(1);
1773 assert_eq!(
1774 selected_index, original_index,
1775 "k key should not move beyond top boundary"
1776 );
1777 }
1778
1779 #[test]
1781 fn test_jk_key_boundary_conditions() {
1782 const CONFIGS_LEN: usize = 5;
1783
1784 let mut selected_index: usize = CONFIGS_LEN + 1; let original_index = selected_index;
1787 if selected_index < CONFIGS_LEN + 1 {
1788 selected_index += 1; }
1790 assert_eq!(
1791 selected_index, original_index,
1792 "j key should respect bottom boundary like Down arrow"
1793 );
1794
1795 let mut selected_index: usize = 0; let original_index = selected_index;
1798 selected_index = selected_index.saturating_sub(1); assert_eq!(
1800 selected_index, original_index,
1801 "k key should respect top boundary like Up arrow"
1802 );
1803 }
1804}
1805
1806#[derive(Debug, PartialEq)]
1808pub(crate) enum EditModeError {
1809 ReturnToMenu,
1810}
1811
1812impl std::fmt::Display for EditModeError {
1813 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1814 match self {
1815 EditModeError::ReturnToMenu => write!(f, "return_to_menu"),
1816 }
1817 }
1818}
1819
1820impl std::error::Error for EditModeError {}
1821
1822fn handle_config_edit(config: &Configuration) -> Result<()> {
1824 println!("\n{}", "配置编辑模式".green().bold());
1825 println!("{}", "===================".green());
1826 println!("正在编辑配置: {}", config.alias_name.cyan().bold());
1827 println!();
1828
1829 let mut editing_config = config.clone();
1831 let original_alias = config.alias_name.clone();
1832
1833 loop {
1834 display_edit_menu(&editing_config);
1836
1837 println!("\n{}", "提示: 可使用大小写字母".dimmed());
1839 print!("请选择要编辑的字段 (1-9, A-H), 或输入 S 保存, Q 返回上一级菜单: ");
1840 io::stdout().flush()?;
1841
1842 let mut input = String::new();
1843 io::stdin().read_line(&mut input)?;
1844 let input = input.trim();
1845
1846 match input {
1848 "1" => edit_field_alias(&mut editing_config)?,
1849 "2" => edit_field_token(&mut editing_config)?,
1850 "3" => edit_field_url(&mut editing_config)?,
1851 "4" => edit_field_model(&mut editing_config)?,
1852 "5" => edit_field_small_fast_model(&mut editing_config)?,
1853 "6" => edit_field_max_thinking_tokens(&mut editing_config)?,
1854 "7" => edit_field_api_timeout_ms(&mut editing_config)?,
1855 "8" => edit_field_claude_code_disable_nonessential_traffic(&mut editing_config)?,
1856 "9" => edit_field_anthropic_default_sonnet_model(&mut editing_config)?,
1857 "10" | "a" | "A" => edit_field_anthropic_default_opus_model(&mut editing_config)?,
1858 "11" | "b" | "B" => edit_field_anthropic_default_haiku_model(&mut editing_config)?,
1859 "12" | "c" | "C" => edit_field_claude_code_subagent_model(&mut editing_config)?,
1860 "13" | "d" | "D" => {
1861 edit_field_claude_code_disable_nonstreaming_fallback(&mut editing_config)?
1862 }
1863 "14" | "e" | "E" => edit_field_claude_code_effort_level(&mut editing_config)?,
1864 "15" | "f" | "F" => edit_field_disable_prompt_caching(&mut editing_config)?,
1865 "16" | "g" | "G" => {
1866 edit_field_claude_code_disable_experimental_betas(&mut editing_config)?
1867 }
1868 "17" | "h" | "H" => edit_field_disable_autoupdater(&mut editing_config)?,
1869 "s" | "S" => {
1870 return save_configuration_changes(&original_alias, &editing_config);
1872 }
1873 "q" | "Q" => {
1874 println!("\n{}", "返回上一级菜单".blue());
1875 return Err(EditModeError::ReturnToMenu.into());
1876 }
1877 _ => {
1878 println!("{}", "无效选择,请重试".red());
1879 }
1880 }
1881 }
1882}
1883
1884fn display_edit_menu(config: &Configuration) {
1886 println!("\n{}", "当前配置值:".blue().bold());
1887 println!("{}", "─────────────────────────".blue());
1888
1889 println!("1. 别名 (alias_name): {}", config.alias_name.green());
1890
1891 println!(
1892 "2. 令牌 (ANTHROPIC_AUTH_TOKEN): {}",
1893 format_token_for_display(&config.token).green()
1894 );
1895
1896 println!("3. URL (ANTHROPIC_BASE_URL): {}", config.url.green());
1897
1898 println!(
1899 "4. 模型 (ANTHROPIC_MODEL): {}",
1900 config.model.as_deref().unwrap_or("[未设置]").green()
1901 );
1902
1903 println!(
1904 "5. 快速模型 (ANTHROPIC_SMALL_FAST_MODEL): {}",
1905 config
1906 .small_fast_model
1907 .as_deref()
1908 .unwrap_or("[未设置]")
1909 .green()
1910 );
1911
1912 println!(
1913 "6. 最大思考令牌数 (ANTHROPIC_MAX_THINKING_TOKENS): {}",
1914 config
1915 .max_thinking_tokens
1916 .map(|t| t.to_string())
1917 .unwrap_or("[未设置]".to_string())
1918 .green()
1919 );
1920
1921 println!(
1922 "7. API超时时间 (API_TIMEOUT_MS): {}",
1923 config
1924 .api_timeout_ms
1925 .map(|t| t.to_string())
1926 .unwrap_or("[未设置]".to_string())
1927 .green()
1928 );
1929
1930 println!(
1931 "8. 禁用非必要流量 (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC): {}",
1932 config
1933 .claude_code_disable_nonessential_traffic
1934 .map(|t| t.to_string())
1935 .unwrap_or("[未设置]".to_string())
1936 .green()
1937 );
1938
1939 println!(
1940 "9. 默认 Sonnet 模型 (ANTHROPIC_DEFAULT_SONNET_MODEL): {}",
1941 config
1942 .anthropic_default_sonnet_model
1943 .as_deref()
1944 .unwrap_or("[未设置]")
1945 .green()
1946 );
1947
1948 println!(
1949 "A. 默认 Opus 模型 (ANTHROPIC_DEFAULT_OPUS_MODEL): {}",
1950 config
1951 .anthropic_default_opus_model
1952 .as_deref()
1953 .unwrap_or("[未设置]")
1954 .green()
1955 );
1956
1957 println!(
1958 "B. 默认 Haiku 模型 (ANTHROPIC_DEFAULT_HAIKU_MODEL): {}",
1959 config
1960 .anthropic_default_haiku_model
1961 .as_deref()
1962 .unwrap_or("[未设置]")
1963 .green()
1964 );
1965
1966 println!(
1967 "C. 子代理模型 (CLAUDE_CODE_SUBAGENT_MODEL): {}",
1968 config
1969 .claude_code_subagent_model
1970 .as_deref()
1971 .unwrap_or("[未设置]")
1972 .green()
1973 );
1974
1975 println!(
1976 "D. 禁用非流式回退 (CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK): {}",
1977 config
1978 .claude_code_disable_nonstreaming_fallback
1979 .map(|t| t.to_string())
1980 .unwrap_or("[未设置]".to_string())
1981 .green()
1982 );
1983
1984 println!(
1985 "E. 努力级别 (CLAUDE_CODE_EFFORT_LEVEL): {}",
1986 config
1987 .claude_code_effort_level
1988 .as_deref()
1989 .unwrap_or("[未设置]")
1990 .green()
1991 );
1992
1993 println!(
1994 "F. 禁用提示缓存 (DISABLE_PROMPT_CACHING): {}",
1995 config
1996 .disable_prompt_caching
1997 .map(|t| t.to_string())
1998 .unwrap_or("[未设置]".to_string())
1999 .green()
2000 );
2001
2002 println!(
2003 "G. 禁用实验性功能 (CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS): {}",
2004 config
2005 .claude_code_disable_experimental_betas
2006 .map(|t| t.to_string())
2007 .unwrap_or("[未设置]".to_string())
2008 .green()
2009 );
2010
2011 println!(
2012 "H. 禁用自动更新 (DISABLE_AUTOUPDATER): {}",
2013 config
2014 .disable_autoupdater
2015 .map(|t| t.to_string())
2016 .unwrap_or("[未设置]".to_string())
2017 .green()
2018 );
2019
2020 println!("{}", "─────────────────────────".blue());
2021 println!(
2022 "S. {} | Q. {}",
2023 "保存更改".green().bold(),
2024 "返回上一级菜单".blue()
2025 );
2026}
2027
2028pub(crate) fn edit_string_field(
2030 field_name: &str,
2031 current_value: &str,
2032 validator: impl Fn(&str) -> Result<()>,
2033) -> Result<Option<String>> {
2034 println!("\n编辑{field_name}:");
2035 println!("当前值: {}", current_value.cyan());
2036 print!("新值 (回车保持不变): ");
2037 io::stdout().flush()?;
2038
2039 let mut input = String::new();
2040 io::stdin().read_line(&mut input)?;
2041 let input = input.trim();
2042
2043 if !input.is_empty() {
2044 validator(input)?;
2045 println!("{field_name}已更新为: {}", input.green());
2046 Ok(Some(input.to_string()))
2047 } else {
2048 Ok(None)
2049 }
2050}
2051
2052pub(crate) type OptionalStringResult = Result<Option<Option<String>>>;
2054
2055pub(crate) fn edit_optional_string_field(
2057 field_name: &str,
2058 current_value: Option<&str>,
2059) -> OptionalStringResult {
2060 println!("\n编辑{field_name}:");
2061 println!("当前值: {}", current_value.unwrap_or("[未设置]").cyan());
2062 print!("新值 (回车保持不变,输入空格清除): ");
2063 io::stdout().flush()?;
2064
2065 let mut input = String::new();
2066 io::stdin().read_line(&mut input)?;
2067 let input = input.trim();
2068
2069 if !input.is_empty() {
2070 if input == " " {
2071 println!("{}", format!("{field_name}已清除").green());
2072 Ok(Some(None))
2073 } else {
2074 println!("{field_name}已更新为: {}", input.green());
2075 Ok(Some(Some(input.to_string())))
2076 }
2077 } else {
2078 Ok(None)
2079 }
2080}
2081
2082type OptionalU32Result = Result<Option<Option<u32>>>;
2084
2085fn edit_optional_u32_field(field_name: &str, current_value: Option<u32>) -> OptionalU32Result {
2087 println!("\n编辑{field_name}:");
2088 println!(
2089 "当前值: {}",
2090 current_value
2091 .map(|t| t.to_string())
2092 .unwrap_or("[未设置]".to_string())
2093 .cyan()
2094 );
2095 print!("新值 (回车保持不变,输入 0 清除): ");
2096 io::stdout().flush()?;
2097
2098 let mut input = String::new();
2099 io::stdin().read_line(&mut input)?;
2100 let input = input.trim();
2101
2102 if !input.is_empty() {
2103 if input == "0" {
2104 println!("{}", format!("{field_name}已清除").green());
2105 Ok(Some(None))
2106 } else if let Ok(value) = input.parse::<u32>() {
2107 println!("{field_name}已更新为: {}", value.to_string().green());
2108 Ok(Some(Some(value)))
2109 } else {
2110 println!("{}", "错误: 请输入有效的数字".red());
2111 Ok(None)
2112 }
2113 } else {
2114 Ok(None)
2115 }
2116}
2117
2118fn edit_field_alias(config: &mut Configuration) -> Result<()> {
2120 let validator = |input: &str| -> Result<()> {
2121 if input.contains(char::is_whitespace) {
2122 anyhow::bail!("错误: 别名不能包含空白字符");
2123 }
2124 if input == "cc" {
2125 anyhow::bail!("错误: 'cc' 是保留名称");
2126 }
2127 if input == "official" {
2128 anyhow::bail!("错误: 'official' 是保留名称");
2129 }
2130 Ok(())
2131 };
2132
2133 match edit_string_field("别名", &config.alias_name, validator) {
2134 Ok(Some(new_value)) => config.alias_name = new_value,
2135 Ok(None) => {}
2136 Err(e) => println!("{}", e.to_string().red()),
2137 }
2138 Ok(())
2139}
2140
2141fn edit_field_token(config: &mut Configuration) -> Result<()> {
2143 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2144 if let Some(new_value) = edit_string_field(
2145 "令牌",
2146 &format_token_for_display(&config.token),
2147 no_validator,
2148 )? {
2149 config.token = new_value;
2150 println!("{}", "令牌已更新".green());
2151 }
2152 Ok(())
2153}
2154
2155fn edit_field_url(config: &mut Configuration) -> Result<()> {
2157 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2158 if let Some(new_value) = edit_string_field("URL", &config.url, no_validator)? {
2159 config.url = new_value;
2160 }
2161 Ok(())
2162}
2163
2164fn edit_field_model(config: &mut Configuration) -> Result<()> {
2166 if let Some(result) = edit_optional_string_field("模型", config.model.as_deref())? {
2167 config.model = result;
2168 }
2169 Ok(())
2170}
2171
2172fn edit_field_small_fast_model(config: &mut Configuration) -> Result<()> {
2174 if let Some(result) =
2175 edit_optional_string_field("快速模型", config.small_fast_model.as_deref())?
2176 {
2177 config.small_fast_model = result;
2178 }
2179 Ok(())
2180}
2181
2182fn edit_field_max_thinking_tokens(config: &mut Configuration) -> Result<()> {
2184 if let Some(result) = edit_optional_u32_field("最大思考令牌数", config.max_thinking_tokens)?
2185 {
2186 config.max_thinking_tokens = result;
2187 }
2188 Ok(())
2189}
2190
2191fn edit_field_api_timeout_ms(config: &mut Configuration) -> Result<()> {
2193 if let Some(result) = edit_optional_u32_field("API超时时间 (毫秒)", config.api_timeout_ms)?
2194 {
2195 config.api_timeout_ms = result;
2196 }
2197 Ok(())
2198}
2199
2200fn edit_field_claude_code_disable_nonessential_traffic(config: &mut Configuration) -> Result<()> {
2202 if let Some(result) = edit_optional_u32_field(
2203 "禁用非必要流量标志",
2204 config.claude_code_disable_nonessential_traffic,
2205 )? {
2206 config.claude_code_disable_nonessential_traffic = result;
2207 }
2208 Ok(())
2209}
2210
2211fn edit_field_anthropic_default_sonnet_model(config: &mut Configuration) -> Result<()> {
2213 if let Some(result) = edit_optional_string_field(
2214 "默认 Sonnet 模型",
2215 config.anthropic_default_sonnet_model.as_deref(),
2216 )? {
2217 config.anthropic_default_sonnet_model = result;
2218 }
2219 Ok(())
2220}
2221
2222fn edit_field_anthropic_default_opus_model(config: &mut Configuration) -> Result<()> {
2224 if let Some(result) = edit_optional_string_field(
2225 "默认 Opus 模型",
2226 config.anthropic_default_opus_model.as_deref(),
2227 )? {
2228 config.anthropic_default_opus_model = result;
2229 }
2230 Ok(())
2231}
2232
2233fn edit_field_anthropic_default_haiku_model(config: &mut Configuration) -> Result<()> {
2235 if let Some(result) = edit_optional_string_field(
2236 "默认 Haiku 模型",
2237 config.anthropic_default_haiku_model.as_deref(),
2238 )? {
2239 config.anthropic_default_haiku_model = result;
2240 }
2241 Ok(())
2242}
2243
2244fn edit_field_claude_code_subagent_model(config: &mut Configuration) -> Result<()> {
2246 if let Some(result) =
2247 edit_optional_string_field("子代理模型", config.claude_code_subagent_model.as_deref())?
2248 {
2249 config.claude_code_subagent_model = result;
2250 }
2251 Ok(())
2252}
2253
2254fn edit_field_claude_code_disable_nonstreaming_fallback(config: &mut Configuration) -> Result<()> {
2256 if let Some(result) = edit_optional_u32_field(
2257 "禁用非流式回退标志",
2258 config.claude_code_disable_nonstreaming_fallback,
2259 )? {
2260 config.claude_code_disable_nonstreaming_fallback = result;
2261 }
2262 Ok(())
2263}
2264
2265fn edit_field_claude_code_effort_level(config: &mut Configuration) -> Result<()> {
2267 if let Some(result) =
2268 edit_optional_string_field("努力级别", config.claude_code_effort_level.as_deref())?
2269 {
2270 config.claude_code_effort_level = result;
2271 }
2272 Ok(())
2273}
2274
2275fn edit_field_disable_prompt_caching(config: &mut Configuration) -> Result<()> {
2277 if let Some(result) =
2278 edit_optional_u32_field("禁用提示缓存标志", config.disable_prompt_caching)?
2279 {
2280 config.disable_prompt_caching = result;
2281 }
2282 Ok(())
2283}
2284
2285fn edit_field_claude_code_disable_experimental_betas(config: &mut Configuration) -> Result<()> {
2287 if let Some(result) = edit_optional_u32_field(
2288 "禁用实验性功能标志",
2289 config.claude_code_disable_experimental_betas,
2290 )? {
2291 config.claude_code_disable_experimental_betas = result;
2292 }
2293 Ok(())
2294}
2295
2296fn edit_field_disable_autoupdater(config: &mut Configuration) -> Result<()> {
2298 if let Some(result) = edit_optional_u32_field("禁用自动更新标志", config.disable_autoupdater)?
2299 {
2300 config.disable_autoupdater = result;
2301 }
2302 Ok(())
2303}
2304
2305fn save_configuration_changes(original_alias: &str, new_config: &Configuration) -> Result<()> {
2307 let mut storage = ConfigStorage::load()?;
2309
2310 if original_alias != new_config.alias_name
2312 && storage.get_configuration(&new_config.alias_name).is_some()
2313 {
2314 println!("\n{}", "别名冲突!".red().bold());
2315 println!("配置 '{}' 已存在", new_config.alias_name.yellow());
2316 print!("是否覆盖现有配置? (y/N): ");
2317 io::stdout().flush()?;
2318
2319 let mut input = String::new();
2320 io::stdin().read_line(&mut input)?;
2321 let input = input.trim().to_lowercase();
2322
2323 if input != "y" && input != "yes" {
2324 println!("{}", "编辑已取消".yellow());
2325 return Ok(());
2326 }
2327 }
2328
2329 storage.update_configuration(original_alias, new_config.clone())?;
2331 storage.save()?;
2332
2333 println!("\n{}", "配置已成功保存!".green().bold());
2334
2335 Ok(())
2336}