返回 CodeWhale
format_helpers.rs
根目录 / crates / tui / src / tui / format_helpers.rs
1 //! Small string builders that compose status-bar / footer chips and
2 //! one-off informational messages.
3 //!
4 //! Each helper is a pure function over a small slice of `App` or
5 //! response data. Grouped here so the composer/footer renderer doesn't
6 //! need to scroll past their bodies, and so the labels can be unit
7 //! tested in isolation.
8
9 use codewhale_localization::{Locale, MessageId, tr};
10 use codewhale_models::{ToolProjectionWarning, Usage};
11
12 pub(super) fn tool_projection_warning(
13 locale: Locale,
14 provider: &str,
15 omitted_tool_names: &[String],
16 omitted_tool_count: usize,
17 ) -> String {
18 let tools = codewhale_engine::core::events::tool_projection_warning_tool_list(
19 omitted_tool_names,
20 omitted_tool_count,
21 );
22 tr(locale, MessageId::ToolProjectionWarning)
23 .replace("{provider}", provider)
24 .replace("{tools}", &tools)
25 }
26
27 /// Build the multi-line "Cache warmup complete: …" status message
28 /// shown after a prefix-cache warmup turn finishes. Handles all four
29 /// combinations of `prompt_cache_hit_tokens` / `prompt_cache_miss_tokens`
30 /// being present or absent so we never report "0% cache hit" for an
31 /// API call that didn't surface telemetry at all.
32 pub(super) fn cache_warmup_result(
33 locale: Locale,
34 usage: &Usage,
35 warning: Option<&ToolProjectionWarning>,
36 ) -> String {
37 let cache = match (
38 usage.prompt_cache_hit_tokens,
39 usage.prompt_cache_miss_tokens,
40 ) {
41 (Some(hit), Some(miss)) => format!("Cache warmup complete: hit {hit} | miss {miss}"),
42 (Some(hit), None) => format!("Cache warmup complete: hit {hit} | miss unavailable"),
43 (None, Some(miss)) => format!("Cache warmup complete: hit unavailable | miss {miss}"),
44 (None, None) => "Cache warmup complete: cache telemetry unavailable".to_string(),
45 };
46 let mut message = format!(
47 "{cache}\nNote: the first warmup is usually a miss. Later requests that reuse the same stable prefix may hit the provider cache; a hit is not guaranteed."
48 );
49 if let Some(warning) = warning {
50 message.push('\n');
51 message.push_str(&tool_projection_warning(
52 locale,
53 &warning.provider,
54 &warning.omitted_tool_names,
55 warning.omitted_tool_count,
56 ));
57 }
58 message
59 }
60
61 /// Render the response body for `/models` / `models list` — the current
62 /// model is starred and other available models follow underneath.
63 pub(super) fn available_models_message(
64 locale: codewhale_localization::Locale,
65 current_provider: &str,
66 current_model: &str,
67 models: &[String],
68 fleet: &Result<
69 Vec<codewhale_engine::fleet::members::FleetModel>,
70 codewhale_engine::fleet::store::FleetStoreError,
71 >,
72 ) -> String {
73 let mut lines = Vec::new();
74 // The fleet leads (design §10 F1): what the person added, with the roles
75 // each model fills, before the provider's full list. A selected fleet
76 // that cannot be read is named as such, never shown as "no fleet".
77 match fleet.as_deref() {
78 Err(error) => lines
79 .push(tr(locale, MessageId::FleetModelsBroken).replace("{error}", &error.to_string())),
80 Ok([]) => lines.push(tr(locale, MessageId::FleetModelsEmpty).into_owned()),
81 Ok(fleet) => {
82 lines.push(
83 tr(locale, MessageId::FleetModelsHeader)
84 .replace("{fleet}", &fleet[0].fleet)
85 .replace("{count}", &fleet.len().to_string()),
86 );
87 for member in fleet {
88 // The exact route, not the bare id: two providers may serve
89 // the same model id and only one of them is the current route.
90 let marker = if member.matches(current_provider, current_model) {
91 "*"
92 } else {
93 " "
94 };
95 lines.push(format!(
96 "{marker} {}/{} · {}",
97 member.provider,
98 member.model,
99 member.roles_label()
100 ));
101 }
102 lines.push(String::new());
103 }
104 }
105 lines.push(format!("Available models ({})", models.len()));
106 for model in models {
107 if model == current_model {
108 lines.push(format!("* {model} (current)"));
109 } else {
110 lines.push(format!(" {model}"));
111 }
112 }
113 lines.join("\n")
114 }
115
116 #[cfg(test)]
117 mod tests {
118 use super::*;
119
120 #[test]
121 fn available_models_message_marks_current_model() {
122 let models = vec![
123 "deepseek-v4-pro".to_string(),
124 "deepseek-v4-flash".to_string(),
125 ];
126 let msg = available_models_message(
127 codewhale_localization::Locale::En,
128 "deepseek",
129 "deepseek-v4-pro",
130 &models,
131 &Ok(Vec::new()),
132 );
133 assert!(msg.contains("* deepseek-v4-pro (current)"), "got: {msg}");
134 assert!(msg.contains(" deepseek-v4-flash"), "got: {msg}");
135 assert!(
136 msg.starts_with("Your team is the session model only"),
137 "got: {msg}"
138 );
139 assert!(msg.contains("Available models (2)"), "got: {msg}");
140 }
141
142 /// A selected fleet that cannot be read is reported as an error, not as
143 /// "the session model only".
144 #[test]
145 fn available_models_message_names_a_broken_fleet_selection() {
146 let broken = Err(codewhale_engine::fleet::store::FleetStoreError::NotFound(
147 "selected fleet `Ops`".to_string(),
148 ));
149 let msg = available_models_message(
150 codewhale_localization::Locale::En,
151 "deepseek",
152 "deepseek-v4-pro",
153 &[],
154 &broken,
155 );
156 assert!(
157 msg.starts_with(
158 "Your selected team could not be loaded: fleet file not found: selected fleet `Ops`"
159 ),
160 "got: {msg}"
161 );
162 assert!(!msg.contains("session model only"), "got: {msg}");
163 }
164
165 #[test]
166 fn fleet_current_marker_matches_the_exact_route_not_the_bare_id() {
167 let fleet = vec![
168 codewhale_engine::fleet::members::FleetModel {
169 provider: "openrouter".to_string(),
170 model: "deepseek/deepseek-v4-flash".to_string(),
171 roles: vec!["scout".to_string()],
172 fleet: "Ops".to_string(),
173 },
174 codewhale_engine::fleet::members::FleetModel {
175 provider: "novita".to_string(),
176 model: "deepseek/deepseek-v4-flash".to_string(),
177 roles: Vec::new(),
178 fleet: "Ops".to_string(),
179 },
180 ];
181 let msg = available_models_message(
182 codewhale_localization::Locale::En,
183 "novita",
184 "deepseek/deepseek-v4-flash",
185 &[],
186 &Ok(fleet),
187 );
188 assert!(
189 msg.contains(" openrouter/deepseek/deepseek-v4-flash · explore"),
190 "got: {msg}"
191 );
192 assert!(
193 msg.contains("* novita/deepseek/deepseek-v4-flash · member"),
194 "got: {msg}"
195 );
196 }
197
198 #[test]
199 fn cache_warmup_result_handles_missing_telemetry() {
200 let usage = Usage {
201 prompt_cache_hit_tokens: None,
202 prompt_cache_miss_tokens: None,
203 ..Default::default()
204 };
205 let msg = cache_warmup_result(Locale::En, &usage, None);
206 assert!(msg.contains("cache telemetry unavailable"), "got: {msg}");
207 }
208
209 #[test]
210 fn cache_warmup_result_reports_omitted_tools_once_alongside_usage() {
211 let usage = Usage {
212 prompt_cache_hit_tokens: Some(32),
213 prompt_cache_miss_tokens: Some(8),
214 ..Default::default()
215 };
216 let warning = ToolProjectionWarning {
217 provider: "Moonshot".to_string(),
218 omitted_tool_names: vec!["workspace_check".to_string()],
219 omitted_tool_count: 3,
220 };
221 for locale in [Locale::En, Locale::ZhHans] {
222 let plain = cache_warmup_result(locale, &usage, None);
223 let result = cache_warmup_result(locale, &usage, Some(&warning));
224 let expected_warning = tr(locale, MessageId::ToolProjectionWarning)
225 .replace("{provider}", "Moonshot")
226 .replace("{tools}", "workspace_check, …");
227
228 assert!(plain.contains("hit 32 | miss 8"));
229 assert!(!plain.contains(&expected_warning));
230 assert_eq!(result, format!("{plain}\n{expected_warning}"));
231 }
232 }
233 }
234
234 lines RUST