返回 CodeWhale
naming.rs
根目录 / crates / tui / src / tools / subagent / naming.rs
1 //! Whale nickname pools and locale-aware display-name helpers for sub-agents.
2
3 /// Whale species used as friendly names for sub-agents in the UI. The full
4 /// Cetacea infraorder — baleen whales (Mysticeti), toothed whales
5 /// (Odontoceti), plus select dolphin species (family Delphinidae) that
6 /// don't conflate with existing agent type labels. Porpoises (Phocoenidae)
7 /// are excluded because their name doesn't carry well as a friendly label.
8 ///
9 /// English and Simplified-Chinese names are stored as adjacent pairs. Name
10 /// selection follows the active session locale; it never mixes languages in
11 /// one session. Smaller curated pools below cover every other shipped locale.
12 ///
13 /// Taxonomy source: Society for Marine Mammalogy (2025).
14 pub const WHALE_NICKNAMES: &[&str] = &[
15 "Blue",
16 "蓝鲸",
17 "Humpback",
18 "座头鲸",
19 "Sperm",
20 "抹香鲸",
21 "Fin",
22 "长须鲸",
23 "Sei",
24 "塞鲸",
25 "Bryde's",
26 "布氏鲸",
27 "Minke",
28 "小须鲸",
29 "Antarctic Minke",
30 "南极小须鲸",
31 "Pygmy Right",
32 "小露脊鲸",
33 "Omura's",
34 "大村鲸",
35 "Eden's",
36 "艾氏鲸",
37 "Rice's",
38 "赖斯鲸",
39 "Gray",
40 "灰鲸",
41 "Bowhead",
42 "弓头鲸",
43 "North Atlantic Right",
44 "北大西洋露脊鲸",
45 "North Pacific Right",
46 "北太平洋露脊鲸",
47 "Southern Right",
48 "南露脊鲸",
49 "Beluga",
50 "白鲸",
51 "Narwhal",
52 "独角鲸",
53 "Orca",
54 "虎鲸",
55 "Pilot",
56 "领航鲸",
57 "False Killer",
58 "伪虎鲸",
59 "Pygmy Killer",
60 "小虎鲸",
61 "Melon-headed",
62 "瓜头鲸",
63 "Beaked",
64 "喙鲸",
65 "Cuvier's Beaked",
66 "柯氏喙鲸",
67 "Baird's Beaked",
68 "贝氏喙鲸",
69 "Blainville's Beaked",
70 "柏氏喙鲸",
71 "Ginkgo-toothed Beaked",
72 "银杏齿喙鲸",
73 "Strap-toothed",
74 "带齿喙鲸",
75 "Stejneger's Beaked",
76 "斯氏喙鲸",
77 "Dwarf Sperm",
78 "小抹香鲸",
79 "Pygmy Sperm",
80 "侏儒抹香鲸",
81 "Rough-toothed",
82 "糙齿海豚",
83 "Atlantic Spotted",
84 "大西洋斑海豚",
85 "Pantropical Spotted",
86 "热带斑海豚",
87 "Spinner",
88 "长吻飞旋海豚",
89 "Clymene",
90 "短吻飞旋海豚",
91 "Striped",
92 "条纹海豚",
93 "Common Bottlenose",
94 "宽吻海豚",
95 "Indo-Pacific Bottlenose",
96 "印太瓶鼻海豚",
97 "Risso's",
98 "灰海豚",
99 "Commerson's",
100 "花斑海豚",
101 "Chilean",
102 "智利海豚",
103 "Heaviside's",
104 "海氏矮海豚",
105 "Hector's",
106 "赫氏矮海豚",
107 "Amazon River",
108 "亚马逊河豚",
109 "Ganges River",
110 "恒河豚",
111 "Indus River",
112 "印度河豚",
113 "La Plata",
114 "拉普拉塔河豚",
115 "Franciscana",
116 "拉河豚",
117 ];
118
119 pub(super) const WHALE_NICKNAMES_JA: &[&str] = &[
120 "シロナガスクジラ",
121 "ザトウクジラ",
122 "マッコウクジラ",
123 "ナガスクジラ",
124 "イワシクジラ",
125 "ミンククジラ",
126 "コククジラ",
127 "ホッキョククジラ",
128 "シロイルカ",
129 "イッカク",
130 "シャチ",
131 "ゴンドウクジラ",
132 ];
133
134 pub(super) const WHALE_NICKNAMES_ZH_HANT: &[&str] = &[
135 "藍鯨",
136 "座頭鯨",
137 "抹香鯨",
138 "長鬚鯨",
139 "塞鯨",
140 "布氏鯨",
141 "小鬚鯨",
142 "灰鯨",
143 "弓頭鯨",
144 "白鯨",
145 "獨角鯨",
146 "虎鯨",
147 ];
148
149 pub(super) const WHALE_NICKNAMES_PT_BR: &[&str] = &[
150 "Azul",
151 "Jubarte",
152 "Cachalote",
153 "Baleia-fin",
154 "Baleia-sei",
155 "Baleia-de-bryde",
156 "Baleia-minke",
157 "Cinzenta",
158 "Baleia-franca",
159 "Beluga",
160 "Narval",
161 "Orca",
162 ];
163
164 pub(super) const WHALE_NICKNAMES_ES_419: &[&str] = &[
165 "Azul",
166 "Jorobada",
167 "Cachalote",
168 "Rorcual común",
169 "Rorcual sei",
170 "Rorcual de Bryde",
171 "Rorcual aliblanco",
172 "Gris",
173 "Ballena franca",
174 "Beluga",
175 "Narval",
176 "Orca",
177 ];
178
179 pub(super) const WHALE_NICKNAMES_VI: &[&str] = &[
180 "Cá voi xanh",
181 "Cá voi lưng gù",
182 "Cá nhà táng",
183 "Cá voi vây",
184 "Cá voi Sei",
185 "Cá voi Bryde",
186 "Cá voi Minke",
187 "Cá voi xám",
188 "Cá voi đầu cong",
189 "Cá voi trắng",
190 "Kỳ lân biển",
191 "Cá voi sát thủ",
192 ];
193
194 pub(super) const WHALE_NICKNAMES_KO: &[&str] = &[
195 "대왕고래",
196 "혹등고래",
197 "향유고래",
198 "참고래",
199 "보리고래",
200 "브라이드고래",
201 "밍크고래",
202 "귀신고래",
203 "북극고래",
204 "흰고래",
205 "외뿔고래",
206 "범고래",
207 ];
208
209 pub(super) const WHALE_NICKNAMES_CA: &[&str] = &[
210 "Balena blava",
211 "Balena geperuda",
212 "Catxalot",
213 "Rorcual comú",
214 "Rorcual boreal",
215 "Balena minke",
216 "Balena franca",
217 "Balena de Groenlàndia",
218 "Beluga",
219 "Narval",
220 "Orca",
221 "Calderó",
222 ];
223
224 pub(super) const WHALE_NICKNAMES_DE: &[&str] = &[
225 "Blauwal",
226 "Buckelwal",
227 "Pottwal",
228 "Finnwal",
229 "Seiwal",
230 "Zwergwal",
231 "Glattwal",
232 "Grönlandwal",
233 "Beluga",
234 "Narwal",
235 "Orca",
236 "Pilotwal",
237 ];
238
239 pub(super) const WHALE_NICKNAMES_FR: &[&str] = &[
240 "Baleine bleue",
241 "Baleine à bosse",
242 "Cachalot",
243 "Rorqual commun",
244 "Rorqual boréal",
245 "Petit rorqual",
246 "Baleine franche",
247 "Baleine boréale",
248 "Béluga",
249 "Narval",
250 "Orque",
251 "Globicéphale",
252 ];
253
254 pub(super) const WHALE_NICKNAMES_ID: &[&str] = &[
255 "Paus biru",
256 "Paus bungkuk",
257 "Paus sperma",
258 "Paus sirip",
259 "Paus sei",
260 "Paus minke",
261 "Paus sikat",
262 "Paus bowhead",
263 "Beluga",
264 "Narwal",
265 "Orca",
266 "Paus pilot",
267 ];
268
269 pub(super) const WHALE_NICKNAMES_HI: &[&str] = &[
270 "नीली व्हेल",
271 "कूबड़ व्हेल",
272 "स्पर्म व्हेल",
273 "फिन व्हेल",
274 "सेई व्हेल",
275 "मिंक व्हेल",
276 "राइट व्हेल",
277 "बोहेड व्हेल",
278 "बेलुगा",
279 "नार्व्हल",
280 "ओर्का",
281 "पायलट व्हेल",
282 ];
283
284 pub(super) const WHALE_NICKNAMES_RU: &[&str] = &[
285 "Синий кит",
286 "Горбатый кит",
287 "Кашалот",
288 "Финвал",
289 "Сейвал",
290 "Малый полосатик",
291 "Гладкий кит",
292 "Гренландский кит",
293 "Белуха",
294 "Нарвал",
295 "Косатка",
296 "Гринда",
297 ];
298
299 pub(super) const WHALE_NICKNAMES_UK: &[&str] = &[
300 "Синій кит",
301 "Горбатий кит",
302 "Кашалот",
303 "Фінвал",
304 "Сейвал",
305 "Малий смугач",
306 "Гладкий кит",
307 "Гренландський кит",
308 "Белуга",
309 "Нарвал",
310 "Косатка",
311 "Гринда",
312 ];
313
314 /// Return a deterministic whale name in the active UI locale.
315 #[must_use]
316 pub fn whale_name_for_id_in_locale(id: &str, locale_tag: &str) -> String {
317 use std::hash::{Hash, Hasher};
318 let mut hasher = std::collections::hash_map::DefaultHasher::new();
319 id.hash(&mut hasher);
320 let hash = hasher.finish() as usize;
321 let normalized = locale_tag.trim().to_ascii_lowercase();
322
323 let localized_pool = match normalized.as_str() {
324 "ja" => Some(WHALE_NICKNAMES_JA),
325 "zh-hant" => Some(WHALE_NICKNAMES_ZH_HANT),
326 "pt-br" => Some(WHALE_NICKNAMES_PT_BR),
327 "es-419" => Some(WHALE_NICKNAMES_ES_419),
328 "vi" => Some(WHALE_NICKNAMES_VI),
329 "ko" => Some(WHALE_NICKNAMES_KO),
330 "ca" => Some(WHALE_NICKNAMES_CA),
331 "de" => Some(WHALE_NICKNAMES_DE),
332 "fr" => Some(WHALE_NICKNAMES_FR),
333 "id" => Some(WHALE_NICKNAMES_ID),
334 "hi" => Some(WHALE_NICKNAMES_HI),
335 "ru" => Some(WHALE_NICKNAMES_RU),
336 "uk" => Some(WHALE_NICKNAMES_UK),
337 _ => None,
338 };
339 if let Some(pool) = localized_pool {
340 return pool[hash % pool.len()].to_string();
341 }
342
343 debug_assert_eq!(WHALE_NICKNAMES.len() % 2, 0);
344 let pair_count = WHALE_NICKNAMES.len() / 2;
345 let pair = hash % pair_count;
346 let language_offset = usize::from(normalized == "zh-hans");
347 let idx = pair * 2 + language_offset;
348 WHALE_NICKNAMES[idx].to_string()
349 }
350
351 /// Assign a unique locale-matched whale name for an agent ID.
352 /// If the deterministic name is taken, appends a numeric suffix (for example,
353 /// `Orca (2)`).
354 #[must_use]
355 pub fn assign_unique_whale_name_in_locale(
356 id: &str,
357 active_names: &std::collections::HashSet<String>,
358 locale_tag: &str,
359 ) -> String {
360 let base = whale_name_for_id_in_locale(id, locale_tag);
361 if !active_names.contains(&base) {
362 return base;
363 }
364 // Deterministic suffix from the same hash to keep it stable
365 use std::hash::{Hash, Hasher};
366 let mut hasher = std::collections::hash_map::DefaultHasher::new();
367 id.hash(&mut hasher);
368 let suffix_seed = hasher.finish();
369 for i in 2.. {
370 let candidate = format!("{base} ({i})");
371 if !active_names.contains(&candidate) {
372 return candidate;
373 }
374 // Vary the probe using the seed
375 let probe = (suffix_seed.wrapping_add(i as u64)) % 100;
376 let candidate2 = format!("{base} ({probe})");
377 if !active_names.contains(&candidate2) {
378 return candidate2;
379 }
380 }
381 // Fallback (should never reach here)
382 format!("{base} ({})", id.get(..4).unwrap_or("?"))
383 }
384
385 /// Return the unsuffixed whale label when `name` could have been generated for
386 /// this exact agent id in a shipped locale. Numeric collision suffixes are
387 /// presentation-only and do not make the label user-authored.
388 pub(super) fn generated_whale_name_base<'a>(agent_id: &str, name: &'a str) -> Option<&'a str> {
389 let name = name.trim();
390 if name.is_empty() {
391 return None;
392 }
393 let base = name
394 .rsplit_once(" (")
395 .and_then(|(base, suffix)| {
396 suffix
397 .strip_suffix(')')
398 .filter(|number| !number.is_empty() && number.chars().all(|ch| ch.is_ascii_digit()))
399 .map(|_| base)
400 })
401 .unwrap_or(name);
402
403 // With no persisted provenance bit, the narrowest truthful test is whether
404 // this exact agent id could have generated the label in a shipped locale.
405 // A user-authored label that happens to be a whale word for some other id
406 // remains explicit. An exact deterministic match is inherently ambiguous
407 // and stays classified as generated for backward compatibility.
408 crate::localization::Locale::shipped()
409 .iter()
410 .any(|locale| whale_name_for_id_in_locale(agent_id, locale.tag()) == base)
411 .then_some(base)
412 }
413
414 /// Derive the generated whale labels shown for a set of workers from their
415 /// locale-neutral ids and the active UI language.
416 ///
417 /// Persisted `nickname` values predate locale-scoped naming and may contain a
418 /// whale label chosen under another language. Those generated values are
419 /// deliberately ignored here. A nickname that this agent id could not have
420 /// generated is an explicit custom label and remains intact, even when it is a
421 /// whale word from a built-in pool.
422 #[must_use]
423 pub(crate) fn localized_whale_display_names<'a>(
424 agents: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
425 locale_tag: &str,
426 ) -> std::collections::HashMap<String, String> {
427 let mut by_id = std::collections::BTreeMap::<String, Option<String>>::new();
428 for (agent_id, nickname) in agents {
429 if agent_id.trim().is_empty() {
430 continue;
431 }
432 let nickname = nickname
433 .map(str::trim)
434 .filter(|name| !name.is_empty())
435 .map(str::to_string);
436 by_id
437 .entry(agent_id.to_string())
438 .and_modify(|existing| {
439 if existing.is_none() && nickname.is_some() {
440 *existing = nickname.clone();
441 }
442 })
443 .or_insert(nickname);
444 }
445
446 let mut names = std::collections::HashMap::with_capacity(by_id.len());
447 let mut active_names = std::collections::HashSet::new();
448
449 // Reserve explicit labels first so generated names never shadow them.
450 for (agent_id, nickname) in &by_id {
451 let Some(nickname) = nickname
452 .as_deref()
453 .filter(|name| generated_whale_name_base(agent_id, name).is_none())
454 else {
455 continue;
456 };
457 active_names.insert(nickname.to_string());
458 names.insert(agent_id.clone(), nickname.to_string());
459 }
460
461 // BTreeMap iteration makes collision suffix ownership stable even when
462 // manager/progress event order changes between frames or session loads.
463 for agent_id in by_id.keys() {
464 if names.contains_key(agent_id) {
465 continue;
466 }
467 let name = assign_unique_whale_name_in_locale(agent_id, &active_names, locale_tag);
468 active_names.insert(name.clone());
469 names.insert(agent_id.clone(), name);
470 }
471
472 names
473 }
474
474 lines RUST