Files
codex/codex-rs/model-provider/src/request_preparation.rs
T
sgarg-oai 53d3d7f64e Centralize provider request preparation auth checks (#58121)
## What changed

Move the model client's request-preparation loop into the shared `prepare_provider_request` helper and add `RequestAuthChange` to classify auth state changes. For managed auth, retry preparation when credentials change and reject account changes, including when the provider starts or stops exposing an auth manager during setup.

Capture the auth owner and credential generations together and pass them into the preparation callback so the resulting client setup records the state used for that attempt.

## Testing

Add a test verifying that an explicit provider bearer token survives a workspace switch during setup without retrying preparation.

GitOrigin-RevId: ed8710d1c344b48ebf6182e25e6269214dd2d3fe
2026-10-29 16:39:38 +00:00

57 lines
1.8 KiB
Rust

//! Keeps request preparation bound to the credential revision it started with.
use std::future::Future;
use std::io;
use codex_login::AuthChangeState;
use codex_login::RequestAuthChange;
use codex_protocol::error::Result;
use crate::ModelProvider;
/// Prepare a request without dispatching it. When the request uses managed auth,
/// repeat preparation after a credential refresh and fail if the owner changes.
pub async fn prepare_provider_request<T, Fut>(
provider: &dyn ModelProvider,
check_auth: bool,
mut prepare: impl FnMut(Option<AuthChangeState>) -> Fut,
) -> Result<T>
where
Fut: Future<Output = Result<T>>,
{
let auth_state = || {
provider
.auth_manager()
.map(|manager| *manager.auth_change_state_receiver().borrow())
};
let mut before = auth_state();
loop {
let prepared = prepare(before).await?;
if !check_auth {
return Ok(prepared);
}
// A managed provider can begin or cease exposing its auth manager during setup.
let after = auth_state();
let change = match (before, after) {
(Some(before), Some(after)) => {
after.compare_for_request(before.owner_generation, before)
}
(None, None) => RequestAuthChange::Unchanged,
_ => RequestAuthChange::OwnerChanged,
};
match change {
RequestAuthChange::Unchanged => return Ok(prepared),
RequestAuthChange::CredentialsChanged => before = after,
RequestAuthChange::OwnerChanged => {
return Err(
io::Error::other("account changed while preparing model request").into(),
);
}
}
}
}
#[cfg(test)]
#[path = "request_preparation_tests.rs"]
mod tests;