use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::time::Duration;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::chrome::contract::{OutKind, Reader};
use crate::chrome::lock_json::LockedJson;
use crate::chrome::spawn::CliRun;
const MIN_HELPER_VERSION: (u64, u64, u64) = (1, 5, 287);
const LIST_BOUND: Duration = Duration::from_secs(10);
const BRING_UP_BUDGET: Duration = Duration::from_secs(45);
const BRING_UP_WAIT_SECS: u64 = 40;
const PINS_FILE_NAME: &str = "chrome-session-profiles.json";
const LOCK_FILE_NAME: &str = "chrome-session-profiles.lock";
#[expect(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct Row {
name: String,
dir: String,
email: Option<String>,
id: Option<String>,
has_extension: bool,
extension_disabled: bool,
connected: bool,
session: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Profile {
pub(crate) display: String,
pub(crate) dir: String,
}
fn describe_pair(name: &str, dir: &str) -> String {
if name == dir {
format!("\"{dir}\"")
} else {
format!("\"{name}\" ({dir})")
}
}
impl Profile {
fn from_row(row: &Row) -> Self {
Self {
display: row.name.clone(),
dir: row.dir.clone(),
}
}
fn describe(&self) -> String {
describe_pair(&self.display, &self.dir)
}
}
#[derive(Debug)]
pub(crate) struct Refusal {
kind: OutKind,
message: String,
profile: Option<Profile>,
}
impl Refusal {
fn usage(message: String) -> Self {
Self {
kind: OutKind::Usage,
message,
profile: None,
}
}
fn environment(message: String) -> Self {
Self {
kind: OutKind::Environment,
message,
profile: None,
}
}
fn conflict(message: String, actual: Profile) -> Self {
Self {
kind: OutKind::Conflict,
message,
profile: Some(actual),
}
}
pub(crate) fn kind(&self) -> OutKind {
self.kind
}
pub(crate) fn message(&self) -> &str {
&self.message
}
pub(crate) fn profile(&self) -> Option<&Profile> {
self.profile.as_ref()
}
}
const PIN_MAX_IDLE_MS: u64 = 2 * 60 * 60 * 1000;
pub(crate) enum LaunchTarget {
None,
Single(Profile),
Mixed,
}
#[must_use]
pub(crate) fn launch_target(owned: impl Fn(&str) -> bool) -> LaunchTarget {
let recorded = crate::chrome::cli_sessions::recorded_names();
let Some(mut store) = LockedJson::<Pins>::open_existing(PINS_FILE_NAME, LOCK_FILE_NAME) else {
return LaunchTarget::None;
};
if store.broken {
return LaunchTarget::None;
}
let (target, pruned) = launch_target_of(&mut store.value, |session| {
recorded.contains(session) || owned(session)
});
if pruned {
store.persist();
}
target
}
fn launch_target_of(pins: &mut Pins, owned: impl Fn(&str) -> bool) -> (LaunchTarget, bool) {
let now = crate::util::unix_millis();
let before = pins.len();
pins.retain(|session, pin| owned(session) || now.saturating_sub(pin.at_ms) < PIN_MAX_IDLE_MS);
let pruned = pins.len() != before;
let mut by_dir: BTreeMap<String, Profile> = BTreeMap::new();
for pin in pins.values() {
by_dir
.entry(pin.profile.dir.clone())
.or_insert_with(|| pin.profile.clone());
}
let mut it = by_dir.into_values();
let target = match (it.next(), it.next()) {
(None, _) => LaunchTarget::None,
(Some(profile), None) => LaunchTarget::Single(profile),
(Some(_), Some(_)) => LaunchTarget::Mixed,
};
(target, pruned)
}
#[must_use]
pub(crate) fn sweep_sessions(fallback: &str, is_door: impl Fn(&str) -> bool) -> Vec<String> {
let mut out = Vec::new();
let mut seen = BTreeSet::new();
let mut fallback_dir = None;
if let Ok(Some(pins)) = read_pins() {
for (session, pin) in &pins {
if is_door(session) && seen.insert(pin.profile.dir.clone()) {
out.push(session.clone());
}
}
fallback_dir = pins.get(fallback).map(|pin| pin.profile.dir.clone());
}
if fallback_dir.is_none_or(|dir| !seen.contains(&dir)) {
out.push(fallback.to_string());
}
out
}
pub(crate) async fn prepare(
cli: &Path,
session: &str,
subject: &str,
requested: Option<&str>,
stored: PinState,
reader: Reader,
) -> Result<Option<Profile>, Refusal> {
let pinned = stored.profile().cloned();
if requested.is_none() && pinned.is_none() {
return Ok(None);
}
let rows = list(cli, Some(session), LIST_BOUND)
.await
.map_err(Refusal::environment)?;
let target = match (requested, pinned.clone()) {
(Some(name), _) => resolve(name, &rows)?,
(None, Some(pinned)) => pinned,
(None, None) => return Ok(None),
};
if matches!(stored, PinState::Unreadable) {
return Err(unreadable_pins());
}
let min = semver::Version::new(
MIN_HELPER_VERSION.0,
MIN_HELPER_VERSION.1,
MIN_HELPER_VERSION.2,
);
match crate::tools::chrome_daemon::cli_version().await {
Some(version) if version >= min => {}
Some(version) => {
return Err(Refusal::environment(format!(
"chrome-use {version} is too old to select a Chrome profile; that needs {min} or \
newer. The product updates its own copy on start — retry after it does."
)));
}
None => {
return Err(Refusal::environment(
"could not read chrome-use's version, so a Chrome profile cannot be selected"
.to_string(),
));
}
}
let bound = rows
.iter()
.find(|row| row.session)
.map(Profile::from_row)
.or_else(|| pinned.clone());
if let Some(bound) = bound
&& bound.dir != target.dir
{
let message = conflict(subject, &bound, &target, reader);
return Err(Refusal::conflict(message, bound));
}
let Some(row) = rows.iter().find(|row| row.dir == target.dir) else {
return Err(Refusal::environment(format!(
"profile {} no longer exists on this machine. Available profiles: {}.",
target.describe(),
listing(&rows.iter().collect::<Vec<_>>())
)));
};
if !row.has_extension {
return Err(Refusal::environment(format!(
"profile {} has no chrome-use extension installed, so it cannot be driven. Install the \
extension in that profile first.",
target.describe()
)));
}
if row.extension_disabled {
return Err(Refusal::environment(format!(
"profile {} has the chrome-use extension disabled. Enable it in that profile first.",
target.describe()
)));
}
if !row.connected {
bring_up(cli, &target).await.map_err(|reason| {
Refusal::environment(format!(
"profile {} could not be brought up: {reason}.",
target.describe()
))
})?;
let confirmed = list(cli, Some(session), LIST_BOUND)
.await
.map_err(Refusal::environment)?;
if !confirmed
.iter()
.any(|row| row.dir == target.dir && row.connected)
{
return Err(Refusal::environment(format!(
"profile {} did not come up: chrome-use reported no relay for it.",
target.describe()
)));
}
}
if !pin(session, &target) {
return Err(Refusal::environment(format!(
"profile {} could not be recorded for this session, so the call would risk landing in \
another profile. Retry.",
target.describe()
)));
}
Ok(Some(target))
}
pub(crate) async fn of_session(cli: &Path, session: &str, bound: Duration) -> Option<Profile> {
let rows = list(cli, Some(session), bound).await.ok()?;
rows.iter().find(|row| row.session).map(Profile::from_row)
}
fn conflict(subject: &str, actual: &Profile, named: &Profile, reader: Reader) -> String {
crate::chrome::contract::profile_conflict_message(
reader,
Some(subject),
&actual.describe(),
Some(&named.describe()),
)
}
pub(crate) async fn served(
cli: &Path,
session: &str,
subject: &str,
named: &Profile,
reader: Reader,
) -> Result<Option<Profile>, Refusal> {
let Some(actual) = of_session(cli, session, LIST_BOUND).await else {
return Ok(None);
};
if actual.dir == named.dir {
return Ok(Some(actual));
}
let message = conflict(subject, &actual, named, reader);
Err(Refusal::conflict(message, actual))
}
fn verb_carries_profile(args: &[&str]) -> bool {
!matches!(
args.first().copied(),
Some(
"session"
| "browsers"
| "status"
| "daemon"
| "connect"
| "doctor"
| "install"
| "update"
)
)
}
#[must_use]
pub(crate) fn browser_arg(args: &[&str], session: Option<&str>) -> Option<String> {
let session = session.filter(|_| verb_carries_profile(args))?;
let pins = read_pins().ok().flatten()?;
pins.get(session).map(|pin| pin.profile.dir.clone())
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Pin {
profile: Profile,
#[serde(default)]
at_ms: u64,
}
type Pins = BTreeMap<String, Pin>;
fn read_pins() -> Result<Option<Pins>, ()> {
LockedJson::<Pins>::read_existing(PINS_FILE_NAME)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PinState {
None,
Pinned(Profile),
Unreadable,
}
impl PinState {
pub(crate) fn profile(&self) -> Option<&Profile> {
match self {
Self::Pinned(profile) => Some(profile),
Self::None | Self::Unreadable => None,
}
}
}
pub(crate) fn pinned(session: &str) -> PinState {
match read_pins() {
Ok(pins) => pins
.and_then(|pins| pins.get(session).map(|pin| pin.profile.clone()))
.map_or(PinState::None, PinState::Pinned),
Err(()) => PinState::Unreadable,
}
}
#[must_use]
pub(crate) fn pins() -> BTreeMap<String, Profile> {
read_pins()
.ok()
.flatten()
.map_or_else(BTreeMap::new, |pins| {
pins.into_iter()
.map(|(session, pin)| (session, pin.profile))
.collect()
})
}
fn pin(session: &str, profile: &Profile) -> bool {
let Some(mut store) = LockedJson::<Pins>::open(PINS_FILE_NAME, LOCK_FILE_NAME) else {
return false;
};
if store.broken {
return false;
}
let at_ms = crate::util::unix_millis();
store.value.insert(
session.to_string(),
Pin {
profile: profile.clone(),
at_ms,
},
);
store.persist()
}
pub(crate) fn forget(session: &str) {
forget_all(std::iter::once(session));
}
pub(crate) fn forget_all<'a>(sessions: impl IntoIterator<Item = &'a str>) {
let Some(mut store) = LockedJson::<Pins>::open_existing(PINS_FILE_NAME, LOCK_FILE_NAME) else {
return;
};
if store.broken {
return;
}
let mut changed = false;
for session in sessions {
changed |= store.value.remove(session).is_some();
}
if changed {
store.persist();
}
}
fn unreadable_pins() -> Refusal {
Refusal::environment(format!(
"the record of which Chrome profile each session is pinned to ({PINS_FILE_NAME}) cannot be \
read. Repair or remove it in the product's storage root, then retry."
))
}
async fn list(cli: &Path, session: Option<&str>, bound: Duration) -> Result<Vec<Row>, String> {
let value = crate::tools::chrome_daemon::run_cli_json_at(cli, &["browsers"], session, bound)
.await
.map_err(|verdict| {
match verdict {
crate::tools::chrome_daemon::NoVerdict::Reported(_) => {
"could not list Chrome profiles: the helper refused the read".to_string()
}
other => format!("could not list Chrome profiles: {}", other.text()),
}
})?;
parse_rows(&value).ok_or_else(|| "chrome-use returned no profile list".to_string())
}
fn parse_rows(value: &Value) -> Option<Vec<Row>> {
let list = crate::tools::chrome_daemon::real_browser_list(value)?;
Some(list.iter().filter_map(Row::from_value).collect())
}
impl Row {
fn from_value(value: &Value) -> Option<Self> {
let dir = value.get("dir").and_then(Value::as_str)?.trim().to_string();
if dir.is_empty() {
return None;
}
let text = |key: &str| {
value
.get(key)
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
};
let name = text("name").unwrap_or_else(|| dir.clone());
Some(Self {
name,
dir,
email: text("email"),
id: text("id"),
has_extension: value.get("hasExtension").and_then(Value::as_bool) == Some(true),
extension_disabled: value
.get("extensionDisabled")
.and_then(Value::as_bool)
.unwrap_or(false),
connected: value
.get("connected")
.and_then(Value::as_bool)
.unwrap_or(false),
session: value
.get("session")
.and_then(Value::as_bool)
.unwrap_or(false),
})
}
}
fn resolve(name: &str, rows: &[Row]) -> Result<Profile, Refusal> {
let want = name.trim();
if want.is_empty() {
return Err(unknown(name, rows));
}
let lower = want.to_lowercase();
let matches = |field: fn(&Row) -> Option<&str>| -> Vec<&Row> {
rows.iter()
.filter(|row| field(row).is_some_and(|value| value.to_lowercase() == lower))
.collect()
};
for field in [
(|row: &Row| Some(row.name.as_str())) as fn(&Row) -> Option<&str>,
|row: &Row| Some(row.dir.as_str()),
|row: &Row| row.email.as_deref(),
|row: &Row| row.id.as_deref(),
] {
match matches(field).as_slice() {
[] => {}
[one] => return Ok(Profile::from_row(one)),
several => return Err(ambiguous(name, several)),
}
}
let prefixed: Vec<&Row> = rows
.iter()
.filter(|row| row.name.to_lowercase().starts_with(&lower))
.collect();
match prefixed.as_slice() {
[] => Err(unknown(name, rows)),
[one] => Ok(Profile::from_row(one)),
several => Err(ambiguous(name, several)),
}
}
fn unknown(name: &str, rows: &[Row]) -> Refusal {
let all: Vec<&Row> = rows.iter().collect();
Refusal::usage(format!(
"invalid profile \"{name}\": no Chrome profile matches. Available profiles: {}.",
listing(&all)
))
}
fn ambiguous(name: &str, matches: &[&Row]) -> Refusal {
Refusal::usage(format!(
"invalid profile \"{name}\": it matches several Chrome profiles: {}. Name the exact \
display name or directory.",
listing(matches)
))
}
fn listing(rows: &[&Row]) -> String {
if rows.is_empty() {
return "none".to_string();
}
rows.iter()
.map(|row| describe_pair(&row.name, &row.dir))
.collect::<Vec<_>>()
.join(", ")
}
async fn bring_up(cli: &Path, profile: &Profile) -> Result<(), String> {
let wait = BRING_UP_WAIT_SECS.to_string();
let args = [
"connect",
"--browser",
profile.dir.as_str(),
"--wait",
wait.as_str(),
];
match crate::tools::chrome_daemon::run_cli_bounded_at(cli, &args, None, BRING_UP_BUDGET).await {
CliRun::Output(out) if out.status.success() => Ok(()),
CliRun::Output(out) => Err(format!("chrome-use connect exited with {}", out.status)),
CliRun::SpawnFailure => Err("chrome-use could not be started".to_string()),
CliRun::TimedOut => Err(format!(
"it did not come up within {}s",
BRING_UP_BUDGET.as_secs()
)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn rows() -> Vec<Row> {
parse_rows(&json!({"data": {"browsers": [
{"name": "Work", "dir": "Default", "email": "work@example.com", "id": "id-work",
"hasExtension": true, "connected": true, "session": false},
{"name": "Your Chrome", "dir": "Profile 8", "email": "home@example.com",
"id": "id-home", "hasExtension": true, "connected": true, "session": false},
{"name": "Work Extra", "dir": "Profile 2", "email": null, "id": null,
"hasExtension": false, "extensionDisabled": false, "connected": false, "session": false},
]}}))
.expect("rows parse")
}
#[test]
fn a_name_resolves_by_display_dir_email_id_and_unique_prefix() {
for (name, dir) in [
("Work", "Default"),
("Default", "Default"),
("work@example.com", "Default"),
("id-home", "Profile 8"),
("Your", "Profile 8"),
] {
assert_eq!(resolve(name, &rows()).unwrap().dir, dir, "name {name}");
}
}
#[test]
fn an_exact_name_wins_over_a_prefix() {
assert_eq!(resolve("Work", &rows()).unwrap().dir, "Default");
}
#[test]
fn an_unknown_name_lists_every_profile_without_addresses() {
let refusal = resolve("nope", &rows()).unwrap_err();
assert_eq!(refusal.kind(), OutKind::Usage);
assert!(
refusal.message().contains("\"Work\" (Default)"),
"{}",
refusal.message()
);
assert!(
refusal.message().contains("\"Your Chrome\" (Profile 8)"),
"{}",
refusal.message()
);
assert!(
!refusal.message().contains("work@example.com"),
"{}",
refusal.message()
);
assert!(
!refusal.message().contains("id-work"),
"{}",
refusal.message()
);
}
#[test]
fn an_ambiguous_prefix_lists_only_the_matches_without_addresses() {
let refusal = resolve("Wor", &rows()).unwrap_err();
assert_eq!(refusal.kind(), OutKind::Usage);
assert!(
refusal.message().contains("\"Work\" (Default)"),
"{}",
refusal.message()
);
assert!(
refusal.message().contains("\"Work Extra\" (Profile 2)"),
"{}",
refusal.message()
);
assert!(
!refusal.message().contains("Your Chrome"),
"{}",
refusal.message()
);
assert!(
!refusal.message().contains("home@example.com"),
"{}",
refusal.message()
);
}
#[test]
fn page_and_group_verbs_carry_the_profile() {
for verb in [
"open",
"click",
"tab",
"close",
"get",
"eval",
"screenshot",
"extension",
] {
assert!(verb_carries_profile(&[verb]), "{verb} works in the browser");
}
for verb in [
"session", "browsers", "status", "daemon", "connect", "doctor",
] {
assert!(
!verb_carries_profile(&[verb]),
"{verb} is a session-less diagnostic"
);
}
}
#[test]
fn browser_arg_follows_the_session_pin_and_the_verb() {
assert_eq!(browser_arg(&["open"], Some("agent-tab-no-pin")), None);
let profile = Profile {
display: "Your Chrome".to_string(),
dir: "Profile 8".to_string(),
};
pin("agent-tab-browser-arg", &profile);
assert_eq!(
browser_arg(&["open"], Some("agent-tab-browser-arg")).as_deref(),
Some("Profile 8")
);
assert_eq!(
browser_arg(&["status"], Some("agent-tab-browser-arg")),
None
);
forget("agent-tab-browser-arg");
}
#[test]
fn a_conflict_names_the_actual_profile_and_never_an_address() {
let actual = Profile {
display: "Your Chrome".to_string(),
dir: "Profile 8".to_string(),
};
let named = Profile {
display: "Work".to_string(),
dir: "Default".to_string(),
};
let message = conflict("work", &actual, &named, Reader::Cli);
assert!(message.contains("\"Your Chrome\" (Profile 8)"), "{message}");
assert!(message.contains("\"Work\" (Default)"), "{message}");
assert!(message.contains("new session"), "{message}");
assert!(!message.contains('@'), "{message}");
let tool = conflict("work", &actual, &named, Reader::Tool);
assert!(tool.contains("new tab"), "{tool}");
assert!(!tool.contains("session"), "{tool}");
}
fn pin_at(pins: &mut Pins, session: &str, dir: &str, at_ms: u64) {
pins.insert(
session.to_string(),
Pin {
profile: Profile {
display: dir.to_string(),
dir: dir.to_string(),
},
at_ms,
},
);
}
#[test]
fn the_launch_decision_is_one_profile_or_none_when_they_disagree() {
let mut pins = Pins::new();
assert!(matches!(
launch_target_of(&mut pins, |_| true),
(LaunchTarget::None, false)
));
let now = crate::util::unix_millis();
pin_at(&mut pins, "a", "Default", now);
pin_at(&mut pins, "b", "Default", now);
let (target, pruned) = launch_target_of(&mut pins, |_| true);
assert!(!pruned);
assert!(
matches!(target, LaunchTarget::Single(profile) if profile.dir == "Default"),
"two sessions on one profile launch that profile"
);
pin_at(&mut pins, "c", "Profile 8", now);
assert!(matches!(
launch_target_of(&mut pins, |_| true),
(LaunchTarget::Mixed, false)
));
}
#[test]
fn an_abandoned_pin_is_pruned_and_an_owned_one_is_kept() {
let mut pins = Pins::new();
pin_at(&mut pins, "gone", "Profile 8", 0);
pin_at(&mut pins, "live", "Default", 0);
let (target, pruned) = launch_target_of(&mut pins, |session| session == "live");
assert!(pruned);
assert!(!pins.contains_key("gone"));
assert!(pins.contains_key("live"));
assert!(
matches!(target, LaunchTarget::Single(profile) if profile.dir == "Default"),
"the abandoned pin no longer forces Mixed"
);
}
#[test]
fn the_store_round_trips_and_forgets_a_session() {
let name = "agent-tab-test-profile-store";
let profile = Profile {
display: "Your Chrome".to_string(),
dir: "Profile 8".to_string(),
};
pin(name, &profile);
assert_eq!(pinned(name), PinState::Pinned(profile));
forget(name);
assert_eq!(pinned(name), PinState::None);
}
}