1use std::collections::HashMap;
12
13use crate::backend::storage::identities::IdentityAccount;
14
15fn group_key(a: &IdentityAccount) -> Option<(String, String)> {
18 let email = a.context.get("email")?.as_str()?.trim().to_lowercase();
19 if email.is_empty() {
20 return None;
21 }
22 let provider = match crate::backend::providers::resolve_provider_alias(&a.provider) {
23 "" => a.provider.to_lowercase(),
24 c => c.to_string(),
25 };
26 Some((provider, email))
27}
28
29fn seq_of(a: &IdentityAccount) -> Option<u32> {
30 a.context.get("seq")?.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|n| *n > 0)
31}
32
33fn high_of(a: &IdentityAccount) -> u32 {
34 a.context.get("seqmax").and_then(|n| n.as_u64()).and_then(|n| u32::try_from(n).ok()).unwrap_or(0)
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct NumberingUpdate {
41 pub id: String,
42 pub seq: Option<u32>,
43 pub high: u32,
44}
45
46pub fn numbering_updates(accounts: &[IdentityAccount]) -> Vec<NumberingUpdate> {
52 let mut groups: HashMap<(String, String), Vec<&IdentityAccount>> = HashMap::new();
53 for a in accounts {
54 if let Some(k) = group_key(a) {
55 groups.entry(k).or_default().push(a);
56 }
57 }
58 let mut out = Vec::new();
59 for members in groups.values_mut() {
60 let base = members.iter().map(|a| seq_of(a).unwrap_or(0).max(high_of(a))).max().unwrap_or(0);
61 members.sort_by(|a, b| (a.created_at, &a.id).cmp(&(b.created_at, &b.id)));
62 let mut next = base;
63 let mut assigned = HashMap::new();
64 for a in members.iter().filter(|a| seq_of(a).is_none()) {
65 next += 1;
66 assigned.insert(a.id.clone(), next);
67 }
68 for a in members.iter() {
69 let seq = assigned.get(&a.id).copied();
70 if seq.is_some() || high_of(a) != next {
71 out.push(NumberingUpdate { id: a.id.clone(), seq, high: next });
72 }
73 }
74 }
75 out
76}
77
78pub fn numbered_label(a: &IdentityAccount, label: &str, all: &[IdentityAccount]) -> String {
82 let (Some(_), Some(n)) = (group_key(a), seq_of(a)) else {
83 return label.to_string();
84 };
85 if group_size(a, all) < 2 {
86 return label.to_string();
87 }
88 format!("{label} \u{b7}{n}")
89}
90
91fn group_size(a: &IdentityAccount, all: &[IdentityAccount]) -> usize {
93 match group_key(a) {
94 Some(key) => all.iter().filter(|o| group_key(o).as_ref() == Some(&key)).count(),
95 None => 1,
96 }
97}
98
99pub fn same_email(a: &str, b: &str) -> bool {
101 a.trim().to_lowercase() == b.trim().to_lowercase()
102}
103
104pub fn carry_over(stored: &serde_json::Value, incoming: &mut serde_json::Value) {
110 let positive = |v: Option<&serde_json::Value>| v.and_then(|n| n.as_u64()).filter(|n| *n > 0);
111 let (stored_seq, stored_high) = (positive(stored.get("seq")), positive(stored.get("seqmax")));
112 if stored_seq.is_none() && stored_high.is_none() {
113 return;
114 }
115 if !incoming.is_object() {
116 *incoming = serde_json::json!({});
117 }
118 let stored_email = stored.get("email").and_then(|e| e.as_str()).unwrap_or("");
119 match incoming.get("email").and_then(|e| e.as_str()).filter(|e| !e.trim().is_empty()) {
120 Some(email) if !same_email(email, stored_email) => {
123 if let Some(ctx) = incoming.as_object_mut() {
124 ctx.remove("seq");
125 ctx.remove("seqmax");
126 }
127 return;
128 }
129 Some(_) => {}
130 None => incoming["email"] = serde_json::json!(stored_email),
131 }
132 if positive(incoming.get("seq")).is_none() {
133 if let Some(seq) = stored_seq {
134 incoming["seq"] = serde_json::json!(seq);
135 }
136 }
137 let high = [stored_high, stored_seq, positive(incoming.get("seqmax"))].into_iter().flatten().max();
140 if let Some(high) = high {
141 incoming["seqmax"] = serde_json::json!(high);
142 }
143}
144
145pub fn names(a: &IdentityAccount, wanted: &str, all: &[IdentityAccount]) -> bool {
149 let wanted = wanted.trim();
150 let email = a.context.get("email").and_then(|e| e.as_str()).unwrap_or("");
151 let shared = group_size(a, all) >= 2;
152 let labels = [a.display_name.as_str(), email, a.name.as_str()];
155 let spoken = normalize_dot(wanted);
156 if labels.iter().any(|l| !l.is_empty() && numbered_label(a, l, all) != *l && numbered_label(a, l, all).eq_ignore_ascii_case(&spoken)) {
157 return true;
158 }
159 if let Some(n) = seq_of(a).filter(|_| group_key(a).is_some()) {
162 if labels.iter().any(|l| !l.is_empty() && format!("{l} \u{b7}{n}").eq_ignore_ascii_case(&spoken)) {
163 return true;
164 }
165 }
166 let same_display = |o: &IdentityAccount| !o.display_name.is_empty() && o.display_name.eq_ignore_ascii_case(wanted);
170 let bare_is_ambiguous = (shared && !email.is_empty() && email.eq_ignore_ascii_case(wanted))
171 || (same_display(a) && all.iter().filter(|o| same_display(o)).count() >= 2);
172 !bare_is_ambiguous && [a.id.as_str(), a.name.as_str(), a.display_name.as_str(), email].into_iter().any(|l| !l.is_empty() && l.eq_ignore_ascii_case(wanted))
173}
174
175fn normalize_dot(wanted: &str) -> String {
177 let spaced = wanted.replace('\u{b7}', " \u{b7}");
178 let mut parts = spaced.split_whitespace();
179 if let (Some(email), Some(rest), None) = (parts.next(), parts.next(), parts.next()) {
180 let n = rest.trim_start_matches('\u{b7}');
181 if !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()) {
182 return format!("{email} \u{b7}{n}");
183 }
184 }
185 wanted.to_string()
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191 use crate::backend::storage::identities::SecretRef;
192
193 fn acct(id: &str, email: &str, seq: Option<u32>, created_at: i64) -> IdentityAccount {
194 let mut context = serde_json::json!({ "email": email });
195 if let Some(n) = seq {
196 context["seq"] = serde_json::json!(n);
197 }
198 IdentityAccount {
199 id: id.into(),
200 name: "claude-oauth".into(),
201 provider: "claude".into(),
202 kind: "oauth".into(),
203 display_name: String::new(),
204 secret_ref: SecretRef::OAuthConfigDir { dir: format!("/d/{id}") },
205 context,
206 status: "valid".into(),
207 created_at,
208 updated_at: created_at,
209 }
210 }
211
212 #[test]
213 fn an_existing_group_is_numbered_oldest_first() {
214 let all = [acct("b", "Me@Example.com", None, 20), acct("a", "me@example.com", None, 10), acct("c", "other@example.com", None, 5)];
215 let mut got: Vec<(String, Option<u32>, u32)> = numbering_updates(&all).into_iter().map(|u| (u.id, u.seq, u.high)).collect();
216 got.sort();
217 assert_eq!(
218 got,
219 [("a".to_string(), Some(1), 2), ("b".to_string(), Some(2), 2), ("c".to_string(), Some(1), 1)],
220 "case-folded group, oldest first; every member records the group's high-water mark"
221 );
222 }
223
224 #[test]
225 fn a_number_is_never_reused_and_shows_only_beside_a_sibling() {
226 let survivor = acct("b", "me@example.com", Some(2), 20);
228 let all = [survivor.clone(), acct("d", "me@example.com", None, 30)];
229 assert_eq!(numbering_updates(&all).into_iter().find(|u| u.id == "d").and_then(|u| u.seq), Some(3));
230 let mut one = acct("a", "me@example.com", Some(1), 10);
232 one.context["seqmax"] = serde_json::json!(2);
233 let updates = numbering_updates(&[one, acct("e", "me@example.com", None, 40)]);
234 assert_eq!(updates.iter().find(|u| u.id == "e").and_then(|u| u.seq), Some(3), "{updates:?}");
235 assert_eq!(numbered_label(&survivor, "me@example.com", &[survivor.clone()]), "me@example.com", "alone again: bare");
236 assert_eq!(numbered_label(&survivor, "me@example.com", &all), "me@example.com \u{b7}2");
237 }
238
239 #[test]
240 fn a_rewrite_of_the_context_keeps_the_stored_number_unless_the_address_changed() {
241 let stored = serde_json::json!({ "email": "me@example.com", "seq": 2 });
242 let mut rebuilt = serde_json::json!({ "email": "Me@Example.com" });
243 carry_over(&stored, &mut rebuilt);
244 assert_eq!(rebuilt["seq"], 2, "a re-login of the same address keeps it");
245 let mut empty = serde_json::json!({});
246 carry_over(&stored, &mut empty);
247 assert_eq!((empty["seq"].clone(), empty["email"].clone()), (serde_json::json!(2), serde_json::json!("me@example.com")), "a context with no email keeps both");
248 let mut other = serde_json::json!({ "email": "else@example.com" });
249 carry_over(&stored, &mut other);
250 assert!(other.get("seq").is_none(), "another address is another group");
251 let mut cloned = serde_json::json!({ "email": "else@example.com", "seq": 2, "seqmax": 4 });
253 carry_over(&stored, &mut cloned);
254 assert!(cloned.get("seq").is_none() && cloned.get("seqmax").is_none(), "{cloned}");
255 let mut given = serde_json::json!({ "email": "me@example.com", "seq": 5 });
256 carry_over(&stored, &mut given);
257 assert_eq!(given["seq"], 5, "an explicit number stands");
258 let stored = serde_json::json!({ "email": "me@example.com", "seq": 1, "seqmax": 3 });
260 let mut stale = serde_json::json!({ "email": "me@example.com", "seq": 1, "seqmax": 1 });
261 carry_over(&stored, &mut stale);
262 assert_eq!(stale["seqmax"], 3);
263 }
264
265 #[test]
266 fn a_different_provider_or_email_is_another_group() {
267 let mut codex = acct("x", "me@example.com", Some(1), 1);
268 codex.provider = "codex".into();
269 let all = [acct("a", "me@example.com", Some(1), 1), codex];
270 assert_eq!(numbered_label(&all[0], "me@example.com", &all), "me@example.com");
271 assert!(numbering_updates(&[acct("n", "", None, 1)]).is_empty(), "no email, nothing to number");
272 }
273
274 #[test]
275 fn a_bare_email_shared_by_two_accounts_names_neither_but_the_numbered_form_names_one() {
276 let all = [acct("a", "me@example.com", Some(1), 1), acct("b", "me@example.com", Some(2), 2)];
277 assert!(!names(&all[0], "me@example.com", &all) && !names(&all[1], "me@example.com", &all));
278 assert!(names(&all[1], "me@example.com \u{b7}2", &all) && !names(&all[0], "me@example.com \u{b7}2", &all));
279 assert!(names(&all[1], "me@example.com 2", &all), "the dot is optional when typing");
280 assert!(names(&all[0], "a", &all), "the id still names it");
281 let unlisted = [acct("a", "me@example.com", None, 1), acct("b", "me@example.com", None, 2)];
282 assert!(!names(&unlisted[0], "me@example.com", &unlisted), "ambiguous before either has a number");
283 let mut work = [acct("a", "me@example.com", Some(1), 1), acct("b", "me@example.com", Some(2), 2)];
285 for w in &mut work {
286 w.display_name = "Work".into();
287 }
288 assert!(names(&work[1], "Work \u{b7}2", &work) && !names(&work[0], "Work \u{b7}2", &work));
289 assert!(!names(&work[0], "Work", &work) && !names(&work[1], "Work", &work), "a bare shared display name names neither");
290 work[0].display_name = "Personal".into();
291 assert!(names(&work[0], "Personal", &work) && names(&work[1], "Work", &work), "a display name only one carries still names it");
292 let lone = [acct("a", "me@example.com", Some(1), 1)];
293 let survivor = [acct("b", "me@example.com", Some(2), 2)];
294 assert!(names(&survivor[0], "me@example.com \u{b7}2", &survivor), "a number advertised before its sibling went still names it");
295 assert!(!names(&survivor[0], "me@example.com \u{b7}1", &survivor));
296 assert!(names(&lone[0], "ME@example.com", &lone), "a lone account answers to its email");
297 }
298}