mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Preserve conversation context and separate next actions in recaps (#45090)
## Why The 900-byte recap prompt limit leaves little room for completed progress, unresolved caveats, and recent corrections. Recaps need this context to distinguish completed work from pending requests. ## What changed - Introduce a shared `RecapPrompt` with a 32 KiB ceiling for instructions and history, using an 8,192-token estimate. Instruct summaries to retain the broader goal, completed outcomes, and unresolved availability or validation caveats. - Select up to eight answered exchanges plus a pending request, preserving adjacent steering and progress messages. Drop older whole exchanges before excerpting both ends of oversized messages, while retaining the newest answer and pending correction. - Require a `summary` and nullable `next_action`, bounded to 700 and 200 characters respectively. Reject malformed or oversized responses and display an optional, separately styled `Next:` line. ## Testing Add coverage for UTF-8 prompt bounds, exchange selection, pending corrections, excerpt boundaries, strict response parsing, and next-action rendering. Extend the recap generation integration test to verify bounded history and the structured response schema. GitOrigin-RevId: 6c6a84bc602a168418c1952feb1d286ec0cb9e28
This commit is contained in:
1 parent
f16c2237a5
commit
8d3c6cc13d
9 files changed
+544
-141
No files matched your search
+39
-111
@@ -1,7 +1,6 @@
|
||||
//! Determines when an unfocused conversation is ready for an automatic recap.
|
||||
//! Schedules and generates bounded recaps through the existing temporary request path.
|
||||
//! The TUI opt-out suppresses automatic scheduling and requests, but not manual `/recap`.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
@@ -10,12 +9,8 @@ use crate::app_event::AppEvent;
|
||||
use crate::app_event::RecapTrigger;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::history_cell::AgentMarkdownCell;
|
||||
use crate::history_cell::AgentMessageCell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::ThreadRecapHistoryCell;
|
||||
use crate::history_cell::ThreadRecapLoadingCell;
|
||||
use crate::history_cell::UserHistoryCell;
|
||||
use crate::pager_overlay::Overlay;
|
||||
use crate::temporary_structured_request::TemporaryStructuredThreadOptions;
|
||||
use crate::temporary_structured_request::run_temporary_structured_turn;
|
||||
@@ -23,6 +18,8 @@ use crate::temporary_structured_request::start_temporary_thread;
|
||||
use crate::temporary_structured_request::unsubscribe_temporary_thread;
|
||||
use codex_app_server_protocol::Turn;
|
||||
use codex_app_server_protocol::TurnStatus;
|
||||
use codex_context_fragments::ContextualUserFragment;
|
||||
use codex_context_fragments::RecapPrompt;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
@@ -34,137 +31,68 @@ use uuid::Uuid;
|
||||
const MIN_COMPLETED_TURNS: usize = 3;
|
||||
const MIN_TURNS_BETWEEN_RECAPS: usize = 2;
|
||||
pub(super) const RECAP_DELAY: Duration = Duration::from_secs(/*secs*/ 30 * 60);
|
||||
const RECAP_HISTORY_MAX_TURNS: usize = 8;
|
||||
const RECAP_MAX_CHARS: usize = 320;
|
||||
const RECAP_MAX_CHARS: usize = 700;
|
||||
const RECAP_NEXT_MAX_CHARS: usize = 200;
|
||||
const RECAP_RETRY_DELAY: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
const MANUAL_RECAP_FAILURE_MESSAGE: &str = "Could not generate a recap. Please try again.";
|
||||
const MANUAL_RECAP_IN_PROGRESS_MESSAGE: &str = "A recap is already being generated.";
|
||||
const MANUAL_RECAP_EMPTY_HISTORY_MESSAGE: &str = "There is no conversation history to recap.";
|
||||
const RECAP_PROMPT_PREFIX: &str = concat!(
|
||||
"Write a brief catch-up for a user returning to this Codex task. ",
|
||||
"In at most 40 words and one or two plain-text sentences, explain the ",
|
||||
"objective, what was completed or learned, and the next step or blocker. ",
|
||||
"Mention changed files, tests, approvals, or requested decisions only ",
|
||||
"when relevant. Never claim changes were made or tests passed unless ",
|
||||
"the conversation confirms it. If the task is complete, say so instead ",
|
||||
"of inventing more work. Use the user's language; omit greetings, ",
|
||||
"markdown, lists, and tool chatter.\n\nRecent conversation:\n",
|
||||
);
|
||||
pub(super) const RECAP_PROMPT_MAX_BYTES: usize = 900;
|
||||
#[cfg(test)]
|
||||
pub(super) const RECAP_PROMPT_MAX_BYTES: usize = RecapPrompt::MAX_BYTES;
|
||||
|
||||
fn render_recap_message(role: &str, content: &str, max_bytes: usize) -> Option<String> {
|
||||
let prefix = format!("{role}: ");
|
||||
let content_budget = max_bytes.checked_sub(prefix.len())?;
|
||||
let end = content.floor_char_boundary(content_budget.min(content.len()));
|
||||
Some(format!("{prefix}{}", &content[..end]))
|
||||
}
|
||||
#[path = "recap_history.rs"]
|
||||
mod history;
|
||||
use history::recap_history;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[derive(Debug, Deserialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct GeneratedRecap {
|
||||
recap: String,
|
||||
}
|
||||
|
||||
fn recap_history(cells: &[Arc<dyn HistoryCell>]) -> String {
|
||||
let mut messages = Vec::new();
|
||||
let mut user_turns = 0;
|
||||
|
||||
for cell in cells.iter().rev() {
|
||||
let is_user = cell.as_any().is::<UserHistoryCell>();
|
||||
|
||||
let role = if is_user {
|
||||
"User"
|
||||
} else if cell.as_any().is::<AgentMarkdownCell>() || cell.as_any().is::<AgentMessageCell>()
|
||||
{
|
||||
"Assistant"
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let content = cell
|
||||
.raw_lines()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
let content = content.trim();
|
||||
if content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
messages.push((role, content.to_string()));
|
||||
|
||||
if is_user {
|
||||
user_turns += 1;
|
||||
if user_turns == RECAP_HISTORY_MAX_TURNS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
messages.reverse();
|
||||
if messages.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
let byte_budget = RECAP_PROMPT_MAX_BYTES.saturating_sub(RECAP_PROMPT_PREFIX.len());
|
||||
let latest = messages
|
||||
.iter()
|
||||
.rposition(|(r, _)| *r == "User")
|
||||
.unwrap_or(messages.len() - 1);
|
||||
// Reserve half the budget for the latest request, then fill from newest to oldest.
|
||||
let latest_user_budget = byte_budget / 2;
|
||||
let (role, content) = &messages[latest];
|
||||
let latest_user = render_recap_message(role, content, latest_user_budget).unwrap_or_default();
|
||||
let mut selected = vec![(latest, latest_user)];
|
||||
let mut remaining = byte_budget.saturating_sub(selected[0].1.len());
|
||||
for (index, (role, content)) in messages.iter().enumerate().rev() {
|
||||
if index == latest || remaining <= 2 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(rendered) = render_recap_message(role, content, remaining - 2) else {
|
||||
continue;
|
||||
};
|
||||
remaining = remaining.saturating_sub(rendered.len() + 2);
|
||||
selected.push((index, rendered));
|
||||
}
|
||||
|
||||
selected.sort_unstable_by_key(|(index, _)| *index);
|
||||
selected
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
summary: String,
|
||||
#[serde(deserialize_with = "Option::deserialize")]
|
||||
next_action: Option<String>,
|
||||
}
|
||||
|
||||
fn recap_prompt(history: &str) -> String {
|
||||
format!("{RECAP_PROMPT_PREFIX}{}", history.trim())
|
||||
RecapPrompt::new(history).render()
|
||||
}
|
||||
|
||||
fn recap_output_schema() -> Value {
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"recap": {
|
||||
"summary": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": RECAP_MAX_CHARS,
|
||||
},
|
||||
"next_action": {
|
||||
"type": ["string", "null"],
|
||||
"maxLength": RECAP_NEXT_MAX_CHARS,
|
||||
},
|
||||
},
|
||||
"required": ["recap"],
|
||||
"required": ["summary", "next_action"],
|
||||
"additionalProperties": false,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_recap(response: &str) -> Option<String> {
|
||||
let recap = serde_json::from_str::<GeneratedRecap>(response).ok()?.recap;
|
||||
|
||||
let recap = recap.trim();
|
||||
if recap.is_empty() {
|
||||
fn parse_recap(response: &str) -> Option<GeneratedRecap> {
|
||||
let mut recap = serde_json::from_str::<GeneratedRecap>(response).ok()?;
|
||||
recap.summary = recap.summary.trim().to_string();
|
||||
if recap.summary.is_empty() || recap.summary.chars().count() > RECAP_MAX_CHARS {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(recap.chars().take(RECAP_MAX_CHARS).collect())
|
||||
recap.next_action = recap
|
||||
.next_action
|
||||
.map(|action| action.trim().to_string())
|
||||
.filter(|action| !action.is_empty());
|
||||
if recap
|
||||
.next_action
|
||||
.as_ref()
|
||||
.is_some_and(|action| action.chars().count() > RECAP_NEXT_MAX_CHARS)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(recap)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -464,7 +392,7 @@ impl App {
|
||||
};
|
||||
|
||||
self.recap.mark_recapped(completed_turn_count);
|
||||
Some(ThreadRecapHistoryCell::new(recap))
|
||||
Some(ThreadRecapHistoryCell::new(recap.summary).with_next_action(recap.next_action))
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%thread_id, %error, "failed to generate thread recap");
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Selects recent visible exchanges without reading tools, reasoning, or another thread's history.
|
||||
//! A newer unanswered request is retained once; excerpts preserve both ends within a byte limit.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use codex_context_fragments::RecapPrompt;
|
||||
|
||||
use crate::history_cell::AgentMarkdownCell;
|
||||
use crate::history_cell::AgentMessageCell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::UserHistoryCell;
|
||||
|
||||
pub(super) const RECAP_HISTORY_MAX_TURNS: usize = 8;
|
||||
const OMITTED_HISTORY: &str = "[Earlier exchanges omitted]\n\n";
|
||||
const EXCERPT_MARKER: &str = "\n[... excerpted ...]\n";
|
||||
|
||||
pub(super) fn recap_history(cells: &[Arc<dyn HistoryCell>]) -> String {
|
||||
let exchanges = recent_exchanges(cells);
|
||||
let Some(latest) = exchanges.last() else {
|
||||
return String::new();
|
||||
};
|
||||
let blocks = exchanges
|
||||
.iter()
|
||||
.map(|exchange| {
|
||||
exchange
|
||||
.fields()
|
||||
.map(|(label, text)| format!("{label}: {text}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut bytes = blocks.iter().map(String::len).sum::<usize>() + 2 * (blocks.len() - 1);
|
||||
if bytes <= RecapPrompt::HISTORY_MAX_BYTES {
|
||||
return blocks.join("\n\n");
|
||||
}
|
||||
|
||||
// Keep the newest answer and any newer unanswered correction together.
|
||||
let retained = if latest.assistant.is_empty() { 2 } else { 1 };
|
||||
let oldest_retained = exchanges.len().saturating_sub(retained);
|
||||
let mut start = 0;
|
||||
while bytes > RecapPrompt::HISTORY_MAX_BYTES - OMITTED_HISTORY.len() && start < oldest_retained
|
||||
{
|
||||
bytes -= blocks[start].len() + 2;
|
||||
start += 1;
|
||||
}
|
||||
let omission = if start > 0 { OMITTED_HISTORY } else { "" };
|
||||
let budget = RecapPrompt::HISTORY_MAX_BYTES - omission.len();
|
||||
if bytes <= budget {
|
||||
return format!("{omission}{}", blocks[start..].join("\n\n"));
|
||||
}
|
||||
|
||||
let fields = exchanges[start..]
|
||||
.iter()
|
||||
.flat_map(Exchange::fields)
|
||||
.collect::<Vec<_>>();
|
||||
let field_count = fields.len();
|
||||
let overhead = fields
|
||||
.iter()
|
||||
.map(|(label, _)| label.len() + 2)
|
||||
.sum::<usize>()
|
||||
+ 2 * (field_count - 1);
|
||||
let mut remaining = budget.saturating_sub(overhead);
|
||||
let excerpts = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (label, text))| {
|
||||
let share = remaining / (field_count - index);
|
||||
// Reserve a share for later fields, without wasting space on short replies.
|
||||
let reserved = fields[index + 1..]
|
||||
.iter()
|
||||
.map(|(_, text)| text.len().min(share))
|
||||
.sum::<usize>();
|
||||
let excerpt = excerpt(text, remaining - reserved);
|
||||
remaining -= excerpt.len();
|
||||
format!("{label}: {excerpt}")
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
format!("{omission}{excerpts}")
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Exchange {
|
||||
user: String,
|
||||
assistant: String,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
fn fields(&self) -> impl Iterator<Item = (&'static str, &str)> {
|
||||
let user_label = if self.assistant.is_empty() {
|
||||
"Pending user request"
|
||||
} else {
|
||||
"User"
|
||||
};
|
||||
[
|
||||
(user_label, self.user.as_str()),
|
||||
("Assistant", self.assistant.as_str()),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(_, text)| !text.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
// Adjacent user cells preserve steering as part of one request.
|
||||
fn recent_exchanges(cells: &[Arc<dyn HistoryCell>]) -> Vec<Exchange> {
|
||||
let mut exchanges = Vec::new();
|
||||
let mut current = Exchange::default();
|
||||
let mut answered = 0;
|
||||
for cell in cells.iter().rev() {
|
||||
let is_user = if cell.as_any().is::<UserHistoryCell>() {
|
||||
true
|
||||
} else if cell.as_any().is::<AgentMarkdownCell>() || cell.as_any().is::<AgentMessageCell>()
|
||||
{
|
||||
false
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
let mut content = cell
|
||||
.raw_lines()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.trim()
|
||||
.to_owned();
|
||||
if content.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// In reverse order, assistant text before a request belongs to the preceding exchange.
|
||||
if !is_user && !current.user.is_empty() {
|
||||
answered += usize::from(!current.assistant.is_empty());
|
||||
exchanges.push(std::mem::take(&mut current));
|
||||
if answered == RECAP_HISTORY_MAX_TURNS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let field = if is_user {
|
||||
&mut current.user
|
||||
} else {
|
||||
&mut current.assistant
|
||||
};
|
||||
if !field.is_empty() {
|
||||
content.push_str("\n\n");
|
||||
content.push_str(field);
|
||||
}
|
||||
*field = content;
|
||||
}
|
||||
if !current.user.is_empty() {
|
||||
exchanges.push(current);
|
||||
}
|
||||
exchanges.reverse();
|
||||
exchanges
|
||||
}
|
||||
|
||||
fn excerpt(text: &str, max_bytes: usize) -> String {
|
||||
if text.len() <= max_bytes {
|
||||
return text.to_owned();
|
||||
}
|
||||
let Some(content_bytes) = max_bytes.checked_sub(EXCERPT_MARKER.len()) else {
|
||||
return text[..text.floor_char_boundary(max_bytes)].to_owned();
|
||||
};
|
||||
let head = text.floor_char_boundary(content_bytes / 2);
|
||||
let tail = text.ceil_char_boundary(text.len() - (content_bytes - content_bytes / 2));
|
||||
format!("{}{EXCERPT_MARKER}{}", &text[..head], &text[tail..])
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
use super::App;
|
||||
use super::GeneratedRecap;
|
||||
use super::RECAP_DELAY;
|
||||
use super::RECAP_HISTORY_MAX_TURNS;
|
||||
use super::RECAP_MAX_CHARS;
|
||||
use super::RECAP_NEXT_MAX_CHARS;
|
||||
use super::RECAP_PROMPT_MAX_BYTES;
|
||||
use super::RECAP_RETRY_DELAY;
|
||||
use super::RecapProgress;
|
||||
use super::RecapRequest;
|
||||
use super::RecapState;
|
||||
use super::history::RECAP_HISTORY_MAX_TURNS;
|
||||
use super::parse_recap;
|
||||
use super::recap_history;
|
||||
use super::recap_prompt;
|
||||
@@ -113,6 +115,7 @@ fn recap_history_ignores_activity_previous_recaps_and_empty_messages() {
|
||||
recap_history(&cells),
|
||||
"User: Implement recap\n\nAssistant: Done"
|
||||
);
|
||||
assert_eq!(recap_history(&cells[..2]), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -136,28 +139,153 @@ fn recap_history_caps_utf8_bytes_without_splitting_characters() {
|
||||
let history = recap_history(&cells);
|
||||
|
||||
assert!(recap_prompt(&history).len() <= RECAP_PROMPT_MAX_BYTES);
|
||||
assert!(history.starts_with("User: 最新の進捗🦀"));
|
||||
assert!(history.starts_with("Pending user request: 最新の進捗🦀"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_keeps_eight_exchanges_and_the_pending_correction_once() {
|
||||
let mut cells = Vec::new();
|
||||
for index in 0..10 {
|
||||
cells.push(user_history_cell(&format!("request-{index}")));
|
||||
cells.push(assistant_history_cell(&format!("result-{index}")));
|
||||
}
|
||||
cells.push(user_history_cell("Keep this queued; do not implement it."));
|
||||
let expected = (2..10)
|
||||
.map(|index| format!("User: request-{index}\n\nAssistant: result-{index}"))
|
||||
.chain(["Pending user request: Keep this queued; do not implement it.".to_string()])
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
assert_eq!(recap_history(&cells), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_preserves_steering_and_intermediate_progress() {
|
||||
let cells = vec![
|
||||
assistant_history_cell("Orphaned older answer"),
|
||||
user_history_cell("Fix the parser"),
|
||||
user_history_cell("Keep the API unchanged"),
|
||||
assistant_history_cell("The parser fix is implemented"),
|
||||
assistant_history_cell("All twelve tests pass"),
|
||||
user_history_cell("Fix the parser"),
|
||||
];
|
||||
assert_eq!(
|
||||
recap_history(&cells),
|
||||
"User: Fix the parser\n\nKeep the API unchanged\n\nAssistant: The parser fix is implemented\n\nAll twelve tests pass\n\nPending user request: Fix the parser"
|
||||
);
|
||||
assert_eq!(
|
||||
recap_history(&[assistant_history_cell("Orphaned answer")]),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_drops_old_whole_exchanges_before_clipping_newest() {
|
||||
let cells = vec![
|
||||
user_history_cell("Old request"),
|
||||
assistant_history_cell(&"old ".repeat(RECAP_PROMPT_MAX_BYTES)),
|
||||
user_history_cell("Current request"),
|
||||
assistant_history_cell("Implemented; what should happen on empty input?"),
|
||||
];
|
||||
assert_eq!(
|
||||
recap_history(&cells),
|
||||
"[Earlier exchanges omitted]\n\nUser: Current request\n\nAssistant: Implemented; what should happen on empty input?"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_excerpts_both_ends_and_keeps_the_latest_correction() {
|
||||
let large = "最新🦀".repeat(RECAP_PROMPT_MAX_BYTES);
|
||||
let cells = vec![
|
||||
user_history_cell(&format!("Request start {large} request end")),
|
||||
assistant_history_cell(&format!("Answer start {large} what should empty input do?")),
|
||||
user_history_cell(&format!("Correction start {large} keep it queued")),
|
||||
];
|
||||
let history = recap_history(&cells);
|
||||
assert!(recap_prompt(&history).len() <= RECAP_PROMPT_MAX_BYTES);
|
||||
for expected in [
|
||||
"User: Request start",
|
||||
"request end",
|
||||
"Assistant: Answer start",
|
||||
"what should empty input do?",
|
||||
"Pending user request: Correction start",
|
||||
"keep it queued",
|
||||
] {
|
||||
assert!(history.contains(expected), "missing {expected}");
|
||||
}
|
||||
assert_eq!(history.matches("[... excerpted ...]").count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_request_uses_space_left_by_short_reply_and_correction() {
|
||||
let cells = vec![
|
||||
user_history_cell(&format!(
|
||||
"Request start {} request end",
|
||||
"🦀".repeat(RECAP_PROMPT_MAX_BYTES)
|
||||
)),
|
||||
assistant_history_cell("Implemented; twelve tests pass."),
|
||||
user_history_cell("Keep further work queued."),
|
||||
];
|
||||
let prompt = recap_prompt(&recap_history(&cells));
|
||||
assert!(prompt.len() <= RECAP_PROMPT_MAX_BYTES);
|
||||
assert!(RECAP_PROMPT_MAX_BYTES - prompt.len() < 8);
|
||||
for expected in [
|
||||
"User: Request start",
|
||||
"request end",
|
||||
"Assistant: Implemented; twelve tests pass.",
|
||||
"Pending user request: Keep further work queued.",
|
||||
] {
|
||||
assert!(prompt.contains(expected), "missing {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_recap_is_normalized_and_bounded() {
|
||||
let expected = "🚀".repeat(RECAP_MAX_CHARS);
|
||||
let summary = "🚀".repeat(RECAP_MAX_CHARS);
|
||||
let action = "🚀".repeat(RECAP_NEXT_MAX_CHARS);
|
||||
let cases = [
|
||||
(
|
||||
serde_json::json!({ "recap": " Fixed the parser. \n" }).to_string(),
|
||||
Some("Fixed the parser.".to_string()),
|
||||
serde_json::json!({"summary": " Fixed the parser. ", "next_action": " Run integration tests. "}),
|
||||
Some(GeneratedRecap {
|
||||
summary: "Fixed the parser.".to_string(),
|
||||
next_action: Some("Run integration tests.".to_string()),
|
||||
}),
|
||||
),
|
||||
(
|
||||
serde_json::json!({ "recap": format!("{expected}discarded") }).to_string(),
|
||||
Some(expected),
|
||||
serde_json::json!({"summary": "Done", "next_action": " "}),
|
||||
Some(GeneratedRecap {
|
||||
summary: "Done".to_string(),
|
||||
next_action: None,
|
||||
}),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"summary": summary, "next_action": action}),
|
||||
Some(GeneratedRecap {
|
||||
summary: summary.clone(),
|
||||
next_action: Some(action.clone()),
|
||||
}),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"summary": format!("{summary}x"), "next_action": null}),
|
||||
None,
|
||||
),
|
||||
(
|
||||
serde_json::json!({"summary": "Done", "next_action": format!("{action}x")}),
|
||||
None,
|
||||
),
|
||||
(
|
||||
serde_json::json!({"summary": " ", "next_action": null}),
|
||||
None,
|
||||
),
|
||||
(serde_json::json!({"summary": "Missing action field"}), None),
|
||||
(
|
||||
serde_json::json!({"summary": "Done", "next_action": null, "unexpected": true}),
|
||||
None,
|
||||
),
|
||||
("not json".to_string(), None),
|
||||
(r#"{"recap":" \t "}"#.to_string(), None),
|
||||
];
|
||||
|
||||
for (response, expected) in cases {
|
||||
assert_eq!(parse_recap(&response), expected, "response: {response}");
|
||||
assert_eq!(parse_recap(&response.to_string()), expected);
|
||||
}
|
||||
assert_eq!(parse_recap("not json"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -689,12 +817,48 @@ fn recap_history_cell_preserves_heading_in_raw_history() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_cell_preserves_explicit_line_breaks() {
|
||||
let cell = ThreadRecapHistoryCell::new(
|
||||
"Finished the parser.\nNext: run the focused tests.".to_string(),
|
||||
fn recap_history_cell_wraps_next_action_urls_in_narrow_terminals() {
|
||||
let cell = ThreadRecapHistoryCell::new("The café draft is ready.".to_string())
|
||||
.with_next_action(Some("Review https://example.com/review/42.".to_string()));
|
||||
let lines = cell.display_lines(/*width*/ 32);
|
||||
assert!(lines.iter().all(|line| line_width(line) <= 30));
|
||||
assert_eq!(
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.find(|span| span.content == "Next: "),
|
||||
Some(&"Next: ".bold().cyan().italic()),
|
||||
);
|
||||
let displayed = cell
|
||||
.display_lines(/*width*/ 48)
|
||||
let rendered = lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
insta::assert_snapshot!(rendered, @r"
|
||||
↳ Recap: The café draft is
|
||||
ready.
|
||||
Next: Review
|
||||
https://example.com
|
||||
/review/42.
|
||||
");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recap_history_cell_preserves_line_breaks_and_optional_next() {
|
||||
let cell = ThreadRecapHistoryCell::new("Finished the parser.\nTwelve tests pass.".to_string())
|
||||
.with_next_action(Some(
|
||||
"Run focused tests and check the empty-input case.".to_string(),
|
||||
));
|
||||
let lines = cell.display_lines(/*width*/ 48);
|
||||
assert_eq!(
|
||||
lines
|
||||
.iter()
|
||||
.flat_map(|line| &line.spans)
|
||||
.find(|span| span.content == "Next: "),
|
||||
Some(&"Next: ".bold().cyan().italic()),
|
||||
);
|
||||
let displayed = lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
@@ -708,12 +872,15 @@ fn recap_history_cell_preserves_explicit_line_breaks() {
|
||||
|
||||
insta::assert_snapshot!(displayed, @r"
|
||||
↳ Recap: Finished the parser.
|
||||
Next: run the focused tests.
|
||||
Twelve tests pass.
|
||||
Next: Run focused tests and check
|
||||
the empty-input case.
|
||||
");
|
||||
insta::assert_snapshot!(raw, @r"
|
||||
Conversation recap
|
||||
Finished the parser.
|
||||
Next: run the focused tests.
|
||||
Twelve tests pass.
|
||||
Next: Run focused tests and check the empty-input case.
|
||||
");
|
||||
}
|
||||
|
||||
@@ -751,7 +918,7 @@ async fn generated_recap_is_returned_for_synchronous_insertion() {
|
||||
.handle_generated_recap(
|
||||
request,
|
||||
temporary_thread_id,
|
||||
Ok(serde_json::json!({ "recap": " Continue with focused tests. " }).to_string()),
|
||||
Ok(serde_json::json!({ "summary": " Continue with focused tests. ", "next_action": null }).to_string()),
|
||||
)
|
||||
.expect("fresh recap");
|
||||
|
||||
@@ -770,7 +937,7 @@ async fn auto_recap_opt_out_discards_results_without_retrying() {
|
||||
let thread_id = ThreadId::new();
|
||||
let mut app = app_with_visible_thread(thread_id).await;
|
||||
for result in [
|
||||
Ok(serde_json::json!({ "recap": "obsolete" }).to_string()),
|
||||
Ok(serde_json::json!({ "summary": "obsolete", "next_action": null }).to_string()),
|
||||
Err("temporary failure".to_string()),
|
||||
] {
|
||||
let (request, temporary_thread_id) = track_in_flight_recap(&mut app, thread_id);
|
||||
@@ -798,7 +965,7 @@ async fn obsolete_recap_result_does_not_clear_the_current_request() {
|
||||
..request
|
||||
},
|
||||
temporary_thread_id,
|
||||
Ok(serde_json::json!({ "recap": "obsolete" }).to_string()),
|
||||
Ok(serde_json::json!({ "summary": "obsolete", "next_action": null }).to_string()),
|
||||
);
|
||||
|
||||
assert!(cell.is_none());
|
||||
@@ -817,7 +984,10 @@ async fn newer_terminal_turn_invalidates_generated_recap() {
|
||||
let cell = app.handle_generated_recap(
|
||||
request,
|
||||
temporary_thread_id,
|
||||
Ok(serde_json::json!({ "recap": "missing the failure" }).to_string()),
|
||||
Ok(
|
||||
serde_json::json!({ "summary": "missing the failure", "next_action": null })
|
||||
.to_string(),
|
||||
),
|
||||
);
|
||||
|
||||
assert!(cell.is_none());
|
||||
|
||||
@@ -62,7 +62,7 @@ async fn recap_generation_uses_bounded_structured_request_and_inserts_result() -
|
||||
ev_response_created("recap-response"),
|
||||
ev_assistant_message(
|
||||
"recap-message",
|
||||
r#"{"recap":"Finished parsing. Next: run focused tests."}"#,
|
||||
r#"{"summary":"Finished parsing.","next_action":"Run focused tests."}"#,
|
||||
),
|
||||
ev_completed("recap-response"),
|
||||
]
|
||||
@@ -118,6 +118,22 @@ stream_max_retries = 0
|
||||
while app_event_rx.try_recv().is_ok() {}
|
||||
|
||||
prepare_eligible_recap(&mut app, thread_id).await;
|
||||
app.transcript_cells
|
||||
.push(Arc::new(crate::history_cell::AgentMarkdownCell::new(
|
||||
format!(
|
||||
"Parser fix implemented. {} What should empty input do?",
|
||||
"progress ".repeat(/*n*/ 5_000)
|
||||
),
|
||||
std::path::Path::new("."),
|
||||
)));
|
||||
app.transcript_cells
|
||||
.push(Arc::new(crate::history_cell::UserHistoryCell {
|
||||
message: "Keep follow-up work queued.".to_string(),
|
||||
spoken: false,
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
remote_image_urls: Vec::new(),
|
||||
}));
|
||||
|
||||
app.handle_event(
|
||||
&mut tui,
|
||||
@@ -169,7 +185,8 @@ stream_max_retries = 0
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"Conversation recap",
|
||||
"Finished parsing. Next: run focused tests.",
|
||||
"Finished parsing.",
|
||||
"Next: Run focused tests.",
|
||||
]
|
||||
);
|
||||
|
||||
@@ -188,7 +205,20 @@ stream_max_retries = 0
|
||||
"prompt: {prompt}\nrequest: {request}"
|
||||
);
|
||||
assert!(prompt.len() <= recap::RECAP_PROMPT_MAX_BYTES);
|
||||
assert!(prompt.contains("Assistant: Parser fix implemented."));
|
||||
assert!(prompt.contains("What should empty input do?"));
|
||||
assert!(prompt.contains("[... excerpted ...]"));
|
||||
assert_eq!(
|
||||
prompt
|
||||
.matches("Pending user request: Keep follow-up work queued.")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(request["text"]["format"]["type"], "json_schema");
|
||||
assert_eq!(
|
||||
request["text"]["format"]["schema"]["required"],
|
||||
serde_json::json!(["summary", "next_action"])
|
||||
);
|
||||
assert_eq!(request["tools"], serde_json::json!([]));
|
||||
|
||||
app_server.shutdown().await?;
|
||||
|
||||
Reference in new issue
Block a user