mirror of
https://github.com/openai/codex.git
synced 2026-11-18 23:02:23 +00:00
Add thread usage to TUI status surfaces (#38282)
## What changed - Add `thread-credits` and `estimated-thread-cost` items to the configurable status line and terminal title for Enterprise workspaces. - Fetch one shared thread usage estimate only when either item is selected, omit unavailable values, and refresh the display after turns complete. - Preserve the last nonzero estimate while usage settles, with bounded delayed refreshes and retries for transient failures. ## Testing - Add coverage for configuration, rendering, previews, plan availability, replay handling, retries, and post-turn settlement. GitOrigin-RevId: dd69ee621c5bca0e5d9edd32b2bba42487eb1500
This commit is contained in:
1 parent
f1a1fce26a
commit
1e71e35df6
19 files changed
+2282
-4
No files matched your search
@@ -134,6 +134,8 @@ fn terminal_title_item_id(item: &str) -> Option<&'static str> {
|
|||||||
"context-used" | "context-usage" => Some("context-used"),
|
"context-used" | "context-usage" => Some("context-used"),
|
||||||
"five-hour-limit" => Some("five-hour-limit"),
|
"five-hour-limit" => Some("five-hour-limit"),
|
||||||
"weekly-limit" => Some("weekly-limit"),
|
"weekly-limit" => Some("weekly-limit"),
|
||||||
|
"thread-credits" => Some("thread-credits"),
|
||||||
|
"estimated-thread-cost" => Some("estimated-thread-cost"),
|
||||||
"codex-version" => Some("codex-version"),
|
"codex-version" => Some("codex-version"),
|
||||||
"used-tokens" => Some("used-tokens"),
|
"used-tokens" => Some("used-tokens"),
|
||||||
"total-input-tokens" => Some("total-input-tokens"),
|
"total-input-tokens" => Some("total-input-tokens"),
|
||||||
@@ -306,6 +308,27 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn terminal_title_accepts_thread_usage_items() {
|
||||||
|
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||||
|
configured_items: Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]),
|
||||||
|
cwd: PathBuf::from("/workspace/project"),
|
||||||
|
project_root: None,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(check.status, CheckStatus::Ok);
|
||||||
|
assert_eq!(check.summary, "terminal title configured");
|
||||||
|
assert!(
|
||||||
|
check.details.contains(
|
||||||
|
&"terminal title items: thread-credits, estimated-thread-cost".to_string()
|
||||||
|
)
|
||||||
|
);
|
||||||
|
assert!(check.issues.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn terminal_title_omits_project_when_project_item_is_not_selected() {
|
fn terminal_title_omits_project_when_project_item_is_not_selected() {
|
||||||
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
let check = terminal_title_check_from_inputs(TerminalTitleInputs {
|
||||||
|
|||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/bottom_pane/status_line_setup.rs
|
||||||
|
expression: "render_lines(&view, 100)"
|
||||||
|
---
|
||||||
|
|
||||||
|
Configure Status Line
|
||||||
|
Select which items to display in the status line.
|
||||||
|
|
||||||
|
Type to search
|
||||||
|
>
|
||||||
|
› [x] Use theme colors Apply colors from the active /theme
|
||||||
|
───────────────────────
|
||||||
|
[x] thread-credits Estimated current-thread credits (Enterprise workspaces only; omitte…
|
||||||
|
[x] estimated-thread-cost Estimated current-thread cost in USD (Enterprise workspaces only; om…
|
||||||
|
[ ] model Current model name
|
||||||
|
[ ] model-with-reasoning Current model name with reasoning level
|
||||||
|
[ ] reasoning Current reasoning level
|
||||||
|
[ ] current-dir Current working directory
|
||||||
|
|
||||||
|
5.2 credits · ~$1.82
|
||||||
|
Press space to toggle; ←/→ to move; enter to confirm and close; esc to close
|
||||||
@@ -124,6 +124,12 @@ pub(crate) enum StatusLineItem {
|
|||||||
/// Total output tokens generated.
|
/// Total output tokens generated.
|
||||||
TotalOutputTokens,
|
TotalOutputTokens,
|
||||||
|
|
||||||
|
/// Estimated credits attributed directly to the current enterprise thread.
|
||||||
|
ThreadCredits,
|
||||||
|
|
||||||
|
/// Estimated dollar cost attributed directly to the current enterprise thread.
|
||||||
|
EstimatedThreadCost,
|
||||||
|
|
||||||
/// Full thread UUID.
|
/// Full thread UUID.
|
||||||
#[strum(to_string = "thread-id", serialize = "session-id")]
|
#[strum(to_string = "thread-id", serialize = "session-id")]
|
||||||
SessionId,
|
SessionId,
|
||||||
@@ -182,6 +188,12 @@ impl StatusLineItem {
|
|||||||
StatusLineItem::UsedTokens => "Total tokens used in session (omitted when zero)",
|
StatusLineItem::UsedTokens => "Total tokens used in session (omitted when zero)",
|
||||||
StatusLineItem::TotalInputTokens => "Total input tokens used in session",
|
StatusLineItem::TotalInputTokens => "Total input tokens used in session",
|
||||||
StatusLineItem::TotalOutputTokens => "Total output tokens used in session",
|
StatusLineItem::TotalOutputTokens => "Total output tokens used in session",
|
||||||
|
StatusLineItem::ThreadCredits => {
|
||||||
|
"Estimated current-thread credits (Enterprise workspaces only; omitted when unavailable)"
|
||||||
|
}
|
||||||
|
StatusLineItem::EstimatedThreadCost => {
|
||||||
|
"Estimated current-thread cost in USD (Enterprise workspaces only; omitted when unavailable)"
|
||||||
|
}
|
||||||
StatusLineItem::SessionId => "Current thread identifier (omitted until thread starts)",
|
StatusLineItem::SessionId => "Current thread identifier (omitted until thread starts)",
|
||||||
StatusLineItem::FastMode => "Whether Fast mode is currently active",
|
StatusLineItem::FastMode => "Whether Fast mode is currently active",
|
||||||
StatusLineItem::RawOutput => "Whether raw scrollback mode is active",
|
StatusLineItem::RawOutput => "Whether raw scrollback mode is active",
|
||||||
@@ -219,6 +231,8 @@ impl StatusLineItem {
|
|||||||
StatusLineItem::UsedTokens => StatusSurfacePreviewItem::UsedTokens,
|
StatusLineItem::UsedTokens => StatusSurfacePreviewItem::UsedTokens,
|
||||||
StatusLineItem::TotalInputTokens => StatusSurfacePreviewItem::TotalInputTokens,
|
StatusLineItem::TotalInputTokens => StatusSurfacePreviewItem::TotalInputTokens,
|
||||||
StatusLineItem::TotalOutputTokens => StatusSurfacePreviewItem::TotalOutputTokens,
|
StatusLineItem::TotalOutputTokens => StatusSurfacePreviewItem::TotalOutputTokens,
|
||||||
|
StatusLineItem::ThreadCredits => StatusSurfacePreviewItem::ThreadCredits,
|
||||||
|
StatusLineItem::EstimatedThreadCost => StatusSurfacePreviewItem::EstimatedThreadCost,
|
||||||
StatusLineItem::SessionId => StatusSurfacePreviewItem::SessionId,
|
StatusLineItem::SessionId => StatusSurfacePreviewItem::SessionId,
|
||||||
StatusLineItem::FastMode => StatusSurfacePreviewItem::FastMode,
|
StatusLineItem::FastMode => StatusSurfacePreviewItem::FastMode,
|
||||||
StatusLineItem::RawOutput => StatusSurfacePreviewItem::RawOutput,
|
StatusLineItem::RawOutput => StatusSurfacePreviewItem::RawOutput,
|
||||||
@@ -436,6 +450,19 @@ mod tests {
|
|||||||
"context-remaining"
|
"context-remaining"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn thread_usage_items_are_independently_selectable() {
|
||||||
|
assert_eq!(
|
||||||
|
"thread-credits".parse::<StatusLineItem>(),
|
||||||
|
Ok(StatusLineItem::ThreadCredits)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
"estimated-thread-cost".parse::<StatusLineItem>(),
|
||||||
|
Ok(StatusLineItem::EstimatedThreadCost)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn project_name_is_canonical_and_accepts_legacy_ids() {
|
fn project_name_is_canonical_and_accepts_legacy_ids() {
|
||||||
assert_eq!(StatusLineItem::ProjectRoot.to_string(), "project-name");
|
assert_eq!(StatusLineItem::ProjectRoot.to_string(), "project-name");
|
||||||
@@ -673,6 +700,32 @@ mod tests {
|
|||||||
assert_snapshot!(render_lines(&view, /*width*/ 72));
|
assert_snapshot!(render_lines(&view, /*width*/ 72));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn setup_view_snapshot_includes_thread_usage_items() {
|
||||||
|
let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
|
||||||
|
let view = StatusLineSetupView::new(
|
||||||
|
Some(&[
|
||||||
|
StatusLineItem::ThreadCredits.to_string(),
|
||||||
|
StatusLineItem::EstimatedThreadCost.to_string(),
|
||||||
|
]),
|
||||||
|
/*use_theme_colors*/ true,
|
||||||
|
StatusSurfacePreviewData::from_iter([
|
||||||
|
(
|
||||||
|
StatusLineItem::ThreadCredits.preview_item(),
|
||||||
|
"5.2 credits".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
StatusLineItem::EstimatedThreadCost.preview_item(),
|
||||||
|
"~$1.82".to_string(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
AppEventSender::new(tx_raw),
|
||||||
|
crate::keymap::RuntimeKeymap::defaults().list,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_snapshot!(render_lines(&view, /*width*/ 100));
|
||||||
|
}
|
||||||
|
|
||||||
fn render_lines(view: &StatusLineSetupView, width: u16) -> String {
|
fn render_lines(view: &StatusLineSetupView, width: u16) -> String {
|
||||||
let height = view.desired_height(width);
|
let height = view.desired_height(width);
|
||||||
let area = Rect::new(0, 0, width, height);
|
let area = Rect::new(0, 0, width, height);
|
||||||
|
|||||||
@@ -43,7 +43,9 @@ impl StatusLineAccent {
|
|||||||
| StatusLineItem::ContextWindowSize
|
| StatusLineItem::ContextWindowSize
|
||||||
| StatusLineItem::UsedTokens
|
| StatusLineItem::UsedTokens
|
||||||
| StatusLineItem::TotalInputTokens
|
| StatusLineItem::TotalInputTokens
|
||||||
| StatusLineItem::TotalOutputTokens => Self::Usage,
|
| StatusLineItem::TotalOutputTokens
|
||||||
|
| StatusLineItem::ThreadCredits
|
||||||
|
| StatusLineItem::EstimatedThreadCost => Self::Usage,
|
||||||
StatusLineItem::FiveHourLimit | StatusLineItem::WeeklyLimit => Self::Limit,
|
StatusLineItem::FiveHourLimit | StatusLineItem::WeeklyLimit => Self::Limit,
|
||||||
StatusLineItem::CodexVersion | StatusLineItem::SessionId => Self::Metadata,
|
StatusLineItem::CodexVersion | StatusLineItem::SessionId => Self::Metadata,
|
||||||
StatusLineItem::FastMode | StatusLineItem::RawOutput => Self::Mode,
|
StatusLineItem::FastMode | StatusLineItem::RawOutput => Self::Mode,
|
||||||
@@ -233,6 +235,23 @@ mod tests {
|
|||||||
assert!(!line.spans[2].style.add_modifier.contains(Modifier::DIM));
|
assert!(!line.spans[2].style.add_modifier.contains(Modifier::DIM));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn thread_usage_items_share_an_accent_and_dim_separator() {
|
||||||
|
let line = status_line_from_segments_with_resolver(
|
||||||
|
[
|
||||||
|
(StatusLineItem::ThreadCredits, "5.2 credits".to_string()),
|
||||||
|
(StatusLineItem::EstimatedThreadCost, "~$0.21".to_string()),
|
||||||
|
],
|
||||||
|
/*use_theme_colors*/ true,
|
||||||
|
|_| None,
|
||||||
|
)
|
||||||
|
.expect("thread usage status line");
|
||||||
|
|
||||||
|
assert_eq!(line_text(&line), "5.2 credits · ~$0.21");
|
||||||
|
assert_eq!(line.spans[0].style, line.spans[2].style);
|
||||||
|
assert!(line.spans[1].style.add_modifier.contains(Modifier::DIM));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[allow(clippy::disallowed_methods)]
|
#[allow(clippy::disallowed_methods)]
|
||||||
fn status_line_segments_soften_rgb_theme_styles_without_dimming_text() {
|
fn status_line_segments_soften_rgb_theme_styles_without_dimming_text() {
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ pub(crate) enum StatusSurfacePreviewItem {
|
|||||||
UsedTokens,
|
UsedTokens,
|
||||||
TotalInputTokens,
|
TotalInputTokens,
|
||||||
TotalOutputTokens,
|
TotalOutputTokens,
|
||||||
|
ThreadCredits,
|
||||||
|
EstimatedThreadCost,
|
||||||
SessionId,
|
SessionId,
|
||||||
FastMode,
|
FastMode,
|
||||||
RawOutput,
|
RawOutput,
|
||||||
@@ -60,6 +62,8 @@ impl StatusSurfacePreviewItem {
|
|||||||
StatusSurfacePreviewItem::UsedTokens => "0 used",
|
StatusSurfacePreviewItem::UsedTokens => "0 used",
|
||||||
StatusSurfacePreviewItem::TotalInputTokens => "0 in",
|
StatusSurfacePreviewItem::TotalInputTokens => "0 in",
|
||||||
StatusSurfacePreviewItem::TotalOutputTokens => "0 out",
|
StatusSurfacePreviewItem::TotalOutputTokens => "0 out",
|
||||||
|
StatusSurfacePreviewItem::ThreadCredits => "5.2 credits",
|
||||||
|
StatusSurfacePreviewItem::EstimatedThreadCost => "~$1.82",
|
||||||
StatusSurfacePreviewItem::SessionId => "550e8400-e29b-41d4",
|
StatusSurfacePreviewItem::SessionId => "550e8400-e29b-41d4",
|
||||||
StatusSurfacePreviewItem::FastMode => "Fast on",
|
StatusSurfacePreviewItem::FastMode => "Fast on",
|
||||||
StatusSurfacePreviewItem::RawOutput => "raw output",
|
StatusSurfacePreviewItem::RawOutput => "raw output",
|
||||||
@@ -93,6 +97,8 @@ impl StatusSurfacePreviewItem {
|
|||||||
Self::UsedTokens,
|
Self::UsedTokens,
|
||||||
Self::TotalInputTokens,
|
Self::TotalInputTokens,
|
||||||
Self::TotalOutputTokens,
|
Self::TotalOutputTokens,
|
||||||
|
Self::ThreadCredits,
|
||||||
|
Self::EstimatedThreadCost,
|
||||||
Self::SessionId,
|
Self::SessionId,
|
||||||
Self::FastMode,
|
Self::FastMode,
|
||||||
Self::RawOutput,
|
Self::RawOutput,
|
||||||
|
|||||||
@@ -72,6 +72,10 @@ pub(crate) enum TerminalTitleItem {
|
|||||||
TotalInputTokens,
|
TotalInputTokens,
|
||||||
/// Total output tokens generated.
|
/// Total output tokens generated.
|
||||||
TotalOutputTokens,
|
TotalOutputTokens,
|
||||||
|
/// Estimated credits attributed directly to the current enterprise thread.
|
||||||
|
ThreadCredits,
|
||||||
|
/// Estimated dollar cost attributed directly to the current enterprise thread.
|
||||||
|
EstimatedThreadCost,
|
||||||
/// Full thread UUID.
|
/// Full thread UUID.
|
||||||
#[strum(to_string = "thread-id", serialize = "session-id")]
|
#[strum(to_string = "thread-id", serialize = "session-id")]
|
||||||
SessionId,
|
SessionId,
|
||||||
@@ -118,6 +122,12 @@ impl TerminalTitleItem {
|
|||||||
TerminalTitleItem::UsedTokens => "Total tokens used in session (omitted when zero)",
|
TerminalTitleItem::UsedTokens => "Total tokens used in session (omitted when zero)",
|
||||||
TerminalTitleItem::TotalInputTokens => "Total input tokens used in session",
|
TerminalTitleItem::TotalInputTokens => "Total input tokens used in session",
|
||||||
TerminalTitleItem::TotalOutputTokens => "Total output tokens used in session",
|
TerminalTitleItem::TotalOutputTokens => "Total output tokens used in session",
|
||||||
|
TerminalTitleItem::ThreadCredits => {
|
||||||
|
"Estimated current-thread credits (Enterprise workspaces only; omitted when unavailable)"
|
||||||
|
}
|
||||||
|
TerminalTitleItem::EstimatedThreadCost => {
|
||||||
|
"Estimated current-thread cost (Enterprise workspaces only; omitted when unavailable)"
|
||||||
|
}
|
||||||
TerminalTitleItem::SessionId => {
|
TerminalTitleItem::SessionId => {
|
||||||
"Current thread identifier (omitted until thread starts)"
|
"Current thread identifier (omitted until thread starts)"
|
||||||
}
|
}
|
||||||
@@ -150,6 +160,10 @@ impl TerminalTitleItem {
|
|||||||
TerminalTitleItem::TotalOutputTokens => {
|
TerminalTitleItem::TotalOutputTokens => {
|
||||||
Some(StatusSurfacePreviewItem::TotalOutputTokens)
|
Some(StatusSurfacePreviewItem::TotalOutputTokens)
|
||||||
}
|
}
|
||||||
|
TerminalTitleItem::ThreadCredits => Some(StatusSurfacePreviewItem::ThreadCredits),
|
||||||
|
TerminalTitleItem::EstimatedThreadCost => {
|
||||||
|
Some(StatusSurfacePreviewItem::EstimatedThreadCost)
|
||||||
|
}
|
||||||
TerminalTitleItem::SessionId => Some(StatusSurfacePreviewItem::SessionId),
|
TerminalTitleItem::SessionId => Some(StatusSurfacePreviewItem::SessionId),
|
||||||
TerminalTitleItem::FastMode => Some(StatusSurfacePreviewItem::FastMode),
|
TerminalTitleItem::FastMode => Some(StatusSurfacePreviewItem::FastMode),
|
||||||
TerminalTitleItem::Model => Some(StatusSurfacePreviewItem::Model),
|
TerminalTitleItem::Model => Some(StatusSurfacePreviewItem::Model),
|
||||||
@@ -533,6 +547,17 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn thread_usage_items_are_independently_selectable() {
|
||||||
|
assert_eq!(
|
||||||
|
parse_terminal_title_items(["thread-credits", "estimated-thread-cost"].into_iter()),
|
||||||
|
Some(vec![
|
||||||
|
TerminalTitleItem::ThreadCredits,
|
||||||
|
TerminalTitleItem::EstimatedThreadCost,
|
||||||
|
])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parse_terminal_title_items_accepts_kebab_case_variants() {
|
fn parse_terminal_title_items_accepts_kebab_case_variants() {
|
||||||
let items = parse_terminal_title_items(
|
let items = parse_terminal_title_items(
|
||||||
@@ -553,6 +578,8 @@ mod tests {
|
|||||||
"used-tokens",
|
"used-tokens",
|
||||||
"total-input-tokens",
|
"total-input-tokens",
|
||||||
"total-output-tokens",
|
"total-output-tokens",
|
||||||
|
"thread-credits",
|
||||||
|
"estimated-thread-cost",
|
||||||
"session-id",
|
"session-id",
|
||||||
"fast-mode",
|
"fast-mode",
|
||||||
]
|
]
|
||||||
@@ -577,6 +604,8 @@ mod tests {
|
|||||||
TerminalTitleItem::UsedTokens,
|
TerminalTitleItem::UsedTokens,
|
||||||
TerminalTitleItem::TotalInputTokens,
|
TerminalTitleItem::TotalInputTokens,
|
||||||
TerminalTitleItem::TotalOutputTokens,
|
TerminalTitleItem::TotalOutputTokens,
|
||||||
|
TerminalTitleItem::ThreadCredits,
|
||||||
|
TerminalTitleItem::EstimatedThreadCost,
|
||||||
TerminalTitleItem::SessionId,
|
TerminalTitleItem::SessionId,
|
||||||
TerminalTitleItem::FastMode,
|
TerminalTitleItem::FastMode,
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -1220,6 +1220,7 @@ impl ChatWidget {
|
|||||||
self.refresh_terminal_title();
|
self.refresh_terminal_title();
|
||||||
}
|
}
|
||||||
self.refresh_status_line_if_workspace_headline_due();
|
self.refresh_status_line_if_workspace_headline_due();
|
||||||
|
self.refresh_thread_usage_if_settlement_due();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush_active_cell(&mut self) {
|
fn flush_active_cell(&mut self) {
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ impl ChatWidget {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion;
|
||||||
|
self.thread_usage.replaying_turn_completion = replay_kind.is_some();
|
||||||
let from_replay = replay_kind.is_some();
|
let from_replay = replay_kind.is_some();
|
||||||
let is_resume_initial_replay =
|
let is_resume_initial_replay =
|
||||||
matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages));
|
matches!(replay_kind, Some(ReplayKind::ResumeInitialMessages));
|
||||||
@@ -230,6 +232,7 @@ impl ChatWidget {
|
|||||||
| ServerNotification::AccountLoginCompleted(_) => {}
|
| ServerNotification::AccountLoginCompleted(_) => {}
|
||||||
ServerNotification::ContextCompacted(_) => {}
|
ServerNotification::ContextCompacted(_) => {}
|
||||||
}
|
}
|
||||||
|
self.thread_usage.replaying_turn_completion = was_replaying_turn_completion;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn handle_turn_completed_notification(
|
pub(super) fn handle_turn_completed_notification(
|
||||||
@@ -241,6 +244,8 @@ impl ChatWidget {
|
|||||||
// this TUI already rendered locally. Once that turn ends, another
|
// this TUI already rendered locally. Once that turn ends, another
|
||||||
// client can submit the same text and it still needs its own user cell.
|
// client can submit the same text and it still needs its own user cell.
|
||||||
self.last_rendered_user_message_display = None;
|
self.last_rendered_user_message_display = None;
|
||||||
|
let was_replaying_turn_completion = self.thread_usage.replaying_turn_completion;
|
||||||
|
self.thread_usage.replaying_turn_completion = replay_kind.is_some();
|
||||||
match notification.turn.status {
|
match notification.turn.status {
|
||||||
TurnStatus::Completed => {
|
TurnStatus::Completed => {
|
||||||
let last_agent_message =
|
let last_agent_message =
|
||||||
@@ -311,6 +316,7 @@ impl ChatWidget {
|
|||||||
}
|
}
|
||||||
TurnStatus::InProgress => {}
|
TurnStatus::InProgress => {}
|
||||||
}
|
}
|
||||||
|
self.thread_usage.replaying_turn_completion = was_replaying_turn_completion;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_item_started_notification(
|
fn handle_item_started_notification(
|
||||||
|
|||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/chatwidget/tests/status_and_layout.rs
|
||||||
|
expression: normalized_backend_snapshot(terminal.backend())
|
||||||
|
---
|
||||||
|
" "
|
||||||
|
" "
|
||||||
|
"› Ask Codex to do anything "
|
||||||
|
" "
|
||||||
|
" gpt-5.6-sol default · 5.2 credits · ~$0.21 "
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/chatwidget/tests/status_surface_previews.rs
|
||||||
|
expression: snapshot
|
||||||
|
---
|
||||||
|
status line: 5.2 credits · ~$0.21
|
||||||
|
terminal title: 5.2 credits | ~$0.21
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
source: tui/src/chatwidget/tests/status_surface_previews.rs
|
||||||
|
expression: terminal_title_popup_snapshot(&mut chat)
|
||||||
|
---
|
||||||
|
Configure Terminal Title
|
||||||
|
Select which items to display in the terminal title.
|
||||||
|
|
||||||
|
Type to search
|
||||||
|
>
|
||||||
|
› [x] thread-credits Estimated current-thread credits (Enterprise workspaces only; omitte…
|
||||||
|
[x] estimated-thread-cost Estimated current-thread cost (Enterprise workspaces only; omitted w…
|
||||||
|
[ ] app-name Codex app name
|
||||||
|
[ ] project-name Project name (falls back to current directory name)
|
||||||
|
[ ] current-dir Current working directory
|
||||||
|
[ ] activity Spinner while working, action-required message while blocked.
|
||||||
|
[ ] run-state Compact session run-state text (Ready, Working, Thinking)
|
||||||
|
[ ] thread-title Current thread title, or thread identifier when unnamed
|
||||||
|
|
||||||
|
5.2 credits | ~$1.82
|
||||||
|
Press space to toggle; ←/→ to move; enter to confirm and close; esc to close
|
||||||
@@ -340,6 +340,13 @@ impl ChatWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if self
|
||||||
|
.estimated_thread_usage()
|
||||||
|
.is_some_and(|usage| usage.estimated_usage_usd_micros.is_none())
|
||||||
|
{
|
||||||
|
preview_data.suppress_placeholder(StatusSurfacePreviewItem::EstimatedThreadCost);
|
||||||
|
}
|
||||||
|
|
||||||
preview_data
|
preview_data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ use crate::branch_summary;
|
|||||||
use crate::chatwidget::limit_label_for_window;
|
use crate::chatwidget::limit_label_for_window;
|
||||||
use crate::chatwidget::rate_limits::get_limits_duration;
|
use crate::chatwidget::rate_limits::get_limits_duration;
|
||||||
use crate::legacy_core::config::Config;
|
use crate::legacy_core::config::Config;
|
||||||
|
use crate::status::format_credit_micros;
|
||||||
|
use crate::status::format_estimated_usd_micros;
|
||||||
use crate::status::format_tokens_compact;
|
use crate::status::format_tokens_compact;
|
||||||
use codex_app_server_protocol::AskForApproval;
|
use codex_app_server_protocol::AskForApproval;
|
||||||
use codex_config::ConfigLayerSource;
|
use codex_config::ConfigLayerSource;
|
||||||
@@ -71,6 +73,20 @@ impl StatusSurfaceSelections {
|
|||||||
self.status_line_items
|
self.status_line_items
|
||||||
.contains(&StatusLineItem::WorkspaceHeadline)
|
.contains(&StatusLineItem::WorkspaceHeadline)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn uses_thread_usage(&self) -> bool {
|
||||||
|
self.status_line_items.iter().any(|item| {
|
||||||
|
matches!(
|
||||||
|
item,
|
||||||
|
StatusLineItem::ThreadCredits | StatusLineItem::EstimatedThreadCost
|
||||||
|
)
|
||||||
|
}) || self.terminal_title_items.iter().any(|item| {
|
||||||
|
matches!(
|
||||||
|
item,
|
||||||
|
TerminalTitleItem::ThreadCredits | TerminalTitleItem::EstimatedThreadCost
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cached project-root display name keyed by the cwd used for the last lookup.
|
/// Cached project-root display name keyed by the cwd used for the last lookup.
|
||||||
@@ -172,6 +188,12 @@ impl ChatWidget {
|
|||||||
} else {
|
} else {
|
||||||
self.request_status_line_workspace_headline_if_due(Instant::now());
|
self.request_status_line_workspace_headline_if_due(Instant::now());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if selections.uses_thread_usage() {
|
||||||
|
self.ensure_thread_usage_requested();
|
||||||
|
} else {
|
||||||
|
self.cancel_thread_usage_polling();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn refresh_status_line_from_selections(&mut self, selections: &StatusSurfaceSelections) {
|
fn refresh_status_line_from_selections(&mut self, selections: &StatusSurfaceSelections) {
|
||||||
@@ -727,6 +749,14 @@ impl ChatWidget {
|
|||||||
format_tokens_compact(self.status_line_total_usage().output_tokens)
|
format_tokens_compact(self.status_line_total_usage().output_tokens)
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
|
StatusLineItem::ThreadCredits => self
|
||||||
|
.estimated_thread_usage()
|
||||||
|
.map(|usage| usage.estimated_usage_credits_micros)
|
||||||
|
.map(|credits| format!("{} credits", format_credit_micros(credits))),
|
||||||
|
StatusLineItem::EstimatedThreadCost => self
|
||||||
|
.estimated_thread_usage()
|
||||||
|
.and_then(|usage| usage.estimated_usage_usd_micros)
|
||||||
|
.and_then(format_estimated_usd_micros),
|
||||||
StatusLineItem::SessionId => self.thread_id.map(|id| id.to_string()),
|
StatusLineItem::SessionId => self.thread_id.map(|id| id.to_string()),
|
||||||
StatusLineItem::FastMode => Some(
|
StatusLineItem::FastMode => Some(
|
||||||
if self.current_service_tier() == Some(ServiceTier::Fast.request_value()) {
|
if self.current_service_tier() == Some(ServiceTier::Fast.request_value()) {
|
||||||
@@ -785,6 +815,8 @@ impl ChatWidget {
|
|||||||
StatusSurfacePreviewItem::UsedTokens => StatusLineItem::UsedTokens,
|
StatusSurfacePreviewItem::UsedTokens => StatusLineItem::UsedTokens,
|
||||||
StatusSurfacePreviewItem::TotalInputTokens => StatusLineItem::TotalInputTokens,
|
StatusSurfacePreviewItem::TotalInputTokens => StatusLineItem::TotalInputTokens,
|
||||||
StatusSurfacePreviewItem::TotalOutputTokens => StatusLineItem::TotalOutputTokens,
|
StatusSurfacePreviewItem::TotalOutputTokens => StatusLineItem::TotalOutputTokens,
|
||||||
|
StatusSurfacePreviewItem::ThreadCredits => StatusLineItem::ThreadCredits,
|
||||||
|
StatusSurfacePreviewItem::EstimatedThreadCost => StatusLineItem::EstimatedThreadCost,
|
||||||
StatusSurfacePreviewItem::SessionId => StatusLineItem::SessionId,
|
StatusSurfacePreviewItem::SessionId => StatusLineItem::SessionId,
|
||||||
StatusSurfacePreviewItem::FastMode => StatusLineItem::FastMode,
|
StatusSurfacePreviewItem::FastMode => StatusLineItem::FastMode,
|
||||||
StatusSurfacePreviewItem::RawOutput => StatusLineItem::RawOutput,
|
StatusSurfacePreviewItem::RawOutput => StatusLineItem::RawOutput,
|
||||||
@@ -843,6 +875,12 @@ impl ChatWidget {
|
|||||||
TerminalTitleItem::TotalOutputTokens => self
|
TerminalTitleItem::TotalOutputTokens => self
|
||||||
.status_line_value_for_item(StatusLineItem::TotalOutputTokens)
|
.status_line_value_for_item(StatusLineItem::TotalOutputTokens)
|
||||||
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
||||||
|
TerminalTitleItem::ThreadCredits => self
|
||||||
|
.status_line_value_for_item(StatusLineItem::ThreadCredits)
|
||||||
|
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
||||||
|
TerminalTitleItem::EstimatedThreadCost => self
|
||||||
|
.status_line_value_for_item(StatusLineItem::EstimatedThreadCost)
|
||||||
|
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
||||||
TerminalTitleItem::SessionId => self
|
TerminalTitleItem::SessionId => self
|
||||||
.status_line_value_for_item(StatusLineItem::SessionId)
|
.status_line_value_for_item(StatusLineItem::SessionId)
|
||||||
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
.map(|value| Self::truncate_terminal_title_part(value, /*max_chars*/ 32)),
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::bottom_pane::goal_status_indicator_line;
|
use crate::bottom_pane::goal_status_indicator_line;
|
||||||
|
use crate::chatwidget::ThreadUsageOutcome;
|
||||||
use crate::chatwidget::rate_limits::NUDGE_MODEL_SLUG;
|
use crate::chatwidget::rate_limits::NUDGE_MODEL_SLUG;
|
||||||
use crate::chatwidget::rate_limits::get_limits_duration;
|
use crate::chatwidget::rate_limits::get_limits_duration;
|
||||||
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
use codex_app_server_protocol::SpendControlLimitSnapshot;
|
||||||
|
use codex_app_server_protocol::ThreadUsage;
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use ratatui::backend::TestBackend;
|
use ratatui::backend::TestBackend;
|
||||||
use serial_test::serial;
|
use serial_test::serial;
|
||||||
@@ -2851,6 +2853,632 @@ async fn status_line_legacy_context_usage_renders_context_used_percent() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_fetches_and_renders_backend_estimate() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
|
||||||
|
chat.refresh_status_line();
|
||||||
|
assert_eq!(status_line_text(&chat), None);
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
request_id,
|
||||||
|
}) => {
|
||||||
|
assert_eq!(requested_thread_id, thread_id);
|
||||||
|
request_id
|
||||||
|
}
|
||||||
|
event => panic!("expected estimated thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(status_line_text(&chat), Some("~$1.82".to_string()));
|
||||||
|
assert!(rx.try_recv().is_err(), "idle refresh must not poll");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_thread_credits_fetches_and_renders_fractional_credits() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["thread-credits".to_string()]);
|
||||||
|
|
||||||
|
chat.refresh_status_line();
|
||||||
|
assert_eq!(status_line_text(&chat), None);
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
request_id,
|
||||||
|
}) => {
|
||||||
|
assert_eq!(requested_thread_id, thread_id);
|
||||||
|
request_id
|
||||||
|
}
|
||||||
|
event => panic!("expected thread credits refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_240_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(status_line_text(&chat), Some("5.2 credits".to_string()));
|
||||||
|
assert!(rx.try_recv().is_err(), "idle refresh must not poll");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_thread_credits_and_cost_share_one_backend_request() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected a shared thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(rx.try_recv().is_err(), "both items must share one request");
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
status_line_text(&chat),
|
||||||
|
Some("5.2 credits · ~$0.21".to_string())
|
||||||
|
);
|
||||||
|
assert!(rx.try_recv().is_err(), "idle refresh must not poll");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_thread_credits_remain_visible_when_usd_is_unavailable() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected a shared thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: None,
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(status_line_text(&chat), Some("5.2 credits".to_string()));
|
||||||
|
assert!(
|
||||||
|
rx.try_recv().is_err(),
|
||||||
|
"credits-only estimates must not trigger retries"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn terminal_title_thread_usage_fetches_and_renders_without_status_line() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(Vec::new());
|
||||||
|
chat.config.tui_terminal_title = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
chat.refresh_terminal_title();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
request_id,
|
||||||
|
}) => {
|
||||||
|
assert_eq!(requested_thread_id, thread_id);
|
||||||
|
request_id
|
||||||
|
}
|
||||||
|
event => panic!("expected title-only thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat.last_terminal_title,
|
||||||
|
Some("5.2 credits | ~$0.21".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(status_line_text(&chat), None);
|
||||||
|
assert!(rx.try_recv().is_err(), "title-only refresh must not poll");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn terminal_title_thread_credits_remain_visible_when_usd_is_unavailable() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(Vec::new());
|
||||||
|
chat.config.tui_terminal_title = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
chat.refresh_terminal_title();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected title-only thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: None,
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.last_terminal_title, Some("5.2 credits".to_string()));
|
||||||
|
assert!(
|
||||||
|
rx.try_recv().is_err(),
|
||||||
|
"credits-only title estimates must not trigger retries"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn terminal_title_and_status_line_share_one_thread_usage_request() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.config.tui_terminal_title = Some(vec!["thread-credits".to_string()]);
|
||||||
|
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected a shared title/footer thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
rx.try_recv().is_err(),
|
||||||
|
"title and footer must share one request"
|
||||||
|
);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.last_terminal_title, Some("5.2 credits".to_string()));
|
||||||
|
assert_eq!(status_line_text(&chat), Some("~$0.21".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_avoids_unsupported_plan_requests() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
chat.thread_id = Some(ThreadId::new());
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Pro);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
"run-state".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
assert_eq!(status_line_text(&chat), Some("Ready".to_string()));
|
||||||
|
assert!(
|
||||||
|
rx.try_recv().is_err(),
|
||||||
|
"unsupported plans must not query usage"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_stops_after_backend_disables_feature() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::EnterpriseCbpAutomation);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected estimated thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Disabled),
|
||||||
|
));
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
|
||||||
|
assert_eq!(status_line_text(&chat), None);
|
||||||
|
assert!(rx.try_recv().is_err(), "disabled feature must not retry");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_preserves_cached_amount_during_settlement() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let settlement_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected post-turn thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
settlement_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 0,
|
||||||
|
estimated_usage_usd_micros: Some(0),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(status_line_text(&chat), Some("~$1.82".to_string()));
|
||||||
|
assert!(
|
||||||
|
rx.try_recv().is_err(),
|
||||||
|
"settlement must not poll continuously"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn completed_turn_refreshes_estimated_thread_cost() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.on_task_complete(
|
||||||
|
/*last_agent_message*/ None, /*duration_ms*/ None, /*from_replay*/ false,
|
||||||
|
);
|
||||||
|
|
||||||
|
let request_id = std::iter::from_fn(|| rx.try_recv().ok())
|
||||||
|
.find_map(|event| match event {
|
||||||
|
AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
request_id,
|
||||||
|
} if requested_thread_id == thread_id => Some(request_id),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("completed turns should refresh estimated thread usage");
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 50_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(2_100_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(status_line_text(&chat), Some("~$2.10".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn completed_turn_refreshes_credits_only_terminal_title() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(Vec::new());
|
||||||
|
chat.config.tui_terminal_title = Some(vec!["thread-credits".to_string()]);
|
||||||
|
chat.refresh_terminal_title();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected title-only thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: None,
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.on_task_complete(
|
||||||
|
/*last_agent_message*/ None, /*duration_ms*/ None, /*from_replay*/ false,
|
||||||
|
);
|
||||||
|
|
||||||
|
let request_id = std::iter::from_fn(|| rx.try_recv().ok())
|
||||||
|
.find_map(|event| match event {
|
||||||
|
AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
request_id,
|
||||||
|
} if requested_thread_id == thread_id => Some(request_id),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("completed turns should refresh title-only thread usage");
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 6_200_000,
|
||||||
|
estimated_usage_usd_micros: None,
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(chat.last_terminal_title, Some("6.2 credits".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn interrupted_turn_refreshes_estimated_thread_usage() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.on_interrupted_turn(TurnAbortReason::Interrupted);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
std::iter::from_fn(|| rx.try_recv().ok()).any(|event| {
|
||||||
|
matches!(
|
||||||
|
event,
|
||||||
|
AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
..
|
||||||
|
} if requested_thread_id == thread_id
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
"interrupted turns must refresh estimated thread usage"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failed_turn_refreshes_estimated_thread_usage() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.handle_non_retry_error(
|
||||||
|
"turn failed after generating tokens".to_string(),
|
||||||
|
/*codex_error_info*/ None,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
std::iter::from_fn(|| rx.try_recv().ok()).any(|event| {
|
||||||
|
matches!(
|
||||||
|
event,
|
||||||
|
AppEvent::RefreshThreadUsage {
|
||||||
|
thread_id: requested_thread_id,
|
||||||
|
..
|
||||||
|
} if requested_thread_id == thread_id
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
"failed turns must refresh estimated thread usage"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_rejects_stale_thread_completions() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let previous_thread_id = ThreadId::new();
|
||||||
|
let active_thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(previous_thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let previous_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected previous-thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
chat.thread_id = Some(active_thread_id);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let active_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected active-thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(!chat.finish_thread_usage_refresh(
|
||||||
|
previous_thread_id,
|
||||||
|
previous_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: previous_thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 46_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(1_820_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(status_line_text(&chat), None);
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
active_thread_id,
|
||||||
|
active_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: active_thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 1_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(400),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(status_line_text(&chat), Some("~$0.0004".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_line_estimated_thread_cost_footer_snapshot() {
|
||||||
|
use ratatui::Terminal;
|
||||||
|
use ratatui::backend::TestBackend;
|
||||||
|
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.show_welcome_banner = false;
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"model-with-reasoning".to_string(),
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected estimated thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
let width = 80;
|
||||||
|
let height = chat.desired_height(width);
|
||||||
|
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("create terminal");
|
||||||
|
terminal
|
||||||
|
.draw(|frame| chat.render(frame.area(), frame.buffer_mut()))
|
||||||
|
.expect("draw estimated-thread-cost footer");
|
||||||
|
assert_chatwidget_snapshot!(
|
||||||
|
"status_line_estimated_thread_cost_footer",
|
||||||
|
normalized_backend_snapshot(terminal.backend())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn status_line_workspace_headline_renders_cached_value() {
|
async fn status_line_workspace_headline_renders_cached_value() {
|
||||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::bottom_pane::preview_line_for_title_items;
|
use crate::bottom_pane::preview_line_for_title_items;
|
||||||
|
use crate::chatwidget::ThreadUsageOutcome;
|
||||||
|
use codex_app_server_protocol::ThreadUsage;
|
||||||
use pretty_assertions::assert_eq;
|
use pretty_assertions::assert_eq;
|
||||||
use ratatui::text::Line;
|
use ratatui::text::Line;
|
||||||
|
|
||||||
@@ -233,6 +235,107 @@ async fn status_surface_preview_lines_rate_limits_snapshot() {
|
|||||||
assert_chatwidget_snapshot!("status_surface_previews_rate_limits", snapshot);
|
assert_chatwidget_snapshot!("status_surface_previews_rate_limits", snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_surface_preview_lines_thread_usage_snapshot() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.config.tui_terminal_title = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected shared thread usage preview request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: Some(210_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
let snapshot = combined_preview_snapshot(
|
||||||
|
&mut chat,
|
||||||
|
&[
|
||||||
|
StatusLineItem::ThreadCredits,
|
||||||
|
StatusLineItem::EstimatedThreadCost,
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
TerminalTitleItem::ThreadCredits,
|
||||||
|
TerminalTitleItem::EstimatedThreadCost,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_chatwidget_snapshot!("status_surface_previews_thread_usage", snapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_surface_thread_usage_previews_omit_unavailable_usd_estimates() {
|
||||||
|
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.config.tui_terminal_title = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected shared thread usage preview request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 5_200_000,
|
||||||
|
estimated_usage_usd_micros: None,
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
status_preview_line(
|
||||||
|
&mut chat,
|
||||||
|
&[
|
||||||
|
StatusLineItem::ThreadCredits,
|
||||||
|
StatusLineItem::EstimatedThreadCost,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
"5.2 credits"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
title_preview_line(
|
||||||
|
&mut chat,
|
||||||
|
&[
|
||||||
|
TerminalTitleItem::ThreadCredits,
|
||||||
|
TerminalTitleItem::EstimatedThreadCost,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
"5.2 credits"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn status_surface_preview_omits_unavailable_rate_limit_items() {
|
async fn status_surface_preview_omits_unavailable_rate_limit_items() {
|
||||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
@@ -374,6 +477,20 @@ async fn terminal_title_setup_popup_rate_limits_snapshot() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn terminal_title_setup_popup_thread_usage_snapshot() {
|
||||||
|
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
chat.config.tui_terminal_title = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert_chatwidget_snapshot!(
|
||||||
|
"terminal_title_setup_popup_thread_usage",
|
||||||
|
terminal_title_popup_snapshot(&mut chat)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn missing_project_root_uses_different_status_and_title_preview_sources() {
|
async fn missing_project_root_uses_different_status_and_title_preview_sources() {
|
||||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||||
|
|||||||
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
use super::AppEvent;
|
use super::AppEvent;
|
||||||
use super::ChatWidget;
|
use super::ChatWidget;
|
||||||
|
use super::Duration;
|
||||||
|
use super::Instant;
|
||||||
use super::PlanType;
|
use super::PlanType;
|
||||||
|
use super::StatusLineItem;
|
||||||
|
use super::TerminalTitleItem;
|
||||||
use super::ThreadId;
|
use super::ThreadId;
|
||||||
use crate::status::StatusHistoryHandle;
|
use crate::status::StatusHistoryHandle;
|
||||||
use codex_app_server_protocol::ThreadUsage;
|
use codex_app_server_protocol::ThreadUsage;
|
||||||
@@ -13,14 +17,41 @@ pub(crate) enum ThreadUsageOutcome {
|
|||||||
Disabled,
|
Disabled,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const THREAD_USAGE_SETTLEMENT_DELAYS: [Duration; 3] = [
|
||||||
|
Duration::from_secs(/*secs*/ 15),
|
||||||
|
Duration::from_secs(/*secs*/ 60),
|
||||||
|
Duration::from_secs(/*secs*/ 120),
|
||||||
|
];
|
||||||
|
const THREAD_USAGE_RETRY_DELAYS: [Duration; 3] = [
|
||||||
|
Duration::from_secs(/*secs*/ 5),
|
||||||
|
Duration::from_secs(/*secs*/ 15),
|
||||||
|
Duration::from_secs(/*secs*/ 60),
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct SelectedThreadUsage {
|
||||||
|
credits: bool,
|
||||||
|
estimated_cost: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub(super) struct ThreadUsageState {
|
pub(super) struct ThreadUsageState {
|
||||||
thread_id: Option<ThreadId>,
|
thread_id: Option<ThreadId>,
|
||||||
estimate: Option<ThreadUsage>,
|
estimate: Option<ThreadUsage>,
|
||||||
pending_request_id: Option<u64>,
|
pending_request_id: Option<u64>,
|
||||||
next_request_id: u64,
|
next_request_id: u64,
|
||||||
|
requested: bool,
|
||||||
feature_disabled: bool,
|
feature_disabled: bool,
|
||||||
status_history_handles: Vec<StatusHistoryHandle>,
|
status_history_handles: Vec<StatusHistoryHandle>,
|
||||||
|
status_requested: bool,
|
||||||
|
retry_attempts: usize,
|
||||||
|
retry_due_at: Option<Instant>,
|
||||||
|
settlement_attempts: usize,
|
||||||
|
settlement_baseline_credits_micros: Option<i64>,
|
||||||
|
settlement_baseline_usd_micros: Option<i64>,
|
||||||
|
settlement_request_id: Option<u64>,
|
||||||
|
settlement_refresh_due_at: Option<Instant>,
|
||||||
|
pub(super) replaying_turn_completion: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChatWidget {
|
impl ChatWidget {
|
||||||
@@ -32,6 +63,85 @@ impl ChatWidget {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn ensure_thread_usage_requested(&mut self) {
|
||||||
|
let Some(thread_id) = self.thread_id else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if self.thread_usage.thread_id != Some(thread_id) {
|
||||||
|
self.clear_thread_usage_state();
|
||||||
|
self.thread_usage.thread_id = Some(thread_id);
|
||||||
|
}
|
||||||
|
if self.thread_usage.requested {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.request_thread_usage();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn refresh_thread_usage_after_turn(&mut self) {
|
||||||
|
if self.thread_usage.replaying_turn_completion
|
||||||
|
|| !self.thread_usage_is_selected()
|
||||||
|
|| !self.thread_usage_is_available()
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.thread_usage.settlement_attempts = 0;
|
||||||
|
self.thread_usage.settlement_request_id = None;
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros = Some(
|
||||||
|
self.thread_usage
|
||||||
|
.estimate
|
||||||
|
.as_ref()
|
||||||
|
.map(|estimate| estimate.estimated_usage_credits_micros)
|
||||||
|
.unwrap_or_default(),
|
||||||
|
);
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = self
|
||||||
|
.thread_usage
|
||||||
|
.estimate
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|estimate| estimate.estimated_usage_usd_micros);
|
||||||
|
self.schedule_next_thread_usage_settlement();
|
||||||
|
self.request_thread_usage();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn refresh_thread_usage_if_settlement_due(&mut self) {
|
||||||
|
let now = Instant::now();
|
||||||
|
let settlement_due = self
|
||||||
|
.thread_usage
|
||||||
|
.settlement_refresh_due_at
|
||||||
|
.is_some_and(|due_at| now >= due_at);
|
||||||
|
let retry_due = self
|
||||||
|
.thread_usage
|
||||||
|
.retry_due_at
|
||||||
|
.is_some_and(|due_at| now >= due_at);
|
||||||
|
if !settlement_due && !retry_due {
|
||||||
|
if let Some(next_due_at) = [
|
||||||
|
self.thread_usage.settlement_refresh_due_at,
|
||||||
|
self.thread_usage.retry_due_at,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.min()
|
||||||
|
{
|
||||||
|
self.frame_requester
|
||||||
|
.schedule_frame_in(next_due_at.saturating_duration_since(now));
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.thread_usage_is_selected() {
|
||||||
|
self.cancel_thread_usage_polling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if settlement_due {
|
||||||
|
self.thread_usage.settlement_refresh_due_at = None;
|
||||||
|
}
|
||||||
|
if retry_due {
|
||||||
|
self.thread_usage.retry_due_at = None;
|
||||||
|
}
|
||||||
|
self.request_thread_usage();
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn request_thread_usage_for_status(&mut self, handle: StatusHistoryHandle) {
|
pub(super) fn request_thread_usage_for_status(&mut self, handle: StatusHistoryHandle) {
|
||||||
if !self.thread_usage_is_available() {
|
if !self.thread_usage_is_available() {
|
||||||
return;
|
return;
|
||||||
@@ -46,9 +156,27 @@ impl ChatWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.thread_usage.status_history_handles.push(handle);
|
self.thread_usage.status_history_handles.push(handle);
|
||||||
|
self.thread_usage.status_requested = true;
|
||||||
|
self.thread_usage.retry_attempts = 0;
|
||||||
self.request_thread_usage();
|
self.request_thread_usage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn cancel_thread_usage_polling(&mut self) {
|
||||||
|
if self.thread_usage.status_requested {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.thread_usage.pending_request_id = None;
|
||||||
|
self.thread_usage.requested = false;
|
||||||
|
self.thread_usage.retry_attempts = 0;
|
||||||
|
self.thread_usage.retry_due_at = None;
|
||||||
|
self.thread_usage.settlement_attempts = 0;
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros = None;
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = None;
|
||||||
|
self.thread_usage.settlement_request_id = None;
|
||||||
|
self.thread_usage.settlement_refresh_due_at = None;
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn finish_thread_usage_refresh(
|
pub(crate) fn finish_thread_usage_refresh(
|
||||||
&mut self,
|
&mut self,
|
||||||
thread_id: ThreadId,
|
thread_id: ThreadId,
|
||||||
@@ -64,11 +192,18 @@ impl ChatWidget {
|
|||||||
|
|
||||||
self.thread_usage.pending_request_id = None;
|
self.thread_usage.pending_request_id = None;
|
||||||
let mut usage_updated = false;
|
let mut usage_updated = false;
|
||||||
|
self.thread_usage.status_requested = false;
|
||||||
|
let post_turn_request = self.thread_usage.settlement_request_id == Some(request_id);
|
||||||
match result {
|
match result {
|
||||||
Ok(ThreadUsageOutcome::Disabled) => {
|
Ok(ThreadUsageOutcome::Disabled) => {
|
||||||
self.thread_usage.feature_disabled = true;
|
self.thread_usage.feature_disabled = true;
|
||||||
self.thread_usage.estimate = None;
|
self.thread_usage.estimate = None;
|
||||||
usage_updated = true;
|
usage_updated = true;
|
||||||
|
self.thread_usage.retry_due_at = None;
|
||||||
|
self.thread_usage.settlement_refresh_due_at = None;
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros = None;
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = None;
|
||||||
|
self.thread_usage.settlement_request_id = None;
|
||||||
}
|
}
|
||||||
Ok(ThreadUsageOutcome::Available(usage))
|
Ok(ThreadUsageOutcome::Available(usage))
|
||||||
if usage.thread_id != thread_id.to_string() =>
|
if usage.thread_id != thread_id.to_string() =>
|
||||||
@@ -78,20 +213,112 @@ impl ChatWidget {
|
|||||||
returned_thread_id = %usage.thread_id,
|
returned_thread_id = %usage.thread_id,
|
||||||
"thread usage response referred to another thread"
|
"thread usage response referred to another thread"
|
||||||
);
|
);
|
||||||
|
self.schedule_thread_usage_retry();
|
||||||
}
|
}
|
||||||
Ok(ThreadUsageOutcome::Available(usage)) => {
|
Ok(ThreadUsageOutcome::Available(mut usage)) => {
|
||||||
self.thread_usage.estimate = Some(usage);
|
|
||||||
usage_updated = true;
|
usage_updated = true;
|
||||||
|
self.thread_usage.retry_attempts = 0;
|
||||||
|
self.thread_usage.retry_due_at = None;
|
||||||
|
let previous_positive_credits_micros = self
|
||||||
|
.thread_usage
|
||||||
|
.estimate
|
||||||
|
.as_ref()
|
||||||
|
.map(|estimate| estimate.estimated_usage_credits_micros)
|
||||||
|
.filter(|micros| *micros > 0);
|
||||||
|
let transient_zero_credits = usage.estimated_usage_credits_micros == 0
|
||||||
|
&& previous_positive_credits_micros.is_some();
|
||||||
|
if let Some(previous_positive_credits_micros) = previous_positive_credits_micros
|
||||||
|
&& transient_zero_credits
|
||||||
|
{
|
||||||
|
usage.estimated_usage_credits_micros = previous_positive_credits_micros;
|
||||||
|
}
|
||||||
|
let previous_positive_usd_micros = self
|
||||||
|
.thread_usage
|
||||||
|
.estimate
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|estimate| estimate.estimated_usage_usd_micros)
|
||||||
|
.filter(|micros| *micros > 0);
|
||||||
|
let transient_zero_cost = usage.estimated_usage_usd_micros == Some(0)
|
||||||
|
&& previous_positive_usd_micros.is_some();
|
||||||
|
if let Some(previous_positive_usd_micros) = previous_positive_usd_micros
|
||||||
|
&& transient_zero_cost
|
||||||
|
{
|
||||||
|
usage.estimated_usage_usd_micros = Some(previous_positive_usd_micros);
|
||||||
|
}
|
||||||
|
if (transient_zero_credits || transient_zero_cost)
|
||||||
|
&& usage.groups.is_empty()
|
||||||
|
&& let Some(previous_usage) = self.thread_usage.estimate.as_ref()
|
||||||
|
{
|
||||||
|
usage.groups.clone_from(&previous_usage.groups);
|
||||||
|
}
|
||||||
|
let estimated_credits_micros = usage.estimated_usage_credits_micros;
|
||||||
|
let estimated_usd_micros = usage.estimated_usage_usd_micros;
|
||||||
|
self.thread_usage.estimate = Some(usage);
|
||||||
|
if let Some(baseline) = self.thread_usage.settlement_baseline_credits_micros {
|
||||||
|
if !post_turn_request {
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros =
|
||||||
|
Some(baseline.max(estimated_credits_micros));
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = match (
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros,
|
||||||
|
estimated_usd_micros,
|
||||||
|
) {
|
||||||
|
(Some(previous), Some(current)) => Some(previous.max(current)),
|
||||||
|
(previous, current) => previous.or(current),
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
let mut selected = self.selected_thread_usage();
|
||||||
|
if !self.thread_usage.status_history_handles.is_empty() {
|
||||||
|
selected.credits = true;
|
||||||
|
selected.estimated_cost |=
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros.is_some()
|
||||||
|
|| estimated_usd_micros.is_some();
|
||||||
|
}
|
||||||
|
let credits_settled =
|
||||||
|
!selected.credits || estimated_credits_micros > baseline;
|
||||||
|
let cost_settled = !selected.estimated_cost
|
||||||
|
|| estimated_usd_micros.is_some_and(|current| {
|
||||||
|
self.thread_usage
|
||||||
|
.settlement_baseline_usd_micros
|
||||||
|
.map_or(current > 0, |previous| current > previous)
|
||||||
|
});
|
||||||
|
if credits_settled && cost_settled {
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros = None;
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = None;
|
||||||
|
self.thread_usage.settlement_request_id = None;
|
||||||
|
self.thread_usage.settlement_refresh_due_at = None;
|
||||||
|
} else if self.thread_usage.settlement_refresh_due_at.is_none() {
|
||||||
|
self.schedule_next_thread_usage_settlement();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
tracing::debug!(error = %err, "failed to fetch estimated thread usage");
|
tracing::debug!(error = %err, "failed to fetch estimated thread usage");
|
||||||
|
self.schedule_thread_usage_retry();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if usage_updated && !self.thread_usage.status_history_handles.is_empty() {
|
if usage_updated && !self.thread_usage.status_history_handles.is_empty() {
|
||||||
for handle in self.thread_usage.status_history_handles.drain(..) {
|
for handle in &self.thread_usage.status_history_handles {
|
||||||
handle.set_thread_usage(self.thread_usage.estimate.clone());
|
handle.set_thread_usage(self.thread_usage.estimate.clone());
|
||||||
}
|
}
|
||||||
|
if self
|
||||||
|
.thread_usage
|
||||||
|
.settlement_baseline_credits_micros
|
||||||
|
.is_none()
|
||||||
|
{
|
||||||
|
self.thread_usage.status_history_handles.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if self
|
||||||
|
.thread_usage
|
||||||
|
.settlement_baseline_credits_micros
|
||||||
|
.is_some()
|
||||||
|
&& self.thread_usage.settlement_request_id.is_none()
|
||||||
|
&& self.thread_usage_is_selected()
|
||||||
|
{
|
||||||
|
self.request_thread_usage();
|
||||||
|
}
|
||||||
|
self.refresh_status_line();
|
||||||
self.request_redraw();
|
self.request_redraw();
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
@@ -112,7 +339,15 @@ impl ChatWidget {
|
|||||||
self.thread_usage.next_request_id =
|
self.thread_usage.next_request_id =
|
||||||
self.thread_usage.next_request_id.wrapping_add(/*rhs*/ 1);
|
self.thread_usage.next_request_id.wrapping_add(/*rhs*/ 1);
|
||||||
self.thread_usage.pending_request_id = Some(request_id);
|
self.thread_usage.pending_request_id = Some(request_id);
|
||||||
|
self.thread_usage.requested = true;
|
||||||
self.thread_usage.thread_id = Some(thread_id);
|
self.thread_usage.thread_id = Some(thread_id);
|
||||||
|
if self
|
||||||
|
.thread_usage
|
||||||
|
.settlement_baseline_credits_micros
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
self.thread_usage.settlement_request_id = Some(request_id);
|
||||||
|
}
|
||||||
self.app_event_tx.send(AppEvent::RefreshThreadUsage {
|
self.app_event_tx.send(AppEvent::RefreshThreadUsage {
|
||||||
thread_id,
|
thread_id,
|
||||||
request_id,
|
request_id,
|
||||||
@@ -132,4 +367,63 @@ impl ChatWidget {
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn thread_usage_is_selected(&self) -> bool {
|
||||||
|
let selected = self.selected_thread_usage();
|
||||||
|
selected.credits || selected.estimated_cost
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selected_thread_usage(&self) -> SelectedThreadUsage {
|
||||||
|
let mut selected = SelectedThreadUsage::default();
|
||||||
|
for item in self.configured_status_line_items() {
|
||||||
|
match item.parse::<StatusLineItem>() {
|
||||||
|
Ok(StatusLineItem::ThreadCredits) => selected.credits = true,
|
||||||
|
Ok(StatusLineItem::EstimatedThreadCost) => selected.estimated_cost = true,
|
||||||
|
Ok(_) | Err(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for item in self.configured_terminal_title_items() {
|
||||||
|
match item.parse::<TerminalTitleItem>() {
|
||||||
|
Ok(TerminalTitleItem::ThreadCredits) => selected.credits = true,
|
||||||
|
Ok(TerminalTitleItem::EstimatedThreadCost) => selected.estimated_cost = true,
|
||||||
|
Ok(_) | Err(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
selected
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schedule_next_thread_usage_settlement(&mut self) {
|
||||||
|
let Some(delay) = THREAD_USAGE_SETTLEMENT_DELAYS
|
||||||
|
.get(self.thread_usage.settlement_attempts)
|
||||||
|
.copied()
|
||||||
|
else {
|
||||||
|
self.thread_usage.settlement_baseline_credits_micros = None;
|
||||||
|
self.thread_usage.settlement_baseline_usd_micros = None;
|
||||||
|
self.thread_usage.settlement_request_id = None;
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.thread_usage.settlement_attempts += 1;
|
||||||
|
self.thread_usage.settlement_refresh_due_at = Some(Instant::now() + delay);
|
||||||
|
self.frame_requester.schedule_frame_in(delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schedule_thread_usage_retry(&mut self) {
|
||||||
|
if !self.thread_usage_is_selected() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(delay) = THREAD_USAGE_RETRY_DELAYS
|
||||||
|
.get(self.thread_usage.retry_attempts)
|
||||||
|
.copied()
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.thread_usage.retry_attempts += 1;
|
||||||
|
self.thread_usage.retry_due_at = Some(Instant::now() + delay);
|
||||||
|
self.frame_requester.schedule_frame_in(delay);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "thread_usage_tests.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,997 @@
|
|||||||
|
use super::THREAD_USAGE_RETRY_DELAYS;
|
||||||
|
use super::THREAD_USAGE_SETTLEMENT_DELAYS;
|
||||||
|
use super::ThreadUsageOutcome;
|
||||||
|
use crate::app_event::AppEvent;
|
||||||
|
use crate::chatwidget::ReplayKind;
|
||||||
|
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||||
|
use crate::status::format_estimated_usd_micros;
|
||||||
|
use crate::tui::FrameRequester;
|
||||||
|
use codex_app_server_protocol::CodexErrorInfo;
|
||||||
|
use codex_app_server_protocol::ErrorNotification;
|
||||||
|
use codex_app_server_protocol::ServerNotification;
|
||||||
|
use codex_app_server_protocol::ThreadUsage;
|
||||||
|
use codex_app_server_protocol::ThreadUsageBreakdownGroup;
|
||||||
|
use codex_app_server_protocol::Turn;
|
||||||
|
use codex_app_server_protocol::TurnError;
|
||||||
|
use codex_app_server_protocol::TurnItemsView;
|
||||||
|
use codex_app_server_protocol::TurnStatus;
|
||||||
|
use codex_protocol::ThreadId;
|
||||||
|
use codex_protocol::account::PlanType;
|
||||||
|
use pretty_assertions::assert_eq;
|
||||||
|
use std::time::Duration;
|
||||||
|
use std::time::Instant;
|
||||||
|
use tokio::sync::mpsc::UnboundedReceiver;
|
||||||
|
|
||||||
|
fn thread_usage_request_id(events: &mut UnboundedReceiver<AppEvent>) -> u64 {
|
||||||
|
match events.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected a thread usage request, got {event:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thread_usage(
|
||||||
|
thread_id: ThreadId,
|
||||||
|
estimated_usage_credits_micros: i64,
|
||||||
|
estimated_usage_usd_micros: Option<i64>,
|
||||||
|
) -> ThreadUsage {
|
||||||
|
ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros,
|
||||||
|
estimated_usage_usd_micros,
|
||||||
|
groups: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn estimated_cost_formats_dollars_and_sub_cent_values() {
|
||||||
|
assert_eq!(
|
||||||
|
format_estimated_usd_micros(/*micros*/ 0),
|
||||||
|
Some("~$0.00".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_estimated_usd_micros(/*micros*/ 1),
|
||||||
|
Some("~$0.000001".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_estimated_usd_micros(/*micros*/ 400),
|
||||||
|
Some("~$0.0004".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_estimated_usd_micros(/*micros*/ 1_820_000),
|
||||||
|
Some("~$1.82".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format_estimated_usd_micros(/*micros*/ 995_000),
|
||||||
|
Some("~$1.00".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(format_estimated_usd_micros(/*micros*/ -1), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn temporary_thread_usage_failures_have_bounded_retries() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
for attempt in 0..=THREAD_USAGE_RETRY_DELAYS.len() {
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected retry attempt {attempt}, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Err("thread usage temporarily unavailable".to_string()),
|
||||||
|
));
|
||||||
|
|
||||||
|
if attempt < THREAD_USAGE_RETRY_DELAYS.len() {
|
||||||
|
assert!(chat.thread_usage.retry_due_at.is_some());
|
||||||
|
chat.thread_usage.retry_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(chat.thread_usage.retry_due_at.is_none());
|
||||||
|
assert!(rx.try_recv().is_err(), "retries must stop after the bound");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_history_survives_exhausted_billing_retries() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let mut request_id = thread_usage_request_id(&mut rx);
|
||||||
|
|
||||||
|
chat.add_status_output(
|
||||||
|
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||||
|
);
|
||||||
|
let first_status_cell = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||||
|
event => panic!("expected the first /status card, got {event:?}"),
|
||||||
|
};
|
||||||
|
|
||||||
|
for attempt in 0..=THREAD_USAGE_RETRY_DELAYS.len() {
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Err("thread usage temporarily unavailable".to_string()),
|
||||||
|
));
|
||||||
|
assert_eq!(chat.thread_usage.status_history_handles.len(), 1);
|
||||||
|
|
||||||
|
if attempt < THREAD_USAGE_RETRY_DELAYS.len() {
|
||||||
|
chat.thread_usage.retry_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
request_id = thread_usage_request_id(&mut rx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert_eq!(chat.thread_usage.retry_due_at, None);
|
||||||
|
chat.add_status_output(
|
||||||
|
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||||
|
);
|
||||||
|
let retry_status_cell = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||||
|
event => panic!("expected a fresh /status card, got {event:?}"),
|
||||||
|
};
|
||||||
|
request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(2_100_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
for status_cell in [&first_status_cell, &retry_status_cell] {
|
||||||
|
let rendered = status_cell
|
||||||
|
.display_lines(/*width*/ 90)
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|line| line.spans)
|
||||||
|
.map(|span| span.content.into_owned())
|
||||||
|
.collect::<String>();
|
||||||
|
assert!(rendered.contains("50 credits · ~$2.10"));
|
||||||
|
}
|
||||||
|
assert!(chat.thread_usage.status_history_handles.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn status_history_updates_again_after_billing_settles() {
|
||||||
|
for (selected_item, stale_credits_micros, stale_usd_micros) in [
|
||||||
|
("estimated-thread-cost", 40_000_000, 1_820_000),
|
||||||
|
("thread-credits", 50_000_000, 1_820_000),
|
||||||
|
("estimated-thread-cost", 40_000_000, 2_100_000),
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![selected_item.to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 40_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
chat.add_status_output(
|
||||||
|
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||||
|
);
|
||||||
|
let status_cell = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||||
|
event => panic!("expected an immediate /status card, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
stale_credits_micros,
|
||||||
|
Some(stale_usd_micros),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
assert_eq!(chat.thread_usage.status_history_handles.len(), 1);
|
||||||
|
|
||||||
|
chat.thread_usage.settlement_refresh_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(2_100_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
let rendered = status_cell
|
||||||
|
.display_lines(/*width*/ 90)
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|line| line.spans)
|
||||||
|
.map(|span| span.content.into_owned())
|
||||||
|
.collect::<String>();
|
||||||
|
assert!(rendered.contains("50 credits · ~$2.10"));
|
||||||
|
assert!(chat.thread_usage.status_history_handles.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn replayed_turn_completions_do_not_start_live_billing_refreshes() {
|
||||||
|
for replay_kind in [
|
||||||
|
ReplayKind::ResumeInitialMessages,
|
||||||
|
ReplayKind::ThreadSnapshot,
|
||||||
|
] {
|
||||||
|
for (status, error) in [
|
||||||
|
(TurnStatus::Completed, None),
|
||||||
|
(TurnStatus::Interrupted, None),
|
||||||
|
(TurnStatus::Failed, None),
|
||||||
|
(
|
||||||
|
TurnStatus::Failed,
|
||||||
|
Some(TurnError {
|
||||||
|
message: "the replayed turn failed".to_string(),
|
||||||
|
codex_error_info: Some(CodexErrorInfo::ServerOverloaded),
|
||||||
|
additional_details: None,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 46_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.replay_thread_turns(
|
||||||
|
vec![Turn {
|
||||||
|
id: "replayed-turn".to_string(),
|
||||||
|
items: Vec::new(),
|
||||||
|
items_view: TurnItemsView::NotLoaded,
|
||||||
|
status: status.clone(),
|
||||||
|
error,
|
||||||
|
started_at: None,
|
||||||
|
completed_at: None,
|
||||||
|
duration_ms: None,
|
||||||
|
}],
|
||||||
|
replay_kind,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!std::iter::from_fn(|| rx.try_recv().ok())
|
||||||
|
.any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })),
|
||||||
|
"{replay_kind:?} replay of {status:?} must not start live billing settlement"
|
||||||
|
);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
assert!(!chat.thread_usage.replaying_turn_completion);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn replayed_errors_do_not_start_live_billing_refreshes() {
|
||||||
|
for replay_kind in [
|
||||||
|
ReplayKind::ResumeInitialMessages,
|
||||||
|
ReplayKind::ThreadSnapshot,
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 46_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
let notification = ServerNotification::Error(ErrorNotification {
|
||||||
|
error: TurnError {
|
||||||
|
message: "the replayed turn failed".to_string(),
|
||||||
|
codex_error_info: Some(CodexErrorInfo::ServerOverloaded),
|
||||||
|
additional_details: None,
|
||||||
|
},
|
||||||
|
will_retry: false,
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
turn_id: "replayed-turn".to_string(),
|
||||||
|
});
|
||||||
|
chat.handle_server_notification(notification.clone(), Some(replay_kind));
|
||||||
|
assert!(
|
||||||
|
!std::iter::from_fn(|| rx.try_recv().ok())
|
||||||
|
.any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })),
|
||||||
|
"{replay_kind:?} error replay must not start live billing settlement"
|
||||||
|
);
|
||||||
|
assert!(!chat.thread_usage.replaying_turn_completion);
|
||||||
|
|
||||||
|
chat.handle_server_notification(notification, /*replay_kind*/ None);
|
||||||
|
assert!(
|
||||||
|
std::iter::from_fn(|| rx.try_recv().ok())
|
||||||
|
.any(|event| matches!(event, AppEvent::RefreshThreadUsage { .. })),
|
||||||
|
"a later live error must still refresh billing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn transient_zero_cost_preserves_fresh_credits_and_breakdowns() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.config.tui_terminal_title = chat.config.tui_status_line.clone();
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 46_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
let fresh_usage = ThreadUsage {
|
||||||
|
groups: vec![ThreadUsageBreakdownGroup {
|
||||||
|
model: Some("gpt-5.4".to_string()),
|
||||||
|
reasoning_effort: Some("high".to_string()),
|
||||||
|
speed: Some("fast".to_string()),
|
||||||
|
estimated_usage_credits_micros: 50_000_000,
|
||||||
|
net_new_input_tokens: Some(80),
|
||||||
|
cached_input_tokens: Some(20),
|
||||||
|
input_tokens: Some(100),
|
||||||
|
output_tokens: Some(40),
|
||||||
|
total_tokens: Some(140),
|
||||||
|
}],
|
||||||
|
..thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(0),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(fresh_usage.clone())),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat.estimated_thread_usage(),
|
||||||
|
Some(&ThreadUsage {
|
||||||
|
estimated_usage_usd_micros: Some(1_820_000),
|
||||||
|
..fresh_usage
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
chat.status_line_text(),
|
||||||
|
Some("50 credits · ~$1.82".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
chat.last_terminal_title,
|
||||||
|
Some("50 credits | ~$1.82".to_string())
|
||||||
|
);
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn transient_zero_credits_preserves_credits_only_estimates() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["thread-credits".to_string()]);
|
||||||
|
chat.config.tui_terminal_title = chat.config.tui_status_line.clone();
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
let previous_usage = ThreadUsage {
|
||||||
|
groups: vec![ThreadUsageBreakdownGroup {
|
||||||
|
model: Some("gpt-5.4".to_string()),
|
||||||
|
reasoning_effort: Some("high".to_string()),
|
||||||
|
speed: Some("fast".to_string()),
|
||||||
|
estimated_usage_credits_micros: 46_000_000,
|
||||||
|
net_new_input_tokens: Some(80),
|
||||||
|
cached_input_tokens: Some(20),
|
||||||
|
input_tokens: Some(100),
|
||||||
|
output_tokens: Some(40),
|
||||||
|
total_tokens: Some(140),
|
||||||
|
}],
|
||||||
|
..thread_usage(
|
||||||
|
thread_id, /*estimated_usage_credits_micros*/ 46_000_000,
|
||||||
|
/*estimated_usage_usd_micros*/ None,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(previous_usage.clone())),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id, /*estimated_usage_credits_micros*/ 0,
|
||||||
|
/*estimated_usage_usd_micros*/ None,
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.estimated_thread_usage(), Some(&previous_usage));
|
||||||
|
assert_eq!(chat.status_line_text(), Some("46 credits".to_string()));
|
||||||
|
assert_eq!(chat.last_terminal_title, Some("46 credits".to_string()));
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cost_settlement_waits_for_new_or_missing_usd_estimates() {
|
||||||
|
for (previous_usd_micros, stale_usd_micros) in [
|
||||||
|
(Some(1_820_000), Some(1_820_000)),
|
||||||
|
(None, None),
|
||||||
|
(None, Some(0)),
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 40_000_000,
|
||||||
|
previous_usd_micros,
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
stale_usd_micros,
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
chat.thread_usage.settlement_baseline_credits_micros,
|
||||||
|
Some(40_000_000)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
chat.thread_usage.settlement_baseline_usd_micros,
|
||||||
|
previous_usd_micros
|
||||||
|
);
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
|
||||||
|
chat.thread_usage.settlement_refresh_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(2_100_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.status_line_text(), Some("~$2.10".to_string()));
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn credits_only_settlement_completes_without_usd_estimates() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_terminal_title = Some(vec!["thread-credits".to_string()]);
|
||||||
|
chat.refresh_terminal_title();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id, /*estimated_usage_credits_micros*/ 40_000_000,
|
||||||
|
/*estimated_usage_usd_micros*/ None,
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id, /*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
/*estimated_usage_usd_micros*/ None,
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.last_terminal_title, Some("50 credits".to_string()));
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn combined_billing_surfaces_wait_for_credits_and_cost() {
|
||||||
|
for (status_line_item, title_item) in [
|
||||||
|
("thread-credits", "estimated-thread-cost"),
|
||||||
|
("estimated-thread-cost", "thread-credits"),
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec![status_line_item.to_string()]);
|
||||||
|
chat.config.tui_terminal_title = Some(vec![title_item.to_string()]);
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 40_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(1_820_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
|
||||||
|
chat.thread_usage.settlement_refresh_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 50_000_000,
|
||||||
|
Some(2_100_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_usd_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn billing_surfaces_render_for_every_supported_enterprise_plan() {
|
||||||
|
for plan_type in [
|
||||||
|
PlanType::Business,
|
||||||
|
PlanType::EnterpriseCbpUsageBased,
|
||||||
|
PlanType::EnterpriseCbpAutomation,
|
||||||
|
] {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(plan_type);
|
||||||
|
chat.config.tui_status_line = Some(vec![
|
||||||
|
"thread-credits".to_string(),
|
||||||
|
"estimated-thread-cost".to_string(),
|
||||||
|
]);
|
||||||
|
chat.config.tui_terminal_title = chat.config.tui_status_line.clone();
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
let request_id = thread_usage_request_id(&mut rx);
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(thread_usage(
|
||||||
|
thread_id,
|
||||||
|
/*estimated_usage_credits_micros*/ 5_200_000,
|
||||||
|
Some(210_000),
|
||||||
|
))),
|
||||||
|
));
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
chat.status_line_text(),
|
||||||
|
Some("5.2 credits · ~$0.21".to_string())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
chat.last_terminal_title,
|
||||||
|
Some("5.2 credits | ~$0.21".to_string())
|
||||||
|
);
|
||||||
|
assert!(rx.try_recv().is_err(), "billing surfaces share a request");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn early_draw_rearms_thread_usage_retry_after_immediate_redraw() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
let (frame_requester, mut frame_rx) = FrameRequester::test_channel();
|
||||||
|
chat.frame_requester = frame_requester;
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Err("thread usage temporarily unavailable".to_string()),
|
||||||
|
));
|
||||||
|
let retry_due_at = chat
|
||||||
|
.thread_usage
|
||||||
|
.retry_due_at
|
||||||
|
.expect("temporary failures schedule a retry");
|
||||||
|
let scheduled = std::iter::from_fn(|| frame_rx.try_recv().ok()).collect::<Vec<_>>();
|
||||||
|
assert!(scheduled.iter().any(|deadline| *deadline >= retry_due_at));
|
||||||
|
assert!(scheduled.iter().any(|deadline| *deadline < retry_due_at));
|
||||||
|
|
||||||
|
chat.pre_draw_tick();
|
||||||
|
|
||||||
|
let rearmed = std::iter::from_fn(|| frame_rx.try_recv().ok())
|
||||||
|
.find(|deadline| *deadline >= retry_due_at)
|
||||||
|
.expect("the immediate redraw must re-arm the pending billing retry");
|
||||||
|
assert!(rearmed.duration_since(retry_due_at) < Duration::from_secs(/*secs*/ 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unchanged_thread_usage_has_bounded_settlement_refreshes() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
for attempt in 0..=THREAD_USAGE_SETTLEMENT_DELAYS.len() {
|
||||||
|
let request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected settlement attempt {attempt}, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
if attempt < THREAD_USAGE_SETTLEMENT_DELAYS.len() {
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
chat.thread_usage.settlement_refresh_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_none());
|
||||||
|
assert!(
|
||||||
|
chat.thread_usage
|
||||||
|
.settlement_baseline_credits_micros
|
||||||
|
.is_none()
|
||||||
|
);
|
||||||
|
assert!(rx.try_recv().is_err(), "settlement polling must stop");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn early_draw_rearms_thread_usage_settlement_after_immediate_redraw() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
let usage = 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(),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(usage.clone())),
|
||||||
|
));
|
||||||
|
|
||||||
|
let (frame_requester, mut frame_rx) = FrameRequester::test_channel();
|
||||||
|
chat.frame_requester = frame_requester;
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let settlement_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected immediate post-turn thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
settlement_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(usage)),
|
||||||
|
));
|
||||||
|
let settlement_due_at = chat
|
||||||
|
.thread_usage
|
||||||
|
.settlement_refresh_due_at
|
||||||
|
.expect("unchanged post-turn billing schedules a settlement refresh");
|
||||||
|
let scheduled = std::iter::from_fn(|| frame_rx.try_recv().ok()).collect::<Vec<_>>();
|
||||||
|
assert!(
|
||||||
|
scheduled
|
||||||
|
.iter()
|
||||||
|
.any(|deadline| *deadline >= settlement_due_at)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
scheduled
|
||||||
|
.iter()
|
||||||
|
.any(|deadline| *deadline < settlement_due_at)
|
||||||
|
);
|
||||||
|
|
||||||
|
chat.pre_draw_tick();
|
||||||
|
|
||||||
|
let rearmed = std::iter::from_fn(|| frame_rx.try_recv().ok())
|
||||||
|
.find(|deadline| *deadline >= settlement_due_at)
|
||||||
|
.expect("the immediate redraw must re-arm the pending billing settlement");
|
||||||
|
assert!(rearmed.duration_since(settlement_due_at) < Duration::from_secs(/*secs*/ 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn thread_usage_settlement_requires_request_started_after_turn_completion() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.refresh_status_line();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 40_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(1_600_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.thread_usage.status_requested = true;
|
||||||
|
chat.request_thread_usage();
|
||||||
|
let pre_turn_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected pre-turn thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
assert_eq!(chat.thread_usage.settlement_request_id, None);
|
||||||
|
assert_eq!(
|
||||||
|
chat.thread_usage.settlement_baseline_credits_micros,
|
||||||
|
Some(40_000_000)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
pre_turn_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
let post_turn_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected a request started after turn completion, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
chat.thread_usage.settlement_baseline_credits_micros,
|
||||||
|
Some(46_000_000)
|
||||||
|
);
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
post_turn_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
|
||||||
|
chat.thread_usage.settlement_refresh_due_at = Some(Instant::now());
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
let settlement_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected another post-turn settlement request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
settlement_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 50_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(2_100_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn deselecting_billing_surfaces_cancels_polling_and_preserves_status_cache() {
|
||||||
|
let (mut chat, _sender, mut rx, _op_rx) = make_chatwidget_manual_with_sender().await;
|
||||||
|
let thread_id = ThreadId::new();
|
||||||
|
chat.thread_id = Some(thread_id);
|
||||||
|
chat.has_codex_backend_auth = true;
|
||||||
|
chat.plan_type = Some(PlanType::Business);
|
||||||
|
chat.config.tui_status_line = Some(vec!["estimated-thread-cost".to_string()]);
|
||||||
|
chat.config.tui_terminal_title = Some(vec!["thread-credits".to_string()]);
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
|
||||||
|
let initial_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
initial_request_id,
|
||||||
|
Ok(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(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
|
||||||
|
chat.thread_usage.status_requested = true;
|
||||||
|
chat.request_thread_usage();
|
||||||
|
assert!(chat.thread_usage.status_requested);
|
||||||
|
let status_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected explicit /status refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
status_request_id,
|
||||||
|
Err("thread usage temporarily unavailable".to_string()),
|
||||||
|
));
|
||||||
|
assert!(!chat.thread_usage.status_requested);
|
||||||
|
assert!(chat.thread_usage.retry_due_at.is_some());
|
||||||
|
|
||||||
|
chat.refresh_thread_usage_after_turn();
|
||||||
|
let settlement_request_id = match rx.try_recv() {
|
||||||
|
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||||
|
event => panic!("expected post-turn thread usage refresh, got {event:?}"),
|
||||||
|
};
|
||||||
|
assert!(chat.thread_usage.settlement_refresh_due_at.is_some());
|
||||||
|
|
||||||
|
chat.config.tui_status_line = Some(Vec::new());
|
||||||
|
chat.config.tui_terminal_title = Some(Vec::new());
|
||||||
|
chat.refresh_status_surfaces();
|
||||||
|
|
||||||
|
assert!(!chat.thread_usage.status_requested);
|
||||||
|
assert!(!chat.thread_usage.requested);
|
||||||
|
assert_eq!(chat.thread_usage.pending_request_id, None);
|
||||||
|
assert_eq!(chat.thread_usage.retry_due_at, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_refresh_due_at, None);
|
||||||
|
assert_eq!(chat.thread_usage.settlement_baseline_credits_micros, None);
|
||||||
|
assert_eq!(
|
||||||
|
chat.estimated_thread_usage(),
|
||||||
|
Some(&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(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert!(!chat.finish_thread_usage_refresh(
|
||||||
|
thread_id,
|
||||||
|
settlement_request_id,
|
||||||
|
Ok(ThreadUsageOutcome::Available(ThreadUsage {
|
||||||
|
thread_id: thread_id.to_string(),
|
||||||
|
estimated_usage_credits_micros: 50_000_000,
|
||||||
|
estimated_usage_usd_micros: Some(2_100_000),
|
||||||
|
groups: Vec::new(),
|
||||||
|
})),
|
||||||
|
));
|
||||||
|
chat.refresh_thread_usage_if_settlement_due();
|
||||||
|
assert!(rx.try_recv().is_err(), "deselected billing must not poll");
|
||||||
|
}
|
||||||
@@ -173,6 +173,7 @@ impl ChatWidget {
|
|||||||
self.transcript.had_work_activity = false;
|
self.transcript.had_work_activity = false;
|
||||||
self.request_status_line_branch_refresh();
|
self.request_status_line_branch_refresh();
|
||||||
self.request_status_line_git_summary_refresh();
|
self.request_status_line_git_summary_refresh();
|
||||||
|
self.refresh_thread_usage_after_turn();
|
||||||
}
|
}
|
||||||
// Mark task stopped and request redraw now that all content is in history.
|
// Mark task stopped and request redraw now that all content is in history.
|
||||||
self.status_state.pending_status_indicator_restore = false;
|
self.status_state.pending_status_indicator_restore = false;
|
||||||
@@ -339,6 +340,7 @@ impl ChatWidget {
|
|||||||
self.safety_buffering_prompt = None;
|
self.safety_buffering_prompt = None;
|
||||||
self.request_status_line_branch_refresh();
|
self.request_status_line_branch_refresh();
|
||||||
self.request_status_line_git_summary_refresh();
|
self.request_status_line_git_summary_refresh();
|
||||||
|
self.refresh_thread_usage_after_turn();
|
||||||
self.maybe_show_pending_rate_limit_prompt();
|
self.maybe_show_pending_rate_limit_prompt();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ pub(crate) use rate_limits::RateLimitWindowDisplay;
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) use rate_limits::rate_limit_snapshot_display;
|
pub(crate) use rate_limits::rate_limit_snapshot_display;
|
||||||
pub(crate) use rate_limits::rate_limit_snapshot_display_for_limit;
|
pub(crate) use rate_limits::rate_limit_snapshot_display_for_limit;
|
||||||
|
pub(crate) use thread_usage::format_credit_micros;
|
||||||
|
pub(crate) use thread_usage::format_estimated_usd_micros;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests;
|
mod tests;
|
||||||
Reference in new issue
Block a user