返回 CodeWhale
router_setup.rs
根目录 / crates / tui / src / tui / views / router_setup.rs
1 //! Router setup (#6525): the one view behind `/router` and `/model router`.
2 //!
3 //! It writes the existing `[auto.router]` table and nothing else — there is
4 //! no second routing system. Presets derive from route capabilities (the
5 //! decision API a key can reach, the active provider's runnable fast tier),
6 //! never from model-name tables:
7 //!
8 //! * **Jev** — TypeSafe's decision model through OpenRouter or TypeSafe
9 //! direct, whichever key exists (OpenRouter first).
10 //! * **Fast** — the active provider's runnable fast sibling, thinking off.
11 //! * **Off** — removes `[auto.router]`; Auto takes its local fallback: the
12 //! default model, or the fast tier when `[auto] cost_saving` is on (Off
13 //! leaves that separate opt-in alone and says so).
14 //! * **Custom** — shows the TOML to edit by hand.
15 //!
16 //! Choosing Jev or Fast makes exactly one test call through the per-turn
17 //! routing path and shows the result before anything is saved; saving is a
18 //! separate, explicit step. No preset is ever elected automatically. The test
19 //! call's usage enters session cost like any routing call, and a save is
20 //! published to the runtime threads as well as the UI's config.
21 //!
22 //! Known limits: "Free OpenRouter model" and "Local model" presets need live
23 //! catalog and reachability probes and are not offered yet; the `/model`
24 //! picker "Router" row is a follow-up.
25
26 use std::cell::RefCell;
27 use std::path::{Path, PathBuf};
28
29 use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
30 use ratatui::{
31 buffer::Buffer,
32 layout::Rect,
33 style::Style,
34 text::{Line, Span},
35 widgets::{Padding, Paragraph, Widget, Wrap},
36 };
37
38 use crate::tui::app::{App, StatusToastLevel};
39 use crate::tui::history::HistoryCell;
40 use crate::tui::views::{
41 ActionHint, CommandPaletteAction, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent,
42 centered_modal_area, render_modal_footer, render_modal_rule, render_rounded_modal,
43 };
44 use codewhale_config::ProviderKind;
45 use codewhale_engine::client::system_one::DecisionRouterRoute;
46 use codewhale_engine::model_inventory::ModelInventory;
47 use codewhale_engine::model_routing::{AutoRouteSelection, provider_router_candidates};
48 use codewhale_localization::{Locale, MessageId, tr};
49 use codewhale_palette as palette;
50 use codewhale_runtime::config::{AutoConfig, AutoRouterConfig, Config};
51 use codewhale_tui_kit::menu_style;
52
53 /// Pinned OpenRouter id for Jev; `~typesafe/jev-latest` is also accepted.
54 pub(crate) const JEV_OPENROUTER_MODEL: &str = "typesafe/jev-1.13";
55 /// TypeSafe direct model id.
56 pub(crate) const JEV_TYPESAFE_MODEL: &str = "jev-latest";
57 /// Router timeout the Jev preset writes; Jev's p50 is ~0.1–0.2 s.
58 const JEV_TIMEOUT_SECS: u64 = 2;
59
60 pub(crate) type RouterPreset = codewhale_commands::router::RouterPreset<DecisionRouterRoute>;
61 pub(crate) type RouterRequest = codewhale_commands::router::RouterRequest<DecisionRouterRoute>;
62
63 pub(crate) fn parse_router_args(args: Option<&str>) -> Result<RouterRequest, String> {
64 codewhale_commands::router::parse_router_args(args, DecisionRouterRoute::parse)
65 }
66
67 impl codewhale_commands::router::RouterHost for crate::tui::app::AppAction {
68 type Route = DecisionRouterRoute;
69 fn parse_route(name: &str) -> Option<Self::Route> {
70 DecisionRouterRoute::parse(name)
71 }
72 fn router_action(request: RouterRequest) -> Self {
73 Self::RouterSetup { request }
74 }
75 }
76
77 /// The `[auto.router]` table a preset writes for this config, `Ok(None)` for
78 /// Off, or a non-secret reason the preset is unavailable.
79 pub(crate) fn preset_router_config(
80 config: &Config,
81 preset: RouterPreset,
82 locale: Locale,
83 ) -> Result<Option<AutoRouterConfig>, String> {
84 match preset {
85 RouterPreset::Off => Ok(None),
86 RouterPreset::Custom => Err(tr(locale, MessageId::RouterCustomByHand).into_owned()),
87 RouterPreset::Jev(route) => {
88 let route = match route {
89 Some(route) if route.has_key(config) => route,
90 Some(route) => {
91 return Err(no_key_reason(locale, route));
92 }
93 None => [
94 DecisionRouterRoute::Openrouter,
95 DecisionRouterRoute::Typesafe,
96 ]
97 .into_iter()
98 .find(|route| route.has_key(config))
99 .ok_or_else(|| tr(locale, MessageId::RouterNeedKey).into_owned())?,
100 };
101 let model = match route {
102 DecisionRouterRoute::Openrouter => JEV_OPENROUTER_MODEL,
103 DecisionRouterRoute::Typesafe => JEV_TYPESAFE_MODEL,
104 };
105 Ok(Some(AutoRouterConfig {
106 kind: Some("decision".to_string()),
107 provider: Some(route.as_str().to_string()),
108 model: Some(model.to_string()),
109 timeout_secs: Some(JEV_TIMEOUT_SECS),
110 min_confidence: Some(codewhale_runtime::config::DEFAULT_AUTO_ROUTER_MIN_CONFIDENCE),
111 shadow_gate: config
112 .auto
113 .as_ref()
114 .and_then(|auto| auto.router.as_ref())
115 .and_then(|router| router.shadow_gate),
116 ..Default::default()
117 }))
118 }
119 RouterPreset::Fast => {
120 let (provider, fast) = runnable_fast_tier(config)
121 .ok_or_else(|| tr(locale, MessageId::RouterNoFastTier).into_owned())?;
122 Ok(Some(AutoRouterConfig {
123 kind: Some("chat".to_string()),
124 provider: Some(provider.as_str().to_string()),
125 model: Some(fast),
126 thinking: Some("off".to_string()),
127 ..Default::default()
128 }))
129 }
130 }
131 }
132
133 /// What Off does for this config: `[auto] cost_saving` is a separate opt-in
134 /// that Off leaves in place, so its fallback is the fast tier, not the default.
135 fn off_hint(config: &Config, locale: Locale) -> String {
136 let id = if config.auto_cost_saving() {
137 MessageId::RouterPresetOffCostSavingHint
138 } else {
139 MessageId::RouterPresetOffHint
140 };
141 tr(locale, id).into_owned()
142 }
143
144 fn no_key_reason(locale: Locale, route: DecisionRouterRoute) -> String {
145 tr(locale, MessageId::RouterNoKey).replace("{route}", route.display_name())
146 }
147
148 /// The active provider's runnable fast sibling, from route capabilities.
149 fn runnable_fast_tier(config: &Config) -> Option<(ProviderKind, String)> {
150 let inventory = ModelInventory::from_config(config).ok()?;
151 let active = inventory.active_default()?;
152 let fast = provider_router_candidates(active.provider, &active.model).cheap?;
153 let candidate = inventory
154 .candidate(active.identity.key.as_str(), &fast)
155 .filter(|candidate| candidate.readiness.can_attempt())?;
156 Some((active.provider, candidate.model.clone()))
157 }
158
159 /// Write `router` as `[auto.router]` (or remove the table for `None`) through
160 /// the single config writer, replacing any previous router keys.
161 pub(crate) fn persist_auto_router(
162 config_path: Option<&Path>,
163 router: Option<&AutoRouterConfig>,
164 ) -> anyhow::Result<PathBuf> {
165 use codewhale_runtime::config_persistence::{
166 config_toml_path, mutate_config_document, set_document_value, unset_document_value,
167 };
168 let path = config_toml_path(config_path)?;
169 mutate_config_document(&path, |doc| {
170 unset_document_value(doc, &["auto", "router"])?;
171 let Some(router) = router else {
172 return Ok(());
173 };
174 let strings = [
175 ("kind", router.kind.as_deref()),
176 ("provider", router.provider.as_deref()),
177 ("model", router.model.as_deref()),
178 ("thinking", router.thinking.as_deref()),
179 ("base_url", router.base_url.as_deref()),
180 ];
181 for (key, value) in strings {
182 if let Some(value) = value {
183 set_document_value(doc, &["auto", "router", key], value)?;
184 }
185 }
186 if let Some(secs) = router.timeout_secs {
187 let secs = i64::try_from(secs).unwrap_or(i64::MAX);
188 set_document_value(doc, &["auto", "router", "timeout_secs"], secs)?;
189 }
190 if let Some(min_confidence) = router.min_confidence {
191 set_document_value(doc, &["auto", "router", "min_confidence"], min_confidence)?;
192 }
193 if let Some(shadow_gate) = router.shadow_gate {
194 set_document_value(doc, &["auto", "router", "shadow_gate"], shadow_gate)?;
195 }
196 Ok(())
197 })?;
198 Ok(path)
199 }
200
201 /// Handle a `/router` request on the UI loop, where the live config lives.
202 pub(crate) async fn handle_router_request(
203 app: &mut App,
204 config: &mut Config,
205 request: RouterRequest,
206 ) {
207 match request {
208 RouterRequest::Open => {
209 if app.view_stack.top_kind() != Some(ModalKind::RouterSetup) {
210 app.view_stack
211 .push(RouterSetupView::picker(config, app.ui_locale));
212 }
213 }
214 RouterRequest::Test(RouterPreset::Custom) => {
215 app.add_message(HistoryCell::System {
216 content: custom_router_help(config, app.ui_locale),
217 });
218 }
219 RouterRequest::Test(preset) => test_preset(app, config, preset).await,
220 RouterRequest::Save(preset) => {
221 // Reads the App's slot: only a save needs the manager, so no other
222 // request has to wait for one to exist.
223 let Some(task_manager) = app.task_manager() else {
224 app.add_message(HistoryCell::System {
225 content: codewhale_localization::tr(
226 app.ui_locale,
227 codewhale_localization::MessageId::TaskInventoryUnavailable,
228 )
229 .to_string(),
230 });
231 return;
232 };
233 save_preset(app, config, &task_manager, preset).await
234 }
235 }
236 }
237
238 async fn test_preset(app: &mut App, config: &Config, preset: RouterPreset) {
239 let locale = app.ui_locale;
240 let router = match preset_router_config(config, preset, locale) {
241 Ok(router) => router,
242 Err(reason) => {
243 app.push_status_toast(
244 tr(app.ui_locale, MessageId::RouterPresetUnavailable).replace("{reason}", &reason),
245 StatusToastLevel::Warning,
246 Some(6_000),
247 );
248 return;
249 }
250 };
251 let lines = match router.as_ref() {
252 None => vec![off_hint(config, locale)],
253 Some(router) => {
254 // The test call awaits a provider inline on the UI loop; refuse
255 // while Runtime Chat owns the run, as other inline calls do.
256 if app.remote_control.runtime_chat_blocks_local_dispatch() {
257 app.push_status_toast(
258 tr(app.ui_locale, MessageId::SettingLockedDuringTurn)
259 .replace("{setting}", "Codewhale Runtime"),
260 StatusToastLevel::Info,
261 Some(6_000),
262 );
263 return;
264 }
265 let mut candidate = config.clone();
266 candidate
267 .auto
268 .get_or_insert_with(AutoConfig::default)
269 .router = Some(router.clone());
270 let mut lines = vec![router_summary(router, locale)];
271 // Captured before the call, like any background provider request.
272 let cost_scope = codewhale_engine::cost_status::scope_token();
273 let origin = app
274 .session_write_receipt
275 .as_ref()
276 .and_then(|source| source.usage_origin(cost_scope).ok());
277 match codewhale_engine::model_routing::test_auto_router(&candidate, origin).await {
278 Ok((selection, latency_ms)) => {
279 // The test call is real spend: settle it into session
280 // cost exactly as a turn's routing call is settled.
281 codewhale_engine::cost_status::record_runtime_usage_batch(
282 cost_scope,
283 None,
284 &codewhale_engine::cost_status::RuntimeUsageBatch {
285 decisions: Vec::new(),
286 records: selection.routed_usage.clone(),
287 drop_records: selection.routed_usage_drop_records.clone(),
288 dropped_records: selection.routed_usage_dropped_records,
289 },
290 );
291 lines.extend(describe_test_selection(&selection, latency_ms, locale));
292 }
293 Err(reason) => lines
294 .push(tr(locale, MessageId::RouterTestNotMade).replace("{reason}", &reason)),
295 }
296 lines
297 }
298 };
299 app.add_message(HistoryCell::System {
300 content: format!(
301 "{}\n{}",
302 tr(locale, MessageId::RouterTestHeader)
303 .replace("{args}", &preset.command_args(DecisionRouterRoute::as_str)),
304 lines.join("\n")
305 ),
306 });
307 app.view_stack
308 .push(RouterSetupView::confirm(preset, lines, app.ui_locale));
309 }
310
311 async fn save_preset(
312 app: &mut App,
313 config: &mut Config,
314 task_manager: &codewhale_engine::task_manager::TaskManager,
315 preset: RouterPreset,
316 ) {
317 let locale = app.ui_locale;
318 let router = match preset_router_config(config, preset, locale) {
319 Ok(router) => router,
320 Err(reason) => {
321 app.add_message(HistoryCell::System {
322 content: tr(locale, MessageId::RouterPresetUnavailable)
323 .replace("{reason}", &reason),
324 });
325 return;
326 }
327 };
328 // The config writer reads, locks and rewrites config.toml; keep that
329 // file IO off the UI runtime (#6149).
330 let config_path = app.config_path.clone();
331 let to_write = router.clone();
332 let persisted = tokio::task::spawn_blocking(move || {
333 persist_auto_router(config_path.as_deref(), to_write.as_ref())
334 })
335 .await
336 .map_err(anyhow::Error::from)
337 .and_then(|result| result);
338 match persisted {
339 Ok(path) => {
340 config.auto.get_or_insert_with(AutoConfig::default).router = router.clone();
341 let what = router.as_ref().map_or_else(
342 || tr(locale, MessageId::ConfigValueOff).into_owned(),
343 |router| router_summary(router, locale),
344 );
345 app.add_message(HistoryCell::System {
346 content: tr(locale, MessageId::RouterSaved)
347 .replace("{router}", &what)
348 .replace("{path}", &path.display().to_string()),
349 });
350 // Runtime-chat and queued runtime turns resolve Auto from the
351 // runtime manager's own config snapshot; publish the new router
352 // there too, or they keep routing with the old one.
353 let runtime_router = router.clone();
354 if let Err(error) = task_manager
355 .reload_runtime_config_with(|runtime| {
356 runtime.auto.get_or_insert_with(AutoConfig::default).router = runtime_router;
357 })
358 .await
359 {
360 app.add_message(HistoryCell::Error {
361 message: tr(locale, MessageId::RouterRuntimeNotReloaded)
362 .replace("{error}", &error.to_string()),
363 severity: codewhale_error_taxonomy::ErrorSeverity::Warning,
364 code: None,
365 });
366 }
367 }
368 Err(error) => app.add_message(HistoryCell::Error {
369 message: tr(locale, MessageId::RouterNotSaved).replace("{error}", &error.to_string()),
370 severity: codewhale_error_taxonomy::ErrorSeverity::Error,
371 code: None,
372 }),
373 }
374 }
375
376 fn router_summary(router: &AutoRouterConfig, locale: Locale) -> String {
377 let kind = router.kind.as_deref().unwrap_or("chat");
378 let provider = router.provider.as_deref().unwrap_or("?");
379 let model = router.model.as_deref().unwrap_or("?");
380 let id = if router.thinking.is_some() {
381 MessageId::RouterSummaryThinking
382 } else {
383 MessageId::RouterSummary
384 };
385 tr(locale, id)
386 .replace("{kind}", kind)
387 .replace("{provider}", provider)
388 .replace("{model}", model)
389 .replace("{thinking}", router.thinking.as_deref().unwrap_or_default())
390 }
391
392 /// The test result: which tier it picked, why, and what the call cost.
393 fn describe_test_selection(
394 selection: &AutoRouteSelection,
395 latency_ms: u64,
396 locale: Locale,
397 ) -> Vec<String> {
398 let percent = |bp: u16| format!("{}%", (u32::from(bp) + 50) / 100);
399 let mut lines = vec![
400 tr(locale, MessageId::RouterTestWouldRoute)
401 .replace(
402 "{request}",
403 codewhale_engine::model_routing::ROUTER_TEST_REQUEST,
404 )
405 .replace(
406 "{provider}",
407 selection
408 .provider
409 .compatibility()
410 .map_or(selection.provider.key.as_str(), |row| row.label),
411 )
412 .replace("{model}", &selection.model)
413 .replace("{latency}", &latency_ms.to_string()),
414 ];
415 let Some(receipt) = selection.receipt.as_ref() else {
416 return lines;
417 };
418 lines.push(
419 tr(locale, MessageId::RouterTestDecision)
420 .replace("{tier}", receipt.tier.label())
421 .replace("{reason}", &receipt.reason.label()),
422 );
423 if let Some(decision) = receipt.decision.as_ref() {
424 let probabilities = decision
425 .probabilities_bp
426 .iter()
427 .map(|(option, bp)| format!("{option} {}", percent(*bp)))
428 .collect::<Vec<_>>()
429 .join(" · ");
430 lines.push(
431 tr(locale, MessageId::RouterTestChoice)
432 .replace("{choice}", &decision.choice)
433 .replace("{probabilities}", &probabilities)
434 .replace("{confidence}", &percent(decision.confidence_bp))
435 .replace("{min}", &percent(decision.min_confidence_bp)),
436 );
437 lines.push(match decision.provider_reported_cost_usd.as_deref() {
438 Some(cost) => tr(locale, MessageId::RouterTestCostReported).replace("{cost}", cost),
439 None => tr(locale, MessageId::RouterTestCostUnreported).into_owned(),
440 });
441 } else if let Some(usage) = selection.routed_usage.first() {
442 lines.push(
443 tr(locale, MessageId::RouterTestUsage)
444 .replace("{input}", &usage.usage.usage.input_tokens.to_string())
445 .replace("{output}", &usage.usage.usage.output_tokens.to_string()),
446 );
447 }
448 if let Some(failure) = receipt.router_failure {
449 lines.push(tr(locale, MessageId::RouterTestFailing).replace("{reason}", &failure.label()));
450 }
451 lines
452 }
453
454 fn custom_router_help(config: &Config, locale: Locale) -> String {
455 let current = config
456 .auto
457 .as_ref()
458 .and_then(|auto| auto.router.as_ref())
459 .map_or_else(
460 || tr(locale, MessageId::ConfigValueOff).into_owned(),
461 |router| router_summary(router, locale),
462 );
463 format!(
464 "{}\n{}\n\n\
465 [auto.router]\n\
466 kind = \"chat\" # or \"decision\" for Jev\n\
467 provider = \"deepseek\" # decision: \"openrouter\" or \"typesafe\"\n\
468 model = \"deepseek-flash\"\n\
469 thinking = \"off\" # chat routers only\n\
470 timeout_secs = 4\n\
471 # min_confidence = 0.5 # decision routers only\n\
472 # shadow_gate = true # decision routers only: log the Decision Gate's recommendation\n\n\
473 {}",
474 tr(locale, MessageId::RouterCurrent).replace("{router}", &current),
475 tr(locale, MessageId::RouterCustomHelpIntro),
476 tr(locale, MessageId::RouterCustomHelpOutro),
477 )
478 }
479
480 struct PresetRow {
481 preset: RouterPreset,
482 label: String,
483 hint: String,
484 available: bool,
485 }
486
487 enum Mode {
488 Pick,
489 Confirm {
490 preset: RouterPreset,
491 lines: Vec<String>,
492 },
493 }
494
495 /// The Router setup view: a preset picker, then a test-result confirmation.
496 pub(crate) struct RouterSetupView {
497 mode: Mode,
498 rows: Vec<PresetRow>,
499 current: String,
500 cursor: usize,
501 locale: Locale,
502 /// `(row index, rect)` for the rows actually drawn this frame.
503 row_hitboxes: RefCell<Vec<(usize, Rect)>>,
504 }
505
506 impl RouterSetupView {
507 fn picker(config: &Config, locale: Locale) -> Self {
508 let unavailable = |reason: String| {
509 tr(locale, MessageId::RouterPresetUnavailable).replace("{reason}", &reason)
510 };
511 let mut rows = Vec::new();
512 let make_jev_row = |route: DecisionRouterRoute| {
513 let preset = RouterPreset::Jev(Some(route));
514 let mut hint =
515 tr(locale, MessageId::RouterPresetJevHint).replace("{route}", route.display_name());
516 let available = route.has_key(config);
517 if !available {
518 hint = unavailable(no_key_reason(locale, route));
519 }
520 if route == DecisionRouterRoute::Typesafe {
521 hint = format!(
522 "{hint} · {}",
523 tr(locale, MessageId::RouterTypesafeSignupPaused)
524 );
525 }
526 PresetRow {
527 preset,
528 label: format!("Jev · {}", route.display_name()),
529 hint,
530 available,
531 }
532 };
533 rows.push(make_jev_row(DecisionRouterRoute::Openrouter));
534 let fast = runnable_fast_tier(config);
535 rows.push(PresetRow {
536 preset: RouterPreset::Fast,
537 label: tr(locale, MessageId::RouterPresetFastLabel).into_owned(),
538 hint: match fast.as_ref() {
539 Some((provider, model)) => tr(locale, MessageId::RouterPresetFastHint)
540 .replace("{model}", model)
541 .replace("{provider}", provider.provider().display_name()),
542 None => unavailable(tr(locale, MessageId::RouterNoFastTier).into_owned()),
543 },
544 available: fast.is_some(),
545 });
546 rows.push(make_jev_row(DecisionRouterRoute::Typesafe));
547 rows.push(PresetRow {
548 preset: RouterPreset::Off,
549 label: tr(locale, MessageId::ConfigValueOff).into_owned(),
550 hint: off_hint(config, locale),
551 available: true,
552 });
553 rows.push(PresetRow {
554 preset: RouterPreset::Custom,
555 label: tr(locale, MessageId::RouterPresetCustomLabel).into_owned(),
556 hint: tr(locale, MessageId::RouterPresetCustomHint).into_owned(),
557 available: true,
558 });
559 let inventory = ModelInventory::from_config(config);
560 let current = match config.auto.as_ref().and_then(|auto| auto.router.as_ref()) {
561 None => tr(locale, MessageId::RouterCurrent)
562 .replace("{router}", &tr(locale, MessageId::ConfigValueOff)),
563 Some(router) => match inventory {
564 Err(reason) => tr(locale, MessageId::RouterCurrentFailing)
565 .replace("{router}", &router_summary(router, locale))
566 .replace("{reason}", &reason),
567 Ok(inventory) => match inventory.router_setup_issue {
568 Some(issue) => tr(locale, MessageId::RouterCurrentFailing)
569 .replace("{router}", &router_summary(router, locale))
570 .replace("{reason}", issue.label()),
571 None => tr(locale, MessageId::RouterCurrent)
572 .replace("{router}", &router_summary(router, locale)),
573 },
574 },
575 };
576 Self {
577 mode: Mode::Pick,
578 rows,
579 current,
580 cursor: 0,
581 locale,
582 row_hitboxes: RefCell::new(Vec::new()),
583 }
584 }
585
586 fn confirm(preset: RouterPreset, lines: Vec<String>, locale: Locale) -> Self {
587 Self {
588 mode: Mode::Confirm { preset, lines },
589 rows: Vec::new(),
590 current: String::new(),
591 cursor: 0,
592 locale,
593 row_hitboxes: RefCell::new(Vec::new()),
594 }
595 }
596
597 fn run(command: String) -> ViewAction {
598 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
599 action: CommandPaletteAction::ExecuteCommand { command },
600 })
601 }
602
603 fn select(&self) -> ViewAction {
604 match &self.mode {
605 Mode::Confirm { preset, .. } => Self::run(format!(
606 "/router save {}",
607 preset.command_args(DecisionRouterRoute::as_str)
608 )),
609 Mode::Pick => match self.rows.get(self.cursor) {
610 Some(row) if row.available => Self::run(format!(
611 "/router {}",
612 row.preset.command_args(DecisionRouterRoute::as_str)
613 )),
614 _ => ViewAction::None,
615 },
616 }
617 }
618 }
619
620 impl ModalView for RouterSetupView {
621 fn kind(&self) -> ModalKind {
622 ModalKind::RouterSetup
623 }
624
625 fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
626 self
627 }
628
629 fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
630 if matches!(self.mode, Mode::Pick)
631 && let Some(motion) = codewhale_tui_kit::list_nav::motion(&key)
632 && let Some(next) = codewhale_tui_kit::list_nav::apply(
633 self.cursor,
634 self.rows.len(),
635 self.rows.len(),
636 motion,
637 )
638 {
639 self.cursor = next;
640 return ViewAction::None;
641 }
642 match key.code {
643 KeyCode::Esc => ViewAction::Close,
644 KeyCode::Enter => self.select(),
645 _ => ViewAction::None,
646 }
647 }
648
649 fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
650 if let MouseEventKind::Down(MouseButton::Left) = mouse.kind {
651 let clicked = self
652 .row_hitboxes
653 .borrow()
654 .iter()
655 .find(|(_, rect)| {
656 rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row))
657 })
658 .map(|(index, _)| *index);
659 if let Some(index) = clicked {
660 self.cursor = index;
661 return self.select();
662 }
663 }
664 ViewAction::None
665 }
666
667 fn render(&self, area: Rect, buf: &mut Buffer) {
668 let body_rows = match &self.mode {
669 Mode::Pick => self.rows.len() * 2 + 2,
670 Mode::Confirm { lines, .. } => lines.len() + 3,
671 };
672 let popup_height = u16::try_from(body_rows)
673 .unwrap_or(u16::MAX)
674 .saturating_add(6);
675 let popup_area = centered_modal_area(area, 96, popup_height, 44, 10);
676 let (inner, _) = render_rounded_modal(
677 area,
678 popup_area,
679 buf,
680 SurfaceFrame::new(tr(self.locale, MessageId::RouterSetupTitle))
681 .padding(Padding::uniform(1)),
682 );
683
684 let locale = self.locale;
685 let hints = match self.mode {
686 Mode::Pick => vec![
687 ActionHint::new("↑/↓", tr(locale, MessageId::PickerActionMove)),
688 ActionHint::new("Enter", tr(locale, MessageId::RouterActionTest)),
689 ActionHint::new("Esc", tr(locale, MessageId::SessionsActionClose)),
690 ],
691 Mode::Confirm { .. } => vec![
692 ActionHint::new("Enter", tr(locale, MessageId::RouterActionSave)),
693 ActionHint::new("Esc", tr(locale, MessageId::RouterActionDiscard)),
694 ],
695 };
696 let content = render_modal_footer(inner, buf, &hints);
697 self.row_hitboxes.borrow_mut().clear();
698
699 let muted = Style::default().fg(palette::TEXT_MUTED);
700 match &self.mode {
701 Mode::Confirm { lines: result, .. } => {
702 let mut lines = Vec::new();
703 for line in result {
704 lines.push(Line::from(Span::styled(
705 line.clone(),
706 Style::default().fg(palette::TEXT_PRIMARY),
707 )));
708 }
709 lines.push(Line::from(""));
710 lines.push(Line::from(Span::styled(
711 tr(self.locale, MessageId::RouterTestSaveHint).into_owned(),
712 muted,
713 )));
714 Paragraph::new(lines)
715 .wrap(Wrap { trim: false })
716 .render(content, buf);
717 }
718 Mode::Pick => {
719 let height = usize::from(content.height);
720 let width = usize::from(content.width);
721 let two_line = height >= 2 + self.rows.len() * 2;
722 let header = if two_line {
723 2
724 } else {
725 usize::from(height >= 2)
726 };
727 let row_height: u16 = if two_line { 2 } else { 1 };
728 let visible = (height.saturating_sub(header) / usize::from(row_height)).max(1);
729 let start = self
730 .cursor
731 .saturating_sub(visible - 1)
732 .min(self.rows.len().saturating_sub(visible));
733 if header > 0 && content.height > 0 {
734 Paragraph::new(Line::from(Span::styled(
735 codewhale_tui_kit::ui_text::semantic_truncate(&self.current, width),
736 muted,
737 )))
738 .render(Rect::new(content.x, content.y, content.width, 1), buf);
739 }
740 if header > 1 && content.height > 1 {
741 render_modal_rule(Rect::new(content.x, content.y + 1, content.width, 1), buf);
742 }
743 let list_area = Rect {
744 y: content.y.saturating_add(header as u16),
745 height: content.height.saturating_sub(header as u16),
746 ..content
747 };
748 let mut lines = Vec::new();
749 let mut selected_row_y: Option<u16> = None;
750 for (idx, row) in self.rows.iter().enumerate().skip(start).take(visible) {
751 let is_cursor = idx == self.cursor;
752 let label_style = if is_cursor {
753 menu_style::selected_row_style()
754 } else if row.available {
755 Style::default().fg(palette::TEXT_PRIMARY)
756 } else {
757 muted
758 };
759 let dot_style = if is_cursor {
760 menu_style::selected_row_style()
761 } else if row.available {
762 Style::default().fg(palette::STATUS_SUCCESS)
763 } else {
764 Style::default().fg(palette::TEXT_DIM)
765 };
766 let pointer = codewhale_tui_kit::glyphs::selection_marker(is_cursor);
767 let dot = if row.available {
768 codewhale_tui_kit::glyphs::CURRENT
769 } else {
770 "○"
771 };
772 let row_y = list_area
773 .y
774 .saturating_add(u16::try_from(lines.len()).unwrap_or(u16::MAX));
775 if is_cursor && row_y < list_area.bottom() {
776 selected_row_y = Some(row_y);
777 }
778 let label_budget = width.saturating_sub(4);
779 lines.push(Line::from(vec![
780 Span::styled(format!("{pointer} "), label_style),
781 Span::styled(format!("{dot} "), dot_style),
782 Span::styled(
783 codewhale_tui_kit::ui_text::semantic_truncate(&row.label, label_budget),
784 label_style,
785 ),
786 ]));
787 if two_line {
788 lines.push(Line::from(Span::styled(
789 format!(
790 " {}",
791 codewhale_tui_kit::ui_text::semantic_truncate(
792 &row.hint,
793 width.saturating_sub(4)
794 )
795 ),
796 muted,
797 )));
798 }
799 self.row_hitboxes.borrow_mut().push((
800 idx,
801 Rect::new(list_area.x, row_y, list_area.width, row_height),
802 ));
803 }
804 if let Some(y) = selected_row_y {
805 buf.set_style(
806 Rect::new(list_area.x, y, list_area.width, 1),
807 menu_style::selected_row_bg_style(),
808 );
809 }
810 Paragraph::new(lines).render(list_area, buf);
811 }
812 }
813 }
814 }
815
816 #[cfg(test)]
817 mod tests {
818 use super::*;
819
820 /// Tuple fields drop in order: restore the environment, then unlock.
821 fn hermetic() -> (
822 crate::test_support::EnvVarGuard,
823 crate::test_support::EnvVarGuard,
824 crate::test_support::TestEnvLock,
825 ) {
826 let lock = crate::test_support::lock_test_env();
827 (
828 crate::test_support::EnvVarGuard::remove("OPENROUTER_API_KEY"),
829 crate::test_support::EnvVarGuard::remove("TYPESAFE_API_KEY"),
830 lock,
831 )
832 }
833
834 fn deepseek_with_openrouter_key(openrouter_key: bool) -> Config {
835 {
836 let __cw_config_init_0_0 = Some("deepseek".to_string());
837 let __cw_config_init_0_1 = Some("deepseek-v4-pro".to_string());
838 let __cw_config_init_0_2 = Some(codewhale_runtime::config::ProvidersConfig {
839 deepseek: codewhale_runtime::config::ProviderConfig {
840 api_key: Some("ds-test-key".to_string()),
841 ..Default::default()
842 },
843 openrouter: codewhale_runtime::config::ProviderConfig {
844 api_key: openrouter_key.then(|| "or-test-key".to_string()),
845 ..Default::default()
846 },
847 ..Default::default()
848 });
849 let mut __cw_config_init_0_value: Config = Default::default();
850 __cw_config_init_0_value.provider = __cw_config_init_0_0;
851 __cw_config_init_0_value.default_text_model = __cw_config_init_0_1;
852 __cw_config_init_0_value.providers = __cw_config_init_0_2;
853 __cw_config_init_0_value
854 }
855 }
856
857 #[test]
858 fn router_args_parse_to_requests() {
859 assert_eq!(parse_router_args(None), Ok(RouterRequest::Open));
860 assert_eq!(
861 parse_router_args(Some("jev")),
862 Ok(RouterRequest::Test(RouterPreset::Jev(None)))
863 );
864 assert_eq!(
865 parse_router_args(Some("save jev typesafe")),
866 Ok(RouterRequest::Save(RouterPreset::Jev(Some(
867 DecisionRouterRoute::Typesafe
868 ))))
869 );
870 assert_eq!(
871 parse_router_args(Some("fast")),
872 Ok(RouterRequest::Test(RouterPreset::Fast))
873 );
874 assert!(parse_router_args(Some("jev zai")).is_err());
875 assert!(parse_router_args(Some("turbo")).is_err());
876 }
877
878 #[test]
879 fn presets_derive_from_keys_and_route_capabilities() {
880 let _env = hermetic();
881 let config = deepseek_with_openrouter_key(true);
882 let jev = preset_router_config(&config, RouterPreset::Jev(None), Locale::En)
883 .expect("jev available")
884 .expect("jev writes a table");
885 assert_eq!(jev.kind.as_deref(), Some("decision"));
886 assert_eq!(jev.provider.as_deref(), Some("openrouter"));
887 assert_eq!(jev.model.as_deref(), Some(JEV_OPENROUTER_MODEL));
888 assert_eq!(jev.timeout_secs, Some(2));
889
890 let fast = preset_router_config(&config, RouterPreset::Fast, Locale::En)
891 .expect("fast available")
892 .expect("fast writes a table");
893 assert_eq!(fast.kind.as_deref(), Some("chat"));
894 assert_eq!(fast.provider.as_deref(), Some("deepseek"));
895 assert_eq!(fast.model.as_deref(), Some("deepseek-flash"));
896 assert_eq!(fast.thinking.as_deref(), Some("off"));
897
898 assert!(matches!(
899 preset_router_config(&config, RouterPreset::Off, Locale::En),
900 Ok(None)
901 ));
902
903 // No key anywhere: Jev is unavailable, never guessed.
904 let no_key = deepseek_with_openrouter_key(false);
905 assert!(preset_router_config(&no_key, RouterPreset::Jev(None), Locale::En).is_err());
906 }
907
908 #[test]
909 fn saving_a_preset_writes_exactly_the_router_table() {
910 let _env = hermetic();
911 let dir = tempfile::tempdir().expect("config dir");
912 let path = dir.path().join("config.toml");
913 std::fs::write(
914 &path,
915 "# keep me\nprovider = \"deepseek\"\n\n[auto]\ncost_saving = true\n\n[auto.router]\nprovider = \"zai\"\nmodel = \"glm-5-turbo\"\nthinking = \"low\"\n",
916 )
917 .expect("seed config");
918 let config = deepseek_with_openrouter_key(true);
919 let jev = preset_router_config(&config, RouterPreset::Jev(None), Locale::En)
920 .expect("jev")
921 .expect("table");
922
923 persist_auto_router(Some(&path), Some(&jev)).expect("persist jev");
924 let written = std::fs::read_to_string(&path).expect("read back");
925 assert!(written.contains("# keep me"), "{written}");
926 let reloaded: Config = toml::from_str(&written).expect("reload");
927 let auto = reloaded.auto.expect("[auto]");
928 assert_eq!(auto.cost_saving, Some(true));
929 let router = auto.router.expect("[auto.router]");
930 assert_eq!(router.kind.as_deref(), Some("decision"));
931 assert_eq!(router.provider.as_deref(), Some("openrouter"));
932 assert_eq!(router.model.as_deref(), Some(JEV_OPENROUTER_MODEL));
933 assert_eq!(router.thinking, None, "stale chat keys are replaced");
934 assert_eq!(router.timeout_secs, Some(2));
935 assert_eq!(router.min_confidence, Some(0.5));
936
937 persist_auto_router(Some(&path), None).expect("persist off");
938 let reloaded: Config =
939 toml::from_str(&std::fs::read_to_string(&path).expect("read back")).expect("reload");
940 assert!(reloaded.auto.expect("[auto] kept").router.is_none());
941 }
942
943 #[test]
944 fn saving_the_decision_preset_keeps_shadow_gate() {
945 let _env = hermetic();
946 let dir = tempfile::tempdir().expect("config dir");
947 let path = dir.path().join("config.toml");
948 std::fs::write(
949 &path,
950 "[auto.router]\nkind = \"decision\"\nprovider = \"typesafe\"\nshadow_gate = true\n",
951 )
952 .expect("seed config");
953 let mut config = deepseek_with_openrouter_key(true);
954 config.auto = Some(codewhale_runtime::config::AutoConfig {
955 router: Some(AutoRouterConfig {
956 kind: Some("decision".to_string()),
957 shadow_gate: Some(true),
958 ..Default::default()
959 }),
960 ..Default::default()
961 });
962 let jev = preset_router_config(&config, RouterPreset::Jev(None), Locale::En)
963 .expect("jev")
964 .expect("table");
965 persist_auto_router(Some(&path), Some(&jev)).expect("persist jev");
966 let reloaded: Config =
967 toml::from_str(&std::fs::read_to_string(&path).expect("read back")).expect("reload");
968 let router = reloaded.auto.and_then(|auto| auto.router).expect("router");
969 assert_eq!(router.shadow_gate, Some(true));
970
971 let fast = AutoRouterConfig {
972 kind: Some("chat".to_string()),
973 provider: Some("deepseek".to_string()),
974 model: Some("deepseek-v4-flash".to_string()),
975 ..Default::default()
976 };
977 persist_auto_router(Some(&path), Some(&fast)).expect("persist chat");
978 let reloaded: Config =
979 toml::from_str(&std::fs::read_to_string(&path).expect("read back")).expect("reload");
980 let router = reloaded.auto.and_then(|auto| auto.router).expect("router");
981 assert_eq!(router.shadow_gate, None);
982 }
983
984 #[test]
985 fn confirm_view_saves_only_on_enter() {
986 use crossterm::event::KeyModifiers;
987 let preset = RouterPreset::Jev(Some(DecisionRouterRoute::Openrouter));
988 let mut view = RouterSetupView::confirm(preset, vec!["result".to_string()], Locale::En);
989 match view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)) {
990 ViewAction::EmitAndClose(ViewEvent::CommandPaletteSelected {
991 action: CommandPaletteAction::ExecuteCommand { command },
992 }) => assert_eq!(command, "/router save jev openrouter"),
993 other => panic!("expected save command, got {other:?}"),
994 }
995 assert!(matches!(
996 view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)),
997 ViewAction::Close
998 ));
999 }
1000
1001 fn rendered(view: &RouterSetupView, width: u16, height: u16) -> String {
1002 let area = Rect::new(0, 0, width, height);
1003 let mut buf = Buffer::empty(area);
1004 view.render(area, &mut buf);
1005 (0..height)
1006 .map(|y| (0..width).map(|x| buf[(x, y)].symbol()).collect::<String>())
1007 .collect::<Vec<_>>()
1008 .join("\n")
1009 }
1010
1011 #[test]
1012 fn compact_picker_keeps_the_focused_row_visible_and_clickable() {
1013 use crossterm::event::KeyModifiers;
1014 let _env = hermetic();
1015 let mut view = RouterSetupView::picker(&deepseek_with_openrouter_key(true), Locale::En);
1016 let last = view.rows.len() - 1;
1017 for _ in 0..last {
1018 view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
1019 }
1020 assert_eq!(view.cursor, last);
1021 let text = rendered(&view, 40, 12);
1022 let custom = tr(Locale::En, MessageId::RouterPresetCustomLabel);
1023 assert!(
1024 text.contains(custom.as_ref()),
1025 "focused row hidden:\n{text}"
1026 );
1027 let hitboxes = view.row_hitboxes.borrow();
1028 assert!(
1029 hitboxes.iter().any(|(index, _)| *index == last),
1030 "focused row has no hitbox"
1031 );
1032 assert!(hitboxes.iter().all(|(_, rect)| rect.bottom() <= 12));
1033 drop(hitboxes);
1034
1035 // A roomy frame still shows every row with its hint.
1036 let roomy = rendered(&view, 100, 40);
1037 assert!(roomy.contains(tr(Locale::En, MessageId::RouterPresetCustomHint).as_ref()));
1038 assert_eq!(view.row_hitboxes.borrow().len(), view.rows.len());
1039 }
1040
1041 #[test]
1042 fn off_hint_names_the_cost_saving_fallback() {
1043 let _env = hermetic();
1044 let mut config = deepseek_with_openrouter_key(true);
1045 let off = |config: &Config| {
1046 RouterSetupView::picker(config, Locale::En)
1047 .rows
1048 .into_iter()
1049 .find(|row| row.preset == RouterPreset::Off)
1050 .expect("off row")
1051 .hint
1052 };
1053 assert_eq!(off(&config), tr(Locale::En, MessageId::RouterPresetOffHint));
1054 config.auto = Some(AutoConfig {
1055 cost_saving: Some(true),
1056 ..Default::default()
1057 });
1058 assert_eq!(
1059 off(&config),
1060 tr(Locale::En, MessageId::RouterPresetOffCostSavingHint)
1061 );
1062 }
1063
1064 #[test]
1065 fn picker_and_reasons_follow_the_ui_locale() {
1066 let _env = hermetic();
1067 let config = deepseek_with_openrouter_key(false);
1068 let view = RouterSetupView::picker(&config, Locale::Ja);
1069 let fast = view
1070 .rows
1071 .iter()
1072 .find(|row| row.preset == RouterPreset::Fast)
1073 .expect("fast row");
1074 assert_eq!(fast.label, tr(Locale::Ja, MessageId::RouterPresetFastLabel));
1075 assert_ne!(fast.label, "Fast tier");
1076 let english = ["Current:", "no OpenRouter API key", "Custom"];
1077 let rendered: Vec<&str> = std::iter::once(view.current.as_str())
1078 .chain(
1079 view.rows
1080 .iter()
1081 .flat_map(|row| [row.label.as_str(), row.hint.as_str()]),
1082 )
1083 .collect();
1084 for text in &rendered {
1085 for word in english {
1086 assert!(
1087 !text.contains(word),
1088 "{word:?} left in Japanese view: {text}"
1089 );
1090 }
1091 }
1092 let reason = preset_router_config(&config, RouterPreset::Jev(None), Locale::Ja)
1093 .expect_err("no decision key");
1094 assert_eq!(reason, tr(Locale::Ja, MessageId::RouterNeedKey));
1095 }
1096
1097 #[test]
1098 fn paused_typesafe_preset_sits_below_runnable_fast_tier() {
1099 let _env = hermetic();
1100 let view = RouterSetupView::picker(&deepseek_with_openrouter_key(true), Locale::En);
1101 let presets: Vec<RouterPreset> = view.rows.iter().map(|row| row.preset).collect();
1102 let fast_idx = presets
1103 .iter()
1104 .position(|preset| *preset == RouterPreset::Fast)
1105 .expect("fast preset");
1106 let typesafe_idx = presets
1107 .iter()
1108 .position(|preset| *preset == RouterPreset::Jev(Some(DecisionRouterRoute::Typesafe)))
1109 .expect("typesafe preset");
1110 assert!(
1111 fast_idx < typesafe_idx,
1112 "runnable Fast tier must appear above paused Jev · TypeSafe: {presets:?}"
1113 );
1114 }
1115 }
1116
1116 lines RUST