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 crate::config::types::ClaudeSettings::write_current_alias("official")?;
920
921 launch_claude_with_env(
922 EnvironmentConfig::empty().with_alias("official"),
923 None,
924 None,
925 false,
926 )
927 } else if selected_index <= configs.len() {
928 let config_index = selected_index - 1; let selected_config = configs[config_index].clone();
931 let env_config = EnvironmentConfig::from_config(&selected_config)
932 .with_alias(&selected_config.alias_name);
933
934 println!(
935 "\nSwitched to configuration '{}'",
936 selected_config.alias_name.green().bold()
937 );
938
939 let details = format_config_details(&selected_config, "", false);
941 for detail_line in details {
942 println!("{detail_line}");
943 }
944
945 let mut settings = crate::config::types::ClaudeSettings::load(
947 storage.get_claude_settings_dir().map(|s| s.as_str()),
948 )?;
949 settings.switch_to_config_with_mode(
950 &selected_config,
951 storage_mode,
952 storage.get_claude_settings_dir().map(|s| s.as_str()),
953 )?;
954
955 crate::config::types::ClaudeSettings::write_current_alias(&selected_config.alias_name)?;
956
957 launch_claude_with_env(env_config, None, None, false)
958 } else {
959 println!("\nExiting...");
961 Ok(())
962 }
963}
964
965pub fn launch_claude_with_env(
967 env_config: EnvironmentConfig,
968 prompt: Option<&str>,
969 resume: Option<&str>,
970 continue_session: bool,
971) -> Result<()> {
972 println!("\nLaunching Claude CLI...");
973
974 let _ = ClaudeSettings::cleanup_orphan_alias_files();
976
977 if let Some(alias) = env_config.env_vars.get("CC_SWITCH_CURRENT_ALIAS") {
981 ClaudeSettings::write_current_alias_for_pid(alias)?;
982 }
983
984 #[cfg(unix)]
986 {
987 use std::os::unix::process::CommandExt;
988 let mut command = Command::new(resolve_npm_cli("claude"));
989 command.envs(env_config.as_env_tuples());
991 command.arg("--dangerously-skip-permissions");
992 if let Some(session_id) = resume {
993 command.args(["--resume", session_id]);
994 }
995 if continue_session {
996 command.arg("--continue");
997 }
998 if let Some(p) = prompt {
999 command.arg(p);
1000 }
1001 let error = command.exec();
1002 let _ = ClaudeSettings::clear_current_alias_for_pid();
1005 anyhow::bail!("Failed to exec claude: {}", error);
1006 }
1007
1008 #[cfg(not(unix))]
1010 {
1011 use std::process::Stdio;
1012 let mut command = Command::new(resolve_npm_cli("claude"));
1013 command.envs(env_config.as_env_tuples());
1015 command.arg("--dangerously-skip-permissions");
1016 if let Some(session_id) = resume {
1017 command.args(["--resume", session_id]);
1018 }
1019 if continue_session {
1020 command.arg("--continue");
1021 }
1022 if let Some(p) = prompt {
1023 command.arg(p);
1024 }
1025 command
1026 .stdin(Stdio::inherit())
1027 .stdout(Stdio::inherit())
1028 .stderr(Stdio::inherit());
1029
1030 let mut child = command.spawn().context(
1031 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1032 )?;
1033
1034 let status = child.wait()?;
1035
1036 let _ = ClaudeSettings::clear_current_alias_for_pid();
1038
1039 if !status.success() {
1040 anyhow::bail!("Claude CLI exited with error status: {}", status);
1041 }
1042 Ok(())
1043 }
1044}
1045
1046fn execute_claude_command(skip_permissions: bool) -> Result<()> {
1051 println!("Launching Claude CLI...");
1052
1053 #[cfg(unix)]
1055 {
1056 use std::os::unix::process::CommandExt;
1057 let mut command = Command::new(resolve_npm_cli("claude"));
1058 if skip_permissions {
1059 command.arg("--dangerously-skip-permissions");
1060 }
1061
1062 let error = command.exec();
1063 anyhow::bail!("Failed to exec claude: {}", error);
1065 }
1066
1067 #[cfg(not(unix))]
1069 {
1070 use std::process::Stdio;
1071 let mut command = Command::new(resolve_npm_cli("claude"));
1072 if skip_permissions {
1073 command.arg("--dangerously-skip-permissions");
1074 }
1075
1076 command
1077 .stdin(Stdio::inherit())
1078 .stdout(Stdio::inherit())
1079 .stderr(Stdio::inherit());
1080
1081 let mut child = command.spawn().context(
1082 "Failed to launch Claude CLI. Make sure 'claude' command is available in PATH",
1083 )?;
1084
1085 let status = child
1086 .wait()
1087 .context("Failed to wait for Claude CLI process")?;
1088
1089 if !status.success() {
1090 anyhow::bail!("Claude CLI exited with error status: {}", status);
1091 }
1092 Ok(())
1093 }
1094}
1095
1096pub fn read_input(prompt: &str) -> Result<String> {
1104 print!("{prompt}");
1105 io::stdout().flush().context("Failed to flush stdout")?;
1106 let mut input = String::new();
1107 io::stdin()
1108 .read_line(&mut input)
1109 .context("Failed to read input")?;
1110 Ok(input.trim().to_string())
1111}
1112
1113pub fn read_sensitive_input(prompt: &str) -> Result<String> {
1121 print!("{prompt}");
1122 io::stdout().flush().context("Failed to flush stdout")?;
1123 let mut input = String::new();
1124 io::stdin()
1125 .read_line(&mut input)
1126 .context("Failed to read input")?;
1127 Ok(input.trim().to_string())
1128}
1129
1130fn format_config_details(config: &Configuration, indent: &str, _compact: bool) -> Vec<String> {
1143 let mut lines = Vec::new();
1144
1145 let terminal_width = get_terminal_width();
1147 let _available_width = terminal_width.saturating_sub(text_display_width(indent) + 8);
1148
1149 let token_label = "Token:";
1151 let url_label = "URL:";
1152 let model_label = "Model:";
1153 let small_model_label = "Small Fast Model:";
1154 let max_thinking_tokens_label = "Max Thinking Tokens:";
1155 let api_timeout_ms_label = "API Timeout (ms):";
1156 let disable_nonessential_traffic_label = "Disable Nonessential Traffic:";
1157 let default_sonnet_model_label = "Default Sonnet Model:";
1158 let default_opus_model_label = "Default Opus Model:";
1159 let default_haiku_model_label = "Default Haiku Model:";
1160 let subagent_model_label = "Subagent Model:";
1161 let disable_nonstreaming_fallback_label = "Disable Nonstreaming Fallback:";
1162 let effort_level_label = "Effort Level:";
1163
1164 let max_label_width = [
1166 token_label,
1167 url_label,
1168 model_label,
1169 small_model_label,
1170 max_thinking_tokens_label,
1171 api_timeout_ms_label,
1172 disable_nonessential_traffic_label,
1173 default_sonnet_model_label,
1174 default_opus_model_label,
1175 default_haiku_model_label,
1176 subagent_model_label,
1177 disable_nonstreaming_fallback_label,
1178 effort_level_label,
1179 ]
1180 .iter()
1181 .map(|label| text_display_width(label))
1182 .max()
1183 .unwrap_or(0);
1184
1185 let token_line = format!(
1187 "{}{} {}",
1188 indent,
1189 pad_text_to_width(token_label, max_label_width, TextAlignment::Left, ' '),
1190 format_token_for_display(&config.token).dimmed()
1191 );
1192 lines.push(token_line);
1193
1194 let url_line = format!(
1196 "{}{} {}",
1197 indent,
1198 pad_text_to_width(url_label, max_label_width, TextAlignment::Left, ' '),
1199 config.url.cyan()
1200 );
1201 lines.push(url_line);
1202
1203 if let Some(model) = &config.model {
1205 let model_line = format!(
1206 "{}{} {}",
1207 indent,
1208 pad_text_to_width(model_label, max_label_width, TextAlignment::Left, ' '),
1209 model.yellow()
1210 );
1211 lines.push(model_line);
1212 }
1213
1214 if let Some(small_fast_model) = &config.small_fast_model {
1216 let small_model_line = format!(
1217 "{}{} {}",
1218 indent,
1219 pad_text_to_width(small_model_label, max_label_width, TextAlignment::Left, ' '),
1220 small_fast_model.yellow()
1221 );
1222 lines.push(small_model_line);
1223 }
1224
1225 if let Some(max_thinking_tokens) = config.max_thinking_tokens {
1227 let tokens_line = format!(
1228 "{}{} {}",
1229 indent,
1230 pad_text_to_width(
1231 max_thinking_tokens_label,
1232 max_label_width,
1233 TextAlignment::Left,
1234 ' '
1235 ),
1236 format!("{}", max_thinking_tokens).yellow()
1237 );
1238 lines.push(tokens_line);
1239 }
1240
1241 if let Some(api_timeout_ms) = config.api_timeout_ms {
1243 let timeout_line = format!(
1244 "{}{} {}",
1245 indent,
1246 pad_text_to_width(
1247 api_timeout_ms_label,
1248 max_label_width,
1249 TextAlignment::Left,
1250 ' '
1251 ),
1252 format!("{}", api_timeout_ms).yellow()
1253 );
1254 lines.push(timeout_line);
1255 }
1256
1257 if let Some(disable_flag) = config.claude_code_disable_nonessential_traffic {
1259 let flag_line = format!(
1260 "{}{} {}",
1261 indent,
1262 pad_text_to_width(
1263 disable_nonessential_traffic_label,
1264 max_label_width,
1265 TextAlignment::Left,
1266 ' '
1267 ),
1268 format!("{}", disable_flag).yellow()
1269 );
1270 lines.push(flag_line);
1271 }
1272
1273 if let Some(sonnet_model) = &config.anthropic_default_sonnet_model {
1275 let sonnet_line = format!(
1276 "{}{} {}",
1277 indent,
1278 pad_text_to_width(
1279 default_sonnet_model_label,
1280 max_label_width,
1281 TextAlignment::Left,
1282 ' '
1283 ),
1284 sonnet_model.yellow()
1285 );
1286 lines.push(sonnet_line);
1287 }
1288
1289 if let Some(opus_model) = &config.anthropic_default_opus_model {
1291 let opus_line = format!(
1292 "{}{} {}",
1293 indent,
1294 pad_text_to_width(
1295 default_opus_model_label,
1296 max_label_width,
1297 TextAlignment::Left,
1298 ' '
1299 ),
1300 opus_model.yellow()
1301 );
1302 lines.push(opus_line);
1303 }
1304
1305 if let Some(haiku_model) = &config.anthropic_default_haiku_model {
1307 let haiku_line = format!(
1308 "{}{} {}",
1309 indent,
1310 pad_text_to_width(
1311 default_haiku_model_label,
1312 max_label_width,
1313 TextAlignment::Left,
1314 ' '
1315 ),
1316 haiku_model.yellow()
1317 );
1318 lines.push(haiku_line);
1319 }
1320
1321 if let Some(subagent_model) = &config.claude_code_subagent_model {
1323 let subagent_line = format!(
1324 "{}{} {}",
1325 indent,
1326 pad_text_to_width(
1327 subagent_model_label,
1328 max_label_width,
1329 TextAlignment::Left,
1330 ' '
1331 ),
1332 subagent_model.yellow()
1333 );
1334 lines.push(subagent_line);
1335 }
1336
1337 if let Some(disable_flag) = config.claude_code_disable_nonstreaming_fallback {
1339 let flag_line = format!(
1340 "{}{} {}",
1341 indent,
1342 pad_text_to_width(
1343 disable_nonstreaming_fallback_label,
1344 max_label_width,
1345 TextAlignment::Left,
1346 ' '
1347 ),
1348 format!("{}", disable_flag).yellow()
1349 );
1350 lines.push(flag_line);
1351 }
1352
1353 if let Some(effort_level) = &config.claude_code_effort_level {
1355 let effort_line = format!(
1356 "{}{} {}",
1357 indent,
1358 pad_text_to_width(
1359 effort_level_label,
1360 max_label_width,
1361 TextAlignment::Left,
1362 ' '
1363 ),
1364 effort_level.yellow()
1365 );
1366 lines.push(effort_line);
1367 }
1368
1369 lines
1370}
1371
1372#[cfg(test)]
1373mod border_drawing_tests {
1374 use super::*;
1375
1376 #[test]
1377 fn test_border_drawing_unicode_support() {
1378 let _border = BorderDrawing::new();
1379 }
1381
1382 #[test]
1383 fn test_border_drawing_top_border() {
1384 let border = BorderDrawing {
1385 unicode_supported: true,
1386 };
1387 let result = border.draw_top_border("Test", 20);
1388 assert!(!result.is_empty());
1389 assert!(result.contains("Test"));
1390 }
1391
1392 #[test]
1393 fn test_border_drawing_ascii_fallback() {
1394 let border = BorderDrawing {
1395 unicode_supported: false,
1396 };
1397 let result = border.draw_top_border("Test", 20);
1398 assert!(!result.is_empty());
1399 assert!(result.contains("Test"));
1400 assert!(result.contains("+"));
1401 assert!(result.contains("-"));
1402 }
1403
1404 #[test]
1405 fn test_border_drawing_middle_line() {
1406 let border = BorderDrawing {
1407 unicode_supported: true,
1408 };
1409 let result = border.draw_middle_line("Test message", 30);
1410 assert!(!result.is_empty());
1411 assert!(result.contains("Test message"));
1412 }
1413
1414 #[test]
1415 fn test_border_drawing_bottom_border() {
1416 let border = BorderDrawing {
1417 unicode_supported: true,
1418 };
1419 let result = border.draw_bottom_border(20);
1420 assert!(!result.is_empty());
1421 }
1422
1423 #[test]
1424 fn test_border_drawing_width_consistency() {
1425 let border = BorderDrawing {
1426 unicode_supported: true,
1427 };
1428 let width = 30;
1429 let top = border.draw_top_border("Title", width);
1430 let middle = border.draw_middle_line("Content", width);
1431 let bottom = border.draw_bottom_border(width);
1432
1433 assert!(top.chars().count() >= width - 2);
1435 assert!(middle.chars().count() >= width - 2);
1436 assert!(bottom.chars().count() >= width - 2);
1437 }
1438}
1439
1440#[cfg(test)]
1441mod pagination_tests {
1442
1443 #[test]
1445 fn test_pagination_calculation() {
1446 const PAGE_SIZE: usize = 9;
1447
1448 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); }
1459
1460 #[test]
1462 fn test_page_range_calculation() {
1463 const PAGE_SIZE: usize = 9;
1464
1465 let current_page = 0;
1467 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 0);
1470 assert_eq!(end_idx, 9);
1471 assert_eq!(end_idx - start_idx, 9); let current_page = 1;
1475 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, 15); assert_eq!(start_idx, 9);
1478 assert_eq!(end_idx, 15);
1479 assert_eq!(end_idx - start_idx, 6); let current_page = 0;
1483 let start_idx = current_page * PAGE_SIZE; let end_idx = std::cmp::min(start_idx + PAGE_SIZE, PAGE_SIZE); assert_eq!(start_idx, 0);
1486 assert_eq!(end_idx, 9);
1487 assert_eq!(end_idx - start_idx, 9); }
1489
1490 #[test]
1492 fn test_digit_mapping_to_config_index() {
1493 const PAGE_SIZE: usize = 9;
1494
1495 let current_page = 0;
1497 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1501 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 0);
1503
1504 let digit = 9;
1506 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 8);
1508
1509 let current_page = 1;
1511 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1515 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 9);
1517
1518 let digit = 5;
1520 let actual_config_index = start_idx + (digit - 1); assert_eq!(actual_config_index, 13);
1522 }
1523
1524 #[test]
1526 fn test_selection_index_conversion() {
1527 const PAGE_SIZE: usize = 9;
1534
1535 let current_page = 0;
1537 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1539 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 1);
1542
1543 let current_page = 1;
1545 let start_idx = current_page * PAGE_SIZE; let digit = 1;
1547 let actual_config_index = start_idx + (digit - 1); let selection_index = actual_config_index + 1; assert_eq!(selection_index, 10);
1550 }
1551
1552 #[test]
1554 fn test_page_navigation_bounds() {
1555 const PAGE_SIZE: usize = 9;
1556 let total_configs: usize = 25; let total_pages = total_configs.div_ceil(PAGE_SIZE); assert_eq!(total_pages, 3);
1559
1560 let mut current_page = 0;
1562 if current_page > 0 {
1563 current_page -= 1;
1564 }
1565 assert_eq!(current_page, 0); let mut current_page = total_pages - 1; if current_page < total_pages - 1 {
1570 current_page += 1;
1571 }
1572 assert_eq!(current_page, 2); let mut current_page = 1;
1576
1577 if current_page < total_pages - 1 {
1579 current_page += 1;
1580 }
1581 assert_eq!(current_page, 2);
1582
1583 if current_page > 0 {
1585 current_page = current_page.saturating_sub(1);
1586 }
1587 assert_eq!(current_page, 1);
1588 }
1589
1590 #[test]
1592 fn test_digit_key_boundary_conditions() {
1593 const PAGE_SIZE: usize = 9;
1594
1595 let digit = 0;
1597 assert!(digit < 1, "Digit 0 should be less than 1 and ignored");
1598
1599 let configs_len = 5; let page_configs_len = std::cmp::min(PAGE_SIZE, configs_len); let digit = 9; assert!(
1604 digit > page_configs_len,
1605 "Digit 9 should be beyond available configs (5) and ignored"
1606 );
1607
1608 for digit in 1..=page_configs_len {
1610 assert!(
1611 digit >= 1 && digit <= page_configs_len,
1612 "Digit {} should be valid",
1613 digit
1614 );
1615 }
1616 }
1617
1618 #[test]
1620 fn test_empty_configs_handling() {
1621 let empty_configs: Vec<String> = Vec::new();
1622 assert!(
1623 empty_configs.is_empty(),
1624 "Empty config list should be properly detected"
1625 );
1626
1627 let configs_len = empty_configs.len(); assert_eq!(configs_len, 0, "Empty configs should have length 0");
1630
1631 }
1634
1635 #[test]
1637 fn test_page_navigation_boundaries() {
1638 const PAGE_SIZE: usize = 9;
1639 let total_configs: usize = 20; let total_pages = total_configs.div_ceil(PAGE_SIZE); let mut current_page = 0;
1644 let original_page = current_page;
1645
1646 if current_page > 0 {
1648 current_page -= 1;
1649 }
1650 assert_eq!(
1651 current_page, original_page,
1652 "First page should not navigate to previous"
1653 );
1654
1655 let mut current_page = total_pages - 1; let original_page = current_page;
1658
1659 if current_page < total_pages - 1 {
1661 current_page += 1;
1662 }
1663 assert_eq!(
1664 current_page, original_page,
1665 "Last page should not navigate to next"
1666 );
1667
1668 let mut current_page = 1; if current_page < total_pages - 1 {
1673 current_page += 1;
1674 }
1675 assert_eq!(current_page, 2, "Should navigate to next page");
1676
1677 if current_page > 0 {
1679 current_page = current_page.saturating_sub(1);
1680 }
1681 assert_eq!(current_page, 1, "Should navigate to previous page");
1682 }
1683
1684 #[test]
1686 fn test_j_key_navigation() {
1687 let mut selected_index: usize = 0;
1688 let configs_len = 5; if selected_index < configs_len + 1 {
1693 selected_index += 1;
1694 }
1695 assert_eq!(selected_index, 1, "j key should move selection down by one");
1696
1697 selected_index = configs_len + 1;
1699 let original_index = selected_index;
1700 if selected_index < configs_len + 1 {
1701 selected_index += 1;
1702 }
1703 assert_eq!(
1704 selected_index, original_index,
1705 "j key should not move beyond bottom boundary"
1706 );
1707 }
1708
1709 #[test]
1711 fn test_k_key_navigation() {
1712 let mut selected_index: usize = 5;
1713
1714 selected_index = selected_index.saturating_sub(1);
1717 assert_eq!(selected_index, 4, "k key should move selection up by one");
1718
1719 selected_index = 0;
1721 let original_index = selected_index;
1722 selected_index = selected_index.saturating_sub(1);
1723 assert_eq!(
1724 selected_index, original_index,
1725 "k key should not move beyond top boundary"
1726 );
1727 }
1728
1729 #[test]
1731 fn test_jk_key_boundary_conditions() {
1732 const CONFIGS_LEN: usize = 5;
1733
1734 let mut selected_index: usize = CONFIGS_LEN + 1; let original_index = selected_index;
1737 if selected_index < CONFIGS_LEN + 1 {
1738 selected_index += 1; }
1740 assert_eq!(
1741 selected_index, original_index,
1742 "j key should respect bottom boundary like Down arrow"
1743 );
1744
1745 let mut selected_index: usize = 0; let original_index = selected_index;
1748 selected_index = selected_index.saturating_sub(1); assert_eq!(
1750 selected_index, original_index,
1751 "k key should respect top boundary like Up arrow"
1752 );
1753 }
1754}
1755
1756#[derive(Debug, PartialEq)]
1758pub(crate) enum EditModeError {
1759 ReturnToMenu,
1760}
1761
1762impl std::fmt::Display for EditModeError {
1763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1764 match self {
1765 EditModeError::ReturnToMenu => write!(f, "return_to_menu"),
1766 }
1767 }
1768}
1769
1770impl std::error::Error for EditModeError {}
1771
1772fn handle_config_edit(config: &Configuration) -> Result<()> {
1774 println!("\n{}", "配置编辑模式".green().bold());
1775 println!("{}", "===================".green());
1776 println!("正在编辑配置: {}", config.alias_name.cyan().bold());
1777 println!();
1778
1779 let mut editing_config = config.clone();
1781 let original_alias = config.alias_name.clone();
1782
1783 loop {
1784 display_edit_menu(&editing_config);
1786
1787 println!("\n{}", "提示: 可使用大小写字母".dimmed());
1789 print!("请选择要编辑的字段 (1-9, A-E), 或输入 S 保存, Q 返回上一级菜单: ");
1790 io::stdout().flush()?;
1791
1792 let mut input = String::new();
1793 io::stdin().read_line(&mut input)?;
1794 let input = input.trim();
1795
1796 match input {
1798 "1" => edit_field_alias(&mut editing_config)?,
1799 "2" => edit_field_token(&mut editing_config)?,
1800 "3" => edit_field_url(&mut editing_config)?,
1801 "4" => edit_field_model(&mut editing_config)?,
1802 "5" => edit_field_small_fast_model(&mut editing_config)?,
1803 "6" => edit_field_max_thinking_tokens(&mut editing_config)?,
1804 "7" => edit_field_api_timeout_ms(&mut editing_config)?,
1805 "8" => edit_field_claude_code_disable_nonessential_traffic(&mut editing_config)?,
1806 "9" => edit_field_anthropic_default_sonnet_model(&mut editing_config)?,
1807 "10" | "a" | "A" => edit_field_anthropic_default_opus_model(&mut editing_config)?,
1808 "11" | "b" | "B" => edit_field_anthropic_default_haiku_model(&mut editing_config)?,
1809 "12" | "c" | "C" => edit_field_claude_code_subagent_model(&mut editing_config)?,
1810 "13" | "d" | "D" => {
1811 edit_field_claude_code_disable_nonstreaming_fallback(&mut editing_config)?
1812 }
1813 "14" | "e" | "E" => edit_field_claude_code_effort_level(&mut editing_config)?,
1814 "s" | "S" => {
1815 return save_configuration_changes(&original_alias, &editing_config);
1817 }
1818 "q" | "Q" => {
1819 println!("\n{}", "返回上一级菜单".blue());
1820 return Err(EditModeError::ReturnToMenu.into());
1821 }
1822 _ => {
1823 println!("{}", "无效选择,请重试".red());
1824 }
1825 }
1826 }
1827}
1828
1829fn display_edit_menu(config: &Configuration) {
1831 println!("\n{}", "当前配置值:".blue().bold());
1832 println!("{}", "─────────────────────────".blue());
1833
1834 println!("1. 别名 (alias_name): {}", config.alias_name.green());
1835
1836 println!(
1837 "2. 令牌 (ANTHROPIC_AUTH_TOKEN): {}",
1838 format_token_for_display(&config.token).green()
1839 );
1840
1841 println!("3. URL (ANTHROPIC_BASE_URL): {}", config.url.green());
1842
1843 println!(
1844 "4. 模型 (ANTHROPIC_MODEL): {}",
1845 config.model.as_deref().unwrap_or("[未设置]").green()
1846 );
1847
1848 println!(
1849 "5. 快速模型 (ANTHROPIC_SMALL_FAST_MODEL): {}",
1850 config
1851 .small_fast_model
1852 .as_deref()
1853 .unwrap_or("[未设置]")
1854 .green()
1855 );
1856
1857 println!(
1858 "6. 最大思考令牌数 (ANTHROPIC_MAX_THINKING_TOKENS): {}",
1859 config
1860 .max_thinking_tokens
1861 .map(|t| t.to_string())
1862 .unwrap_or("[未设置]".to_string())
1863 .green()
1864 );
1865
1866 println!(
1867 "7. API超时时间 (API_TIMEOUT_MS): {}",
1868 config
1869 .api_timeout_ms
1870 .map(|t| t.to_string())
1871 .unwrap_or("[未设置]".to_string())
1872 .green()
1873 );
1874
1875 println!(
1876 "8. 禁用非必要流量 (CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC): {}",
1877 config
1878 .claude_code_disable_nonessential_traffic
1879 .map(|t| t.to_string())
1880 .unwrap_or("[未设置]".to_string())
1881 .green()
1882 );
1883
1884 println!(
1885 "9. 默认 Sonnet 模型 (ANTHROPIC_DEFAULT_SONNET_MODEL): {}",
1886 config
1887 .anthropic_default_sonnet_model
1888 .as_deref()
1889 .unwrap_or("[未设置]")
1890 .green()
1891 );
1892
1893 println!(
1894 "A. 默认 Opus 模型 (ANTHROPIC_DEFAULT_OPUS_MODEL): {}",
1895 config
1896 .anthropic_default_opus_model
1897 .as_deref()
1898 .unwrap_or("[未设置]")
1899 .green()
1900 );
1901
1902 println!(
1903 "B. 默认 Haiku 模型 (ANTHROPIC_DEFAULT_HAIKU_MODEL): {}",
1904 config
1905 .anthropic_default_haiku_model
1906 .as_deref()
1907 .unwrap_or("[未设置]")
1908 .green()
1909 );
1910
1911 println!(
1912 "C. 子代理模型 (CLAUDE_CODE_SUBAGENT_MODEL): {}",
1913 config
1914 .claude_code_subagent_model
1915 .as_deref()
1916 .unwrap_or("[未设置]")
1917 .green()
1918 );
1919
1920 println!(
1921 "D. 禁用非流式回退 (CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK): {}",
1922 config
1923 .claude_code_disable_nonstreaming_fallback
1924 .map(|t| t.to_string())
1925 .unwrap_or("[未设置]".to_string())
1926 .green()
1927 );
1928
1929 println!(
1930 "E. 努力级别 (CLAUDE_CODE_EFFORT_LEVEL): {}",
1931 config
1932 .claude_code_effort_level
1933 .as_deref()
1934 .unwrap_or("[未设置]")
1935 .green()
1936 );
1937
1938 println!("{}", "─────────────────────────".blue());
1939 println!(
1940 "S. {} | Q. {}",
1941 "保存更改".green().bold(),
1942 "返回上一级菜单".blue()
1943 );
1944}
1945
1946pub(crate) fn edit_string_field(
1948 field_name: &str,
1949 current_value: &str,
1950 validator: impl Fn(&str) -> Result<()>,
1951) -> Result<Option<String>> {
1952 println!("\n编辑{field_name}:");
1953 println!("当前值: {}", current_value.cyan());
1954 print!("新值 (回车保持不变): ");
1955 io::stdout().flush()?;
1956
1957 let mut input = String::new();
1958 io::stdin().read_line(&mut input)?;
1959 let input = input.trim();
1960
1961 if !input.is_empty() {
1962 validator(input)?;
1963 println!("{field_name}已更新为: {}", input.green());
1964 Ok(Some(input.to_string()))
1965 } else {
1966 Ok(None)
1967 }
1968}
1969
1970pub(crate) type OptionalStringResult = Result<Option<Option<String>>>;
1972
1973pub(crate) fn edit_optional_string_field(
1975 field_name: &str,
1976 current_value: Option<&str>,
1977) -> OptionalStringResult {
1978 println!("\n编辑{field_name}:");
1979 println!("当前值: {}", current_value.unwrap_or("[未设置]").cyan());
1980 print!("新值 (回车保持不变,输入空格清除): ");
1981 io::stdout().flush()?;
1982
1983 let mut input = String::new();
1984 io::stdin().read_line(&mut input)?;
1985 let input = input.trim();
1986
1987 if !input.is_empty() {
1988 if input == " " {
1989 println!("{}", format!("{field_name}已清除").green());
1990 Ok(Some(None))
1991 } else {
1992 println!("{field_name}已更新为: {}", input.green());
1993 Ok(Some(Some(input.to_string())))
1994 }
1995 } else {
1996 Ok(None)
1997 }
1998}
1999
2000type OptionalU32Result = Result<Option<Option<u32>>>;
2002
2003fn edit_optional_u32_field(field_name: &str, current_value: Option<u32>) -> OptionalU32Result {
2005 println!("\n编辑{field_name}:");
2006 println!(
2007 "当前值: {}",
2008 current_value
2009 .map(|t| t.to_string())
2010 .unwrap_or("[未设置]".to_string())
2011 .cyan()
2012 );
2013 print!("新值 (回车保持不变,输入 0 清除): ");
2014 io::stdout().flush()?;
2015
2016 let mut input = String::new();
2017 io::stdin().read_line(&mut input)?;
2018 let input = input.trim();
2019
2020 if !input.is_empty() {
2021 if input == "0" {
2022 println!("{}", format!("{field_name}已清除").green());
2023 Ok(Some(None))
2024 } else if let Ok(value) = input.parse::<u32>() {
2025 println!("{field_name}已更新为: {}", value.to_string().green());
2026 Ok(Some(Some(value)))
2027 } else {
2028 println!("{}", "错误: 请输入有效的数字".red());
2029 Ok(None)
2030 }
2031 } else {
2032 Ok(None)
2033 }
2034}
2035
2036fn edit_field_alias(config: &mut Configuration) -> Result<()> {
2038 let validator = |input: &str| -> Result<()> {
2039 if input.contains(char::is_whitespace) {
2040 anyhow::bail!("错误: 别名不能包含空白字符");
2041 }
2042 if input == "cc" {
2043 anyhow::bail!("错误: 'cc' 是保留名称");
2044 }
2045 if input == "official" {
2046 anyhow::bail!("错误: 'official' 是保留名称");
2047 }
2048 Ok(())
2049 };
2050
2051 match edit_string_field("别名", &config.alias_name, validator) {
2052 Ok(Some(new_value)) => config.alias_name = new_value,
2053 Ok(None) => {}
2054 Err(e) => println!("{}", e.to_string().red()),
2055 }
2056 Ok(())
2057}
2058
2059fn edit_field_token(config: &mut Configuration) -> Result<()> {
2061 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2062 if let Some(new_value) = edit_string_field(
2063 "令牌",
2064 &format_token_for_display(&config.token),
2065 no_validator,
2066 )? {
2067 config.token = new_value;
2068 println!("{}", "令牌已更新".green());
2069 }
2070 Ok(())
2071}
2072
2073fn edit_field_url(config: &mut Configuration) -> Result<()> {
2075 let no_validator = |_: &str| -> Result<()> { Ok(()) };
2076 if let Some(new_value) = edit_string_field("URL", &config.url, no_validator)? {
2077 config.url = new_value;
2078 }
2079 Ok(())
2080}
2081
2082fn edit_field_model(config: &mut Configuration) -> Result<()> {
2084 if let Some(result) = edit_optional_string_field("模型", config.model.as_deref())? {
2085 config.model = result;
2086 }
2087 Ok(())
2088}
2089
2090fn edit_field_small_fast_model(config: &mut Configuration) -> Result<()> {
2092 if let Some(result) =
2093 edit_optional_string_field("快速模型", config.small_fast_model.as_deref())?
2094 {
2095 config.small_fast_model = result;
2096 }
2097 Ok(())
2098}
2099
2100fn edit_field_max_thinking_tokens(config: &mut Configuration) -> Result<()> {
2102 if let Some(result) = edit_optional_u32_field("最大思考令牌数", config.max_thinking_tokens)?
2103 {
2104 config.max_thinking_tokens = result;
2105 }
2106 Ok(())
2107}
2108
2109fn edit_field_api_timeout_ms(config: &mut Configuration) -> Result<()> {
2111 if let Some(result) = edit_optional_u32_field("API超时时间 (毫秒)", config.api_timeout_ms)?
2112 {
2113 config.api_timeout_ms = result;
2114 }
2115 Ok(())
2116}
2117
2118fn edit_field_claude_code_disable_nonessential_traffic(config: &mut Configuration) -> Result<()> {
2120 if let Some(result) = edit_optional_u32_field(
2121 "禁用非必要流量标志",
2122 config.claude_code_disable_nonessential_traffic,
2123 )? {
2124 config.claude_code_disable_nonessential_traffic = result;
2125 }
2126 Ok(())
2127}
2128
2129fn edit_field_anthropic_default_sonnet_model(config: &mut Configuration) -> Result<()> {
2131 if let Some(result) = edit_optional_string_field(
2132 "默认 Sonnet 模型",
2133 config.anthropic_default_sonnet_model.as_deref(),
2134 )? {
2135 config.anthropic_default_sonnet_model = result;
2136 }
2137 Ok(())
2138}
2139
2140fn edit_field_anthropic_default_opus_model(config: &mut Configuration) -> Result<()> {
2142 if let Some(result) = edit_optional_string_field(
2143 "默认 Opus 模型",
2144 config.anthropic_default_opus_model.as_deref(),
2145 )? {
2146 config.anthropic_default_opus_model = result;
2147 }
2148 Ok(())
2149}
2150
2151fn edit_field_anthropic_default_haiku_model(config: &mut Configuration) -> Result<()> {
2153 if let Some(result) = edit_optional_string_field(
2154 "默认 Haiku 模型",
2155 config.anthropic_default_haiku_model.as_deref(),
2156 )? {
2157 config.anthropic_default_haiku_model = result;
2158 }
2159 Ok(())
2160}
2161
2162fn edit_field_claude_code_subagent_model(config: &mut Configuration) -> Result<()> {
2164 if let Some(result) =
2165 edit_optional_string_field("子代理模型", config.claude_code_subagent_model.as_deref())?
2166 {
2167 config.claude_code_subagent_model = result;
2168 }
2169 Ok(())
2170}
2171
2172fn edit_field_claude_code_disable_nonstreaming_fallback(config: &mut Configuration) -> Result<()> {
2174 if let Some(result) = edit_optional_u32_field(
2175 "禁用非流式回退标志",
2176 config.claude_code_disable_nonstreaming_fallback,
2177 )? {
2178 config.claude_code_disable_nonstreaming_fallback = result;
2179 }
2180 Ok(())
2181}
2182
2183fn edit_field_claude_code_effort_level(config: &mut Configuration) -> Result<()> {
2185 if let Some(result) =
2186 edit_optional_string_field("努力级别", config.claude_code_effort_level.as_deref())?
2187 {
2188 config.claude_code_effort_level = result;
2189 }
2190 Ok(())
2191}
2192
2193fn save_configuration_changes(original_alias: &str, new_config: &Configuration) -> Result<()> {
2195 let mut storage = ConfigStorage::load()?;
2197
2198 if original_alias != new_config.alias_name
2200 && storage.get_configuration(&new_config.alias_name).is_some()
2201 {
2202 println!("\n{}", "别名冲突!".red().bold());
2203 println!("配置 '{}' 已存在", new_config.alias_name.yellow());
2204 print!("是否覆盖现有配置? (y/N): ");
2205 io::stdout().flush()?;
2206
2207 let mut input = String::new();
2208 io::stdin().read_line(&mut input)?;
2209 let input = input.trim().to_lowercase();
2210
2211 if input != "y" && input != "yes" {
2212 println!("{}", "编辑已取消".yellow());
2213 return Ok(());
2214 }
2215 }
2216
2217 storage.update_configuration(original_alias, new_config.clone())?;
2219 storage.save()?;
2220
2221 println!("\n{}", "配置已成功保存!".green().bold());
2222
2223 Ok(())
2224}