Checkpoint before e2e test

This commit is contained in:
Richard Lee
2026-04-04 16:50:19 -07:00
parent e6d2da4716
commit 24ce07949e
21 changed files with 1269 additions and 8 deletions
@@ -147,6 +147,63 @@
],
"type": "object"
},
"CodexAvatarAdminAwardGrantParams": {
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"sourceType"
],
"type": "object"
},
"CodexAvatarAdminCapabilitiesReadParams": {
"type": "object"
},
"CodexAvatarEquipParams": {
"properties": {
"avatarId": {
@@ -4600,6 +4657,54 @@
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/admin/award"
],
"title": "Avatar/admin/awardRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarAdminAwardGrantParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/awardRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/admin/capabilities/read"
],
"title": "Avatar/admin/capabilities/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarAdminCapabilitiesReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/capabilities/readRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -1367,6 +1367,54 @@
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"avatar/admin/award"
],
"title": "Avatar/admin/awardRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/CodexAvatarAdminAwardGrantParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/awardRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"avatar/admin/capabilities/read"
],
"title": "Avatar/admin/capabilities/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/CodexAvatarAdminCapabilitiesReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/capabilities/readRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -5655,6 +5703,80 @@
],
"type": "string"
},
"CodexAvatarAdminAwardGrantParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"sourceType"
],
"title": "CodexAvatarAdminAwardGrantParams",
"type": "object"
},
"CodexAvatarAdminCapabilitiesReadParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarAdminCapabilitiesReadParams",
"type": "object"
},
"CodexAvatarAdminCapabilitiesReadResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"canGrantAwards": {
"type": "boolean"
}
},
"required": [
"canGrantAwards"
],
"title": "CodexAvatarAdminCapabilitiesReadResponse",
"type": "object"
},
"CodexAvatarDefinition": {
"properties": {
"assetRef": {
@@ -1942,6 +1942,54 @@
"title": "Avatar/equipRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/admin/award"
],
"title": "Avatar/admin/awardRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarAdminAwardGrantParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/awardRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"avatar/admin/capabilities/read"
],
"title": "Avatar/admin/capabilities/readRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/CodexAvatarAdminCapabilitiesReadParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Avatar/admin/capabilities/readRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -2260,6 +2308,80 @@
],
"title": "ClientRequest"
},
"CodexAvatarAdminAwardGrantParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"sourceType"
],
"title": "CodexAvatarAdminAwardGrantParams",
"type": "object"
},
"CodexAvatarAdminCapabilitiesReadParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarAdminCapabilitiesReadParams",
"type": "object"
},
"CodexAvatarAdminCapabilitiesReadResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"canGrantAwards": {
"type": "boolean"
}
},
"required": [
"canGrantAwards"
],
"title": "CodexAvatarAdminCapabilitiesReadResponse",
"type": "object"
},
"CodexAvatarDefinition": {
"properties": {
"assetRef": {
@@ -0,0 +1,56 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"accountUserId": {
"type": "string"
},
"avatarId": {
"type": "string"
},
"awardId": {
"type": "string"
},
"awardedAt": {
"format": "int64",
"type": [
"integer",
"null"
]
},
"awardedBy": {
"type": [
"string",
"null"
]
},
"metadataJson": {
"type": [
"string",
"null"
]
},
"sourceRef": {
"type": [
"string",
"null"
]
},
"sourceSummary": {
"type": [
"string",
"null"
]
},
"sourceType": {
"type": "string"
}
},
"required": [
"accountUserId",
"avatarId",
"awardId",
"sourceType"
],
"title": "CodexAvatarAdminAwardGrantParams",
"type": "object"
}
@@ -0,0 +1,5 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "CodexAvatarAdminCapabilitiesReadParams",
"type": "object"
}
@@ -0,0 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"canGrantAwards": {
"type": "boolean"
}
},
"required": [
"canGrantAwards"
],
"title": "CodexAvatarAdminCapabilitiesReadResponse",
"type": "object"
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type CodexAvatarAdminAwardGrantParams = { accountUserId: string, awardId: string, avatarId: string, sourceType: string, sourceRef?: string | null, awardedAt?: bigint | null, awardedBy?: string | null, metadataJson?: string | null, sourceSummary?: string | null, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type CodexAvatarAdminCapabilitiesReadParams = Record<string, never>;
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type CodexAvatarAdminCapabilitiesReadResponse = { canGrantAwards: boolean, };
@@ -31,6 +31,9 @@ export type { CancelLoginAccountStatus } from "./CancelLoginAccountStatus";
export type { ChatgptAuthTokensRefreshParams } from "./ChatgptAuthTokensRefreshParams";
export type { ChatgptAuthTokensRefreshReason } from "./ChatgptAuthTokensRefreshReason";
export type { ChatgptAuthTokensRefreshResponse } from "./ChatgptAuthTokensRefreshResponse";
export type { CodexAvatarAdminAwardGrantParams } from "./CodexAvatarAdminAwardGrantParams";
export type { CodexAvatarAdminCapabilitiesReadParams } from "./CodexAvatarAdminCapabilitiesReadParams";
export type { CodexAvatarAdminCapabilitiesReadResponse } from "./CodexAvatarAdminCapabilitiesReadResponse";
export type { CodexAvatarAward } from "./CodexAvatarAward";
export type { CodexAvatarDefinition } from "./CodexAvatarDefinition";
export type { CodexAvatarEquipParams } from "./CodexAvatarEquipParams";
@@ -495,6 +495,16 @@ client_request_definitions! {
response: v2::CodexAvatarInventoryReadResponse,
},
AvatarAdminAward => "avatar/admin/award" {
params: v2::CodexAvatarAdminAwardGrantParams,
response: v2::CodexAvatarInventoryReadResponse,
},
AvatarAdminCapabilitiesRead => "avatar/admin/capabilities/read" {
params: v2::CodexAvatarAdminCapabilitiesReadParams,
response: v2::CodexAvatarAdminCapabilitiesReadResponse,
},
FeedbackUpload => "feedback/upload" {
params: v2::FeedbackUploadParams,
response: v2::FeedbackUploadResponse,
@@ -1565,6 +1575,60 @@ mod tests {
Ok(())
}
#[test]
fn serialize_avatar_admin_award() -> Result<()> {
let request = ClientRequest::AvatarAdminAward {
request_id: RequestId::Integer(9),
params: v2::CodexAvatarAdminAwardGrantParams {
account_user_id: "target-user-123".to_string(),
award_id: "manual-grant-1".to_string(),
avatar_id: "prism".to_string(),
source_type: "manual-admin-grant".to_string(),
source_ref: Some("support-ticket-1".to_string()),
awarded_at: Some(123),
awarded_by: Some("admin-user".to_string()),
metadata_json: Some("{\"reason\":\"support\"}".to_string()),
source_summary: Some("Manual support grant".to_string()),
},
};
assert_eq!(
json!({
"method": "avatar/admin/award",
"id": 9,
"params": {
"accountUserId": "target-user-123",
"awardId": "manual-grant-1",
"avatarId": "prism",
"sourceType": "manual-admin-grant",
"sourceRef": "support-ticket-1",
"awardedAt": 123,
"awardedBy": "admin-user",
"metadataJson": "{\"reason\":\"support\"}",
"sourceSummary": "Manual support grant"
}
}),
serde_json::to_value(&request)?,
);
Ok(())
}
#[test]
fn serialize_avatar_admin_capabilities_read() -> Result<()> {
let request = ClientRequest::AvatarAdminCapabilitiesRead {
request_id: RequestId::Integer(10),
params: v2::CodexAvatarAdminCapabilitiesReadParams::default(),
};
assert_eq!(
json!({
"method": "avatar/admin/capabilities/read",
"id": 10,
"params": {}
}),
serde_json::to_value(&request)?,
);
Ok(())
}
#[test]
fn account_serializes_fields_in_camel_case() -> Result<()> {
let api_key = v2::Account::ApiKey {};
@@ -1810,6 +1810,38 @@ pub struct CodexAvatarEquipParams {
pub avatar_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarAdminAwardGrantParams {
pub account_user_id: String,
pub award_id: String,
pub avatar_id: String,
pub source_type: String,
#[ts(optional = nullable)]
pub source_ref: Option<String>,
#[ts(optional = nullable)]
pub awarded_at: Option<i64>,
#[ts(optional = nullable)]
pub awarded_by: Option<String>,
#[ts(optional = nullable)]
pub metadata_json: Option<String>,
#[ts(optional = nullable)]
pub source_summary: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarAdminCapabilitiesReadParams {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct CodexAvatarAdminCapabilitiesReadResponse {
pub can_grant_awards: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
+50 -1
View File
@@ -1,5 +1,7 @@
use crate::error_code::INTERNAL_ERROR_CODE;
use crate::error_code::INVALID_REQUEST_ERROR_CODE;
use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams;
use codex_app_server_protocol::CodexAvatarAdminCapabilitiesReadResponse;
use codex_app_server_protocol::CodexAvatarDefinition;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexAvatarInventoryReadResponse;
@@ -8,6 +10,8 @@ use codex_app_server_protocol::CodexAvatarRarity;
use codex_app_server_protocol::CodexAvatarStatus;
use codex_app_server_protocol::JSONRPCErrorError;
use codex_backend_client::Client as BackendClient;
use codex_backend_client::CodexAvatarAdminAwardGrantRequest as BackendAvatarAdminAwardGrantRequest;
use codex_backend_client::CodexAvatarAdminCapabilitiesResponse as BackendAvatarAdminCapabilitiesResponse;
use codex_backend_client::CodexAvatarDefinition as BackendAvatarDefinition;
use codex_backend_client::CodexAvatarInventoryResponse as BackendAvatarInventoryResponse;
use codex_backend_client::CodexAvatarOwnership as BackendAvatarOwnership;
@@ -42,6 +46,41 @@ pub(crate) async fn equip_avatar(
Ok(map_avatar_inventory_response(response))
}
pub(crate) async fn grant_admin_avatar_award(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
params: CodexAvatarAdminAwardGrantParams,
) -> Result<CodexAvatarInventoryReadResponse, JSONRPCErrorError> {
let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?;
let response = client
.grant_admin_avatar_award(BackendAvatarAdminAwardGrantRequest {
account_user_id: params.account_user_id,
award_id: params.award_id,
avatar_id: params.avatar_id,
source_type: params.source_type,
source_ref: params.source_ref,
awarded_at: params.awarded_at,
awarded_by: params.awarded_by,
metadata_json: params.metadata_json,
source_summary: params.source_summary,
})
.await
.map_err(|err| backend_avatar_error("grant avatar award", err))?;
Ok(map_avatar_inventory_response(response))
}
pub(crate) async fn read_avatar_admin_capabilities(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
) -> Result<CodexAvatarAdminCapabilitiesReadResponse, JSONRPCErrorError> {
let client = avatar_backend_client(auth_manager, chatgpt_base_url).await?;
let response = client
.get_avatar_admin_capabilities()
.await
.map_err(|err| backend_avatar_error("read avatar admin capabilities", err))?;
Ok(map_avatar_admin_capabilities_response(response))
}
async fn avatar_backend_client(
auth_manager: &AuthManager,
chatgpt_base_url: &str,
@@ -71,7 +110,9 @@ async fn avatar_backend_client(
fn backend_avatar_error(action: &str, err: RequestError) -> JSONRPCErrorError {
match &err {
RequestError::UnexpectedStatus { status, body, .. } if status.as_u16() == 400 => {
RequestError::UnexpectedStatus { status, body, .. }
if status.as_u16() == 400 || status.as_u16() == 403 =>
{
JSONRPCErrorError {
code: INVALID_REQUEST_ERROR_CODE,
message: avatar_error_detail(body)
@@ -118,6 +159,14 @@ fn map_avatar_inventory_response(
}
}
fn map_avatar_admin_capabilities_response(
response: BackendAvatarAdminCapabilitiesResponse,
) -> CodexAvatarAdminCapabilitiesReadResponse {
CodexAvatarAdminCapabilitiesReadResponse {
can_grant_awards: response.can_grant_awards,
}
}
fn map_avatar_definition(definition: BackendAvatarDefinition) -> CodexAvatarDefinition {
CodexAvatarDefinition {
avatar_id: definition.avatar_id,
@@ -34,6 +34,7 @@ use codex_app_server_protocol::CancelLoginAccountResponse;
use codex_app_server_protocol::CancelLoginAccountStatus;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::ClientResponse;
use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexErrorInfo as AppServerCodexErrorInfo;
use codex_app_server_protocol::CollaborationModeListParams;
@@ -917,6 +918,17 @@ impl CodexMessageProcessor {
self.avatar_equip(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::AvatarAdminAward { request_id, params } => {
self.avatar_admin_award(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::AvatarAdminCapabilitiesRead {
request_id,
params: _,
} => {
self.avatar_admin_capabilities_read(to_connection_request_id(request_id))
.await;
}
ClientRequest::GitDiffToRemote { request_id, params } => {
self.git_diff_to_origin(to_connection_request_id(request_id), params.cwd)
.await;
@@ -1725,6 +1737,43 @@ impl CodexMessageProcessor {
}
}
async fn avatar_admin_award(
&self,
request_id: ConnectionRequestId,
params: CodexAvatarAdminAwardGrantParams,
) {
match avatar_rpc::grant_admin_avatar_award(
&self.auth_manager,
&self.config.chatgpt_base_url,
params,
)
.await
{
Ok(response) => {
self.outgoing.send_response(request_id, response).await;
}
Err(error) => {
self.outgoing.send_error(request_id, error).await;
}
}
}
async fn avatar_admin_capabilities_read(&self, request_id: ConnectionRequestId) {
match avatar_rpc::read_avatar_admin_capabilities(
&self.auth_manager,
&self.config.chatgpt_base_url,
)
.await
{
Ok(response) => {
self.outgoing.send_response(request_id, response).await;
}
Err(error) => {
self.outgoing.send_error(request_id, error).await;
}
}
}
async fn fetch_account_rate_limits(
&self,
) -> Result<
@@ -15,6 +15,7 @@ use codex_app_server_protocol::AppsListParams;
use codex_app_server_protocol::CancelLoginAccountParams;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::ClientNotification;
use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CollaborationModeListParams;
use codex_app_server_protocol::CommandExecParams;
@@ -312,6 +313,22 @@ impl McpProcess {
self.send_request("avatar/equip", params).await
}
/// Send an `avatar/admin/award` JSON-RPC request.
pub async fn send_avatar_admin_award_request(
&mut self,
params: CodexAvatarAdminAwardGrantParams,
) -> anyhow::Result<i64> {
let params = Some(serde_json::to_value(params)?);
self.send_request("avatar/admin/award", params).await
}
/// Send an `avatar/admin/capabilities/read` JSON-RPC request.
pub async fn send_avatar_admin_capabilities_read_request(&mut self) -> anyhow::Result<i64> {
let params = Some(serde_json::json!({}));
self.send_request("avatar/admin/capabilities/read", params)
.await
}
/// Send an `account/login/start` JSON-RPC request with ChatGPT auth tokens.
pub async fn send_chatgpt_auth_tokens_login_request(
&mut self,
+177 -6
View File
@@ -3,6 +3,8 @@ use app_test_support::ChatGptAuthFixture;
use app_test_support::McpProcess;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::CodexAvatarAdminAwardGrantParams;
use codex_app_server_protocol::CodexAvatarAdminCapabilitiesReadResponse;
use codex_app_server_protocol::CodexAvatarDefinition;
use codex_app_server_protocol::CodexAvatarEquipParams;
use codex_app_server_protocol::CodexAvatarInventoryReadResponse;
@@ -23,6 +25,7 @@ use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
@@ -206,6 +209,163 @@ async fn avatar_equip_returns_snapshot_with_clippy_fallback() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn avatar_admin_award_forwards_request_and_returns_target_user_snapshot() -> Result<()> {
let codex_home = TempDir::new()?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
let server = MockServer::start().await;
write_chatgpt_base_url(codex_home.path(), &server.uri())?;
Mock::given(method("POST"))
.and(path("/api/codex/avatars/admin/awards"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.and(body_json(json!({
"accountUserId": "target-user-456",
"awardId": "manual-grant-1",
"avatarId": "prism",
"sourceType": "manual-admin-grant",
"sourceRef": "support-ticket-1",
"awardedAt": 123,
"awardedBy": "admin-user",
"metadataJson": "{\"reason\":\"support\"}",
"sourceSummary": "Manual support grant"
})))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(snapshot_json_for_user("prism", "target-user-456")),
)
.mount(&server)
.await;
let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_avatar_admin_award_request(CodexAvatarAdminAwardGrantParams {
account_user_id: "target-user-456".to_string(),
award_id: "manual-grant-1".to_string(),
avatar_id: "prism".to_string(),
source_type: "manual-admin-grant".to_string(),
source_ref: Some("support-ticket-1".to_string()),
awarded_at: Some(123),
awarded_by: Some("admin-user".to_string()),
metadata_json: Some("{\"reason\":\"support\"}".to_string()),
source_summary: Some("Manual support grant".to_string()),
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let received: CodexAvatarInventoryReadResponse = to_response(response)?;
assert_eq!(
received,
expected_snapshot_for_user("prism", "target-user-456")
);
Ok(())
}
#[tokio::test]
async fn avatar_admin_award_forwards_backend_permission_error() -> Result<()> {
let codex_home = TempDir::new()?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
let server = MockServer::start().await;
write_chatgpt_base_url(codex_home.path(), &server.uri())?;
Mock::given(method("POST"))
.and(path("/api/codex/avatars/admin/awards"))
.respond_with(ResponseTemplate::new(403).set_body_json(json!({
"detail": "Not a Codex admin",
})))
.mount(&server)
.await;
let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_avatar_admin_award_request(CodexAvatarAdminAwardGrantParams {
account_user_id: "target-user-456".to_string(),
award_id: "manual-grant-1".to_string(),
avatar_id: "prism".to_string(),
source_type: "manual-admin-grant".to_string(),
source_ref: None,
awarded_at: None,
awarded_by: None,
metadata_json: None,
source_summary: None,
})
.await?;
let error: JSONRPCError = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.id, RequestId::Integer(request_id));
assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(error.error.message, "Not a Codex admin");
Ok(())
}
#[tokio::test]
async fn avatar_admin_capabilities_read_returns_backend_capability_flags() -> Result<()> {
let codex_home = TempDir::new()?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
let server = MockServer::start().await;
write_chatgpt_base_url(codex_home.path(), &server.uri())?;
Mock::given(method("GET"))
.and(path("/api/codex/avatars/admin/capabilities"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"canGrantAwards": true,
})))
.mount(&server)
.await;
let mut mcp = McpProcess::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp.send_avatar_admin_capabilities_read_request().await?;
let response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let received: CodexAvatarAdminCapabilitiesReadResponse = to_response(response)?;
assert_eq!(
received,
CodexAvatarAdminCapabilitiesReadResponse {
can_grant_awards: true,
}
);
Ok(())
}
fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
@@ -214,8 +374,12 @@ fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<
}
fn snapshot_json(equipped_avatar_id: &str) -> Value {
snapshot_json_for_user(equipped_avatar_id, "account-123")
}
fn snapshot_json_for_user(equipped_avatar_id: &str, account_user_id: &str) -> Value {
json!({
"accountUserId": "account-123",
"accountUserId": account_user_id,
"avatarDefinitions": [
{
"avatarId": "clippy",
@@ -244,14 +408,14 @@ fn snapshot_json(equipped_avatar_id: &str) -> Value {
],
"ownedAvatars": [
{
"accountUserId": "account-123",
"accountUserId": account_user_id,
"avatarId": "clippy",
"firstUnlockedAt": 100,
"lastAwardedAt": 100,
"sourceSummary": "Default avatar",
},
{
"accountUserId": "account-123",
"accountUserId": account_user_id,
"avatarId": "prism",
"firstUnlockedAt": 200,
"lastAwardedAt": 300,
@@ -267,8 +431,15 @@ fn snapshot_json(equipped_avatar_id: &str) -> Value {
}
fn expected_snapshot(equipped_avatar_id: &str) -> CodexAvatarInventoryReadResponse {
expected_snapshot_for_user(equipped_avatar_id, "account-123")
}
fn expected_snapshot_for_user(
equipped_avatar_id: &str,
account_user_id: &str,
) -> CodexAvatarInventoryReadResponse {
CodexAvatarInventoryReadResponse {
account_user_id: "account-123".to_string(),
account_user_id: account_user_id.to_string(),
avatar_definitions: vec![
CodexAvatarDefinition {
avatar_id: "clippy".to_string(),
@@ -297,14 +468,14 @@ fn expected_snapshot(equipped_avatar_id: &str) -> CodexAvatarInventoryReadRespon
],
owned_avatars: vec![
CodexAvatarOwnership {
account_user_id: "account-123".to_string(),
account_user_id: account_user_id.to_string(),
avatar_id: "clippy".to_string(),
first_unlocked_at: 100,
last_awarded_at: 100,
source_summary: Some("Default avatar".to_string()),
},
CodexAvatarOwnership {
account_user_id: "account-123".to_string(),
account_user_id: account_user_id.to_string(),
avatar_id: "prism".to_string(),
first_unlocked_at: 200,
last_awarded_at: 300,
+38
View File
@@ -1,4 +1,6 @@
use crate::types::CodeTaskDetailsResponse;
use crate::types::CodexAvatarAdminAwardGrantRequest;
use crate::types::CodexAvatarAdminCapabilitiesResponse;
use crate::types::CodexAvatarEquipRequest;
use crate::types::CodexAvatarInventoryResponse;
use crate::types::ConfigFileResponse;
@@ -300,6 +302,42 @@ impl Client {
.map_err(RequestError::from)
}
pub async fn grant_admin_avatar_award(
&self,
request_body: CodexAvatarAdminAwardGrantRequest,
) -> std::result::Result<CodexAvatarInventoryResponse, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => format!("{}/api/codex/avatars/admin/awards", self.base_url),
PathStyle::ChatGptApi => format!("{}/wham/avatars/admin/awards", self.base_url),
};
let req = self
.http
.post(&url)
.headers(self.headers())
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.json(&request_body);
let (body, ct) = self.exec_request_detailed(req, "POST", &url).await?;
self.decode_json::<CodexAvatarInventoryResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
pub async fn get_avatar_admin_capabilities(
&self,
) -> std::result::Result<CodexAvatarAdminCapabilitiesResponse, RequestError> {
let url = match self.path_style {
PathStyle::CodexApi => {
format!("{}/api/codex/avatars/admin/capabilities", self.base_url)
}
PathStyle::ChatGptApi => {
format!("{}/wham/avatars/admin/capabilities", self.base_url)
}
};
let req = self.http.get(&url).headers(self.headers());
let (body, ct) = self.exec_request_detailed(req, "GET", &url).await?;
self.decode_json::<CodexAvatarAdminCapabilitiesResponse>(&url, &ct, &body)
.map_err(RequestError::from)
}
pub async fn list_tasks(
&self,
limit: Option<i32>,
+2
View File
@@ -5,6 +5,8 @@ pub use client::Client;
pub use client::RequestError;
pub use types::CodeTaskDetailsResponse;
pub use types::CodeTaskDetailsResponseExt;
pub use types::CodexAvatarAdminAwardGrantRequest;
pub use types::CodexAvatarAdminCapabilitiesResponse;
pub use types::CodexAvatarDefinition;
pub use types::CodexAvatarEquipRequest;
pub use types::CodexAvatarInventoryResponse;
+20
View File
@@ -74,6 +74,20 @@ pub struct CodexAvatarEquipRequest {
pub avatar_id: String,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarAdminAwardGrantRequest {
pub account_user_id: String,
pub award_id: String,
pub avatar_id: String,
pub source_type: String,
pub source_ref: Option<String>,
pub awarded_at: Option<i64>,
pub awarded_by: Option<String>,
pub metadata_json: Option<String>,
pub source_summary: Option<String>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarInventoryResponse {
@@ -87,6 +101,12 @@ pub struct CodexAvatarInventoryResponse {
pub catalog_version: Option<i64>,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CodexAvatarAdminCapabilitiesResponse {
pub can_grant_awards: bool,
}
/// Hand-rolled models for the Cloud Tasks task-details response.
/// The generated OpenAPI models are pretty bad. This is a half-step
/// towards hand-rolling them.
@@ -0,0 +1,376 @@
use codex_app_server_protocol::CodexErrorInfo;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::TurnError;
use codex_backend_client::Client as BackendClient;
use codex_backend_client::WorkspaceOutOfCreditsNotificationStatus;
use codex_core::AuthManager;
use codex_core::CodexAuth;
use codex_core::config::Config;
use codex_protocol::account::PlanType;
use codex_protocol::protocol::RateLimitSnapshot;
use std::io;
use std::io::IsTerminal;
const REQUEST_PROMPT: &str =
"Workspace out of credits. Request more from your workspace owner? [y/N]";
const REQUEST_SENT_MESSAGE: &str = "Request sent!";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PromptDecisionInput {
candidate_usage_limit_failure: bool,
human_output: bool,
stdin_is_tty: bool,
stderr_is_tty: bool,
auth_supports_request: bool,
}
pub(crate) fn notification_is_usage_limit_failure(
notification: &ServerNotification,
thread_id: &str,
turn_id: &str,
) -> bool {
match notification {
ServerNotification::Error(payload) => {
payload.thread_id == thread_id
&& payload.turn_id == turn_id
&& !payload.will_retry
&& turn_error_is_usage_limit(&payload.error)
}
ServerNotification::TurnCompleted(payload) => {
payload.thread_id == thread_id
&& payload.turn.id == turn_id
&& payload.turn.status == codex_app_server_protocol::TurnStatus::Failed
&& payload
.turn
.error
.as_ref()
.is_some_and(turn_error_is_usage_limit)
}
_ => false,
}
}
pub(crate) async fn maybe_prompt_for_workspace_out_of_credits(
config: &Config,
candidate_usage_limit_failure: bool,
human_output: bool,
) -> anyhow::Result<()> {
let stdin_is_tty = io::stdin().is_terminal();
let stderr_is_tty = io::stderr().is_terminal();
let initial_decision = PromptDecisionInput {
candidate_usage_limit_failure,
human_output,
stdin_is_tty,
stderr_is_tty,
auth_supports_request: false,
};
if !terminal_prompt_prerequisites_met(initial_decision) {
return Ok(());
}
let auth_manager = AuthManager::shared(
config.codex_home.clone(),
/*enable_codex_api_key_env*/ true,
config.cli_auth_credentials_store_mode,
);
let auth = auth_manager.auth().await;
let auth_supports_request = auth_supports_workspace_request(auth.as_ref());
let decision = PromptDecisionInput {
auth_supports_request,
..initial_decision
};
if !decision.auth_supports_request {
return Ok(());
}
let Some(auth) = auth else {
return Ok(());
};
let client = BackendClient::from_auth(config.chatgpt_base_url.clone(), &auth)?;
let rate_limits = client.get_rate_limits().await?;
if !should_offer_workspace_out_of_credits_prompt(decision, Some(&rate_limits)) {
return Ok(());
}
if !prompt_for_workspace_request()? {
return Ok(());
}
let response = client.post_workspace_out_of_credits_notification().await?;
match response.status {
WorkspaceOutOfCreditsNotificationStatus::Sent
| WorkspaceOutOfCreditsNotificationStatus::CooldownActive => {
eprintln!("{REQUEST_SENT_MESSAGE}");
}
}
Ok(())
}
fn turn_error_is_usage_limit(error: &TurnError) -> bool {
matches!(
error.codex_error_info,
Some(CodexErrorInfo::UsageLimitExceeded)
)
}
fn terminal_prompt_prerequisites_met(input: PromptDecisionInput) -> bool {
input.candidate_usage_limit_failure
&& input.human_output
&& input.stdin_is_tty
&& input.stderr_is_tty
}
fn auth_supports_workspace_request(auth: Option<&CodexAuth>) -> bool {
auth.is_some_and(|auth| auth.is_chatgpt_auth() && auth.get_account_id().is_some())
}
fn should_offer_workspace_out_of_credits_prompt(
input: PromptDecisionInput,
snapshot: Option<&RateLimitSnapshot>,
) -> bool {
terminal_prompt_prerequisites_met(input)
&& input.auth_supports_request
&& snapshot.is_some_and(rate_limits_confirm_workspace_out_of_credits)
}
fn rate_limits_confirm_workspace_out_of_credits(snapshot: &RateLimitSnapshot) -> bool {
if snapshot.plan_type != Some(PlanType::SelfServeBusinessUsageBased) {
return false;
}
let Some(credits) = snapshot.credits.as_ref() else {
return false;
};
if credits.unlimited {
return false;
}
credits
.balance
.as_deref()
.and_then(parse_credit_balance)
.is_some_and(|balance| balance <= 0.0)
}
fn parse_credit_balance(balance: &str) -> Option<f64> {
balance.trim().parse::<f64>().ok()
}
fn prompt_for_workspace_request() -> io::Result<bool> {
eprintln!("{REQUEST_PROMPT}");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(parse_affirmative_response(&input))
}
fn parse_affirmative_response(input: &str) -> bool {
let answer = input.trim();
answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes")
}
#[cfg(test)]
mod tests {
use super::*;
use codex_app_server_protocol::ErrorNotification;
use codex_app_server_protocol::Turn;
use codex_app_server_protocol::TurnCompletedNotification;
use codex_app_server_protocol::TurnStatus;
use codex_protocol::protocol::CreditsSnapshot;
use pretty_assertions::assert_eq;
fn zero_credit_snapshot() -> RateLimitSnapshot {
RateLimitSnapshot {
limit_id: Some("codex".to_string()),
limit_name: None,
primary: None,
secondary: None,
credits: Some(CreditsSnapshot {
has_credits: false,
unlimited: false,
balance: Some("0".to_string()),
}),
plan_type: Some(PlanType::SelfServeBusinessUsageBased),
}
}
fn usage_limit_turn_error() -> TurnError {
TurnError {
message: "You've hit your usage limit.".to_string(),
codex_error_info: Some(CodexErrorInfo::UsageLimitExceeded),
additional_details: None,
}
}
#[test]
fn error_notification_marks_usage_limit_failure() {
let notification = ServerNotification::Error(ErrorNotification {
error: usage_limit_turn_error(),
will_retry: false,
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
});
assert!(notification_is_usage_limit_failure(
&notification,
"thread-1",
"turn-1"
));
}
#[test]
fn unrelated_notification_does_not_mark_usage_limit_failure() {
let notification = ServerNotification::Error(ErrorNotification {
error: TurnError {
message: "network failed".to_string(),
codex_error_info: Some(CodexErrorInfo::ResponseStreamDisconnected {
http_status_code: Some(503),
}),
additional_details: None,
},
will_retry: false,
thread_id: "thread-1".to_string(),
turn_id: "turn-1".to_string(),
});
assert!(!notification_is_usage_limit_failure(
&notification,
"thread-1",
"turn-1"
));
}
#[test]
fn failed_turn_marks_usage_limit_failure() {
let notification = ServerNotification::TurnCompleted(TurnCompletedNotification {
thread_id: "thread-1".to_string(),
turn: Turn {
id: "turn-1".to_string(),
items: Vec::new(),
status: TurnStatus::Failed,
error: Some(usage_limit_turn_error()),
},
});
assert!(notification_is_usage_limit_failure(
&notification,
"thread-1",
"turn-1"
));
}
#[test]
fn prompt_decision_requires_ttys_and_human_output() {
let snapshot = zero_credit_snapshot();
let input = PromptDecisionInput {
candidate_usage_limit_failure: true,
human_output: false,
stdin_is_tty: true,
stderr_is_tty: true,
auth_supports_request: true,
};
assert!(!should_offer_workspace_out_of_credits_prompt(
input,
Some(&snapshot)
));
}
#[test]
fn prompt_decision_requires_supported_auth() {
let snapshot = zero_credit_snapshot();
let input = PromptDecisionInput {
candidate_usage_limit_failure: true,
human_output: true,
stdin_is_tty: true,
stderr_is_tty: true,
auth_supports_request: false,
};
assert!(!should_offer_workspace_out_of_credits_prompt(
input,
Some(&snapshot)
));
}
#[test]
fn workspace_out_of_credits_confirmation_requires_zero_balance() {
assert!(rate_limits_confirm_workspace_out_of_credits(
&zero_credit_snapshot()
));
}
#[test]
fn workspace_out_of_credits_confirmation_rejects_missing_balance() {
let mut snapshot = zero_credit_snapshot();
snapshot.credits.as_mut().expect("credits").balance = None;
assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot));
}
#[test]
fn workspace_out_of_credits_confirmation_rejects_positive_balance() {
let mut snapshot = zero_credit_snapshot();
snapshot.credits.as_mut().expect("credits").balance = Some("12.5".to_string());
assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot));
}
#[test]
fn workspace_out_of_credits_confirmation_rejects_wrong_plan() {
let mut snapshot = zero_credit_snapshot();
snapshot.plan_type = Some(PlanType::Team);
assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot));
}
#[test]
fn workspace_out_of_credits_confirmation_rejects_unlimited_credits() {
let mut snapshot = zero_credit_snapshot();
snapshot.credits = Some(CreditsSnapshot {
has_credits: true,
unlimited: true,
balance: Some("0".to_string()),
});
assert!(!rate_limits_confirm_workspace_out_of_credits(&snapshot));
}
#[test]
fn chatgpt_auth_with_account_id_is_supported() {
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
assert!(auth_supports_workspace_request(Some(&auth)));
}
#[test]
fn api_key_auth_is_not_supported() {
let auth = CodexAuth::from_api_key("test-key");
assert!(!auth_supports_workspace_request(Some(&auth)));
}
#[test]
fn affirmative_response_accepts_y_and_yes() {
assert!(parse_affirmative_response("y"));
assert!(parse_affirmative_response("YES"));
assert!(!parse_affirmative_response(""));
assert!(!parse_affirmative_response("n"));
}
#[test]
fn prompt_decision_accepts_usage_limit_zero_credit_case() {
let input = PromptDecisionInput {
candidate_usage_limit_failure: true,
human_output: true,
stdin_is_tty: true,
stderr_is_tty: true,
auth_supports_request: true,
};
assert_eq!(
should_offer_workspace_out_of_credits_prompt(input, Some(&zero_credit_snapshot())),
true
);
}
}