mirror of
https://github.com/openai/codex.git
synced 2026-11-30 00:10:49 +00:00
tui compact
This commit is contained in:
+196
-8
@@ -12,6 +12,7 @@ use crate::slash_command::SlashCommand;
|
||||
use crate::tui;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::protocol::Event;
|
||||
use codex_core::protocol::Op;
|
||||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
@@ -21,6 +22,22 @@ use std::path::PathBuf;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
/// Template for compact summary continuation prompt
|
||||
const COMPACT_SUMMARY_TEMPLATE: &str = concat!(
|
||||
"This chat is a continuation of a previous conversation. ",
|
||||
"After providing the summary, acknowledge that /compact command has been applied. ",
|
||||
"Here is the summary of the previous conversation:\n\n{}"
|
||||
);
|
||||
|
||||
/// Creates the initial prompt for a compacted conversation
|
||||
fn create_compact_summary_prompt(summary_text: &str) -> String {
|
||||
if summary_text.trim().is_empty() {
|
||||
"Previous conversation has been summarized.".to_string()
|
||||
} else {
|
||||
COMPACT_SUMMARY_TEMPLATE.replace("{}", summary_text.trim())
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level application state: which full-screen view is currently active.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
enum AppState<'a> {
|
||||
@@ -36,6 +53,21 @@ enum AppState<'a> {
|
||||
GitWarning { screen: GitWarningScreen },
|
||||
}
|
||||
|
||||
/// State for tracking a pending summarization request
|
||||
struct PendingSummarization {
|
||||
/// Buffer to collect the summary response
|
||||
summary_buffer: String,
|
||||
}
|
||||
|
||||
/// Aggregate parameters needed to create a `ChatWidget`, as creation may be
|
||||
/// deferred until after the Git warning screen is dismissed.
|
||||
#[derive(Clone)]
|
||||
struct ChatWidgetArgs {
|
||||
config: Config,
|
||||
initial_prompt: Option<String>,
|
||||
initial_images: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
pub(crate) struct App<'a> {
|
||||
app_event_tx: AppEventSender,
|
||||
app_event_rx: Receiver<AppEvent>,
|
||||
@@ -49,15 +81,9 @@ pub(crate) struct App<'a> {
|
||||
/// Stored parameters needed to instantiate the ChatWidget later, e.g.,
|
||||
/// after dismissing the Git-repo warning.
|
||||
chat_args: Option<ChatWidgetArgs>,
|
||||
}
|
||||
|
||||
/// Aggregate parameters needed to create a `ChatWidget`, as creation may be
|
||||
/// deferred until after the Git warning screen is dismissed.
|
||||
#[derive(Clone)]
|
||||
struct ChatWidgetArgs {
|
||||
config: Config,
|
||||
initial_prompt: Option<String>,
|
||||
initial_images: Vec<PathBuf>,
|
||||
/// Tracks pending summarization requests for the compact feature
|
||||
pending_summarization: Option<PendingSummarization>,
|
||||
}
|
||||
|
||||
impl<'a> App<'a> {
|
||||
@@ -167,6 +193,7 @@ impl<'a> App<'a> {
|
||||
config,
|
||||
file_search,
|
||||
chat_args,
|
||||
pending_summarization: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,6 +251,40 @@ impl<'a> App<'a> {
|
||||
self.dispatch_scroll_event(scroll_delta);
|
||||
}
|
||||
AppEvent::CodexEvent(event) => {
|
||||
// Check if we're waiting for a summarization response
|
||||
if let Some(ref mut pending) = self.pending_summarization {
|
||||
if let Event {
|
||||
msg: codex_core::protocol::EventMsg::AgentMessage(ref msg),
|
||||
..
|
||||
} = event
|
||||
{
|
||||
// Collect the summary response
|
||||
pending.summary_buffer.push_str(&msg.message);
|
||||
pending.summary_buffer.push('\n');
|
||||
} else if let Event {
|
||||
msg: codex_core::protocol::EventMsg::TaskComplete(_),
|
||||
..
|
||||
} = event
|
||||
{
|
||||
// Task is complete, now create a new widget with the summary
|
||||
if let Some(pending) = self.pending_summarization.take() {
|
||||
let summary =
|
||||
create_compact_summary_prompt(&pending.summary_buffer);
|
||||
|
||||
// Create new widget with summary as initial prompt
|
||||
let new_widget = Box::new(ChatWidget::new(
|
||||
self.config.clone(),
|
||||
self.app_event_tx.clone(),
|
||||
Some(summary),
|
||||
Vec::new(),
|
||||
));
|
||||
self.app_state = AppState::Chat { widget: new_widget };
|
||||
self.app_event_tx.send(AppEvent::Redraw);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.dispatch_codex_event(event);
|
||||
}
|
||||
AppEvent::ExitRequest => {
|
||||
@@ -277,6 +338,17 @@ impl<'a> App<'a> {
|
||||
widget.add_diff_output(text);
|
||||
}
|
||||
}
|
||||
SlashCommand::Compact => {
|
||||
if let AppState::Chat { widget } = &mut self.app_state {
|
||||
// Submit the summarization request to the current widget
|
||||
widget.submit_op(Op::SummarizeContext);
|
||||
|
||||
// Set up tracking for the summary response
|
||||
self.pending_summarization = Some(PendingSummarization {
|
||||
summary_buffer: String::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
AppEvent::StartFileSearch(query) => {
|
||||
self.file_search.on_user_query(query);
|
||||
@@ -357,3 +429,119 @@ impl<'a> App<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use codex_core::protocol::AgentMessageEvent;
|
||||
use codex_core::protocol::EventMsg;
|
||||
use codex_core::protocol::TaskCompleteEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn test_create_compact_summary_prompt_with_content() {
|
||||
let summary_text = "User asked about Rust. I explained ownership and borrowing.";
|
||||
let result = create_compact_summary_prompt(summary_text);
|
||||
|
||||
let expected = COMPACT_SUMMARY_TEMPLATE.replace(
|
||||
"{}",
|
||||
"User asked about Rust. I explained ownership and borrowing.",
|
||||
);
|
||||
assert_eq!(result, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_create_compact_summary_prompt_empty_content() {
|
||||
let result = create_compact_summary_prompt("");
|
||||
assert_eq!(result, "Previous conversation has been summarized.");
|
||||
|
||||
let result_whitespace = create_compact_summary_prompt(" \n\t ");
|
||||
assert_eq!(
|
||||
result_whitespace,
|
||||
"Previous conversation has been summarized."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pending_summarization_state_management() {
|
||||
let mut pending = PendingSummarization {
|
||||
summary_buffer: String::new(),
|
||||
};
|
||||
|
||||
// Simulate collecting summary pieces
|
||||
pending.summary_buffer.push_str("First part of summary");
|
||||
pending.summary_buffer.push('\n');
|
||||
pending.summary_buffer.push_str("Second part of summary");
|
||||
|
||||
let expected = "First part of summary\nSecond part of summary";
|
||||
assert_eq!(pending.summary_buffer, expected);
|
||||
|
||||
// Test that create_compact_summary_prompt works with collected buffer
|
||||
let prompt = create_compact_summary_prompt(&pending.summary_buffer);
|
||||
assert!(prompt.contains("First part of summary"));
|
||||
assert!(prompt.contains("Second part of summary"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_summary_template_integrity() {
|
||||
// Ensure the template has expected structure and placeholder
|
||||
assert!(COMPACT_SUMMARY_TEMPLATE.contains("{}"));
|
||||
assert!(COMPACT_SUMMARY_TEMPLATE.contains("continuation of a previous conversation"));
|
||||
assert!(COMPACT_SUMMARY_TEMPLATE.contains("/compact command has been applied"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_agent_message_event_creation() {
|
||||
// Test that we can create the events we expect to handle
|
||||
let msg_event = EventMsg::AgentMessage(AgentMessageEvent {
|
||||
message: "This is a test summary".to_string(),
|
||||
});
|
||||
|
||||
if let EventMsg::AgentMessage(agent_msg) = msg_event {
|
||||
assert_eq!(agent_msg.message, "This is a test summary");
|
||||
} else {
|
||||
panic!("Expected AgentMessage event");
|
||||
}
|
||||
|
||||
let task_complete_event = EventMsg::TaskComplete(TaskCompleteEvent {
|
||||
last_agent_message: Some("Final message".to_string()),
|
||||
});
|
||||
|
||||
matches!(task_complete_event, EventMsg::TaskComplete(_));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiline_summary_handling() {
|
||||
let multiline_summary = "Line 1: User question\nLine 2: My response\nLine 3: Follow-up";
|
||||
let result = create_compact_summary_prompt(multiline_summary);
|
||||
|
||||
assert!(result.contains("Line 1: User question"));
|
||||
assert!(result.contains("Line 2: My response"));
|
||||
assert!(result.contains("Line 3: Follow-up"));
|
||||
assert!(result.contains("continuation of a previous conversation"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_summary_buffer_accumulation() {
|
||||
let mut buffer = String::new();
|
||||
|
||||
// Simulate the way we accumulate messages in pending_summarization
|
||||
buffer.push_str("First message part");
|
||||
buffer.push('\n');
|
||||
buffer.push_str("Second message part");
|
||||
buffer.push('\n');
|
||||
buffer.push_str("Final message part");
|
||||
|
||||
let prompt = create_compact_summary_prompt(&buffer);
|
||||
|
||||
// Should contain all parts
|
||||
assert!(prompt.contains("First message part"));
|
||||
assert!(prompt.contains("Second message part"));
|
||||
assert!(prompt.contains("Final message part"));
|
||||
|
||||
// Should preserve newlines in the content
|
||||
let trimmed_buffer = buffer.trim();
|
||||
assert!(prompt.contains(trimmed_buffer));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ pub enum SlashCommand {
|
||||
Diff,
|
||||
Quit,
|
||||
ToggleMouseMode,
|
||||
Compact,
|
||||
}
|
||||
|
||||
impl SlashCommand {
|
||||
@@ -30,6 +31,9 @@ impl SlashCommand {
|
||||
SlashCommand::Diff => {
|
||||
"Show git diff of the working directory (including untracked files)"
|
||||
}
|
||||
SlashCommand::Compact => {
|
||||
"Summarize and compact the current conversation to free up context."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,3 +48,28 @@ impl SlashCommand {
|
||||
pub fn built_in_slash_commands() -> Vec<(&'static str, SlashCommand)> {
|
||||
SlashCommand::iter().map(|c| (c.command(), c)).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[test]
|
||||
fn test_compact_from_string() {
|
||||
let result = SlashCommand::from_str("compact").unwrap();
|
||||
assert_eq!(result, SlashCommand::Compact);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_in_built_in_commands() {
|
||||
let built_in = built_in_slash_commands();
|
||||
let compact_entry = built_in.iter().find(|(cmd, _)| *cmd == "compact");
|
||||
|
||||
assert!(compact_entry.is_some());
|
||||
let (cmd, slash_cmd) = compact_entry.unwrap();
|
||||
assert_eq!(*cmd, "compact");
|
||||
assert_eq!(*slash_cmd, SlashCommand::Compact);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user