mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
feat(tui): support goal budgets
This commit is contained in:
@@ -653,9 +653,10 @@ impl App {
|
||||
AppEvent::SetThreadGoalObjective {
|
||||
thread_id,
|
||||
objective,
|
||||
budget,
|
||||
mode,
|
||||
} => {
|
||||
self.set_thread_goal_objective(app_server, thread_id, objective, mode)
|
||||
self.set_thread_goal_objective(app_server, thread_id, objective, budget, mode)
|
||||
.await;
|
||||
}
|
||||
AppEvent::SetThreadGoalStatus { thread_id, status } => {
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::bottom_pane::SelectionViewParams;
|
||||
use crate::bottom_pane::popup_consts::standard_popup_hint_line;
|
||||
use crate::goal_display::goal_status_label;
|
||||
use crate::goal_display::goal_usage_summary;
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
use codex_protocol::ThreadId;
|
||||
|
||||
@@ -32,10 +33,7 @@ impl App {
|
||||
};
|
||||
|
||||
let Some(goal) = response.goal else {
|
||||
self.chat_widget.add_info_message(
|
||||
"Usage: /goal <objective>".to_string(),
|
||||
Some("No goal is currently set.".to_string()),
|
||||
);
|
||||
self.chat_widget.show_goal_setup(thread_id);
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -47,6 +45,7 @@ impl App {
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
objective: String,
|
||||
budget: Option<ThreadGoalBudgetParams>,
|
||||
mode: ThreadGoalSetMode,
|
||||
) {
|
||||
if mode == ThreadGoalSetMode::ConfirmIfExists {
|
||||
@@ -57,7 +56,7 @@ impl App {
|
||||
|
||||
match result {
|
||||
Ok(response) if response.goal.is_some() => {
|
||||
self.show_replace_thread_goal_confirmation(thread_id, objective);
|
||||
self.show_replace_thread_goal_confirmation(thread_id, objective, budget);
|
||||
return;
|
||||
}
|
||||
Ok(_) => {}
|
||||
@@ -74,6 +73,7 @@ impl App {
|
||||
thread_id,
|
||||
Some(objective),
|
||||
Some(ThreadGoalStatus::Active),
|
||||
budget.map(Some),
|
||||
/*token_budget*/ None,
|
||||
)
|
||||
.await;
|
||||
@@ -103,6 +103,7 @@ impl App {
|
||||
thread_id,
|
||||
/*objective*/ None,
|
||||
Some(status),
|
||||
/*budget*/ None,
|
||||
/*token_budget*/ None,
|
||||
)
|
||||
.await;
|
||||
@@ -149,12 +150,19 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
fn show_replace_thread_goal_confirmation(&mut self, thread_id: ThreadId, objective: String) {
|
||||
fn show_replace_thread_goal_confirmation(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
objective: String,
|
||||
budget: Option<ThreadGoalBudgetParams>,
|
||||
) {
|
||||
let replace_objective = objective.clone();
|
||||
let replace_budget = budget;
|
||||
let replace_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::SetThreadGoalObjective {
|
||||
thread_id,
|
||||
objective: replace_objective.clone(),
|
||||
budget: replace_budget.clone(),
|
||||
mode: ThreadGoalSetMode::ReplaceExisting,
|
||||
});
|
||||
})];
|
||||
|
||||
@@ -25,6 +25,7 @@ use codex_app_server_protocol::PluginReadResponse;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use codex_app_server_protocol::RateLimitSnapshot;
|
||||
use codex_app_server_protocol::SkillsListResponse;
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
use codex_file_search::FileMatch;
|
||||
use codex_protocol::ThreadId;
|
||||
@@ -226,6 +227,7 @@ pub(crate) enum AppEvent {
|
||||
SetThreadGoalObjective {
|
||||
thread_id: ThreadId,
|
||||
objective: String,
|
||||
budget: Option<ThreadGoalBudgetParams>,
|
||||
mode: ThreadGoalSetMode,
|
||||
},
|
||||
|
||||
|
||||
@@ -55,6 +55,7 @@ use codex_app_server_protocol::ThreadCompactStartParams;
|
||||
use codex_app_server_protocol::ThreadCompactStartResponse;
|
||||
use codex_app_server_protocol::ThreadForkParams;
|
||||
use codex_app_server_protocol::ThreadForkResponse;
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
use codex_app_server_protocol::ThreadGoalClearParams;
|
||||
use codex_app_server_protocol::ThreadGoalClearResponse;
|
||||
use codex_app_server_protocol::ThreadGoalGetParams;
|
||||
@@ -686,6 +687,7 @@ impl AppServerSession {
|
||||
thread_id: ThreadId,
|
||||
objective: Option<String>,
|
||||
status: Option<ThreadGoalStatus>,
|
||||
budget: Option<Option<ThreadGoalBudgetParams>>,
|
||||
token_budget: Option<Option<i64>>,
|
||||
) -> Result<ThreadGoalSetResponse> {
|
||||
let request_id = self.next_request_id();
|
||||
@@ -696,6 +698,7 @@ impl AppServerSession {
|
||||
thread_id: thread_id.to_string(),
|
||||
objective,
|
||||
status,
|
||||
budget,
|
||||
token_budget,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::text::Span;
|
||||
use ratatui::widgets::Clear;
|
||||
use ratatui::widgets::Paragraph;
|
||||
use ratatui::widgets::StatefulWidgetRef;
|
||||
use ratatui::widgets::Widget;
|
||||
use std::cell::RefCell;
|
||||
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
|
||||
use crate::render::renderable::Renderable;
|
||||
|
||||
use super::CancellationEvent;
|
||||
use super::bottom_pane_view::BottomPaneView;
|
||||
use super::bottom_pane_view::ViewCompletion;
|
||||
use super::popup_consts::standard_popup_hint_line;
|
||||
use super::textarea::TextArea;
|
||||
use super::textarea::TextAreaState;
|
||||
|
||||
pub(crate) type GoalSetupSubmitted =
|
||||
Box<dyn Fn(String, Option<ThreadGoalBudgetParams>) + Send + Sync>;
|
||||
|
||||
pub(crate) struct GoalSetupView {
|
||||
objective: TextArea,
|
||||
objective_state: RefCell<TextAreaState>,
|
||||
budget_value: TextArea,
|
||||
budget_value_state: RefCell<TextAreaState>,
|
||||
budget_kind: GoalBudgetKind,
|
||||
focus: GoalSetupFocus,
|
||||
error: Option<String>,
|
||||
on_submit: GoalSetupSubmitted,
|
||||
completion: Option<ViewCompletion>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum GoalBudgetKind {
|
||||
None,
|
||||
Tokens,
|
||||
FiveHourLimit,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum GoalSetupFocus {
|
||||
Objective,
|
||||
Budget,
|
||||
Value,
|
||||
}
|
||||
|
||||
impl GoalSetupView {
|
||||
pub(crate) fn new(on_submit: GoalSetupSubmitted) -> Self {
|
||||
Self {
|
||||
objective: TextArea::new(),
|
||||
objective_state: RefCell::new(TextAreaState::default()),
|
||||
budget_value: TextArea::new(),
|
||||
budget_value_state: RefCell::new(TextAreaState::default()),
|
||||
budget_kind: GoalBudgetKind::None,
|
||||
focus: GoalSetupFocus::Objective,
|
||||
error: None,
|
||||
on_submit,
|
||||
completion: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(&mut self) {
|
||||
let objective = self.objective.text().trim().to_string();
|
||||
if objective.is_empty() {
|
||||
self.error = Some("Goal objective must not be empty.".to_string());
|
||||
return;
|
||||
}
|
||||
match self.budget() {
|
||||
Ok(budget) => {
|
||||
(self.on_submit)(objective, budget);
|
||||
self.completion = Some(ViewCompletion::Accepted);
|
||||
}
|
||||
Err(err) => self.error = Some(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn budget(&self) -> Result<Option<ThreadGoalBudgetParams>, String> {
|
||||
let value = self.budget_value.text().trim();
|
||||
match self.budget_kind {
|
||||
GoalBudgetKind::None => Ok(None),
|
||||
GoalBudgetKind::Tokens => Ok(Some(ThreadGoalBudgetParams::Tokens {
|
||||
token_budget: parse_token_budget(value)?,
|
||||
})),
|
||||
GoalBudgetKind::FiveHourLimit => {
|
||||
Ok(Some(ThreadGoalBudgetParams::FiveHourLimitPercent {
|
||||
percent: parse_five_hour_percent(value)?,
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn cycle_budget(&mut self) {
|
||||
self.budget_kind = match self.budget_kind {
|
||||
GoalBudgetKind::None => GoalBudgetKind::Tokens,
|
||||
GoalBudgetKind::Tokens => GoalBudgetKind::FiveHourLimit,
|
||||
GoalBudgetKind::FiveHourLimit => GoalBudgetKind::None,
|
||||
};
|
||||
if self.budget_kind == GoalBudgetKind::None && self.focus == GoalSetupFocus::Value {
|
||||
self.focus = GoalSetupFocus::Budget;
|
||||
}
|
||||
self.error = None;
|
||||
}
|
||||
|
||||
fn cycle_focus(&mut self) {
|
||||
self.focus = match (self.focus, self.budget_kind) {
|
||||
(GoalSetupFocus::Objective, _) => GoalSetupFocus::Budget,
|
||||
(GoalSetupFocus::Budget, GoalBudgetKind::None) => GoalSetupFocus::Objective,
|
||||
(GoalSetupFocus::Budget, _) => GoalSetupFocus::Value,
|
||||
(GoalSetupFocus::Value, _) => GoalSetupFocus::Objective,
|
||||
};
|
||||
}
|
||||
|
||||
fn budget_label(&self) -> &'static str {
|
||||
match self.budget_kind {
|
||||
GoalBudgetKind::None => "None",
|
||||
GoalBudgetKind::Tokens => "Tokens",
|
||||
GoalBudgetKind::FiveHourLimit => "5h limit",
|
||||
}
|
||||
}
|
||||
|
||||
fn value_placeholder(&self) -> &'static str {
|
||||
match self.budget_kind {
|
||||
GoalBudgetKind::None => "",
|
||||
GoalBudgetKind::Tokens => "500000 or 500k",
|
||||
GoalBudgetKind::FiveHourLimit => "10%",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BottomPaneView for GoalSetupView {
|
||||
fn handle_key_event(&mut self, key_event: KeyEvent) {
|
||||
self.error = None;
|
||||
match key_event {
|
||||
KeyEvent {
|
||||
code: KeyCode::Esc, ..
|
||||
} => {
|
||||
self.on_ctrl_c();
|
||||
}
|
||||
KeyEvent {
|
||||
code: KeyCode::Tab, ..
|
||||
} => self.cycle_focus(),
|
||||
KeyEvent {
|
||||
code: KeyCode::Enter,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
..
|
||||
} if self.focus == GoalSetupFocus::Budget => self.cycle_budget(),
|
||||
KeyEvent {
|
||||
code: KeyCode::Left | KeyCode::Right | KeyCode::Char(' '),
|
||||
..
|
||||
} if self.focus == GoalSetupFocus::Budget => self.cycle_budget(),
|
||||
KeyEvent {
|
||||
code: KeyCode::Enter,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
..
|
||||
} => self.submit(),
|
||||
other => match self.focus {
|
||||
GoalSetupFocus::Objective => self.objective.input(other),
|
||||
GoalSetupFocus::Value => self.budget_value.input(other),
|
||||
GoalSetupFocus::Budget => {}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn on_ctrl_c(&mut self) -> CancellationEvent {
|
||||
self.completion = Some(ViewCompletion::Cancelled);
|
||||
CancellationEvent::Handled
|
||||
}
|
||||
|
||||
fn is_complete(&self) -> bool {
|
||||
self.completion.is_some()
|
||||
}
|
||||
|
||||
fn completion(&self) -> Option<ViewCompletion> {
|
||||
self.completion
|
||||
}
|
||||
|
||||
fn handle_paste(&mut self, pasted: String) -> bool {
|
||||
if pasted.is_empty() {
|
||||
return false;
|
||||
}
|
||||
match self.focus {
|
||||
GoalSetupFocus::Objective => self.objective.insert_str(&pasted),
|
||||
GoalSetupFocus::Value => self.budget_value.insert_str(&pasted),
|
||||
GoalSetupFocus::Budget => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for GoalSetupView {
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
let value_rows = if self.budget_kind == GoalBudgetKind::None {
|
||||
0
|
||||
} else {
|
||||
2
|
||||
};
|
||||
6u16.saturating_add(self.objective_height(width))
|
||||
.saturating_add(value_rows)
|
||||
.saturating_add(u16::from(self.error.is_some()))
|
||||
}
|
||||
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
if area.height == 0 || area.width == 0 {
|
||||
return;
|
||||
}
|
||||
let mut y = area.y;
|
||||
Paragraph::new(Line::from(vec![gutter(), "Set goal".bold()])).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
|
||||
let budget_style = if self.focus == GoalSetupFocus::Budget {
|
||||
self.budget_label().cyan()
|
||||
} else {
|
||||
self.budget_label().into()
|
||||
};
|
||||
Paragraph::new(Line::from(vec![
|
||||
gutter(),
|
||||
"Budget: ".dim(),
|
||||
budget_style,
|
||||
" ".into(),
|
||||
"tab focus, arrows cycle".dim(),
|
||||
]))
|
||||
.render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
|
||||
if self.budget_kind != GoalBudgetKind::None {
|
||||
Paragraph::new(Line::from(vec![gutter(), "Value: ".dim()])).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
self.render_textarea(
|
||||
&self.budget_value,
|
||||
&self.budget_value_state,
|
||||
self.value_placeholder(),
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
}
|
||||
|
||||
Paragraph::new(Line::from(vec![gutter(), "Objective: ".dim()])).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
let objective_height = self.objective_height(area.width);
|
||||
self.render_textarea(
|
||||
&self.objective,
|
||||
&self.objective_state,
|
||||
"What should Codex keep working toward?",
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: objective_height,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(objective_height);
|
||||
|
||||
if let Some(error) = &self.error {
|
||||
Paragraph::new(Line::from(vec![gutter(), error.clone().red()])).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
y = y.saturating_add(1);
|
||||
}
|
||||
|
||||
let hint_y = y.saturating_add(1);
|
||||
if hint_y < area.y.saturating_add(area.height) {
|
||||
Paragraph::new(standard_popup_hint_line()).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y: hint_y,
|
||||
width: area.width,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
|
||||
if area.width <= 2 {
|
||||
return None;
|
||||
}
|
||||
match self.focus {
|
||||
GoalSetupFocus::Objective => {
|
||||
let y = area.y
|
||||
+ 3
|
||||
+ if self.budget_kind == GoalBudgetKind::None {
|
||||
0
|
||||
} else {
|
||||
2
|
||||
};
|
||||
let rect = Rect {
|
||||
x: area.x.saturating_add(2),
|
||||
y,
|
||||
width: area.width.saturating_sub(2),
|
||||
height: self.objective_height(area.width),
|
||||
};
|
||||
self.objective
|
||||
.cursor_pos_with_state(rect, *self.objective_state.borrow())
|
||||
}
|
||||
GoalSetupFocus::Value if self.budget_kind != GoalBudgetKind::None => {
|
||||
let rect = Rect {
|
||||
x: area.x.saturating_add(2),
|
||||
y: area.y.saturating_add(3),
|
||||
width: area.width.saturating_sub(2),
|
||||
height: 1,
|
||||
};
|
||||
self.budget_value
|
||||
.cursor_pos_with_state(rect, *self.budget_value_state.borrow())
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl GoalSetupView {
|
||||
fn objective_height(&self, width: u16) -> u16 {
|
||||
self.objective
|
||||
.desired_height(width.saturating_sub(2))
|
||||
.clamp(2, 6)
|
||||
}
|
||||
|
||||
fn render_textarea(
|
||||
&self,
|
||||
textarea: &TextArea,
|
||||
state: &RefCell<TextAreaState>,
|
||||
placeholder: &str,
|
||||
area: Rect,
|
||||
buf: &mut Buffer,
|
||||
) {
|
||||
for row in 0..area.height {
|
||||
Paragraph::new(Line::from(vec![gutter()])).render(
|
||||
Rect {
|
||||
x: area.x,
|
||||
y: area.y.saturating_add(row),
|
||||
width: 2,
|
||||
height: 1,
|
||||
},
|
||||
buf,
|
||||
);
|
||||
}
|
||||
let textarea_rect = Rect {
|
||||
x: area.x.saturating_add(2),
|
||||
y: area.y,
|
||||
width: area.width.saturating_sub(2),
|
||||
height: area.height,
|
||||
};
|
||||
Clear.render(textarea_rect, buf);
|
||||
StatefulWidgetRef::render_ref(&textarea, textarea_rect, buf, &mut *state.borrow_mut());
|
||||
if textarea.text().is_empty() {
|
||||
Paragraph::new(Line::from(placeholder.to_string().dim())).render(textarea_rect, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_token_budget(value: &str) -> Result<i64, String> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() {
|
||||
return Err("Token budget must not be empty.".to_string());
|
||||
}
|
||||
let (number, multiplier) = match value.chars().last() {
|
||||
Some('k' | 'K') => (&value[..value.len() - 1], 1_000.0),
|
||||
Some('m' | 'M') => (&value[..value.len() - 1], 1_000_000.0),
|
||||
_ => (value, 1.0),
|
||||
};
|
||||
let parsed = number
|
||||
.parse::<f64>()
|
||||
.map_err(|_| "Token budget must be a number like 500000 or 500k.".to_string())?;
|
||||
let budget = (parsed * multiplier).round();
|
||||
if !budget.is_finite() || budget <= 0.0 || budget > i64::MAX as f64 {
|
||||
return Err("Token budget must be positive.".to_string());
|
||||
}
|
||||
Ok(budget as i64)
|
||||
}
|
||||
|
||||
fn parse_five_hour_percent(value: &str) -> Result<f64, String> {
|
||||
let value = value
|
||||
.trim()
|
||||
.strip_suffix('%')
|
||||
.unwrap_or(value.trim())
|
||||
.trim();
|
||||
let percent = value
|
||||
.parse::<f64>()
|
||||
.map_err(|_| "5h limit must be a percent like 10%.".to_string())?;
|
||||
if !percent.is_finite() || percent <= 0.0 || percent > 100.0 {
|
||||
return Err("5h limit must be between 0% and 100%.".to_string());
|
||||
}
|
||||
Ok(percent)
|
||||
}
|
||||
|
||||
fn gutter() -> Span<'static> {
|
||||
"| ".cyan()
|
||||
}
|
||||
@@ -91,6 +91,7 @@ pub(crate) mod custom_prompt_view;
|
||||
mod experimental_features_view;
|
||||
mod file_search_popup;
|
||||
mod footer;
|
||||
mod goal_setup_view;
|
||||
mod list_selection_view;
|
||||
mod memories_settings_view;
|
||||
pub(crate) mod prompt_args;
|
||||
@@ -101,6 +102,7 @@ pub(crate) use footer::CollaborationModeIndicator;
|
||||
pub(crate) use footer::GoalStatusIndicator;
|
||||
#[cfg(test)]
|
||||
pub(crate) use footer::goal_status_indicator_line;
|
||||
pub(crate) use goal_setup_view::GoalSetupView;
|
||||
pub(crate) use list_selection_view::ColumnWidthMode;
|
||||
#[cfg(test)]
|
||||
pub(crate) use list_selection_view::ListSelectionView;
|
||||
|
||||
@@ -1,14 +1,34 @@
|
||||
//! Goal summary for the bare `/goal` command.
|
||||
|
||||
use super::*;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event::ThreadGoalSetMode;
|
||||
use crate::bottom_pane::GoalSetupView;
|
||||
use crate::goal_display::format_five_hour_goal_progress;
|
||||
use crate::goal_display::format_goal_elapsed_seconds;
|
||||
use crate::status::format_tokens_compact;
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
|
||||
impl ChatWidget {
|
||||
pub(crate) fn show_goal_summary(&mut self, goal: AppThreadGoal) {
|
||||
self.add_plain_history_lines(goal_summary_lines(&goal));
|
||||
}
|
||||
|
||||
pub(crate) fn show_goal_setup(&mut self, thread_id: ThreadId) {
|
||||
let tx = self.app_event_tx.clone();
|
||||
let view = GoalSetupView::new(Box::new(
|
||||
move |objective: String, budget: Option<ThreadGoalBudgetParams>| {
|
||||
tx.send(AppEvent::SetThreadGoalObjective {
|
||||
thread_id,
|
||||
objective,
|
||||
budget,
|
||||
mode: ThreadGoalSetMode::ConfirmIfExists,
|
||||
});
|
||||
},
|
||||
));
|
||||
self.bottom_pane.show_view(Box::new(view));
|
||||
}
|
||||
|
||||
pub(crate) fn on_thread_goal_cleared(&mut self, thread_id: &str) {
|
||||
if self
|
||||
.thread_id
|
||||
@@ -42,6 +62,12 @@ fn goal_summary_lines(goal: &AppThreadGoal) -> Vec<Line<'static>> {
|
||||
"Token budget: ".dim(),
|
||||
format_tokens_compact(token_budget).into(),
|
||||
]));
|
||||
} else if let Some(progress) = goal
|
||||
.budget
|
||||
.as_ref()
|
||||
.and_then(format_five_hour_goal_progress)
|
||||
{
|
||||
lines.push(Line::from(vec!["5h limit: ".dim(), progress.into()]));
|
||||
}
|
||||
let command_hint = match goal.status {
|
||||
AppThreadGoalStatus::Active => "Commands: /goal pause, /goal clear",
|
||||
|
||||
@@ -5,6 +5,7 @@ use codex_app_server_protocol::ThreadGoalStatus as AppThreadGoalStatus;
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::bottom_pane::GoalStatusIndicator;
|
||||
use crate::goal_display::format_five_hour_goal_progress;
|
||||
use crate::goal_display::format_goal_elapsed_seconds;
|
||||
use crate::status::format_tokens_compact;
|
||||
|
||||
@@ -47,14 +48,24 @@ pub(super) fn goal_status_indicator_from_app_goal(
|
||||
) -> Option<GoalStatusIndicator> {
|
||||
match goal.status {
|
||||
AppThreadGoalStatus::Active => Some(GoalStatusIndicator::Active {
|
||||
usage: active_goal_usage(goal.token_budget, goal.tokens_used, goal.time_used_seconds),
|
||||
usage: active_goal_usage(
|
||||
goal.budget.as_ref(),
|
||||
goal.token_budget,
|
||||
goal.tokens_used,
|
||||
goal.time_used_seconds,
|
||||
),
|
||||
}),
|
||||
AppThreadGoalStatus::Paused => Some(GoalStatusIndicator::Paused),
|
||||
AppThreadGoalStatus::BudgetLimited => Some(GoalStatusIndicator::BudgetLimited {
|
||||
usage: stopped_goal_budget_usage(goal.token_budget, goal.tokens_used),
|
||||
usage: stopped_goal_budget_usage(
|
||||
goal.budget.as_ref(),
|
||||
goal.token_budget,
|
||||
goal.tokens_used,
|
||||
),
|
||||
}),
|
||||
AppThreadGoalStatus::Complete => Some(GoalStatusIndicator::Complete {
|
||||
usage: Some(completed_goal_usage(
|
||||
goal.budget.as_ref(),
|
||||
goal.token_budget,
|
||||
goal.tokens_used,
|
||||
goal.time_used_seconds,
|
||||
@@ -64,10 +75,14 @@ pub(super) fn goal_status_indicator_from_app_goal(
|
||||
}
|
||||
|
||||
fn active_goal_usage(
|
||||
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
|
||||
token_budget: Option<i64>,
|
||||
tokens_used: i64,
|
||||
time_used_seconds: i64,
|
||||
) -> Option<String> {
|
||||
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
|
||||
return Some(budget);
|
||||
}
|
||||
if let Some(token_budget) = token_budget {
|
||||
return Some(format!(
|
||||
"{} / {}",
|
||||
@@ -79,7 +94,14 @@ fn active_goal_usage(
|
||||
Some(format_goal_elapsed_seconds(time_used_seconds))
|
||||
}
|
||||
|
||||
fn stopped_goal_budget_usage(token_budget: Option<i64>, tokens_used: i64) -> Option<String> {
|
||||
fn stopped_goal_budget_usage(
|
||||
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
|
||||
token_budget: Option<i64>,
|
||||
tokens_used: i64,
|
||||
) -> Option<String> {
|
||||
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
|
||||
return Some(format!("{budget} 5h limit"));
|
||||
}
|
||||
token_budget.map(|token_budget| {
|
||||
format!(
|
||||
"{} / {} tokens",
|
||||
@@ -90,10 +112,14 @@ fn stopped_goal_budget_usage(token_budget: Option<i64>, tokens_used: i64) -> Opt
|
||||
}
|
||||
|
||||
fn completed_goal_usage(
|
||||
budget: Option<&codex_app_server_protocol::ThreadGoalBudget>,
|
||||
token_budget: Option<i64>,
|
||||
tokens_used: i64,
|
||||
time_used_seconds: i64,
|
||||
) -> String {
|
||||
if let Some(budget) = budget.and_then(format_five_hour_goal_progress) {
|
||||
return format!("{budget} 5h limit");
|
||||
}
|
||||
if token_budget.is_some() {
|
||||
return format!("{} tokens", format_tokens_compact(tokens_used));
|
||||
}
|
||||
@@ -117,6 +143,7 @@ mod tests {
|
||||
fn active_goal_usage_prefers_token_budget() {
|
||||
assert_eq!(
|
||||
active_goal_usage(
|
||||
/*budget*/ None,
|
||||
Some(50_000),
|
||||
/*tokens_used*/ 12_500,
|
||||
/*time_used_seconds*/ 90
|
||||
@@ -129,7 +156,7 @@ mod tests {
|
||||
fn active_goal_usage_reports_time_without_budget() {
|
||||
assert_eq!(
|
||||
active_goal_usage(
|
||||
/*token_budget*/ None, /*tokens_used*/ 12_500,
|
||||
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 12_500,
|
||||
/*time_used_seconds*/ 120,
|
||||
),
|
||||
Some("2m".to_string())
|
||||
@@ -139,7 +166,11 @@ mod tests {
|
||||
#[test]
|
||||
fn stopped_goal_budget_usage_reports_budgeted_tokens() {
|
||||
assert_eq!(
|
||||
stopped_goal_budget_usage(Some(50_000), /*tokens_used*/ 63_876),
|
||||
stopped_goal_budget_usage(
|
||||
/*budget*/ None,
|
||||
Some(50_000),
|
||||
/*tokens_used*/ 63_876
|
||||
),
|
||||
Some("63.9K / 50K tokens".to_string())
|
||||
);
|
||||
}
|
||||
@@ -147,7 +178,9 @@ mod tests {
|
||||
#[test]
|
||||
fn stopped_goal_budget_usage_omits_unbudgeted_usage() {
|
||||
assert_eq!(
|
||||
stopped_goal_budget_usage(/*token_budget*/ None, /*tokens_used*/ 12_500),
|
||||
stopped_goal_budget_usage(
|
||||
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 12_500
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
@@ -156,6 +189,7 @@ mod tests {
|
||||
fn completed_goal_usage_reports_tokens_when_budgeted() {
|
||||
assert_eq!(
|
||||
completed_goal_usage(
|
||||
/*budget*/ None,
|
||||
Some(50_000),
|
||||
/*tokens_used*/ 40_000,
|
||||
/*time_used_seconds*/ 120,
|
||||
@@ -168,7 +202,7 @@ mod tests {
|
||||
fn completed_goal_usage_reports_time_without_token_budget() {
|
||||
assert_eq!(
|
||||
completed_goal_usage(
|
||||
/*token_budget*/ None, /*tokens_used*/ 40_000,
|
||||
/*budget*/ None, /*token_budget*/ None, /*tokens_used*/ 40_000,
|
||||
/*time_used_seconds*/ 36_720,
|
||||
),
|
||||
"10h 12m".to_string()
|
||||
@@ -214,6 +248,7 @@ mod tests {
|
||||
thread_id: "thread".to_string(),
|
||||
objective: "do the thing".to_string(),
|
||||
status: AppThreadGoalStatus::Active,
|
||||
budget: None,
|
||||
token_budget: None,
|
||||
tokens_used: 0,
|
||||
time_used_seconds,
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::*;
|
||||
use crate::app_event::ThreadGoalSetMode;
|
||||
use crate::bottom_pane::prompt_args::parse_slash_name;
|
||||
use crate::bottom_pane::slash_commands;
|
||||
use codex_app_server_protocol::ThreadGoalBudgetParams;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum SlashCommandDispatchSource {
|
||||
@@ -32,6 +33,84 @@ const SIDE_SLASH_COMMAND_UNAVAILABLE_HINT: &str = "Press Esc to return to the ma
|
||||
const GOAL_USAGE: &str = "Usage: /goal <objective>";
|
||||
const GOAL_USAGE_HINT: &str = "Example: /goal improve benchmark coverage";
|
||||
|
||||
struct ParsedGoalCommand {
|
||||
objective: String,
|
||||
budget: Option<ThreadGoalBudgetParams>,
|
||||
}
|
||||
|
||||
fn parse_goal_objective_and_budget(input: &str) -> Result<ParsedGoalCommand, String> {
|
||||
let Some(rest) = input.strip_prefix("--tokens ") else {
|
||||
if let Some(rest) = input.strip_prefix("--5h-limit ") {
|
||||
return parse_goal_five_hour_limit_budget(rest, "--5h-limit");
|
||||
}
|
||||
if let Some(rest) = input.strip_prefix("--five-hour-limit ") {
|
||||
return parse_goal_five_hour_limit_budget(rest, "--five-hour-limit");
|
||||
};
|
||||
return Ok(ParsedGoalCommand {
|
||||
objective: input.to_string(),
|
||||
budget: None,
|
||||
});
|
||||
};
|
||||
let (tokens, objective) = split_budget_value(rest, "--tokens")?;
|
||||
Ok(ParsedGoalCommand {
|
||||
objective: objective.to_string(),
|
||||
budget: Some(ThreadGoalBudgetParams::Tokens {
|
||||
token_budget: parse_goal_token_budget(tokens)?,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_goal_five_hour_limit_budget(input: &str, flag: &str) -> Result<ParsedGoalCommand, String> {
|
||||
let (percent, objective) = split_budget_value(input, flag)?;
|
||||
Ok(ParsedGoalCommand {
|
||||
objective: objective.to_string(),
|
||||
budget: Some(ThreadGoalBudgetParams::FiveHourLimitPercent {
|
||||
percent: parse_goal_five_hour_percent(percent)?,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn split_budget_value<'a>(input: &'a str, flag: &str) -> Result<(&'a str, &'a str), String> {
|
||||
let mut parts = input.trim().splitn(2, char::is_whitespace);
|
||||
let value = parts.next().unwrap_or_default();
|
||||
let objective = parts.next().unwrap_or_default().trim();
|
||||
if value.is_empty() || objective.is_empty() {
|
||||
return Err(format!("Usage: /goal {flag} <value> <objective>"));
|
||||
}
|
||||
Ok((value, objective))
|
||||
}
|
||||
|
||||
fn parse_goal_token_budget(value: &str) -> Result<i64, String> {
|
||||
let (number, multiplier) = match value.chars().last() {
|
||||
Some('k' | 'K') => (&value[..value.len() - 1], 1_000.0),
|
||||
Some('m' | 'M') => (&value[..value.len() - 1], 1_000_000.0),
|
||||
_ => (value, 1.0),
|
||||
};
|
||||
let parsed = number
|
||||
.parse::<f64>()
|
||||
.map_err(|_| "Token budget must be a number like 500000 or 500k.".to_string())?;
|
||||
let budget = (parsed * multiplier).round();
|
||||
if !budget.is_finite() || budget <= 0.0 || budget > i64::MAX as f64 {
|
||||
return Err("Token budget must be positive.".to_string());
|
||||
}
|
||||
Ok(budget as i64)
|
||||
}
|
||||
|
||||
fn parse_goal_five_hour_percent(value: &str) -> Result<f64, String> {
|
||||
let value = value
|
||||
.trim()
|
||||
.strip_suffix('%')
|
||||
.unwrap_or(value.trim())
|
||||
.trim();
|
||||
let percent = value
|
||||
.parse::<f64>()
|
||||
.map_err(|_| "5h limit must be a percent like 10%.".to_string())?;
|
||||
if !percent.is_finite() || percent <= 0.0 || percent > 100.0 {
|
||||
return Err("5h limit must be between 0% and 100%.".to_string());
|
||||
}
|
||||
Ok(percent)
|
||||
}
|
||||
|
||||
impl ChatWidget {
|
||||
/// Dispatch a bare slash command and record its staged local-history entry.
|
||||
///
|
||||
@@ -654,7 +733,17 @@ impl ChatWidget {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let objective = args.trim();
|
||||
let parsed_goal = match parse_goal_objective_and_budget(args.trim()) {
|
||||
Ok(parsed_goal) => parsed_goal,
|
||||
Err(err) => {
|
||||
self.add_error_message(err);
|
||||
if source == SlashCommandDispatchSource::Live {
|
||||
self.bottom_pane.drain_pending_submission_state();
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
let objective = parsed_goal.objective.as_str();
|
||||
if objective.is_empty() {
|
||||
self.add_error_message("Goal objective must not be empty.".to_string());
|
||||
self.add_info_message(
|
||||
@@ -689,7 +778,8 @@ impl ChatWidget {
|
||||
};
|
||||
self.app_event_tx.send(AppEvent::SetThreadGoalObjective {
|
||||
thread_id,
|
||||
objective: objective.to_string(),
|
||||
objective: parsed_goal.objective,
|
||||
budget: parsed_goal.budget,
|
||||
mode: ThreadGoalSetMode::ConfirmIfExists,
|
||||
});
|
||||
if source == SlashCommandDispatchSource::Live {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
---
|
||||
source: tui/src/chatwidget/tests/goal_menu.rs
|
||||
expression: "render_bottom_popup(&chat, 80)"
|
||||
---
|
||||
| Set goal
|
||||
| Budget: None tab focus, arrows cycle
|
||||
| Objective:
|
||||
| What should Codex keep working toward?
|
||||
|
|
||||
|
||||
Press enter to confirm or esc to go back
|
||||
@@ -42,6 +42,14 @@ async fn goal_menu_budget_limited_snapshot() {
|
||||
assert_chatwidget_snapshot!("goal_menu_budget_limited", rendered_goal_summary(&mut rx));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn goal_setup_snapshot() {
|
||||
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.show_goal_setup(ThreadId::new());
|
||||
|
||||
assert_chatwidget_snapshot!("goal_setup", render_bottom_popup(&chat, /*width*/ 80));
|
||||
}
|
||||
|
||||
fn test_goal(
|
||||
thread_id: ThreadId,
|
||||
status: AppThreadGoalStatus,
|
||||
@@ -52,6 +60,7 @@ fn test_goal(
|
||||
objective: "Keep improving the bare goal command until it feels calm and useful."
|
||||
.to_string(),
|
||||
status,
|
||||
budget: None,
|
||||
token_budget,
|
||||
tokens_used: 12_500,
|
||||
time_used_seconds: 90,
|
||||
|
||||
@@ -1180,6 +1180,7 @@ async fn interrupted_turn_after_goal_budget_limited_uses_budget_message_snapshot
|
||||
thread_id: "thread-1".to_string(),
|
||||
objective: "Run until the token budget is limited".to_string(),
|
||||
status: codex_app_server_protocol::ThreadGoalStatus::BudgetLimited,
|
||||
budget: None,
|
||||
token_budget: Some(10_000),
|
||||
tokens_used: 10_500,
|
||||
time_used_seconds: 0,
|
||||
|
||||
@@ -571,18 +571,59 @@ async fn goal_slash_command_emits_set_goal_event() {
|
||||
let AppEvent::SetThreadGoalObjective {
|
||||
thread_id: actual_thread_id,
|
||||
objective,
|
||||
budget,
|
||||
mode,
|
||||
} = event
|
||||
else {
|
||||
panic!("expected SetThreadGoalObjective, got {event:?}");
|
||||
};
|
||||
assert_eq!(actual_thread_id, thread_id);
|
||||
assert_eq!(objective, "--tokens 98.5K improve benchmark coverage");
|
||||
assert_eq!(objective, "improve benchmark coverage");
|
||||
assert_eq!(
|
||||
budget,
|
||||
Some(codex_app_server_protocol::ThreadGoalBudgetParams::Tokens {
|
||||
token_budget: 98_500,
|
||||
})
|
||||
);
|
||||
assert_eq!(mode, crate::app_event::ThreadGoalSetMode::ConfirmIfExists);
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
assert_eq!(recall_latest_after_clearing(&mut chat), command);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn goal_slash_command_accepts_five_hour_limit_budget() {
|
||||
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
chat.set_feature_enabled(Feature::Goals, /*enabled*/ true);
|
||||
let thread_id = ThreadId::new();
|
||||
chat.thread_id = Some(thread_id);
|
||||
let command = "/goal --5h-limit 7.5% finish the risky migration";
|
||||
|
||||
submit_composer_text(&mut chat, command);
|
||||
|
||||
let event = rx.try_recv().expect("expected goal objective event");
|
||||
let AppEvent::SetThreadGoalObjective {
|
||||
thread_id: actual_thread_id,
|
||||
objective,
|
||||
budget,
|
||||
mode,
|
||||
} = event
|
||||
else {
|
||||
panic!("expected SetThreadGoalObjective, got {event:?}");
|
||||
};
|
||||
assert_eq!(actual_thread_id, thread_id);
|
||||
assert_eq!(objective, "finish the risky migration");
|
||||
assert_eq!(
|
||||
budget,
|
||||
Some(
|
||||
codex_app_server_protocol::ThreadGoalBudgetParams::FiveHourLimitPercent {
|
||||
percent: 7.5
|
||||
}
|
||||
)
|
||||
);
|
||||
assert_eq!(mode, crate::app_event::ThreadGoalSetMode::ConfirmIfExists);
|
||||
assert_no_submit_op(&mut op_rx);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn goal_slash_command_uses_plain_text_for_mentions() {
|
||||
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(/*model_override*/ None).await;
|
||||
@@ -1355,6 +1396,7 @@ async fn active_goal_without_follow_up_suppresses_agent_turn_complete_notificati
|
||||
thread_id: "thread-1".to_string(),
|
||||
objective: "finish the benchmark".to_string(),
|
||||
status: codex_app_server_protocol::ThreadGoalStatus::Active,
|
||||
budget: None,
|
||||
token_budget: None,
|
||||
tokens_used: 0,
|
||||
time_used_seconds: 0,
|
||||
|
||||
@@ -1867,6 +1867,7 @@ fn test_thread_goal(
|
||||
thread_id: "thread-1".to_string(),
|
||||
objective: "Keep improving the benchmark".to_string(),
|
||||
status,
|
||||
budget: None,
|
||||
token_budget,
|
||||
tokens_used,
|
||||
time_used_seconds: 30 * 60,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::status::format_tokens_compact;
|
||||
use codex_app_server_protocol::ThreadGoal;
|
||||
use codex_app_server_protocol::ThreadGoalBudget;
|
||||
use codex_app_server_protocol::ThreadGoalStatus;
|
||||
|
||||
pub(crate) fn format_goal_elapsed_seconds(seconds: i64) -> String {
|
||||
@@ -51,10 +52,69 @@ pub(crate) fn goal_usage_summary(goal: &ThreadGoal) -> String {
|
||||
format_tokens_compact(goal.tokens_used),
|
||||
format_tokens_compact(token_budget)
|
||||
));
|
||||
} else if let Some(ThreadGoalBudget::FiveHourLimitPercent {
|
||||
percent,
|
||||
baseline_used_percent,
|
||||
latest_used_percent,
|
||||
baseline_resets_at,
|
||||
..
|
||||
}) = &goal.budget
|
||||
{
|
||||
parts.push(format!(
|
||||
"5h limit: {} / {}.",
|
||||
format_percent_points(latest_used_percent - baseline_used_percent),
|
||||
format_percent_points(*percent)
|
||||
));
|
||||
if let Some(resets_at) = baseline_resets_at {
|
||||
parts.push(format!(
|
||||
"Started at {}; limit at {}; resets {}.",
|
||||
format_percent(*baseline_used_percent),
|
||||
format_percent(baseline_used_percent + percent),
|
||||
format_unix_date(*resets_at)
|
||||
));
|
||||
}
|
||||
}
|
||||
parts.join(" ")
|
||||
}
|
||||
|
||||
pub(crate) fn format_five_hour_goal_progress(budget: &ThreadGoalBudget) -> Option<String> {
|
||||
match budget {
|
||||
ThreadGoalBudget::FiveHourLimitPercent {
|
||||
percent,
|
||||
baseline_used_percent,
|
||||
latest_used_percent,
|
||||
..
|
||||
} => Some(format!(
|
||||
"{} / {}",
|
||||
format_percent_points(latest_used_percent - baseline_used_percent),
|
||||
format_percent_points(*percent)
|
||||
)),
|
||||
ThreadGoalBudget::Tokens { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn format_percent_points(value: f64) -> String {
|
||||
format!("+{}pp", format_percent_number(value.max(0.0)))
|
||||
}
|
||||
|
||||
fn format_percent(value: f64) -> String {
|
||||
format!("{}%", format_percent_number(value))
|
||||
}
|
||||
|
||||
fn format_percent_number(value: f64) -> String {
|
||||
if (value.fract()).abs() < 0.05 {
|
||||
format!("{value:.0}")
|
||||
} else {
|
||||
format!("{value:.1}")
|
||||
}
|
||||
}
|
||||
|
||||
fn format_unix_date(value: i64) -> String {
|
||||
chrono::DateTime::from_timestamp(value, 0)
|
||||
.map(|date| date.format("%b %-d, %Y").to_string())
|
||||
.unwrap_or_else(|| "unknown".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -86,6 +146,7 @@ mod tests {
|
||||
objective: "Complete the task described in ../gameboy-long-running-prompt5.txt"
|
||||
.to_string(),
|
||||
status: ThreadGoalStatus::BudgetLimited,
|
||||
budget: token_budget.map(|token_budget| ThreadGoalBudget::Tokens { token_budget }),
|
||||
token_budget,
|
||||
tokens_used,
|
||||
time_used_seconds: 120,
|
||||
|
||||
Reference in New Issue
Block a user