Skip to content

Commit 6967dbf

Browse files
committed
Add doctor check for desktop remote control enrollment
1 parent 24faf49 commit 6967dbf

1 file changed

Lines changed: 355 additions & 0 deletions

File tree

‎codex-rs/cli/src/doctor.rs‎

Lines changed: 355 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,10 @@ const COLOR_ENV_VARS: &[&str] = &[
107107
const TERMINAL_DIMENSION_ENV_VARS: &[&str] = &["COLUMNS", "LINES"];
108108
const TERMINFO_ENV_VARS: &[&str] = &["TERMINFO", "TERMINFO_DIRS"];
109109
const LOCALE_ENV_VARS: &[&str] = &["LC_ALL", "LC_CTYPE", "LANG"];
110+
const ELECTRON_GLOBAL_STATE_FILE: &str = ".codex-global-state.json";
111+
const ELECTRON_REMOTE_CONTROL_CLIENT_ENROLLMENTS_KEY: &str =
112+
"electron-remote-control-client-enrollments";
113+
const ELECTRON_ADDED_REMOTE_CONTROL_ENV_IDS_KEY: &str = "added-remote-control-env-ids";
110114
#[cfg(windows)]
111115
const NPM_COMMAND: &str = "npm.cmd";
112116
#[cfg(not(windows))]
@@ -401,6 +405,9 @@ async fn build_report(
401405
background_server_check,
402406
reachability_check,
403407
]);
408+
checks.push(run_sync_check("remote-control", progress.clone(), || {
409+
desktop_remote_control_client_check(config)
410+
}));
404411
}
405412
Err(err) => {
406413
let reachability_plan = default_reachability_plan();
@@ -2014,6 +2021,269 @@ async fn state_check(config: &Config) -> DoctorCheck {
20142021
check
20152022
}
20162023

2024+
fn desktop_remote_control_client_check(config: &Config) -> DoctorCheck {
2025+
let global_state_path = config.codex_home.join(ELECTRON_GLOBAL_STATE_FILE);
2026+
let mut details = vec![format!(
2027+
"desktop global state: {}",
2028+
global_state_path.display()
2029+
)];
2030+
2031+
let auth = load_auth_dot_json(&config.codex_home, config.cli_auth_credentials_store_mode);
2032+
let identity = match auth.as_ref() {
2033+
Ok(Some(auth)) => current_chatgpt_account_user_identity(auth),
2034+
Ok(None) => None,
2035+
Err(err) => {
2036+
details.push(format!("auth identity read: {err}"));
2037+
None
2038+
}
2039+
};
2040+
details.push(format!(
2041+
"selected account-user identity: {}",
2042+
if identity.is_some() {
2043+
"available"
2044+
} else {
2045+
"unavailable"
2046+
}
2047+
));
2048+
2049+
let state_contents = match std::fs::read_to_string(&global_state_path) {
2050+
Ok(contents) => contents,
2051+
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
2052+
return DoctorCheck::new(
2053+
"remote_control.desktop_controller",
2054+
"remote-control",
2055+
CheckStatus::Ok,
2056+
"desktop remote-control controller state is absent",
2057+
)
2058+
.details(details);
2059+
}
2060+
Err(err) => {
2061+
return DoctorCheck::new(
2062+
"remote_control.desktop_controller",
2063+
"remote-control",
2064+
CheckStatus::Warning,
2065+
"desktop remote-control controller state could not be read",
2066+
)
2067+
.details(details)
2068+
.issue(
2069+
DoctorIssue::new(
2070+
CheckStatus::Warning,
2071+
"desktop global state file could not be read",
2072+
)
2073+
.measured(err.to_string())
2074+
.expected("readable desktop global state")
2075+
.field(ELECTRON_GLOBAL_STATE_FILE),
2076+
);
2077+
}
2078+
};
2079+
2080+
let state = match serde_json::from_str::<serde_json::Value>(&state_contents) {
2081+
Ok(state) => state,
2082+
Err(err) => {
2083+
return DoctorCheck::new(
2084+
"remote_control.desktop_controller",
2085+
"remote-control",
2086+
CheckStatus::Warning,
2087+
"desktop remote-control controller state could not be parsed",
2088+
)
2089+
.details(details)
2090+
.issue(
2091+
DoctorIssue::new(
2092+
CheckStatus::Warning,
2093+
"desktop global state file is not valid JSON",
2094+
)
2095+
.measured(err.to_string())
2096+
.expected("valid JSON")
2097+
.field(ELECTRON_GLOBAL_STATE_FILE),
2098+
);
2099+
}
2100+
};
2101+
2102+
let analysis = analyze_desktop_remote_control_client_state(&state, identity.as_ref());
2103+
details.extend(desktop_remote_control_client_state_details(&analysis));
2104+
2105+
if analysis.missing_selected_account_enrollment() {
2106+
return DoctorCheck::new(
2107+
"remote_control.desktop_controller",
2108+
"remote-control",
2109+
CheckStatus::Warning,
2110+
"desktop remote-control controller enrollment is missing the selected account key",
2111+
)
2112+
.details(details)
2113+
.issue(
2114+
DoctorIssue::new(
2115+
CheckStatus::Warning,
2116+
"a controller enrollment exists for the current ChatGPT user, but not for the selected account-user key",
2117+
)
2118+
.measured("current user enrollment: present; selected account-user enrollment: missing")
2119+
.expected("controller enrollment stored under the selected account-user key")
2120+
.remedy(
2121+
"Update Codex Desktop, rerun Connections > Control other devices > Setup, then restart Codex Desktop if the device picker is still empty.",
2122+
)
2123+
.field(ELECTRON_REMOTE_CONTROL_CLIENT_ENROLLMENTS_KEY),
2124+
)
2125+
.remediation(
2126+
"Update Codex Desktop, rerun remote-control setup, and include codex doctor --json in a support report if signed-in devices remain empty.",
2127+
);
2128+
}
2129+
2130+
DoctorCheck::new(
2131+
"remote_control.desktop_controller",
2132+
"remote-control",
2133+
CheckStatus::Ok,
2134+
"desktop remote-control controller state is consistent",
2135+
)
2136+
.details(details)
2137+
}
2138+
2139+
#[derive(Debug, Clone, PartialEq, Eq)]
2140+
struct ChatGptAccountUserIdentity {
2141+
user_id: String,
2142+
account_user_id: String,
2143+
}
2144+
2145+
fn current_chatgpt_account_user_identity(auth: &AuthDotJson) -> Option<ChatGptAccountUserIdentity> {
2146+
let tokens = auth.tokens.as_ref()?;
2147+
let user_id = tokens.id_token.chatgpt_user_id.clone()?;
2148+
let account_id = tokens
2149+
.account_id
2150+
.clone()
2151+
.or_else(|| tokens.id_token.chatgpt_account_id.clone())?;
2152+
Some(ChatGptAccountUserIdentity {
2153+
account_user_id: format!("{user_id}__{account_id}"),
2154+
user_id,
2155+
})
2156+
}
2157+
2158+
#[derive(Debug, Default, Clone, PartialEq, Eq)]
2159+
struct DesktopRemoteControlClientStateAnalysis {
2160+
enrollment_count: usize,
2161+
qualified_key_count: usize,
2162+
unqualified_key_count: usize,
2163+
added_remote_env_count: usize,
2164+
selected_account_user_key_present: Option<bool>,
2165+
current_user_key_present: Option<bool>,
2166+
current_user_value_present: Option<bool>,
2167+
}
2168+
2169+
impl DesktopRemoteControlClientStateAnalysis {
2170+
fn missing_selected_account_enrollment(&self) -> bool {
2171+
self.added_remote_env_count > 0
2172+
&& self.enrollment_count > 0
2173+
&& self.selected_account_user_key_present == Some(false)
2174+
&& (self.current_user_key_present == Some(true)
2175+
|| self.current_user_value_present == Some(true))
2176+
}
2177+
}
2178+
2179+
fn analyze_desktop_remote_control_client_state(
2180+
state: &serde_json::Value,
2181+
identity: Option<&ChatGptAccountUserIdentity>,
2182+
) -> DesktopRemoteControlClientStateAnalysis {
2183+
let enrollments = state
2184+
.get(ELECTRON_REMOTE_CONTROL_CLIENT_ENROLLMENTS_KEY)
2185+
.and_then(serde_json::Value::as_object);
2186+
let added_remote_env_count = state
2187+
.get(ELECTRON_ADDED_REMOTE_CONTROL_ENV_IDS_KEY)
2188+
.map_or(0, json_collection_len);
2189+
2190+
let mut analysis = DesktopRemoteControlClientStateAnalysis {
2191+
enrollment_count: enrollments.map_or(0, serde_json::Map::len),
2192+
added_remote_env_count,
2193+
selected_account_user_key_present: identity.map(|_| false),
2194+
current_user_key_present: identity.map(|_| false),
2195+
current_user_value_present: identity.map(|_| false),
2196+
..Default::default()
2197+
};
2198+
2199+
let Some(enrollments) = enrollments else {
2200+
return analysis;
2201+
};
2202+
2203+
for (key, value) in enrollments {
2204+
let key_account_user_id = desktop_remote_control_enrollment_key_account_user_id(key);
2205+
if is_qualified_account_user_id(key_account_user_id) {
2206+
analysis.qualified_key_count += 1;
2207+
} else {
2208+
analysis.unqualified_key_count += 1;
2209+
}
2210+
2211+
if let Some(identity) = identity {
2212+
if key_account_user_id == identity.account_user_id {
2213+
analysis.selected_account_user_key_present = Some(true);
2214+
}
2215+
if key_account_user_id == identity.user_id {
2216+
analysis.current_user_key_present = Some(true);
2217+
}
2218+
if value
2219+
.get("accountUserId")
2220+
.and_then(serde_json::Value::as_str)
2221+
.is_some_and(|account_user_id| account_user_id == identity.user_id)
2222+
{
2223+
analysis.current_user_value_present = Some(true);
2224+
}
2225+
}
2226+
}
2227+
2228+
analysis
2229+
}
2230+
2231+
fn desktop_remote_control_enrollment_key_account_user_id(key: &str) -> &str {
2232+
key.rsplit('\n').next().unwrap_or(key)
2233+
}
2234+
2235+
fn is_qualified_account_user_id(account_user_id: &str) -> bool {
2236+
account_user_id.contains("__")
2237+
}
2238+
2239+
fn json_collection_len(value: &serde_json::Value) -> usize {
2240+
match value {
2241+
serde_json::Value::Array(items) => items.len(),
2242+
serde_json::Value::Object(entries) => entries.len(),
2243+
_ => 0,
2244+
}
2245+
}
2246+
2247+
fn desktop_remote_control_client_state_details(
2248+
analysis: &DesktopRemoteControlClientStateAnalysis,
2249+
) -> Vec<String> {
2250+
vec![
2251+
format!("controller enrollments: {}", analysis.enrollment_count),
2252+
format!(
2253+
"controller enrollment qualified keys: {}",
2254+
analysis.qualified_key_count
2255+
),
2256+
format!(
2257+
"controller enrollment unqualified keys: {}",
2258+
analysis.unqualified_key_count
2259+
),
2260+
format!(
2261+
"added remote-control env ids: {}",
2262+
analysis.added_remote_env_count
2263+
),
2264+
format!(
2265+
"selected account-user key present: {}",
2266+
option_bool_label(analysis.selected_account_user_key_present)
2267+
),
2268+
format!(
2269+
"current user key present: {}",
2270+
option_bool_label(analysis.current_user_key_present)
2271+
),
2272+
format!(
2273+
"current user enrollment value present: {}",
2274+
option_bool_label(analysis.current_user_value_present)
2275+
),
2276+
]
2277+
}
2278+
2279+
fn option_bool_label(value: Option<bool>) -> &'static str {
2280+
match value {
2281+
Some(true) => "yes",
2282+
Some(false) => "no",
2283+
None => "unavailable",
2284+
}
2285+
}
2286+
20172287
async fn sqlite_integrity_detail(
20182288
details: &mut Vec<String>,
20192289
integrity_failures: &mut Vec<String>,
@@ -3266,6 +3536,91 @@ mod tests {
32663536
);
32673537
}
32683538

3539+
#[test]
3540+
fn current_chatgpt_account_user_identity_derives_selected_account_key() {
3541+
let auth = AuthDotJson {
3542+
auth_mode: None,
3543+
openai_api_key: None,
3544+
tokens: Some(codex_login::TokenData {
3545+
id_token: codex_login::token_data::IdTokenInfo {
3546+
chatgpt_user_id: Some("user-123".to_string()),
3547+
chatgpt_account_id: Some("account-from-token".to_string()),
3548+
..Default::default()
3549+
},
3550+
access_token: "access".to_string(),
3551+
refresh_token: "refresh".to_string(),
3552+
account_id: Some("account-selected".to_string()),
3553+
}),
3554+
last_refresh: None,
3555+
agent_identity: None,
3556+
};
3557+
3558+
assert_eq!(
3559+
current_chatgpt_account_user_identity(&auth),
3560+
Some(ChatGptAccountUserIdentity {
3561+
user_id: "user-123".to_string(),
3562+
account_user_id: "user-123__account-selected".to_string(),
3563+
})
3564+
);
3565+
}
3566+
3567+
#[test]
3568+
fn desktop_remote_control_analysis_warns_when_selected_account_key_missing() {
3569+
let state = serde_json::json!({
3570+
ELECTRON_REMOTE_CONTROL_CLIENT_ENROLLMENTS_KEY: {
3571+
"Codex Desktop\nhttp://localhost:8000/api\nhttps://chatgpt.com/backend-api\nuser-123": {
3572+
"accountUserId": "user-123",
3573+
"clientId": "client-1",
3574+
"keyId": "key-1"
3575+
}
3576+
},
3577+
ELECTRON_ADDED_REMOTE_CONTROL_ENV_IDS_KEY: ["env-1"]
3578+
});
3579+
let identity = ChatGptAccountUserIdentity {
3580+
user_id: "user-123".to_string(),
3581+
account_user_id: "user-123__account-selected".to_string(),
3582+
};
3583+
3584+
let analysis = analyze_desktop_remote_control_client_state(&state, Some(&identity));
3585+
3586+
assert_eq!(analysis.enrollment_count, 1);
3587+
assert_eq!(analysis.unqualified_key_count, 1);
3588+
assert_eq!(analysis.qualified_key_count, 0);
3589+
assert_eq!(analysis.added_remote_env_count, 1);
3590+
assert_eq!(analysis.selected_account_user_key_present, Some(false));
3591+
assert_eq!(analysis.current_user_key_present, Some(true));
3592+
assert_eq!(analysis.current_user_value_present, Some(true));
3593+
assert!(analysis.missing_selected_account_enrollment());
3594+
}
3595+
3596+
#[test]
3597+
fn desktop_remote_control_analysis_accepts_selected_account_key_alias() {
3598+
let state = serde_json::json!({
3599+
ELECTRON_REMOTE_CONTROL_CLIENT_ENROLLMENTS_KEY: {
3600+
"Codex Desktop\nhttp://localhost:8000/api\nhttps://chatgpt.com/backend-api\nuser-123__account-selected": {
3601+
"accountUserId": "user-123",
3602+
"clientId": "client-1",
3603+
"keyId": "key-1"
3604+
}
3605+
},
3606+
ELECTRON_ADDED_REMOTE_CONTROL_ENV_IDS_KEY: ["env-1"]
3607+
});
3608+
let identity = ChatGptAccountUserIdentity {
3609+
user_id: "user-123".to_string(),
3610+
account_user_id: "user-123__account-selected".to_string(),
3611+
};
3612+
3613+
let analysis = analyze_desktop_remote_control_client_state(&state, Some(&identity));
3614+
3615+
assert_eq!(analysis.enrollment_count, 1);
3616+
assert_eq!(analysis.unqualified_key_count, 0);
3617+
assert_eq!(analysis.qualified_key_count, 1);
3618+
assert_eq!(analysis.selected_account_user_key_present, Some(true));
3619+
assert_eq!(analysis.current_user_key_present, Some(false));
3620+
assert_eq!(analysis.current_user_value_present, Some(true));
3621+
assert!(!analysis.missing_selected_account_enrollment());
3622+
}
3623+
32693624
#[test]
32703625
fn stored_auth_validation_rejects_missing_api_key() {
32713626
let auth = AuthDotJson {

0 commit comments

Comments
 (0)