mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Show estimated thread usage in /status (#38281)
## What changed - Extend `account/usage/read` with an optional `threadId` request and a backward-compatible `threadUsage` response containing estimated credits, optional USD cost, and model, reasoning, speed, and token breakdowns. - Fetch thread usage for eligible Business and Enterprise plans when `/status` is opened, then update the rendered status card asynchronously. - Preserve terminal scrollback when replacing a visible status-card tail, and append a refreshed card when the original tail can no longer be updated. ## Testing - Add app-server coverage for authentication, canonical thread IDs, unavailable billing routes, and malformed IDs. - Add TUI coverage for usage formatting, stale responses, retries, history updates, terminal reflow, and scrollback preservation. GitOrigin-RevId: 49300914b3fba917c0f08e8595363e04e5ba6d37
This commit is contained in:
1 parent
27a98dde4d
commit
f1a1fce26a
55 files changed
+2903
-60
No files matched your search
@@ -111,6 +111,10 @@ impl App {
|
||||
return;
|
||||
}
|
||||
ServerNotification::AccountUpdated(notification) => {
|
||||
// Deferred terminal writes must never carry the previous account's billing into
|
||||
// the newly authenticated identity, even when both accounts share one thread.
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
let has_codex_backend_auth = matches!(
|
||||
notification.auth_mode,
|
||||
Some(
|
||||
|
||||
@@ -8,18 +8,20 @@ use super::plugin_mentions::fetch_plugin_mentions;
|
||||
use super::*;
|
||||
use crate::app_event::ConnectorsSnapshot;
|
||||
use crate::app_info::app_info_from_api;
|
||||
use crate::chatwidget::ThreadUsageOutcome;
|
||||
use crate::config_update::format_config_error;
|
||||
use codex_app_server_protocol::AppsListParams;
|
||||
use codex_app_server_protocol::AppsListResponse;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageParams;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageResponse;
|
||||
use codex_app_server_protocol::MarketplaceAddParams;
|
||||
use codex_app_server_protocol::MarketplaceAddResponse;
|
||||
use codex_app_server_protocol::MarketplaceRemoveParams;
|
||||
use codex_app_server_protocol::MarketplaceRemoveResponse;
|
||||
use codex_app_server_protocol::MarketplaceUpgradeParams;
|
||||
use codex_app_server_protocol::MarketplaceUpgradeResponse;
|
||||
|
||||
use codex_app_server_protocol::RequestId;
|
||||
|
||||
use crate::hooks_rpc::fetch_hooks_list;
|
||||
@@ -29,6 +31,8 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
const TOKEN_ACTIVITY_FETCH_TIMEOUT: std::time::Duration =
|
||||
std::time::Duration::from_secs(/*secs*/ 15);
|
||||
const THREAD_USAGE_FETCH_TIMEOUT: std::time::Duration =
|
||||
std::time::Duration::from_secs(/*secs*/ 65);
|
||||
const RATE_LIMIT_RESET_REQUEST_TIMEOUT: std::time::Duration =
|
||||
std::time::Duration::from_secs(/*secs*/ 15);
|
||||
const WORKSPACE_HEADLINE_FETCH_TIMEOUT: std::time::Duration =
|
||||
@@ -124,6 +128,30 @@ impl App {
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn refresh_thread_usage(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
request_id: u64,
|
||||
) {
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = tokio::time::timeout(
|
||||
THREAD_USAGE_FETCH_TIMEOUT,
|
||||
fetch_thread_usage(request_handle, thread_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "thread usage request timed out in TUI".to_string())
|
||||
.and_then(|result| result.map_err(|err| err.to_string()));
|
||||
app_event_tx.send(AppEvent::ThreadUsageLoaded {
|
||||
thread_id,
|
||||
request_id,
|
||||
result,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn consume_rate_limit_reset_credit(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
@@ -783,6 +811,26 @@ pub(super) async fn fetch_account_token_activity(
|
||||
.wrap_err("account/usage/read failed in TUI")
|
||||
}
|
||||
|
||||
async fn fetch_thread_usage(
|
||||
request_handle: AppServerRequestHandle,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<ThreadUsageOutcome> {
|
||||
let request_id = RequestId::String(format!("thread-usage-{}", Uuid::new_v4()));
|
||||
let response: GetAccountTokenUsageResponse = request_handle
|
||||
.request_typed(ClientRequest::GetAccountTokenUsage {
|
||||
request_id,
|
||||
params: Some(GetAccountTokenUsageParams {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
}),
|
||||
})
|
||||
.await
|
||||
.wrap_err("account/usage/read failed for thread usage in TUI")?;
|
||||
Ok(response
|
||||
.thread_usage
|
||||
.map(ThreadUsageOutcome::Available)
|
||||
.unwrap_or(ThreadUsageOutcome::Disabled))
|
||||
}
|
||||
|
||||
pub(super) async fn consume_rate_limit_reset_credit_request(
|
||||
request_handle: AppServerRequestHandle,
|
||||
idempotency_key: String,
|
||||
@@ -1285,11 +1333,79 @@ pub(super) fn mcp_inventory_maps_from_statuses(statuses: Vec<McpServerStatus>) -
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use app_test_support::ChatGptAuthFixture;
|
||||
use app_test_support::write_chatgpt_auth;
|
||||
use codex_app_server_protocol::PluginMarketplaceEntry;
|
||||
use codex_app_server_protocol::ThreadUsage;
|
||||
use codex_config::types::AuthCredentialsStoreMode;
|
||||
use codex_protocol::mcp::Tool;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fetch_thread_usage_uses_app_server_auth_after_persisted_account_changes() {
|
||||
let mut app = make_test_app().await;
|
||||
let server = wiremock::MockServer::start().await;
|
||||
let thread_id = ThreadId::new();
|
||||
app.config.chatgpt_base_url = server.uri();
|
||||
app.config.cli_auth_credentials_store_mode = AuthCredentialsStoreMode::File;
|
||||
write_chatgpt_auth(
|
||||
app.config.codex_home.as_path(),
|
||||
ChatGptAuthFixture::new("chatgpt-token").account_id("account-123"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)
|
||||
.expect("write ChatGPT authentication");
|
||||
let app_server = crate::start_embedded_app_server_for_picker(&app.config)
|
||||
.await
|
||||
.expect("start authenticated embedded app server");
|
||||
write_chatgpt_auth(
|
||||
app.config.codex_home.as_path(),
|
||||
ChatGptAuthFixture::new("different-token").account_id("different-account"),
|
||||
AuthCredentialsStoreMode::File,
|
||||
)
|
||||
.expect("replace persisted ChatGPT authentication");
|
||||
|
||||
wiremock::Mock::given(wiremock::matchers::method("POST"))
|
||||
.and(wiremock::matchers::path(
|
||||
"/api/codex/usage/thread_usage/query",
|
||||
))
|
||||
.and(wiremock::matchers::header(
|
||||
"authorization",
|
||||
"Bearer chatgpt-token",
|
||||
))
|
||||
.and(wiremock::matchers::header(
|
||||
"chatgpt-account-id",
|
||||
"account-123",
|
||||
))
|
||||
.and(wiremock::matchers::body_json(serde_json::json!({
|
||||
"thread_ids": [thread_id.to_string()]
|
||||
})))
|
||||
.respond_with(wiremock::ResponseTemplate::new(/*s*/ 200).set_body_json(
|
||||
serde_json::json!({
|
||||
"threads": [{
|
||||
"thread_id": thread_id.to_string(),
|
||||
"estimated_usage_credits_micros": 46_000_000,
|
||||
"estimated_usage_usd_micros": 1_820_000
|
||||
}]
|
||||
}),
|
||||
))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
fetch_thread_usage(app_server.request_handle(), thread_id)
|
||||
.await
|
||||
.expect("read thread usage through the authenticated app server"),
|
||||
ThreadUsageOutcome::Available(ThreadUsage {
|
||||
thread_id: thread_id.to_string(),
|
||||
estimated_usage_credits_micros: 46_000_000,
|
||||
estimated_usage_usd_micros: Some(1_820_000),
|
||||
groups: Vec::new(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn test_absolute_path(path: &str) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::try_from(PathBuf::from(path)).expect("absolute test path")
|
||||
}
|
||||
|
||||
@@ -983,6 +983,12 @@ impl App {
|
||||
AppEvent::RefreshTokenActivity { request_id } => {
|
||||
self.refresh_token_activity(app_server, request_id);
|
||||
}
|
||||
AppEvent::RefreshThreadUsage {
|
||||
thread_id,
|
||||
request_id,
|
||||
} => {
|
||||
self.refresh_thread_usage(app_server, thread_id, request_id);
|
||||
}
|
||||
AppEvent::RefreshStatusLineWorkspaceHeadline { request_id } => {
|
||||
self.refresh_status_line_workspace_headline(app_server, request_id);
|
||||
}
|
||||
@@ -1208,6 +1214,13 @@ impl App {
|
||||
self.insert_pending_usage_output_if_ready(tui);
|
||||
}
|
||||
}
|
||||
AppEvent::ThreadUsageLoaded {
|
||||
thread_id,
|
||||
request_id,
|
||||
result,
|
||||
} => {
|
||||
self.finish_thread_usage_refresh(tui, thread_id, request_id, result)?;
|
||||
}
|
||||
AppEvent::CommitPendingUsageOutput => {
|
||||
self.insert_pending_usage_output_if_ready(tui);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,22 @@
|
||||
//! state, and resetting transcript-related app state after `/clear` or Ctrl-L.
|
||||
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use std::sync::Weak;
|
||||
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app.";
|
||||
|
||||
pub(super) struct RenderedHistoryTail {
|
||||
pub(super) cell: Weak<dyn HistoryCell>,
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
pub(super) struct ThreadUsageStatusHistory {
|
||||
thread_id: ThreadId,
|
||||
pub(super) cell: Weak<dyn HistoryCell>,
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn insert_history_cell(&mut self, tui: &mut tui::Tui, cell: Box<dyn HistoryCell>) {
|
||||
let cell: Arc<dyn HistoryCell> = cell.into();
|
||||
@@ -15,26 +28,155 @@ impl App {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
self.transcript_cells.push(cell.clone());
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
let lines =
|
||||
cell.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
|
||||
if cell.as_any().is::<history_cell::CompositeHistoryCell>()
|
||||
&& lines.first().is_some_and(|line| {
|
||||
line.line.spans.len() == 1 && line.line.spans[0].content.as_ref() == "/status"
|
||||
})
|
||||
&& let Some(thread_id) = self.chat_widget.thread_id()
|
||||
{
|
||||
self.last_thread_usage_status_cell = Some(ThreadUsageStatusHistory {
|
||||
thread_id,
|
||||
cell: Arc::downgrade(&cell),
|
||||
lines: lines.clone(),
|
||||
});
|
||||
}
|
||||
if self.initial_history_replay_buffer.as_ref().is_some() {
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = None;
|
||||
} else {
|
||||
self.insert_history_cell_lines(
|
||||
tui,
|
||||
cell.as_ref(),
|
||||
self.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width),
|
||||
);
|
||||
self.insert_history_cell_lines(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = if self.overlay.is_none() && !lines.is_empty() {
|
||||
Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&cell),
|
||||
lines,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
// A committed cell can unblock a settled /usage card that was waiting
|
||||
// behind a transient active cell or a provisional stream tail.
|
||||
self.chat_widget.request_pending_usage_output_insertion();
|
||||
}
|
||||
|
||||
pub(super) fn finish_thread_usage_refresh(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
thread_id: ThreadId,
|
||||
request_id: u64,
|
||||
result: std::result::Result<crate::chatwidget::ThreadUsageOutcome, String>,
|
||||
) -> Result<()> {
|
||||
let may_update_status = match &result {
|
||||
Ok(crate::chatwidget::ThreadUsageOutcome::Available(usage)) => {
|
||||
usage.thread_id == thread_id.to_string()
|
||||
}
|
||||
Ok(crate::chatwidget::ThreadUsageOutcome::Disabled) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
if !self
|
||||
.chat_widget
|
||||
.finish_thread_usage_refresh(thread_id, request_id, result)
|
||||
|| !may_update_status
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if self.overlay.is_some() || self.initial_history_replay_buffer.is_some() {
|
||||
self.pending_thread_usage_history_refresh = true;
|
||||
return Ok(());
|
||||
}
|
||||
self.refresh_thread_usage_history_tail(tui)
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_thread_usage_history_tail(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
let Some(status_history) = self.last_thread_usage_status_cell.as_ref() else {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
if self.chat_widget.thread_id() != Some(status_history.thread_id) {
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(status_cell) = status_history.cell.upgrade() else {
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
let updated_lines = status_cell
|
||||
.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
|
||||
if updated_lines == status_history.lines {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(rendered_tail) = self.last_rendered_history_tail.as_ref() else {
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
if !rendered_tail
|
||||
.cell
|
||||
.upgrade()
|
||||
.is_some_and(|cell| Arc::ptr_eq(&cell, &status_cell))
|
||||
{
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let prefix_len = rendered_tail
|
||||
.lines
|
||||
.iter()
|
||||
.zip(&updated_lines)
|
||||
.take_while(|(previous, updated)| previous == updated)
|
||||
.count();
|
||||
if prefix_len == rendered_tail.lines.len() && prefix_len == updated_lines.len() {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let wrap_policy = self.history_line_wrap_policy();
|
||||
if !tui.replace_visible_history_tail(
|
||||
&rendered_tail.lines[prefix_len..],
|
||||
&updated_lines[prefix_len..],
|
||||
wrap_policy,
|
||||
)? {
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
}
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn pending_usage_output_insertion_blocked(&self) -> bool {
|
||||
self.chat_widget.usage_history_insertion_blocked()
|
||||
|| self
|
||||
@@ -165,6 +307,9 @@ impl App {
|
||||
pub(super) fn reset_transcript_state_after_clear(&mut self) {
|
||||
self.overlay = None;
|
||||
self.transcript_cells.clear();
|
||||
self.last_rendered_history_tail = None;
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
self.deferred_history_lines.clear();
|
||||
self.has_emitted_history_lines = false;
|
||||
self.transcript_reflow.clear();
|
||||
|
||||
@@ -81,6 +81,7 @@ impl App {
|
||||
pub(super) fn reset_history_emission_state(&mut self) {
|
||||
self.has_emitted_history_lines = false;
|
||||
self.deferred_history_lines.clear();
|
||||
self.last_rendered_history_tail = None;
|
||||
}
|
||||
|
||||
fn display_lines_for_history_insert(
|
||||
@@ -179,6 +180,11 @@ impl App {
|
||||
retained_lines,
|
||||
self.history_line_wrap_policy(),
|
||||
);
|
||||
if self.pending_thread_usage_history_refresh
|
||||
&& let Err(err) = self.refresh_thread_usage_history_tail(tui)
|
||||
{
|
||||
tracing::warn!(error = %err, "failed to refresh thread usage after initial replay");
|
||||
}
|
||||
self.request_scrollback_history_top_up(retained_rows);
|
||||
}
|
||||
|
||||
@@ -480,6 +486,25 @@ impl App {
|
||||
self.history_line_wrap_policy(),
|
||||
);
|
||||
}
|
||||
self.last_rendered_history_tail =
|
||||
self.transcript_cells
|
||||
.last()
|
||||
.map(|cell| super::history_ui::RenderedHistoryTail {
|
||||
cell: Arc::downgrade(cell),
|
||||
lines: cell.display_hyperlink_lines_for_mode(
|
||||
width,
|
||||
self.chat_widget.history_render_mode(),
|
||||
),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut()
|
||||
&& let Some(cell) = status_history.cell.upgrade()
|
||||
{
|
||||
status_history.lines = cell
|
||||
.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
|
||||
}
|
||||
if self.pending_thread_usage_history_refresh {
|
||||
self.refresh_thread_usage_history_tail(tui)?;
|
||||
}
|
||||
self.request_scrollback_history_top_up(reflowed_rows);
|
||||
|
||||
Ok(terminal_width)
|
||||
|
||||
@@ -33,6 +33,9 @@ pub(super) async fn make_test_app() -> App {
|
||||
runtime_permission_profile_override: None,
|
||||
file_search,
|
||||
transcript_cells: Vec::new(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
|
||||
@@ -14,6 +14,8 @@ mod safety_buffering;
|
||||
mod session_lifecycle_requests;
|
||||
mod session_summary;
|
||||
mod startup;
|
||||
#[path = "tests/thread_usage.rs"]
|
||||
mod thread_usage;
|
||||
#[path = "tests/turn_submission.rs"]
|
||||
mod turn_submission;
|
||||
|
||||
@@ -4801,6 +4803,9 @@ async fn make_test_app() -> App {
|
||||
runtime_permission_profile_override: None,
|
||||
file_search,
|
||||
transcript_cells: Vec::new(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
@@ -4871,6 +4876,9 @@ async fn make_test_app_with_channels() -> (
|
||||
runtime_permission_profile_override: None,
|
||||
file_search,
|
||||
transcript_cells: Vec::new(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
has_emitted_history_lines: false,
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
use super::*;
|
||||
use crate::chatwidget::ThreadUsageOutcome;
|
||||
use codex_app_server_client::AppServerEvent;
|
||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
use codex_app_server_protocol::ThreadUsage;
|
||||
use codex_protocol::account::PlanType;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::layout::Size;
|
||||
|
||||
async fn app_with_pending_thread_usage() -> Result<(App, AppServerSession, tui::Tui, ThreadId, u64)>
|
||||
{
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
let thread_id = ThreadId::new();
|
||||
app.chat_widget.handle_thread_session(test_thread_session(
|
||||
thread_id,
|
||||
test_path_buf("/tmp/project"),
|
||||
));
|
||||
app.chat_widget.update_account_state(
|
||||
/*status_account_display*/ None,
|
||||
Some(PlanType::Business),
|
||||
/*has_chatgpt_account*/ false,
|
||||
/*has_codex_backend_auth*/ true,
|
||||
);
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
let mut app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0, /*y*/ 21, /*width*/ 80, /*height*/ 3,
|
||||
));
|
||||
|
||||
app.chat_widget.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
let initial_status = match app_event_rx.try_recv() {
|
||||
Ok(event @ AppEvent::InsertHistoryCell(_)) => event,
|
||||
other => panic!("expected immediate status card, got {other:?}"),
|
||||
};
|
||||
let request_id = match app_event_rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage {
|
||||
thread_id: requested_thread_id,
|
||||
request_id,
|
||||
}) if requested_thread_id == thread_id => request_id,
|
||||
other => panic!("expected asynchronous thread usage request, got {other:?}"),
|
||||
};
|
||||
app.handle_event(&mut tui, &mut app_server, initial_status)
|
||||
.await?;
|
||||
|
||||
Ok((app, app_server, tui, thread_id, request_id))
|
||||
}
|
||||
|
||||
fn successful_thread_usage(thread_id: ThreadId, request_id: u64) -> AppEvent {
|
||||
AppEvent::ThreadUsageLoaded {
|
||||
thread_id,
|
||||
request_id,
|
||||
result: Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||
thread_id: thread_id.to_string(),
|
||||
estimated_usage_credits_micros: 50_000_000,
|
||||
estimated_usage_usd_micros: Some(1_820_000),
|
||||
groups: Vec::new(),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_history_text(tui: &tui::Tui) -> String {
|
||||
tui.pending_history_lines_for_test()
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
line.line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_updated_with_backend_only_auth_enables_thread_usage() -> Result<()> {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
let thread_id = ThreadId::new();
|
||||
app.chat_widget.handle_thread_session(test_thread_session(
|
||||
thread_id,
|
||||
test_path_buf("/tmp/project"),
|
||||
));
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
let app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated(
|
||||
AccountUpdatedNotification {
|
||||
auth_mode: Some(AuthMode::AgentIdentity),
|
||||
plan_type: Some(PlanType::Business),
|
||||
},
|
||||
))),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(!app.chat_widget.has_chatgpt_account());
|
||||
assert!(app.chat_widget.has_codex_backend_auth());
|
||||
app.chat_widget.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
assert_matches!(app_event_rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
assert_matches!(
|
||||
app_event_rx.try_recv(),
|
||||
Ok(AppEvent::RefreshThreadUsage {
|
||||
thread_id: requested_thread_id,
|
||||
..
|
||||
}) if requested_thread_id == thread_id
|
||||
);
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_thread_usage_updates_status_without_scrollback_reflow() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
assert!(pending_history_text(&tui).contains("/status"));
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
assert!(
|
||||
tui.pending_history_lines_for_test().is_empty(),
|
||||
"a visible status tail should be replaced directly instead of appending a duplicate card"
|
||||
);
|
||||
let status = app
|
||||
.transcript_cells
|
||||
.last()
|
||||
.expect("status card should remain in terminal history");
|
||||
let rendered = lines_to_single_string(&status.display_lines(/*width*/ 90));
|
||||
assert!(rendered.contains("50 credits"), "{rendered}");
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_usage_after_intervening_history_appends_refreshed_status() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec![
|
||||
Line::from("/status"),
|
||||
Line::from("intervening model output"),
|
||||
])),
|
||||
);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let pending = pending_history_text(&tui);
|
||||
assert!(pending.contains("intervening model output"), "{pending}");
|
||||
assert!(pending.contains("50 credits"), "{pending}");
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_thread_usage_after_intervening_history_does_not_duplicate_status() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec![Line::from(
|
||||
"intervening model output",
|
||||
)])),
|
||||
);
|
||||
let pending_before_failure = pending_history_text(&tui);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::ThreadUsageLoaded {
|
||||
thread_id,
|
||||
request_id,
|
||||
result: Err("thread usage request timed out".to_string()),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(pending_history_text(&tui), pending_before_failure);
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_usage_finishing_during_overlay_updates_history_after_close() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
tui.set_alt_screen_enabled(/*enabled*/ false);
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.pending_thread_usage_history_refresh);
|
||||
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
|
||||
assert!(!app.pending_thread_usage_history_refresh);
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
assert!(
|
||||
app.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("updated status should remain the rendered history tail")
|
||||
.lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("50 credits"))
|
||||
);
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_discards_thread_usage_deferred_while_overlay_is_open() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
tui.set_alt_screen_enabled(/*enabled*/ false);
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.pending_thread_usage_history_refresh);
|
||||
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated(
|
||||
AccountUpdatedNotification {
|
||||
auth_mode: Some(AuthMode::AgentIdentity),
|
||||
plan_type: Some(PlanType::Business),
|
||||
},
|
||||
))),
|
||||
)
|
||||
.await;
|
||||
assert!(!app.pending_thread_usage_history_refresh);
|
||||
assert!(app.last_thread_usage_status_cell.is_none());
|
||||
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
|
||||
assert!(!pending_history_text(&tui).contains("50 credits"));
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_reflow_rebases_pending_status_update_to_new_width() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
let original = app
|
||||
.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("initial rendered status")
|
||||
.lines
|
||||
.clone();
|
||||
let screen_size = Size::new(/*width*/ 52, /*height*/ 24);
|
||||
tui.terminal.last_known_screen_size = screen_size;
|
||||
let viewport = Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 21,
|
||||
screen_size.width,
|
||||
/*height*/ 3,
|
||||
);
|
||||
tui.terminal.set_viewport_area(viewport);
|
||||
|
||||
app.reflow_transcript_now(&mut tui, screen_size.into())?;
|
||||
|
||||
let resized = app
|
||||
.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("resized rendered status")
|
||||
.lines
|
||||
.clone();
|
||||
assert_ne!(original, resized);
|
||||
// Bazel tests run without a TTY, so model the settled viewport explicitly
|
||||
// before simulating an asynchronous usage update after resize replay.
|
||||
tui.terminal.set_viewport_area(viewport);
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user