Skip to main content

agentmux_srv/server/
browser_identity.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which cookie jar a browser tab browses as: its block's `browser:identity`
5//! (docs/specs/SPEC_BROWSER_PANE_PROFILES_MENU_2026_10_09.md §5–§6). Absent
6//! for Personal; `incognito:<jar>` for an in-memory jar of its own, which the
7//! CEF host makes on first use. Set when the tab is opened and never changed:
8//! to browse as someone else, open another tab.
9
10use std::collections::{HashMap, HashSet};
11
12use serde_json::{json, Value};
13
14use crate::backend::browser_profiles_store::BrowserProfile;
15use crate::backend::obj::{Block, MetaMapType};
16use crate::server::AppState;
17
18pub(crate) const IDENTITY_META_KEY: &str = "browser:identity";
19
20/// Most Incognito jars open at once: each is its own Chrome profile with its
21/// own renderer (identities spec §4.3). The host keeps the same cap.
22pub(crate) const MAX_INCOGNITO_JARS: usize = 8;
23
24/// Is `identity` a well-formed Incognito identity?
25pub(crate) fn is_incognito(identity: &str) -> bool {
26    identity
27        .strip_prefix("incognito:")
28        .is_some_and(|jar| (8..=64).contains(&jar.len()) && jar.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-'))
29}
30
31/// The profile id of a `profile:<id>` identity.
32pub(crate) fn profile_id(identity: &str) -> Option<&str> {
33    identity
34        .strip_prefix("profile:")
35        .filter(|id| crate::backend::browser_profiles_store::is_profile_id(id))
36}
37
38/// The ids of the named profiles there are, or `None` when they can't be read.
39pub(crate) fn profile_ids() -> Option<HashSet<String>> {
40    match crate::server::app_api::browser_profiles_list() {
41        Ok(ps) => Some(ps.into_iter().map(|p| p.id).collect()),
42        Err(e) => {
43            tracing::warn!(error = %e, "[browser-identity] couldn't read the browser profiles");
44            None
45        }
46    }
47}
48
49fn identity_of(meta: &MetaMapType) -> Option<&str> {
50    meta.get(IDENTITY_META_KEY).and_then(Value::as_str)
51}
52
53/// Whose sign-ins a pane with `meta` browses with, in words: "personal" (no identity), "incognito" (a jar of
54/// its own) or the named profile. What `OpenBrowser` tells the agent that opened it.
55pub(crate) fn browsing_as(meta: &MetaMapType) -> String {
56    match identity_of(meta) {
57        None => "personal".to_string(),
58        Some(i) if is_incognito(i) => "incognito".to_string(),
59        Some(i) => profile_id(i)
60            .and_then(|id| crate::server::app_api::browser_profiles_list().ok()?.into_iter().find(|p| p.id == id))
61            .map_or_else(|| i.to_string(), |p| format!("profile:{}", p.name)),
62    }
63}
64
65/// The Incognito identities blocks use now: the jars the host must keep.
66/// `None` when the store can't be read: the host then keeps every jar, rather
67/// than taking an empty list as "no tab uses any" and signing them all out.
68pub(crate) fn live_jars(state: &AppState) -> Option<Vec<String>> {
69    let blocks = match state.mstore.get_all::<Block>() {
70        Ok(b) => b,
71        Err(e) => {
72            tracing::warn!(error = %e, "[browser-identity] couldn't list blocks; the host keeps its jars");
73            return None;
74        }
75    };
76    let set: HashSet<String> = blocks
77        .iter()
78        .filter_map(|b| identity_of(&b.meta))
79        .filter(|i| is_incognito(i))
80        .map(str::to_string)
81        .collect();
82    Some(set.into_iter().collect())
83}
84
85/// Check the identity a client gives a new browser tab (`pane.open`): an
86/// Incognito one that is well formed, within the cap unless it shares a jar
87/// already open. Anything else
88/// fails the open rather than quietly browsing in the shared jar.
89pub(crate) fn check_new_tab(state: &AppState, meta: &MetaMapType) -> Result<(), String> {
90    let Some(v) = meta.get(IDENTITY_META_KEY) else { return Ok(()) };
91    let identity = v.as_str().unwrap_or("");
92    if let Some(id) = profile_id(identity) {
93        let known = profile_ids().ok_or("couldn't read the browser profiles")?;
94        return if known.contains(id) { Ok(()) } else { Err(format!("there is no browser profile {id:?}")) };
95    }
96    if !is_incognito(identity) {
97        return Err(format!("{IDENTITY_META_KEY} must be incognito:<id> or profile:<id>"));
98    }
99    let open = live_jars(state).ok_or("couldn't count the Incognito tabs open")?;
100    if !open.iter().any(|j| j == identity) && open.len() >= MAX_INCOGNITO_JARS {
101        return Err(format!(
102            "at most {MAX_INCOGNITO_JARS} Incognito tabs can be open at once: close one to open another"
103        ));
104    }
105    Ok(())
106}
107
108/// A popup pane browses as the tab that opened it: same jar, so a sign-in in
109/// it signs in the tab.
110pub(crate) fn inherit(meta: &mut MetaMapType, opener: &Block) {
111    if let Some(identity) = identity_of(&opener.meta).filter(|i| is_incognito(i) || profile_id(i).is_some()) {
112        meta.insert(IDENTITY_META_KEY.to_string(), json!(identity));
113    }
114}
115
116/// How many more Incognito jars a layout replay may open: the cap less those
117/// open now (none when they can't be counted).
118pub(crate) fn jars_available(state: &AppState) -> usize {
119    live_jars(state).map_or(0, |open| MAX_INCOGNITO_JARS.saturating_sub(open.len()))
120}
121
122/// For a layout being replayed: each Incognito identity becomes a fresh one,
123/// so the replay doesn't share a jar with a tab still open. Tabs that shared
124/// a jar keep sharing one. `fresh` maps old to new across the replay; at most
125/// `available` fresh jars are made. Returns false for a tab that would need
126/// one more: it is left out of the replay, not opened as a blank pane or in
127/// the shared jar.
128pub(crate) fn refresh_for_replay(
129    meta: &mut Value,
130    fresh: &mut HashMap<String, String>,
131    available: usize,
132    profiles: Option<&HashSet<String>>,
133) -> bool {
134    let Some(obj) = meta.as_object_mut() else { return true };
135    // A tab of a profile that no longer exists is left out, not reopened in
136    // a jar the host would make anew under the old id.
137    if let Some(id) = obj.get(IDENTITY_META_KEY).and_then(Value::as_str).and_then(profile_id) {
138        return profiles.is_some_and(|known| known.contains(id));
139    }
140    let Some(old) = obj.get(IDENTITY_META_KEY).and_then(Value::as_str).filter(|i| is_incognito(i)).map(str::to_string) else {
141        return true;
142    };
143    if !fresh.contains_key(&old) && fresh.len() >= available {
144        tracing::info!("[browser-identity] a replayed Incognito tab left out: no jar to spare");
145        return false;
146    }
147    let new = fresh.entry(old).or_insert_with(|| format!("incognito:{}", uuid::Uuid::new_v4())).clone();
148    obj.insert(IDENTITY_META_KEY.to_string(), json!(new));
149    true
150}
151
152/// Who owns an agent's own browser profile: its uid, which a rename keeps, else (an agent srv does not know by
153/// a uid) the name it calls itself.
154pub(crate) fn profile_owner(state: &AppState, agent: &str) -> String {
155    state.reactive_handler.get_agent(agent).and_then(|a| a.uid).unwrap_or_else(|| agent.to_string())
156}
157
158/// May the agent `owner` (see [`profile_owner`]) browse as `p`: its own profile, or one the user lets agents use.
159fn agent_may_use(p: &BrowserProfile, owner: &str) -> bool {
160    p.agents_allowed || p.owner_agent.as_deref() == Some(owner)
161}
162
163/// The identity an agent's `OpenBrowser` asked for by `profile` browses as:
164/// its own profile for nothing, "" or "own" (made by srv before this, see
165/// `app_api::browser_profiles::ensure_agent_profile`); none (Personal) for
166/// "personal"; a fresh Incognito jar for "incognito", always allowed since it gives
167/// the agent less, not more; and a named profile (by name, any case, or id): the
168/// agent's own, or one the user switched on "Agents may use it" for in Settings →
169/// Browser (docs/specs/SPEC_AGENT_OWN_BROWSER_PROFILE_2026_11_04.md).
170pub(crate) fn identity_for_agent(owner: &str, requested: &str, profiles: &[BrowserProfile]) -> Result<Option<String>, String> {
171    let requested = requested.trim();
172    if requested.eq_ignore_ascii_case("personal") {
173        return Ok(None);
174    }
175    if requested.eq_ignore_ascii_case("incognito") {
176        return Ok(Some(format!("incognito:{}", uuid::Uuid::new_v4())));
177    }
178    if requested.is_empty() || requested.eq_ignore_ascii_case("own") {
179        return match profiles.iter().find(|p| p.owner_agent.as_deref() == Some(owner)) {
180            Some(p) => Ok(Some(format!("profile:{}", p.id))),
181            None => Err("your own browser profile couldn't be made (the browser profiles can't be read or written); ask for \"incognito\" meanwhile".to_string()),
182        };
183    }
184    let allowed = || {
185        let names: Vec<&str> = profiles.iter().filter(|p| agent_may_use(p, owner)).map(|p| p.name.as_str()).collect();
186        if names.is_empty() {
187            "none".to_string()
188        } else {
189            names.join(", ")
190        }
191    };
192    // The agent's own profile first, then the user's, then another agent's.
193    let named = |p: &&BrowserProfile| p.name.eq_ignore_ascii_case(requested) || p.id == requested;
194    let found = profiles.iter().filter(named).min_by_key(|p| match p.owner_agent.as_deref() {
195        Some(o) if o == owner => 0,
196        None => 1,
197        Some(_) => 2,
198    });
199    let Some(p) = found else {
200        return Err(format!(
201            "there is no browser profile called {requested:?}. Use \"incognito\", or a profile you may use: {}",
202            allowed()
203        ));
204    };
205    if !agent_may_use(p, owner) {
206        return Err(format!(
207            "the user hasn't let agents use the browser profile {:?}: they can switch on \"Agents may use it\" for it in Settings → Browser. Use \"incognito\", or a profile agents may use: {}",
208            p.name,
209            allowed()
210        ));
211    }
212    Ok(Some(format!("profile:{}", p.id)))
213}
214
215/// What a container agent's `profile` asks for, once its defaults are applied. A container agent exists
216/// to be isolated from the user's own sign-ins, so with nothing asked it gets its own profile, never
217/// Personal; it browses as another named profile only when the user lets agents use that profile
218/// (the check `identity_for_agent` makes for every agent).
219fn requested_by_container(requested: Option<&str>) -> Result<&str, String> {
220    match requested.map(str::trim) {
221        None | Some("") => Ok("own"),
222        Some(r) if r.eq_ignore_ascii_case("personal") => Err(
223            "a container agent doesn't browse as the user's Personal profile: it has its own profile by default, or a profile the user \
224             lets agents use (Settings → Browser → \"Agents may use it\")"
225                .to_string(),
226        ),
227        Some(r) => Ok(r),
228    }
229}
230
231/// Whether `requested` (an `OpenBrowser` `profile`) asks for the agent's own profile, which srv makes the first time.
232pub(crate) fn asks_for_own(agent_id: &str, requested: Option<&str>) -> bool {
233    match requested.map(str::trim) {
234        None | Some("") => true,
235        Some(r) => r.eq_ignore_ascii_case("own") || r.eq_ignore_ascii_case(agent_id),
236    }
237}
238
239/// The `profile` an agent's open is carried out with. With none asked for, the agent browses as its own: made here,
240/// the first time. If it can't be made (the shared folder is given up to an older srv), a fresh Incognito jar, never
241/// the user's Personal.
242pub(crate) async fn requested_or_own(state: &AppState, agent_id: &str, requested: Option<&str>) -> Option<String> {
243    if asks_for_own(agent_id, requested) {
244        let owner = profile_owner(state, agent_id);
245        if let Err(e) = crate::server::app_api::browser_ensure_agent_profile(state, &owner, agent_id).await {
246            tracing::warn!(agent_id = %agent_id, error = %e, "[ui-automation] browser open: no own profile; Incognito instead");
247            return Some("incognito".to_string());
248        }
249    }
250    requested.map(str::to_string)
251}
252
253/// `OpenBrowser`'s `profile`: give the agent's new tab the identity it asked
254/// for, checked like any new tab (the platform, the Incognito cap). With nothing asked, every agent, native
255/// or container, browses as its own profile ([`requested_by_container`] for the container's other rules).
256pub(crate) fn for_agent_open(state: &AppState, meta: &mut MetaMapType, owner: &str, requested: Option<&str>, from_container: bool) -> Result<(), String> {
257    let requested = if from_container { requested_by_container(requested)? } else { requested.unwrap_or("own") };
258    let profiles = crate::server::app_api::browser_profiles_list()?;
259    if let Some(identity) = identity_for_agent(owner, requested, &profiles)? {
260        meta.insert(IDENTITY_META_KEY.to_string(), json!(identity));
261        check_new_tab(state, meta)?;
262    }
263    Ok(())
264}
265
266/// Whether pane `block_id` is a container agent's: whatever key it asks with, what it opens is not the user's own.
267pub(crate) fn in_container(state: &AppState, block_id: &str) -> bool {
268    state.mstore.get::<Block>(block_id).ok().flatten().is_some_and(|b| crate::server::agent_resources::container_of(&b).is_some())
269}
270
271/// A new pane for the agent `(id, allowed sites, profile asked for, from a container)`: owned by it, limited to
272/// its sites, and browsing as the identity it gets ([`for_agent_open`]). Returns whom it browses as, in words.
273pub(crate) fn for_agent_pane(
274    state: &AppState,
275    meta: &mut MetaMapType,
276    (agent_id, allowed, requested, from_container): (&str, Option<&[String]>, Option<&str>, bool),
277) -> Result<String, String> {
278    meta.extend(crate::server::browser_owner::driver_meta(agent_id));
279    crate::server::browser_allowlist::mirror(meta, allowed);
280    let owner = profile_owner(state, agent_id);
281    for_agent_open(state, meta, &owner, requested, from_container)?;
282    // "own": the agent's own profile, which is what an agent should be told apart from the user's.
283    let own = format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(&owner));
284    Ok(if identity_of(meta) == Some(own.as_str()) { "own".to_string() } else { browsing_as(meta) })
285}
286
287/// An agent opening a browser tab some other way (`pane.open`, the HTTP pane
288/// open) with a `browser:identity`: a named profile only if it is the agent's own or agents may use it.
289pub(crate) fn check_agent_may_use(meta: &MetaMapType, owner: &str) -> Result<(), String> {
290    let Some(id) = identity_of(meta).and_then(profile_id) else { return Ok(()) };
291    let profiles = crate::server::app_api::browser_profiles_list()?;
292    match profiles.iter().find(|p| p.id == id) {
293        Some(p) if agent_may_use(p, owner) => Ok(()),
294        Some(p) => Err(format!("the user hasn't let agents use the browser profile {:?}", p.name)),
295        None => Err(format!("there is no browser profile {id:?}")),
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::backend::browser_profiles_store::agent_profile_id;
303
304    fn profile(id: &str, name: &str, agents_allowed: bool) -> BrowserProfile {
305        BrowserProfile { id: id.into(), name: name.into(), color: "#3b82f6".into(), created_at: 0, agents_allowed, owner_agent: None }
306    }
307
308    fn agents_own(agent_id: &str) -> BrowserProfile {
309        BrowserProfile { owner_agent: Some(agent_id.into()), ..profile(&agent_profile_id(agent_id), agent_id, false) }
310    }
311
312    /// A pane asked for as Incognito carries a jar of its own and says so, a new one each time; Personal is not one a
313    /// container agent can ask for. (With nothing asked, the agent's own profile: `an_agent_with_no_profile_...`.)
314    #[tokio::test]
315    async fn a_pane_asked_for_incognito_browses_in_a_jar_of_its_own() {
316        let state = crate::server::tests::test_state();
317        let mut first = MetaMapType::new();
318        assert_eq!(for_agent_pane(&state, &mut first, ("kcont", None, Some("incognito"), true)).unwrap(), "incognito");
319        assert!(identity_of(&first).is_some_and(is_incognito), "{first:?}");
320        let mut other = MetaMapType::new();
321        assert_eq!(for_agent_pane(&state, &mut other, ("lark", None, Some("incognito"), false)).unwrap(), "incognito");
322        assert_ne!(identity_of(&first), identity_of(&other), "each pane gets a jar of its own");
323        let mut asked = MetaMapType::new();
324        assert!(for_agent_pane(&state, &mut asked, ("kcont", None, Some("Personal"), true)).is_err());
325        assert!(identity_of(&asked).is_none());
326    }
327
328    /// With no `profile`, a native and a container agent alike browse as the profile of their own, the same one every
329    /// time, and not as each other's; Personal and Incognito stay what they are asked for.
330    #[test]
331    fn an_agent_with_no_profile_browses_as_its_own_the_same_one_every_time() {
332        let (lark, kcont) = (agents_own("lark"), agents_own("kcont"));
333        let ps = [profile("p-work", "Work", true), lark.clone(), kcont.clone()];
334        let (lark_id, kcont_id) = (agent_profile_id("lark"), agent_profile_id("kcont"));
335        for asked in ["", "  ", "own", "Own", "lark", lark_id.as_str()] {
336            assert_eq!(identity_for_agent("lark", asked, &ps), Ok(Some(format!("profile:{lark_id}"))), "{asked:?}");
337        }
338        assert_eq!(identity_for_agent("kcont", "", &ps), Ok(Some(format!("profile:{kcont_id}"))));
339        assert_eq!(identity_for_agent("lark", "Personal", &ps), Ok(None), "Personal only when asked for");
340        assert_eq!(requested_by_container(None), Ok("own"));
341        // Another agent's profile is not offered, and not resolvable, until the user lets agents use it.
342        let refused = identity_for_agent("lark", "kcont", &ps).unwrap_err();
343        assert!(refused.contains("hasn't let agents use") && refused.contains("lark") && refused.contains("Work"), "{refused}");
344        let shared = BrowserProfile { agents_allowed: true, ..kcont };
345        assert_eq!(identity_for_agent("lark", "kcont", &[lark.clone(), shared]), Ok(Some(format!("profile:{kcont_id}"))));
346        // Its own profile is found before a user's profile of the same name.
347        let clash = profile("p-lark", "lark", true);
348        assert_eq!(identity_for_agent("lark", "lark", &[clash, lark]), Ok(Some(format!("profile:{lark_id}"))));
349        // No profile made yet (the profiles can't be written): it says so rather than browsing as Personal.
350        assert!(identity_for_agent("lark", "", &[profile("p-work", "Work", true)]).unwrap_err().contains("couldn't be made"));
351        assert!(asks_for_own("lark", None) && asks_for_own("lark", Some("Lark")) && !asks_for_own("lark", Some("incognito")));
352    }
353
354    #[test]
355    fn an_agent_may_open_its_own_profile_by_pane_open_and_not_anothers() {
356        // `check_agent_may_use` reads the profile file; the rule it applies is `agent_may_use`.
357        let (mine, theirs) = (agents_own("lark"), agents_own("kcont"));
358        assert!(agent_may_use(&mine, "lark") && !agent_may_use(&theirs, "lark"));
359        assert!(agent_may_use(&BrowserProfile { agents_allowed: true, ..theirs }, "lark"));
360        assert!(!agent_may_use(&profile("p-bank", "Bank", false), "lark"));
361    }
362
363    #[test]
364    fn a_container_agent_browses_in_its_own_jar_unless_a_shared_profile_is_asked_for() {
365        // Nothing asked: its own profile, not the user's Personal profile.
366        assert_eq!(requested_by_container(None), Ok("own"));
367        assert_eq!(requested_by_container(Some("  ")), Ok("own"));
368        // Personal asked for by name is refused, with the way out.
369        let refused = requested_by_container(Some("Personal")).unwrap_err();
370        assert!(refused.contains("its own profile") && refused.contains("Agents may use it"), "{refused}");
371        // A named profile still goes through the usual check, which lets in only shared ones.
372        assert_eq!(requested_by_container(Some("Work")), Ok("Work"));
373        let ps = [profile("p-work", "Work", true), profile("p-bank", "Bank", false)];
374        assert_eq!(identity_for_agent("kcont", "Work", &ps), Ok(Some("profile:p-work".into())));
375        assert!(identity_for_agent("kcont", "Bank", &ps).is_err());
376        // Incognito really is a fresh jar.
377        let jar = identity_for_agent("kcont", "incognito", &ps).unwrap().unwrap();
378        assert!(is_incognito(&jar));
379    }
380
381    #[test]
382    fn an_agent_gets_personal_incognito_or_a_profile_it_is_allowed() {
383        let ps = [profile("p-work", "Work", true), profile("p-bank", "Bank", false)];
384        assert_eq!(identity_for_agent("lark", "Personal", &ps), Ok(None));
385        let a = identity_for_agent("lark", "incognito", &ps).unwrap().unwrap();
386        let b = identity_for_agent("lark", "Incognito", &ps).unwrap().unwrap();
387        assert!(is_incognito(&a) && is_incognito(&b) && a != b, "a fresh jar each time");
388        assert_eq!(identity_for_agent("lark", "work", &ps), Ok(Some("profile:p-work".into())));
389        assert_eq!(identity_for_agent("lark", "p-work", &ps), Ok(Some("profile:p-work".into())));
390        let refused = identity_for_agent("lark", "Bank", &ps).unwrap_err();
391        assert!(refused.contains("hasn't let agents use") && refused.contains("Work"), "{refused}");
392        assert!(refused.contains("\"Agents may use it\" for it in Settings → Browser") && !refused.contains("  "), "{refused}");
393        let unknown = identity_for_agent("lark", "Nope", &ps).unwrap_err();
394        assert!(unknown.contains("no browser profile") && !unknown.contains("Bank"), "{unknown}");
395    }
396
397    #[test]
398    fn only_well_formed_incognito_identities_pass() {
399        assert!(is_incognito("incognito:0f0e2d1c-aaaa-bbbb-cccc-0123456789ab"));
400        for bad in ["incognito:short", "incognito:has spaces x", "profile:work", "incognito:", ""] {
401            assert!(!is_incognito(bad), "{bad:?}");
402        }
403    }
404
405    #[test]
406    fn a_replayed_layout_gets_fresh_jars_and_keeps_shared_ones_shared() {
407        let mut fresh = HashMap::new();
408        let mut a = json!({ "view": "browser", IDENTITY_META_KEY: "incognito:aaaaaaaa-1111" });
409        let mut b = json!({ "view": "browser", IDENTITY_META_KEY: "incognito:aaaaaaaa-1111" });
410        let mut c = json!({ "view": "browser" });
411        assert!(refresh_for_replay(&mut a, &mut fresh, 8, None));
412        assert!(refresh_for_replay(&mut b, &mut fresh, 8, None));
413        assert!(refresh_for_replay(&mut c, &mut fresh, 8, None));
414        let ia = a[IDENTITY_META_KEY].as_str().unwrap();
415        assert_ne!(ia, "incognito:aaaaaaaa-1111");
416        assert!(is_incognito(ia));
417        assert_eq!(a[IDENTITY_META_KEY], b[IDENTITY_META_KEY]);
418        assert!(c.get(IDENTITY_META_KEY).is_none());
419        // Past the jars there are to spare, a tab needing a new one is left out;
420        // one sharing a jar already made still comes.
421        let mut d = json!({ "view": "browser", IDENTITY_META_KEY: "incognito:dddddddd-4444" });
422        assert!(!refresh_for_replay(&mut d, &mut fresh, 1, None));
423        let mut e = json!({ "view": "browser", IDENTITY_META_KEY: "incognito:aaaaaaaa-1111" });
424        assert!(refresh_for_replay(&mut e, &mut fresh, 1, None));
425        // A profile tab comes only while its profile exists, and keeps its id.
426        let known: HashSet<String> = ["p-work".to_string()].into();
427        let mut f = json!({ "view": "browser", IDENTITY_META_KEY: "profile:p-work" });
428        assert!(refresh_for_replay(&mut f, &mut fresh, 0, Some(&known)));
429        assert_eq!(f[IDENTITY_META_KEY], json!("profile:p-work"));
430        let mut g = json!({ "view": "browser", IDENTITY_META_KEY: "profile:p-gone" });
431        assert!(!refresh_for_replay(&mut g, &mut fresh, 0, Some(&known)));
432    }
433
434    #[test]
435    fn a_popup_pane_inherits_an_incognito_jar_only() {
436        let mut opener = Block::default();
437        opener.meta.insert(IDENTITY_META_KEY.into(), json!("incognito:bbbbbbbb-2222"));
438        let mut meta = MetaMapType::new();
439        inherit(&mut meta, &opener);
440        assert_eq!(meta[IDENTITY_META_KEY], json!("incognito:bbbbbbbb-2222"));
441        let mut meta = MetaMapType::new();
442        inherit(&mut meta, &Block::default());
443        assert!(meta.get(IDENTITY_META_KEY).is_none());
444        let mut work = Block::default();
445        work.meta.insert(IDENTITY_META_KEY.into(), json!("profile:p-work"));
446        let mut meta = MetaMapType::new();
447        inherit(&mut meta, &work);
448        assert_eq!(meta[IDENTITY_META_KEY], json!("profile:p-work"));
449    }
450
451    #[tokio::test]
452    async fn a_new_tab_identity_is_checked() {
453        let state = crate::server::tests::test_state();
454        let with = |v: Value| {
455            let mut m = MetaMapType::new();
456            m.insert(IDENTITY_META_KEY.into(), v);
457            m
458        };
459        assert!(check_new_tab(&state, &MetaMapType::new()).is_ok());
460        assert!(check_new_tab(&state, &with(json!("incognito:short"))).is_err());
461        // Profiles work on every platform: an unknown one is refused as unknown.
462        let unknown = check_new_tab(&state, &with(json!("profile:p-none"))).unwrap_err();
463        assert!(unknown.contains("there is no browser profile"), "{unknown}");
464        assert!(check_new_tab(&state, &with(json!("profile:Bad Id"))).is_err());
465        assert!(check_new_tab(&state, &with(json!(5))).is_err());
466        let ok = check_new_tab(&state, &with(json!("incognito:cccccccc-3333")));
467        assert!(ok.is_ok(), "{ok:?}");
468    }
469}