Skip to main content

agentmux_srv_core/identity/
account_numbering.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Numbers for accounts that share a provider and an email
4//! (`docs/specs/SPEC_ACCOUNT_SWITCH_FROM_THE_COMPOSER_NO_BIND_2026_10_26.md` §3.3).
5//!
6//! Two Claude sign-ins of one address both show `user@example.com`. Each gets a
7//! number, kept in `context.seq` and never reused, so `·2` stays `·2` when
8//! `·1` is deleted and across restarts. The number shows only while two or more
9//! accounts share the key; a lone account shows its bare name.
10
11use std::collections::HashMap;
12
13use crate::backend::storage::identities::IdentityAccount;
14
15/// The provider and (case-folded) email two accounts must share to be numbered
16/// together. `None` without an email: nothing to tell apart.
17fn 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/// One account's numbering to write: its number (`None`: it keeps the one it has)
38/// and the highest number its group has handed out.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct NumberingUpdate {
41    pub id: String,
42    pub seq: Option<u32>,
43    pub high: u32,
44}
45
46/// The numbering to write. Each account with an email and no number gets the
47/// group's highest number ever handed out plus one, oldest first (creation time,
48/// then id), so an existing group is numbered in the order its accounts were made.
49/// "Ever": every member records the group's high-water mark (`seqmax`), so deleting
50/// the account that held the highest number doesn't free it for the next sign-in.
51pub 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
78/// `a`'s name for a person: `label` with ` ·N` after it while another account
79/// shares its provider and email. `all` is every account that could be shown
80/// beside it.
81pub 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
91/// How many of `all` share `a`'s provider and email, `a` included; 1 without an email.
92fn 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
99/// Whether two emails are the same group's: equal ignoring case and padding.
100pub fn same_email(a: &str, b: &str) -> bool {
101    a.trim().to_lowercase() == b.trim().to_lowercase()
102}
103
104/// An account is written again with a `context` that doesn't carry what the
105/// stored one had: a re-login that rebuilds it as `{ "email": .. }`, or a client
106/// holding a copy from before numbering. Keep the stored number when the new
107/// context has none and names the same address (or none: the email backfill
108/// settles that on the next list, and drops the number if it really changed).
109pub 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        // Another address is another group: the numbering the incoming context carries
121        // (a reconnect clones the old context and replaces only the email) is the old group's.
122        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    // The high-water mark only ever rises: a copy of the account from before another
138    // sign-in was numbered and deleted must not lower it.
139    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
145/// Whether `wanted` (an id, name, display name, email, or `email ·N`) names `a`.
146/// A bare email that more than one account in `all` carries names none of them:
147/// the caller reports the candidates instead of taking the first.
148pub 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    // The names a person sees for it: the display name, the email, the account name;
153    // `label ·N` while it shares them with another account.
154    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    // A number once advertised keeps naming its account after a sibling is deleted, when
160    // the label no longer shows it.
161    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    // A bare email its group shares, or a display name two accounts carry, names none of
167    // them, numbered or not yet: by the group, not by the number, which an account not
168    // listed yet doesn't have. A display name only one carries still names it.
169    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
175/// `user@example.com 2` and `user@example.com·2` read as `user@example.com ·2`.
176fn 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        // `·1` was deleted: the survivor stays `·2`, the next sign-in is `·3`.
227        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        // The highest number is deleted: the next sign-in doesn't get it again.
231        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        // A reconnect that replaced only the email on a clone of the old context drops the old numbering.
252        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        // A stale copy of an account can't lower the group's high-water mark.
259        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        // A display name is advertised as `Work ·2` when the pair shares it; that must be accepted.
284        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}