diff --git a/apps/maple-agent/app/locales/de/app.ftl b/apps/maple-agent/app/locales/de/app.ftl index 45b0efd50..fe13991d2 100644 --- a/apps/maple-agent/app/locales/de/app.ftl +++ b/apps/maple-agent/app/locales/de/app.ftl @@ -1610,6 +1610,11 @@ chat-turn-worked = Gearbeitet chat-turn-worked-seconds = { $seconds } s gearbeitet # $minutes is a whole number of minutes; $seconds is the rest, under 60. chat-turn-worked-minutes = { $minutes } min { $seconds } s gearbeitet +# $count is the number of files a turn changed. +chat-turn-files-changed = { $count -> + [one] { $count } Datei geändert + *[other] { $count } Dateien geändert + } # $count is the number of tool and thinking steps in one activity chunk. chat-activity-steps = { $count -> diff --git a/apps/maple-agent/app/locales/en/app.ftl b/apps/maple-agent/app/locales/en/app.ftl index 4529a0076..4ef5b859a 100644 --- a/apps/maple-agent/app/locales/en/app.ftl +++ b/apps/maple-agent/app/locales/en/app.ftl @@ -1610,6 +1610,11 @@ chat-turn-worked = Worked chat-turn-worked-seconds = Worked for { $seconds }s # $minutes is a whole number of minutes; $seconds is the rest, under 60. chat-turn-worked-minutes = Worked for { $minutes }m { $seconds }s +# $count is the number of files a turn changed. +chat-turn-files-changed = { $count -> + [one] { $count } file changed + *[other] { $count } files changed + } # $count is the number of tool and thinking steps in one activity chunk. chat-activity-steps = { $count -> diff --git a/apps/maple-agent/app/locales/es/app.ftl b/apps/maple-agent/app/locales/es/app.ftl index ea1bb0ec3..49724dedc 100644 --- a/apps/maple-agent/app/locales/es/app.ftl +++ b/apps/maple-agent/app/locales/es/app.ftl @@ -1497,6 +1497,11 @@ chat-turn-worked = Trabajó chat-turn-worked-seconds = Trabajó { $seconds } s # $minutes is a whole number of minutes; $seconds is the rest, under 60. chat-turn-worked-minutes = Trabajó { $minutes } min { $seconds } s +# $count is the number of files a turn changed. +chat-turn-files-changed = { $count -> + [one] { $count } archivo modificado + *[other] { $count } archivos modificados + } # $count is the number of tool and thinking steps in one activity chunk. chat-activity-steps = { $count -> diff --git a/apps/maple-agent/app/locales/ko/app.ftl b/apps/maple-agent/app/locales/ko/app.ftl index 2adfeaba8..cf791e32d 100644 --- a/apps/maple-agent/app/locales/ko/app.ftl +++ b/apps/maple-agent/app/locales/ko/app.ftl @@ -1556,6 +1556,8 @@ chat-turn-worked = 작업 완료 chat-turn-worked-seconds = { $seconds }초 동안 작업했어요 # $minutes is a whole number of minutes; $seconds is the rest, under 60. chat-turn-worked-minutes = { $minutes }분 { $seconds }초 동안 작업했어요 +# $count is the number of files a turn changed. +chat-turn-files-changed = 파일 { $count }개 변경됨 # $count is the number of tool and thinking steps in one activity chunk. chat-activity-steps = 단계 { $count }개 chat-settings = 설정 diff --git a/apps/maple-agent/app/src/ui/chat/changes.rs b/apps/maple-agent/app/src/ui/chat/changes.rs new file mode 100644 index 000000000..2821ca716 --- /dev/null +++ b/apps/maple-agent/app/src/ui/chat/changes.rs @@ -0,0 +1,423 @@ +//! The files a turn changed, listed in a card under its reply. +//! +//! A turn's edits and writes each say what they did on their own step. +//! Once the turn is over, the card adds them up by file, so what changed is +//! one glance away without opening the steps. A file's row opens the +//! changes the turn made to it. + +use std::cell::RefCell; +use std::collections::{BTreeSet, HashMap}; +use std::rc::Rc; +use std::sync::Arc; + +use gpui::{Context, Div, SharedString, div, prelude::*, px}; +use maple_agent::agent::AgentTimelineItem; + +use super::ChatScreen; +use super::step::{self, StepState}; +use super::transcript::diff_rows; +use super::turn::TurnRow; +use crate::ui::i18n::MessageCache; +use crate::ui::motion::{self, HoverBg as _}; +use crate::ui::theme; +use crate::ui::widgets; + +/// The +/- lines of an edit or a write, as its row derives them. +type DiffLines = Vec<(char, SharedString)>; + +/// One file a turn changed. +struct FileChange { + /// The path as the tool call gave it. + path: SharedString, + name: SharedString, + /// The folders before the name, with their trailing slash. + folder: SharedString, + /// "+6" and "−2". + counts: (SharedString, SharedString), + /// The +/- lines of every step that changed the file, in order. + lines: DiffLines, +} + +/// What a turn changed, file by file in the order it first touched them. +pub(super) struct TurnChanges { + files: Vec, + counts: (SharedString, SharedString), +} + +/// The card a reply row carries. +pub(super) struct ReplyChanges<'a> { + pub(super) changes: Rc, + /// The id of the turn's lead row, which the card's state is kept under. + pub(super) lead: &'a str, + /// The files whose changes show. + pub(super) open: Option<&'a BTreeSet>, +} + +/// The path an edit or a write call names. +fn changed_path(item: &AgentTimelineItem) -> Option<&str> { + let input = item.input.as_ref()?.as_object()?; + if !input.contains_key("edits") && !input.contains_key("content") { + return None; + } + input.get("path")?.as_str() +} + +fn counts(added: usize, removed: usize) -> (SharedString, SharedString) { + ( + format!("+{added}").into(), + format!("\u{2212}{removed}").into(), + ) +} + +impl TurnChanges { + /// Add up the edits and writes among a turn's `steps` that went + /// through, each with the +/- lines its row derived. `None` when the + /// turn changed nothing. + pub(super) fn of<'a>( + steps: impl Iterator)>, + ) -> Option { + struct Sum<'a> { + path: &'a str, + added: usize, + removed: usize, + lines: DiffLines, + } + let mut sums: Vec = Vec::new(); + for (item, lines) in steps { + // A call that failed or was refused changed nothing. + if StepState::of(item.status.as_deref()) != StepState::Done { + continue; + } + let Some(path) = changed_path(item) else { + continue; + }; + let index = sums + .iter() + .position(|sum| sum.path == path) + .unwrap_or_else(|| { + sums.push(Sum { + path, + added: 0, + removed: 0, + lines: Vec::new(), + }); + sums.len() - 1 + }); + let sum = &mut sums[index]; + // Counted from the whole edit; the lines shown stop at a cap. + let (added, removed) = super::transcript::diff_counts(item); + sum.added += added; + sum.removed += removed; + // All but the line that names the file, which the row does. + sum.lines.extend( + lines + .iter() + .filter(|(sign, _)| matches!(sign, '+' | '-')) + .cloned(), + ); + } + if sums.is_empty() { + return None; + } + let total = sums.iter().fold((0, 0), |(added, removed), sum| { + (added + sum.added, removed + sum.removed) + }); + Some(Self { + counts: counts(total.0, total.1), + files: sums + .into_iter() + .map(|sum| { + let name = sum.path.rfind(['/', '\\']).map_or(0, |at| at + 1); + FileChange { + path: sum.path.to_owned().into(), + name: sum.path[name..].to_owned().into(), + folder: sum.path[..name].to_owned().into(), + counts: counts(sum.added, sum.removed), + lines: sum.lines, + } + }) + .collect(), + }) + } + + /// Each file's path with its "+n" and "−n". + #[cfg(test)] + pub(super) fn files(&self) -> Vec<(&str, &str, &str)> { + self.files + .iter() + .map(|file| { + ( + file.path.as_ref(), + file.counts.0.as_ref(), + file.counts.1.as_ref(), + ) + }) + .collect() + } +} + +/// Each finished turn's changes, by the id of its lead row. An entry is +/// dropped when one of the turn's steps changes, and built again the next +/// time its card draws. +#[derive(Default)] +pub(super) struct ChangesCache(RefCell>>>); + +impl ChangesCache { + pub(super) fn clear(&self) { + self.0.borrow_mut().clear(); + } + + pub(super) fn forget(&self, lead: &str) { + self.0.borrow_mut().remove(lead); + } + + fn get( + &self, + lead: &str, + build: impl FnOnce() -> Option, + ) -> Option> { + if let Some(changes) = self.0.borrow().get(lead) { + return changes.clone(); + } + let changes = build().map(Rc::new); + self.0.borrow_mut().insert(lead.to_owned(), changes.clone()); + changes + } +} + +/// The card under a turn's reply. `reply` is the id of the row it sits on. +pub(super) fn render_changes( + card: &ReplyChanges, + reply: &str, + chat: &gpui::WeakEntity, + messages: &MessageCache, +) -> Div { + const ROW: gpui::Pixels = px(34.); + let rule = gpui::rgb(theme::border_subtle()); + let changes = &card.changes; + let mut body = div() + .debug_selector(|| "turn-changes".to_string()) + .mt_2() + .w_full() + .max_w(px(620.)) + .rounded(theme::RADIUS_MD) + .bg(gpui::rgb(theme::bg_tool_card())) + .border_1() + .border_color(rule) + .overflow_hidden() + .flex() + .flex_col() + .child( + div() + .h(ROW) + .px_3() + .flex() + .items_center() + .justify_between() + .gap_3() + .text_xs() + .text_color(gpui::rgb(theme::text_muted())) + .child(gpui::text!(messages.get( + "chat-turn-files-changed", + [("count", changes.files.len().into())], + ))) + .child(step::changed(&changes.counts)), + ); + for (index, file) in changes.files.iter().enumerate() { + let shown = card.open.is_some_and(|open| open.contains(&index)); + let (chat, reply, lead) = (chat.clone(), reply.to_owned(), card.lead.to_owned()); + body = body.child( + div() + .id(SharedString::from(format!( + "turn-change-{}-{index}", + card.lead + ))) + .debug_selector(|| "turn-change".to_string()) + .role(gpui::Role::DisclosureTriangle) + .aria_label(file.path.clone()) + .aria_expanded(shown) + .tab_index(0) + .on_key_down(ChatScreen::sidebar_button_key_down) + .focus_visible(widgets::focus_ring) + .h(ROW) + .px_3() + .flex() + .items_center() + .gap_2p5() + .border_t_1() + .border_color(rule) + .font_family(crate::assets::FONT_MONO) + .text_xs() + .cursor_pointer() + .child(motion::chevron( + SharedString::from(format!("turn-change-chevron-{}-{index}", card.lead)), + shown, + px(12.), + theme::text_muted(), + )) + .child( + div() + .flex_none() + .text_color(gpui::rgb(theme::text_primary())) + .child(gpui::text!(file.name.clone())), + ) + .child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_color(gpui::rgb(theme::text_muted())) + .child(gpui::text!(file.folder.clone())), + ) + .child(step::changed(&file.counts)) + .hover_bg(theme::overlay_hover()) + .on_click(move |_event, _window, cx: &mut gpui::App| { + chat.update(cx, |chat, cx| chat.toggle_change(&reply, &lead, index, cx)) + .ok(); + }), + ); + if shown { + body = body.child( + div() + .debug_selector(|| "turn-change-diff".to_string()) + .py_1() + .border_t_1() + .border_color(rule) + .bg(gpui::rgb(theme::bg_code_block())) + .child(diff_rows(&file.lines)), + ); + } + } + body +} + +impl ChatScreen { + /// The changes to list under the row at `reply`, with the lead of + /// their turn: the row is the reply that ends a turn, the turn is + /// over, and it changed files. + pub(super) fn changes_under(&self, reply: usize) -> Option<(usize, Rc)> { + let lead = self.turns.reply_of(reply)?; + if self.turn_runs(lead) { + return None; + } + let lead_id = &self.timeline.get(lead)?.id; + let changes = self.turn_changes.get(lead_id, || { + TurnChanges::of( + self.timeline[lead..reply] + .iter() + .enumerate() + // Only the calls that changed a file have their + // rows derived: a turn of commands derives none. + .filter(|(offset, item)| { + self.turns.row(lead + offset) != TurnRow::Plain + && StepState::of(item.status.as_deref()) == StepState::Done + && changed_path(item).is_some() + }) + .map(|(_, item)| { + let revision = self + .timeline_index + .get(&item.id) + .map_or(0, |(_, revision)| *revision); + (item, self.derived.get(item, revision).diff_lines.clone()) + }), + ) + })?; + Some((lead, changes)) + } + + /// Show or fold one file's changes in the card under the row `reply`. + pub(super) fn toggle_change( + &mut self, + reply: &str, + lead: &str, + file: usize, + cx: &mut Context, + ) { + let open = self.open_changes.entry(lead.to_owned()).or_default(); + if !open.remove(&file) { + open.insert(file); + } + if let Some(&(index, _)) = self.timeline_index.get(reply) { + self.list_state.remeasure_items(index..index + 1); + } + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn call(status: &str, input: serde_json::Value) -> AgentTimelineItem { + AgentTimelineItem { + label: None, + persisted: None, + live: None, + truncated: None, + revision: 0, + id: String::new(), + item_type: "tool".into(), + role: None, + title: None, + text: None, + status: Some(status.into()), + input: Some(input), + output: None, + created_ms: 0, + merge: "replace".into(), + } + } + + fn changes(calls: &[AgentTimelineItem]) -> Option { + TurnChanges::of(calls.iter().map(|call| { + ( + call, + Arc::new(super::super::transcript::diff_lines_for(call)), + ) + })) + } + + #[test] + fn a_turns_changes_add_up_by_file() { + let edit = |status: &str, path: &str, old: &str, new: &str| { + call( + status, + serde_json::json!({ "path": path, "edits": [{ "oldText": old, "newText": new }] }), + ) + }; + let turn = [ + edit("completed", "src/net/retry.rs", "a", "b\nc"), + call("completed", serde_json::json!({ "command": "cargo test" })), + call( + "completed", + serde_json::json!({ "path": "notes.md", "content": "one\ntwo\nthree" }), + ), + // A second edit of the same file joins the first. + edit("completed", "src/net/retry.rs", "d\ne", "f"), + // An edit that failed changed nothing. + edit("failed", "src/lib.rs", "x", "y"), + ]; + let changes = changes(&turn).expect("the turn changed files"); + assert_eq!( + changes.files(), + [ + ("src/net/retry.rs", "+3", "\u{2212}3"), + ("notes.md", "+3", "\u{2212}0"), + ] + ); + assert_eq!(changes.counts.0.as_ref(), "+6"); + assert_eq!(changes.counts.1.as_ref(), "\u{2212}3"); + assert_eq!(changes.files[0].name.as_ref(), "retry.rs"); + assert_eq!(changes.files[0].folder.as_ref(), "src/net/"); + assert_eq!(changes.files[1].folder.as_ref(), ""); + } + + #[test] + fn a_turn_that_only_ran_commands_changed_nothing() { + let turn = [call( + "completed", + serde_json::json!({ "command": "cargo test" }), + )]; + assert!(changes(&turn).is_none()); + } +} diff --git a/apps/maple-agent/app/src/ui/chat/mod.rs b/apps/maple-agent/app/src/ui/chat/mod.rs index 42ec3925e..0c36f6ef1 100644 --- a/apps/maple-agent/app/src/ui/chat/mod.rs +++ b/apps/maple-agent/app/src/ui/chat/mod.rs @@ -34,6 +34,7 @@ use crate::ui::titlebar; use crate::ui::widgets; mod cache; +mod changes; mod commands; mod composer; pub(crate) mod computers; @@ -233,6 +234,8 @@ struct TranscriptCtx<'a> { rail: step::Rail, /// For a tool call the user was asked to allow: where that stands. asked: Option, + /// For the reply that ends a turn: the files the turn changed. + changes: Option>, } /// Text-to-speech progress for one message. @@ -861,6 +864,14 @@ pub struct ChatScreen { /// What the user said to the permission requests answered in this /// view, by the id of the tool call each was about: allowed, or not. step_permissions: HashMap, + /// What each finished turn changed, built when its card first draws. + turn_changes: changes::ChangesCache, + /// The files whose changes show in a turn's card, by the turn's lead + /// item id. + open_changes: HashMap>, + /// The reply of the turn at the end, once that turn is over and the + /// row was measured with its card. + settled_reply: Option, /// Clocks of the runs this window saw start, by session id. run_clocks: HashMap, /// A repaint for a running turn's time is on its way. @@ -1706,6 +1717,9 @@ impl ChatScreen { toggled_chunks: HashSet::new(), turn_worked: HashMap::new(), step_permissions: HashMap::new(), + turn_changes: changes::ChangesCache::default(), + open_changes: HashMap::new(), + settled_reply: None, run_clocks: HashMap::new(), run_tick_pending: std::cell::Cell::new(false), question_selected: HashMap::new(), @@ -3498,6 +3512,7 @@ impl ChatScreen { self.pages.weights.clear(); self.bound_transcript_window(true); self.turns.rebuild(&self.timeline); + self.turn_changes.clear(); self.timeline_index = self .timeline .iter() @@ -3789,6 +3804,8 @@ impl ChatScreen { self.toggled_chunks.clear(); self.turn_worked.clear(); self.step_permissions.clear(); + self.turn_changes.clear(); + self.open_changes.clear(); if let Some(composer) = self.composer.clone() { composer.update(cx, |input, cx| input.reset_vim_context(cx)); } @@ -6430,9 +6447,15 @@ impl ChatScreen { motion::now(), self.list_state.is_following_tail(), ); + // A message from the user ends the turn before it, whose + // reply may now carry the card of what the turn changed. + let settled = self.turns.tail_reply().filter(|_| turn::starts_turn(&item)); self.turns.push(&item); self.timeline.push(item); self.list_state.splice(index..index, 1); + if let Some(reply) = settled { + self.list_state.remeasure_items(reply..reply + 1); + } // The step before a new one loses the gap under it, so // the rail joins them: its height changed too. if index > 0 @@ -6452,6 +6475,13 @@ impl ChatScreen { .timeline_revisions .entry(session_id.to_string()) .or_insert(0) += 1; + // A step that arrived or changed may change what its turn's card + // lists. + if self.turns.row(index) != turn::TurnRow::Plain + && let Some(lead) = self.turns.turn_of(index) + { + self.turn_changes.forget(&self.timeline[lead].id); + } let id = self.timeline[index].id.clone(); let anchor = self.scroll_anchor(); let count = self.timeline.len(); diff --git a/apps/maple-agent/app/src/ui/chat/paging.rs b/apps/maple-agent/app/src/ui/chat/paging.rs index 999c3cb76..0f4a7ce5b 100644 --- a/apps/maple-agent/app/src/ui/chat/paging.rs +++ b/apps/maple-agent/app/src/ui/chat/paging.rs @@ -266,6 +266,9 @@ impl ChatScreen { .retain(|id, _| self.timeline_index.contains_key(id)); self.step_permissions .retain(|id, _| self.timeline_index.contains_key(id)); + self.turn_changes.clear(); + self.open_changes + .retain(|id, _| self.timeline_index.contains_key(id)); self.markdown_cache.clear(); self.derived.clear(); self.messages = Default::default(); @@ -437,7 +440,11 @@ impl ChatScreen { this.markdown_cache.clear(); this.derived.clear(); this.messages = Default::default(); - this.remeasure_item(index); + // The whole input may change what its turn's + // card lists, and so the height of the reply + // that carries it. + this.turn_changes.clear(); + this.list_state.remeasure_items(index..this.timeline.len()); this.warm_markdown(cx); } } diff --git a/apps/maple-agent/app/src/ui/chat/transcript.rs b/apps/maple-agent/app/src/ui/chat/transcript.rs index 49d31bb03..7dac49de4 100644 --- a/apps/maple-agent/app/src/ui/chat/transcript.rs +++ b/apps/maple-agent/app/src/ui/chat/transcript.rs @@ -16,6 +16,7 @@ use maple_agent::agent::{ }; use super::cache::{MAX_DIFF_LINES, MarkdownKind}; +use super::changes; use super::speech::speak_message_button; use super::step::{self, StepState}; use super::turn::{self, TurnRow}; @@ -132,6 +133,14 @@ impl ChatScreen { } }) }, + changes: chat.changes_under(ix).map(|(lead, changes)| { + let lead = chat.timeline[lead].id.as_str(); + changes::ReplyChanges { + changes, + lead, + open: chat.open_changes.get(lead), + } + }), }; let expanded = tool_details != chat.toggled_tools.contains(&item.id); let revision = chat @@ -1352,6 +1361,9 @@ fn render_message(item: &AgentTimelineItem, revision: u64, transcript: &Transcri }) .child(timestamp_label(item, &group, transcript.messages)) })) + .children(transcript.changes.as_ref().map(|card| { + changes::render_changes(card, &item.id, transcript.chat, transcript.messages) + })) } } @@ -1830,20 +1842,25 @@ pub(super) fn diff_counts(item: &AgentTimelineItem) -> (usize, usize) { (added, removed) } -/// The +/- lines of an edit or write, coloured. +/// The +/- lines of an edit or write, coloured, in the box a step's +/// details show them in. fn render_diff(lines: &[(char, SharedString)]) -> Option
{ if lines.is_empty() { return None; } - let mut diff = div() - .flex() - .flex_col() - .mt_1() - .rounded(theme::RADIUS_SM) - .bg(gpui::rgb(theme::bg_code_block())) - .border_1() - .border_color(gpui::rgb(theme::border_subtle())) - .overflow_x_hidden(); + Some( + diff_rows(lines) + .mt_1() + .rounded(theme::RADIUS_SM) + .bg(gpui::rgb(theme::bg_code_block())) + .border_1() + .border_color(gpui::rgb(theme::border_subtle())), + ) +} + +/// One row per +/- line, each clipped to the width it has. +pub(super) fn diff_rows(lines: &[(char, SharedString)]) -> Div { + let mut diff = div().flex().flex_col().overflow_x_hidden(); for (sign, line) in lines { let color = match sign { '+' => theme::status_success(), @@ -1874,7 +1891,7 @@ fn render_diff(lines: &[(char, SharedString)]) -> Option
{ ), ); } - Some(diff) + diff } /// Title shown before the model summary arrives: just the tool label from @@ -3775,6 +3792,74 @@ mod motion_tests { }); } + #[gpui::test] + fn a_finished_turn_lists_what_it_changed_under_its_reply(cx: &mut TestAppContext) { + use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; + + let _clock = Clock::start(); + let (chat, cx) = pane(cx, 0); + chat.update(cx, |chat, cx| { + chat.replace_timeline(vec![user_item("ask", "Cap the wait")]); + chat.handle_service_event(run_event(AgentRunEvent::Started), cx); + for row in [ + AgentTimelineItem { + status: Some("completed".to_string()), + input: Some(serde_json::json!({ + "path": "src/net/retry.rs", + "edits": [{ + "oldText": "loop {", + "newText": "let deadline = now + MAX;\nloop {", + }], + })), + ..item("edit", "tool", None) + }, + item("reply", "message", Some("Done.")), + ] { + chat.handle_service_event(run_event(AgentRunEvent::TimelineItem(row)), cx); + } + }); + redraw(&chat, cx); + assert!( + cx.debug_bounds("turn-changes").is_none(), + "a turn still running has not finished changing things" + ); + + chat.update(cx, |chat, cx| { + chat.handle_service_event( + run_event(AgentRunEvent::Finished(AgentRunTerminal::Completed)), + cx, + ); + }); + // Past the reply's entrance, so its row has its full height. + motion::set_test_now(Some(motion::now() + motion::ENTER.settle * 2)); + redraw(&chat, cx); + let card = bounds(cx, "turn-changes"); + let reply = bounds(cx, "timeline-row-reply"); + assert!( + card.top() > reply.top() && card.bottom() <= reply.bottom(), + "the card sits in the reply's row, which grew to hold it: {card:?} in {reply:?}" + ); + assert!( + cx.debug_bounds("turn-change-diff").is_none(), + "a file's changes start folded" + ); + + let file = bounds(cx, "turn-change").center(); + cx.simulate_click(file, gpui::Modifiers::default()); + redraw(&chat, cx); + let diff = bounds(cx, "turn-change-diff"); + let opened = bounds(cx, "turn-changes"); + let reply = bounds(cx, "timeline-row-reply"); + assert!( + opened.size.height > card.size.height + && diff.top() > opened.top() + && diff.bottom() <= opened.bottom() + && opened.bottom() <= reply.bottom(), + "the file's changes open inside the card, and the row grows again: \ + {diff:?} in {opened:?} in {reply:?}" + ); + } + #[gpui::test] fn a_run_whose_rows_a_paged_back_view_missed_keeps_no_time(cx: &mut TestAppContext) { use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; diff --git a/apps/maple-agent/app/src/ui/chat/turn.rs b/apps/maple-agent/app/src/ui/chat/turn.rs index 2edfc6696..9a23abef4 100644 --- a/apps/maple-agent/app/src/ui/chat/turn.rs +++ b/apps/maple-agent/app/src/ui/chat/turn.rs @@ -113,10 +113,15 @@ pub(super) struct Turns { chunks: HashMap, /// First step of the latest user turn, kept stable for its clock. tail: Option, + /// The reply that ends a turn, by its row, with the turn's lead: the + /// last message from Maple after the turn's last step. + replies: HashMap, + /// The reply of the turn at the end, while no step has followed it. + tail_reply: Option, chunk: Option, } -fn starts_turn(item: &AgentTimelineItem) -> bool { +pub(super) fn starts_turn(item: &AgentTimelineItem) -> bool { item.item_type == "message" && item.role.as_deref() == Some("user") } @@ -173,6 +178,8 @@ impl Turns { self.chunks.clear(); self.chunk = None; self.tail = None; + self.replies.clear(); + self.tail_reply = None; for item in timeline { self.push(item); } @@ -185,6 +192,7 @@ impl Turns { let row = if starts_turn { self.tail = None; self.chunk = None; + self.tail_reply = None; TurnRow::Plain } else if !is_step { // Hidden plans and empty streamed messages do not separate @@ -192,16 +200,33 @@ impl Turns { if breaks_chunk { self.chunk = None; } + // What Maple says after the turn's steps is its reply, until + // it says more or takes another step. A message with nothing + // in it yet draws no row, so it cannot carry the card. + if let Some(lead) = self.tail + && breaks_chunk + && item.item_type == "message" + { + if let Some(earlier) = self.tail_reply.replace(index) { + self.replies.remove(&earlier); + } + self.replies.insert(index, lead); + } TurnRow::Plain - } else if let Some(lead) = self.chunk { - TurnRow::Step(lead) } else { - self.chunk = Some(index); - if self.tail.is_none() { - self.tail = Some(index); - TurnRow::Lead + if let Some(reply) = self.tail_reply.take() { + self.replies.remove(&reply); + } + if let Some(lead) = self.chunk { + TurnRow::Step(lead) } else { - TurnRow::Chunk + self.chunk = Some(index); + if self.tail.is_none() { + self.tail = Some(index); + TurnRow::Lead + } else { + TurnRow::Chunk + } } }; if let Some(lead) = row.lead(index) { @@ -220,6 +245,29 @@ impl Turns { self.tail } + /// The lead of the turn the row at `row` is the reply of. + pub(super) fn reply_of(&self, row: usize) -> Option { + self.replies.get(&row).copied() + } + + /// The reply of the turn at the end, if it has one yet. + pub(super) fn tail_reply(&self) -> Option { + self.tail_reply + } + + /// The lead of the turn the step at `index` belongs to. A chunk's own + /// lead is not its turn's unless it is the turn's first. + pub(super) fn turn_of(&self, index: usize) -> Option { + match self.tail { + Some(tail) if index >= tail => Some(tail), + _ => self + .rows + .get(..=index)? + .iter() + .rposition(|row| *row == TurnRow::Lead), + } + } + pub(super) fn chunk(&self, lead: usize) -> Option<&Chunk> { self.chunks.get(&lead) } @@ -797,6 +845,16 @@ impl ChatScreen { /// the turn it was working on keeps how long it worked. A run that /// waits on the user holds its time. pub(super) fn sync_run_clocks(&mut self) { + // Once its turn is over, a reply may carry the card of what the + // turn changed: that row is taller from then on, so measure it + // again the first time it is seen settled. + let running = self.turns.tail().is_some_and(|lead| self.turn_runs(lead)); + let settled = self.turns.tail_reply().filter(|_| !running); + if std::mem::replace(&mut self.settled_reply, settled) != settled + && let Some(reply) = settled + { + self.list_state.remeasure_items(reply..reply + 1); + } if self.run_clocks.is_empty() { return; } @@ -850,6 +908,10 @@ impl ChatScreen { if let Some(allowed) = self.step_permissions.remove(old) { self.step_permissions.insert(new.to_owned(), allowed); } + self.turn_changes.forget(old); + if let Some(open) = self.open_changes.remove(old) { + self.open_changes.insert(new.to_owned(), open); + } } /// The permission request on screen, if the question card shows one. @@ -1031,6 +1093,7 @@ mod tests { } assert_eq!(live.rows, snapshot.rows); assert_eq!(live.tail, snapshot.tail); + assert_eq!(live.replies, snapshot.replies); // A window that starts mid-turn leads with its first loaded step. assert_eq!(snapshot.row(0), TurnRow::Lead); // A new message from the user starts a turn with no line yet. @@ -1038,6 +1101,70 @@ mod tests { assert_eq!(live.tail(), None); } + #[test] + fn a_later_chunk_belongs_to_its_turns_first_step() { + let said = || AgentTimelineItem { + text: Some("Checking the result.".into()), + ..item("message", Some("assistant")) + }; + let mut turns = Turns::default(); + turns.rebuild(&[ + item("message", Some("user")), + item("tool", None), + said(), + item("tool", None), + item("message", Some("user")), + item("tool", None), + said(), + item("tool", None), + ]); + assert_eq!(turns.row(3), TurnRow::Chunk); + assert_eq!(turns.turn_of(3), Some(1)); + assert_eq!(turns.turn_of(7), Some(5)); + // The reply after a later chunk still ends the whole turn. + turns.push(&said()); + assert_eq!(turns.reply_of(8), Some(5)); + } + + #[test] + fn a_turns_reply_is_what_maple_says_after_its_last_step() { + let said = || AgentTimelineItem { + text: Some("Done.".into()), + ..item("message", Some("assistant")) + }; + let mut turns = Turns::default(); + turns.rebuild(&[ + item("message", Some("user")), + // Said before any step: not a reply to carry what changed. + said(), + item("tool", None), + said(), + ]); + assert_eq!(turns.reply_of(1), None); + assert_eq!(turns.reply_of(3), Some(2)); + // Another step: the turn is not over, and what was said is no + // longer its last word. + turns.push(&item("tool", None)); + assert_eq!(turns.reply_of(3), None); + turns.push(&said()); + assert_eq!(turns.reply_of(5), Some(2)); + assert_eq!(turns.tail_reply(), Some(5)); + // A plain turn has no steps, so nothing to list. + turns.push(&item("message", Some("user"))); + turns.push(&said()); + assert_eq!(turns.reply_of(7), None); + // A message that is still empty draws nothing, so the reply before + // it keeps the card. + let mut turns = Turns::default(); + turns.rebuild(&[ + item("tool", None), + said(), + item("message", Some("assistant")), + ]); + assert_eq!(turns.reply_of(1), Some(0)); + assert_eq!(turns.tail_reply(), Some(1)); + } + #[test] fn hidden_plans_do_not_split_activity_and_status_updates_stay_in_their_chunk() { let done = AgentTimelineItem { diff --git a/apps/maple-agent/app/translation-revisions/de.txt b/apps/maple-agent/app/translation-revisions/de.txt index aa3dbded6..9100aff67 100644 --- a/apps/maple-agent/app/translation-revisions/de.txt +++ b/apps/maple-agent/app/translation-revisions/de.txt @@ -400,6 +400,7 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-files-changed 708debceb2de53ea chat-turn-waiting 130514d0bacc91a7 chat-turn-worked 5dcfb6d76e519bf9 chat-turn-worked-minutes 9b13b6f2c1f967be diff --git a/apps/maple-agent/app/translation-revisions/es.txt b/apps/maple-agent/app/translation-revisions/es.txt index aa3dbded6..9100aff67 100644 --- a/apps/maple-agent/app/translation-revisions/es.txt +++ b/apps/maple-agent/app/translation-revisions/es.txt @@ -400,6 +400,7 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-files-changed 708debceb2de53ea chat-turn-waiting 130514d0bacc91a7 chat-turn-worked 5dcfb6d76e519bf9 chat-turn-worked-minutes 9b13b6f2c1f967be diff --git a/apps/maple-agent/app/translation-revisions/ko.txt b/apps/maple-agent/app/translation-revisions/ko.txt index aa3dbded6..9100aff67 100644 --- a/apps/maple-agent/app/translation-revisions/ko.txt +++ b/apps/maple-agent/app/translation-revisions/ko.txt @@ -400,6 +400,7 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-files-changed 708debceb2de53ea chat-turn-waiting 130514d0bacc91a7 chat-turn-worked 5dcfb6d76e519bf9 chat-turn-worked-minutes 9b13b6f2c1f967be