mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Open /status in an interactive TUI modal (#64772)
## Why Rate limits and thread usage can arrive after `/status` is displayed. Updating a status card already in terminal scrollback required rewriting history and depended on where the card was rendered. ## What changed - Show the report in a scrollable modal with Overview, Configuration, and Session tabs. Apply rate limit and thread usage results to the open report without writing status output to the transcript or terminal scrollback. - Copy a selected field or the full report directly from the modal, and open usage settings from the same view. Remove status fields from the `/copy` picker. ## Testing Add coverage for overlapping refreshes, dismissal during account or thread changes, keyboard navigation and copying during an active turn, and scrolling in a narrow terminal. GitOrigin-RevId: 64961c4d013607e373d50a79182b74e3048c632f
This commit is contained in:
@@ -554,6 +554,8 @@ trust_level = "trusted"
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("daemon status timed out: {output}"))??;
|
||||
// Dismiss the status modal before sending /quit to the composer.
|
||||
session.writer_sender().send(b"\x03".to_vec()).await?;
|
||||
}
|
||||
if analytics {
|
||||
for reason in ["turn_start", "resize"] {
|
||||
|
||||
@@ -610,9 +610,6 @@ pub(crate) struct App {
|
||||
turn_tips: turn_tips::TurnTips,
|
||||
pub(crate) transcript_view: crate::transcript_view::TranscriptView,
|
||||
conversation_frame: owned_transcript::ConversationFrame,
|
||||
last_rendered_history_tail: Option<history_ui::RenderedHistoryTail>,
|
||||
last_thread_usage_status_cell: Option<history_ui::ThreadUsageStatusHistory>,
|
||||
pub(crate) pending_thread_usage_history_refresh: bool,
|
||||
|
||||
// Alternate-screen overlays: transcript, diff, and analytics.
|
||||
pub(crate) overlay: Option<Overlay>,
|
||||
|
||||
@@ -45,7 +45,6 @@ impl App {
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
self.insert_history_cell_lines(tui, completed.as_ref(), width);
|
||||
self.last_rendered_history_tail = None;
|
||||
}
|
||||
group.group.calls[member] = completed.group.calls.remove(0);
|
||||
self.replace_activity_group(index..index + 1, Arc::new(group));
|
||||
|
||||
@@ -2179,7 +2179,7 @@ async fn shared_overview_shows_only_root_sessions() {
|
||||
app.render_chat_widget_frame(&mut tui, screen_size)
|
||||
.expect("restore conversation after closing dashboard");
|
||||
assert!(tui.terminal.viewport_area.height < screen_size.height);
|
||||
assert!(app.last_rendered_history_tail.is_some());
|
||||
assert!(app.has_emitted_history_lines);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -493,10 +493,6 @@ impl App {
|
||||
self.rate_limit_hard_stop_generation =
|
||||
self.rate_limit_hard_stop_generation.wrapping_add(1);
|
||||
self.rate_limit_refresh_state.invalidate_recovery();
|
||||
// Deferred terminal writes must never carry the previous account's billing into
|
||||
// the newly authenticated identity, even when both accounts share one thread.
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
let has_codex_backend_auth = matches!(
|
||||
notification.auth_mode,
|
||||
Some(
|
||||
|
||||
@@ -671,9 +671,9 @@ impl App {
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
AppEvent::CopySelection { text, label, format } => {
|
||||
AppEvent::CopySelection { text, label, format, feedback } => {
|
||||
let result = tui.clipboard.copy(text, format, tui.frame_requester());
|
||||
self.chat_widget.show_copy_result(&label, result);
|
||||
self.chat_widget.report_copy_result(&label, &result, feedback);
|
||||
}
|
||||
AppEvent::ClearUi { name } => {
|
||||
if self.reject_pending_permission_root_switch() {
|
||||
@@ -1121,9 +1121,6 @@ impl App {
|
||||
self.transcript_view = Default::default();
|
||||
self.scrollback_has_older_history = app_server.has_older_history(thread_id);
|
||||
self.deferred_history_lines.clear();
|
||||
self.last_rendered_history_tail = None;
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
self.backtrack_render_pending = !tui.is_owned_screen();
|
||||
// Input was blocked through the transcript reset. A queued Enter must
|
||||
// not submit the prompt we just restored for editing.
|
||||
@@ -2414,9 +2411,7 @@ impl App {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id } => {
|
||||
if self.chat_widget.finish_status_rate_limit_refresh(request_id, snapshots) {
|
||||
self.refresh_status_history(tui)?;
|
||||
}
|
||||
self.chat_widget.finish_status_rate_limit_refresh(request_id, snapshots);
|
||||
}
|
||||
RateLimitRefreshOrigin::UsageMenu { request_id } => {
|
||||
self.chat_widget.finish_usage_menu_rate_limit_refresh(
|
||||
@@ -2466,9 +2461,7 @@ impl App {
|
||||
);
|
||||
}
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id } => {
|
||||
if self.chat_widget.finish_status_rate_limit_refresh(request_id, Vec::new()) {
|
||||
self.refresh_status_history(tui)?;
|
||||
}
|
||||
self.chat_widget.finish_status_rate_limit_refresh(request_id, Vec::new());
|
||||
}
|
||||
RateLimitRefreshOrigin::UsageMenu { request_id } => {
|
||||
self.chat_widget.finish_usage_menu_rate_limit_refresh(
|
||||
@@ -2586,7 +2579,7 @@ impl App {
|
||||
request_id,
|
||||
result,
|
||||
} => {
|
||||
self.finish_thread_usage_refresh(tui, thread_id, request_id, result)?;
|
||||
self.chat_widget.finish_thread_usage_refresh(thread_id, request_id, result);
|
||||
}
|
||||
AppEvent::AgentsOverviewUsageLoaded { thread_id, request_id, result } => {
|
||||
self.finish_agents_overview_usage(thread_id, request_id, result);
|
||||
|
||||
@@ -5,22 +5,9 @@
|
||||
//! keep committed cells as the render source and never enqueue terminal-scrollback rows here.
|
||||
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use std::sync::Weak;
|
||||
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app.";
|
||||
|
||||
pub(super) struct RenderedHistoryTail {
|
||||
pub(super) cell: Weak<dyn HistoryCell>,
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
pub(super) struct ThreadUsageStatusHistory {
|
||||
thread_id: Option<ThreadId>,
|
||||
pub(super) cell: Weak<dyn HistoryCell>,
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn link_viewed_image(&self, cell: &mut dyn HistoryCell) {
|
||||
if let Some(image) = cell
|
||||
@@ -84,7 +71,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Track mutable status cards before choosing retained or terminal-owned rendering.
|
||||
pub(super) fn render_inserted_history_cell(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
@@ -94,181 +80,15 @@ impl App {
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
// Owned replay must not eagerly format every historical entry. Composite status cards are
|
||||
// the only committed cells whose mutable usage data needs insertion-time bookkeeping.
|
||||
let lines = if !deferred || cell.as_any().is::<history_cell::CompositeHistoryCell>() {
|
||||
cell.scrollback_lines(width, self.chat_widget.history_render_mode())
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if cell.as_any().is::<history_cell::CompositeHistoryCell>()
|
||||
&& lines.first().is_some_and(|line| {
|
||||
line.line.spans.len() == 1 && line.line.spans[0].content.as_ref() == "/status"
|
||||
})
|
||||
{
|
||||
self.last_thread_usage_status_cell = Some(ThreadUsageStatusHistory {
|
||||
thread_id: self.chat_widget.thread_id(),
|
||||
cell: Arc::downgrade(cell),
|
||||
lines: lines.clone(),
|
||||
});
|
||||
}
|
||||
// Invisible diagnostics still update the badge without replacing the rendered tail.
|
||||
if deferred || lines.is_empty() {
|
||||
if deferred {
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
if self.initial_history_replay_buffer.as_ref().is_some() {
|
||||
} else if self.initial_history_replay_buffer.is_some() {
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = None;
|
||||
} else {
|
||||
self.insert_history_cell_lines(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = if self.overlay.is_none() {
|
||||
Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(cell),
|
||||
lines,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish_thread_usage_refresh(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
thread_id: ThreadId,
|
||||
request_id: Uuid,
|
||||
result: std::result::Result<crate::chatwidget::ThreadUsageOutcome, String>,
|
||||
) -> Result<()> {
|
||||
let may_update_status = match &result {
|
||||
Ok(crate::chatwidget::ThreadUsageOutcome::Available(usage)) => {
|
||||
usage.thread_id == thread_id.to_string()
|
||||
}
|
||||
Ok(crate::chatwidget::ThreadUsageOutcome::Disabled) => true,
|
||||
Err(_) => false,
|
||||
};
|
||||
if !self
|
||||
.chat_widget
|
||||
.finish_thread_usage_refresh(thread_id, request_id, result)
|
||||
|| !may_update_status
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.refresh_status_history(tui)
|
||||
}
|
||||
|
||||
pub(super) fn refresh_status_history(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
if !tui.is_owned_screen()
|
||||
&& (self.overlay.is_some() || self.initial_history_replay_buffer.is_some())
|
||||
{
|
||||
self.pending_thread_usage_history_refresh = true;
|
||||
return Ok(());
|
||||
}
|
||||
self.refresh_thread_usage_history_tail(tui)
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_thread_usage_history_tail(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
let Some(status_history) = self.last_thread_usage_status_cell.as_ref() else {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
if self.chat_widget.thread_id() != status_history.thread_id {
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
let Some(status_cell) = status_history.cell.upgrade() else {
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
// A queued card reads the latest usage when it is first emitted.
|
||||
if self.native_history.contains(&status_cell) {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
let updated_lines = status_cell
|
||||
.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
|
||||
if updated_lines == status_history.lines {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
if tui.is_owned_screen() {
|
||||
// Composite cells are backed by mutable usage state, so the retained view remeasures
|
||||
// them on its next frame without replacing native terminal history.
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.last_rendered_history_tail = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
tui.frame_requester().schedule_frame();
|
||||
return Ok(());
|
||||
}
|
||||
let Some(rendered_tail) = self.last_rendered_history_tail.as_ref() else {
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
};
|
||||
if !rendered_tail
|
||||
.cell
|
||||
.upgrade()
|
||||
.is_some_and(|cell| Arc::ptr_eq(&cell, &status_cell))
|
||||
{
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let prefix_len = rendered_tail
|
||||
.lines
|
||||
.iter()
|
||||
.zip(&updated_lines)
|
||||
.take_while(|(previous, updated)| previous == updated)
|
||||
.count();
|
||||
if prefix_len == rendered_tail.lines.len() && prefix_len == updated_lines.len() {
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let wrap_policy = self.history_line_wrap_policy();
|
||||
if !tui.replace_visible_history_tail(
|
||||
&rendered_tail.lines[prefix_len..],
|
||||
&updated_lines[prefix_len..],
|
||||
wrap_policy,
|
||||
)? {
|
||||
self.insert_history_cell_lines(tui, status_cell.as_ref(), width);
|
||||
}
|
||||
self.last_rendered_history_tail = Some(RenderedHistoryTail {
|
||||
cell: Arc::downgrade(&status_cell),
|
||||
lines: updated_lines.clone(),
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut() {
|
||||
status_history.lines = updated_lines;
|
||||
}
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn pending_usage_output_insertion_blocked(&self) -> bool {
|
||||
self.chat_widget.usage_history_insertion_blocked()
|
||||
|| self
|
||||
@@ -436,9 +256,6 @@ impl App {
|
||||
self.cancel_pending_key_chord();
|
||||
self.transcript_view = Default::default();
|
||||
*self.chat_widget.rendered_selection.borrow_mut() = Default::default();
|
||||
self.last_rendered_history_tail = None;
|
||||
self.last_thread_usage_status_cell = None;
|
||||
self.pending_thread_usage_history_refresh = false;
|
||||
self.deferred_history_lines.clear();
|
||||
self.has_emitted_history_lines = false;
|
||||
self.transcript_reflow.clear();
|
||||
|
||||
@@ -2178,7 +2178,7 @@ async fn inline_confirmation_preserves_compact_viewport_without_replaying_histor
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
app.render_chat_widget_frame(&mut tui, size)?;
|
||||
assert!(tui.terminal.viewport_area.height < size.height);
|
||||
assert!(app.last_rendered_history_tail.is_none());
|
||||
assert!(!app.has_emitted_history_lines);
|
||||
assert!(
|
||||
buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal
|
||||
|
||||
@@ -85,7 +85,6 @@ impl App {
|
||||
pub(super) fn reset_history_emission_state(&mut self) {
|
||||
self.has_emitted_history_lines = false;
|
||||
self.deferred_history_lines.clear();
|
||||
self.last_rendered_history_tail = None;
|
||||
}
|
||||
|
||||
fn display_lines_for_history_insert(
|
||||
@@ -124,6 +123,7 @@ impl App {
|
||||
display: Vec<HyperlinkLine>,
|
||||
) {
|
||||
if display.is_empty() {
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
if self.overlay.is_some() {
|
||||
@@ -200,11 +200,6 @@ impl App {
|
||||
retained_lines,
|
||||
self.history_line_wrap_policy(),
|
||||
);
|
||||
if self.pending_thread_usage_history_refresh
|
||||
&& let Err(err) = self.refresh_thread_usage_history_tail(tui)
|
||||
{
|
||||
tracing::warn!(error = %err, "failed to refresh thread usage after initial replay");
|
||||
}
|
||||
self.request_scrollback_history_top_up(retained_rows);
|
||||
}
|
||||
|
||||
@@ -229,6 +224,7 @@ impl App {
|
||||
let display = self.display_lines_for_history_insert(cell, width);
|
||||
|
||||
if display.is_empty() {
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -548,27 +544,6 @@ impl App {
|
||||
|
||||
self.deferred_history_lines.clear();
|
||||
tui.queue_history_replay(reflowed_lines, self.history_line_wrap_policy());
|
||||
self.last_rendered_history_tail = self
|
||||
.native_history
|
||||
.replayable_cells(&self.transcript_cells)
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|cell| {
|
||||
let lines = cell.scrollback_lines(width, self.chat_widget.history_render_mode());
|
||||
(!lines.is_empty()).then(|| super::history_ui::RenderedHistoryTail {
|
||||
cell: Arc::downgrade(cell),
|
||||
lines,
|
||||
})
|
||||
});
|
||||
if let Some(status_history) = self.last_thread_usage_status_cell.as_mut()
|
||||
&& let Some(cell) = status_history.cell.upgrade()
|
||||
{
|
||||
status_history.lines = cell
|
||||
.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode());
|
||||
}
|
||||
if self.pending_thread_usage_history_refresh {
|
||||
self.refresh_thread_usage_history_tail(tui)?;
|
||||
}
|
||||
// When flushing a partial refill, the next request is in flight or just failed.
|
||||
if !flushing_refill {
|
||||
self.request_scrollback_history_top_up(reflowed_rows);
|
||||
|
||||
@@ -1092,9 +1092,6 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
turn_tips: Default::default(),
|
||||
transcript_view: Default::default(),
|
||||
conversation_frame: Default::default(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
retained_analytics: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
|
||||
@@ -91,9 +91,6 @@ pub(crate) async fn make_test_app() -> Box<App> {
|
||||
turn_tips: Default::default(),
|
||||
transcript_view: Default::default(),
|
||||
conversation_frame: Default::default(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
retained_analytics: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
|
||||
@@ -9158,9 +9158,6 @@ async fn make_test_app() -> Box<App> {
|
||||
turn_tips: Default::default(),
|
||||
transcript_view: Default::default(),
|
||||
conversation_frame: Default::default(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
retained_analytics: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
@@ -9307,9 +9304,6 @@ pub(super) async fn make_test_app_with_channels() -> (
|
||||
turn_tips: Default::default(),
|
||||
transcript_view: Default::default(),
|
||||
conversation_frame: Default::default(),
|
||||
last_rendered_history_tail: None,
|
||||
last_thread_usage_status_cell: None,
|
||||
pending_thread_usage_history_refresh: false,
|
||||
overlay: None,
|
||||
retained_analytics: None,
|
||||
deferred_history_lines: Vec::new(),
|
||||
@@ -9962,7 +9956,7 @@ async fn closing_fullscreen_inline_overlay_restores_history_once() -> Result<()>
|
||||
let popup_height = screen_size.height - 1;
|
||||
tui.draw(popup_height, |_| {})?;
|
||||
app.render_chat_widget_frame(&mut tui, screen_size)?;
|
||||
assert!(app.last_rendered_history_tail.is_none());
|
||||
assert!(!app.has_emitted_history_lines);
|
||||
|
||||
tui.enter_alt_screen()?;
|
||||
tui.draw(screen_size.height, |_| {})?;
|
||||
@@ -9971,18 +9965,7 @@ async fn closing_fullscreen_inline_overlay_restores_history_once() -> Result<()>
|
||||
|
||||
assert!(tui.terminal.viewport_area.height < screen_size.height);
|
||||
assert!(tui.terminal.viewport_area.y > 0);
|
||||
let tail = app
|
||||
.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("fullscreen exit rebuilt history");
|
||||
assert_snapshot!(
|
||||
tail.lines
|
||||
.iter()
|
||||
.map(rendered_line_text)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
@"Previous conversation"
|
||||
);
|
||||
assert!(app.has_emitted_history_lines);
|
||||
|
||||
let deferred = vec![Line::from("Pending history").into()];
|
||||
app.deferred_history_lines = deferred.clone();
|
||||
|
||||
@@ -83,7 +83,9 @@ async fn backend_banner_fallback_updates_task_settings_and_keeps_notice() -> Res
|
||||
&mut server,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id: 1,
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 },
|
||||
origin: RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: uuid::Uuid::new_v4(),
|
||||
},
|
||||
hard_stop_generation: generation,
|
||||
result: Ok(response.clone()),
|
||||
},
|
||||
@@ -201,7 +203,9 @@ async fn backend_banner_fallback_uses_current_task_and_accepted_generation() ->
|
||||
&mut server,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id: 1,
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id: 0 },
|
||||
origin: RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: uuid::Uuid::new_v4(),
|
||||
},
|
||||
hard_stop_generation: generation,
|
||||
result: Ok(fallback_response()),
|
||||
},
|
||||
|
||||
@@ -235,6 +235,9 @@ async fn commands_can_precede_the_sparkle_but_inserted_or_typed_drafts_cannot()
|
||||
type_into(&mut app.chat_widget, command);
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
if command == "/status" {
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
"mention" => {
|
||||
@@ -362,6 +365,9 @@ async fn a_command_pending_on_fresh_astra_start_can_finish_before_the_sparkle()
|
||||
);
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
if command == "/status" {
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
assert_eq!(visible(&app.chat_widget), visible_after, "{command}");
|
||||
}
|
||||
Ok(())
|
||||
@@ -755,6 +761,7 @@ async fn a_read_only_command_can_return_to_active_stars_but_mention_ends_them()
|
||||
assert!(!visible(&app.chat_widget));
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(visible(&app.chat_widget));
|
||||
type_into(&mut app.chat_widget, "/mention");
|
||||
app.chat_widget
|
||||
|
||||
@@ -82,7 +82,7 @@ async fn disconnected_feedback_reveals_the_thread_id_from_older_history() -> Res
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settings_pickers_preserve_the_reading_anchor_through_open_and_close() -> Result<()> {
|
||||
async fn composer_modals_preserve_the_reading_anchor_through_open_and_close() -> Result<()> {
|
||||
let (mut app, mut events, _op_rx) = make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut server = start_config_write_test_app_server(&app).await?;
|
||||
@@ -97,6 +97,7 @@ async fn settings_pickers_preserve_the_reading_anchor_through_open_and_close() -
|
||||
|
||||
for (command, close) in [
|
||||
("/model", KeyCode::Esc),
|
||||
("/status", KeyCode::Esc),
|
||||
("/theme", KeyCode::Enter),
|
||||
("/keymap", KeyCode::Esc),
|
||||
("/memories", KeyCode::Esc),
|
||||
@@ -414,7 +415,7 @@ async fn local_command_and_inline_error_reveal_their_history_output() -> Result<
|
||||
"/model",
|
||||
"Model selection is disabled until startup completes.",
|
||||
),
|
||||
("/status", "/status"),
|
||||
("/pwd", "Current working directory:"),
|
||||
("/keymap invalid", "Usage: /keymap [debug]"),
|
||||
] {
|
||||
hold_older_history(&mut app, &mut tui);
|
||||
|
||||
@@ -553,10 +553,7 @@ async fn cloud_model_selection_waits_for_native_admission() -> Result<()> {
|
||||
while events.try_recv().is_ok() {}
|
||||
app.chat_widget
|
||||
.dispatch_command(crate::slash_command::SlashCommand::Status);
|
||||
let AppEvent::InsertHistoryCell(status) = events.try_recv()? else {
|
||||
panic!("expected /status output");
|
||||
};
|
||||
let status = lines_to_single_string(&status.display_lines(/*width*/ 120));
|
||||
let status = render_bottom_popup(&app.chat_widget, /*width*/ 120);
|
||||
let model = status
|
||||
.lines()
|
||||
.find_map(|line| line.split_once("Model:"))
|
||||
|
||||
@@ -76,18 +76,11 @@ fn render_status_output(
|
||||
app_event_rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
|
||||
) -> String {
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
app.chat_widget.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
match app_event_rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell
|
||||
.display_lines(/*width*/ 120)
|
||||
.into_iter()
|
||||
.map(|line| line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
other => panic!("expected status output, got {other:?}"),
|
||||
}
|
||||
app.chat_widget.show_status(/*quota_request*/ None);
|
||||
let popup = render_bottom_popup(&app.chat_widget, /*width*/ 120);
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
popup
|
||||
}
|
||||
|
||||
fn deliver_usage_limit_error(app: &mut App) {
|
||||
@@ -164,9 +157,8 @@ async fn accepted_rate_limit_read_updates_billing_after_its_status_card_is_gone(
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let card_id = 1;
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(card_id));
|
||||
let card_id = uuid::Uuid::new_v4();
|
||||
app.chat_widget.show_status(Some(card_id));
|
||||
let origin = RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: card_id,
|
||||
};
|
||||
@@ -300,9 +292,10 @@ async fn stale_rate_limit_reads_preserve_newer_workspace_hard_stop_for_every_ori
|
||||
reset_hint_request_id: app.chat_widget.start_rate_limit_reset_startup_check(),
|
||||
},
|
||||
"status" => {
|
||||
let request_id = 7;
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
app.chat_widget.show_status(Some(request_id));
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id }
|
||||
}
|
||||
"usage" => {
|
||||
@@ -408,9 +401,10 @@ async fn stale_rate_limit_read_does_not_dismiss_visible_workspace_advisory() ->
|
||||
app.chat_widget.config_ref(),
|
||||
))
|
||||
.await?;
|
||||
let request_id = 7;
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
app.chat_widget.show_status(Some(request_id));
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
let read_generation = app.rate_limit_hard_stop_generation;
|
||||
|
||||
deliver_rolling_rate_limit_snapshot(
|
||||
@@ -474,9 +468,10 @@ async fn post_hard_stop_rate_limit_read_clears_recovered_workspace_limit() -> Re
|
||||
)
|
||||
.await;
|
||||
let read_generation = app.rate_limit_hard_stop_generation;
|
||||
let request_id = 7;
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
app.chat_widget.show_status(Some(request_id));
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
|
||||
let control = Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
@@ -533,9 +528,10 @@ async fn failed_rate_limit_read_preserves_visible_backend_banner() -> Result<()>
|
||||
app.chat_widget.update_backend_banner(&response);
|
||||
let before = render_bottom_popup(&app.chat_widget, /*width*/ 90);
|
||||
assert!(before.contains("Workspace needs credits"));
|
||||
let request_id = 7;
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
app.chat_widget.show_status(Some(request_id));
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
let generation = app.rate_limit_hard_stop_generation;
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
@@ -570,7 +566,9 @@ async fn backend_banner_reads_ignore_older_completions() -> Result<()> {
|
||||
for request_id in 1..=5 {
|
||||
app.rate_limit_refresh_state
|
||||
.start(
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: uuid::Uuid::from_u128(request_id),
|
||||
},
|
||||
&mut app.rate_limit_hard_stop_generation,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -605,7 +603,9 @@ async fn backend_banner_reads_ignore_older_completions() -> Result<()> {
|
||||
&mut session,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id: id,
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id: id },
|
||||
origin: RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: uuid::Uuid::from_u128(id.into()),
|
||||
},
|
||||
hard_stop_generation: generation,
|
||||
result,
|
||||
},
|
||||
|
||||
@@ -7,7 +7,6 @@ use codex_app_server_protocol::ThreadUsage;
|
||||
use codex_protocol::account::PlanType;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::layout::Size;
|
||||
|
||||
async fn app_with_pending_thread_usage()
|
||||
-> Result<(Box<App>, AppServerSession, tui::Tui, ThreadId, Uuid)> {
|
||||
@@ -24,20 +23,14 @@ async fn app_with_pending_thread_usage()
|
||||
/*has_codex_backend_auth*/ true,
|
||||
);
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
let mut app_server =
|
||||
let app_server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0, /*y*/ 21, /*width*/ 80, /*height*/ 3,
|
||||
));
|
||||
|
||||
app.chat_widget.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
let initial_status = match app_event_rx.try_recv() {
|
||||
Ok(event @ AppEvent::InsertHistoryCell(_)) => event,
|
||||
other => panic!("expected immediate status card, got {other:?}"),
|
||||
};
|
||||
app.chat_widget.show_status(/*quota_request*/ None);
|
||||
let request_id = match app_event_rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage {
|
||||
thread_id: requested_thread_id,
|
||||
@@ -45,9 +38,6 @@ async fn app_with_pending_thread_usage()
|
||||
}) if requested_thread_id == thread_id => request_id,
|
||||
other => panic!("expected asynchronous thread usage request, got {other:?}"),
|
||||
};
|
||||
app.handle_event(&mut tui, &mut app_server, initial_status)
|
||||
.await?;
|
||||
|
||||
Ok((app, app_server, tui, thread_id, request_id))
|
||||
}
|
||||
|
||||
@@ -65,20 +55,6 @@ fn successful_thread_usage(thread_id: ThreadId, request_id: Uuid) -> AppEvent {
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_history_text(tui: &tui::Tui) -> String {
|
||||
tui.pending_history_lines_for_test()
|
||||
.into_iter()
|
||||
.map(|line| {
|
||||
line.line
|
||||
.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_updated_with_backend_only_auth_enables_thread_usage() -> Result<()> {
|
||||
let (mut app, mut app_event_rx, _op_rx) = make_test_app_with_channels().await;
|
||||
@@ -106,10 +82,7 @@ async fn account_updated_with_backend_only_auth_enables_thread_usage() -> Result
|
||||
assert!(!app.chat_widget.has_chatgpt_account());
|
||||
assert!(app.chat_widget.has_codex_backend_auth());
|
||||
assert_matches!(app_event_rx.try_recv(), Ok(AppEvent::FetchModels { .. }));
|
||||
app.chat_widget.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
assert_matches!(app_event_rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
app.chat_widget.show_status(/*quota_request*/ None);
|
||||
assert_matches!(
|
||||
app_event_rx.try_recv(),
|
||||
Ok(AppEvent::RefreshThreadUsage {
|
||||
@@ -122,7 +95,7 @@ async fn account_updated_with_backend_only_auth_enables_thread_usage() -> Result
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_reply_corrects_the_first_status_card_in_scrollback() -> Result<()> {
|
||||
async fn quota_reply_updates_account_in_open_status_view() -> Result<()> {
|
||||
let (mut app, mut events, _) = make_test_app_with_channels().await;
|
||||
app.chat_widget.update_account_state(
|
||||
Some(crate::status::StatusAccountDisplay::ChatGpt {
|
||||
@@ -141,13 +114,14 @@ async fn quota_reply_corrects_the_first_status_card_in_scrollback() -> Result<()
|
||||
));
|
||||
let mut server =
|
||||
crate::start_embedded_app_server_for_picker(app.chat_widget.config_ref()).await?;
|
||||
let origin = RateLimitRefreshOrigin::StatusCommand { request_id: 1 };
|
||||
let request_id = uuid::Uuid::new_v4();
|
||||
let origin = RateLimitRefreshOrigin::StatusCommand { request_id };
|
||||
app.chat_widget.show_status(Some(request_id));
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(1));
|
||||
app.handle_event(&mut tui, &mut server, events.try_recv()?)
|
||||
.await?;
|
||||
assert!(pending_history_text(&tui).contains("user@example.com (Plus)"));
|
||||
tui.draw(/*height*/ 3, |_| {})?;
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Left));
|
||||
assert!(
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("user@example.com (Plus)")
|
||||
);
|
||||
|
||||
let (request_id, hard_stop_generation) = app
|
||||
.rate_limit_refresh_state
|
||||
@@ -167,254 +141,41 @@ async fn quota_reply_corrects_the_first_status_card_in_scrollback() -> Result<()
|
||||
.await?;
|
||||
|
||||
assert!(
|
||||
tui.pending_history_lines_for_test().is_empty(),
|
||||
"expected in-place replacement"
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 90).contains("user@example.com (Pro 200)")
|
||||
);
|
||||
let tail = app.last_rendered_history_tail.as_ref().unwrap();
|
||||
let account = tail
|
||||
.lines
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.find(|line| line.contains("Account:"))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(account.split_once("Account:").unwrap().1.trim(), @"user@example.com (Pro 200)");
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_thread_usage_updates_status_without_scrollback_reflow() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
assert!(pending_history_text(&tui).contains("/status"));
|
||||
|
||||
let status = Arc::clone(app.transcript_cells.last().expect("status card"));
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_warning_event("diagnostic".into())),
|
||||
);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
assert!(
|
||||
tui.pending_history_lines_for_test().is_empty(),
|
||||
"a visible status tail should be replaced directly instead of appending a duplicate card"
|
||||
);
|
||||
let rendered = lines_to_single_string(&status.display_lines(/*width*/ 90));
|
||||
assert!(rendered.contains("50 credits"), "{rendered}");
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_usage_after_intervening_history_appends_refreshed_status() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec![
|
||||
Line::from("/status"),
|
||||
Line::from("intervening model output"),
|
||||
])),
|
||||
);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let pending = pending_history_text(&tui);
|
||||
assert!(pending.contains("intervening model output"), "{pending}");
|
||||
assert!(pending.contains("50 credits"), "{pending}");
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_thread_usage_after_intervening_history_does_not_duplicate_status() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec![Line::from(
|
||||
"intervening model output",
|
||||
)])),
|
||||
);
|
||||
let pending_before_failure = pending_history_text(&tui);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::ThreadUsageLoaded {
|
||||
thread_id,
|
||||
request_id,
|
||||
result: Err("thread usage request timed out".to_string()),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
assert_eq!(pending_history_text(&tui), pending_before_failure);
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn thread_usage_finishing_during_overlay_updates_history_after_close() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
tui.set_alt_screen_enabled(/*enabled*/ false);
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.pending_thread_usage_history_refresh);
|
||||
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
|
||||
assert!(!app.pending_thread_usage_history_refresh);
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
assert!(
|
||||
app.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("updated status should remain the rendered history tail")
|
||||
.lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("50 credits"))
|
||||
);
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_discards_thread_usage_deferred_while_overlay_is_open() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
tui.set_alt_screen_enabled(/*enabled*/ false);
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.pending_thread_usage_history_refresh);
|
||||
|
||||
app.handle_app_server_event(
|
||||
&app_server,
|
||||
AppServerEvent::ServerNotification(Box::new(ServerNotification::AccountUpdated(
|
||||
AccountUpdatedNotification {
|
||||
reason: None,
|
||||
auth_mode: Some(AuthMode::AgentIdentity),
|
||||
plan_type: Some(PlanType::Business),
|
||||
},
|
||||
))),
|
||||
)
|
||||
.await;
|
||||
assert!(!app.pending_thread_usage_history_refresh);
|
||||
assert!(app.last_thread_usage_status_cell.is_none());
|
||||
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
|
||||
assert!(!pending_history_text(&tui).contains("50 credits"));
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_reflow_rebases_pending_status_update_to_new_width() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_warning_event("diagnostic".into())),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(
|
||||
history_cell::DynamicToolCallCell::from_item(ThreadItemPayload::DynamicToolCall {
|
||||
id: "pending-tool".into(),
|
||||
namespace: None,
|
||||
tool: "lookup".into(),
|
||||
arguments: serde_json::json!({}),
|
||||
status: codex_app_server_protocol::DynamicToolCallStatus::InProgress,
|
||||
success: None,
|
||||
duration_ms: None,
|
||||
content_items: None,
|
||||
})
|
||||
.unwrap(),
|
||||
),
|
||||
);
|
||||
let original = app
|
||||
.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("initial rendered status")
|
||||
.lines
|
||||
.clone();
|
||||
let screen_size = Size::new(/*width*/ 52, /*height*/ 24);
|
||||
tui.terminal.last_known_screen_size = screen_size;
|
||||
let viewport = Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 21,
|
||||
screen_size.width,
|
||||
/*height*/ 3,
|
||||
);
|
||||
tui.terminal.set_viewport_area(viewport);
|
||||
|
||||
app.reflow_transcript_now(&mut tui, screen_size.into())?;
|
||||
|
||||
let resized = app
|
||||
.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("resized rendered status")
|
||||
.lines
|
||||
.clone();
|
||||
assert_ne!(original, resized);
|
||||
// Bazel tests run without a TTY, so model the settled viewport explicitly
|
||||
// before simulating an asynchronous usage update after resize replay.
|
||||
tui.terminal.set_viewport_area(viewport);
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_status_reads_refreshed_usage_only_when_emitted() -> Result<()> {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
let status = Arc::clone(app.transcript_cells.last().unwrap());
|
||||
tui.clear_pending_history_lines();
|
||||
app.native_history.defer(&status);
|
||||
app.render_inserted_history_cell(&mut tui, &status, /*deferred*/ true);
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
app.flush_native_history(&mut tui);
|
||||
assert_eq!(pending_history_text(&tui).matches("50 credits").count(), 1);
|
||||
app_server.shutdown().await?;
|
||||
async fn thread_usage_reply_updates_only_the_open_status_modal() -> Result<()> {
|
||||
for dismiss in [false, true] {
|
||||
let (mut app, mut app_server, mut tui, thread_id, request_id) =
|
||||
app_with_pending_thread_usage().await?;
|
||||
if dismiss {
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
}
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec![Line::from(
|
||||
"intervening model output",
|
||||
)])),
|
||||
);
|
||||
let before = tui.pending_history_lines_for_test();
|
||||
let history_len = app.transcript_cells.len();
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
successful_thread_usage(thread_id, request_id),
|
||||
)
|
||||
.await?;
|
||||
let popup = render_bottom_popup(&app.chat_widget, /*width*/ 90);
|
||||
assert_eq!(popup.contains("50 credits"), !dismiss, "{popup}");
|
||||
assert_eq!(tui.pending_history_lines_for_test(), before);
|
||||
assert_eq!(app.transcript_cells.len(), history_len);
|
||||
app_server.shutdown().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -413,13 +413,7 @@ async fn assert_transcript_close_repaints_inline_draft(mut app: Box<App>) -> Res
|
||||
app.handle_tui_event(&mut tui, &mut app_server, TuiEvent::Draw)
|
||||
.await?;
|
||||
assert!(!app.transcript_reflow.has_pending_reflow());
|
||||
assert_eq!(
|
||||
app.last_rendered_history_tail
|
||||
.as_ref()
|
||||
.expect("inline history reflowed")
|
||||
.lines,
|
||||
deferred_history
|
||||
);
|
||||
assert!(app.deferred_history_lines.is_empty());
|
||||
|
||||
insta::assert_snapshot!(
|
||||
"transcript_close_restores_inline_draft",
|
||||
|
||||
@@ -141,8 +141,13 @@ async fn unavailable_thread_routes_local_and_recovery_commands() -> Result<()> {
|
||||
.restore_user_message_to_composer("/status".into());
|
||||
app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Enter.into()))
|
||||
.await?;
|
||||
let history = drain_history(&mut app, &mut tui, &mut session, &mut events).await?;
|
||||
assert!(history.contains("Model:"), "{history}");
|
||||
assert_eq!(
|
||||
drain_history(&mut app, &mut tui, &mut session, &mut events).await?,
|
||||
history
|
||||
);
|
||||
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 80).contains("Model:"));
|
||||
app.handle_tui_event(&mut tui, &mut session, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(app.chat_widget.composer_is_empty());
|
||||
assert!(ops.try_recv().is_err());
|
||||
|
||||
|
||||
@@ -258,11 +258,6 @@ impl App {
|
||||
view.cancel_loads();
|
||||
self.retained_analytics = Some(view);
|
||||
}
|
||||
if self.pending_thread_usage_history_refresh
|
||||
&& let Err(err) = self.refresh_thread_usage_history_tail(tui)
|
||||
{
|
||||
tracing::warn!(error = %err, "failed to refresh thread usage after closing overlay");
|
||||
}
|
||||
self.backtrack.overlay_preview_active = false;
|
||||
tui.frame_requester().schedule_frame();
|
||||
if was_backtrack {
|
||||
|
||||
@@ -229,7 +229,7 @@ pub(crate) enum RateLimitRefreshOrigin {
|
||||
StartupPrefetch { reset_hint_request_id: u64 },
|
||||
/// User-initiated via `/status`; the `request_id` correlates with the
|
||||
/// status card that should be updated when the fetch completes.
|
||||
StatusCommand { request_id: u64 },
|
||||
StatusCommand { request_id: Uuid },
|
||||
/// User reopened `/usage` while the cached reset-credit count was zero.
|
||||
UsageMenu { request_id: u64 },
|
||||
/// User opened the reset-credit picker.
|
||||
@@ -686,6 +686,7 @@ pub(crate) enum AppEvent {
|
||||
|
||||
/// Copy text through the session clipboard worker.
|
||||
CopySelection {
|
||||
feedback: Option<crate::chatwidget::StatusCopyFeedback>,
|
||||
text: Arc<str>,
|
||||
label: String,
|
||||
format: crate::clipboard_copy::CopyFormat,
|
||||
|
||||
@@ -55,6 +55,7 @@ use crate::render::renderable::RenderableItem;
|
||||
use crate::terminal_palette::effective_stdout_color_level;
|
||||
use crate::terminal_program_status::ProgramStatusKind;
|
||||
use crate::tui::FrameRequester;
|
||||
pub(crate) const STATUS_VIEW_ID: &str = "status";
|
||||
pub(crate) use bottom_pane_view::BottomPaneView;
|
||||
pub(crate) use bottom_pane_view::ViewCompletion;
|
||||
pub(crate) use bottom_pane_view::ViewPresentation;
|
||||
@@ -171,6 +172,7 @@ mod picker_style;
|
||||
mod shortcut_hud;
|
||||
mod shortcut_overlay;
|
||||
pub(crate) use picker_style::active_tab_style;
|
||||
pub(crate) use picker_style::render_scroll_indicators;
|
||||
pub(crate) use picker_style::selection_style;
|
||||
pub(crate) use shortcut_hud::ShortcutHud;
|
||||
pub(crate) mod prompt_args;
|
||||
@@ -224,7 +226,9 @@ pub(crate) use picker_option::picker_option_list;
|
||||
pub(crate) use picker_option::picker_option_row;
|
||||
pub(crate) mod popup_consts;
|
||||
mod scroll_state;
|
||||
pub(crate) use scroll_state::ScrollState;
|
||||
mod selection_popup_common;
|
||||
pub(crate) use selection_popup_common::RenderedRows;
|
||||
pub(crate) use selection_popup_common::menu_surface_padding_height;
|
||||
pub(crate) use selection_popup_common::render_menu_surface;
|
||||
mod selection_row_layout;
|
||||
@@ -2569,11 +2573,27 @@ impl BottomPane {
|
||||
banner.visible.set(false);
|
||||
}
|
||||
if let Some(view) = views.last() {
|
||||
if view.presentation() == ViewPresentation::Centered {
|
||||
let panel = if view.presentation() == ViewPresentation::Centered {
|
||||
RenderableItem::Owned(Box::new(view_stack::ViewStack(views)))
|
||||
} else {
|
||||
RenderableItem::Borrowed(view.as_ref())
|
||||
};
|
||||
if let Some(status) = self.status_widget()
|
||||
&& view.view_id() == Some(STATUS_VIEW_ID)
|
||||
{
|
||||
let mut flex = FlexRenderable::new();
|
||||
flex.push(
|
||||
/*flex*/ 0,
|
||||
RenderableItem::Owned(Box::new(
|
||||
status
|
||||
.with_timer(&self.status_timer)
|
||||
.without_interrupt_hint(),
|
||||
)),
|
||||
);
|
||||
flex.push(/*flex*/ 1, panel);
|
||||
return RenderableItem::Owned(Box::new(flex));
|
||||
}
|
||||
panel
|
||||
} else {
|
||||
let mut flex = FlexRenderable::new();
|
||||
if let Some(banner) = self
|
||||
|
||||
@@ -51,7 +51,7 @@ pub(crate) fn active_tab_style() -> Style {
|
||||
}
|
||||
|
||||
/// Draw overflow hints against the background already painted beneath each cell.
|
||||
pub(super) fn render_scroll_indicators(area: Rect, buf: &mut Buffer, rendered: RenderedRows) {
|
||||
pub(crate) fn render_scroll_indicators(area: Rect, buf: &mut Buffer, rendered: RenderedRows) {
|
||||
if area.height < 3 || area.width == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ use crate::session_state::SessionNetworkProxyRuntime;
|
||||
use crate::session_state::ThreadSessionState;
|
||||
use crate::status::RateLimitWindowDisplay;
|
||||
use crate::status::StatusAccountDisplay;
|
||||
use crate::status::StatusHistoryHandle;
|
||||
use crate::status::StatusReport;
|
||||
use crate::status::format_directory_display;
|
||||
use crate::status::format_tokens_compact;
|
||||
use crate::status::rate_limit_snapshot_display_for_limit;
|
||||
@@ -305,6 +305,7 @@ mod session_header;
|
||||
use self::session_header::SessionHeader;
|
||||
mod clipboard;
|
||||
pub(crate) use clipboard::ClipboardPasteContext;
|
||||
pub(crate) use clipboard::StatusCopyFeedback;
|
||||
mod copy_picker;
|
||||
mod hook_lifecycle;
|
||||
mod hooks;
|
||||
@@ -401,6 +402,7 @@ use self::status_state::TerminalTitleStatusKind;
|
||||
mod status_controls;
|
||||
mod status_surface_commands;
|
||||
mod status_surfaces;
|
||||
mod status_view;
|
||||
mod statusline_reader;
|
||||
pub(crate) use statusline_reader::StatuslineReadEvent;
|
||||
|
||||
@@ -598,8 +600,9 @@ pub(crate) struct ChatWidget {
|
||||
// Status and polling use account usage reads; response streams may identify meters differently.
|
||||
rate_limit_snapshots_by_limit_id: BTreeMap<String, RateLimitSnapshotDisplay>,
|
||||
inherited_quota_provider: Option<String>,
|
||||
refreshing_status_outputs: Vec<(u64, StatusHistoryHandle)>,
|
||||
next_status_refresh_request_id: u64,
|
||||
// Only StatusView owns a report. Finishing a read after dismissal can still update the cache.
|
||||
active_status: std::sync::Weak<StatusReport>,
|
||||
pending_status_quota: HashMap<uuid::Uuid, std::sync::Weak<StatusReport>>,
|
||||
pending_rate_limit_reset_request_id: Option<u64>,
|
||||
pending_rate_limit_reset_idempotency_key: Option<String>,
|
||||
rate_limit_reset_picker_request_id: Option<u64>,
|
||||
@@ -1459,7 +1462,6 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn on_user_message_display(&mut self, display: UserMessageDisplay) {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
self.last_rendered_user_message_display = Some(display.clone());
|
||||
self.last_rendered_user_message_client_id = None;
|
||||
if !display.message.trim().is_empty()
|
||||
@@ -1953,7 +1955,6 @@ impl ChatWidget {
|
||||
| AppCommand::Review { .. }
|
||||
| AppCommand::RunUserShellCommand { .. }
|
||||
) {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
self.input_queue.user_turn_pending_start = true;
|
||||
}
|
||||
if matches!(op, AppCommand::Interrupt) && self.turn_lifecycle.agent_turn_running {
|
||||
|
||||
@@ -13,8 +13,12 @@ pub(crate) enum ClipboardPasteContext {
|
||||
DraftHandoff,
|
||||
}
|
||||
|
||||
/// Per-modal clipboard results prevent a late completion from updating a new view.
|
||||
pub(crate) type CopyNotice = Option<(Instant, Line<'static>)>;
|
||||
pub(crate) type StatusCopyFeedback = tokio::sync::watch::Sender<CopyNotice>;
|
||||
|
||||
pub(super) enum PendingCopy {
|
||||
Message(u64, String),
|
||||
Message(u64, String, Option<StatusCopyFeedback>),
|
||||
Selection(u64),
|
||||
}
|
||||
|
||||
@@ -105,21 +109,54 @@ impl ChatWidget {
|
||||
.show_footer_flash(line, Duration::from_secs(/*secs*/ 3));
|
||||
}
|
||||
|
||||
pub(crate) fn report_copy_result(
|
||||
&mut self,
|
||||
label: &str,
|
||||
result: &CopyResult,
|
||||
feedback: Option<StatusCopyFeedback>,
|
||||
) {
|
||||
if let Ok(crate::clipboard_copy::CopyStatus::Pending(id)) = result {
|
||||
self.pending_clipboard =
|
||||
Some(PendingCopy::Message(*id, label.into(), feedback.clone()));
|
||||
}
|
||||
let message = match result {
|
||||
// A status report exists only in the panel, so /export cannot recover its fields.
|
||||
Ok(crate::clipboard_copy::CopyStatus::Unconfirmed) if feedback.is_some() => {
|
||||
format!("Sent {label} · try pasting")
|
||||
}
|
||||
Ok(status) => status.message(label),
|
||||
Err(error) => format!("Copy failed: {error}"),
|
||||
};
|
||||
if let Some(feedback) = feedback {
|
||||
let line = if result.is_err() {
|
||||
message.red()
|
||||
} else {
|
||||
message.dim()
|
||||
};
|
||||
let duration = Duration::from_secs(/*secs*/ 3);
|
||||
let _ = feedback.send(Some((Instant::now() + duration, line.into())));
|
||||
} else if result.is_err() {
|
||||
self.add_error_message(message);
|
||||
} else {
|
||||
self.add_info_message(message, /*hint*/ None);
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
pub(crate) fn finish_clipboard(
|
||||
&mut self,
|
||||
completion: &(u64, CopyResult),
|
||||
composer_visible: bool,
|
||||
) -> Option<usize> {
|
||||
let pending_id = match &self.pending_clipboard {
|
||||
Some(PendingCopy::Message(id, _) | PendingCopy::Selection(id)) => Some(*id),
|
||||
Some(PendingCopy::Message(id, ..) | PendingCopy::Selection(id)) => Some(*id),
|
||||
None => None,
|
||||
};
|
||||
if pending_id == Some(completion.0) {
|
||||
match self.pending_clipboard.take() {
|
||||
Some(PendingCopy::Message(_, label)) => match &completion.1 {
|
||||
Ok(status) => self.add_info_message(status.message(&label), /*hint*/ None),
|
||||
Err(error) => self.add_error_message(format!("Copy failed: {error}")),
|
||||
},
|
||||
Some(PendingCopy::Message(_, label, feedback)) => {
|
||||
self.report_copy_result(&label, &completion.1, feedback);
|
||||
}
|
||||
Some(PendingCopy::Selection(_)) => self.show_clipboard_flash(&completion.1),
|
||||
None => {}
|
||||
}
|
||||
|
||||
@@ -172,8 +172,8 @@ impl ChatWidget {
|
||||
token_usage_pending: false,
|
||||
rate_limit_snapshots_by_limit_id: BTreeMap::new(),
|
||||
inherited_quota_provider: None,
|
||||
refreshing_status_outputs: Vec::new(),
|
||||
next_status_refresh_request_id: 0,
|
||||
active_status: std::sync::Weak::new(),
|
||||
pending_status_quota: HashMap::new(),
|
||||
pending_rate_limit_reset_request_id: None,
|
||||
pending_rate_limit_reset_idempotency_key: None,
|
||||
rate_limit_reset_picker_request_id: None,
|
||||
|
||||
@@ -8,9 +8,7 @@ use crate::text_formatting::truncate_text;
|
||||
|
||||
impl ChatWidget {
|
||||
pub(super) fn show_copy_picker(&mut self) {
|
||||
if self.local_settings.transcript_mode.is_owned()
|
||||
&& self.transcript.last_status_copy_targets.is_none()
|
||||
{
|
||||
if self.local_settings.transcript_mode.is_owned() {
|
||||
let guard = Arc::new(crate::copy_input_guard::CopyInputGuard(
|
||||
self.app_event_tx.clone(),
|
||||
));
|
||||
@@ -20,20 +18,7 @@ impl ChatWidget {
|
||||
return;
|
||||
}
|
||||
let mut choices = Vec::new();
|
||||
if let Some(status_targets) = &self.transcript.last_status_copy_targets {
|
||||
choices.push((
|
||||
"Whole status".to_string(),
|
||||
Arc::<str>::from(status_targets.handle.copy_text()),
|
||||
CopyFormat::PlainText,
|
||||
));
|
||||
choices.extend(
|
||||
status_targets
|
||||
.fields
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|(label, text)| (label, text, CopyFormat::PlainText)),
|
||||
);
|
||||
} else if let Some(markdown) = self
|
||||
if let Some(markdown) = self
|
||||
.transcript
|
||||
.last_agent_markdown
|
||||
.as_deref()
|
||||
@@ -99,6 +84,7 @@ impl ChatWidget {
|
||||
text: Arc::clone(&text),
|
||||
label: label.clone(),
|
||||
format: format.clone(),
|
||||
feedback: None,
|
||||
});
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
|
||||
@@ -33,6 +33,7 @@ impl ChatWidget {
|
||||
| SlashCommand::Memories
|
||||
| SlashCommand::Config
|
||||
| SlashCommand::Title
|
||||
| SlashCommand::Status
|
||||
| SlashCommand::Statusline
|
||||
| SlashCommand::Theme,
|
||||
) => false,
|
||||
|
||||
@@ -597,14 +597,7 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
pub(crate) fn show_copy_result(&mut self, label: &str, result: CopyResult) {
|
||||
if let Ok(CopyStatus::Pending(id)) = result {
|
||||
self.pending_clipboard = Some(PendingCopy::Message(id, label.into()));
|
||||
}
|
||||
match result {
|
||||
Ok(status) => self.add_info_message(status.message(label), /*hint*/ None),
|
||||
Err(error) => self.add_error_message(format!("Copy failed: {error}")),
|
||||
}
|
||||
self.request_redraw();
|
||||
self.report_copy_result(label, &result, /*feedback*/ None);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -135,6 +135,7 @@ impl ChatWidget {
|
||||
self.automatic_model_switch_state =
|
||||
backend_banners::AutomaticModelSwitchState::default();
|
||||
self.review.recent_auto_review_denials = RecentAutoReviewDenials::default();
|
||||
self.dismiss_status_view();
|
||||
self.clear_thread_usage_state();
|
||||
}
|
||||
let has_turn_history =
|
||||
|
||||
@@ -277,14 +277,8 @@ impl ChatWidget {
|
||||
self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
|
||||
self.bottom_pane
|
||||
.dismiss_view_by_id(RATE_LIMIT_SWITCH_PROMPT_VIEW_ID);
|
||||
let had_refreshing_status_outputs = !self.refreshing_status_outputs.is_empty();
|
||||
let now = Local::now();
|
||||
for (_, handle) in self.refreshing_status_outputs.drain(..) {
|
||||
handle.finish_rate_limit_refresh(&[], /*quota_plan*/ None, now);
|
||||
}
|
||||
if had_refreshing_status_outputs {
|
||||
self.request_redraw();
|
||||
}
|
||||
self.dismiss_status_view();
|
||||
self.pending_status_quota.clear();
|
||||
self.status_line_workspace_headline = None;
|
||||
self.status_line_workspace_headline_pending_request_id = None;
|
||||
self.status_line_workspace_headline_last_requested_at = None;
|
||||
|
||||
@@ -90,7 +90,6 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
pub(super) fn handle_service_tier_command_dispatch(&mut self, command: ServiceTierCommand) {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
if self.active_side_conversation {
|
||||
self.add_error_message(format!(
|
||||
"'/{}' is unavailable in side conversations. {SIDE_SLASH_COMMAND_UNAVAILABLE_HINT}",
|
||||
@@ -253,9 +252,6 @@ impl ChatWidget {
|
||||
cmd: SlashCommand,
|
||||
source: SlashCommandDispatchSource,
|
||||
) {
|
||||
if cmd != SlashCommand::Copy {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
}
|
||||
if !self.ensure_slash_command_allowed_in_side_conversation(cmd) {
|
||||
return;
|
||||
}
|
||||
@@ -582,18 +578,12 @@ impl ChatWidget {
|
||||
)),
|
||||
SlashCommand::Warnings => self.app_event_tx.send(AppEvent::OpenWarnings),
|
||||
SlashCommand::Status => {
|
||||
if self.should_prefetch_rate_limits() {
|
||||
let request_id = self.next_status_refresh_request_id;
|
||||
self.next_status_refresh_request_id =
|
||||
self.next_status_refresh_request_id.wrapping_add(1);
|
||||
self.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
let quota_request = self.should_prefetch_rate_limits().then(uuid::Uuid::new_v4);
|
||||
self.show_status(quota_request);
|
||||
if let Some(request_id) = quota_request {
|
||||
self.app_event_tx.send(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
});
|
||||
} else {
|
||||
self.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
}
|
||||
}
|
||||
SlashCommand::Cd => {
|
||||
@@ -716,9 +706,6 @@ impl ChatWidget {
|
||||
args: String,
|
||||
text_elements: Vec<TextElement>,
|
||||
) {
|
||||
if cmd != SlashCommand::Copy {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
}
|
||||
if !self.ensure_slash_command_allowed_in_side_conversation(cmd) {
|
||||
return;
|
||||
}
|
||||
@@ -833,9 +820,6 @@ impl ChatWidget {
|
||||
cmd: SlashCommand,
|
||||
prepared: PreparedSlashCommandArgs,
|
||||
) {
|
||||
if cmd != SlashCommand::Copy {
|
||||
self.transcript.last_status_copy_targets = None;
|
||||
}
|
||||
let PreparedSlashCommandArgs {
|
||||
args,
|
||||
text_elements,
|
||||
@@ -1363,7 +1347,10 @@ impl ChatWidget {
|
||||
}
|
||||
|
||||
fn queued_command_drain_result(&self, cmd: SlashCommand) -> QueueDrain {
|
||||
if self.is_user_turn_pending_or_running() || !self.bottom_pane.no_modal_or_popup_active() {
|
||||
if self.is_user_turn_pending_or_running()
|
||||
|| (!self.bottom_pane.no_modal_or_popup_active()
|
||||
&& self.bottom_pane.active_view_id() != Some(crate::bottom_pane::STATUS_VIEW_ID))
|
||||
{
|
||||
return QueueDrain::Stop;
|
||||
}
|
||||
match cmd {
|
||||
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/slash_commands.rs
|
||||
expression: "render_bottom_popup(&chat,\n100).replace(&directory,\n\"[[workspace]]\").replace(crate::version::CODEX_CLI_VERSION, \"VERSION\")"
|
||||
---
|
||||
Copy to clipboard
|
||||
|
||||
|
||||
› 1. Whole status >_ OpenAI Codex (vVERSION)
|
||||
2. Model gpt-5.5
|
||||
3. Directory [[workspace]]
|
||||
4. Thread name Clipboard example
|
||||
5. Session ID 00000000-0000-0000-0000-000000000123
|
||||
|
||||
enter select · esc back
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/status_command_tests.rs
|
||||
expression: "render(&chat, 80)"
|
||||
---
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration Session
|
||||
|
||||
Model: GPT-5.5 (reasoning medium, summaries auto)
|
||||
Model provider: openai
|
||||
Directory: /tmp/project
|
||||
Permissions: Unknown
|
||||
Agents.md: <none>
|
||||
|
||||
←/→ tabs · ↑/↓/j/k select · c copy all · u usage settings · esc close
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/status_command_tests.rs
|
||||
expression: "format!(\"Open\\n{open}\\n\\nFirst j or ↓\\n{first}\\n\\nFirst k or ↑\\n{last}\")"
|
||||
---
|
||||
Open
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration Session
|
||||
|
||||
Model: GPT-5.5 (reasoning medium, summaries auto)
|
||||
Token usage: 0 total (0 input + 0 output)
|
||||
Context window: [███████░░░░░░░░░░░░░] 35% left (172K used / 258K)
|
||||
Limits: data not available yet
|
||||
|
||||
|
||||
←/→ tabs · ↑/↓/j/k select · c copy all · u usage settings · esc close
|
||||
|
||||
First j or ↓
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration Session
|
||||
|
||||
› Model: GPT-5.5 (reasoning medium, summaries auto)
|
||||
Token usage: 0 total (0 input + 0 output)
|
||||
Context window: [███████░░░░░░░░░░░░░] 35% left (172K used / 258K)
|
||||
Limits: data not available yet
|
||||
|
||||
|
||||
←/→ tabs · ↑/↓/j/k select · enter copy · c copy all · u usage · esc close
|
||||
|
||||
First k or ↑
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration Session
|
||||
|
||||
Model: GPT-5.5 (reasoning medium, summaries auto)
|
||||
Token usage: 0 total (0 input + 0 output)
|
||||
Context window: [███████░░░░░░░░░░░░░] 35% left (172K used / 258K)
|
||||
› Limits: data not available yet
|
||||
|
||||
|
||||
←/→ tabs · ↑/↓/j/k select · enter copy · c copy all · u usage · esc close
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/status_command_tests.rs
|
||||
expression: "format!(\"Overview\\n{overview}\\n\\nSession\\n{tall}\\n\\nShort, top\\n{top}\\n\\nPage down\\n{middle}\\n\\nEnd\\n{bottom}\").replace(crate::version::CODEX_CLI_VERSION,\n\"VERSION\")"
|
||||
---
|
||||
Overview
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration ›
|
||||
|
||||
Model: GPT-5.5
|
||||
(reasoning
|
||||
medium,
|
||||
summaries auto)
|
||||
Token usage: 0 total (0
|
||||
input + 0
|
||||
output)
|
||||
Limits: data not
|
||||
available yet
|
||||
|
||||
|
||||
←→ ↑/↓/j/k c all u usage esc
|
||||
|
||||
Session
|
||||
>_ Session status vVERSION
|
||||
|
||||
‹ Configuration Session
|
||||
|
||||
Thread name: Investigate
|
||||
why the task
|
||||
queue pauses
|
||||
when a client
|
||||
reconnects and
|
||||
how to resume
|
||||
pending work
|
||||
without starting
|
||||
duplicate jobs
|
||||
Collaboration mode: Default
|
||||
|
||||
←→ ↑/↓/j/k c all u usage esc
|
||||
|
||||
Short, top
|
||||
>_ Session status vVERSION
|
||||
|
||||
‹ Configuration Session
|
||||
› Thread name: Investigate
|
||||
why the task
|
||||
queue pauses
|
||||
when a client ↓
|
||||
←→ ↑/↓/j/k enter c all u esc
|
||||
|
||||
Page down
|
||||
>_ Session status vVERSION
|
||||
|
||||
‹ Configuration Session
|
||||
› reconnects and ↑
|
||||
how to resume
|
||||
pending work
|
||||
without starting↓
|
||||
←→ ↑/↓/j/k enter c all u esc
|
||||
|
||||
End
|
||||
>_ Session status vVERSION
|
||||
|
||||
‹ Configuration Session
|
||||
pending work ↑
|
||||
without starting
|
||||
duplicate jobs
|
||||
› Collaboration mode: Default
|
||||
←→ ↑/↓/j/k enter c all u esc
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/status_command_tests.rs
|
||||
expression: session
|
||||
---
|
||||
>_ Session status vVERSION
|
||||
|
||||
Overview Configuration Session
|
||||
|
||||
Thread name: Investigate request status
|
||||
Collaboration mode: Default
|
||||
Session: 019fc8ab-1fb2-7000-8000-000000000001
|
||||
|
||||
|
||||
|
||||
←/→ tabs · ↑/↓/j/k select · c copy all · u usage settings · esc close
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Rendering details live in `status_surfaces`; this module owns the mutable
|
||||
//! widget entrypoints that apply status state, open setup views, and update the
|
||||
//! history-facing `/status` surface.
|
||||
//! open `/status` report.
|
||||
|
||||
use super::*;
|
||||
use crate::bottom_pane::StatusLine;
|
||||
@@ -214,11 +214,7 @@ impl ChatWidget {
|
||||
self.refresh_status_surfaces();
|
||||
}
|
||||
|
||||
pub(crate) fn add_status_output(
|
||||
&mut self,
|
||||
refreshing_rate_limits: bool,
|
||||
request_id: Option<u64>,
|
||||
) {
|
||||
pub(crate) fn show_status(&mut self, quota_request: Option<uuid::Uuid>) {
|
||||
let default_usage = TokenUsage::default();
|
||||
let token_info = self.token_info.as_ref();
|
||||
let total_usage = token_info
|
||||
@@ -253,8 +249,9 @@ impl ChatWidget {
|
||||
.collect();
|
||||
let agents_summary =
|
||||
crate::status::compose_agents_summary(&self.config, &self.instruction_source_paths);
|
||||
let (cell, handle) = crate::status::new_status_output_with_rate_limits_handle(
|
||||
let report = Arc::new(StatusReport::new(
|
||||
&self.config,
|
||||
model,
|
||||
self.confirmed_permissions.as_deref(),
|
||||
self.requires_openai_auth,
|
||||
self.thread_id
|
||||
@@ -273,67 +270,51 @@ impl ChatWidget {
|
||||
collaboration_mode,
|
||||
reasoning_effort_override,
|
||||
agents_summary,
|
||||
refreshing_rate_limits,
|
||||
quota_request.is_some(),
|
||||
));
|
||||
self.dismiss_status_view();
|
||||
self.active_status = Arc::downgrade(&report);
|
||||
if let Some(request_id) = quota_request {
|
||||
self.pending_status_quota
|
||||
.insert(request_id, self.active_status.clone());
|
||||
}
|
||||
self.request_thread_usage_for_status(&report);
|
||||
let view = super::status_view::StatusView::new(
|
||||
report,
|
||||
self.app_event_tx.clone(),
|
||||
self.bottom_pane.list_keymap(),
|
||||
);
|
||||
if let Some(request_id) = request_id {
|
||||
self.refreshing_status_outputs
|
||||
.push((request_id, handle.clone()));
|
||||
}
|
||||
if self.thread_usage_is_available() {
|
||||
handle.reserve_thread_usage_label_width();
|
||||
handle.set_thread_usage(self.estimated_thread_usage().cloned(), self.plan_type);
|
||||
self.add_to_history(cell);
|
||||
self.request_thread_usage_for_status(handle.clone());
|
||||
} else {
|
||||
self.add_to_history(cell);
|
||||
}
|
||||
// Capture the displayed status inputs before later configuration or thread changes.
|
||||
let mut copy_targets = vec![
|
||||
("Model".to_string(), Arc::<str>::from(model)),
|
||||
(
|
||||
"Directory".to_string(),
|
||||
Arc::from(self.config.cwd.display().to_string()),
|
||||
),
|
||||
];
|
||||
if let Some(name) = self.thread_name.as_deref().filter(|name| !name.is_empty()) {
|
||||
copy_targets.push(("Thread name".to_string(), Arc::from(name)));
|
||||
}
|
||||
if let Some(thread_id) = self.thread_id {
|
||||
copy_targets.push(("Session ID".to_string(), Arc::from(thread_id.to_string())));
|
||||
}
|
||||
self.transcript.last_status_copy_targets = Some(super::transcript::StatusCopySource {
|
||||
handle,
|
||||
fields: copy_targets,
|
||||
});
|
||||
self.bottom_pane.show_view(Box::new(view));
|
||||
}
|
||||
|
||||
pub(super) fn dismiss_status_view(&mut self) {
|
||||
self.bottom_pane
|
||||
.dismiss_view_by_id(crate::bottom_pane::STATUS_VIEW_ID);
|
||||
self.active_status = std::sync::Weak::new();
|
||||
}
|
||||
|
||||
/// Returns whether terminal history needs to show a corrected account label.
|
||||
pub(crate) fn finish_status_rate_limit_refresh(
|
||||
&mut self,
|
||||
request_id: u64,
|
||||
request_id: uuid::Uuid,
|
||||
snapshots: Vec<RateLimitSnapshot>,
|
||||
) -> bool {
|
||||
let Some(index) = self
|
||||
.refreshing_status_outputs
|
||||
.iter()
|
||||
.position(|(pending_request_id, _)| *pending_request_id == request_id)
|
||||
else {
|
||||
return false;
|
||||
) {
|
||||
let Some(target) = self.pending_status_quota.remove(&request_id) else {
|
||||
return;
|
||||
};
|
||||
for snapshot in snapshots {
|
||||
self.on_rate_limit_snapshot(Some(snapshot));
|
||||
}
|
||||
let (_, handle) = self.refreshing_status_outputs.swap_remove(index);
|
||||
let Some(report) = target.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let rate_limit_snapshots: Vec<RateLimitSnapshotDisplay> = self
|
||||
.rate_limit_snapshots_by_limit_id
|
||||
.values()
|
||||
.cloned()
|
||||
.collect();
|
||||
let plan_changed =
|
||||
handle.finish_rate_limit_refresh(&rate_limit_snapshots, self.quota_plan, Local::now());
|
||||
report.finish_rate_limit_refresh(&rate_limit_snapshots, self.quota_plan, Local::now());
|
||||
self.request_redraw();
|
||||
plan_changed
|
||||
}
|
||||
|
||||
pub(super) fn open_status_line_setup(&mut self) {
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
//! The status panel occupies the composer while its shared report receives asynchronous updates.
|
||||
|
||||
mod navigation;
|
||||
|
||||
use super::StatusCopyFeedback;
|
||||
use super::clipboard::CopyNotice;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::bottom_pane::BottomPaneView;
|
||||
use crate::bottom_pane::CancellationEvent;
|
||||
use crate::bottom_pane::RenderedRows;
|
||||
use crate::bottom_pane::menu_surface_padding_height;
|
||||
use crate::bottom_pane::popup_content_width;
|
||||
use crate::bottom_pane::render_filled_tab_bar;
|
||||
use crate::bottom_pane::render_menu_surface;
|
||||
use crate::bottom_pane::render_scroll_indicators;
|
||||
use crate::clipboard_copy::CopyFormat;
|
||||
use crate::key_hint;
|
||||
use crate::keymap::KeymapContext;
|
||||
use crate::keymap::KeymapContextSet;
|
||||
use crate::keymap::ListAction;
|
||||
use crate::keymap::ListKeymap;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::status::StatusReport;
|
||||
use crate::status::StatusTab;
|
||||
use crate::style::accent_color;
|
||||
use crate::style::selection_style;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::mark_buffer_hyperlinks;
|
||||
use crate::version::CODEX_CLI_VERSION;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use navigation::Viewport;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::Widget;
|
||||
use std::cell::Cell;
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::watch;
|
||||
|
||||
// Title, spacer, tabs.
|
||||
const HEADING_ROWS: u16 = 3;
|
||||
const REPORT_GAPS: u16 = 2;
|
||||
|
||||
fn content_height(tabs: &[StatusTab]) -> u16 {
|
||||
let report_rows = tabs
|
||||
.iter()
|
||||
.map(|tab| tab.lines.len())
|
||||
.max()
|
||||
.unwrap_or_default();
|
||||
let footer_rows = 1;
|
||||
u16::try_from(report_rows.max(1) + usize::from(HEADING_ROWS) + footer_rows).unwrap_or(u16::MAX)
|
||||
}
|
||||
|
||||
pub(super) struct StatusView {
|
||||
report: Arc<StatusReport>,
|
||||
tx: AppEventSender,
|
||||
keys: ListKeymap,
|
||||
feedback: StatusCopyFeedback,
|
||||
tab: usize,
|
||||
notice: watch::Receiver<CopyNotice>,
|
||||
width: Cell<u16>,
|
||||
viewport: RefCell<Viewport>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl StatusView {
|
||||
pub(super) fn new(report: Arc<StatusReport>, tx: AppEventSender, keys: ListKeymap) -> Self {
|
||||
let (feedback, notice) = watch::channel(None);
|
||||
Self {
|
||||
report,
|
||||
tx,
|
||||
keys,
|
||||
feedback,
|
||||
tab: 0,
|
||||
notice,
|
||||
width: Cell::new(u16::MAX),
|
||||
viewport: RefCell::default(),
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_reports(&self, width: u16) -> [StatusTab; StatusReport::TAB_TITLES.len()] {
|
||||
let inner = popup_content_width(width);
|
||||
let width = if inner == 0 { width } else { inner };
|
||||
self.report.tabs(width)
|
||||
}
|
||||
|
||||
fn shortcut(&self, key: char) -> Option<key_hint::KeyBinding> {
|
||||
let code = KeyCode::Char(key);
|
||||
(self.keys.action_for(code.into()).is_none() && !self.keys.has_chord_prefix(code.into()))
|
||||
.then(|| key_hint::plain(code))
|
||||
}
|
||||
|
||||
fn copy_all_key(&self) -> Option<key_hint::KeyBinding> {
|
||||
self.shortcut('c').or_else(|| self.shortcut('a'))
|
||||
}
|
||||
|
||||
fn copy(&self, label: String, text: String) {
|
||||
self.tx.send(AppEvent::CopySelection {
|
||||
text: text.into(),
|
||||
label,
|
||||
format: CopyFormat::PlainText,
|
||||
feedback: Some(self.feedback.clone()),
|
||||
});
|
||||
}
|
||||
|
||||
fn hints(&self, width: u16, selected: bool) -> HyperlinkLine {
|
||||
let key = |action| {
|
||||
self.keys
|
||||
.primary_hint(action)
|
||||
.map(key_hint::ShortcutHint::display_label)
|
||||
};
|
||||
let pair = |a, b| [key(a), key(b)].into_iter().flatten().collect::<Vec<_>>();
|
||||
let tabs = pair(ListAction::MoveLeft, ListAction::MoveRight).join("/");
|
||||
let mut move_keys = pair(ListAction::MoveUp, ListAction::MoveDown);
|
||||
for (code, action) in [
|
||||
(KeyCode::Up, ListAction::MoveUp),
|
||||
(KeyCode::Down, ListAction::MoveDown),
|
||||
(KeyCode::Char('j'), ListAction::MoveDown),
|
||||
(KeyCode::Char('k'), ListAction::MoveUp),
|
||||
] {
|
||||
let label = key_hint::plain(code).display_label();
|
||||
if self.keys.action_for(code.into()) == Some(action) && !move_keys.contains(&label) {
|
||||
move_keys.push(label);
|
||||
}
|
||||
}
|
||||
let select = move_keys.join("/");
|
||||
let copy = key(ListAction::Accept).filter(|_| selected);
|
||||
let copy_all = self.copy_all_key().map(|binding| binding.display_label());
|
||||
let close = key(ListAction::Cancel);
|
||||
let render = |compact, separator: &'static str, usage_label: &'static str| {
|
||||
let mut line = HyperlinkLine::default();
|
||||
let mut hint = |key: &str, label: &'static str, url: Option<&str>| {
|
||||
if key.is_empty() && label.is_empty() {
|
||||
return;
|
||||
}
|
||||
if !line.line.spans.is_empty() {
|
||||
line.line.push_span(separator.dim());
|
||||
}
|
||||
for span in key_hint::key_label_spans(key) {
|
||||
line.push_span(span, url);
|
||||
}
|
||||
if !key.is_empty() && !label.is_empty() {
|
||||
line.push_span(" ".dim(), url);
|
||||
}
|
||||
line.push_span(label.dim(), url);
|
||||
};
|
||||
if !tabs.is_empty() {
|
||||
let label = if compact && tabs == "←/→" {
|
||||
"←→"
|
||||
} else {
|
||||
&tabs
|
||||
};
|
||||
hint(label, if compact { "" } else { "tabs" }, None);
|
||||
}
|
||||
if !select.is_empty() {
|
||||
hint(&select, if compact { "" } else { "select" }, None);
|
||||
}
|
||||
if let Some(key) = © {
|
||||
hint(key, if usage_label.is_empty() { "" } else { "copy" }, None);
|
||||
}
|
||||
if let Some(key) = ©_all {
|
||||
hint(key, if compact { "all" } else { "copy all" }, None);
|
||||
}
|
||||
if let Some(url) = self.report.usage_url() {
|
||||
if self.shortcut('u').is_some() {
|
||||
hint("u", usage_label, Some(url));
|
||||
} else {
|
||||
hint("", if compact { "usage" } else { usage_label }, Some(url));
|
||||
}
|
||||
}
|
||||
if let Some(key) = &close {
|
||||
hint(key, if compact { "" } else { "close" }, None);
|
||||
}
|
||||
line
|
||||
};
|
||||
for (compact, separator, usage_label) in [
|
||||
(false, " · ", "usage settings"),
|
||||
(false, " · ", "usage"),
|
||||
(false, " ", "usage"),
|
||||
(true, " ", "usage"),
|
||||
(true, " ", "usage"),
|
||||
] {
|
||||
let line = render(compact, separator, usage_label);
|
||||
if line.width() <= usize::from(width) {
|
||||
return line;
|
||||
}
|
||||
}
|
||||
render(/*compact*/ true, " ", "")
|
||||
}
|
||||
|
||||
fn render_header(&self, area: Rect, buf: &mut Buffer) {
|
||||
let message = self
|
||||
.notice
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.filter(|(expiry, _)| *expiry > Instant::now())
|
||||
.map(|(_, line)| line.clone());
|
||||
if area.is_empty() {
|
||||
return;
|
||||
}
|
||||
let title = Line::from(vec![">_ ".fg(accent_color()), "Session status".bold()]);
|
||||
let row = Rect { height: 1, ..area };
|
||||
let has_message = message.is_some();
|
||||
let info = message.unwrap_or_else(|| Line::from(format!("v{CODEX_CLI_VERSION}").dim()));
|
||||
if title.width() + 2 + info.width() <= usize::from(area.width) {
|
||||
title.render(row, buf);
|
||||
info.right_aligned().render(row, buf);
|
||||
} else if has_message {
|
||||
info.render(row, buf);
|
||||
} else {
|
||||
title.render(row, buf);
|
||||
}
|
||||
if area.height > 1 {
|
||||
render_filled_tab_bar(
|
||||
&StatusReport::TAB_TITLES,
|
||||
self.tab,
|
||||
Rect {
|
||||
y: row.y + area.height.min(HEADING_ROWS) - 1,
|
||||
..row
|
||||
},
|
||||
buf,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BottomPaneView for StatusView {
|
||||
fn next_frame_delay(&self) -> Option<Duration> {
|
||||
self.notice
|
||||
.borrow()
|
||||
.as_ref()?
|
||||
.0
|
||||
.checked_duration_since(Instant::now())
|
||||
}
|
||||
|
||||
fn view_id(&self) -> Option<&'static str> {
|
||||
Some(crate::bottom_pane::STATUS_VIEW_ID)
|
||||
}
|
||||
|
||||
fn keymap_contexts(&self) -> KeymapContextSet {
|
||||
KeymapContextSet::new(KeymapContext::List)
|
||||
}
|
||||
|
||||
fn accepts_input_when_disconnected(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, key: KeyEvent) {
|
||||
let count = StatusReport::TAB_TITLES.len();
|
||||
match self.keys.action_for(key) {
|
||||
Some(ListAction::MoveLeft) => {
|
||||
self.tab = (self.tab + count - 1) % count;
|
||||
self.viewport.get_mut().reset();
|
||||
}
|
||||
Some(ListAction::MoveRight) => {
|
||||
self.tab = (self.tab + 1) % count;
|
||||
self.viewport.get_mut().reset();
|
||||
}
|
||||
Some(ListAction::Cancel) => self.done = true,
|
||||
Some(ListAction::Accept) => {
|
||||
let tab = &self.tab_reports(self.width.get())[self.tab];
|
||||
if key.kind == KeyEventKind::Press
|
||||
&& let Some(index) = self.viewport.get_mut().reconcile(tab)
|
||||
{
|
||||
let field = &tab.fields[index].1;
|
||||
self.copy(field.label.clone(), field.value.clone());
|
||||
}
|
||||
}
|
||||
Some(action) => {
|
||||
let tab = &self.tab_reports(self.width.get())[self.tab];
|
||||
self.viewport.get_mut().navigate(tab, action);
|
||||
}
|
||||
None => {
|
||||
if key.kind != KeyEventKind::Press {
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.copy_all_key()
|
||||
.is_some_and(|binding| binding.is_press(key))
|
||||
{
|
||||
self.copy("Whole status".into(), self.report.copy_text());
|
||||
} else if let Some(url) = self.report.usage_url()
|
||||
&& self
|
||||
.shortcut('u')
|
||||
.is_some_and(|binding| binding.is_press(key))
|
||||
{
|
||||
self.tx.send(AppEvent::OpenUrlInBrowser { url: url.into() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prefer_esc_to_handle_key_event(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn on_ctrl_c(&mut self) -> CancellationEvent {
|
||||
self.done = true;
|
||||
CancellationEvent::Handled
|
||||
}
|
||||
|
||||
fn is_complete(&self) -> bool {
|
||||
self.done
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for StatusView {
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
content_height(&self.tab_reports(width))
|
||||
.saturating_add(REPORT_GAPS + menu_surface_padding_height())
|
||||
}
|
||||
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
if area.is_empty() {
|
||||
return;
|
||||
}
|
||||
let tabs = self.tab_reports(area.width);
|
||||
let tab = &tabs[self.tab];
|
||||
self.width.set(area.width);
|
||||
let padded = render_menu_surface(area, buf);
|
||||
// The first spare row separates the report from the footer, the second from the tabs.
|
||||
let spare = area.height.saturating_sub(content_height(&tabs));
|
||||
let tab_gap = u16::from(spare >= REPORT_GAPS);
|
||||
let padding = spare
|
||||
.saturating_sub(REPORT_GAPS)
|
||||
.min(menu_surface_padding_height());
|
||||
let inner = Rect {
|
||||
y: area.y + padding.div_ceil(2),
|
||||
height: area.height - padding,
|
||||
..if padded.width > 0 { padded } else { area }
|
||||
};
|
||||
let header_height = inner.height.saturating_sub(2).min(HEADING_ROWS + tab_gap);
|
||||
self.render_header(
|
||||
Rect {
|
||||
height: header_height,
|
||||
..inner
|
||||
},
|
||||
buf,
|
||||
);
|
||||
let show_footer = inner.height >= 2;
|
||||
let body_y = inner.y + header_height;
|
||||
let height = inner.height - header_height - u16::from(show_footer);
|
||||
let mut viewport = self.viewport.borrow_mut();
|
||||
viewport.height = usize::from(height);
|
||||
let selected = viewport.reconcile(tab).map(|index| &tab.fields[index].0);
|
||||
let offset = viewport.offset;
|
||||
for (y, line) in (body_y..body_y + height).zip(tab.lines.iter().skip(offset)) {
|
||||
let row = Rect::new(inner.x, y, inner.width, 1);
|
||||
Widget::render(line, row, buf);
|
||||
if selected.is_some_and(|range| range.contains(&(offset + usize::from(y - body_y)))) {
|
||||
buf.set_style(row, selection_style());
|
||||
}
|
||||
}
|
||||
// Selection and overflow can share a screen line, so use opposite gutters.
|
||||
let gutter_width = area.right() - inner.right();
|
||||
let gutter = if height >= 3 {
|
||||
Rect::new(inner.right(), body_y, gutter_width, height)
|
||||
} else {
|
||||
Rect::new(inner.right(), inner.y, gutter_width, inner.height)
|
||||
};
|
||||
render_scroll_indicators(
|
||||
gutter,
|
||||
buf,
|
||||
RenderedRows {
|
||||
has_above: offset > 0,
|
||||
has_below: offset + viewport.height < tab.lines.len(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
if let Some(range) = selected
|
||||
&& inner.x > area.x
|
||||
{
|
||||
let y = body_y + range.start.saturating_sub(offset) as u16;
|
||||
buf[(area.x, y)]
|
||||
.set_symbol("›")
|
||||
.set_style(selection_style());
|
||||
}
|
||||
if show_footer {
|
||||
let footer = Rect::new(inner.x, inner.bottom() - 1, inner.width, 1);
|
||||
let hints = self.hints(inner.width, selected.is_some());
|
||||
Widget::render(&hints.line, footer, buf);
|
||||
mark_buffer_hyperlinks(buf, footer, &[hints], /*scroll_rows*/ 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Navigate logical fields while paging through their wrapped screen lines.
|
||||
|
||||
use crate::bottom_pane::ScrollState;
|
||||
use crate::keymap::ListAction;
|
||||
use crate::status::StatusFieldId;
|
||||
use crate::status::StatusTab;
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Viewport {
|
||||
selected: Option<StatusFieldId>,
|
||||
pub(super) offset: usize,
|
||||
pub(super) height: usize,
|
||||
}
|
||||
|
||||
impl Viewport {
|
||||
pub(super) fn reset(&mut self) {
|
||||
self.selected = None;
|
||||
self.offset = 0;
|
||||
}
|
||||
|
||||
/// Resolve the selection against the latest quota/billing data and terminal width.
|
||||
pub(super) fn reconcile(&mut self, tab: &StatusTab) -> Option<usize> {
|
||||
self.offset = self.offset.min(tab.lines.len().saturating_sub(self.height));
|
||||
let selected = self.selected.as_ref()?;
|
||||
let Some(index) = tab
|
||||
.fields
|
||||
.iter()
|
||||
.position(|(_, field)| &field.id == selected)
|
||||
else {
|
||||
self.selected = None;
|
||||
return None;
|
||||
};
|
||||
let range = &tab.fields[index].0;
|
||||
if !self.intersects(range) {
|
||||
self.reveal(range);
|
||||
}
|
||||
Some(index)
|
||||
}
|
||||
|
||||
fn intersects(&self, range: &Range<usize>) -> bool {
|
||||
range.end > self.offset && range.start < self.offset + self.height.max(1)
|
||||
}
|
||||
|
||||
fn reveal(&mut self, range: &Range<usize>) {
|
||||
if range.start < self.offset || range.len() > self.height {
|
||||
self.offset = range.start;
|
||||
} else {
|
||||
self.offset = self.offset.max(range.end.saturating_sub(self.height));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn navigate(&mut self, tab: &StatusTab, action: ListAction) {
|
||||
let selected_idx = self.reconcile(tab);
|
||||
let max_offset = tab.lines.len().saturating_sub(self.height);
|
||||
if matches!(action, ListAction::PageDown | ListAction::PageUp) {
|
||||
let step = self.height.max(1);
|
||||
self.offset = if action == ListAction::PageDown {
|
||||
(self.offset + step).min(max_offset)
|
||||
} else {
|
||||
self.offset.saturating_sub(step)
|
||||
};
|
||||
if selected_idx.is_some_and(|idx| !self.intersects(&tab.fields[idx].0)) {
|
||||
self.selected = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let mut state = ScrollState {
|
||||
selected_idx,
|
||||
..Default::default()
|
||||
};
|
||||
let movement = if action == ListAction::MoveUp && selected_idx.is_none() {
|
||||
ListAction::JumpBottom
|
||||
} else {
|
||||
action
|
||||
};
|
||||
state.apply_vertical_action(movement, tab.fields.len(), self.height);
|
||||
if let Some(index) = state.selected_idx {
|
||||
let (range, field) = &tab.fields[index];
|
||||
self.selected = Some(field.id.clone());
|
||||
self.reveal(range);
|
||||
if action == ListAction::JumpBottom {
|
||||
self.offset = max_offset;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,16 +125,10 @@ async fn permission_status_follows_the_displayed_thread() {
|
||||
let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("gpt-5.2")).await;
|
||||
chat.local_settings.tui.status_line = Some(vec!["permissions".into(), "approval-mode".into()]);
|
||||
let rendered = |chat: &mut ChatWidget| {
|
||||
chat.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
let card = chat
|
||||
.transcript
|
||||
.last_status_copy_targets
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.handle
|
||||
.copy_text();
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
let card = render_bottom_popup(chat, /*width*/ 120);
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
let permissions = card
|
||||
.lines()
|
||||
.find_map(|line| line.split_once("Permissions:"))
|
||||
@@ -190,15 +184,10 @@ async fn session_and_settings_sync_server_provider_id() {
|
||||
chat.refresh_status_line();
|
||||
assert_eq!(status_line_text(&chat), None);
|
||||
let status = |chat: &mut ChatWidget| {
|
||||
chat.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
chat.transcript
|
||||
.last_status_copy_targets
|
||||
.as_ref()
|
||||
.expect("status")
|
||||
.handle
|
||||
.copy_text()
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
let report = chat.active_status.upgrade().expect("status").copy_text();
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
report
|
||||
};
|
||||
assert!(!status(&mut chat).contains("Model provider:"));
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ async fn copy_export_picker_custom_keys_preserve_payloads_and_composer_draft() {
|
||||
text,
|
||||
label,
|
||||
format,
|
||||
..
|
||||
} => Some((text.to_string(), label, format)),
|
||||
_ => None,
|
||||
});
|
||||
@@ -137,7 +138,9 @@ async fn owned_copy_opens_transcript_selection() {
|
||||
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned;
|
||||
let markdown = "Latest **response**\n\n```sh\necho hello \n```";
|
||||
chat.transcript.last_agent_markdown = Some(markdown.into());
|
||||
chat.show_copy_picker();
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
assert!(
|
||||
std::iter::from_fn(|| rx.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::SelectTranscriptCopy { .. }))
|
||||
|
||||
@@ -1380,7 +1380,10 @@ pub(super) fn render_bottom_first_row(chat: &ChatWidget, width: u16) -> String {
|
||||
}
|
||||
|
||||
pub(crate) fn render_bottom_popup(chat: &ChatWidget, width: u16) -> String {
|
||||
let height = chat.desired_height(width);
|
||||
render_bottom_popup_at_size(chat, width, chat.desired_height(width))
|
||||
}
|
||||
|
||||
pub(super) fn render_bottom_popup_at_size(chat: &ChatWidget, width: u16, height: u16) -> String {
|
||||
let area = Rect::new(0, 0, width, height);
|
||||
let mut buf = Buffer::empty(area);
|
||||
chat.render(area, &mut buf);
|
||||
|
||||
@@ -1858,7 +1858,7 @@ async fn slash_copy_picker_previews_whole_response_code_blocks_and_blockquotes()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_copy_picker_copies_status_fields_and_preserves_source_after_copying() {
|
||||
async fn status_copies_the_open_report_from_any_tab() {
|
||||
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await;
|
||||
let session_id = "00000000-0000-0000-0000-000000000123";
|
||||
chat.thread_id = Some(ThreadId::from_string(session_id).expect("valid thread ID"));
|
||||
@@ -1866,20 +1866,18 @@ async fn slash_copy_picker_copies_status_fields_and_preserves_source_after_copyi
|
||||
chat.config.cwd = test_path_buf("/workspace").abs();
|
||||
let directory = chat.config.cwd.display().to_string();
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
// The picker must copy the status that was displayed, not newer widget settings.
|
||||
chat.config.cwd = test_path_buf("/another-workspace").abs();
|
||||
chat.thread_name = Some("New name".to_string());
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
assert_chatwidget_snapshot!(
|
||||
"slash_copy_picker_status_fields",
|
||||
render_bottom_popup(&chat, /*width*/ 100)
|
||||
.replace(&directory, "[[workspace]]")
|
||||
.replace(crate::version::CODEX_CLI_VERSION, "VERSION"),
|
||||
);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
let (whole_status, label) = next_copy_selection(&mut rx);
|
||||
|
||||
chat.handle_key_event(KeyCode::Char('c').into());
|
||||
let Ok(AppEvent::CopySelection {
|
||||
text: whole_status,
|
||||
label,
|
||||
..
|
||||
}) = rx.try_recv()
|
||||
else {
|
||||
panic!("expected the open report");
|
||||
};
|
||||
assert_eq!(label, "Whole status");
|
||||
assert_chatwidget_snapshot!(
|
||||
"slash_copy_whole_status",
|
||||
@@ -1887,115 +1885,49 @@ async fn slash_copy_picker_copies_status_fields_and_preserves_source_after_copyi
|
||||
.replace(&directory, "[[workspace]]")
|
||||
.replace(crate::version::CODEX_CLI_VERSION, "VERSION"),
|
||||
);
|
||||
let expected = [
|
||||
("Whole status", whole_status.as_str()),
|
||||
("Model", "gpt-5.5"),
|
||||
("Directory", directory.as_str()),
|
||||
("Thread name", "Clipboard example"),
|
||||
("Session ID", session_id),
|
||||
];
|
||||
for (index, (label, value)) in expected.into_iter().enumerate() {
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
let shortcut =
|
||||
char::from_digit((index + 1) as u32, /*radix*/ 10).expect("numeric shortcut");
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char(shortcut), KeyModifiers::NONE));
|
||||
assert_eq!(
|
||||
next_copy_selection(&mut rx),
|
||||
(value.to_string(), label.to_string())
|
||||
);
|
||||
chat.show_copy_result(label, Ok(crate::clipboard_copy::CopyStatus::Confirmed));
|
||||
drain_insert_history(&mut rx);
|
||||
assert!(chat.bottom_pane.no_modal_or_popup_active());
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::CopySelection { text, .. }) if text.as_ref() == "gpt-5.5");
|
||||
for _ in 0..2 {
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
chat.handle_key_event(KeyCode::End.into());
|
||||
chat.handle_key_event(KeyCode::Char('c').into());
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::CopySelection { text, .. }) if text == whole_status);
|
||||
}
|
||||
assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_copy_status_omits_missing_fields_and_copies_full_directory() {
|
||||
async fn status_copies_a_wrapped_directory_in_full() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
|
||||
chat.config.cwd = test_path_buf(&format!("/workspace/{}", "nested/".repeat(/*n*/ 20))).abs();
|
||||
chat.config.cwd =
|
||||
test_path_buf(&format!("/workspace/{}", "nested/日本語/".repeat(/*n*/ 20))).abs();
|
||||
let directory = chat.config.cwd.display().to_string();
|
||||
chat.thread_name = Some(String::new());
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
let popup = render_bottom_popup(&chat, /*width*/ 80);
|
||||
assert!(popup.contains("2. Model"));
|
||||
assert!(popup.contains("3. Directory"));
|
||||
assert!(!popup.contains("Thread name"));
|
||||
assert!(!popup.contains("Session ID"));
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char('3'), KeyModifiers::NONE));
|
||||
assert_eq!(
|
||||
next_copy_selection(&mut rx),
|
||||
(directory, "Directory".to_string())
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
render_bottom_popup_at_size(&chat, /*width*/ 32, /*height*/ 9);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::CopySelection { text, label, .. }) if text.as_ref() == directory && label == "Directory");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slash_copy_status_yields_to_later_turns_and_commands_even_after_refresh() {
|
||||
enum NextTurn {
|
||||
Response,
|
||||
UserTurn,
|
||||
Command,
|
||||
InlineCommand,
|
||||
RejectedInlineCommand,
|
||||
ServiceTier,
|
||||
ShellCommand,
|
||||
}
|
||||
for next in [
|
||||
NextTurn::Response,
|
||||
NextTurn::UserTurn,
|
||||
NextTurn::Command,
|
||||
NextTurn::InlineCommand,
|
||||
NextTurn::RejectedInlineCommand,
|
||||
NextTurn::ServiceTier,
|
||||
NextTurn::ShellCommand,
|
||||
] {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
|
||||
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
complete_turn_with_message(&mut chat, "turn-1", Some("Original reply"));
|
||||
set_chatgpt_auth(&mut chat);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
drain_insert_history(&mut rx);
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("1. Whole status"));
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
drain_insert_history(&mut rx);
|
||||
async fn slash_copy_after_dismissing_status_targets_the_conversation() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.4")).await;
|
||||
chat.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
complete_turn_with_message(&mut chat, "turn-1", Some("Original reply"));
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
match next {
|
||||
NextTurn::Response => {
|
||||
complete_turn_with_message(&mut chat, "turn-2", Some("Next reply"))
|
||||
}
|
||||
NextTurn::UserTurn => chat.submit_user_message(UserMessage::from("Next question")),
|
||||
NextTurn::Command => chat.dispatch_command(SlashCommand::Pwd),
|
||||
NextTurn::InlineCommand => chat.dispatch_command_with_args(
|
||||
SlashCommand::Rename,
|
||||
"Renamed thread".to_string(),
|
||||
Vec::new(),
|
||||
),
|
||||
NextTurn::RejectedInlineCommand => {
|
||||
handle_turn_started(&mut chat, "turn-2");
|
||||
chat.dispatch_command_with_args(SlashCommand::Cd, "/tmp".to_string(), Vec::new());
|
||||
}
|
||||
NextTurn::ServiceTier => chat.handle_service_tier_command_dispatch(fast_tier_command()),
|
||||
NextTurn::ShellCommand => chat.submit_user_message(UserMessage::from("!echo hello")),
|
||||
}
|
||||
chat.finish_status_rate_limit_refresh(/*request_id*/ 0, Vec::new());
|
||||
drain_insert_history(&mut rx);
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
|
||||
let expected = if matches!(next, NextTurn::Response) {
|
||||
"Next reply"
|
||||
} else {
|
||||
"Original reply"
|
||||
};
|
||||
assert_eq!(
|
||||
next_copy_selection(&mut rx),
|
||||
(expected.to_string(), "Whole response".to_string())
|
||||
);
|
||||
}
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_eq!(
|
||||
next_copy_selection(&mut rx),
|
||||
("Original reply".to_string(), "Whole response".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2008,13 +1940,9 @@ async fn slash_copy_status_yields_to_queued_commands_after_queued_status() {
|
||||
queue_composer_text_with_tab(&mut chat, "/status");
|
||||
queue_composer_text_with_tab(&mut chat, command);
|
||||
complete_turn_with_message(&mut chat, "turn-1", Some("Original reply"));
|
||||
let history = drain_insert_history(&mut rx);
|
||||
assert!(
|
||||
history
|
||||
.iter()
|
||||
.any(|lines| lines_to_single_string(lines).contains("/status"))
|
||||
);
|
||||
drain_insert_history(&mut rx);
|
||||
assert!(chat.input_queue.queued_user_messages.is_empty());
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Esc));
|
||||
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
|
||||
@@ -2130,6 +2058,7 @@ async fn slash_copy_picker_renders_only_whole_responses_as_markdown() {
|
||||
text,
|
||||
label,
|
||||
format,
|
||||
..
|
||||
} = event
|
||||
else {
|
||||
panic!("expected selected clipboard content, got {event:?}");
|
||||
|
||||
@@ -440,7 +440,7 @@ async fn context_indicator_shows_used_tokens_when_window_unknown() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn token_usage_update_uses_runtime_context_window() {
|
||||
let (mut chat, mut rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let (mut chat, _rx, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
|
||||
chat.config.model_context_window = Some(1_000_000);
|
||||
|
||||
@@ -457,21 +457,11 @@ async fn token_usage_update_uses_runtime_context_window() {
|
||||
);
|
||||
assert_eq!(chat.bottom_pane.context_window_percent(), Some(100));
|
||||
|
||||
chat.add_status_output(
|
||||
/*refreshing_rate_limits*/ false, /*request_id*/ None,
|
||||
);
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
|
||||
let cells = drain_insert_history(&mut rx);
|
||||
let context_line = cells
|
||||
.last()
|
||||
.expect("status output inserted")
|
||||
.iter()
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.iter()
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect::<String>()
|
||||
})
|
||||
let popup = render_bottom_popup(&chat, /*width*/ 100);
|
||||
let context_line = popup
|
||||
.lines()
|
||||
.find(|line| line.contains("Context window"))
|
||||
.expect("context window line");
|
||||
|
||||
|
||||
@@ -5,6 +5,10 @@ use codex_app_server_protocol::ThreadUsage;
|
||||
use codex_app_server_protocol::ThreadUsageBreakdownGroup;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
fn report(chat: &ChatWidget) -> Arc<StatusReport> {
|
||||
chat.active_status.upgrade().unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_renders_immediately_and_refreshes_rate_limits_for_chatgpt_auth() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
@@ -12,23 +16,16 @@ async fn status_command_renders_immediately_and_refreshes_rate_limits_for_chatgp
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
||||
}
|
||||
other => panic!("expected status output before refresh request, got {other:?}"),
|
||||
};
|
||||
assert!(
|
||||
!rendered.contains("refreshing limits"),
|
||||
"expected /status to avoid transient refresh text in terminal history, got: {rendered}"
|
||||
);
|
||||
let rendered = render_bottom_popup(&chat, /*width*/ 80);
|
||||
assert!(rendered.contains("Session status"));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
}) => request_id,
|
||||
other => panic!("expected rate-limit refresh request, got {other:?}"),
|
||||
};
|
||||
pretty_assertions::assert_eq!(request_id, 0);
|
||||
chat.finish_status_rate_limit_refresh(request_id, Vec::new());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("data not available yet"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -43,12 +40,7 @@ async fn status_command_refresh_updates_cached_limits_for_future_status_outputs(
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
assert!(lines_to_single_string(&cell.display_lines(/*width*/ 80)).contains("(Plus)"));
|
||||
}
|
||||
other => panic!("expected status output before refresh request, got {other:?}"),
|
||||
}
|
||||
assert!(report(&chat).copy_text().contains("(Plus)"));
|
||||
let first_request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
@@ -61,22 +53,16 @@ async fn status_command_refresh_updates_cached_limits_for_future_status_outputs(
|
||||
chat.finish_status_rate_limit_refresh(first_request_id, vec![limits]);
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Copy);
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
chat.handle_key_event(KeyCode::Char('c').into());
|
||||
assert_matches!(
|
||||
rx.try_recv(),
|
||||
Ok(AppEvent::CopySelection { text, label, .. })
|
||||
if label == "Whole status" && text.contains("8% left") && text.contains("user@example.com (Pro 200)")
|
||||
);
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::SettingsSelectionClosed));
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let refreshed = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
||||
}
|
||||
other => panic!("expected refreshed status output, got {other:?}"),
|
||||
};
|
||||
let refreshed = report(&chat).copy_text();
|
||||
insta::assert_snapshot!(
|
||||
refreshed.lines().find_map(|line| line.trim().strip_prefix("Account:")).unwrap().trim(),
|
||||
@"user@example.com (Pro 200)"
|
||||
@@ -93,7 +79,8 @@ async fn status_command_refresh_updates_cached_limits_for_future_status_outputs(
|
||||
};
|
||||
let mut limits = snapshot(/*percent*/ 93.0);
|
||||
limits.plan_type = Some(PlanType::Pro);
|
||||
assert!(!chat.finish_status_rate_limit_refresh(request_id, vec![limits]));
|
||||
chat.finish_status_rate_limit_refresh(request_id, vec![limits]);
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("7% left"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -102,7 +89,6 @@ async fn status_command_renders_immediately_without_rate_limit_refresh() {
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
assert!(
|
||||
!std::iter::from_fn(|| rx.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::RefreshRateLimits { .. })),
|
||||
@@ -112,17 +98,12 @@ async fn status_command_renders_immediately_without_rate_limit_refresh() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_uses_catalog_default_reasoning_when_config_empty() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await;
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.5")).await;
|
||||
chat.config.model_reasoning_effort = None;
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
||||
}
|
||||
other => panic!("expected status output, got {other:?}"),
|
||||
};
|
||||
let rendered = render_bottom_popup(&chat, /*width*/ 120);
|
||||
assert!(
|
||||
rendered.contains("GPT-5.5 (reasoning medium, summaries auto)"),
|
||||
"expected /status to render the catalog default reasoning effort, got: {rendered}"
|
||||
@@ -131,7 +112,7 @@ async fn status_command_uses_catalog_default_reasoning_when_config_empty() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_renders_native_and_foreign_instruction_sources() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
let (foreign_source, foreign_display) = if cfg!(windows) {
|
||||
(
|
||||
PathUri::parse("file:///remote/AGENTS.md").expect("POSIX instruction source"),
|
||||
@@ -150,12 +131,8 @@ async fn status_command_renders_native_and_foreign_instruction_sources() {
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
||||
}
|
||||
other => panic!("expected status output, got {other:?}"),
|
||||
};
|
||||
chat.handle_key_event(KeyEvent::from(KeyCode::Right));
|
||||
let rendered = render_bottom_popup(&chat, /*width*/ 120);
|
||||
assert!(
|
||||
rendered.contains(&format!("AGENTS.md, {foreign_display}")),
|
||||
"expected /status to show native-relative and environment-native foreign paths, got: {rendered}"
|
||||
@@ -167,15 +144,12 @@ async fn status_command_renders_native_and_foreign_instruction_sources() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_overlapping_refreshes_update_matching_cells_only() {
|
||||
async fn status_command_overlapping_refreshes_finish_only_the_matching_report() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(_)) => {}
|
||||
other => panic!("expected first status output, got {other:?}"),
|
||||
}
|
||||
|
||||
let first_request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
@@ -184,12 +158,7 @@ async fn status_command_overlapping_refreshes_update_matching_cells_only() {
|
||||
};
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let second_rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 80))
|
||||
}
|
||||
other => panic!("expected second status output, got {other:?}"),
|
||||
};
|
||||
let second = report(&chat);
|
||||
let second_request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
@@ -198,16 +167,13 @@ async fn status_command_overlapping_refreshes_update_matching_cells_only() {
|
||||
};
|
||||
|
||||
assert_ne!(first_request_id, second_request_id);
|
||||
assert!(
|
||||
!second_rendered.contains("refreshing limits"),
|
||||
"expected /status to avoid transient refresh text in terminal history, got: {second_rendered}"
|
||||
);
|
||||
|
||||
let before = second.copy_text();
|
||||
chat.finish_status_rate_limit_refresh(first_request_id, Vec::new());
|
||||
pretty_assertions::assert_eq!(chat.refreshing_status_outputs.len(), 1);
|
||||
assert_eq!(before, second.copy_text());
|
||||
pretty_assertions::assert_eq!(chat.pending_status_quota.len(), 1);
|
||||
|
||||
chat.finish_status_rate_limit_refresh(second_request_id, vec![snapshot(/*percent*/ 92.0)]);
|
||||
assert!(chat.refreshing_status_outputs.is_empty());
|
||||
assert!(chat.pending_status_quota.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -215,7 +181,6 @@ async fn account_update_rejects_stale_status_rate_limit_snapshots() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshRateLimits {
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
@@ -233,7 +198,7 @@ async fn account_update_rejects_stale_status_rate_limit_snapshots() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_renders_immediately_and_updates_first_card_without_status_line() {
|
||||
async fn reopened_status_gets_pending_thread_usage_without_status_line() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
let thread_id =
|
||||
@@ -243,12 +208,10 @@ async fn status_command_renders_immediately_and_updates_first_card_without_statu
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let first_cell = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
event => panic!("expected immediate /status output, got {event:?}"),
|
||||
};
|
||||
let initial = lines_to_single_string(&first_cell.display_lines(/*width*/ 90));
|
||||
assert!(!initial.contains("Thread usage"));
|
||||
let first = chat.active_status.clone();
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
assert!(first.upgrade().is_none());
|
||||
assert!(!report(&chat).copy_text().contains("Thread usage"));
|
||||
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage {
|
||||
@@ -296,17 +259,13 @@ async fn status_command_renders_immediately_and_updates_first_card_without_statu
|
||||
})),
|
||||
));
|
||||
|
||||
let settled = lines_to_single_string(&first_cell.display_lines(/*width*/ 90));
|
||||
let settled = report(&chat).copy_text();
|
||||
assert!(settled.contains("50 credits · ~$1.82"));
|
||||
assert!(settled.contains("GPT-5.4 80%, GPT-5 Mini 20%"));
|
||||
assert!(drain_insert_history(&mut rx).is_empty());
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let cell = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
event => panic!("expected /status output with cached thread usage, got {event:?}"),
|
||||
};
|
||||
let rendered =
|
||||
normalize_snapshot_paths(lines_to_single_string(&cell.display_lines(/*width*/ 90)));
|
||||
let cell = report(&chat);
|
||||
let rendered = normalize_snapshot_paths(cell.copy_text());
|
||||
assert!(rendered.contains("50 credits · ~$1.82"));
|
||||
assert!(rendered.contains("GPT-5.4 80%, GPT-5 Mini 20%"));
|
||||
assert!(rendered.contains("Medium 20%, High 80%"));
|
||||
@@ -341,12 +300,7 @@ async fn status_command_omits_thread_usage_for_unsupported_plans() {
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 90))
|
||||
}
|
||||
event => panic!("expected immediate /status output, got {event:?}"),
|
||||
};
|
||||
let rendered = report(&chat).copy_text();
|
||||
assert!(!rendered.contains("Thread usage"));
|
||||
assert!(
|
||||
!std::iter::from_fn(|| rx.try_recv().ok())
|
||||
@@ -365,11 +319,8 @@ async fn status_command_stays_visible_and_updates_after_thread_usage_retry() {
|
||||
chat.plan_type = Some(PlanType::Business);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let cell = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
event => panic!("expected immediate /status output, got {event:?}"),
|
||||
};
|
||||
assert!(!lines_to_single_string(&cell.display_lines(/*width*/ 90)).contains("Thread usage"));
|
||||
let first = chat.active_status.clone();
|
||||
assert!(!report(&chat).copy_text().contains("Thread usage"));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected thread usage request, got {event:?}"),
|
||||
@@ -383,10 +334,7 @@ async fn status_command_stays_visible_and_updates_after_thread_usage_retry() {
|
||||
assert!(drain_insert_history(&mut rx).is_empty());
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let retry_cell = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
event => panic!("expected another immediate /status output, got {event:?}"),
|
||||
};
|
||||
assert!(first.upgrade().is_none());
|
||||
let retry_request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected thread usage retry, got {event:?}"),
|
||||
@@ -403,12 +351,7 @@ async fn status_command_stays_visible_and_updates_after_thread_usage_retry() {
|
||||
})),
|
||||
));
|
||||
|
||||
for status_cell in [&cell, &retry_cell] {
|
||||
assert!(
|
||||
lines_to_single_string(&status_cell.display_lines(/*width*/ 90))
|
||||
.contains("50 credits · ~$1.82")
|
||||
);
|
||||
}
|
||||
assert!(report(&chat).copy_text().contains("50 credits · ~$1.82"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -420,10 +363,7 @@ async fn status_command_renders_credits_and_breakdowns_without_usd_estimate() {
|
||||
chat.plan_type = Some(PlanType::Business);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let first_cell = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => cell,
|
||||
event => panic!("expected immediate /status output, got {event:?}"),
|
||||
};
|
||||
let first_cell = report(&chat);
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected thread usage request, got {event:?}"),
|
||||
@@ -451,18 +391,13 @@ async fn status_command_renders_credits_and_breakdowns_without_usd_estimate() {
|
||||
})),
|
||||
));
|
||||
|
||||
let first_rendered = lines_to_single_string(&first_cell.display_lines(/*width*/ 90));
|
||||
let first_rendered = first_cell.copy_text();
|
||||
assert!(first_rendered.contains("50 credits"));
|
||||
assert!(first_rendered.contains("GPT-5.4 100%"));
|
||||
assert!(!first_rendered.contains("~$"));
|
||||
drain_insert_history(&mut rx);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let rendered = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 90))
|
||||
}
|
||||
event => panic!("expected cached credits-only /status output, got {event:?}"),
|
||||
};
|
||||
let rendered = report(&chat).copy_text();
|
||||
assert!(rendered.contains("50 credits"));
|
||||
assert!(rendered.contains("GPT-5.4 100%"));
|
||||
assert!(rendered.contains("High 100%"));
|
||||
@@ -489,7 +424,6 @@ async fn status_command_drops_stale_usd_when_updated_usage_has_only_credits() {
|
||||
chat.plan_type = Some(PlanType::Business);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected initial thread usage request, got {event:?}"),
|
||||
@@ -509,12 +443,7 @@ async fn status_command_drops_stale_usd_when_updated_usage_has_only_credits() {
|
||||
|
||||
drain_insert_history(&mut rx);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let cached = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 90))
|
||||
}
|
||||
event => panic!("expected cached /status output, got {event:?}"),
|
||||
};
|
||||
let cached = report(&chat).copy_text();
|
||||
assert!(cached.contains("40 credits · ~$1.82"));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
@@ -535,12 +464,7 @@ async fn status_command_drops_stale_usd_when_updated_usage_has_only_credits() {
|
||||
|
||||
drain_insert_history(&mut rx);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let refreshed = match rx.try_recv() {
|
||||
Ok(AppEvent::InsertHistoryCell(cell)) => {
|
||||
lines_to_single_string(&cell.display_lines(/*width*/ 90))
|
||||
}
|
||||
event => panic!("expected credits-only /status output, got {event:?}"),
|
||||
};
|
||||
let refreshed = report(&chat).copy_text();
|
||||
assert!(refreshed.contains("50 credits"));
|
||||
assert!(!refreshed.contains("~$1.82"));
|
||||
}
|
||||
@@ -564,7 +488,6 @@ async fn status_command_requests_thread_usage_for_remote_connection_metadata() {
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::RefreshThreadUsage { .. }));
|
||||
}
|
||||
|
||||
@@ -582,12 +505,11 @@ async fn status_command_requests_thread_usage_with_backend_only_authentication()
|
||||
assert!(chat.has_codex_backend_auth());
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::RefreshThreadUsage { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_remains_visible_when_account_changes_during_usage_refresh() {
|
||||
async fn account_change_dismisses_status_during_usage_refresh() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
let thread_id = ThreadId::new();
|
||||
@@ -595,18 +517,20 @@ async fn status_command_remains_visible_when_account_changes_during_usage_refres
|
||||
chat.plan_type = Some(PlanType::Business);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected thread usage request, got {event:?}"),
|
||||
};
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
chat.update_account_state(
|
||||
/*status_account_display*/ None, /*plan_type*/ None,
|
||||
/*has_chatgpt_account*/ false, /*has_codex_backend_auth*/ false,
|
||||
);
|
||||
|
||||
assert!(chat.active_status.upgrade().is_none());
|
||||
assert!(chat.bottom_pane.no_modal_or_popup_active());
|
||||
assert!(!chat.finish_thread_usage_refresh(
|
||||
thread_id,
|
||||
request_id,
|
||||
@@ -622,7 +546,7 @@ async fn status_command_remains_visible_when_account_changes_during_usage_refres
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_command_remains_visible_when_thread_changes_during_usage_refresh() {
|
||||
async fn thread_change_dismisses_status_during_usage_refresh() {
|
||||
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
let thread_id = ThreadId::new();
|
||||
@@ -630,15 +554,15 @@ async fn status_command_remains_visible_when_thread_changes_during_usage_refresh
|
||||
chat.plan_type = Some(PlanType::Business);
|
||||
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::InsertHistoryCell(_)));
|
||||
let request_id = match rx.try_recv() {
|
||||
Ok(AppEvent::RefreshThreadUsage { request_id, .. }) => request_id,
|
||||
event => panic!("expected thread usage request, got {event:?}"),
|
||||
};
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
chat.clear_thread_usage_state();
|
||||
chat.handle_thread_session_quiet(super::app_server::configured_thread_session(ThreadId::new()));
|
||||
assert!(!render_bottom_popup(&chat, /*width*/ 80).contains("Session status"));
|
||||
drain_insert_history(&mut rx);
|
||||
|
||||
assert!(!chat.finish_thread_usage_refresh(
|
||||
thread_id,
|
||||
@@ -653,3 +577,240 @@ async fn status_command_remains_visible_when_thread_changes_during_usage_refresh
|
||||
));
|
||||
assert!(drain_insert_history(&mut rx).is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_modal_selects_and_copies_fields_through_an_active_turn() {
|
||||
use crate::clipboard_copy::CopyFormat;
|
||||
use crate::clipboard_copy::CopyStatus;
|
||||
|
||||
let (mut chat, mut events, mut ops) = make_chatwidget_manual(Some("gpt-5.5")).await;
|
||||
let id = "019fc8ab-1fb2-7000-8000-000000000001";
|
||||
chat.thread_id = Some(ThreadId::from_string(id).unwrap());
|
||||
chat.thread_name = Some("Investigate request status".into());
|
||||
chat.config.cwd = test_path_buf("/tmp/project").abs();
|
||||
chat.token_info = Some(make_token_info(
|
||||
/*total_tokens*/ 172_000, /*context_window*/ 258_000,
|
||||
));
|
||||
chat.on_rolling_rate_limit_snapshot(snapshot(/*percent*/ 8.0));
|
||||
chat.insert_str("current draft");
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
let render = |chat: &ChatWidget, width| {
|
||||
normalize_snapshot_paths(
|
||||
render_bottom_popup(chat, width).replace(crate::version::CODEX_CLI_VERSION, "VERSION"),
|
||||
)
|
||||
};
|
||||
let open = render(&chat, 80);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(events.try_recv().is_err());
|
||||
chat.handle_key_event(KeyCode::Char('j').into());
|
||||
let first = render(&chat, 80);
|
||||
chat.handle_key_event(KeyCode::Up.into());
|
||||
let last = render(&chat, 80);
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
assert_eq!(render(&chat, 80), first);
|
||||
for (key, expected) in [
|
||||
(KeyCode::Down, &first),
|
||||
(KeyCode::Up, &last),
|
||||
(KeyCode::Char('k'), &last),
|
||||
] {
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
chat.handle_key_event(KeyCode::Left.into());
|
||||
assert_eq!(render(&chat, 80), open);
|
||||
chat.handle_key_event(key.into());
|
||||
assert_eq!(&render(&chat, 80), expected);
|
||||
}
|
||||
assert_chatwidget_snapshot!(
|
||||
"status_modal_overview",
|
||||
format!("Open\n{open}\n\nFirst j or ↓\n{first}\n\nFirst k or ↑\n{last}")
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Char('k').into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(
|
||||
events.try_recv(), Ok(AppEvent::CopySelection { text, .. })
|
||||
if text.as_ref() == "35% left (172K used / 258K)"
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
assert_chatwidget_snapshot!("status_modal_configuration", render(&chat, 80));
|
||||
chat.handle_key_event(KeyCode::Right.into());
|
||||
let session = render(&chat, 80);
|
||||
assert_chatwidget_snapshot!("status_modal_session", session);
|
||||
chat.handle_key_event(KeyCode::Char('u').into());
|
||||
assert_matches!(
|
||||
events.try_recv(), Ok(AppEvent::OpenUrlInBrowser { url })
|
||||
if Some(url.as_str()) == report(&chat).usage_url()
|
||||
);
|
||||
assert_eq!(render(&chat, 80), session);
|
||||
|
||||
chat.transcript
|
||||
.record_agent_markdown("A reply".into(), "A reply".into());
|
||||
chat.handle_key_event(KeyCode::Char('j').into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(
|
||||
events.try_recv(), Ok(AppEvent::CopySelection { label, text, feedback: Some(_), format: CopyFormat::PlainText })
|
||||
if label == "Thread name" && text.as_ref() == "Investigate request status"
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Char('k').into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
let AppEvent::CopySelection {
|
||||
text,
|
||||
label,
|
||||
format,
|
||||
feedback: Some(feedback),
|
||||
} = events.try_recv().unwrap()
|
||||
else {
|
||||
panic!("expected the ID");
|
||||
};
|
||||
assert_eq!((text.as_ref(), format), (id, CopyFormat::PlainText));
|
||||
chat.report_copy_result(&label, &Ok(CopyStatus::Pending(1)), Some(feedback.clone()));
|
||||
assert!(render(&chat, 80).contains("Copying Session"));
|
||||
chat.finish_clipboard(
|
||||
&(1, Ok(CopyStatus::Confirmed)),
|
||||
/*composer_visible*/ false,
|
||||
);
|
||||
assert!(render(&chat, 80).contains("Copied Session"));
|
||||
chat.report_copy_result(&label, &Ok(CopyStatus::Unconfirmed), Some(feedback.clone()));
|
||||
assert!(render(&chat, 44).contains("Sent Session · try pasting"));
|
||||
chat.report_copy_result(&label, &Ok(CopyStatus::Pending(2)), Some(feedback));
|
||||
chat.bottom_pane.set_task_running(/*running*/ true);
|
||||
let running = render(&chat, 80);
|
||||
assert!(
|
||||
running.contains("Working") && !running.contains("to interrupt"),
|
||||
"{running}"
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(chat.bottom_pane.is_task_running());
|
||||
assert!(chat.bottom_pane.no_modal_or_popup_active());
|
||||
assert_eq!(chat.composer_text_with_pending(), "current draft");
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
chat.finish_clipboard(
|
||||
&(2, Err("late error".into())),
|
||||
/*composer_visible*/ false,
|
||||
);
|
||||
assert!(!render(&chat, 80).contains("late error"));
|
||||
assert!(drain_insert_history(&mut events).is_empty());
|
||||
assert!(ops.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_modal_fits_the_tallest_tab_and_scrolls_only_in_a_short_pane() {
|
||||
let (mut chat, mut events, _ops) = make_chatwidget_manual(Some("gpt-5.5")).await;
|
||||
chat.config.cwd = test_path_buf("/tmp/project").abs();
|
||||
chat.thread_name = Some(
|
||||
"Investigate why the task queue pauses when a client reconnects and how to resume pending work without starting duplicate jobs".into()
|
||||
);
|
||||
chat.insert_str("/status");
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
let overview = render_bottom_popup(&chat, /*width*/ 32);
|
||||
chat.handle_key_event(KeyCode::Left.into());
|
||||
let tall = render_bottom_popup(&chat, /*width*/ 32);
|
||||
let short =
|
||||
|chat: &ChatWidget| render_bottom_popup_at_size(chat, /*width*/ 32, /*height*/ 9);
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
let top = short(&chat);
|
||||
chat.handle_key_event(KeyCode::PageDown.into());
|
||||
let middle = short(&chat);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
let event = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.find(|event| matches!(event, AppEvent::CopySelection { .. }));
|
||||
assert_matches!(event, Some(AppEvent::CopySelection { text, .. }) if Some(text.as_ref()) == chat.thread_name.as_deref());
|
||||
chat.handle_key_event(KeyCode::Down.into());
|
||||
let bottom = short(&chat);
|
||||
chat.handle_key_event(KeyCode::Home.into());
|
||||
assert_eq!(short(&chat), top);
|
||||
chat.handle_key_event(KeyCode::End.into());
|
||||
assert_eq!(short(&chat), bottom);
|
||||
assert_chatwidget_snapshot!(
|
||||
"status_modal_scrolled_narrow",
|
||||
format!("Overview\n{overview}\n\nSession\n{tall}\n\nShort, top\n{top}\n\nPage down\n{middle}\n\nEnd\n{bottom}")
|
||||
.replace(crate::version::CODEX_CLI_VERSION, "VERSION")
|
||||
);
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("› Collaboration mode"));
|
||||
assert_eq!(short(&chat), bottom);
|
||||
chat.handle_key_event(KeyCode::PageUp.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
chat.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(chat.bottom_pane.no_modal_or_popup_active());
|
||||
assert!(
|
||||
!std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
|
||||
event,
|
||||
AppEvent::FollowTranscript
|
||||
| AppEvent::InsertHistoryCell(_)
|
||||
| AppEvent::CopySelection { .. }
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_modal_yields_shortcuts_to_custom_tab_keys() {
|
||||
let (mut chat, mut events, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.thread_id = Some(ThreadId::new());
|
||||
let mut keymap = crate::keymap::RuntimeKeymap::defaults();
|
||||
keymap.list.move_right = vec![
|
||||
key_hint::plain(KeyCode::Char('i')),
|
||||
key_hint::plain(KeyCode::Char('u')),
|
||||
];
|
||||
keymap.list.move_left = vec![key_hint::plain(KeyCode::Char('c'))];
|
||||
keymap.list.move_down = vec![key_hint::plain(KeyCode::Char('n'))];
|
||||
keymap.list.move_up = vec![key_hint::plain(KeyCode::Char('p'))];
|
||||
keymap.list.accept = vec![key_hint::plain(KeyCode::Char('y'))];
|
||||
chat.bottom_pane.set_keymap_bindings(&keymap);
|
||||
chat.dispatch_command(SlashCommand::Status);
|
||||
|
||||
let overview = render_bottom_popup(&chat, /*width*/ 80);
|
||||
assert!(
|
||||
overview.contains("c/i tabs · p/n select · a copy all"),
|
||||
"{overview}"
|
||||
);
|
||||
assert!(overview.contains("usage settings") && !overview.contains("u usage"));
|
||||
chat.handle_key_event(KeyCode::Char('i').into());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Directory:"));
|
||||
chat.handle_key_event(KeyCode::Char('c').into());
|
||||
assert_eq!(render_bottom_popup(&chat, /*width*/ 80), overview);
|
||||
chat.handle_key_event(KeyCode::Char('u').into());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("Directory:"));
|
||||
assert!(
|
||||
!std::iter::from_fn(|| events.try_recv().ok()).any(|event| matches!(
|
||||
event,
|
||||
AppEvent::CopySelection { .. } | AppEvent::OpenUrlInBrowser { .. }
|
||||
))
|
||||
);
|
||||
chat.handle_key_event(KeyCode::Char('a').into());
|
||||
assert_matches!(events.try_recv(), Ok(AppEvent::CopySelection { text, .. }) if text.as_ref() == report(&chat).copy_text());
|
||||
chat.handle_key_event(KeyCode::Char('n').into());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 80).contains("y copy"));
|
||||
chat.handle_key_event(KeyCode::Char('y').into());
|
||||
assert_matches!(events.try_recv(), Ok(AppEvent::CopySelection { label, .. }) if label == "Model");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_selection_follows_its_bucket_and_window_when_the_report_changes() {
|
||||
let (mut chat, mut events, _ops) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
set_chatgpt_auth(&mut chat);
|
||||
let mut extra = snapshot(/*percent*/ 10.0);
|
||||
extra.limit_id = Some("extra".into());
|
||||
chat.on_rate_limit_snapshot(Some(extra));
|
||||
let request = uuid::Uuid::new_v4();
|
||||
chat.show_status(Some(request));
|
||||
chat.handle_key_event(KeyCode::Up.into());
|
||||
// The selected primary window gets a group heading and a sibling. Both buckets
|
||||
// now have the same primary label, and the ordinary bucket sorts first.
|
||||
let mut extra = snapshot(/*percent*/ 33.0);
|
||||
extra.limit_id = Some("extra".into());
|
||||
extra.secondary = snapshot(/*percent*/ 24.0).primary;
|
||||
chat.finish_status_rate_limit_refresh(request, vec![snapshot(/*percent*/ 15.0), extra]);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(events.try_recv(), Ok(AppEvent::CopySelection { text, .. }) if text.as_ref() == "67% left");
|
||||
chat.handle_key_event(KeyCode::Up.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(events.try_recv(), Ok(AppEvent::CopySelection { text, .. }) if text.as_ref() == "85% left");
|
||||
|
||||
let request = uuid::Uuid::new_v4();
|
||||
chat.show_status(Some(request));
|
||||
chat.handle_key_event(KeyCode::Up.into());
|
||||
let mut single = snapshot(/*percent*/ 33.0);
|
||||
single.limit_id = Some("extra".into());
|
||||
chat.finish_status_rate_limit_refresh(request, vec![single]);
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(events.try_recv().is_err());
|
||||
assert!(!render_bottom_popup(&chat, /*width*/ 80).contains("enter copy"));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ use super::PlanType;
|
||||
use super::StatusLineItem;
|
||||
use super::TerminalTitleItem;
|
||||
use super::ThreadId;
|
||||
use crate::status::StatusHistoryHandle;
|
||||
use crate::status::StatusReport;
|
||||
use crate::status::thread_cost_micros;
|
||||
use codex_app_server_protocol::ThreadUsage;
|
||||
use uuid::Uuid;
|
||||
@@ -43,7 +43,6 @@ pub(super) struct ThreadUsageState {
|
||||
pending_request_id: Option<Uuid>,
|
||||
requested: bool,
|
||||
feature_disabled: bool,
|
||||
status_history_handles: Vec<StatusHistoryHandle>,
|
||||
status_requested: bool,
|
||||
retry_attempts: usize,
|
||||
retry_due_at: Option<Instant>,
|
||||
@@ -66,11 +65,13 @@ impl ChatWidget {
|
||||
self.plan_type = plan;
|
||||
if !self.thread_usage_is_available() {
|
||||
self.clear_thread_usage_state();
|
||||
} else if !previously_available {
|
||||
// A pending /status can learn that the account is billable from its own quota read.
|
||||
for (_, handle) in self.refreshing_status_outputs.clone() {
|
||||
handle.reserve_thread_usage_label_width();
|
||||
self.request_thread_usage_for_status(handle);
|
||||
}
|
||||
if let Some(report) = self.active_status.upgrade() {
|
||||
if !previously_available && self.thread_usage_is_available() {
|
||||
// Quota can establish billing eligibility after the modal opens.
|
||||
self.request_thread_usage_for_status(&report);
|
||||
} else {
|
||||
report.set_thread_usage(self.thread_usage.estimate.clone(), plan);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,7 +159,7 @@ impl ChatWidget {
|
||||
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, report: &StatusReport) {
|
||||
if !self.thread_usage_is_available() {
|
||||
return;
|
||||
}
|
||||
@@ -171,7 +172,8 @@ impl ChatWidget {
|
||||
self.thread_usage.thread_id = Some(thread_id);
|
||||
}
|
||||
|
||||
self.thread_usage.status_history_handles.push(handle);
|
||||
report.reserve_thread_usage_label_width();
|
||||
report.set_thread_usage(self.thread_usage.estimate.clone(), self.plan_type);
|
||||
self.thread_usage.status_requested = true;
|
||||
self.thread_usage.retry_attempts = 0;
|
||||
self.request_thread_usage();
|
||||
@@ -286,7 +288,7 @@ impl ChatWidget {
|
||||
};
|
||||
} else {
|
||||
let mut selected = self.selected_thread_usage();
|
||||
if !self.thread_usage.status_history_handles.is_empty() {
|
||||
if self.active_status.upgrade().is_some() {
|
||||
selected.credits = self.plan_type != Some(PlanType::Ent26);
|
||||
selected.estimated_cost |= self.plan_type == Some(PlanType::Ent26)
|
||||
|| self.thread_usage.settlement_baseline_usd_micros.is_some()
|
||||
@@ -316,17 +318,8 @@ impl ChatWidget {
|
||||
self.schedule_thread_usage_retry();
|
||||
}
|
||||
}
|
||||
if usage_updated && !self.thread_usage.status_history_handles.is_empty() {
|
||||
for handle in &self.thread_usage.status_history_handles {
|
||||
handle.set_thread_usage(self.thread_usage.estimate.clone(), self.plan_type);
|
||||
}
|
||||
if self
|
||||
.thread_usage
|
||||
.settlement_baseline_credits_micros
|
||||
.is_none()
|
||||
{
|
||||
self.thread_usage.status_history_handles.clear();
|
||||
}
|
||||
if usage_updated && let Some(report) = self.active_status.upgrade() {
|
||||
report.set_thread_usage(self.thread_usage.estimate.clone(), self.plan_type);
|
||||
}
|
||||
if self
|
||||
.thread_usage
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::app_event::AppEvent;
|
||||
use crate::chatwidget::ChatWidget;
|
||||
use crate::chatwidget::ReplayKind;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::chatwidget::tests::render_bottom_popup;
|
||||
use crate::status::format_estimated_usd_micros;
|
||||
use crate::tui::FrameRequester;
|
||||
use codex_app_server_protocol::CodexErrorInfo;
|
||||
@@ -112,11 +113,8 @@ async fn pending_status_card_uses_the_corrected_plan_for_its_usage_reply() {
|
||||
chat.thread_id = Some(thread);
|
||||
chat.has_codex_backend_auth = true;
|
||||
chat.plan_type = Some(original_plan);
|
||||
let status_request = 1;
|
||||
chat.add_status_output(/*refreshing_rate_limits*/ true, Some(status_request));
|
||||
let AppEvent::InsertHistoryCell(card) = events.try_recv().unwrap() else {
|
||||
panic!("expected a /status card");
|
||||
};
|
||||
let status_request = uuid::Uuid::new_v4();
|
||||
chat.show_status(Some(status_request));
|
||||
let corrected_ent26 =
|
||||
serde_json::from_value(serde_json::json!({"planType": PlanType::Ent26})).unwrap();
|
||||
chat.finish_status_rate_limit_refresh(status_request, vec![corrected_ent26]);
|
||||
@@ -134,10 +132,9 @@ async fn pending_status_card_uses_the_corrected_plan_for_its_usage_reply() {
|
||||
request,
|
||||
Ok(ThreadUsageOutcome::Available(usage))
|
||||
));
|
||||
let row = card
|
||||
.display_lines(/*width*/ 90)
|
||||
.into_iter()
|
||||
.map(|line| line.to_string())
|
||||
let row = render_bottom_popup(&chat, /*width*/ 90)
|
||||
.lines()
|
||||
.map(|line| line.trim_end().to_owned())
|
||||
.find(|line| line.contains("Thread usage:"))
|
||||
.unwrap();
|
||||
rows.push(format!("{original_plan:?} → Ent26: {}", row.trim()));
|
||||
@@ -236,7 +233,7 @@ async fn temporary_thread_usage_failures_have_bounded_retries() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_history_survives_exhausted_billing_retries() {
|
||||
async fn status_report_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);
|
||||
@@ -246,13 +243,8 @@ async fn status_history_survives_exhausted_billing_retries() {
|
||||
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:?}"),
|
||||
};
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
let first = chat.active_status.clone();
|
||||
|
||||
for attempt in 0..=THREAD_USAGE_RETRY_DELAYS.len() {
|
||||
assert!(chat.finish_thread_usage_refresh(
|
||||
@@ -260,7 +252,6 @@ async fn status_history_survives_exhausted_billing_retries() {
|
||||
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());
|
||||
@@ -270,13 +261,8 @@ async fn status_history_survives_exhausted_billing_retries() {
|
||||
}
|
||||
|
||||
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:?}"),
|
||||
};
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
assert!(first.upgrade().is_none());
|
||||
request_id = thread_usage_request_id(&mut rx);
|
||||
assert!(chat.finish_thread_usage_refresh(
|
||||
thread_id,
|
||||
@@ -288,20 +274,11 @@ async fn status_history_survives_exhausted_billing_retries() {
|
||||
))),
|
||||
));
|
||||
|
||||
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());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 90).contains("50 credits · ~$2.10"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_history_updates_again_after_billing_settles() {
|
||||
async fn status_report_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),
|
||||
@@ -327,13 +304,7 @@ async fn status_history_updates_again_after_billing_settles() {
|
||||
|
||||
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:?}"),
|
||||
};
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
assert!(chat.finish_thread_usage_refresh(
|
||||
thread_id,
|
||||
request_id,
|
||||
@@ -343,7 +314,6 @@ async fn status_history_updates_again_after_billing_settles() {
|
||||
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();
|
||||
@@ -358,14 +328,7 @@ async fn status_history_updates_again_after_billing_settles() {
|
||||
))),
|
||||
));
|
||||
|
||||
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());
|
||||
assert!(render_bottom_popup(&chat, /*width*/ 90).contains("50 credits · ~$2.10"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -832,17 +795,10 @@ async fn billing_surfaces_render_for_every_supported_enterprise_plan() {
|
||||
if plan_type == PlanType::Ent26 {
|
||||
insta::assert_snapshot!(chat.status_line_text().unwrap(), @"~$0.75");
|
||||
insta::assert_snapshot!(chat.last_terminal_title.as_ref().unwrap(), @"~$0.75");
|
||||
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 /status card, got {event:?}"),
|
||||
};
|
||||
let usage_row = status_cell
|
||||
.display_lines(/*width*/ 90)
|
||||
.into_iter()
|
||||
.map(|line| line.to_string())
|
||||
chat.show_status(/*quota_request*/ None);
|
||||
let usage_row = render_bottom_popup(&chat, /*width*/ 90)
|
||||
.lines()
|
||||
.map(|line| line.trim_end().to_owned())
|
||||
.find(|line| line.contains("Thread usage:"))
|
||||
.unwrap();
|
||||
insta::assert_snapshot!(usage_row, @" Thread usage: ~$0.75");
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
use super::HistoryCell;
|
||||
use super::HistoryRenderMode;
|
||||
use std::cell::Cell;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Identifies the render state that determines an active cell's viewport height.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
@@ -26,11 +25,6 @@ pub(super) struct ActiveCellLayoutCache {
|
||||
pub(super) rendered_height: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) struct StatusCopySource {
|
||||
pub(super) handle: crate::status::StatusHistoryHandle,
|
||||
pub(super) fields: Vec<(String, Arc<str>)>,
|
||||
}
|
||||
|
||||
/// Completion status and observation order for each replayed assistant item in one turn.
|
||||
type ReplayedCloudItems = std::collections::HashMap<String, (bool, i64)>;
|
||||
|
||||
@@ -51,8 +45,6 @@ pub(super) struct TranscriptState {
|
||||
/// Original source of that response, before display sanitization, for exact block copying.
|
||||
pub(super) last_agent_source: Option<String>,
|
||||
pub(super) last_agent_copy_item: Option<(String, String)>,
|
||||
/// Latest `/status` card and fields, retained across copying until a later turn or command.
|
||||
pub(super) last_status_copy_targets: Option<StatusCopySource>,
|
||||
pub(super) last_completed_agent_message: Option<(String, String)>,
|
||||
/// Whether each assistant item projected from Cloud history was finished, keyed by turn.
|
||||
pub(super) replayed_cloud_text: Option<std::collections::HashMap<String, ReplayedCloudItems>>,
|
||||
@@ -116,7 +108,6 @@ impl TranscriptState {
|
||||
}
|
||||
|
||||
pub(super) fn record_agent_markdown(&mut self, markdown: String, source: String) {
|
||||
self.last_status_copy_targets = None;
|
||||
self.last_agent_markdown =
|
||||
Some(crate::markdown_render::followup_labels(&markdown).into_owned());
|
||||
self.last_agent_source = Some(source);
|
||||
@@ -129,7 +120,6 @@ impl TranscriptState {
|
||||
}
|
||||
|
||||
pub(super) fn reset_copy_history(&mut self) {
|
||||
self.last_status_copy_targets = None;
|
||||
self.last_agent_markdown = None;
|
||||
self.last_agent_source = None;
|
||||
self.last_agent_copy_item = None;
|
||||
|
||||
@@ -335,13 +335,13 @@ async fn overlapping_reads_keep_older_success_when_newer_read_fails() -> color_e
|
||||
),
|
||||
(5, None, healthy, None),
|
||||
] {
|
||||
for request_id in first_id..=first_id + 1 {
|
||||
let origin = |id: u64| RateLimitRefreshOrigin::StatusCommand {
|
||||
request_id: uuid::Uuid::from_u128(id.into()),
|
||||
};
|
||||
for id in first_id..=first_id + 1 {
|
||||
app.chat_widget
|
||||
.add_status_output(/*refreshing_rate_limits*/ true, Some(request_id));
|
||||
app.refresh_rate_limits(
|
||||
&session,
|
||||
RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
);
|
||||
.show_status(Some(uuid::Uuid::from_u128(id.into())));
|
||||
app.refresh_rate_limits(&session, origin(id));
|
||||
}
|
||||
if let Some(rolling) = rolling {
|
||||
app.chat_widget.on_rolling_rate_limit_snapshot(rolling);
|
||||
@@ -356,7 +356,7 @@ async fn overlapping_reads_keep_older_success_when_newer_read_fails() -> color_e
|
||||
&mut session,
|
||||
AppEvent::RateLimitsLoaded {
|
||||
request_id,
|
||||
origin: RateLimitRefreshOrigin::StatusCommand { request_id },
|
||||
origin: origin(request_id),
|
||||
hard_stop_generation: 0,
|
||||
result: result.map(|update| {
|
||||
serde_json::from_value(serde_json::json!({"rateLimits": update})).unwrap()
|
||||
|
||||
@@ -276,6 +276,7 @@ impl ChatWidget {
|
||||
Some(match action {
|
||||
Action::Resume(owner) => AppEvent::ResumeSessionByIdOrName(owner.to_string()),
|
||||
Action::Copy(cwd) => AppEvent::CopySelection {
|
||||
feedback: None,
|
||||
text: cwd.to_str()?.into(),
|
||||
label: "Worktree working directory".to_string(),
|
||||
format: crate::clipboard_copy::CopyFormat::PlainText,
|
||||
|
||||
@@ -414,12 +414,14 @@ impl<'a> Renderable for InsetRenderable<'a> {
|
||||
self.child.render(area.inset(self.insets), buf);
|
||||
}
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.child.desired_height(
|
||||
let height = self.child.desired_height(
|
||||
width
|
||||
.saturating_sub(self.insets.left)
|
||||
.saturating_sub(self.insets.right),
|
||||
) + self.insets.top
|
||||
+ self.insets.bottom
|
||||
);
|
||||
height
|
||||
.saturating_add(self.insets.top)
|
||||
.saturating_add(self.insets.bottom)
|
||||
}
|
||||
|
||||
/// Preserve clipped inset padding while forwarding only visible child rows.
|
||||
|
||||
@@ -10,11 +10,13 @@ fn inbound_fallback_records_only_variant_names() {
|
||||
logger.open(path.clone()).expect("open session log");
|
||||
for event in [
|
||||
AppEvent::CopySelection {
|
||||
feedback: None,
|
||||
text: Arc::from("private plan without parentheses"),
|
||||
label: "private label".to_string(),
|
||||
format: crate::clipboard_copy::CopyFormat::Markdown,
|
||||
},
|
||||
AppEvent::CopySelection {
|
||||
feedback: None,
|
||||
text: Arc::from("private code(with parentheses)"),
|
||||
label: "private label".to_string(),
|
||||
format: crate::clipboard_copy::CopyFormat::PlainText,
|
||||
|
||||
+184
-249
@@ -1,7 +1,3 @@
|
||||
use crate::history_cell::CompositeHistoryCell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use crate::history_cell::plain_lines;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::line_truncation::line_width;
|
||||
use crate::session_state::ConfirmedPermissions;
|
||||
@@ -32,6 +28,9 @@ use std::path::PathBuf;
|
||||
|
||||
use super::account::StatusAccountDisplay;
|
||||
use super::format::FieldFormatter;
|
||||
use super::format::ReportRow;
|
||||
use super::format::StatusField;
|
||||
use super::format::StatusTab;
|
||||
use super::format::push_label;
|
||||
use super::helpers::compose_account_display;
|
||||
use super::helpers::compose_model_display;
|
||||
@@ -49,7 +48,6 @@ use super::remote_connection::RemoteConnectionStatus;
|
||||
use super::thread_usage::StatusThreadUsage;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
const CHATGPT_USAGE_URL: &str = "https://chatgpt.com/settings/usage";
|
||||
@@ -77,31 +75,27 @@ struct StatusRateLimitState {
|
||||
}
|
||||
|
||||
impl StatusRateLimitState {
|
||||
/// Returns whether the account label changed in the rendered card.
|
||||
fn update_quota_plan(&mut self, quota_plan: Option<PlanType>) -> bool {
|
||||
let (Some(StatusAccountDisplay::ChatGpt { plan, .. }), Some(quota_plan)) =
|
||||
fn update_quota_plan(&mut self, quota_plan: Option<PlanType>) {
|
||||
if let (Some(StatusAccountDisplay::ChatGpt { plan, .. }), Some(quota_plan)) =
|
||||
(&mut self.account, quota_plan)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let label = super::plan_type_display_name(quota_plan);
|
||||
if plan.as_ref() == Some(&label) {
|
||||
return false;
|
||||
{
|
||||
*plan = Some(super::plan_type_display_name(quota_plan));
|
||||
}
|
||||
*plan = Some(label);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StatusHistoryHandle {
|
||||
card: Arc<StatusHistoryCell>,
|
||||
enum StatusLayout {
|
||||
Tabs,
|
||||
FullReport,
|
||||
}
|
||||
|
||||
impl StatusHistoryHandle {
|
||||
impl StatusReport {
|
||||
pub(crate) fn usage_url(&self) -> Option<&'static str> {
|
||||
self.show_chatgpt_usage_link.then_some(CHATGPT_USAGE_URL)
|
||||
}
|
||||
|
||||
pub(crate) fn copy_text(&self) -> String {
|
||||
self.card
|
||||
.content_lines(u16::MAX)
|
||||
self.display_lines(u16::MAX)
|
||||
.iter()
|
||||
.map(|line| line.to_string().trim_end().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
@@ -111,7 +105,7 @@ impl StatusHistoryHandle {
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_thread_usage_label_width(&self) {
|
||||
self.card.thread_usage.reserve_label_width();
|
||||
self.thread_usage.reserve_label_width();
|
||||
}
|
||||
|
||||
pub(crate) fn finish_rate_limit_refresh(
|
||||
@@ -119,7 +113,7 @@ impl StatusHistoryHandle {
|
||||
rate_limits: &[RateLimitSnapshotDisplay],
|
||||
quota_plan: Option<PlanType>,
|
||||
now: DateTime<Local>,
|
||||
) -> bool {
|
||||
) {
|
||||
let rate_limits = if rate_limits.len() <= 1 {
|
||||
compose_rate_limit_data(rate_limits.first(), now)
|
||||
} else {
|
||||
@@ -127,13 +121,12 @@ impl StatusHistoryHandle {
|
||||
};
|
||||
#[expect(clippy::expect_used)]
|
||||
let mut state = self
|
||||
.card
|
||||
.rate_limit_state
|
||||
.write()
|
||||
.expect("status history rate-limit state poisoned");
|
||||
.expect("status rate-limit state poisoned");
|
||||
state.rate_limits = rate_limits;
|
||||
state.refreshing_rate_limits = false;
|
||||
state.update_quota_plan(quota_plan)
|
||||
state.update_quota_plan(quota_plan);
|
||||
}
|
||||
|
||||
pub(crate) fn set_thread_usage(
|
||||
@@ -141,17 +134,18 @@ impl StatusHistoryHandle {
|
||||
estimate: Option<codex_app_server_protocol::ThreadUsage>,
|
||||
plan: Option<PlanType>,
|
||||
) {
|
||||
self.card.thread_usage.set_estimate(estimate, plan);
|
||||
self.thread_usage.set_estimate(estimate, plan);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StatusHistoryCell {
|
||||
pub(crate) struct StatusReport {
|
||||
model_id: String,
|
||||
model_name: String,
|
||||
model_details: Vec<String>,
|
||||
directory: PathBuf,
|
||||
permissions: String,
|
||||
agents_summary: Arc<RwLock<String>>,
|
||||
agents_summary: String,
|
||||
collaboration_mode: Option<String>,
|
||||
model_provider: Option<String>,
|
||||
remote_connection: Option<RemoteConnectionStatus>,
|
||||
@@ -160,7 +154,7 @@ struct StatusHistoryCell {
|
||||
session_id: Option<String>,
|
||||
forked_from: Option<String>,
|
||||
token_usage: StatusTokenUsageData,
|
||||
rate_limit_state: Arc<RwLock<StatusRateLimitState>>,
|
||||
rate_limit_state: RwLock<StatusRateLimitState>,
|
||||
thread_usage: StatusThreadUsage,
|
||||
}
|
||||
|
||||
@@ -180,7 +174,7 @@ pub(crate) fn new_status_output(
|
||||
model_name: &str,
|
||||
collaboration_mode: Option<&str>,
|
||||
reasoning_effort_override: Option<Option<ReasoningEffort>>,
|
||||
) -> CompositeHistoryCell {
|
||||
) -> StatusReport {
|
||||
let snapshots = rate_limits.map(std::slice::from_ref).unwrap_or_default();
|
||||
new_status_output_with_rate_limits(
|
||||
config,
|
||||
@@ -217,9 +211,10 @@ pub(crate) fn new_status_output_with_rate_limits(
|
||||
collaboration_mode: Option<&str>,
|
||||
reasoning_effort_override: Option<Option<ReasoningEffort>>,
|
||||
refreshing_rate_limits: bool,
|
||||
) -> CompositeHistoryCell {
|
||||
new_status_output_with_rate_limits_handle(
|
||||
) -> StatusReport {
|
||||
StatusReport::new(
|
||||
config,
|
||||
model_name.to_string(),
|
||||
Some(&ConfirmedPermissions {
|
||||
profile: config.permissions.effective_permission_profile(),
|
||||
active: config.permissions.active_permission_profile(),
|
||||
@@ -246,67 +241,13 @@ pub(crate) fn new_status_output_with_rate_limits(
|
||||
"<none>".to_string(),
|
||||
refreshing_rate_limits,
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new_status_output_with_rate_limits_handle(
|
||||
config: &Config,
|
||||
confirmed_permissions: Option<&ConfirmedPermissions>,
|
||||
requires_openai_auth: bool,
|
||||
model_provider_id: Option<&str>,
|
||||
remote_connection: Option<&RemoteConnectionStatus>,
|
||||
account_display: Option<&StatusAccountDisplay>,
|
||||
token_info: Option<&TokenUsageInfo>,
|
||||
total_usage: &TokenUsage,
|
||||
session_id: &Option<ThreadId>,
|
||||
thread_name: Option<String>,
|
||||
forked_from: Option<ThreadId>,
|
||||
rate_limits: &[RateLimitSnapshotDisplay],
|
||||
quota_plan: Option<PlanType>,
|
||||
now: DateTime<Local>,
|
||||
model_name: &str,
|
||||
collaboration_mode: Option<&str>,
|
||||
reasoning_effort_override: Option<Option<ReasoningEffort>>,
|
||||
agents_summary: String,
|
||||
refreshing_rate_limits: bool,
|
||||
) -> (CompositeHistoryCell, StatusHistoryHandle) {
|
||||
let command = PlainHistoryCell::new(vec!["/status".magenta().into()]);
|
||||
let card = Arc::new(StatusHistoryCell::new(
|
||||
config,
|
||||
confirmed_permissions,
|
||||
requires_openai_auth,
|
||||
model_provider_id,
|
||||
remote_connection,
|
||||
account_display,
|
||||
token_info,
|
||||
total_usage,
|
||||
session_id,
|
||||
thread_name,
|
||||
forked_from,
|
||||
rate_limits,
|
||||
quota_plan,
|
||||
now,
|
||||
model_name,
|
||||
collaboration_mode,
|
||||
reasoning_effort_override,
|
||||
agents_summary,
|
||||
refreshing_rate_limits,
|
||||
));
|
||||
let handle = StatusHistoryHandle {
|
||||
card: Arc::clone(&card),
|
||||
};
|
||||
|
||||
(
|
||||
CompositeHistoryCell::new(vec![Box::new(command), Box::new(card)]),
|
||||
handle,
|
||||
)
|
||||
}
|
||||
|
||||
impl StatusHistoryCell {
|
||||
impl StatusReport {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn new(
|
||||
pub(crate) fn new(
|
||||
config: &Config,
|
||||
model_id: String,
|
||||
confirmed_permissions: Option<&ConfirmedPermissions>,
|
||||
requires_openai_auth: bool,
|
||||
model_provider_id: Option<&str>,
|
||||
@@ -420,10 +361,10 @@ impl StatusHistoryCell {
|
||||
refreshing_rate_limits,
|
||||
};
|
||||
rate_limit_state.update_quota_plan(quota_plan);
|
||||
let agents_summary = Arc::new(RwLock::new(agents_summary));
|
||||
let thread_usage = StatusThreadUsage::default();
|
||||
|
||||
Self {
|
||||
model_id,
|
||||
model_name,
|
||||
model_details,
|
||||
directory: config.cwd.to_path_buf(),
|
||||
@@ -437,7 +378,7 @@ impl StatusHistoryCell {
|
||||
forked_from,
|
||||
token_usage,
|
||||
agents_summary,
|
||||
rate_limit_state: Arc::new(RwLock::new(rate_limit_state)),
|
||||
rate_limit_state: RwLock::new(rate_limit_state),
|
||||
thread_usage,
|
||||
}
|
||||
}
|
||||
@@ -476,27 +417,26 @@ impl StatusHistoryCell {
|
||||
])
|
||||
}
|
||||
|
||||
fn rate_limit_lines(
|
||||
fn rate_limit_rows(
|
||||
&self,
|
||||
state: &StatusRateLimitState,
|
||||
available_inner_width: usize,
|
||||
formatter: &FieldFormatter,
|
||||
) -> Vec<Line<'static>> {
|
||||
) -> Vec<ReportRow> {
|
||||
match &state.rate_limits {
|
||||
StatusRateLimitData::Available(rows_data) => {
|
||||
if rows_data.is_empty() {
|
||||
return vec![formatter.line(
|
||||
return vec![formatter.row(
|
||||
"Limits",
|
||||
vec![Span::from("not available for this account").dim()],
|
||||
)];
|
||||
}
|
||||
|
||||
self.rate_limit_row_lines(rows_data, available_inner_width, formatter)
|
||||
self.format_limit_rows(rows_data, available_inner_width, formatter)
|
||||
}
|
||||
StatusRateLimitData::Stale(rows_data) => {
|
||||
let mut lines =
|
||||
self.rate_limit_row_lines(rows_data, available_inner_width, formatter);
|
||||
lines.push(formatter.line(
|
||||
let mut lines = self.format_limit_rows(rows_data, available_inner_width, formatter);
|
||||
lines.push(formatter.row(
|
||||
"Warning",
|
||||
vec![Span::from(if state.refreshing_rate_limits {
|
||||
"limits may be stale - run /status again shortly."
|
||||
@@ -508,13 +448,13 @@ impl StatusHistoryCell {
|
||||
lines
|
||||
}
|
||||
StatusRateLimitData::Unavailable => {
|
||||
vec![formatter.line(
|
||||
vec![formatter.row(
|
||||
"Limits",
|
||||
vec![Span::from("not available for this account").dim()],
|
||||
)]
|
||||
}
|
||||
StatusRateLimitData::Missing => {
|
||||
vec![formatter.line(
|
||||
vec![formatter.row(
|
||||
"Limits",
|
||||
vec![Span::from(if state.refreshing_rate_limits {
|
||||
"refresh requested; run /status again shortly."
|
||||
@@ -527,15 +467,17 @@ impl StatusHistoryCell {
|
||||
}
|
||||
}
|
||||
|
||||
fn rate_limit_row_lines(
|
||||
fn format_limit_rows(
|
||||
&self,
|
||||
rows: &[StatusRateLimitRow],
|
||||
available_inner_width: usize,
|
||||
formatter: &FieldFormatter,
|
||||
) -> Vec<Line<'static>> {
|
||||
let mut lines = Vec::with_capacity(rows.len().saturating_mul(2));
|
||||
) -> Vec<ReportRow> {
|
||||
let mut formatted = Vec::with_capacity(rows.len());
|
||||
|
||||
for row in rows {
|
||||
let mut lines = Vec::new();
|
||||
let mut value;
|
||||
match &row.value {
|
||||
StatusRateLimitValue::Window {
|
||||
percent_used,
|
||||
@@ -544,6 +486,7 @@ impl StatusHistoryCell {
|
||||
} => {
|
||||
let percent_remaining = (100.0 - percent_used).clamp(0.0, 100.0);
|
||||
let summary = format_status_limit_summary(percent_remaining);
|
||||
value = summary.clone();
|
||||
let full_value_spans = vec![
|
||||
Span::from(render_status_limit_progress_bar(percent_remaining)),
|
||||
Span::from(" "),
|
||||
@@ -562,7 +505,10 @@ impl StatusHistoryCell {
|
||||
let base_line = Line::from(base_spans.clone());
|
||||
|
||||
if let Some(resets_at) = resets_at.as_ref() {
|
||||
let resets_span = Span::from(format!("(resets {resets_at})")).dim();
|
||||
let reset_text = format!("(resets {resets_at})");
|
||||
value.push(' ');
|
||||
value.push_str(&reset_text);
|
||||
let resets_span = Span::from(reset_text.clone()).dim();
|
||||
let mut inline_spans = base_spans.clone();
|
||||
inline_spans.push(Span::from(" ").dim());
|
||||
inline_spans.push(resets_span.clone());
|
||||
@@ -571,7 +517,6 @@ impl StatusHistoryCell {
|
||||
lines.push(Line::from(inline_spans));
|
||||
} else {
|
||||
lines.push(base_line);
|
||||
let reset_text = format!("(resets {resets_at})");
|
||||
let reset_width = formatter.value_width(available_inner_width).max(1);
|
||||
let wrap_options =
|
||||
textwrap::Options::new(reset_width).break_words(false);
|
||||
@@ -591,6 +536,8 @@ impl StatusHistoryCell {
|
||||
lines.push(base_line);
|
||||
}
|
||||
if let Some(details) = details {
|
||||
value.push(' ');
|
||||
value.push_str(details);
|
||||
let detail_width = formatter.value_width(available_inner_width).max(1);
|
||||
let wrap_options = textwrap::Options::new(detail_width).break_words(false);
|
||||
lines.extend(
|
||||
@@ -604,15 +551,21 @@ impl StatusHistoryCell {
|
||||
}
|
||||
}
|
||||
StatusRateLimitValue::Text(text) => {
|
||||
let label = row.label.clone();
|
||||
let spans =
|
||||
formatter.full_spans(label.as_str(), vec![Span::from(text.clone())]);
|
||||
lines.push(Line::from(spans));
|
||||
value = text.clone();
|
||||
lines.push(Line::from(
|
||||
formatter.full_spans(&row.label, vec![text.clone().into()]),
|
||||
));
|
||||
}
|
||||
}
|
||||
let field = row.field_id.clone().map(|id| StatusField {
|
||||
id,
|
||||
label: row.label.clone(),
|
||||
value,
|
||||
});
|
||||
formatted.push(ReportRow { field, lines });
|
||||
}
|
||||
|
||||
lines
|
||||
formatted
|
||||
}
|
||||
|
||||
fn collect_rate_limit_labels(
|
||||
@@ -759,19 +712,37 @@ fn decorate_workspace_sandbox_label(sandbox: &str, workspace_root_suffix: Option
|
||||
}
|
||||
}
|
||||
|
||||
impl StatusHistoryCell {
|
||||
fn content_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
impl StatusReport {
|
||||
pub(crate) const TAB_TITLES: [&str; 3] = ["Overview", "Configuration", "Session"];
|
||||
|
||||
pub(crate) fn tabs(&self, width: u16) -> [StatusTab; Self::TAB_TITLES.len()] {
|
||||
self.render_sections(width, StatusLayout::Tabs)
|
||||
}
|
||||
|
||||
pub(crate) fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let [overview, mut configuration, session] =
|
||||
self.render_sections(width, StatusLayout::FullReport);
|
||||
configuration.lines.extend(session.lines);
|
||||
configuration.lines.extend(overview.lines);
|
||||
configuration.lines
|
||||
}
|
||||
|
||||
fn render_sections(
|
||||
&self,
|
||||
width: u16,
|
||||
layout: StatusLayout,
|
||||
) -> [StatusTab; Self::TAB_TITLES.len()] {
|
||||
let available_width = usize::from(width);
|
||||
if available_width == 0 {
|
||||
return Vec::new();
|
||||
return Default::default();
|
||||
}
|
||||
let mut lines = Vec::new();
|
||||
let tabbed = matches!(layout, StatusLayout::Tabs);
|
||||
|
||||
#[expect(clippy::expect_used)]
|
||||
let rate_limit_state = self
|
||||
.rate_limit_state
|
||||
.read()
|
||||
.expect("status history rate-limit state poisoned");
|
||||
.expect("status rate-limit state poisoned");
|
||||
let account_value = rate_limit_state
|
||||
.account
|
||||
.as_ref()
|
||||
@@ -798,13 +769,6 @@ impl StatusHistoryCell {
|
||||
.collect();
|
||||
let mut seen: BTreeSet<String> = labels.iter().cloned().collect();
|
||||
let thread_name = self.thread_name.as_deref().filter(|name| !name.is_empty());
|
||||
#[expect(clippy::expect_used)]
|
||||
let agents_summary = self
|
||||
.agents_summary
|
||||
.read()
|
||||
.expect("status history agents summary state poisoned")
|
||||
.clone();
|
||||
|
||||
if self.model_provider.is_some() {
|
||||
push_label(&mut labels, &mut seen, "Model provider");
|
||||
}
|
||||
@@ -833,9 +797,16 @@ impl StatusHistoryCell {
|
||||
self.collect_rate_limit_labels(&rate_limit_state, &mut seen, &mut labels);
|
||||
self.thread_usage.push_labels(&mut labels, &mut seen);
|
||||
|
||||
let formatter = FieldFormatter::from_labels(labels.iter().map(String::as_str));
|
||||
// The panel supplies its own gutter and limits long labels to leave room for values.
|
||||
let (max_label_width, field_indent) = if tabbed {
|
||||
(available_width / 3, "")
|
||||
} else {
|
||||
(usize::MAX, " ")
|
||||
};
|
||||
let formatter = FieldFormatter::from_labels(&labels, max_label_width, field_indent);
|
||||
let value_width = formatter.value_width(available_width);
|
||||
|
||||
let mut server = Vec::new();
|
||||
if let Some(remote_connection) = self.remote_connection.as_ref() {
|
||||
let value = if remote_connection.is_local_daemon {
|
||||
Line::from("Local background server")
|
||||
@@ -846,13 +817,10 @@ impl StatusHistoryCell {
|
||||
}
|
||||
Line::from(spans)
|
||||
};
|
||||
let wrapped_remote = word_wrap_lines([value], RtOptions::new(value_width.max(1)));
|
||||
let mut wrapped_remote = wrapped_remote.into_iter();
|
||||
if let Some(first) = wrapped_remote.next() {
|
||||
lines.push(formatter.line("Server", first.spans));
|
||||
lines.extend(wrapped_remote.map(|line| formatter.continuation(line.spans)));
|
||||
server.push(formatter.wrapped_row("Server", value, value_width));
|
||||
if !tabbed {
|
||||
server.push(ReportRow::spacer());
|
||||
}
|
||||
lines.push(Line::from(Vec::<Span<'static>>::new()));
|
||||
}
|
||||
|
||||
let mut model_spans = vec![Span::from(self.model_name.clone())];
|
||||
@@ -864,161 +832,128 @@ impl StatusHistoryCell {
|
||||
|
||||
let directory_value = format_directory_display(&self.directory, /*max_width*/ None);
|
||||
|
||||
lines.push(formatter.line("Model", model_spans));
|
||||
let model = formatter.row_with_value("Model", model_spans, self.model_id.clone());
|
||||
let mut overview = if tabbed {
|
||||
let mut rows = server.clone();
|
||||
rows.push(model.clone());
|
||||
rows
|
||||
} else {
|
||||
vec![ReportRow::spacer()]
|
||||
};
|
||||
let mut configuration = server;
|
||||
configuration.push(model);
|
||||
if let Some(model_provider) = self.model_provider.as_ref() {
|
||||
lines.push(formatter.line("Model provider", vec![Span::from(model_provider.clone())]));
|
||||
configuration
|
||||
.push(formatter.row("Model provider", vec![Span::from(model_provider.clone())]));
|
||||
}
|
||||
lines.push(formatter.line("Directory", vec![Span::from(directory_value)]));
|
||||
lines.push(formatter.line("Permissions", vec![Span::from(self.permissions.clone())]));
|
||||
lines.push(formatter.line("Agents.md", vec![Span::from(agents_summary)]));
|
||||
configuration.push(formatter.row_with_value(
|
||||
"Directory",
|
||||
vec![Span::from(directory_value)],
|
||||
self.directory.to_string_lossy().into_owned(),
|
||||
));
|
||||
configuration
|
||||
.push(formatter.row("Permissions", vec![Span::from(self.permissions.clone())]));
|
||||
configuration
|
||||
.push(formatter.row("Agents.md", vec![Span::from(self.agents_summary.clone())]));
|
||||
|
||||
let mut session = Vec::new();
|
||||
if let Some(account_value) = account_value {
|
||||
lines.push(formatter.line("Account", vec![Span::from(account_value)]));
|
||||
session.push(formatter.row("Account", vec![Span::from(account_value)]));
|
||||
}
|
||||
if let Some(workspace) = workspace {
|
||||
lines.push(formatter.line("ChatGPT workspace", vec![Span::from(workspace.to_owned())]));
|
||||
session
|
||||
.push(formatter.row("ChatGPT workspace", vec![Span::from(workspace.to_owned())]));
|
||||
}
|
||||
|
||||
if let Some(thread_name) = thread_name {
|
||||
lines.push(formatter.line("Thread name", vec![Span::from(thread_name.to_string())]));
|
||||
session.push(formatter.row("Thread name", vec![Span::from(thread_name.to_string())]));
|
||||
}
|
||||
if let Some(collab_mode) = self.collaboration_mode.as_ref() {
|
||||
lines.push(formatter.line("Collaboration mode", vec![Span::from(collab_mode.clone())]));
|
||||
session
|
||||
.push(formatter.row("Collaboration mode", vec![Span::from(collab_mode.clone())]));
|
||||
}
|
||||
if let Some(session) = self.session_id.as_ref() {
|
||||
lines.push(formatter.line("Session", vec![Span::from(session.clone())]));
|
||||
if let Some(id) = self.session_id.as_ref() {
|
||||
session.push(formatter.row("Session", vec![Span::from(id.clone())]));
|
||||
}
|
||||
if self.session_id.is_some()
|
||||
&& let Some(forked_from) = self.forked_from.as_ref()
|
||||
{
|
||||
lines.push(formatter.line("Forked from", vec![Span::from(forked_from.clone())]));
|
||||
session.push(formatter.row("Forked from", vec![Span::from(forked_from.clone())]));
|
||||
}
|
||||
|
||||
lines.push(Line::from(Vec::<Span<'static>>::new()));
|
||||
// Hide token usage only for ChatGPT subscribers
|
||||
if !matches!(
|
||||
rate_limit_state.account,
|
||||
Some(StatusAccountDisplay::ChatGpt { .. })
|
||||
) {
|
||||
lines.push(formatter.line("Token usage", self.token_usage_spans()));
|
||||
overview.push(formatter.row("Token usage", self.token_usage_spans()));
|
||||
}
|
||||
|
||||
if let Some(spans) = self.context_window_spans() {
|
||||
lines.push(formatter.line("Context window", spans));
|
||||
if let Some(mut spans) = self.context_window_spans() {
|
||||
let value = spans.iter().map(|span| span.content.as_ref()).collect();
|
||||
if tabbed && let Some(context) = &self.token_usage.context_window {
|
||||
let bar = render_status_limit_progress_bar(context.percent_remaining as f64);
|
||||
if line_width(&Line::from(spans.clone())) + bar.chars().count() < value_width {
|
||||
spans.insert(0, format!("{bar} ").into());
|
||||
}
|
||||
}
|
||||
overview.push(formatter.row_with_value("Context window", spans, value));
|
||||
}
|
||||
|
||||
lines.extend(self.rate_limit_lines(&rate_limit_state, available_width, &formatter));
|
||||
let thread_usage_lines = self.thread_usage.lines(&formatter, value_width);
|
||||
if !thread_usage_lines.is_empty() {
|
||||
lines.push(Line::from(Vec::<Span<'static>>::new()));
|
||||
lines.extend(thread_usage_lines);
|
||||
overview.extend(self.rate_limit_rows(&rate_limit_state, available_width, &formatter));
|
||||
let thread_usage_rows = self.thread_usage.rows(&formatter, value_width);
|
||||
if !thread_usage_rows.is_empty() {
|
||||
overview.push(ReportRow::spacer());
|
||||
overview.extend(thread_usage_rows);
|
||||
}
|
||||
|
||||
// Leave room for the two-column title mark even in a tiny terminal.
|
||||
let indent = if available_width >= FieldFormatter::INDENT.len() + 2 {
|
||||
FieldFormatter::INDENT
|
||||
let indent = if available_width >= field_indent.len() + 2 {
|
||||
field_indent
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut title = vec![indent.into()];
|
||||
title.extend(crate::history_cell::codex_title(CODEX_CLI_VERSION));
|
||||
let mut rendered = word_wrap_lines(
|
||||
[Line::from(title)],
|
||||
RtOptions::new(available_width).subsequent_indent(indent.into()),
|
||||
);
|
||||
rendered.push(Line::default());
|
||||
// Providers such as Bedrock manage limits and billing elsewhere.
|
||||
if self.show_chatgpt_usage_link {
|
||||
rendered.extend(word_wrap_lines(
|
||||
[
|
||||
Line::from(vec![
|
||||
"Visit ".fg(accent_color()),
|
||||
CHATGPT_USAGE_URL.fg(accent_color()).underlined(),
|
||||
" for up-to-date".fg(accent_color()),
|
||||
]),
|
||||
"information on rate limits and credits"
|
||||
.fg(accent_color())
|
||||
.into(),
|
||||
],
|
||||
RtOptions::new(available_width)
|
||||
.initial_indent(indent.into())
|
||||
.subsequent_indent(indent.into())
|
||||
.word_separator(textwrap::WordSeparator::AsciiSpace)
|
||||
.word_splitter(textwrap::WordSplitter::NoHyphenation),
|
||||
));
|
||||
let mut rendered = Vec::new();
|
||||
if !tabbed {
|
||||
let mut title = vec![indent.into()];
|
||||
title.extend(crate::history_cell::codex_title(CODEX_CLI_VERSION));
|
||||
rendered = word_wrap_lines(
|
||||
[Line::from(title)],
|
||||
RtOptions::new(available_width).subsequent_indent(indent.into()),
|
||||
);
|
||||
rendered.push(Line::default());
|
||||
}
|
||||
// Keep every value, including long paths and IDs, aligned beneath its first line.
|
||||
// At widths too small for the label column, use the outer indent instead.
|
||||
let continuation = if value_width > 0 {
|
||||
formatter.continuation(Vec::new())
|
||||
} else {
|
||||
indent.into()
|
||||
};
|
||||
let options = RtOptions::new(available_width)
|
||||
.subsequent_indent(continuation)
|
||||
.word_splitter(textwrap::WordSplitter::NoHyphenation);
|
||||
rendered.extend(lines.into_iter().flat_map(|line| {
|
||||
let wrapped = word_wrap_lines([line.clone()], options.clone());
|
||||
if wrapped
|
||||
.iter()
|
||||
.any(|line| line_width(line) > available_width)
|
||||
{
|
||||
// A wide grapheme may not fit after the continuation indent.
|
||||
word_wrap_lines(
|
||||
[line],
|
||||
// Providers such as Bedrock manage limits and billing elsewhere.
|
||||
if self.show_chatgpt_usage_link {
|
||||
rendered.extend(word_wrap_lines(
|
||||
[
|
||||
Line::from(vec![
|
||||
"Visit ".fg(accent_color()),
|
||||
CHATGPT_USAGE_URL.fg(accent_color()).underlined(),
|
||||
" for up-to-date".fg(accent_color()),
|
||||
]),
|
||||
"information on rate limits and credits"
|
||||
.fg(accent_color())
|
||||
.into(),
|
||||
],
|
||||
RtOptions::new(available_width)
|
||||
.initial_indent(indent.into())
|
||||
.subsequent_indent(indent.into())
|
||||
.word_separator(textwrap::WordSeparator::AsciiSpace)
|
||||
.word_splitter(textwrap::WordSplitter::NoHyphenation),
|
||||
)
|
||||
} else {
|
||||
wrapped
|
||||
}
|
||||
}));
|
||||
|
||||
rendered
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for Arc<StatusHistoryCell> {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.content_lines(width)
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.display_lines(u16::MAX))
|
||||
}
|
||||
|
||||
fn display_hyperlink_lines(
|
||||
&self,
|
||||
width: u16,
|
||||
) -> Vec<crate::terminal_hyperlinks::HyperlinkLine> {
|
||||
let mut lines =
|
||||
crate::terminal_hyperlinks::plain_hyperlink_lines(self.display_lines(width));
|
||||
// The usage URL has a known destination; wrapping preserves its underlined spans.
|
||||
// Attach that destination to every fragment instead of searching for the full URL.
|
||||
if self.show_chatgpt_usage_link {
|
||||
for line in &mut lines {
|
||||
let mut column = 0;
|
||||
for span in &line.line.spans {
|
||||
let end = column + span.width();
|
||||
if span.style.add_modifier.contains(Modifier::UNDERLINED) {
|
||||
line.hyperlinks
|
||||
.push(crate::terminal_hyperlinks::TerminalHyperlink::web(
|
||||
column..end,
|
||||
CHATGPT_USAGE_URL.to_string(),
|
||||
));
|
||||
}
|
||||
column = end;
|
||||
}
|
||||
));
|
||||
rendered.push(Line::default());
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
fn transcript_hyperlink_lines(
|
||||
&self,
|
||||
width: u16,
|
||||
) -> Vec<crate::terminal_hyperlinks::HyperlinkLine> {
|
||||
self.display_hyperlink_lines(width)
|
||||
if !rendered.is_empty() {
|
||||
configuration.insert(
|
||||
0,
|
||||
ReportRow {
|
||||
field: None,
|
||||
lines: rendered,
|
||||
},
|
||||
);
|
||||
}
|
||||
[overview, configuration, session]
|
||||
.map(|rows| formatter.layout(rows, available_width, indent))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,50 @@ use ratatui::prelude::*;
|
||||
use ratatui::style::Stylize;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::line_truncation::line_width;
|
||||
use crate::width::display_width;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use std::ops::Range;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum StatusFieldId {
|
||||
Named(&'static str),
|
||||
Primary(String, Option<i64>),
|
||||
Secondary(String, Option<i64>),
|
||||
Credits(String),
|
||||
Monthly(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct StatusField {
|
||||
pub(crate) id: StatusFieldId,
|
||||
pub(crate) label: String,
|
||||
pub(crate) value: String,
|
||||
}
|
||||
|
||||
/// One report row before the final line wrap. Spacers and group headings have no field.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct ReportRow {
|
||||
pub(super) field: Option<StatusField>,
|
||||
pub(super) lines: Vec<Line<'static>>,
|
||||
}
|
||||
|
||||
impl ReportRow {
|
||||
pub(super) fn spacer() -> Self {
|
||||
Self {
|
||||
field: None,
|
||||
lines: vec![Line::default()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Each copyable field owns a contiguous range of screen lines in this layout.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct StatusTab {
|
||||
pub(crate) lines: Vec<Line<'static>>,
|
||||
pub(crate) fields: Vec<(Range<usize>, StatusField)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct FieldFormatter {
|
||||
@@ -13,9 +56,11 @@ pub(crate) struct FieldFormatter {
|
||||
}
|
||||
|
||||
impl FieldFormatter {
|
||||
pub(crate) const INDENT: &'static str = " ";
|
||||
|
||||
pub(crate) fn from_labels<S>(labels: impl IntoIterator<Item = S>) -> Self
|
||||
pub(crate) fn from_labels<S>(
|
||||
labels: impl IntoIterator<Item = S>,
|
||||
max_label_width: usize,
|
||||
indent: &'static str,
|
||||
) -> Self
|
||||
where
|
||||
S: AsRef<str>,
|
||||
{
|
||||
@@ -23,24 +68,53 @@ impl FieldFormatter {
|
||||
.into_iter()
|
||||
.map(|label| display_width(label.as_ref()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
let indent_width = display_width(Self::INDENT);
|
||||
.unwrap_or(0)
|
||||
.min(max_label_width);
|
||||
let indent_width = display_width(indent);
|
||||
let value_offset = indent_width + label_width + 1 + 2;
|
||||
|
||||
Self {
|
||||
indent: Self::INDENT,
|
||||
indent,
|
||||
label_width,
|
||||
value_offset,
|
||||
value_indent: " ".repeat(value_offset),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn line(
|
||||
pub(super) fn row(&self, label: &'static str, spans: Vec<Span<'static>>) -> ReportRow {
|
||||
let value = spans.iter().map(|span| span.content.as_ref()).collect();
|
||||
self.row_with_value(label, spans, value)
|
||||
}
|
||||
|
||||
pub(super) fn row_with_value(
|
||||
&self,
|
||||
label: &'static str,
|
||||
value_spans: Vec<Span<'static>>,
|
||||
) -> Line<'static> {
|
||||
Line::from(self.full_spans(label, value_spans))
|
||||
spans: Vec<Span<'static>>,
|
||||
value: String,
|
||||
) -> ReportRow {
|
||||
ReportRow {
|
||||
field: Some(StatusField {
|
||||
id: StatusFieldId::Named(label),
|
||||
label: label.trim_start().into(),
|
||||
value,
|
||||
}),
|
||||
lines: vec![Line::from(self.full_spans(label, spans))],
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn wrapped_row(
|
||||
&self,
|
||||
label: &'static str,
|
||||
value: Line<'static>,
|
||||
width: usize,
|
||||
) -> ReportRow {
|
||||
let text = value.to_string();
|
||||
let mut wrapped = word_wrap_lines([value], RtOptions::new(width.max(1))).into_iter();
|
||||
let first = wrapped.next().unwrap_or_default();
|
||||
let mut row = self.row_with_value(label, first.spans, text);
|
||||
row.lines
|
||||
.extend(wrapped.map(|line| self.continuation(line.spans)));
|
||||
row
|
||||
}
|
||||
|
||||
pub(crate) fn continuation(&self, mut spans: Vec<Span<'static>>) -> Line<'static> {
|
||||
@@ -65,6 +139,49 @@ impl FieldFormatter {
|
||||
spans
|
||||
}
|
||||
|
||||
pub(super) fn layout(
|
||||
&self,
|
||||
rows: Vec<ReportRow>,
|
||||
available_width: usize,
|
||||
indent: &'static str,
|
||||
) -> StatusTab {
|
||||
// Keep every value, including long paths and IDs, aligned beneath its first line.
|
||||
// At widths too small for the label column, use the outer indent instead.
|
||||
let continuation = if self.value_width(available_width) > 0 {
|
||||
self.continuation(Vec::new())
|
||||
} else {
|
||||
indent.into()
|
||||
};
|
||||
let options = RtOptions::new(available_width)
|
||||
.subsequent_indent(continuation)
|
||||
.word_splitter(textwrap::WordSplitter::NoHyphenation);
|
||||
let wrap = |line: Line<'static>| {
|
||||
let wrapped = word_wrap_lines([line.clone()], options.clone());
|
||||
if wrapped
|
||||
.iter()
|
||||
.any(|line| line_width(line) > available_width)
|
||||
{
|
||||
// A wide grapheme may not fit after the continuation indent.
|
||||
word_wrap_lines(
|
||||
[line],
|
||||
RtOptions::new(available_width)
|
||||
.word_splitter(textwrap::WordSplitter::NoHyphenation),
|
||||
)
|
||||
} else {
|
||||
wrapped
|
||||
}
|
||||
};
|
||||
let mut tab = StatusTab::default();
|
||||
for row in rows {
|
||||
let start = tab.lines.len();
|
||||
tab.lines.extend(row.lines.into_iter().flat_map(&wrap));
|
||||
if let Some(field) = row.field {
|
||||
tab.fields.push((start..tab.lines.len(), field));
|
||||
}
|
||||
}
|
||||
tab
|
||||
}
|
||||
|
||||
fn label_span(&self, label: &str) -> Span<'static> {
|
||||
let mut buf = String::with_capacity(self.value_offset);
|
||||
buf.push_str(self.indent);
|
||||
|
||||
@@ -15,12 +15,13 @@ pub(crate) mod remote_connection;
|
||||
mod thread_usage;
|
||||
|
||||
pub(crate) use account::StatusAccountDisplay;
|
||||
pub(crate) use card::StatusHistoryHandle;
|
||||
pub(crate) use card::StatusReport;
|
||||
#[cfg(test)]
|
||||
pub(crate) use card::new_status_output;
|
||||
#[cfg(test)]
|
||||
pub(crate) use card::new_status_output_with_rate_limits;
|
||||
pub(crate) use card::new_status_output_with_rate_limits_handle;
|
||||
pub(crate) use format::StatusFieldId;
|
||||
pub(crate) use format::StatusTab;
|
||||
pub(crate) use helpers::compose_agents_summary;
|
||||
pub(crate) use helpers::format_directory_display;
|
||||
pub(crate) use helpers::format_reset_timestamp;
|
||||
|
||||
@@ -10,6 +10,7 @@ use crate::chatwidget::limit_label_for_window;
|
||||
use crate::clock_format::ClockFormat;
|
||||
use crate::text_formatting::capitalize_first;
|
||||
|
||||
use super::format::StatusFieldId;
|
||||
use super::helpers::format_reset_timestamp;
|
||||
use chrono::DateTime;
|
||||
use chrono::Duration as ChronoDuration;
|
||||
@@ -27,6 +28,7 @@ const STATUS_LIMIT_BAR_EMPTY: &str = "░";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct StatusRateLimitRow {
|
||||
pub field_id: Option<StatusFieldId>,
|
||||
/// Human-readable row label, such as `"5h limit"`, `"Monthly limit"`, or `"Credits"`.
|
||||
pub label: String,
|
||||
/// Value payload for the row.
|
||||
@@ -103,6 +105,8 @@ impl RateLimitWindowDisplay {
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct RateLimitSnapshotDisplay {
|
||||
/// Canonical limit identifier (for example: `codex` or `codex_other`).
|
||||
pub limit_id: String,
|
||||
/// Display name used in model-specific headings.
|
||||
pub limit_name: String,
|
||||
/// Optional normal model associated with this account-read quota alias.
|
||||
pub normal_model_slug: Option<String>,
|
||||
@@ -164,6 +168,7 @@ pub(crate) fn rate_limit_snapshot_display_for_limit(
|
||||
clock_format: ClockFormat,
|
||||
) -> RateLimitSnapshotDisplay {
|
||||
RateLimitSnapshotDisplay {
|
||||
limit_id: snapshot.limit_id.clone().unwrap_or_else(|| "codex".into()),
|
||||
normal_model_slug: snapshot.normal_model_slug.clone(),
|
||||
limit_name,
|
||||
captured_at,
|
||||
@@ -239,11 +244,11 @@ pub(crate) fn compose_rate_limit_data_many(
|
||||
let mut ordered_snapshots = snapshots.iter().collect::<Vec<_>>();
|
||||
ordered_snapshots.sort_by_key(|snapshot| !snapshot.limit_name.eq_ignore_ascii_case("codex"));
|
||||
for snapshot in ordered_snapshots {
|
||||
let credit_row = snapshot.credits.as_ref().and_then(credit_status_row);
|
||||
let credit_value = snapshot.credits.as_ref().and_then(credit_status_value);
|
||||
// Metadata-only buckets have no visible values and should not leave an empty heading.
|
||||
if snapshot.primary.is_none()
|
||||
&& snapshot.secondary.is_none()
|
||||
&& credit_row.is_none()
|
||||
&& credit_value.is_none()
|
||||
&& snapshot.individual_limit.is_none()
|
||||
{
|
||||
continue;
|
||||
@@ -279,6 +284,7 @@ pub(crate) fn compose_rate_limit_data_many(
|
||||
|
||||
if show_limit_prefix && !combine_non_codex_single_limit {
|
||||
rows.push(StatusRateLimitRow {
|
||||
field_id: None,
|
||||
label: format!("{limit_bucket_label} limit"),
|
||||
value: StatusRateLimitValue::Text(String::new()),
|
||||
});
|
||||
@@ -302,6 +308,10 @@ pub(crate) fn compose_rate_limit_data_many(
|
||||
)
|
||||
};
|
||||
rows.push(StatusRateLimitRow {
|
||||
field_id: Some(StatusFieldId::Primary(
|
||||
snapshot.limit_id.clone(),
|
||||
primary.window_minutes,
|
||||
)),
|
||||
label,
|
||||
value: StatusRateLimitValue::Window {
|
||||
percent_used: primary.used_percent,
|
||||
@@ -329,6 +339,10 @@ pub(crate) fn compose_rate_limit_data_many(
|
||||
)
|
||||
};
|
||||
rows.push(StatusRateLimitRow {
|
||||
field_id: Some(StatusFieldId::Secondary(
|
||||
snapshot.limit_id.clone(),
|
||||
secondary.window_minutes,
|
||||
)),
|
||||
label,
|
||||
value: StatusRateLimitValue::Window {
|
||||
percent_used: secondary.used_percent,
|
||||
@@ -338,11 +352,16 @@ pub(crate) fn compose_rate_limit_data_many(
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(row) = credit_row {
|
||||
rows.push(row);
|
||||
if let Some(value) = credit_value {
|
||||
rows.push(StatusRateLimitRow {
|
||||
field_id: Some(StatusFieldId::Credits(snapshot.limit_id.clone())),
|
||||
label: "Credits".to_string(),
|
||||
value: StatusRateLimitValue::Text(value),
|
||||
});
|
||||
}
|
||||
if let Some(individual_limit) = snapshot.individual_limit.as_ref() {
|
||||
rows.push(StatusRateLimitRow {
|
||||
field_id: Some(StatusFieldId::Monthly(snapshot.limit_id.clone())),
|
||||
label: "Monthly credit limit".to_string(),
|
||||
value: StatusRateLimitValue::Window {
|
||||
percent_used: 100.0 - individual_limit.percent_remaining,
|
||||
@@ -391,15 +410,12 @@ pub(crate) fn format_status_limit_summary(percent_remaining: f64) -> String {
|
||||
format!("{percent_remaining:.0}% left")
|
||||
}
|
||||
|
||||
/// Builds a single `StatusRateLimitRow` when workspace credits are available.
|
||||
/// Formats the value of the workspace credits field when available.
|
||||
/// Unlimited credits are shown explicitly; finite credits show their rounded
|
||||
/// balance or `Available` when the balance is hidden.
|
||||
fn credit_status_row(credits: &CreditsSnapshotDisplay) -> Option<StatusRateLimitRow> {
|
||||
fn credit_status_value(credits: &CreditsSnapshotDisplay) -> Option<String> {
|
||||
if credits.unlimited {
|
||||
return Some(StatusRateLimitRow {
|
||||
label: "Credits".to_string(),
|
||||
value: StatusRateLimitValue::Text("Unlimited".to_string()),
|
||||
});
|
||||
return Some("Unlimited".to_string());
|
||||
}
|
||||
if !credits.has_credits {
|
||||
return None;
|
||||
@@ -412,10 +428,7 @@ fn credit_status_row(credits: &CreditsSnapshotDisplay) -> Option<StatusRateLimit
|
||||
|| "Available".to_string(),
|
||||
|display_balance| format!("{display_balance} credits"),
|
||||
);
|
||||
Some(StatusRateLimitRow {
|
||||
label: "Credits".to_string(),
|
||||
value: StatusRateLimitValue::Text(value),
|
||||
})
|
||||
Some(value)
|
||||
}
|
||||
|
||||
fn format_credit_balance(raw: &str) -> Option<String> {
|
||||
@@ -472,6 +485,7 @@ mod tests {
|
||||
fn non_codex_single_limit_renders_combined_row() {
|
||||
let now = Local::now();
|
||||
let codex = RateLimitSnapshotDisplay {
|
||||
limit_id: "codex".to_string(),
|
||||
limit_name: "codex".to_string(),
|
||||
normal_model_slug: None,
|
||||
captured_at: now,
|
||||
@@ -485,6 +499,7 @@ mod tests {
|
||||
individual_limit: None,
|
||||
};
|
||||
let other = RateLimitSnapshotDisplay {
|
||||
limit_id: "codex-other".to_string(),
|
||||
limit_name: "codex-other".to_string(),
|
||||
normal_model_slug: None,
|
||||
captured_at: now,
|
||||
@@ -520,6 +535,7 @@ mod tests {
|
||||
fn non_codex_multi_limit_keeps_group_row() {
|
||||
let now = Local::now();
|
||||
let other = RateLimitSnapshotDisplay {
|
||||
limit_id: "codex-other".to_string(),
|
||||
limit_name: "codex-other".to_string(),
|
||||
normal_model_slug: None,
|
||||
captured_at: now,
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Model: gpt-5.6-sol (reasoning none, summaries auto)
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: rendered
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
|
||||
-2
@@ -2,8 +2,6 @@
|
||||
source: tui/src/status/tests.rs
|
||||
expression: sanitized
|
||||
---
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for
|
||||
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
---
|
||||
source: tui/src/status/tests.rs
|
||||
expression: "format!(\"before:\\n{before}\\n\\nafter:\\n{after}\")"
|
||||
---
|
||||
before:
|
||||
/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
information on rate limits and credits
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
Permissions: Unknown
|
||||
Agents.md: <none>
|
||||
|
||||
Token usage: 0 total (0 input + 0 output)
|
||||
Limits: refresh requested; run /status again shortly.
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
⌃space select
|
||||
↑/↓ to scroll · pgup/pgdn to page · home/end to jump
|
||||
q close · f3 find · esc browse prompts
|
||||
|
||||
|
||||
after:
|
||||
/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
|
||||
/status
|
||||
|
||||
>_ OpenAI Codex (v0.0.0)
|
||||
|
||||
Visit https://chatgpt.com/settings/usage for up-to-date
|
||||
information on rate limits and credits
|
||||
|
||||
Model: gpt-5.1-codex-max (reasoning none, summaries auto)
|
||||
Directory: [[workspace]]
|
||||
Permissions: Unknown
|
||||
Agents.md: <none>
|
||||
|
||||
Token usage: 0 total (0 input + 0 output)
|
||||
spark limit:
|
||||
5h limit: [███████████░░░░░░░░░] 55% left (resets soon)
|
||||
Weekly limit: [██████████████░░░░░░] 70% left (resets later)
|
||||
|
||||
next message
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
⌃space select
|
||||
↑/↓ to scroll · pgup/pgdn to page · home/end to jump
|
||||
q close · f3 find · esc browse prompts
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::StatusReport;
|
||||
use super::new_status_output;
|
||||
use super::new_status_output_with_rate_limits;
|
||||
use super::new_status_output_with_rate_limits_handle;
|
||||
use super::rate_limit_snapshot_display;
|
||||
use super::rate_limits::RateLimitSnapshotDisplay;
|
||||
use super::rate_limits::RateLimitWindowDisplay;
|
||||
@@ -8,13 +8,9 @@ use super::rate_limits::SpendControlLimitSnapshotDisplay;
|
||||
use super::rate_limits::StatusRateLimitData;
|
||||
use super::rate_limits::compose_rate_limit_data_many;
|
||||
use crate::clock_format::ClockFormat;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use crate::keymap::RuntimeKeymap;
|
||||
use crate::legacy_core::config::Config;
|
||||
use crate::legacy_core::config::ConfigBuilder;
|
||||
use crate::legacy_core::config::PermissionProfileSnapshot;
|
||||
use crate::pager_overlay::TranscriptOverlay;
|
||||
use crate::status::StatusAccountDisplay;
|
||||
use crate::status::remote_connection::RemoteConnectionStatus;
|
||||
use crate::status::remote_connection::remote_connection_status_value;
|
||||
@@ -65,6 +61,7 @@ use tempfile::TempDir;
|
||||
fn stale_monthly_limit_marks_fresh_rolling_snapshot_stale() {
|
||||
let now = Local::now();
|
||||
let snapshot = RateLimitSnapshotDisplay {
|
||||
limit_id: "codex".to_string(),
|
||||
limit_name: "codex".to_string(),
|
||||
normal_model_slug: None,
|
||||
captured_at: now,
|
||||
@@ -201,28 +198,6 @@ fn sanitize_directory(lines: Vec<String>) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn buffer_to_text(buffer: &Buffer, width: u16) -> String {
|
||||
let lines = buffer
|
||||
.content
|
||||
.chunks(usize::from(width))
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(|cell| {
|
||||
let symbol = cell.symbol();
|
||||
symbol
|
||||
.strip_prefix("\x1b]8;;")
|
||||
.and_then(|symbol| symbol.split_once('\x07'))
|
||||
.and_then(|(_, symbol)| symbol.strip_suffix("\x1b]8;;\x07"))
|
||||
.unwrap_or(symbol)
|
||||
})
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
sanitize_directory(lines).join("\n")
|
||||
}
|
||||
|
||||
fn reset_at_from(captured_at: &chrono::DateTime<chrono::Local>, seconds: i64) -> i64 {
|
||||
(*captured_at + ChronoDuration::seconds(seconds))
|
||||
.with_timezone(&Utc)
|
||||
@@ -794,8 +769,9 @@ async fn status_uses_server_provider_id_and_auth_requirement() {
|
||||
let model_slug = get_model_offline_for_tests(config.model.as_deref());
|
||||
|
||||
config.model_provider.requires_openai_auth = true;
|
||||
let (composite, _handle) = new_status_output_with_rate_limits_handle(
|
||||
let composite = StatusReport::new(
|
||||
&config,
|
||||
config.model.clone().unwrap_or_default(),
|
||||
/*confirmed_permissions*/ None,
|
||||
/*requires_openai_auth*/ false,
|
||||
Some("server-ollama"),
|
||||
@@ -826,8 +802,9 @@ async fn status_uses_server_provider_id_and_auth_requirement() {
|
||||
requires_openai_auth: false,
|
||||
..ModelProviderInfo::default()
|
||||
};
|
||||
let (composite, _handle) = new_status_output_with_rate_limits_handle(
|
||||
let composite = StatusReport::new(
|
||||
&config,
|
||||
config.model.clone().unwrap_or_default(),
|
||||
/*confirmed_permissions*/ None,
|
||||
/*requires_openai_auth*/ true,
|
||||
Some("server-openai"),
|
||||
@@ -851,33 +828,10 @@ async fn status_uses_server_provider_id_and_auth_requirement() {
|
||||
sanitize_directory(render_lines(&composite.display_lines(/*width*/ 120))).join("\n");
|
||||
assert_snapshot!("status_server_auth_required", rendered);
|
||||
|
||||
for width in [24, 42, 120] {
|
||||
let lines = composite.display_hyperlink_lines(width);
|
||||
let mut fragments = String::new();
|
||||
let mut destinations = Vec::new();
|
||||
for line in lines {
|
||||
let visible = line.line.to_string();
|
||||
for link in line.hyperlinks {
|
||||
fragments.extend(
|
||||
visible
|
||||
.chars()
|
||||
.skip(link.columns.start)
|
||||
.take(link.columns.len()),
|
||||
);
|
||||
destinations.push(link.destination);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
fragments, "https://chatgpt.com/settings/usage",
|
||||
"width {width}"
|
||||
);
|
||||
assert!(!destinations.is_empty());
|
||||
assert!(
|
||||
destinations
|
||||
.iter()
|
||||
.all(|destination| destination == "https://chatgpt.com/settings/usage")
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
composite.usage_url(),
|
||||
Some("https://chatgpt.com/settings/usage")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1367,8 +1321,9 @@ async fn status_wraps_long_paths_and_session_ids_without_losing_text() {
|
||||
let session =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("session id");
|
||||
let usage = TokenUsage::default();
|
||||
let (status, handle) = new_status_output_with_rate_limits_handle(
|
||||
let status = StatusReport::new(
|
||||
&config,
|
||||
config.model.clone().unwrap_or_default(),
|
||||
/*confirmed_permissions*/ None,
|
||||
/*requires_openai_auth*/ true,
|
||||
/*model_provider_id*/ None,
|
||||
@@ -1409,8 +1364,8 @@ async fn status_wraps_long_paths_and_session_ids_without_losing_text() {
|
||||
"session lost at width {width}: {joined}"
|
||||
);
|
||||
}
|
||||
assert!(handle.copy_text().contains(directory.as_ref()));
|
||||
assert!(handle.copy_text().contains(&session.to_string()));
|
||||
assert!(status.copy_text().contains(directory.as_ref()));
|
||||
assert!(status.copy_text().contains(&session.to_string()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1635,8 +1590,9 @@ async fn status_snapshot_uses_default_reasoning_when_config_empty() {
|
||||
]) {
|
||||
let model_slug = get_model_offline_for_tests(config.model.as_deref());
|
||||
let token_info = token_info_for(&model_slug, &config, &usage);
|
||||
let (composite, _) = new_status_output_with_rate_limits_handle(
|
||||
let composite = StatusReport::new(
|
||||
&config,
|
||||
config.model.clone().unwrap_or_default(),
|
||||
/*confirmed_permissions*/ None,
|
||||
/*requires_openai_auth*/ true,
|
||||
/*model_provider_id*/ None,
|
||||
@@ -1736,95 +1692,6 @@ async fn status_snapshot_shows_refreshing_limits_notice() {
|
||||
assert_snapshot!(sanitized);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transcript_overlay_remeasures_status_after_rate_limit_refresh() {
|
||||
let temp_home = TempDir::new().expect("temp home");
|
||||
let mut config = test_config(&temp_home).await;
|
||||
config.model = Some("gpt-5.1-codex-max".to_string());
|
||||
set_workspace_cwd(&mut config, test_path_buf("/workspace/tests").abs());
|
||||
let usage = TokenUsage::default();
|
||||
let now = Local
|
||||
.with_ymd_and_hms(2024, 6, 7, 8, 9, 10)
|
||||
.single()
|
||||
.expect("timestamp");
|
||||
let model_slug = get_model_offline_for_tests(config.model.as_deref());
|
||||
|
||||
let (status, handle) = new_status_output_with_rate_limits_handle(
|
||||
&config,
|
||||
/*confirmed_permissions*/ None,
|
||||
/*requires_openai_auth*/ true,
|
||||
/*model_provider_id*/ None,
|
||||
/*remote_connection*/ None,
|
||||
/*account_display*/ None,
|
||||
/*token_info*/ None,
|
||||
&usage,
|
||||
&None,
|
||||
/*thread_name*/ None,
|
||||
/*forked_from*/ None,
|
||||
/*rate_limits*/ &[],
|
||||
/*quota_plan*/ None,
|
||||
now,
|
||||
&model_slug,
|
||||
/*collaboration_mode*/ None,
|
||||
/*reasoning_effort_override*/ None,
|
||||
"<none>".to_string(),
|
||||
/*refreshing_rate_limits*/ true,
|
||||
);
|
||||
let mut overlay =
|
||||
TranscriptOverlay::new(vec![Arc::new(status)], RuntimeKeymap::defaults().pager);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 30,
|
||||
);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
overlay.render(area, &mut buffer);
|
||||
let before = buffer_to_text(&buffer, area.width);
|
||||
|
||||
handle.finish_rate_limit_refresh(
|
||||
&[RateLimitSnapshotDisplay {
|
||||
limit_name: "spark".to_string(),
|
||||
normal_model_slug: None,
|
||||
captured_at: now,
|
||||
primary: Some(RateLimitWindowDisplay {
|
||||
used_percent: 45.0,
|
||||
resets_at_unix: None,
|
||||
resets_at: Some("soon".to_string()),
|
||||
window_minutes: Some(300),
|
||||
}),
|
||||
secondary: Some(RateLimitWindowDisplay {
|
||||
used_percent: 30.0,
|
||||
resets_at_unix: None,
|
||||
resets_at: Some("later".to_string()),
|
||||
window_minutes: Some(10_080),
|
||||
}),
|
||||
credits: None,
|
||||
individual_limit: None,
|
||||
}],
|
||||
/*quota_plan*/ None,
|
||||
now,
|
||||
);
|
||||
overlay.insert_cell(Arc::new(PlainHistoryCell::new(vec!["next message".into()])));
|
||||
buffer = Buffer::empty(area);
|
||||
overlay.render(area, &mut buffer);
|
||||
let after = buffer_to_text(&buffer, area.width);
|
||||
|
||||
assert!(
|
||||
after.contains("spark limit"),
|
||||
"status output was clipped: {after:?}"
|
||||
);
|
||||
assert!(
|
||||
after.contains("5h limit"),
|
||||
"status output was clipped: {after:?}"
|
||||
);
|
||||
assert!(
|
||||
after.contains("Weekly limit"),
|
||||
"status output was clipped: {after:?}"
|
||||
);
|
||||
insta::assert_snapshot!(
|
||||
"transcript_overlay_status_rate_limit_refresh",
|
||||
format!("before:\n{before}\n\nafter:\n{after}")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_snapshot_includes_credits_and_limits() {
|
||||
let temp_home = TempDir::new().expect("temp home");
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
//! Live-updating, thread-scoped billing details embedded in `/status` history cards.
|
||||
//! Live-updating, thread-scoped billing details embedded in `/status` reports.
|
||||
|
||||
use super::format::FieldFormatter;
|
||||
use super::format::ReportRow;
|
||||
use super::format::push_label;
|
||||
use super::helpers::format_tokens_compact;
|
||||
use crate::wrapping::RtOptions;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use codex_app_server_protocol::ThreadUsage;
|
||||
use codex_app_server_protocol::ThreadUsageBreakdownGroup;
|
||||
use codex_protocol::account::PlanType;
|
||||
@@ -41,7 +40,7 @@ pub(crate) fn thread_cost_micros(usage: &ThreadUsage, plan_type: Option<PlanType
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared state updates a committed `/status` card when its asynchronous estimate arrives.
|
||||
/// Shared state updates the open `/status` report when its asynchronous estimate arrives.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct StatusThreadUsage {
|
||||
billing: RwLock<CardBilling>,
|
||||
@@ -65,7 +64,7 @@ impl StatusThreadUsage {
|
||||
let mut billing = self
|
||||
.billing
|
||||
.write()
|
||||
.expect("status history thread-usage state poisoned");
|
||||
.expect("status thread-usage state poisoned");
|
||||
*billing = CardBilling { estimate, plan };
|
||||
}
|
||||
|
||||
@@ -79,7 +78,7 @@ impl StatusThreadUsage {
|
||||
let billing = self
|
||||
.billing
|
||||
.read()
|
||||
.expect("status history thread-usage state poisoned");
|
||||
.expect("status thread-usage state poisoned");
|
||||
let Some(estimate) = billing.estimate.as_ref() else {
|
||||
return;
|
||||
};
|
||||
@@ -98,16 +97,12 @@ impl StatusThreadUsage {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lines(
|
||||
&self,
|
||||
formatter: &FieldFormatter,
|
||||
value_width: usize,
|
||||
) -> Vec<Line<'static>> {
|
||||
pub(super) fn rows(&self, formatter: &FieldFormatter, value_width: usize) -> Vec<ReportRow> {
|
||||
#[expect(clippy::expect_used)]
|
||||
let billing = self
|
||||
.billing
|
||||
.read()
|
||||
.expect("status history thread-usage state poisoned");
|
||||
.expect("status thread-usage state poisoned");
|
||||
let Some(estimate) = billing.estimate.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
@@ -116,7 +111,7 @@ impl StatusThreadUsage {
|
||||
// Credit-weighted breakdowns do not describe native dollar usage.
|
||||
return thread_cost_micros(estimate, billing.plan)
|
||||
.and_then(format_estimated_usd_micros)
|
||||
.map(|cost| vec![formatter.line("Thread usage", vec![cost.into()])])
|
||||
.map(|cost| vec![formatter.row("Thread usage", vec![cost.into()])])
|
||||
.unwrap_or_default();
|
||||
}
|
||||
|
||||
@@ -129,7 +124,7 @@ impl StatusThreadUsage {
|
||||
usage.push(" · ".dim());
|
||||
usage.push(cost.into());
|
||||
}
|
||||
let mut lines = vec![formatter.line("Thread usage", usage)];
|
||||
let mut rows = vec![formatter.row("Thread usage", usage)];
|
||||
|
||||
for (label, dimension) in [
|
||||
(MODELS_LABEL, BreakdownDimension::Model),
|
||||
@@ -139,15 +134,7 @@ impl StatusThreadUsage {
|
||||
let Some(value) = grouped_usage(&estimate.groups, dimension) else {
|
||||
continue;
|
||||
};
|
||||
let mut wrapped = word_wrap_lines(
|
||||
[Line::from(value)],
|
||||
RtOptions::new(value_width.max(/*other*/ 1)),
|
||||
)
|
||||
.into_iter();
|
||||
if let Some(first) = wrapped.next() {
|
||||
lines.push(formatter.line(label, first.spans));
|
||||
lines.extend(wrapped.map(|line| formatter.continuation(line.spans)));
|
||||
}
|
||||
rows.push(formatter.wrapped_row(label, Line::from(value), value_width));
|
||||
}
|
||||
|
||||
let sum_tokens = |count: fn(&ThreadUsageBreakdownGroup) -> Option<i64>| {
|
||||
@@ -175,10 +162,10 @@ impl StatusThreadUsage {
|
||||
}
|
||||
tokens.push(format!("{} output", format_tokens_compact(output_tokens)));
|
||||
}
|
||||
lines.push(formatter.line(BILLED_TOKENS_LABEL, vec![tokens.join(" ").into()]));
|
||||
rows.push(formatter.row(BILLED_TOKENS_LABEL, vec![tokens.join(" ").into()]));
|
||||
}
|
||||
|
||||
lines
|
||||
rows
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -250,8 +250,12 @@ impl StatusIndicatorWidget {
|
||||
self.interrupt_binding = binding;
|
||||
}
|
||||
|
||||
pub(crate) fn with_timer<'a>(&'a self, timer: &'a StatusTimer) -> impl Renderable + 'a {
|
||||
StatusIndicator { row: self, timer }
|
||||
pub(crate) fn with_timer<'a>(&'a self, timer: &'a StatusTimer) -> StatusIndicator<'a> {
|
||||
StatusIndicator {
|
||||
row: self,
|
||||
timer,
|
||||
show_interrupt_hint: self.show_interrupt_hint,
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the details text into a fixed width and return the lines, truncating if necessary.
|
||||
@@ -282,12 +286,18 @@ impl StatusIndicatorWidget {
|
||||
}
|
||||
}
|
||||
|
||||
struct StatusIndicator<'a> {
|
||||
pub(crate) struct StatusIndicator<'a> {
|
||||
show_interrupt_hint: bool,
|
||||
row: &'a StatusIndicatorWidget,
|
||||
timer: &'a StatusTimer,
|
||||
}
|
||||
|
||||
impl StatusIndicator<'_> {
|
||||
pub(crate) fn without_interrupt_hint(mut self) -> Self {
|
||||
self.show_interrupt_hint = false;
|
||||
self
|
||||
}
|
||||
|
||||
// Share width decisions between height measurement and rendering, including
|
||||
// wide Unicode characters, remapped interrupt hints, and elapsed-time text.
|
||||
fn lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
@@ -312,7 +322,7 @@ impl StatusIndicator<'_> {
|
||||
if !spans.is_empty() {
|
||||
spans.push(" ".into());
|
||||
}
|
||||
if row.show_interrupt_hint
|
||||
if self.show_interrupt_hint
|
||||
&& let Some(interrupt_binding) = row.interrupt_binding
|
||||
{
|
||||
spans.push(format!("({pretty_elapsed} • ").dim());
|
||||
|
||||
@@ -108,11 +108,7 @@ fn shimmer_and_progress_are_independent_and_obey_master_switch() {
|
||||
last_resume_at: start,
|
||||
..Default::default()
|
||||
};
|
||||
let lines = StatusIndicator {
|
||||
row: &row,
|
||||
timer: &timer,
|
||||
}
|
||||
.lines(/*width*/ 80);
|
||||
let lines = row.with_timer(&timer).lines(/*width*/ 80);
|
||||
let header = &lines[0];
|
||||
// Omit the bullet's process-clock-driven styling from the snapshot.
|
||||
let label_start = if animations && progress { 2 } else { 0 };
|
||||
|
||||
@@ -67,7 +67,6 @@ mod alternate_screen;
|
||||
mod event_stream;
|
||||
mod frame_rate_limiter;
|
||||
mod frame_requester;
|
||||
mod history_tail;
|
||||
mod input_boundary;
|
||||
#[cfg(unix)]
|
||||
mod job_control;
|
||||
@@ -778,6 +777,14 @@ where
|
||||
}
|
||||
|
||||
impl Tui {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pending_history_lines_for_test(&self) -> Vec<HyperlinkLine> {
|
||||
self.pending_history_lines
|
||||
.iter()
|
||||
.flat_map(|batch| batch.lines.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn is_alt_screen_enabled(&self) -> bool {
|
||||
self.alt_screen_enabled
|
||||
}
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
//! Update visible terminal-history tails without discarding terminal scrollback.
|
||||
//! When the existing tail is an unchanged prefix, append only the new rows.
|
||||
|
||||
use super::Tui;
|
||||
use crate::custom_terminal::Terminal as CustomTerminal;
|
||||
use crate::insert_history::HistoryLineWrapPolicy;
|
||||
use crate::insert_history::InsertHistoryMode;
|
||||
use crate::insert_history::insert_history_hyperlink_lines_with_mode_and_wrap_policy;
|
||||
use crate::insert_history::wrap_history_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use ratatui::backend::Backend;
|
||||
use ratatui::layout::Position;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
|
||||
impl Tui {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pending_history_lines_for_test(&self) -> Vec<HyperlinkLine> {
|
||||
self.pending_history_lines
|
||||
.iter()
|
||||
.flat_map(|batch| batch.lines.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn replace_visible_history_tail(
|
||||
&mut self,
|
||||
previous_lines: &[HyperlinkLine],
|
||||
replacement: &[HyperlinkLine],
|
||||
wrap_policy: HistoryLineWrapPolicy,
|
||||
) -> io::Result<bool> {
|
||||
self.flush_history_before_draw()?;
|
||||
let mode = self.scrollback.history_insertion_mode(wrap_policy);
|
||||
let replaced = replace_visible_terminal_history_tail(
|
||||
&mut self.terminal,
|
||||
previous_lines,
|
||||
replacement,
|
||||
mode,
|
||||
wrap_policy,
|
||||
)?;
|
||||
if replaced {
|
||||
self.frame_requester().schedule_frame();
|
||||
}
|
||||
Ok(replaced)
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_visible_terminal_history_tail<B>(
|
||||
terminal: &mut CustomTerminal<B>,
|
||||
previous_lines: &[HyperlinkLine],
|
||||
replacement: &[HyperlinkLine],
|
||||
mode: InsertHistoryMode,
|
||||
wrap_policy: HistoryLineWrapPolicy,
|
||||
) -> io::Result<bool>
|
||||
where
|
||||
B: Backend<Error = io::Error> + Write,
|
||||
{
|
||||
let screen_size = terminal.last_known_screen_size;
|
||||
let mut viewport = terminal.viewport_area;
|
||||
let wrap_width = usize::from(viewport.width.max(/*other*/ 1));
|
||||
let (_, previous_rows) = wrap_history_hyperlink_lines(previous_lines, wrap_width, wrap_policy);
|
||||
let Ok(previous_rows) = u16::try_from(previous_rows) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if previous_rows > viewport.top() {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
viewport.y -= previous_rows;
|
||||
terminal.clear_after_position(Position::new(/*x*/ 0, viewport.y))?;
|
||||
terminal.set_viewport_area(viewport);
|
||||
terminal.invalidate_viewport();
|
||||
insert_history_hyperlink_lines_with_mode_and_wrap_policy(
|
||||
terminal,
|
||||
replacement,
|
||||
mode,
|
||||
wrap_policy,
|
||||
screen_size,
|
||||
)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_tail_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,178 +0,0 @@
|
||||
use super::replace_visible_terminal_history_tail;
|
||||
use crate::custom_terminal::Terminal;
|
||||
use crate::insert_history::HistoryLineWrapPolicy;
|
||||
use crate::insert_history::InsertHistoryMode;
|
||||
use crate::insert_history::insert_history_lines;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use crate::test_backend::VT100Backend;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::Line;
|
||||
use std::io::Write;
|
||||
|
||||
#[test]
|
||||
fn replacing_visible_history_tail_preserves_existing_terminal_scrollback() {
|
||||
let width = 52;
|
||||
let height = 8;
|
||||
let backend = VT100Backend::with_scrollback(width, height, /*scrollback_len*/ 32);
|
||||
let mut terminal = Terminal::with_options(backend).expect("terminal");
|
||||
for line in [
|
||||
"shell history that predates Codex",
|
||||
"shell output one",
|
||||
"shell output two",
|
||||
"shell output three",
|
||||
"shell output four",
|
||||
"shell output five",
|
||||
"shell output six",
|
||||
"shell output seven",
|
||||
] {
|
||||
writeln!(terminal.backend_mut(), "{line}\r").expect("seed shell history");
|
||||
}
|
||||
terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ height - 2,
|
||||
width,
|
||||
/*height*/ 2,
|
||||
));
|
||||
insert_history_lines(
|
||||
&mut terminal,
|
||||
vec![
|
||||
Line::from("/status"),
|
||||
Line::from("Account: business"),
|
||||
Line::from("old closing border"),
|
||||
],
|
||||
)
|
||||
.expect("insert initial status card");
|
||||
|
||||
let previous_lines = plain_hyperlink_lines(vec![Line::from("old closing border")]);
|
||||
let replacement = plain_hyperlink_lines(vec![
|
||||
Line::from("Thread usage: 50 credits"),
|
||||
Line::from("new closing border"),
|
||||
]);
|
||||
assert!(
|
||||
replace_visible_terminal_history_tail(
|
||||
&mut terminal,
|
||||
&previous_lines,
|
||||
&replacement,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::PreWrap,
|
||||
)
|
||||
.expect("replace status-card tail")
|
||||
);
|
||||
|
||||
let contents = terminal.backend().vt100().screen().contents();
|
||||
assert!(contents.contains("/status"), "{contents}");
|
||||
assert!(contents.contains("Account: business"), "{contents}");
|
||||
assert!(contents.contains("Thread usage: 50 credits"), "{contents}");
|
||||
assert!(!contents.contains("old closing border"), "{contents}");
|
||||
|
||||
let mut screen_with_scrollback = terminal.backend().vt100().screen().clone();
|
||||
screen_with_scrollback.set_scrollback(/*rows*/ usize::MAX);
|
||||
let scrollback = screen_with_scrollback.contents();
|
||||
assert!(
|
||||
scrollback.contains("shell history that predates Codex"),
|
||||
"existing terminal scrollback was discarded: {scrollback}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inaccessible_history_tail_is_preserved_for_non_destructive_append() {
|
||||
let width = 36;
|
||||
let height = 6;
|
||||
let backend = VT100Backend::with_scrollback(width, height, /*scrollback_len*/ 16);
|
||||
let mut terminal = Terminal::with_options(backend).expect("terminal");
|
||||
terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ 1,
|
||||
width,
|
||||
/*height*/ height - 1,
|
||||
));
|
||||
let before = terminal.backend().vt100().screen().contents();
|
||||
let previous_lines =
|
||||
plain_hyperlink_lines(vec![Line::from("first line"), Line::from("second line")]);
|
||||
let replacement = plain_hyperlink_lines(vec![Line::from("Thread usage: 50 credits")]);
|
||||
|
||||
assert!(
|
||||
!replace_visible_terminal_history_tail(
|
||||
&mut terminal,
|
||||
&previous_lines,
|
||||
&replacement,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::PreWrap,
|
||||
)
|
||||
.expect("leave inaccessible history untouched")
|
||||
);
|
||||
assert_eq!(terminal.backend().vt100().screen().contents(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_to_unchanged_history_tail_preserves_existing_rows() {
|
||||
let width = 52;
|
||||
let height = 8;
|
||||
let backend = VT100Backend::new(width, height);
|
||||
let mut terminal = Terminal::with_options(backend).expect("terminal");
|
||||
terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, width, /*height*/ 2,
|
||||
));
|
||||
insert_history_lines(
|
||||
&mut terminal,
|
||||
vec![Line::from("/status"), Line::from("Account: business")],
|
||||
)
|
||||
.expect("insert initial status card");
|
||||
let replacement = plain_hyperlink_lines(vec![Line::from("Thread usage: 50 credits")]);
|
||||
|
||||
assert!(
|
||||
replace_visible_terminal_history_tail(
|
||||
&mut terminal,
|
||||
/*previous_lines*/ &[],
|
||||
&replacement,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::PreWrap,
|
||||
)
|
||||
.expect("append late billing details")
|
||||
);
|
||||
assert_eq!(
|
||||
terminal.backend().vt100().screen().contents(),
|
||||
"/status\nAccount: business\nThread usage: 50 credits"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_soft_wrapped_history_counts_physical_terminal_rows() {
|
||||
let width = 12;
|
||||
let height = 8;
|
||||
let backend = VT100Backend::new(width, height);
|
||||
let mut terminal = Terminal::with_options(backend).expect("terminal");
|
||||
terminal.set_viewport_area(Rect::new(
|
||||
/*x*/ 0,
|
||||
/*y*/ height - 2,
|
||||
width,
|
||||
/*height*/ 2,
|
||||
));
|
||||
let previous_lines = plain_hyperlink_lines(vec![Line::from("old-long-line-spanning-two-rows")]);
|
||||
let screen_size = terminal.last_known_screen_size;
|
||||
crate::insert_history::insert_history_hyperlink_lines_with_mode_and_wrap_policy(
|
||||
&mut terminal,
|
||||
&previous_lines,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::Terminal,
|
||||
screen_size,
|
||||
)
|
||||
.expect("insert soft-wrapped history");
|
||||
let replacement = plain_hyperlink_lines(vec![Line::from("new billing")]);
|
||||
|
||||
assert!(
|
||||
replace_visible_terminal_history_tail(
|
||||
&mut terminal,
|
||||
&previous_lines,
|
||||
&replacement,
|
||||
InsertHistoryMode::Standard,
|
||||
HistoryLineWrapPolicy::Terminal,
|
||||
)
|
||||
.expect("replace physically wrapped rows")
|
||||
);
|
||||
let contents = terminal.backend().vt100().screen().contents();
|
||||
assert!(contents.contains("new billing"), "{contents}");
|
||||
assert!(!contents.contains("old-long"), "{contents}");
|
||||
assert!(!contents.contains("spanning"), "{contents}");
|
||||
}
|
||||
@@ -117,6 +117,8 @@ async fn statusline_reads_the_selected_stdio_resource_on_the_displayed_thread()
|
||||
.context("missing displayed thread ID")?;
|
||||
terminal.wait_for_screen(&format!("Provider thread {thread}"))?;
|
||||
terminal.write_input(b"/status\r")?;
|
||||
terminal.wait_for_screen("Session status")?;
|
||||
terminal.write_input(b"\x1b[D")?;
|
||||
terminal.wait_for_screen("Session:")?;
|
||||
let status = terminal.screen_contents();
|
||||
let session = status
|
||||
@@ -129,6 +131,8 @@ async fn statusline_reads_the_selected_stdio_resource_on_the_displayed_thread()
|
||||
);
|
||||
if mode == Setup::Embedded {
|
||||
assert_eq!(state["app"]["display_mode"], "raw");
|
||||
terminal.write_input(b"\x1b")?;
|
||||
terminal.wait_for_screen(&format!("Provider thread {thread}"))?;
|
||||
terminal.write_input(b"/raw off\r")?;
|
||||
terminal.wait_for_screen("Raw output mode off")?;
|
||||
terminal.wait_for_screen(&format!("Provider thread {thread} (standard)"))?;
|
||||
|
||||
Reference in New Issue
Block a user