diff --git a/apps/maple-agent/app/assets/icons/file-text.svg b/apps/maple-agent/app/assets/icons/file-text.svg new file mode 100644 index 000000000..3305a11d9 --- /dev/null +++ b/apps/maple-agent/app/assets/icons/file-text.svg @@ -0,0 +1 @@ + diff --git a/apps/maple-agent/app/locales/de/app.ftl b/apps/maple-agent/app/locales/de/app.ftl index 3ed977574..1bf9b24a0 100644 --- a/apps/maple-agent/app/locales/de/app.ftl +++ b/apps/maple-agent/app/locales/de/app.ftl @@ -1607,6 +1607,12 @@ 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 tool and thinking steps in one activity chunk. +chat-activity-steps = + { $count -> + [one] { $count } Schritt + *[other] { $count } Schritte + } chat-settings = Einstellungen chat-usage = Nutzung chat-usage-unavailable = Nutzung nicht verfügbar @@ -1721,7 +1727,6 @@ chat-thinking-save-failed = Denkstufe konnte nicht gespeichert werden: { $error chat-composer-placeholder = Bitte Maple, in diesem Ordner zu arbeiten… chat-side-thread-placeholder = Stelle eine Nebenfrage (Esc verlässt das Gespräch)… chat-queue-edit-placeholder = Bearbeite die eingereihte Nachricht und sende sie, um ihren Platz zu behalten. Escape verwirft sie. -chat-status-completed = abgeschlossen chat-status-failed = fehlgeschlagen chat-status-stopped = gestoppt chat-status-running = läuft diff --git a/apps/maple-agent/app/locales/en/app.ftl b/apps/maple-agent/app/locales/en/app.ftl index b527b2ead..8b63c35b4 100644 --- a/apps/maple-agent/app/locales/en/app.ftl +++ b/apps/maple-agent/app/locales/en/app.ftl @@ -1607,6 +1607,12 @@ 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 tool and thinking steps in one activity chunk. +chat-activity-steps = + { $count -> + [one] { $count } step + *[other] { $count } steps + } chat-settings = Settings chat-usage = Usage chat-usage-unavailable = Usage unavailable @@ -1721,7 +1727,6 @@ chat-thinking-save-failed = Could not save the thinking level: { $error } chat-composer-placeholder = Ask Maple to work in this folder… chat-side-thread-placeholder = Ask a side question (Esc to leave the thread)… chat-queue-edit-placeholder = Edit the queued message, then send to keep its place. Escape discards. -chat-status-completed = completed chat-status-failed = failed chat-status-stopped = stopped chat-status-running = running diff --git a/apps/maple-agent/app/locales/es/app.ftl b/apps/maple-agent/app/locales/es/app.ftl index 54caa6549..3ef024da4 100644 --- a/apps/maple-agent/app/locales/es/app.ftl +++ b/apps/maple-agent/app/locales/es/app.ftl @@ -1494,6 +1494,12 @@ 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 tool and thinking steps in one activity chunk. +chat-activity-steps = + { $count -> + [one] { $count } paso + *[other] { $count } pasos + } chat-settings = Configuración chat-usage = Uso chat-usage-unavailable = Uso no disponible @@ -1598,7 +1604,6 @@ chat-thinking-save-failed = No se pudo guardar el nivel de razonamiento: { $erro chat-composer-placeholder = Pídele a Maple que trabaje en esta carpeta… chat-side-thread-placeholder = Haz una pregunta aparte (Esc para salir del hilo)… chat-queue-edit-placeholder = Edita el mensaje en cola y envíalo para conservar su lugar. Esc descarta los cambios. -chat-status-completed = completado chat-status-failed = falló chat-status-stopped = detenido chat-status-running = en ejecución diff --git a/apps/maple-agent/app/locales/ko/app.ftl b/apps/maple-agent/app/locales/ko/app.ftl index 9278b72a7..290cbebbd 100644 --- a/apps/maple-agent/app/locales/ko/app.ftl +++ b/apps/maple-agent/app/locales/ko/app.ftl @@ -1553,6 +1553,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 tool and thinking steps in one activity chunk. +chat-activity-steps = 단계 { $count }개 chat-settings = 설정 chat-usage = 사용량 chat-usage-unavailable = 사용량을 확인할 수 없음 @@ -1667,7 +1669,6 @@ chat-thinking-save-failed = 사고 수준을 저장하지 못했어요: { $error chat-composer-placeholder = 이 폴더에서 할 작업을 Maple에 요청하세요… chat-side-thread-placeholder = 곁가지 질문을 입력하세요(Esc로 스레드 나가기)… chat-queue-edit-placeholder = 대기 중인 메시지를 편집한 뒤 보내면 순서가 유지돼요. Escape를 누르면 취소돼요. -chat-status-completed = 완료됨 chat-status-failed = 실패 chat-status-stopped = 중지됨 chat-status-running = 실행 중 diff --git a/apps/maple-agent/app/src/assets.rs b/apps/maple-agent/app/src/assets.rs index 2f07bc322..9fc5c7c15 100644 --- a/apps/maple-agent/app/src/assets.rs +++ b/apps/maple-agent/app/src/assets.rs @@ -66,6 +66,7 @@ assets!( "icons/effort-burst.svg", "icons/ellipsis.svg", "icons/external-link.svg", + "icons/file-text.svg", "icons/folder-open.svg", "icons/folder-plus.svg", "icons/folder.svg", diff --git a/apps/maple-agent/app/src/ui/chat/cache.rs b/apps/maple-agent/app/src/ui/chat/cache.rs index 92d658626..002fa66cd 100644 --- a/apps/maple-agent/app/src/ui/chat/cache.rs +++ b/apps/maple-agent/app/src/ui/chat/cache.rs @@ -15,7 +15,7 @@ use maple_agent::agent::{AgentTimelineItem, ExternalAgentActivity}; use super::ChatScreen; use super::transcript::{ - PlanEntry, diff_lines_for, external_agent_activity, plan_entries, tool_input_line, + PlanEntry, diff_counts, diff_lines_for, external_agent_activity, plan_entries, tool_input_line, tool_output_markdown, }; use crate::ui::markdown; @@ -270,6 +270,11 @@ pub(super) struct ItemDerived { pub(super) input_line: Option, /// +/- lines of an edit or write tool, capped at `MAX_DIFF_LINES`. pub(super) diff_lines: Arc>, + /// Lines that edit or write adds and removes, as "+12" and "−3". + pub(super) changed: Option<(SharedString, SharedString)>, + /// What a tool call acts on: the command, path or query the host put + /// in its label. + pub(super) acted_on: Option, /// What an external agent (Codex) did, for the row of the tool call /// that ran it. pub(super) external_agent: Option>, @@ -282,6 +287,8 @@ pub(super) const MAX_DIFF_LINES: usize = 200; impl ItemDerived { fn build(item: &AgentTimelineItem) -> Self { let output_text = tool_output_markdown(item).map(SharedString::from); + // Counted from the whole input: the lines shown stop at a cap. + let (added, removed) = diff_counts(item); Self { text: SharedString::from(item.text.clone().unwrap_or_default()), attachments: super::transcript::attachment_metadata(item) @@ -295,6 +302,19 @@ impl ItemDerived { .collect(), output_text, input_line: tool_input_line(item).map(SharedString::from), + changed: (added + removed > 0).then(|| { + ( + format!("+{added}").into(), + format!("\u{2212}{removed}").into(), + ) + }), + acted_on: item + .label + .as_ref() + // A skill's name is already its row's title. + .filter(|label| label.kind == "tool" && label.name.as_deref() != Some("load_skill")) + .and_then(|label| label.detail.clone()) + .map(SharedString::from), diff_lines: Arc::new(diff_lines_for(item)), external_agent: external_agent_activity(item).map(Arc::new), plan: plan_entries(item), diff --git a/apps/maple-agent/app/src/ui/chat/mod.rs b/apps/maple-agent/app/src/ui/chat/mod.rs index 2dbf9527d..81fd65db2 100644 --- a/apps/maple-agent/app/src/ui/chat/mod.rs +++ b/apps/maple-agent/app/src/ui/chat/mod.rs @@ -50,6 +50,7 @@ mod sending; mod sidebar; mod speech; mod staging; +mod step; mod summaries; #[cfg(test)] mod tests; @@ -227,6 +228,9 @@ struct TranscriptCtx<'a> { /// How far the row's just-opened details are through fading in; 1 at /// rest. reveal: f32, + /// For a step: whether the thread's rail runs on to the steps drawn + /// right above and below it. + rail: step::Rail, } /// Text-to-speech progress for one message. @@ -847,9 +851,8 @@ pub struct ChatScreen { toggled_tools: HashSet, /// Each row's place in its turn, rebuilt or extended with `timeline`. turns: turn::Turns, - /// Lead item ids of turns whose line was clicked; membership inverts - /// the `tool_details` default for whether that turn's steps show. - toggled_turns: HashSet, + /// Chunk lead ids whose disclosure differs from `tool_details`. + toggled_chunks: HashSet, /// How long finished turns worked, by lead item id. Only turns this /// window timed have one. turn_worked: HashMap, @@ -1695,7 +1698,7 @@ impl ChatScreen { loading_since: None, toggled_tools: HashSet::new(), turns: turn::Turns::default(), - toggled_turns: HashSet::new(), + toggled_chunks: HashSet::new(), turn_worked: HashMap::new(), run_clocks: HashMap::new(), run_tick_pending: std::cell::Cell::new(false), @@ -3777,7 +3780,7 @@ impl ChatScreen { self.attachment_queue.clear(); self.attachment_viewport = 0..0; self.toggled_tools.clear(); - self.toggled_turns.clear(); + self.toggled_chunks.clear(); self.turn_worked.clear(); if let Some(composer) = self.composer.clone() { composer.update(cx, |input, cx| input.reset_vim_context(cx)); @@ -6355,6 +6358,7 @@ impl ChatScreen { } = item; let existing = &mut self.timeline[index]; let part = turn::part(existing); + let step_before = turn::step_info(existing); existing.revision = incoming_revision; if let Some(label) = incoming_label { match &mut existing.label { @@ -6390,11 +6394,17 @@ impl ChatScreen { existing.output = incoming_output.or_else(|| existing.output.take()); existing.merge = incoming_merge; } - // A row that became a step, or stopped being one, moves - // every row after it to another place in its turn. if turn::part(&self.timeline[index]) != part { self.turns.rebuild(&self.timeline); - self.list_state.remeasure_items(index..self.timeline.len()); + // A changed boundary can merge or split an earlier + // header. Remeasure without moving the scroll anchor. + self.list_state.remeasure_items(0..self.timeline.len()); + } else if let Some(lead) = self.turns.update_step( + index, + step_before, + turn::step_info(&self.timeline[index]), + ) { + self.list_state.remeasure_items(lead..lead + 1); } index } @@ -6409,6 +6419,17 @@ impl ChatScreen { self.turns.push(&item); self.timeline.push(item); self.list_state.splice(index..index, 1); + // The step before a new one loses the gap under it, so + // the rail joins them: its height changed too. + if index > 0 + && matches!(self.turns.row(index), turn::TurnRow::Step(_)) + && self.turns.row(index - 1) != turn::TurnRow::Plain + { + self.list_state.remeasure_items(index - 1..index); + } + if let turn::TurnRow::Step(lead) = self.turns.row(index) { + self.list_state.remeasure_items(lead..lead + 1); + } self.time_arrival(session_id, index); index } diff --git a/apps/maple-agent/app/src/ui/chat/navigation.rs b/apps/maple-agent/app/src/ui/chat/navigation.rs index e09ba6082..25c138a07 100644 --- a/apps/maple-agent/app/src/ui/chat/navigation.rs +++ b/apps/maple-agent/app/src/ui/chat/navigation.rs @@ -661,9 +661,9 @@ impl ChatScreen { let Some(&(index, _)) = self.timeline_index.get(&item_id) else { return; }; - // On a turn's first step the selection is the turn's line. - if self.turns.row(index) == TurnRow::Lead { - self.toggle_turn(&item_id, cx); + // A chunk's first row selects its disclosure header. + if matches!(self.turns.row(index), TurnRow::Lead | TurnRow::Chunk) { + self.toggle_chunk(&item_id, cx); return; } let Some(item) = self.timeline.get(index) else { @@ -710,13 +710,13 @@ impl ChatScreen { return; } let current = self.tool_details != self.toggled_tools.contains(item_id); - // A turn's first step sits under the turn's line: the line opens - // before the step's details do, and folds after them. - if self.turns.row(index) == TurnRow::Lead - && self.turn_open(index) != expanded + // Open the chunk before its first step's details, and fold it + // after those details have closed. + if matches!(self.turns.row(index), TurnRow::Lead | TurnRow::Chunk) + && self.chunk_open(index) != expanded && (expanded || !current) { - self.toggle_turn(item_id, cx); + self.toggle_chunk(item_id, cx); return; } if current != expanded { @@ -803,18 +803,16 @@ impl ChatScreen { .collect() } - /// Whether the selection can rest on the row at `index`. A step under - /// a folded line draws nothing, and a turn's first step always draws - /// the line. + /// A folded chunk keeps its header navigable and hides its later steps. fn timeline_row_navigable(&self, index: usize, item: &AgentTimelineItem) -> bool { match self.turns.row(index) { - TurnRow::Lead => true, - TurnRow::Step(lead) => self.turn_open(lead) && timeline_item_is_navigable(item), + TurnRow::Lead | TurnRow::Chunk => true, + TurnRow::Step(lead) => self.chunk_open(lead) && timeline_item_is_navigable(item), TurnRow::Plain => timeline_item_is_navigable(item), } } - /// A turn folded: a selection on one of its steps moves to its line. + /// Folding a chunk moves a hidden selection to its header. pub(super) fn keep_application_selection_shown(&mut self, lead: usize) { if !self.application_vim_enabled { return; @@ -1228,7 +1226,7 @@ impl ChatScreen { } } -fn timeline_item_is_navigable(item: &AgentTimelineItem) -> bool { +pub(super) fn timeline_item_is_navigable(item: &AgentTimelineItem) -> bool { if item.item_type == "internal" { return false; } diff --git a/apps/maple-agent/app/src/ui/chat/paging.rs b/apps/maple-agent/app/src/ui/chat/paging.rs index 5b2f9f031..b4d6c308b 100644 --- a/apps/maple-agent/app/src/ui/chat/paging.rs +++ b/apps/maple-agent/app/src/ui/chat/paging.rs @@ -260,7 +260,7 @@ impl ChatScreen { .map(|(i, item)| (item.id.clone(), (i, 0))) .collect(); self.turns.rebuild(&self.timeline); - self.toggled_turns + self.toggled_chunks .retain(|id| self.timeline_index.contains_key(id)); self.turn_worked .retain(|id, _| self.timeline_index.contains_key(id)); diff --git a/apps/maple-agent/app/src/ui/chat/step.rs b/apps/maple-agent/app/src/ui/chat/step.rs new file mode 100644 index 000000000..fdcfbb081 --- /dev/null +++ b/apps/maple-agent/app/src/ui/chat/step.rs @@ -0,0 +1,203 @@ +//! A turn's steps, drawn as a thread under the turn's line: each thinking +//! row and tool call is a node on a rail, with a one-line header that opens +//! its details under it. + +use gpui::{AnyElement, Div, Pixels, SharedString, Stateful, div, prelude::*, px}; +use maple_agent::agent::AgentTimelineItem; + +use crate::ui::icons::icon; +use crate::ui::theme; + +/// Width of the column the nodes and the rail sit in. The mark on the +/// turn's line is centred in the same column. +pub(super) const NODE: Pixels = px(22.); + +/// From a step's top to the centre of its node, where the rail meets it. +const NODE_CENTRE: Pixels = px(16.); + +/// How a step reads at a glance. Only the turn's line animates: a step is +/// dim until it has run and inked once it has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum StepState { + Running, + Done, + Failed, + Stopped, +} + +impl StepState { + pub(super) fn of(status: Option<&str>) -> Self { + match status { + Some("completed") => Self::Done, + Some("failed" | "error") => Self::Failed, + Some("cancelled") => Self::Stopped, + _ => Self::Running, + } + } + + /// Colour of the step's title. + pub(super) fn ink(self) -> u32 { + match self { + Self::Done | Self::Failed => theme::text_primary(), + Self::Running | Self::Stopped => theme::text_muted(), + } + } +} + +/// Whether the rail runs on from a step's node to the step drawn right +/// above it, and to the one right below. +pub(super) type Rail = (bool, bool); + +/// The icon on a tool call's node, by what the tool does. +pub(super) fn tool_icon(item: &AgentTimelineItem) -> &'static str { + let name = item + .label + .as_ref() + .filter(|label| label.kind == "tool") + .and_then(|label| label.name.as_deref()); + match name { + Some("bash" | "powershell" | "shell") => "terminal", + Some("read" | "read_file") => "file-text", + Some("list_files" | "glob") => "folder", + Some("grep") => "search", + Some( + "edit" + | "write" + | "write_file" + | "text_editor" + | "str_replace_editor" + | "str_replace_based_edit_tool", + ) => "pencil", + Some("web_search") => "globe", + Some("load_skill") => "puzzle", + Some( + "agent_start" | "agent_send" | "agent_status" | "agent_cancel" | "list_agent_providers", + ) => "users", + _ => "wrench", + } +} + +/// One step: its node on the rail, then `header` and, when it is open, +/// `details` under it. +pub(super) fn step( + icon_name: &'static str, + state: StepState, + rail: Rail, + header: impl IntoElement, + details: Option, +) -> Div { + let line = gpui::rgb(theme::border()); + let glyph = match state { + StepState::Done => theme::text_secondary(), + StepState::Failed => theme::status_error(), + StepState::Running | StepState::Stopped => theme::text_muted(), + }; + let segment = || div().absolute().left(px(10.)).w(px(1.)).bg(line); + div() + .flex() + .gap_3() + .child( + // The column is as tall as the step, so the rail reaches the + // next step's without a gap. + div() + .relative() + .flex_none() + .w(NODE) + .pt(px(5.)) + .when(rail.0, |column| { + column.child(segment().top_0().h(NODE_CENTRE)) + }) + .when(rail.1, |column| { + column.child(segment().top(NODE_CENTRE).bottom_0()) + }) + .child( + // Filled with the transcript's colour, so the rail + // stops at the node's edge. + div() + .debug_selector(|| "step-node".to_string()) + .relative() + .size(NODE) + .rounded_full() + .bg(gpui::rgb(theme::bg_app())) + .border_1() + .border_color(line) + .flex() + .items_center() + .justify_center() + .child(icon(icon_name, px(12.), glyph).opacity( + if state == StepState::Running { + 0.45 + } else { + 1. + }, + )), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .py_1() + .flex() + .flex_col() + .items_start() + .child(header) + .children(details.map(|details| div().w_full().pt_1().pb_1().child(details))), + ) +} + +/// The line of a step that opens its details: as wide as what it says, +/// with a hover plate that reaches a little past it on both sides. +pub(super) fn step_header(id: SharedString) -> Stateful
{ + div() + .id(id) + .max_w_full() + .min_h(px(24.)) + .ml(px(-8.)) + .px_2() + .flex() + .items_center() + .gap_2p5() + .rounded(theme::RADIUS_SM) + .text_sm() +} + +/// What a tool call acts on, beside its title: a command, a path, a query. +pub(super) fn chip(text: SharedString) -> Div { + div() + .debug_selector(|| "step-chip".to_string()) + .min_w_0() + .max_w(px(440.)) + .px_2() + .py(px(2.)) + .rounded(theme::RADIUS_SM) + .bg(theme::overlay_hover()) + .font_family(crate::assets::FONT_MONO) + .font_weight(gpui::FontWeight::NORMAL) + .text_xs() + .text_color(gpui::rgb(theme::text_secondary())) + .truncate() + .child(gpui::text!(text)) +} + +/// The lines an edit adds and removes. +pub(super) fn changed((added, removed): &(SharedString, SharedString)) -> Div { + div() + .debug_selector(|| "step-changed".to_string()) + .flex_none() + .flex() + .gap_1p5() + .font_family(crate::assets::FONT_MONO) + .font_weight(gpui::FontWeight::NORMAL) + .text_xs() + .child( + div() + .text_color(gpui::rgb(theme::status_success())) + .child(gpui::text!(added.clone())), + ) + .child( + div() + .text_color(gpui::rgb(theme::status_error())) + .child(gpui::text!(removed.clone())), + ) +} diff --git a/apps/maple-agent/app/src/ui/chat/tests.rs b/apps/maple-agent/app/src/ui/chat/tests.rs index 1f4873aeb..aa66eff8a 100644 --- a/apps/maple-agent/app/src/ui/chat/tests.rs +++ b/apps/maple-agent/app/src/ui/chat/tests.rs @@ -9,7 +9,7 @@ mod state_tests { use crate::ui::chat::composer::SideThreadTurn; use crate::ui::chat::computers::ProjectTarget; use crate::ui::chat::sidebar::{RenameTarget, SidebarEvent, TaskMove, root_display_name}; - use crate::ui::chat::transcript::{diff_lines_for, tool_label_title}; + use crate::ui::chat::transcript::{diff_counts, diff_lines_for, tool_label_title}; use crate::ui::chat::*; use gpui::{Context, TestAppContext}; use maple_agent::agent::{ @@ -6144,6 +6144,31 @@ mod state_tests { assert_eq!(lines[1], ('+', SharedString::from("0"))); } + /// The counts on a step come from the whole edit, not from the lines + /// the display keeps. + #[test] + fn test_changed_line_counts_are_not_cut_at_the_display_cap() { + let lines = |count: usize| { + (0..count) + .map(|n| n.to_string()) + .collect::>() + .join("\n") + }; + let mut write = item("write", "tool", None); + write.input = Some(serde_json::json!({ "path": "big.txt", "content": lines(1000) })); + assert_eq!(diff_counts(&write), (1000, 0)); + + let mut edit = item("edit", "tool", None); + edit.input = Some(serde_json::json!({ + "path": "big.txt", + "edits": [ + { "oldText": lines(300), "newText": lines(2) }, + { "oldText": "one", "newText": "one\ntwo" }, + ], + })); + assert_eq!(diff_counts(&edit), (4, 301)); + } + #[test] fn test_markdown_cache_keys_on_revision() { // Unattached: every parse is inline. @@ -12715,81 +12740,263 @@ mod state_tests { }); } - /// To the keyboard a folded turn is one row, its line. `l` shows the - /// steps, which then take the selection one by one, and `h` on the - /// line folds them again. + /// Each activity chunk is a keyboard row; assistant messages between + /// chunks remain readable regardless of either disclosure's state. #[gpui::test] - fn test_application_vim_opens_a_turn_from_its_line(cx: &mut TestAppContext) { - struct ChatHost { - chat: Entity, - } - impl Render for ChatHost { - fn render( - &mut self, - _window: &mut Window, - _cx: &mut Context, - ) -> impl IntoElement { - div().w(px(1200.)).h(px(800.)).child(self.chat.clone()) - } - } - - cx.executor().allow_parking(); - let chat = cx.new(|cx| { - let _guard = SETTINGS_LOCK.lock(); - let backend = std::sync::Arc::new( - crate::backend::AgentBackend::for_test( - "http://127.0.0.1:9".to_string(), - String::new(), - ) - .expect("backend"), - ); - crate::desktop::register_key_bindings(cx); - let mut chat = ChatScreen::new_inner_for_test(backend, "user".to_string(), cx); - chat.selected_session = Some("s1".to_string()); - chat.application_vim_enabled = true; - chat.application_focus = Some(cx.focus_handle()); - chat.screen_focus_pending = true; - chat.booting = false; + fn test_application_vim_opens_chunks_independently_from_their_lines(cx: &mut TestAppContext) { + cx.update(|cx| cx.set_reduce_motion(true)); + let (chat, cx) = chat_window(cx, |chat, cx| { + chat.set_application_vim_enabled(false, cx); + chat.tool_details = false; chat.replace_timeline(vec![ user_item("u1", "question"), - item("call", "tool", None), + AgentTimelineItem { + input: Some(serde_json::json!({"command": "ls"})), + ..item("call", "tool", None) + }, item("thought", "thinking", Some("reasoning")), - item("a1", "message", Some("answer")), + item("a1", "message", Some("Interim answer")), + item("later", "tool", None), + item("later-thought", "thinking", Some("more reasoning")), + item("a2", "message", Some("Final answer")), ]); - chat + chat.set_application_vim_enabled(true, cx); }); - let (_host, cx) = cx.add_window_view(|_window, _cx| ChatHost { chat: chat.clone() }); - cx.simulate_resize(gpui::size(px(1200.), px(800.))); let rows = |cx: &mut gpui::VisualTestContext| { cx.update(|_window, app| chat.read(app).navigable_timeline_ids()) }; let selected = |cx: &mut gpui::VisualTestContext| { cx.update(|_window, app| chat.read(app).selected_transcript_id().map(str::to_owned)) }; + let messages_shown = |cx: &mut gpui::VisualTestContext| { + cx.run_until_parked(); + for id in ["timeline-row-a1", "timeline-row-a2"] { + assert!(cx.debug_bounds(id).is_some(), "{id} stays visible"); + } + }; - assert_eq!(rows(cx), ["u1", "call", "a1"], "folded steps are skipped"); + assert_eq!(rows(cx), ["u1", "call", "a1", "later", "a2"]); + assert!(cx.debug_bounds("tool-card").is_none()); + messages_shown(cx); cx.simulate_keystrokes("g g j l"); - assert_eq!(rows(cx), ["u1", "call", "thought", "a1"]); + assert_eq!(rows(cx), ["u1", "call", "thought", "a1", "later", "a2"]); + cx.simulate_keystrokes("l"); + cx.run_until_parked(); + let detail_height = cx.debug_bounds("tool-card").unwrap().size.height; + chat.update(cx, |chat, _| { + assert!(chat.toggled_tools.contains("call")); + assert!(!chat.chunk_open(4)); + }); cx.simulate_keystrokes("j"); assert_eq!(selected(cx).as_deref(), Some("thought")); - // Folding from the pointer while a step is selected: the selection - // moves to the line rather than staying on a row that is gone. - chat.update(cx, |chat, cx| chat.toggle_turn("call", cx)); + // A pointer fold moves a hidden selection to its own chunk header, + // and does not clear the individual tool's disclosure choice. + press(cx, "activity-chunk-call"); assert_eq!(selected(cx).as_deref(), Some("call")); + assert_eq!(rows(cx), ["u1", "call", "a1", "later", "a2"]); + assert!(cx.debug_bounds("tool-card").is_none()); + messages_shown(cx); + press(cx, "activity-chunk-later"); + assert_eq!( + rows(cx), + ["u1", "call", "a1", "later", "later-thought", "a2"] + ); + chat.update(cx, |chat, _| { + assert!(!chat.chunk_open(1)); + assert!(chat.chunk_open(4)); + assert!(chat.toggled_tools.contains("call")); + assert!(!chat.toggled_tools.contains("later")); + }); + messages_shown(cx); - cx.simulate_keystrokes("l"); + cx.simulate_keystrokes("g g 3 j h"); + assert_eq!(selected(cx).as_deref(), Some("later")); + assert_eq!(rows(cx), ["u1", "call", "a1", "later", "a2"]); + press(cx, "activity-chunk-call"); + chat.update(cx, |chat, _| { + assert!(chat.chunk_open(1)); + assert!(!chat.chunk_open(4)); + assert!(chat.toggled_tools.contains("call")); + }); + cx.run_until_parked(); assert_eq!( - rows(cx).len(), - 4, - "the line opens before its step's details" + cx.debug_bounds("tool-card").unwrap().size.height, + detail_height, + "reopening the chunk restores the tool's visible details" ); - cx.simulate_keystrokes("h"); + messages_shown(cx); + } + + #[gpui::test] + fn folded_chunks_keep_live_rows_and_outcomes_under_one_turn_clock(cx: &mut TestAppContext) { + use std::time::{Duration, Instant}; + + use crate::ui::motion; + use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; + + struct ResetClock; + impl Drop for ResetClock { + fn drop(&mut self) { + motion::set_test_now(None); + } + } + let _reset_clock = ResetClock; + let began = Instant::now(); + motion::set_test_now(Some(began)); + cx.update(|cx| cx.set_reduce_motion(true)); + let (chat, cx) = chat_window(cx, |chat, _| { + chat.tool_details = false; + chat.summaries_enabled = false; + chat.replace_timeline(vec![user_item("u1", "Run the checks")]); + }); + let event = |event| AgentServiceEvent::Run { + session_id: "s1".into(), + run_id: "run-1".into(), + event, + }; + chat.update(cx, |chat, cx| { + chat.handle_service_event(event(AgentRunEvent::Started), cx); + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(item("call", "tool", None))), + cx, + ); + }); + motion::set_test_now(Some(began + Duration::from_secs(5))); + chat.update(cx, |chat, cx| { + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(item( + "a1", + "message", + Some("The first check is done; checking the rest."), + ))), + cx, + ); + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(AgentTimelineItem { + status: Some("running".into()), + ..item("later", "tool", None) + })), + cx, + ); + assert!(!chat.chunk_open(1)); + assert!(!chat.chunk_open(3)); + }); + cx.run_until_parked(); + assert!(cx.debug_bounds("activity-status-later").is_some()); + assert!(cx.debug_bounds("timeline-row-a1").is_some()); + assert!(cx.debug_bounds("tool-card").is_none()); + + motion::set_test_now(Some(began + Duration::from_secs(8))); + chat.update(cx, |chat, cx| { + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(item( + "live-thought", + "thinking", + Some("Another row arrives while this chunk is folded."), + ))), + cx, + ); + assert_eq!(chat.turns.tail(), Some(1)); + assert!(!chat.chunk_open(3)); + assert_eq!(chat.navigable_timeline_ids(), ["u1", "call", "a1", "later"]); + assert!( + chat.turn_worked.is_empty(), + "a new chunk does not end the turn" + ); + }); + cx.run_until_parked(); + assert!(cx.debug_bounds("thinking-title").is_none()); + assert!(cx.debug_bounds("timeline-row-a1").is_some()); + + motion::set_test_now(Some(began + Duration::from_secs(13))); + chat.update(cx, |chat, cx| { + for (id, status) in [("call", "failed"), ("later", "cancelled")] { + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(AgentTimelineItem { + status: Some(status.into()), + ..item(id, "tool", None) + })), + cx, + ); + } + chat.handle_service_event( + event(AgentRunEvent::TimelineItem(item( + "failure", + "error", + Some("One check failed."), + ))), + cx, + ); + chat.handle_service_event( + event(AgentRunEvent::Finished(AgentRunTerminal::Cancelled)), + cx, + ); + assert_eq!(chat.turn_worked.len(), 1); + assert_eq!(chat.turn_worked.get("call"), Some(&Duration::from_secs(13))); + assert!(!chat.chunk_open(1)); + assert!(!chat.chunk_open(3)); + assert_eq!( + chat.turns.chunk(1).unwrap().state(false), + Some(crate::ui::chat::step::StepState::Failed) + ); + assert_eq!( + chat.turns.chunk(3).unwrap().state(false), + Some(crate::ui::chat::step::StepState::Stopped) + ); + assert_eq!( + chat.navigable_timeline_ids(), + ["u1", "call", "a1", "later", "failure"] + ); + }); + cx.run_until_parked(); + for selector in [ + "activity-status-call", + "activity-status-later", + "timeline-row-a1", + "timeline-row-failure", + ] { + assert!( + cx.debug_bounds(selector).is_some(), + "{selector} remains visible" + ); + } + assert!(cx.debug_bounds("tool-card").is_none()); + assert!(cx.debug_bounds("thinking-title").is_none()); + } + + #[test] + fn chunk_disclosure_motion_is_independent_and_settles_with_reduced_motion() { + use std::time::Instant; + + use crate::ui::chat::transcript::RowMotion; + use crate::ui::motion; + + let began = Instant::now(); + let midway = began + motion::REVEAL.duration / 2; + let mut rows = RowMotion::default(); + rows.disclose("tool", true, began); + rows.disclose_chunk("first", true, began); + let progress = rows.chunk_disclosure("first", midway, false); + assert!(progress > 0. && progress < 1.); + assert_eq!(rows.chunk_disclosure("second", midway, false), 1.); + rows.disclose_chunk("second", true, midway); + assert_eq!(rows.chunk_disclosure("second", midway, false), 0.); + assert_eq!(rows.chunk_disclosure("first", midway, false), progress); + assert_eq!(rows.disclosure("tool", midway, false), progress); + + rows.rekey("first", "persisted-first"); assert_eq!( - rows(cx), - ["u1", "call", "a1"], - "h on the line folds the turn" + rows.chunk_disclosure("persisted-first", midway, false), + progress ); + rows.disclose_chunk("second", false, midway); + assert_eq!(rows.chunk_disclosure("second", midway, false), 1.); + assert_eq!(rows.disclosure("tool", midway, false), progress); + assert_eq!(rows.chunk_disclosure("persisted-first", midway, true), 1.); + assert!(!rows.settle(midway, true)); + assert_eq!(rows.chunk_disclosure("persisted-first", midway, false), 1.); + assert_eq!(rows.disclosure("tool", midway, false), 1.); } #[gpui::test] @@ -13564,7 +13771,7 @@ mod state_tests { chat.tool_summaries .insert("think-1".to_string(), SharedString::from(summary)); // The rows under test are the turn's steps: show them. - chat.toggle_turn("tool-1", cx); + chat.toggle_chunk("tool-1", cx); chat }); @@ -13595,6 +13802,100 @@ mod state_tests { ); } + /// A step says what it acted on beside its title, an edit also what it + /// changed, and the steps' nodes sit under the mark on the turn's line. + #[gpui::test] + fn test_a_step_shows_what_it_acted_on_and_what_it_changed(cx: &mut TestAppContext) { + cx.executor().allow_parking(); + struct ChatHost { + chat: Entity, + } + impl Render for ChatHost { + fn render( + &mut self, + _window: &mut Window, + _cx: &mut Context, + ) -> impl IntoElement { + div() + .w(px(1200.)) + .h(px(800.)) + .flex() + .flex_col() + .child(self.chat.clone()) + } + } + + let call = |id: &str, name: &str, acts_on: &str| AgentTimelineItem { + label: Some(maple_agent::agent::AgentTimelineLabel { + kind: "tool".to_string(), + name: Some(name.to_string()), + detail: Some(acts_on.to_string()), + }), + status: Some("completed".to_string()), + ..item(id, "tool", None) + }; + let chat = cx.new(|cx| { + let _guard = SETTINGS_LOCK.lock(); + let backend = std::sync::Arc::new( + crate::backend::AgentBackend::for_test( + "http://127.0.0.1:9".to_string(), + String::new(), + ) + .expect("backend"), + ); + crate::desktop::register_key_bindings(cx); + let mut chat = ChatScreen::new_without_start(backend, "user".to_string(), cx); + chat.selected_session = Some("s1".to_string()); + chat.booting = false; + chat.replace_timeline(vec![ + user_item("u1", "Cap the wait"), + call("run", "bash", "cargo test -p net retry"), + AgentTimelineItem { + input: Some(serde_json::json!({ + "path": "src/net/retry.rs", + "edits": [{ + "oldText": "loop {", + "newText": "let deadline = now + MAX;\nloop {", + }], + })), + ..call("edit", "edit", "src/net/retry.rs") + }, + ]); + chat.toggle_chunk("run", cx); + chat + }); + + let (_host, cx) = cx.add_window_view(|_window, _cx| ChatHost { chat: chat.clone() }); + cx.simulate_resize(gpui::size(px(1200.), px(800.))); + + // The edit is the last step drawn, so these are its parts. + let title = cx.debug_bounds("tool-title").expect("the step's title"); + let chip = cx + .debug_bounds("step-chip") + .expect("the path the edit acts on"); + let changed = cx + .debug_bounds("step-changed") + .expect("the lines the edit changed"); + assert!( + title.right() <= chip.left() && chip.right() <= changed.left(), + "the title, what it acts on and what it changed read in that order: \ + {title:?}, {chip:?}, {changed:?}" + ); + assert!( + (chip.center().y - title.center().y).abs() <= px(1.) + && (changed.center().y - title.center().y).abs() <= px(1.), + "on one line: {title:?}, {chip:?}, {changed:?}" + ); + let node = cx.debug_bounds("step-node").expect("the step's node"); + let mark = cx + .debug_bounds("turn-mark") + .expect("the mark on the turn's line"); + assert!( + (node.center().x - mark.center().x).abs() <= px(1.), + "the nodes sit under the mark: {node:?}, {mark:?}" + ); + } + #[gpui::test] fn out_of_usage_offers_billing_from_the_composer_until_a_later_turn(cx: &mut TestAppContext) { use std::cell::Cell; diff --git a/apps/maple-agent/app/src/ui/chat/transcript.rs b/apps/maple-agent/app/src/ui/chat/transcript.rs index cdb4f52c3..0d17e3321 100644 --- a/apps/maple-agent/app/src/ui/chat/transcript.rs +++ b/apps/maple-agent/app/src/ui/chat/transcript.rs @@ -17,11 +17,12 @@ use maple_agent::agent::{ use super::cache::{MAX_DIFF_LINES, MarkdownKind}; use super::speech::speak_message_button; +use super::step::{self, StepState}; use super::turn::{self, TurnRow}; use super::{CONTENT_WIDTH, ChatScreen, QuestionSelection, TranscriptCtx}; use crate::ui::i18n::{MessageCache, tr}; -use crate::ui::icons::{icon, spinner, spinner_with_id}; +use crate::ui::icons::{icon, spinner}; use crate::ui::markdown; use crate::ui::motion; use crate::ui::rich_text::{self, RenderCtx}; @@ -75,16 +76,12 @@ impl ChatScreen { let Some(item) = chat.timeline.get(ix) else { return div().into_any_element(); }; - // A turn's first step carries the turn's line. Folded, the line - // is all of that row, and the later steps draw nothing. + // Each activity chunk has a disclosure; only the first also + // carries the overall turn's animated status line. let turn = chat.turns.row(ix); - let lead = match turn { - TurnRow::Plain => None, - TurnRow::Lead => Some(ix), - TurnRow::Step(lead) => Some(lead), - }; - let open = lead.is_none_or(|lead| chat.turn_open(lead)); - if !open && turn != TurnRow::Lead { + let lead = turn.lead(ix); + let open = lead.is_none_or(|lead| chat.chunk_open(lead)); + if !open && matches!(turn, TurnRow::Step(_)) { return div().into_any_element(); } // A row that arrived live enters, timed from view state so @@ -113,6 +110,15 @@ impl ChatScreen { speech_available: chat.audio_caps.speech, position: (ix + 1, chat.timeline.len()), reveal: chat.row_motion.disclosure(&item.id, now, reduced), + // Steps of one turn that sit next to each other share + // the rail; a reply between two of them breaks it. + rail: ( + matches!(turn, TurnRow::Step(_)) + && ix > 0 + && chat.turns.row(ix - 1) != TurnRow::Plain, + turn != TurnRow::Plain + && matches!(chat.turns.row(ix + 1), TurnRow::Step(_)), + ), }; let expanded = tool_details != chat.toggled_tools.contains(&item.id); let revision = chat @@ -139,22 +145,31 @@ impl ChatScreen { }), ); } - // Steps the line just showed fade in, like any details - // the user opens. + // Each chunk keeps the existing details reveal timing. let shown = lead.map_or(1., |lead| { chat.row_motion - .turn_disclosure(&chat.timeline[lead].id, now, reduced) + .chunk_disclosure(&chat.timeline[lead].id, now, reduced) }); row.when(shown < 1., |row| row.opacity(motion::ease_out_quint(shown))) }); - let line = (turn == TurnRow::Lead).then(|| { - turn::render_line( - chat.turn_line(ix, still), - Some((&item.id, open)), - &entity, - &chat.messages, + let body = if let Some(chunk) = chat.turns.chunk(ix) { + Some( + div() + .child(turn::render_chunk( + &item.id, + chunk, + open, + chat.turn_runs(ix), + &entity, + &chat.messages, + )) + .children(body), ) - }); + } else { + body + }; + let line = (turn == TurnRow::Lead) + .then(|| turn::render_line(chat.turn_line(ix, still), &item.id, &chat.messages)); let select = |row: Div| { if !chat.application_vim_enabled { return row; @@ -429,8 +444,7 @@ impl ChatScreen { let line = self.line_in_slot().then(|| { turn::render_line( self.live_line(motion::loops_paused(window, cx)), - None, - &cx.entity().downgrade(), + "slot", &self.messages, ) }); @@ -569,7 +583,7 @@ pub(super) struct RowMotion { pub(super) heights: Rc>>, /// Rows whose details the user just opened, by item id. disclosed: HashMap, - /// Turns whose steps the user just showed, by the id of their lead row. + /// Chunks whose steps the user just showed, by their lead row id. unfolded: HashMap, /// When another task's transcript landed. switched: Option, @@ -713,8 +727,8 @@ impl RowMotion { } } - /// The user showed or folded a turn's steps. Folding is immediate. - pub(super) fn disclose_turn(&mut self, lead: &str, open: bool, now: Instant) { + /// The user showed or folded a chunk. Folding is immediate. + pub(super) fn disclose_chunk(&mut self, lead: &str, open: bool, now: Instant) { if open { self.unfolded.insert(lead.to_owned(), now); } else { @@ -773,7 +787,7 @@ impl RowMotion { } /// Progress of the fade of steps the user just showed. - pub(super) fn turn_disclosure(&self, lead: &str, now: Instant, reduced: bool) -> f32 { + pub(super) fn chunk_disclosure(&self, lead: &str, now: Instant, reduced: bool) -> f32 { self.unfolded .get(lead) .map_or(1., |at| motion::progress(*at, motion::REVEAL, now, reduced)) @@ -946,12 +960,11 @@ pub(super) fn render_timeline_item( Some(plan) => plan, None => return div().into_any_element(), } - } else if has_tool_input(item, "edits") - || (has_tool_input(item, "content") && has_tool_input(item, "path")) - { - render_tool_with_diff(item, revision, expanded, transcript) } else { - render_tool(item, revision, expanded, transcript) + // An edit or a write carries replacements to show. + let diff = has_tool_input(item, "edits") + || (has_tool_input(item, "content") && has_tool_input(item, "path")); + render_tool(item, revision, expanded, diff, transcript) } } "error" => render_error(item, transcript), @@ -959,10 +972,11 @@ pub(super) fn render_timeline_item( _ => render_system(item, transcript), }; // Per-item spacing (instead of a container gap) keeps non-renderable - // items from producing phantom gaps. Rows a screen reader should + // items from producing phantom gaps. Steps joined by the thread's rail + // sit flush, so the rail has no break. Rows a screen reader should // announce get a role, a sender, and their position in the // conversation; the others stay plain containers. - let row = div().pb_2().child(item); + let row = div().when(!transcript.rail.1, |row| row.pb_2()).child(item); match role { Some(role) => { let (position, count) = transcript.position; @@ -1333,12 +1347,17 @@ fn render_thinking( transcript: &TranscriptCtx, ) -> Div { let text = transcript.derived.get(item, revision).text.clone(); + let id = SharedString::from(format!("thinking-toggle-{}", item.id)); if text.trim().is_empty() { - return div().child( - div() - .text_color(gpui::rgb(theme::status_running())) - .text_sm() + // Nothing to open yet. + return step::step( + "brain", + StepState::Running, + transcript.rail, + step::step_header(id) + .text_color(gpui::rgb(StepState::Running.ink())) .child(tr("chat-thinking")), + None, ); } let item_id = item.id.clone(); @@ -1353,68 +1372,49 @@ fn render_thinking( .unwrap_or_else(|| tr("chat-thinking-title")) }); // Only the header toggles, so clicks in the body still select text. - let header = div() - .id(gpui::SharedString::from(format!( - "thinking-toggle-{}", - item.id - ))) + let header = step::step_header(id) .role(gpui::Role::DisclosureTriangle) .aria_label(title.clone()) .aria_expanded(expanded) - .flex() - .items_center() - .gap_1() - .text_sm() - .text_color(gpui::rgb(theme::text_muted())) - .hover(|style| { - style - .cursor_pointer() - .text_color(gpui::rgb(theme::text_secondary())) - }) - .on_click(move |_event, _window, cx: &mut gpui::App| { - chat.update(cx, |chat, cx| { - chat.toggle_tool(&item_id, cx); - }) - .ok(); - }) - .child(motion::chevron( - SharedString::from(format!("thinking-chevron-{}", item.id)), - expanded, - px(14.), - theme::text_muted(), - )) + .cursor_pointer() + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(gpui::rgb(StepState::Done.ink())) .child( div() - // Same prose-summary rule as the tool card title. + // Same prose-summary rule as a tool call's title. .min_w_0() - .flex_1() .truncate() .debug_selector(|| "thinking-title".to_string()) .child(title), - ); - let card = div() - .px_3() - .py_2() - .rounded(theme::RADIUS_SM) - .bg(gpui::rgb(theme::bg_elevated())) - .flex() - .flex_col() - .gap_1() - .child(header); - if !expanded { - return card; - } - card.child(revealed( - typography::chat_reading(div()) - .text_color(gpui::rgb(theme::text_secondary())) - .child(markdown::render_with( - &transcript - .markdown_cache - .get(&item.id, MarkdownKind::Body, revision, &text), - transcript.render, - )), - transcript.reveal, - )) + ) + .child(motion::chevron( + SharedString::from(format!("thinking-chevron-{}", item.id)), + expanded, + px(14.), + theme::text_muted(), + )) + .hover_bg(theme::overlay_hover()) + .on_click(move |_event, _window, cx: &mut gpui::App| { + chat.update(cx, |chat, cx| { + chat.toggle_tool(&item_id, cx); + }) + .ok(); + }); + let details = expanded.then(|| { + revealed( + typography::chat_reading(div()) + .text_color(gpui::rgb(theme::text_secondary())) + .child(markdown::render_with( + &transcript + .markdown_cache + .get(&item.id, MarkdownKind::Body, revision, &text), + transcript.render, + )), + transcript.reveal, + ) + .into_any_element() + }); + step::step("brain", StepState::Done, transcript.rail, header, details) } /// Details the user just opened fade in; `reveal` is how far along they @@ -1427,47 +1427,22 @@ fn revealed(details: E, reveal: f32) -> E { } } -fn tool_status_style(status: Option<&str>) -> (SharedString, u32) { - match status { - Some("completed") => (tr("chat-status-completed"), theme::status_success()), - Some("failed") | Some("error") => (tr("chat-status-failed"), theme::status_error()), - Some("cancelled") => (tr("chat-status-stopped"), theme::text_muted()), - _ => (tr("chat-status-running"), theme::status_running()), - } -} - -/// A tool card's spinner and status label. When the call finishes on -/// screen the running state goes at once and the outcome fades in over -/// [`motion::TOGGLE`]: two labels drawn over each other would read as -/// one garbled word. A card that mounts finished (history, a row scrolled -/// back) shows its state at once. -fn tool_status(item_id: &str, running: bool, label: SharedString, color: u32) -> motion::Animated { - let spinner_id = SharedString::from(format!("tool-spinner-{item_id}")); - motion::animated( - SharedString::from(format!("tool-status-{item_id}")), - if running { 0. } else { 1. }, - motion::TOGGLE, - move |done| { - div() - .flex() - .items_center() - .gap_2() - .opacity(if running { 1. - done } else { done }) - .when(running, |state| { - state.child(spinner_with_id( - spinner_id.clone(), - px(12.), - theme::accent(), - )) - }) - .child( - div() - .text_xs() - .text_color(gpui::rgb(color)) - .child(label.clone()), - ) - .into_any_element() - }, +/// What a step says after its title when it did not simply finish. A +/// running step says nothing: it is dim, and the turn's line is the one +/// thing that moves. +fn step_outcome(state: StepState) -> Option
{ + let (label, color) = match state { + StepState::Failed => (tr("chat-status-failed"), theme::status_error()), + StepState::Stopped => (tr("chat-status-stopped"), theme::text_muted()), + StepState::Running | StepState::Done => return None, + }; + Some( + div() + .flex_none() + .font_weight(gpui::FontWeight::NORMAL) + .text_xs() + .text_color(gpui::rgb(color)) + .child(label), ) } @@ -1573,8 +1548,8 @@ pub(super) fn plan_finished(plan: &[PlanEntry]) -> bool { .all(|entry| entry.status == PlanStatus::Completed) } -/// The transcript row of a finished todo list: a foldable card like a tool -/// call's, or `None` while the list is unfinished and the pinned card +/// The transcript row of a finished todo list: a step that opens like a +/// tool call's, or `None` while the list is unfinished and the pinned card /// shows it. fn render_finished_plan( item: &AgentTimelineItem, @@ -1587,8 +1562,7 @@ fn render_finished_plan( let count = format!("{}/{}", plan.len(), plan.len()); let item_id = item.id.clone(); let chat = transcript.chat.clone(); - let mut card = div() - .id(SharedString::from(format!("plan-toggle-{item_id}"))) + let header = step::step_header(SharedString::from(format!("plan-toggle-{item_id}"))) .debug_selector(|| "plan-row".to_string()) .role(gpui::Role::DisclosureTriangle) .aria_label( @@ -1597,61 +1571,46 @@ fn render_finished_plan( .get("chat-plan-done", [("count", count.clone().into())]), ) .aria_expanded(details) - .flex() - .flex_col() - .gap_1() - .px_3() - .py_2() - .rounded(theme::RADIUS_SM) - .bg(gpui::rgb(theme::bg_tool_card())) - .border_1() - .border_color(gpui::rgb(theme::border_subtle())) - .hover(|style| { - style - .border_color(gpui::rgb(theme::border())) - .cursor_pointer() - }) + .cursor_pointer() + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(gpui::rgb(StepState::Done.ink())) + .child(tr("chat-plan")) + .child( + div() + .font_weight(gpui::FontWeight::NORMAL) + .text_xs() + .text_color(gpui::rgb(theme::text_muted())) + .child(count), + ) + .child(motion::chevron( + SharedString::from(format!("plan-chevron-{}", item.id)), + details, + px(14.), + theme::text_muted(), + )) + .hover_bg(theme::overlay_hover()) .on_click(move |_event, _window, cx: &mut gpui::App| { chat.update(cx, |chat, cx| chat.toggle_tool(&item_id, cx)) .ok(); - }) - .child( - div() - .flex() - .gap_2() - .items_center() - .child( - div() - .flex_1() - .text_sm() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(gpui::rgb(theme::text_primary())) - .child(tr("chat-plan")), - ) - .child( - div() - .text_xs() - .text_color(gpui::rgb(theme::text_muted())) - .child(count), - ) - .child(motion::chevron( - SharedString::from(format!("plan-chevron-{}", item.id)), - details, - px(14.), - theme::text_muted(), - )), - ); - if details { - card = card.child(revealed( + }); + let rows = details.then(|| { + revealed( div() .flex() .flex_col() .gap_1() .children(plan.iter().map(render_plan_row)), transcript.reveal, - )); - } - Some(div().child(card)) + ) + .into_any_element() + }); + Some(step::step( + "check", + StepState::Done, + transcript.rail, + header, + rows, + )) } /// One row of the subagent card: what the subagent was asked to do, the @@ -1830,21 +1789,30 @@ pub(super) fn diff_lines_for(item: &AgentTimelineItem) -> Vec<(char, SharedStrin lines } -/// Tool card whose payload renders as a colored diff when it carries -/// edit/write replacements. -fn render_tool_with_diff( - item: &AgentTimelineItem, - revision: u64, - details: bool, - transcript: &TranscriptCtx, -) -> Div { - let card = render_tool(item, revision, details, transcript); - if !details { - return card; +/// How many lines an edit or write adds and removes, counted from the +/// whole input. `diff_lines_for` stops at the display cap; this does not. +pub(super) fn diff_counts(item: &AgentTimelineItem) -> (usize, usize) { + let Some(serde_json::Value::Object(map)) = item.input.as_ref() else { + return (0, 0); + }; + let lines = |text: Option<&serde_json::Value>| { + text.and_then(|text| text.as_str()) + .map_or(0, |text| text.lines().count()) + }; + let (mut added, mut removed) = (lines(map.get("content")), 0); + if let Some(serde_json::Value::Array(edits)) = map.get("edits") { + for edit in edits { + removed += lines(edit.get("oldText")); + added += lines(edit.get("newText")); + } } - let diff_lines = Arc::clone(&transcript.derived.get(item, revision).diff_lines); - if diff_lines.is_empty() { - return card; + (added, removed) +} + +/// The +/- lines of an edit or write, coloured. +fn render_diff(lines: &[(char, SharedString)]) -> Option
{ + if lines.is_empty() { + return None; } let mut diff = div() .flex() @@ -1855,7 +1823,7 @@ fn render_tool_with_diff( .border_1() .border_color(gpui::rgb(theme::border_subtle())) .overflow_x_hidden(); - for (sign, line) in diff_lines.iter() { + for (sign, line) in lines { let color = match sign { '+' => theme::status_success(), '-' => theme::status_error(), @@ -1885,18 +1853,7 @@ fn render_tool_with_diff( ), ); } - // The diff is content: swallow clicks so selecting it does not toggle. - card.child(revealed( - div() - .id(gpui::SharedString::from(format!("tool-diff-{}", item.id))) - .on_click( - |_event: &gpui::ClickEvent, _window: &mut Window, cx: &mut gpui::App| { - cx.stop_propagation(); - }, - ) - .child(diff), - transcript.reveal, - )) + Some(diff) } /// Title shown before the model summary arrives: just the tool label from @@ -1922,138 +1879,126 @@ pub(super) fn tool_label_title(title: &str) -> &str { } } +/// A tool call as a step. `diff`: an edit or write, whose details also +/// show its replacements as a coloured diff. fn render_tool( item: &AgentTimelineItem, revision: u64, details: bool, + diff: bool, transcript: &TranscriptCtx, ) -> Div { - let (label, status_color) = tool_status_style(item.status.as_deref()); - let running = !matches!( - item.status.as_deref(), - Some("completed" | "failed" | "error" | "cancelled") - ); + let state = StepState::of(item.status.as_deref()); let item_id = item.id.clone(); - let chat_header = transcript.chat.clone(); + let chat = transcript.chat.clone(); + let derived = transcript.derived.get(item, revision); // An external agent's row draws its own activity; a summary asked // when its call started would hide what it did. let summary = (!has_external_agent_activity(item)) .then(|| transcript.tool_summaries.get(&item.id).cloned()) .flatten(); - // The model summary stands in for the title; until it lands, show just - // the tool label ("Terminal"), not the raw `tool: args` title. - let title = summary.clone().unwrap_or_else(|| { - if let Some(label) = crate::ui::timeline_labels::tool_label(item, transcript.messages) - .or_else(|| crate::ui::timeline_labels::title(item, transcript.messages)) - { - return label; + // The model summary stands in for the title; until it lands, the + // tool's name does ("Terminal"). Either leaves what the call acts on + // to the chip beside it. + let named = + summary.or_else(|| crate::ui::timeline_labels::tool_name(item, transcript.messages)); + let acted_on = named.as_ref().and(derived.acted_on.clone()); + let title = named.unwrap_or_else(|| { + if let Some(title) = crate::ui::timeline_labels::title(item, transcript.messages) { + return title; } let raw = item.title.as_deref().unwrap_or(&item.item_type); SharedString::from(tool_label_title(raw).to_string()) }); - let card = div() - .id(gpui::SharedString::from(format!("tool-toggle-{item_id}"))) - .debug_selector(|| "tool-card".to_string()) + // Only the header toggles, so the details under it can be read and + // selected without folding them. + let header = step::step_header(SharedString::from(format!("tool-toggle-{item_id}"))) .role(gpui::Role::DisclosureTriangle) .aria_label(title.clone()) .aria_expanded(details) - .flex() - .flex_col() - .gap_1() - .px_3() - .py_2() - .rounded(theme::RADIUS_SM) - .bg(gpui::rgb(theme::bg_tool_card())) - .border_1() - .border_color(gpui::rgb(theme::border_subtle())) - .hover(|style| { - style - .border_color(gpui::rgb(theme::border())) - .cursor_pointer() - }) - .on_click(move |_event, _window, cx: &mut gpui::App| { - chat_header - .update(cx, |chat, cx| { - chat.toggle_tool(&item_id, cx); - }) - .ok(); - }) + .cursor_pointer() + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(gpui::rgb(state.ink())) .child( div() - .flex() - .gap_2() - .items_center() - .child( - div() - // The summary is prose: it grows to fill the row - // and ellipsizes at the row's end. Without min_w_0 - // the flex item collapses to its longest word and - // the old middle-ellipsis cut mid-sentence inside - // a sliver while the row sat empty. - .min_w_0() - .flex_1() - .text_sm() - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(gpui::rgb(theme::text_primary())) - .truncate() - .debug_selector(|| "tool-title".to_string()) - .child(title), - ) - .child(tool_status(&item.id, running, label, status_color)) - .child(motion::chevron( - SharedString::from(format!("tool-chevron-{}", item.id)), - details, - px(14.), - theme::text_muted(), - )), - ); - // Collapsed: the header alone; the summary takes over the title when it lands. - // Expanded cards also show the cached arguments and output. - if !details { - return div().child(card); - } - let derived = transcript.derived.get(item, revision); - if let Some(activity) = &derived.external_agent { - return div().child(card.child(revealed( - render_external_agent_activity(item, revision, activity, transcript), - transcript.reveal, - ))); - } - // A click anywhere on the card, payload included, toggles it. - let mut payload = div().flex().flex_col().gap_1(); - // Expanded: the call arguments and the raw output. The summary is - // made from the input alone, so it never stands in for the output. - if let Some(input) = &derived.input_line { - payload = payload.child( - div() - .text_xs() - .text_color(gpui::rgb(theme::text_muted())) - .font_family(crate::assets::FONT_MONO) - .overflow_x_hidden() - .child(gpui::text!( - id = SharedString::from(format!("tool-input-{}", item.id)), - input.clone() - )), - ); - } - if let Some(output) = &derived.output_text { - payload = payload.child( - typography::chat_reading(div()) - .mt_1() - .w_full() - .text_color(gpui::rgb(theme::text_secondary())) - .child(markdown::render_with( - &transcript.markdown_cache.get( - &item.id, - MarkdownKind::ToolOutput, - revision, - output, - ), - &readable_ctx(transcript.render), - )), - ); - } - div().child(card.child(revealed(payload, transcript.reveal))) + // The summary is prose: it takes the row's width before + // it ellipsizes at the row's end. Without min_w_0 the + // flex item would not shrink and would push the rest out. + .min_w_0() + .truncate() + .debug_selector(|| "tool-title".to_string()) + .child(title), + ) + .children(acted_on.map(step::chip)) + // Counted from the call's input: true only once the edit landed. + .children( + derived + .changed + .as_ref() + .filter(|_| state == StepState::Done) + .map(step::changed), + ) + .children(step_outcome(state)) + .child(motion::chevron( + SharedString::from(format!("tool-chevron-{}", item.id)), + details, + px(14.), + theme::text_muted(), + )) + .hover_bg(theme::overlay_hover()) + .on_click(move |_event, _window, cx: &mut gpui::App| { + chat.update(cx, |chat, cx| { + chat.toggle_tool(&item_id, cx); + }) + .ok(); + }); + // Open: the call's arguments and its raw output. The summary is made + // from the input alone, so it never stands in for the output. + let body = details.then(|| { + if let Some(activity) = &derived.external_agent { + return render_external_agent_activity(item, revision, activity, transcript); + } + let mut payload = div().flex().flex_col().gap_1(); + if let Some(input) = &derived.input_line { + payload = payload.child( + div() + .text_xs() + .text_color(gpui::rgb(theme::text_muted())) + .font_family(crate::assets::FONT_MONO) + .overflow_x_hidden() + .child(gpui::text!( + id = SharedString::from(format!("tool-input-{}", item.id)), + input.clone() + )), + ); + } + if let Some(output) = &derived.output_text { + payload = payload.child( + typography::chat_reading(div()) + .mt_1() + .w_full() + .text_color(gpui::rgb(theme::text_secondary())) + .child(markdown::render_with( + &transcript.markdown_cache.get( + &item.id, + MarkdownKind::ToolOutput, + revision, + output, + ), + &readable_ctx(transcript.render), + )), + ); + } + payload.children(diff.then(|| render_diff(&derived.diff_lines)).flatten()) + }); + step::step( + step::tool_icon(item), + state, + transcript.rail, + header, + body.map(|body| revealed(body, transcript.reveal).into_any_element()), + ) + .debug_selector(|| "tool-card".to_string()) } /// Keep a card's output out of the shared selection, which would treat its @@ -3593,7 +3538,7 @@ mod motion_tests { } #[gpui::test] - fn a_turns_steps_stay_folded_until_its_line_is_clicked(cx: &mut TestAppContext) { + fn a_chunks_steps_stay_folded_until_its_header_is_clicked(cx: &mut TestAppContext) { let _clock = Clock::start(); let (chat, cx) = pane(cx, 30); // A finished turn after the history: two steps, then the reply. @@ -3617,6 +3562,13 @@ mod motion_tests { cx.simulate_click(line.center(), gpui::Modifiers::default()); redraw(&chat, cx); + assert!( + cx.debug_bounds("tool-card").is_none(), + "the turn line is informational" + ); + let header = bounds(cx, "activity-chunk-call"); + cx.simulate_click(header.center(), gpui::Modifiers::default()); + redraw(&chat, cx); let call = bounds(cx, "tool-card"); let thought = bounds(cx, "thinking-title"); assert_eq!( @@ -3629,7 +3581,8 @@ mod motion_tests { "the steps open under the line, in order: {line:?}, {call:?}, {thought:?}" ); - cx.simulate_click(line.center(), gpui::Modifiers::default()); + let header = bounds(cx, "activity-chunk-call"); + cx.simulate_click(header.center(), gpui::Modifiers::default()); redraw(&chat, cx); assert!( cx.debug_bounds("tool-card").is_none(), @@ -3658,7 +3611,7 @@ mod motion_tests { } #[gpui::test] - fn the_line_keeps_its_place_when_the_turns_first_step_arrives(cx: &mut TestAppContext) { + fn the_line_hands_off_without_a_jump_as_the_first_chunk_enters(cx: &mut TestAppContext) { let clock = Clock::start(); let (chat, cx) = pane(cx, 30); // A run is going and nothing has come back yet: the line waits @@ -3683,17 +3636,23 @@ mod motion_tests { }); let tops = tops_through_entrance(&chat, &clock, start, &["turn-line", "timeline-row-h29"], cx); - assert!( - tops[0].iter().all(|top| *top == waiting.origin.y), - "the line stays where it waited ({:?}) once a row carries it: {:?}", - waiting.origin.y, - tops[0] + assert_eq!(tops[0][0], waiting.origin.y, "the line hands off in place"); + assert_eq!( + tops[1][0], older.origin.y, + "older rows do not jump on handoff" ); + assert_glides(&tops[0], "the line above the arriving chunk header"); + assert_glides(&tops[1], "the history above the arriving chunk header"); + for (line, history) in tops[0].iter().zip(&tops[1]) { + assert_eq!( + *line - *history, + waiting.origin.y - older.origin.y, + "the header's entrance moves the line and history together" + ); + } assert!( - tops[1].iter().all(|top| *top == older.origin.y), - "older rows hold still: {:?} then {:?}", - older.origin.y, - tops[1] + bounds(cx, "activity-chunk-call").top() >= bounds(cx, "turn-line").bottom(), + "the inline disclosure settles below the informational line" ); } diff --git a/apps/maple-agent/app/src/ui/chat/turn.rs b/apps/maple-agent/app/src/ui/chat/turn.rs index f21f072d0..945c3b940 100644 --- a/apps/maple-agent/app/src/ui/chat/turn.rs +++ b/apps/maple-agent/app/src/ui/chat/turn.rs @@ -1,24 +1,25 @@ -//! The line a turn's steps fold under. +//! A turn's status line and independently disclosed activity chunks. //! -//! A turn is what Maple does between two messages from the user. Its -//! thinking rows and tool calls are its steps. The first step carries the -//! turn's line: the Maple mark, what Maple is doing, and for how long. The -//! steps stay folded under the line until it is clicked. Before a turn has -//! a step, the same line waits in the slot under the transcript. +//! A turn runs between user messages. Visible messages and notices split +//! its steps into chunks, without splitting its clock or animated status. +use std::collections::HashMap; use std::time::{Duration, Instant}; use gpui::{Context, Div, SharedString, div, prelude::*, px}; use maple_agent::agent::AgentTimelineItem; use super::ChatScreen; +use super::step; use super::transcript::{ WAITING_ROW_HEIGHT, format_subagent_elapsed, has_tool_input, plan_entries, plan_finished, }; use crate::ui::i18n::{MessageCache, tr}; use crate::ui::morph_text::morph_text; use crate::ui::motion; +use crate::ui::motion::HoverBg as _; use crate::ui::theme; +use crate::ui::{icons::icon, widgets}; /// Gap between two repaints of a running turn's time where loops hold /// still. The time counts whole seconds, so one repaint a second is enough. @@ -30,25 +31,87 @@ const RUN_TICK: Duration = Duration::from_secs(1); const MARK_CYCLE: Duration = Duration::from_millis(2400); const SHINE_CYCLE: Duration = Duration::from_millis(1900); -/// What a transcript row is to its turn's line. +/// A transcript row's place in its turn and activity chunk. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum TurnRow { - /// A message, a notice, an error: always shown. Plain, - /// The turn's first step. The line is drawn above it. + /// The first chunk also carries the turn's status line. Lead, - /// A later step, folded under the lead at this index. + Chunk, Step(usize), } -/// Each loaded row's place in its turn, kept beside the timeline so no -/// frame regroups it. +impl TurnRow { + pub(super) fn lead(self, index: usize) -> Option { + match self { + Self::Plain => None, + Self::Lead | Self::Chunk => Some(index), + Self::Step(lead) => Some(lead), + } + } +} + +/// Header data maintained on row changes, never derived during rendering. +#[derive(Default)] +pub(super) struct Chunk { + end: usize, + icons: Vec<(&'static str, usize)>, + states: [usize; 4], +} + +impl Chunk { + fn add_icon(&mut self, icon: &'static str) { + if let Some((_, count)) = self.icons.iter_mut().find(|(name, _)| *name == icon) { + *count += 1; + } else { + self.icons.push((icon, 1)); + } + } + + fn add(&mut self, (icon, state): (&'static str, step::StepState)) { + self.add_icon(icon); + self.states[state as usize] += 1; + } + + fn replace( + &mut self, + before: (&'static str, step::StepState), + after: (&'static str, step::StepState), + ) { + self.states[before.1 as usize] -= 1; + self.states[after.1 as usize] += 1; + if before.0 != after.0 { + for (name, count) in &mut self.icons { + if *name == before.0 { + *count -= 1; + } + } + self.icons.retain(|(_, count)| *count > 0); + self.add_icon(after.0); + } + } + + pub(super) fn count(&self) -> usize { + self.states.iter().sum() + } + + pub(super) fn state(&self, live: bool) -> Option { + use step::StepState; + [StepState::Failed, StepState::Running, StepState::Stopped] + .into_iter() + .find(|state| { + self.states[*state as usize] > 0 && (*state != StepState::Running || live) + }) + } +} + #[derive(Default)] pub(super) struct Turns { rows: Vec, - /// The lead of the turn at the end of the loaded rows, once that turn - /// has a step. + chunks: HashMap, + /// First step of the latest user turn, kept stable for its clock. tail: Option, + chunk: Option, } fn starts_turn(item: &AgentTimelineItem) -> bool { @@ -69,16 +132,44 @@ fn is_step(item: &AgentTimelineItem) -> bool { matches!(item.item_type.as_str(), "thinking" | "reasoning") } -/// What decides a row's place in its turn: whether it starts one, and -/// whether it is a step. -pub(super) fn part(item: &AgentTimelineItem) -> (bool, bool) { - (starts_turn(item), is_step(item)) +/// Classification changes can move both turn and chunk boundaries. +pub(super) fn part(item: &AgentTimelineItem) -> (bool, bool, bool) { + let step = is_step(item); + ( + starts_turn(item), + step, + !step && !is_tool(item) && super::navigation::timeline_item_is_navigable(item), + ) +} + +pub(super) fn step_info(item: &AgentTimelineItem) -> (&'static str, step::StepState) { + if is_tool(item) { + if has_tool_input(item, "todos") { + return ("check", step::StepState::Done); + } + return ( + step::tool_icon(item), + step::StepState::of(item.status.as_deref()), + ); + } + let state = if item + .text + .as_deref() + .is_none_or(|text| text.trim().is_empty()) + { + step::StepState::Running + } else { + step::StepState::Done + }; + ("brain", state) } impl Turns { /// Group a whole timeline: a snapshot, a history page, a trimmed window. pub(super) fn rebuild(&mut self, timeline: &[AgentTimelineItem]) { self.rows.clear(); + self.chunks.clear(); + self.chunk = None; self.tail = None; for item in timeline { self.push(item); @@ -87,17 +178,35 @@ impl Turns { /// One row arrived at the end. pub(super) fn push(&mut self, item: &AgentTimelineItem) { - let row = if starts_turn(item) { + let index = self.rows.len(); + let (starts_turn, is_step, breaks_chunk) = part(item); + let row = if starts_turn { self.tail = None; + self.chunk = None; TurnRow::Plain - } else if !is_step(item) { + } else if !is_step { + // Hidden plans and empty streamed messages do not separate + // the activities around them. + if breaks_chunk { + self.chunk = None; + } TurnRow::Plain - } else if let Some(lead) = self.tail { + } else if let Some(lead) = self.chunk { TurnRow::Step(lead) } else { - self.tail = Some(self.rows.len()); - TurnRow::Lead + 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) { + let chunk = self.chunks.entry(lead).or_default(); + chunk.end = index + 1; + chunk.add(step_info(item)); + } self.rows.push(row); } @@ -109,17 +218,26 @@ impl Turns { self.tail } - /// One past the last step of the turn led by the row at `lead`. + pub(super) fn chunk(&self, lead: usize) -> Option<&Chunk> { + self.chunks.get(&lead) + } + pub(super) fn end(&self, lead: usize) -> usize { - let mut end = lead + 1; - for (index, row) in self.rows.iter().enumerate().skip(end) { - match row { - TurnRow::Step(of) if *of == lead => end = index + 1, - TurnRow::Lead => break, - _ => {} - } + self.chunk(lead).map_or(lead + 1, |chunk| chunk.end) + } + + pub(super) fn update_step( + &mut self, + index: usize, + before: (&'static str, step::StepState), + after: (&'static str, step::StepState), + ) -> Option { + if before == after { + return None; } - end + let lead = self.row(index).lead(index)?; + self.chunks.get_mut(&lead)?.replace(before, after); + Some(lead) } } @@ -350,17 +468,9 @@ fn maple_mark(mark: Mark, phase: f32) -> Div { grid } -/// The line, as tall as the slot under the transcript it first shows in, -/// so taking its place in the list moves nothing. `fold` names the turn's -/// lead and says whether its steps show; the slot's line has no steps to -/// open and passes `None`. -pub(super) fn render_line( - line: Line, - fold: Option<(&str, bool)>, - chat: &gpui::WeakEntity, - messages: &MessageCache, -) -> Div { - let key = fold.map_or("slot", |(lead, _)| lead); +/// The summary keeps the same height and identity when it takes over the +/// waiting slot. Chunk disclosures do not replace or restart its motion. +pub(super) fn render_line(line: Line, key: &str, messages: &MessageCache) -> Div { let id = |part: &str| SharedString::from(format!("turn-{part}-{key}")); let (label, mark, time) = match line { Line::Live { @@ -399,14 +509,24 @@ pub(super) fn render_line( } else { theme::text_secondary() })) - .child(if running { - motion::ticker(id("mark"), MARK_CYCLE, |phase| { - maple_mark(Mark::Working, phase).into_any_element() - }) - .into_any_element() - } else { - maple_mark(mark, 0.).into_any_element() - }) + // The mark sits in the column of the steps' nodes, and the words + // start where the steps' titles do. + .child( + div() + .flex_none() + .w(step::NODE) + .mr(px(2.)) + .flex() + .justify_center() + .child(if running { + motion::ticker(id("mark"), MARK_CYCLE, |phase| { + maple_mark(Mark::Working, phase).into_any_element() + }) + .into_any_element() + } else { + maple_mark(mark, 0.).into_any_element() + }), + ) .child(if running { words.shine(SHINE_CYCLE, gpui::rgb(theme::text_heading())) } else { @@ -421,31 +541,100 @@ pub(super) fn render_line( .text_color(gpui::rgb(theme::text_muted())) .child(gpui::text!(time)) })); - let row = div().h(WAITING_ROW_HEIGHT).flex().items_center(); - let Some((lead, open)) = fold else { - return row.child(button.role(gpui::Role::Status)); - }; - let lead = lead.to_owned(); - let chat = chat.clone(); - row.child( - button - .role(gpui::Role::DisclosureTriangle) - .aria_expanded(open) - .hover(|style| { - style - .cursor_pointer() - .text_color(gpui::rgb(theme::text_primary())) - }) - .child(motion::chevron( - id("chevron"), - open, - px(14.), - theme::text_muted(), - )) - .on_click(move |_event, _window, cx: &mut gpui::App| { - chat.update(cx, |chat, cx| chat.toggle_turn(&lead, cx)).ok(); - }), - ) + div() + .h(WAITING_ROW_HEIGHT) + .flex() + .items_center() + .child(button.role(gpui::Role::Status)) +} + +pub(super) fn render_chunk( + lead: &str, + chunk: &Chunk, + open: bool, + live: bool, + chat: &gpui::WeakEntity, + messages: &MessageCache, +) -> Div { + let label = messages.get("chat-activity-steps", [("count", chunk.count().into())]); + let status = chunk.state(live).map(|state| { + let (key, ink) = match state { + step::StepState::Failed => ("chat-status-failed", theme::status_error()), + step::StepState::Stopped => ("chat-status-stopped", theme::text_muted()), + _ => ("chat-status-running", theme::text_muted()), + }; + let id = SharedString::from(format!("activity-status-{lead}")); + div() + .id(id.clone()) + .debug_selector(move || id.to_string()) + .role(gpui::Role::Status) + .aria_label(tr(key)) + .text_xs() + .text_color(gpui::rgb(ink)) + .child(gpui::text!(tr(key))) + }); + let debug = format!("activity-chunk-{lead}"); + let target = chat.clone(); + let key = lead.to_owned(); + div() + .flex() + .when(!open, |row| row.pb_2()) + .items_start() + .child( + div() + .id(SharedString::from(format!("activity-toggle-{lead}"))) + .debug_selector(move || debug.clone()) + .role(gpui::Role::DisclosureTriangle) + .aria_label(label.clone()) + .aria_expanded(open) + .tab_index(0) + .on_key_down(ChatScreen::sidebar_button_key_down) + .focus_visible(widgets::focus_ring) + .min_h(px(32.)) + .max_w_full() + .px_2() + .ml(px(-8.)) + .rounded(theme::RADIUS_SM) + .flex() + .flex_wrap() + .items_center() + .gap_2p5() + .text_sm() + .text_color(gpui::rgb(theme::text_secondary())) + .hover_bg(theme::overlay_hover()) + .hover(|style| { + style + .cursor_pointer() + .text_color(gpui::rgb(theme::text_primary())) + }) + .child( + div() + .w(step::NODE) + .flex() + .justify_center() + .child(motion::chevron( + SharedString::from(format!("activity-chevron-{lead}")), + open, + px(14.), + theme::text_muted(), + )), + ) + .child(gpui::text!(label)) + .child( + div().flex().gap_1p5().children( + chunk + .icons + .iter() + .map(|(name, _)| icon(name, px(12.), theme::text_muted())), + ), + ) + .children(status) + .on_click(move |_, _, cx| { + target + .update(cx, |chat, cx| chat.toggle_chunk(&key, cx)) + .ok(); + }), + ) } impl ChatScreen { @@ -460,8 +649,8 @@ impl ChatScreen { /// earlier one, and the line waits in the slot instead. A window that /// is paged back in history, or still lacks the run's newest rows, /// does not hold the turn the run works on at all. - fn turn_runs(&self, lead: usize) -> bool { - self.turns.tail() == Some(lead) + pub(super) fn turn_runs(&self, lead: usize) -> bool { + self.turns.tail().is_some_and(|turn| lead >= turn) && self.is_run_active() && !self.awaiting_first_token && !self.pages.after @@ -506,25 +695,24 @@ impl ChatScreen { } } - /// Whether the steps of the turn led by the row at `lead` show. "Show - /// tool call details" opens every turn; a click on the line inverts - /// that for its turn. - pub(super) fn turn_open(&self, lead: usize) -> bool { + /// The existing details preference is the default; a click changes + /// only this chunk, including while more steps arrive in it. + pub(super) fn chunk_open(&self, lead: usize) -> bool { self.timeline .get(lead) - .is_some_and(|item| self.tool_details != self.toggled_turns.contains(&item.id)) + .is_some_and(|item| self.tool_details != self.toggled_chunks.contains(&item.id)) } - /// Show or fold a turn's steps and re-measure their rows. - pub(super) fn toggle_turn(&mut self, lead_id: &str, cx: &mut Context) { + /// Show or fold one chunk and re-measure only its rows. + pub(super) fn toggle_chunk(&mut self, lead_id: &str, cx: &mut Context) { let Some(&(lead, _)) = self.timeline_index.get(lead_id) else { return; }; - if !self.toggled_turns.remove(lead_id) { - self.toggled_turns.insert(lead_id.to_owned()); + if !self.toggled_chunks.remove(lead_id) { + self.toggled_chunks.insert(lead_id.to_owned()); } - let open = self.turn_open(lead); - self.row_motion.disclose_turn(lead_id, open, motion::now()); + let open = self.chunk_open(lead); + self.row_motion.disclose_chunk(lead_id, open, motion::now()); if !open { self.keep_application_selection_shown(lead); } else if self.list_state.is_following_tail() @@ -637,8 +825,8 @@ impl ChatScreen { /// A live row took its persisted id; what was kept under the old one /// follows it. pub(super) fn rekey_turn(&mut self, old: &str, new: &str) { - if self.toggled_turns.remove(old) { - self.toggled_turns.insert(new.to_owned()); + if self.toggled_chunks.remove(old) { + self.toggled_chunks.insert(new.to_owned()); } if let Some(worked) = self.turn_worked.remove(old) { self.turn_worked.insert(new.to_owned(), worked); @@ -701,11 +889,14 @@ mod tests { } #[test] - fn a_turn_folds_its_later_steps_under_its_first() { + fn messages_split_chunks_without_splitting_the_turn() { let timeline = [ item("message", Some("user")), item("thinking", None), - item("message", Some("assistant")), + AgentTimelineItem { + text: Some("Checking the remaining files.".into()), + ..item("message", Some("assistant")) + }, item("tool", None), item("error", None), item("message", Some("user")), @@ -721,15 +912,15 @@ mod tests { TurnRow::Plain, TurnRow::Lead, TurnRow::Plain, - TurnRow::Step(1), + TurnRow::Chunk, TurnRow::Plain, TurnRow::Plain, TurnRow::Plain, TurnRow::Lead, ] ); - // The first turn ends at its last step, not at the error after it. - assert_eq!(turns.end(1), 4); + assert_eq!(turns.end(1), 2); + assert_eq!(turns.end(3), 4); assert_eq!(turns.end(7), 8); assert_eq!(turns.tail(), Some(7)); } @@ -758,6 +949,103 @@ mod tests { assert_eq!(live.tail(), None); } + #[test] + fn hidden_plans_do_not_split_activity_and_status_updates_stay_in_their_chunk() { + let done = AgentTimelineItem { + status: Some("completed".into()), + ..item("tool", None) + }; + let plan = AgentTimelineItem { + input: Some(serde_json::json!({"todos": [{"text": "Read", "status": "pending"}]})), + ..item("tool", None) + }; + let mut turns = Turns::default(); + turns.rebuild(&[done.clone(), plan, done.clone()]); + assert_eq!(turns.row(2), TurnRow::Step(0)); + let chunk = turns.chunk(0).unwrap(); + assert_eq!(chunk.count(), 2); + assert_eq!(chunk.state(true), None); + let failed = AgentTimelineItem { + status: Some("failed".into()), + ..done.clone() + }; + assert_eq!( + turns.update_step(2, step_info(&done), step_info(&failed)), + Some(0) + ); + assert_eq!( + turns.chunk(0).unwrap().state(false), + Some(step::StepState::Failed) + ); + turns.update_step(2, step_info(&failed), step_info(&done)); + assert_eq!(turns.chunk(0).unwrap().state(false), None); + assert_eq!(turns.chunk(0).unwrap().count(), 2); + turns.push(&AgentTimelineItem { + input: Some(serde_json::json!({"todos": [{"text": "Read", "status": "completed"}]})), + ..item("tool", None) + }); + assert_eq!(turns.chunk(0).unwrap().count(), 3); + assert!( + turns + .chunk(0) + .unwrap() + .icons + .iter() + .any(|(icon, _)| *icon == "check") + ); + } + + #[test] + fn empty_messages_and_internal_rows_do_not_split_activity_chunks() { + let mut timeline = [ + item("tool", None), + AgentTimelineItem { + text: Some("\n\n".into()), + ..item("message", Some("assistant")) + }, + item("internal", None), + item("tool", None), + ]; + let mut turns = Turns::default(); + turns.rebuild(&timeline); + assert_eq!(turns.row(3), TurnRow::Step(0)); + assert_eq!(turns.chunk(0).unwrap().count(), 2); + let before = part(&timeline[1]); + timeline[1].text = Some("Now checking the result.".into()); + assert_ne!(before, part(&timeline[1])); + turns.rebuild(&timeline); + assert_eq!(turns.row(3), TurnRow::Chunk); + assert_eq!(turns.chunk(0).unwrap().count(), 1); + assert_eq!(turns.tail(), Some(0)); + } + + #[test] + fn finished_thinking_clears_its_chunk_status_during_a_live_turn() { + let thinking = item("thinking", None); + let mut turns = Turns::default(); + turns.push(&thinking); + assert_eq!( + turns.chunk(0).unwrap().state(true), + Some(step::StepState::Running) + ); + let done = AgentTimelineItem { + text: Some("The next action is clear.".into()), + ..thinking.clone() + }; + turns.update_step(0, step_info(&thinking), step_info(&done)); + assert_eq!(turns.chunk(0).unwrap().state(true), None); + turns.push(&AgentTimelineItem { + text: Some("Applying the change.".into()), + ..item("message", Some("assistant")) + }); + turns.push(&item("tool", None)); + assert_eq!(turns.chunk(0).unwrap().state(true), None); + assert_eq!( + turns.chunk(2).unwrap().state(true), + Some(step::StepState::Running) + ); + } + #[test] fn the_clock_stops_while_a_question_waits() { let began = Instant::now(); diff --git a/apps/maple-agent/app/src/ui/timeline_labels.rs b/apps/maple-agent/app/src/ui/timeline_labels.rs index dc5f45079..993378bc6 100644 --- a/apps/maple-agent/app/src/ui/timeline_labels.rs +++ b/apps/maple-agent/app/src/ui/timeline_labels.rs @@ -27,19 +27,7 @@ pub(crate) fn title(item: &AgentTimelineItem, cache: &MessageCache) -> Option tr("runtime-timeline-builtin-read"), - "edit" => tr("runtime-timeline-builtin-edit"), - "write" => tr("runtime-timeline-builtin-write"), - "agent_start" => tr("runtime-timeline-agent-start"), - "agent_send" => tr("runtime-timeline-agent-send"), - "agent_status" => tr("runtime-timeline-agent-status"), - "agent_cancel" => tr("runtime-timeline-agent-cancel"), - "list_agent_providers" => tr("runtime-timeline-agent-providers"), - _ => return None, - }) - })?; + let name = tool_name(item, cache)?; match &label.detail { Some(detail) => cache.get( "runtime-timeline-tool-detail", @@ -111,6 +99,24 @@ pub(crate) fn body(item: &AgentTimelineItem, cache: &MessageCache) -> Option Option { + tool_label(item, cache).or_else(|| { + let label = item.label.as_ref().filter(|label| label.kind == "tool")?; + Some(match label.name.as_deref()? { + "read" => tr("runtime-timeline-builtin-read"), + "edit" => tr("runtime-timeline-builtin-edit"), + "write" => tr("runtime-timeline-builtin-write"), + "agent_start" => tr("runtime-timeline-agent-start"), + "agent_send" => tr("runtime-timeline-agent-send"), + "agent_status" => tr("runtime-timeline-agent-status"), + "agent_cancel" => tr("runtime-timeline-agent-cancel"), + "list_agent_providers" => tr("runtime-timeline-agent-providers"), + _ => return None, + }) + }) +} + pub(crate) fn tool_label(item: &AgentTimelineItem, _cache: &MessageCache) -> Option { let label = item.label.as_ref()?; if label.kind != "tool" { diff --git a/apps/maple-agent/app/translation-revisions/de.txt b/apps/maple-agent/app/translation-revisions/de.txt index f2fd49ea9..6793328af 100644 --- a/apps/maple-agent/app/translation-revisions/de.txt +++ b/apps/maple-agent/app/translation-revisions/de.txt @@ -2,6 +2,7 @@ chat-absolute-path a2ba378ac24704c4 chat-active 196d1c9462f99ad3 chat-activity-outside dc914a2d8037659c +chat-activity-steps a12bb21490dd0f51 chat-agent-task-cancelled e26bb0917a4c240b chat-agents-running 15f7861d7b1f2dc3 chat-all-settings f521b783e34e05d0 @@ -354,7 +355,6 @@ chat-staging-unsafe-directory 13ed7aa88e08c0a8 chat-starting f00ec83fc396c4b0 chat-starting-agent 0e61b8da983ef787 chat-status-allowed 11310a7438dc9e0c -chat-status-completed f7f8f9dd4adb3a0c chat-status-denied deee947bb13482c4 chat-status-done 54904e435ce0c52e chat-status-failed 3aa7979f86ebefa0 diff --git a/apps/maple-agent/app/translation-revisions/es.txt b/apps/maple-agent/app/translation-revisions/es.txt index f2fd49ea9..6793328af 100644 --- a/apps/maple-agent/app/translation-revisions/es.txt +++ b/apps/maple-agent/app/translation-revisions/es.txt @@ -2,6 +2,7 @@ chat-absolute-path a2ba378ac24704c4 chat-active 196d1c9462f99ad3 chat-activity-outside dc914a2d8037659c +chat-activity-steps a12bb21490dd0f51 chat-agent-task-cancelled e26bb0917a4c240b chat-agents-running 15f7861d7b1f2dc3 chat-all-settings f521b783e34e05d0 @@ -354,7 +355,6 @@ chat-staging-unsafe-directory 13ed7aa88e08c0a8 chat-starting f00ec83fc396c4b0 chat-starting-agent 0e61b8da983ef787 chat-status-allowed 11310a7438dc9e0c -chat-status-completed f7f8f9dd4adb3a0c chat-status-denied deee947bb13482c4 chat-status-done 54904e435ce0c52e chat-status-failed 3aa7979f86ebefa0 diff --git a/apps/maple-agent/app/translation-revisions/ko.txt b/apps/maple-agent/app/translation-revisions/ko.txt index f2fd49ea9..6793328af 100644 --- a/apps/maple-agent/app/translation-revisions/ko.txt +++ b/apps/maple-agent/app/translation-revisions/ko.txt @@ -2,6 +2,7 @@ chat-absolute-path a2ba378ac24704c4 chat-active 196d1c9462f99ad3 chat-activity-outside dc914a2d8037659c +chat-activity-steps a12bb21490dd0f51 chat-agent-task-cancelled e26bb0917a4c240b chat-agents-running 15f7861d7b1f2dc3 chat-all-settings f521b783e34e05d0 @@ -354,7 +355,6 @@ chat-staging-unsafe-directory 13ed7aa88e08c0a8 chat-starting f00ec83fc396c4b0 chat-starting-agent 0e61b8da983ef787 chat-status-allowed 11310a7438dc9e0c -chat-status-completed f7f8f9dd4adb3a0c chat-status-denied deee947bb13482c4 chat-status-done 54904e435ce0c52e chat-status-failed 3aa7979f86ebefa0 diff --git a/apps/maple-agent/docs/motion.md b/apps/maple-agent/docs/motion.md index 0ae290a0e..9a3f93ecc 100644 --- a/apps/maple-agent/docs/motion.md +++ b/apps/maple-agent/docs/motion.md @@ -85,13 +85,13 @@ the shared 15 fps `ticker` clock and pause in background windows. | Screen change (Chat ↔ Settings) and Settings sections | new content fades in, `REVEAL` | immediate | | Empty state ↔ conversation (first message, opening a task, New Task) | the composer changes place at once | at once | | Switching tasks | transcript fades in when its snapshot lands, `REVEAL` | immediate | -| Live transcript rows at the end of the thread (sent message, reply, thinking, tool card, error, stop notice) | height grows from 0 and the row fades in, `ENTER`, so older rows glide up; scrolled up, a fade and 6 px rise | — | +| Live transcript rows at the end of the thread (sent message, reply, thinking, tool call, error, stop notice) | height grows from 0 and the row fades in, `ENTER`, so older rows glide up; scrolled up, a fade and 6 px rise | — | | Sent message | the composer empties at once and the bubble's slot opens from the height it gave up, so the thread does not drop; the bubble rises in, the real row takes its exact place, and "Sending…" and the turn's line share one slot under it | — | -| Tool status | spinner leaves at once, the outcome fades in, `TOGGLE` | — | +| A step's state | a running step is dim and inks at once when it finishes; nothing on it loops, the turn's line carries the motion | — | | Disclosed details (tool output, thinking) | fade in, `REVEAL` | immediate | | Streaming text | grows in place, no animation | — | | A turn's line ("Maple is thinking", "Worked for 11s") | fades in under the transcript, `REVEAL`, and keeps its place when the turn's first step takes it into the list; while Maple works a shine crosses the words and the mark's blocks shrink and grow one at a time all the way around the M's outline, never both shining; the words morph when they change and the time counts whole seconds | immediate | -| A turn's steps, shown from its line | fade in, `REVEAL`; the chevron turns, `TOGGLE` | immediate | +| Activity chunks between visible messages, shown from their inline headers | fade in independently, `REVEAL`; each chevron turns, `TOGGLE` | immediate | | Notices, queued messages, cards above the composer | fade and rise, `ENTER` | immediate | | Files attached to the draft | fade and 6 px rise, `ENTER` | immediate | | Composer and multi-line fields | height eases to the new line count, `resize(distance)` | same | @@ -103,6 +103,12 @@ the shared 15 fps `ticker` clock and pause in background windows. | Sidebar collapse | width eases, `PANEL` | same, reversed | | Task status in the sidebar, project folders | indicators and folder icons cross-fade, `TOGGLE` | same | +The turn's line stays informational and keeps one clock for the whole turn. +Each activity chunk has its own disclosure; folding one leaves the other +chunks and the assistant's explanations alone. Tool details keep their own +disclosure state. Chunk headers use the same hover and chevron motion as +other controls; they do not add another looping indicator. + Loading spinners for work that usually finishes quickly (opening a task) appear only after 300 ms, so fast loads never flash a spinner.