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:
Felipe Coury authored and copyberry committed 2026-09-12 18:16:17 +00:00
1 parent f16c2237a5
commit 8d3c6cc13d
9 files changed
+544 -141

No files matched your search

+192 -22
View File
@@ -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());