diff --git a/apps/maple-agent/app/locales/de/app.ftl b/apps/maple-agent/app/locales/de/app.ftl index 3d38f3e8b..3ed977574 100644 --- a/apps/maple-agent/app/locales/de/app.ftl +++ b/apps/maple-agent/app/locales/de/app.ftl @@ -1599,6 +1599,14 @@ chat-permission-reason-uncertain = Maple ist nicht sicher, ob diese Aktion siche chat-permission-reason-unavailable = Maple konnte diese Aktion nicht prüfen. chat-permission-reason-too-long = Diese Aktion ist zu lang, um von Maple geprüft zu werden. chat-thinking-label = Maple denkt nach +chat-turn-working = Maple arbeitet +chat-turn-writing = Maple schreibt +chat-turn-waiting = Wartet auf dich +chat-turn-worked = Gearbeitet +# $seconds is a whole number of seconds, under 60. +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 chat-settings = Einstellungen chat-usage = Nutzung chat-usage-unavailable = Nutzung nicht verfügbar diff --git a/apps/maple-agent/app/locales/en/app.ftl b/apps/maple-agent/app/locales/en/app.ftl index 5cdced0e0..b527b2ead 100644 --- a/apps/maple-agent/app/locales/en/app.ftl +++ b/apps/maple-agent/app/locales/en/app.ftl @@ -1599,6 +1599,14 @@ chat-permission-reason-uncertain = Maple isn't sure this is safe to run. chat-permission-reason-unavailable = Maple couldn't check this action. chat-permission-reason-too-long = This action is too long for Maple to check. chat-thinking-label = Maple is thinking +chat-turn-working = Maple is working +chat-turn-writing = Maple is writing +chat-turn-waiting = Waiting for you +chat-turn-worked = Worked +# $seconds is a whole number of seconds, under 60. +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 chat-settings = Settings chat-usage = Usage chat-usage-unavailable = Usage unavailable diff --git a/apps/maple-agent/app/locales/es/app.ftl b/apps/maple-agent/app/locales/es/app.ftl index d1ed75bfe..54caa6549 100644 --- a/apps/maple-agent/app/locales/es/app.ftl +++ b/apps/maple-agent/app/locales/es/app.ftl @@ -1486,6 +1486,14 @@ chat-permission-reason-uncertain = Maple no está seguro de que sea seguro ejecu chat-permission-reason-unavailable = Maple no pudo revisar esta acción. chat-permission-reason-too-long = Esta acción es demasiado larga para que Maple la revise. chat-thinking-label = Maple está pensando +chat-turn-working = Maple está trabajando +chat-turn-writing = Maple está escribiendo +chat-turn-waiting = Esperando tu respuesta +chat-turn-worked = Trabajó +# $seconds is a whole number of seconds, under 60. +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 chat-settings = Configuración chat-usage = Uso chat-usage-unavailable = Uso no disponible diff --git a/apps/maple-agent/app/locales/ko/app.ftl b/apps/maple-agent/app/locales/ko/app.ftl index bffa581fe..9278b72a7 100644 --- a/apps/maple-agent/app/locales/ko/app.ftl +++ b/apps/maple-agent/app/locales/ko/app.ftl @@ -1545,6 +1545,14 @@ chat-permission-reason-uncertain = Maple이 이 동작의 안전 여부를 확 chat-permission-reason-unavailable = Maple이 이 동작을 검사하지 못했어요. chat-permission-reason-too-long = 이 동작은 너무 길어 Maple이 검사할 수 없어요. chat-thinking-label = Maple이 생각하는 중이에요 +chat-turn-working = Maple이 작업하는 중이에요 +chat-turn-writing = Maple이 작성하는 중이에요 +chat-turn-waiting = 응답을 기다리고 있어요 +chat-turn-worked = 작업 완료 +# $seconds is a whole number of seconds, under 60. +chat-turn-worked-seconds = { $seconds }초 동안 작업했어요 +# $minutes is a whole number of minutes; $seconds is the rest, under 60. +chat-turn-worked-minutes = { $minutes }분 { $seconds }초 동안 작업했어요 chat-settings = 설정 chat-usage = 사용량 chat-usage-unavailable = 사용량을 확인할 수 없음 diff --git a/apps/maple-agent/app/src/ui/chat/mod.rs b/apps/maple-agent/app/src/ui/chat/mod.rs index 565fa2bdd..2dbf9527d 100644 --- a/apps/maple-agent/app/src/ui/chat/mod.rs +++ b/apps/maple-agent/app/src/ui/chat/mod.rs @@ -55,6 +55,7 @@ mod summaries; mod tests; mod thinking; mod transcript; +mod turn; #[cfg(test)] mod upload_tests; mod uploads; @@ -68,7 +69,6 @@ use self::sidebar::SessionActivity; use self::sidebar::{Sidebar, SidebarEvent, TaskActivity, session_summary_eq}; use self::transcript::{ ActiveSubagent, PlanEntry, PlanStatus, plan_entries, plan_finished, render_question_card, - render_waiting_indicator, }; gpui::actions!( @@ -655,11 +655,11 @@ pub struct ChatScreen { snapshot_revision: u64, /// Virtualized transcript state; bottom-aligned like a chat log. list_state: gpui::ListState, - /// First and past-last transcript rows painted in view in the last - /// frame. A wheel outside the list reports them for paging and - /// images, as the list's own wheel reports its visible range; the - /// list's scroll top names no row while it rests at the end. - painted_rows: std::rc::Rc>>, + /// The transcript rows painted in view in the last frame. A wheel + /// outside the list reports them for paging and images, as the list's + /// own wheel reports its visible range; the list's scroll top names no + /// row while it rests at the end. + painted_rows: transcript::PaintedRows, /// Set when the transcript should jump to its newest content on the /// next render (session switch or send); streaming follows only while /// the view is already at the bottom. @@ -833,8 +833,8 @@ pub struct ChatScreen { /// Focus handle of the transcript; a selection press moves focus here /// so the copy keybinding applies. transcript_focus: Option, - /// True from send until the first agent item of the run arrives; shows - /// the waiting indicator under the transcript. + /// True from send until the first agent item of the run arrives. The + /// turn's line waits under the transcript meanwhile. awaiting_first_token: bool, /// Live row entrances and reveals in the transcript, kept here so a /// row scrolled away and back never replays them. @@ -845,6 +845,18 @@ pub struct ChatScreen { /// Item ids whose tool card or thinking row was clicked; membership /// inverts the `tool_details` default for that item. 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, + /// How long finished turns worked, by lead item id. Only turns this + /// window timed have one. + turn_worked: HashMap, + /// 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. + run_tick_pending: std::cell::Cell, /// Ticked options of a multi-select question. question_selected: HashMap, /// Index of the question being shown within the current card; a batch @@ -1143,6 +1155,7 @@ impl ChatScreen { /// tasks wait, run, or ended unseen, and the recent roots. Called when /// any of them changed; the sidebar rebuilds only what moved. fn sync_sidebar(&mut self, cx: &mut Context) { + self.sync_run_clocks(); let sessions = self.sessions.clone(); let selected = self.sidebar_selection(); let activity = self.task_activity(); @@ -1159,6 +1172,7 @@ impl ChatScreen { /// Push only the row indicators: a question arrived or went away. /// Other computers' sidebars show them too. fn sync_sidebar_activity(&mut self, cx: &mut Context) { + self.sync_run_clocks(); let activity = self.task_activity(); self.sidebar .update(cx, |sidebar, cx| sidebar.set_activity(activity, cx)); @@ -1680,6 +1694,11 @@ impl ChatScreen { row_motion: transcript::RowMotion::default(), loading_since: None, toggled_tools: HashSet::new(), + turns: turn::Turns::default(), + toggled_turns: HashSet::new(), + turn_worked: HashMap::new(), + run_clocks: HashMap::new(), + run_tick_pending: std::cell::Cell::new(false), question_selected: HashMap::new(), question_step: 0, question_step_answers: HashMap::new(), @@ -3469,6 +3488,7 @@ impl ChatScreen { self.timeline = timeline.into_iter().map(paging::normalize).collect(); self.pages.weights.clear(); self.bound_transcript_window(true); + self.turns.rebuild(&self.timeline); self.timeline_index = self .timeline .iter() @@ -3757,6 +3777,8 @@ impl ChatScreen { self.attachment_queue.clear(); self.attachment_viewport = 0..0; self.toggled_tools.clear(); + self.toggled_turns.clear(); + self.turn_worked.clear(); if let Some(composer) = self.composer.clone() { composer.update(cx, |input, cx| input.reset_vim_context(cx)); } @@ -6257,6 +6279,11 @@ impl ChatScreen { // needs a fresh bounded open, so keep Reload latest available even // after paging reaches the committed tail. self.pages.live_has_more = true; + // A row the view did not take in: the run can no longer be + // timed, as when its task is not the one on screen. + if let Some(timed) = self.run_clocks.get_mut(session_id) { + timed.stop_timing(); + } return None; } if let Some(index) = alias_index @@ -6278,6 +6305,7 @@ impl ChatScreen { self.timeline_index.insert(item.id.clone(), (index, 0)); self.rekey_summary(&old, &item.id); self.row_motion.rekey(&old, &item.id); + self.rekey_turn(&old, &item.id); } if let Some((index, _)) = self.timeline_index.get(&item.id) && let (Some(old), Some(new)) = (&self.timeline[*index].persisted, &item.persisted) @@ -6326,6 +6354,7 @@ impl ChatScreen { .. } = item; let existing = &mut self.timeline[index]; + let part = turn::part(existing); existing.revision = incoming_revision; if let Some(label) = incoming_label { match &mut existing.label { @@ -6361,6 +6390,12 @@ 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()); + } index } None => { @@ -6371,8 +6406,10 @@ impl ChatScreen { motion::now(), self.list_state.is_following_tail(), ); + self.turns.push(&item); self.timeline.push(item); self.list_state.splice(index..index, 1); + self.time_arrival(session_id, index); index } }; @@ -6441,7 +6478,7 @@ impl ChatScreen { } /// Whether the slot under the transcript shows something: the message - /// being sent or the waiting dots. + /// being sent or the turn's line. fn waiting_slot_shown(&self) -> bool { self.has_send_feedback() || (self.awaiting_first_token && self.is_run_active()) } @@ -6466,7 +6503,7 @@ impl ChatScreen { let Some(index) = self.apply_timeline_item(session_id, item) else { return; }; - // The waiting row (or the sent message's status) leaves the slot + // The turn's line (or the sent message's status) leaves the slot // under the transcript as this row arrives: the row opens from that // height, so nothing above it jumps. if new_row && self.row_motion.slot_on_screen && !self.waiting_slot_shown() { @@ -7119,6 +7156,11 @@ impl ChatScreen { .timeline_revisions .entry(session_id.to_string()) .or_insert(0) += 1; + // A run whose rows this view did not take in is no longer one it + // can time: it cannot tell where the run's turns began. + if let Some(timed) = self.run_clocks.get_mut(session_id) { + timed.stop_timing(); + } } /// Drop every queued question of a session whose run ended. @@ -7154,6 +7196,7 @@ impl ChatScreen { AgentRunEvent::Started => { self.active_runs .insert(session_id.to_string(), run_id.to_string()); + self.run_began(session_id, run_id, cx); // The sections read `active_runs`; keep them in step. self.sync_sidebar(cx); self.start_usage_poller(session_id.to_string(), cx); @@ -7279,7 +7322,7 @@ impl ChatScreen { self.clear_session_questions(session_id, cx); } if self.is_selected(session_id) { - // Another task finishing must not hide the dots for + // Another task finishing must not hide the line for // the send that is still waiting here. self.awaiting_first_token = false; self.refresh_context_usage(cx); @@ -8462,10 +8505,6 @@ impl ChatScreen { }, )), ) - .when( - self.awaiting_first_token && self.is_run_active(), - |column| column.child(div().mt_6().child(render_waiting_indicator())), - ) .children(privacy) .when_some(self.runtime_error.clone(), |column, error| { column.child(widgets::banner(widgets::Tone::Error, error).mt_6()) diff --git a/apps/maple-agent/app/src/ui/chat/navigation.rs b/apps/maple-agent/app/src/ui/chat/navigation.rs index 9e1a842f9..e09ba6082 100644 --- a/apps/maple-agent/app/src/ui/chat/navigation.rs +++ b/apps/maple-agent/app/src/ui/chat/navigation.rs @@ -14,6 +14,7 @@ use super::ChatScreen; use super::commands::ChatCommand; use super::composer::ComposerControl; use super::transcript::{PlanStatus, attachment_refs, has_tool_input, plan_entries, plan_finished}; +use super::turn::TurnRow; use crate::ui::application_vim::{self, CountOutcome, CountState, SpatialDirection}; use crate::ui::i18n::UiText; use crate::ui::text_input::vim::VimMode; @@ -660,6 +661,11 @@ 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); + return; + } let Some(item) = self.timeline.get(index) else { return; }; @@ -704,6 +710,15 @@ 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 + && (expanded || !current) + { + self.toggle_turn(item_id, cx); + return; + } if current != expanded { if !self.toggled_tools.insert(item_id.to_owned()) { self.toggled_tools.remove(item_id); @@ -782,11 +797,42 @@ impl ChatScreen { pub(super) fn navigable_timeline_ids(&self) -> Vec { self.timeline .iter() - .filter(|item| timeline_item_is_navigable(item)) - .map(|item| item.id.clone()) + .enumerate() + .filter(|(index, item)| self.timeline_row_navigable(*index, item)) + .map(|(_, item)| item.id.clone()) .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. + 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::Plain => timeline_item_is_navigable(item), + } + } + + /// A turn folded: a selection on one of its steps moves to its line. + pub(super) fn keep_application_selection_shown(&mut self, lead: usize) { + if !self.application_vim_enabled { + return; + } + let Some(task_id) = self.selected_session.clone() else { + return; + }; + let hidden = self + .selected_transcript_id() + .and_then(|id| self.timeline_index.get(id)) + .is_some_and(|(index, _)| self.turns.row(*index) == TurnRow::Step(lead)); + if hidden && let Some(item) = self.timeline.get(lead) { + self.application_vim + .transcript_by_task + .insert(task_id, item.id.clone()); + } + } + fn ensure_transcript_application_selection(&mut self) { let ids = self.navigable_timeline_ids(); let Some(task_id) = self.selected_session.clone() else { @@ -935,8 +981,10 @@ impl ChatScreen { let newest = self .timeline .iter() + .enumerate() .rev() - .find(|item| timeline_item_is_navigable(item)); + .find(|(index, item)| self.timeline_row_navigable(*index, item)) + .map(|(_, item)| item); if let Some(item) = newest { self.application_vim .transcript_by_task @@ -962,10 +1010,11 @@ impl ChatScreen { cx: &mut Context, ) { if !self.application_vim_enabled - || !self - .timeline - .iter() - .any(|item| item.id == item_id && timeline_item_is_navigable(item)) + || !self.timeline_index.get(item_id).is_some_and(|(index, _)| { + self.timeline + .get(*index) + .is_some_and(|item| self.timeline_row_navigable(*index, item)) + }) { return; } diff --git a/apps/maple-agent/app/src/ui/chat/paging.rs b/apps/maple-agent/app/src/ui/chat/paging.rs index 9fee4edb1..5b2f9f031 100644 --- a/apps/maple-agent/app/src/ui/chat/paging.rs +++ b/apps/maple-agent/app/src/ui/chat/paging.rs @@ -259,6 +259,11 @@ impl ChatScreen { .enumerate() .map(|(i, item)| (item.id.clone(), (i, 0))) .collect(); + self.turns.rebuild(&self.timeline); + self.toggled_turns + .retain(|id| self.timeline_index.contains_key(id)); + self.turn_worked + .retain(|id, _| self.timeline_index.contains_key(id)); self.markdown_cache.clear(); self.derived.clear(); self.messages = Default::default(); diff --git a/apps/maple-agent/app/src/ui/chat/sending.rs b/apps/maple-agent/app/src/ui/chat/sending.rs index f5ae5c275..4704bccd6 100644 --- a/apps/maple-agent/app/src/ui/chat/sending.rs +++ b/apps/maple-agent/app/src/ui/chat/sending.rs @@ -294,6 +294,7 @@ impl ChatScreen { self.acknowledge_send_preview(&send_id, &run_id); // A short run can finish before admission returns. if !self.finished_runs.contains(&run_id) { + self.run_began(&session, &run_id, cx); self.active_runs.insert(session, run_id); self.sync_sidebar(cx); } @@ -355,7 +356,7 @@ impl ChatScreen { /// The message being sent, under the transcript. Its bubble rises in /// from the moment it shows; the status line under it fades in once, - /// in the slot the waiting dots use, so the real row that takes over + /// in the slot a turn's line waits in, so the real row that takes over /// lands where the bubble was. pub(super) fn render_send_preview( &self, diff --git a/apps/maple-agent/app/src/ui/chat/tests.rs b/apps/maple-agent/app/src/ui/chat/tests.rs index 82863eef0..1f4873aeb 100644 --- a/apps/maple-agent/app/src/ui/chat/tests.rs +++ b/apps/maple-agent/app/src/ui/chat/tests.rs @@ -10548,7 +10548,7 @@ mod state_tests { } #[gpui::test] - fn test_another_task_finishing_keeps_the_waiting_dots(cx: &mut TestAppContext) { + fn test_another_task_finishing_keeps_the_waiting_line(cx: &mut TestAppContext) { cx.executor().allow_parking(); let screen = screen(cx); screen.update(cx, |this, cx| { @@ -12715,6 +12715,83 @@ 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. + #[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; + chat.replace_timeline(vec![ + user_item("u1", "question"), + item("call", "tool", None), + item("thought", "thinking", Some("reasoning")), + item("a1", "message", Some("answer")), + ]); + chat + }); + 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)) + }; + + assert_eq!(rows(cx), ["u1", "call", "a1"], "folded steps are skipped"); + cx.simulate_keystrokes("g g j l"); + assert_eq!(rows(cx), ["u1", "call", "thought", "a1"]); + 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)); + assert_eq!(selected(cx).as_deref(), Some("call")); + + cx.simulate_keystrokes("l"); + assert_eq!( + rows(cx).len(), + 4, + "the line opens before its step's details" + ); + cx.simulate_keystrokes("h"); + assert_eq!( + rows(cx), + ["u1", "call", "a1"], + "h on the line folds the turn" + ); + } + #[gpui::test] fn test_application_vim_escape_assistant_focus_and_plain_command_count( cx: &mut TestAppContext, @@ -13486,6 +13563,8 @@ mod state_tests { .insert("tool-1".to_string(), SharedString::from(summary)); 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 }); diff --git a/apps/maple-agent/app/src/ui/chat/transcript.rs b/apps/maple-agent/app/src/ui/chat/transcript.rs index 0b195e64a..cdb4f52c3 100644 --- a/apps/maple-agent/app/src/ui/chat/transcript.rs +++ b/apps/maple-agent/app/src/ui/chat/transcript.rs @@ -17,6 +17,7 @@ use maple_agent::agent::{ use super::cache::{MAX_DIFF_LINES, MarkdownKind}; use super::speech::speak_message_button; +use super::turn::{self, TurnRow}; use super::{CONTENT_WIDTH, ChatScreen, QuestionSelection, TranscriptCtx}; use crate::ui::i18n::{MessageCache, tr}; @@ -48,6 +49,8 @@ impl ChatScreen { // frame only while one is still running. let now = motion::now(); let reduced = cx.reduce_motion(); + // Where loops hold still, a running turn's line rests too. + let still = motion::loops_paused(window, cx); if self.row_motion.settle(now, reduced) { window.request_animation_frame(); } @@ -69,138 +72,144 @@ impl ChatScreen { return div().into_any_element(); }; let chat = chat_entity.read(cx); + 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. + 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 { + return div().into_any_element(); + } // A row that arrived live enters, timed from view state so // scrolling it away and back never replays the entrance. - let entrance = chat - .timeline - .get(ix) - .and_then(|item| chat.row_motion.entrance(&item.id, now, reduced)); - let row = match chat.timeline.get(ix) { - Some(item) => { - let render_ctx = RenderCtx { - selection: selection.clone(), - base_ordinal: Some(chat.markdown_cache.ordinal_for(&item.id)), - focus: transcript_focus.clone(), - id_seed: item.id.clone(), - view: Some(window.current_view()), - }; - let transcript = TranscriptCtx { - messages: &chat.messages, - local_error_text: &chat.local_error_text, - markdown_cache: &chat.markdown_cache, - derived: &chat.derived, - attachment_images: &chat.attachment_images, - attachment_previews: &chat.attachment_previews, - attachment_failures: &chat.attachment_failures, - chat: &entity, - tool_summaries: &chat.tool_summaries, - render: &render_ctx, - speech: chat.speech.as_ref(), - speech_available: chat.audio_caps.speech, - position: (ix + 1, chat.timeline.len()), - reveal: chat.row_motion.disclosure(&item.id, now, reduced), - }; - let expanded = tool_details != chat.toggled_tools.contains(&item.id); - let revision = chat - .timeline_index - .get(&item.id) - .map_or(0, |(_, revision)| *revision); - let mut row = - div().child(render_timeline_item(item, revision, expanded, &transcript)); - if item.truncated.is_some() { - let id = item.id.clone(); - let target = entity.clone(); - row = row.child( - widgets::secondary_button(SharedString::from(format!( - "expand-{}", - item.id - ))) - .text_xs() - .mt_2() - .child(gpui::text!(tr("chat-full-output"))) - .on_click(move |_, _, cx| { - if let Some(chat) = target.upgrade() { - chat.update(cx, |chat, cx| chat.expand_paged_row(&id, cx)); - } - }), - ); - } - if !chat.application_vim_enabled { - row.into_any_element() - } else { - let application_selected = chat.application_vim_selects_timeline(&item.id); - let application_item_id = item.id.clone(); - let application_entity = entity.clone(); - div() - .on_mouse_down(gpui::MouseButton::Left, move |_event, window, cx| { - // A focusable control inside the row owns this - // press; keep its keyboard focus. - if window.default_prevented() { - return; - } - let Some(chat_entity) = application_entity.upgrade() else { - return; - }; - chat_entity.update(cx, |chat, cx| { - chat.select_timeline_from_pointer( - &application_item_id, - window, - cx, - ); - }); - }) - .when(application_selected, |row| { - row.rounded(theme::RADIUS_SM) - .border_l_2() - .border_color(gpui::rgb(theme::accent())) - }) - .child(row) - .into_any_element() - } + let entrance = chat.row_motion.entrance(&item.id, now, reduced); + let body = open.then(|| { + let render_ctx = RenderCtx { + selection: selection.clone(), + base_ordinal: Some(chat.markdown_cache.ordinal_for(&item.id)), + focus: transcript_focus.clone(), + id_seed: item.id.clone(), + view: Some(window.current_view()), + }; + let transcript = TranscriptCtx { + messages: &chat.messages, + local_error_text: &chat.local_error_text, + markdown_cache: &chat.markdown_cache, + derived: &chat.derived, + attachment_images: &chat.attachment_images, + attachment_previews: &chat.attachment_previews, + attachment_failures: &chat.attachment_failures, + chat: &entity, + tool_summaries: &chat.tool_summaries, + render: &render_ctx, + speech: chat.speech.as_ref(), + speech_available: chat.audio_caps.speech, + position: (ix + 1, chat.timeline.len()), + reveal: chat.row_motion.disclosure(&item.id, now, reduced), + }; + let expanded = tool_details != chat.toggled_tools.contains(&item.id); + let revision = chat + .timeline_index + .get(&item.id) + .map_or(0, |(_, revision)| *revision); + let mut row = + div().child(render_timeline_item(item, revision, expanded, &transcript)); + if item.truncated.is_some() { + let id = item.id.clone(); + let target = entity.clone(); + row = row.child( + widgets::secondary_button(SharedString::from(format!( + "expand-{}", + item.id + ))) + .text_xs() + .mt_2() + .child(gpui::text!(tr("chat-full-output"))) + .on_click(move |_, _, cx| { + if let Some(chat) = target.upgrade() { + chat.update(cx, |chat, cx| chat.expand_paged_row(&id, cx)); + } + }), + ); } - None => div().into_any_element(), - }; - // Only rows the list places in view are prepainted here; rows - // measured for overdraw are not, and a focused row kept alive - // off screen lands outside the mask. - let painted_rows = painted_rows.clone(); - let row = div() - .child(row) - .on_children_prepainted(move |bounds, window, _cx| { - let view = window.content_mask().bounds; - let on_screen = bounds - .first() - .is_some_and(|row| row.top() < view.bottom() && row.bottom() > view.top()); - if on_screen { - painted_rows.set(Some(match painted_rows.get() { - Some((start, end)) => (start.min(ix), end.max(ix + 1)), - None => (ix, ix + 1), - })); - } + // Steps the line just showed fade in, like any details + // the user opens. + let shown = lead.map_or(1., |lead| { + chat.row_motion + .turn_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 select = |row: Div| { + if !chat.application_vim_enabled { + return row; + } + let application_selected = chat.application_vim_selects_timeline(&item.id); + let application_item_id = item.id.clone(); + let application_entity = entity.clone(); + div() + .on_mouse_down(gpui::MouseButton::Left, move |_event, window, cx| { + // A focusable control inside the row owns this + // press; keep its keyboard focus. + if window.default_prevented() { + return; + } + let Some(chat_entity) = application_entity.upgrade() else { + return; + }; + chat_entity.update(cx, |chat, cx| { + chat.select_timeline_from_pointer(&application_item_id, window, cx); + }); + }) + .when(application_selected, |row| { + row.rounded(theme::RADIUS_SM) + .border_l_2() + .border_color(gpui::rgb(theme::accent())) + }) + .child(row) + }; + let track = |row: Div| track_row(row, ix, &painted_rows); + let enter = + |row: Div, entrance| enter_row(row, entrance, &item.id, &chat.row_motion.heights); + let Some(line) = line else { + return enter(track(select(body.unwrap_or_else(div))), entrance); + }; match entrance { - None => row.into_any_element(), - // Scrolled up: paint offset and opacity only, so nothing - // on screen moves. - Some(Entrance { - progress, - grow: None, - .. - }) => motion::arrive(row, progress).into_any_element(), - // At the tail: the row opens to its height and the rows - // above glide up with it. + // The line stood in the slot under the transcript until + // this row arrived. It keeps its place, and only what is + // under it opens. Some(Entrance { progress, grow: Some(grow), natural, - }) => grow_in( - row, - progress, - grow, - natural, - chat.row_motion.heights.clone(), - chat.timeline[ix].id.clone(), - ), + }) if grow.from >= WAITING_ROW_HEIGHT => { + let under = Entrance { + progress, + grow: Some(Grow { + from: grow.from - WAITING_ROW_HEIGHT, + ..grow + }), + natural, + }; + let body = body.map(|body| enter(body, Some(under))); + track(select(div().child(line).children(body))).into_any_element() + } + entrance => enter(track(select(div().child(line).children(body))), entrance), } }) .size_full(); @@ -262,7 +271,10 @@ impl ChatScreen { .max_w(CONTENT_WIDTH) .mx_auto() .px_6() - .pb_4() + // While a turn's line waits under the list, the + // padding sits under the line instead (see + // `render_under_transcript`). + .when(!self.line_in_slot(), |rows| rows.pb_4()) // Another task's transcript fades in when it lands. .when(switch_reveal < 1., |rows| { rows.opacity(motion::ease_out_quint(switch_reveal)) @@ -353,7 +365,7 @@ impl ChatScreen { } // The list's own wheel reports the rows it last painted, also at // the end where its scroll top names no row; report the same. - if let Some((start, end)) = self.painted_rows.get() { + if let Some((start, end, _)) = self.painted_rows.get() { self.transcript_scrolled(start, end, cx); } } @@ -392,7 +404,7 @@ impl ChatScreen { } /// The slot under the transcript: the message being sent with its - /// status line, or the waiting dots, both `WAITING_ROW_HEIGHT` tall so + /// status line, or the turn's line, both `WAITING_ROW_HEIGHT` tall so /// one taking over from the other moves nothing. /// /// It sits outside the list, so its height is taken from the list's @@ -412,9 +424,18 @@ impl ChatScreen { // up; a slot that appears later opens from nothing. let freed = std::mem::take(&mut self.row_motion.slot_from).as_f32(); let preview = self.render_send_preview(window, cx); - let dots = self.awaiting_first_token && self.is_run_active() && !self.has_send_feedback(); + let reduced = cx.reduce_motion(); + // Until the turn has a step to carry it, its line waits here. + let line = self.line_in_slot().then(|| { + turn::render_line( + self.live_line(motion::loops_paused(window, cx)), + None, + &cx.entity().downgrade(), + &self.messages, + ) + }); let slot = &mut self.row_motion; - slot.slot_on_screen = preview.is_some() || dots; + slot.slot_on_screen = preview.is_some() || line.is_some(); if !slot.slot_on_screen { slot.slot_open = None; slot.slot_natural.set(None); @@ -422,7 +443,6 @@ impl ChatScreen { return None; } let now = motion::now(); - let reduced = cx.reduce_motion(); // Measured last frame; `None` on the frame it appears. let natural = slot.slot_natural.get().map(f32::from); if reduced { @@ -477,46 +497,56 @@ impl ChatScreen { }; let natural_height = slot.slot_natural.clone(); let shown_height = slot.slot_shown.clone(); + let lined = line.is_some(); let content = div() .flex_none() .w_full() .flex() .flex_col() .children(preview) - .when(dots, |content| { - // Same gutter as transcript text so the dots line up. - content.child( - div() - .w_full() - .max_w(CONTENT_WIDTH) - .mx_auto() - .px_6() - .child(render_waiting_indicator()), - ) + // Same gutter as the transcript's rows. + .children(line.map(|line| { + div() + .w_full() + .max_w(CONTENT_WIDTH) + .mx_auto() + .px_6() + .child(motion::fade_in(line, "waiting-indicator-reveal")) + })); + let under = div() + .flex_none() + .w_full() + .flex() + .flex_col() + .justify_end() + .overflow_hidden() + .when_some(cap, |slot, cap| slot.max_h(cap)) + .child(content) + .on_children_prepainted(move |bounds, _, _| { + if let Some(content) = bounds.first() { + let height = content.size.height; + natural_height.set(Some(height)); + shown_height.set(cap.map_or(height, |cap| height.min(cap))); + } }); + if !lined { + return Some(under.into_any_element()); + } + // The transcript's bottom padding sits under the waiting line, not + // over it: the line is then where the row that carries it next + // draws it, so it stays put when the turn's first step arrives. Some( div() .flex_none() .w_full() - .flex() - .flex_col() - .justify_end() - .overflow_hidden() - .when_some(cap, |slot, cap| slot.max_h(cap)) - .child(content) - .on_children_prepainted(move |bounds, _, _| { - if let Some(content) = bounds.first() { - let height = content.size.height; - natural_height.set(Some(height)); - shown_height.set(cap.map_or(height, |cap| height.min(cap))); - } - }) + .child(under) + .child(div().h_4()) .into_any_element(), ) } } -/// Height of the row under the transcript that shows the waiting dots or, +/// Height of the row under the transcript that shows a turn's line or, /// while a message is being sent, its status line. Both take the same /// slot so one replacing the other moves nothing. pub(super) const WAITING_ROW_HEIGHT: Pixels = px(36.); @@ -539,6 +569,8 @@ 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. + unfolded: HashMap, /// When another task's transcript landed. switched: Option, /// The user row that takes over from the send preview on screen, @@ -549,7 +581,7 @@ pub(super) struct RowMotion { pub(super) preview_body: Rc>>>, /// Rows apply without an entrance (events replayed on reconnect). quiet: bool, - /// The slot under the transcript (waiting dots or the sent message's + /// The slot under the transcript (a turn's line or the sent message's /// status) showed last frame. pub(super) slot_on_screen: bool, /// The slot's height cap while it opens and after, so it grows rather @@ -663,6 +695,9 @@ impl RowMotion { if let Some(at) = self.disclosed.remove(old) { self.disclosed.insert(new.to_owned(), at); } + if let Some(at) = self.unfolded.remove(old) { + self.unfolded.insert(new.to_owned(), at); + } let mut heights = self.heights.borrow_mut(); if let Some(height) = heights.remove(old) { heights.insert(new.to_owned(), height); @@ -678,6 +713,15 @@ 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) { + if open { + self.unfolded.insert(lead.to_owned(), now); + } else { + self.unfolded.remove(lead); + } + } + /// Another task's transcript landed. pub(super) fn switch_task(&mut self, now: Instant) { self.switched = Some(now); @@ -688,6 +732,7 @@ impl RowMotion { self.arrived.clear(); self.heights.borrow_mut().clear(); self.disclosed.clear(); + self.unfolded.clear(); self.handed_off = None; self.slot_snap = true; } @@ -727,6 +772,13 @@ impl RowMotion { .map_or(1., |at| motion::progress(*at, motion::REVEAL, now, reduced)) } + /// Progress of the fade of steps the user just showed. + pub(super) fn turn_disclosure(&self, lead: &str, now: Instant, reduced: bool) -> f32 { + self.unfolded + .get(lead) + .map_or(1., |at| motion::progress(*at, motion::REVEAL, now, reduced)) + } + /// Progress of the fade of a task's transcript after a switch. pub(super) fn switch_progress(&self, now: Instant, reduced: bool) -> f32 { self.switched @@ -740,6 +792,7 @@ impl RowMotion { self.arrived.clear(); self.heights.borrow_mut().clear(); self.disclosed.clear(); + self.unfolded.clear(); self.switched = None; return false; } @@ -751,10 +804,15 @@ impl RowMotion { .retain(|id, _| self.arrived.contains_key(id)); self.disclosed .retain(|_, at| running(at, motion::REVEAL.duration)); + self.unfolded + .retain(|_, at| running(at, motion::REVEAL.duration)); self.switched = self .switched .filter(|at| running(at, motion::REVEAL.duration)); - !self.arrived.is_empty() || !self.disclosed.is_empty() || self.switched.is_some() + !self.arrived.is_empty() + || !self.disclosed.is_empty() + || !self.unfolded.is_empty() + || self.switched.is_some() } } @@ -794,6 +852,63 @@ fn grow_in( .into_any_element() } +/// First and past-last transcript rows painted in view in the last frame, +/// and how far the view's top is into the first. +pub(super) type PaintedRows = Rc>>; + +/// A list row that notes when it paints in view: a wheel elsewhere in the +/// pane reports the rows on screen like the list's own wheel, and a turn +/// opening its steps holds the first of them where it is. +fn track_row(row: Div, ix: usize, painted_rows: &PaintedRows) -> Div { + // Only rows the list places in view are prepainted here; rows + // measured for overdraw are not, and a focused row kept alive + // off screen lands outside the mask. + let painted_rows = painted_rows.clone(); + div() + .child(row) + .on_children_prepainted(move |bounds, window, _cx| { + let view = window.content_mask().bounds; + let Some(row) = bounds + .first() + .filter(|row| row.top() < view.bottom() && row.bottom() > view.top()) + else { + return; + }; + let into = view.top() - row.top(); + painted_rows.set(Some(match painted_rows.get() { + Some((start, end, _)) if ix < start => (ix, end, into), + Some((start, end, top)) => (start, end.max(ix + 1), top), + None => (ix, ix + 1, into), + })); + }) +} + +/// A row with the entrance of one that arrived live. +fn enter_row( + row: Div, + entrance: Option, + id: &str, + heights: &Rc>>, +) -> gpui::AnyElement { + match entrance { + None => row.into_any_element(), + // Scrolled up: paint offset and opacity only, so nothing on + // screen moves. + Some(Entrance { + progress, + grow: None, + .. + }) => motion::arrive(row, progress).into_any_element(), + // At the tail: the row opens to its height and the rows above + // glide up with it. + Some(Entrance { + progress, + grow: Some(grow), + natural, + }) => grow_in(row, progress, grow, natural, heights.clone(), id.to_owned()), + } +} + pub(super) fn render_timeline_item( item: &AgentTimelineItem, revision: u64, @@ -2707,45 +2822,6 @@ pub(super) fn render_question_card( card.child(footer) } -/// Pulsing dots shown between send and the first streamed content. They -/// breathe on the shared low-rate clock, so waiting costs the same as a -/// spinner rather than a full-rate animation. They fade in when they -/// appear and leave at once when the reply arrives. -pub(super) fn render_waiting_indicator() -> impl IntoElement { - const CYCLE: std::time::Duration = std::time::Duration::from_millis(1400); - let indicator = div() - .id("waiting-indicator") - .role(gpui::Role::Status) - .aria_label(tr("chat-thinking-label")) - .flex() - .items_center() - .gap_2() - .px_4() - // The send preview's status line takes the same slot. - .h(WAITING_ROW_HEIGHT) - .child(motion::ticker("waiting-dots", CYCLE, |phase| { - let mut row = div().flex().items_center().gap_1p5(); - for index in 0..3 { - let level = motion::pulse(phase, -(index as f32) * 0.18, 0.25, 1.0); - row = row.child( - div() - .size(px(7.)) - .rounded_full() - .bg(gpui::rgb(theme::accent())) - .opacity(level), - ); - } - row.into_any_element() - })) - .child( - div() - .text_sm() - .text_color(gpui::rgb(theme::text_muted())) - .child(tr("chat-thinking-label")), - ); - motion::fade_in(indicator, "waiting-indicator-reveal") -} - #[cfg(test)] mod motion_tests { use std::time::{Duration, Instant}; @@ -3168,7 +3244,7 @@ mod motion_tests { fn a_run_error_takes_the_waiting_rows_place(cx: &mut TestAppContext) { let clock = Clock::start(); let (chat, cx) = pane(cx, 30); - // A run is going and nothing has come back yet: the waiting dots show. + // A run is going and nothing has come back yet: its line waits. chat.update(cx, |chat, _| { chat.active_runs.insert("s1".into(), "run-1".into()); chat.awaiting_first_token = true; @@ -3201,7 +3277,7 @@ mod motion_tests { ); assert!( (tops[0] - before).abs() <= px(1.), - "older rows hold still as the error replaces the dots: {before:?} then {tops:?}" + "older rows hold still as the error replaces the line: {before:?} then {tops:?}" ); assert_glides(&tops, "an older row"); } @@ -3499,4 +3575,238 @@ mod motion_tests { assert!(chat.loading_spinner_due()); }); } + + fn run_event(event: maple_agent::agent::AgentRunEvent) -> AgentServiceEvent { + AgentServiceEvent::Run { + session_id: "s1".into(), + run_id: "run-1".into(), + event, + } + } + + fn tool_call(id: &str) -> AgentTimelineItem { + AgentTimelineItem { + title: Some("Terminal: cargo test".to_string()), + status: Some("completed".to_string()), + ..item(id, "tool", None) + } + } + + #[gpui::test] + fn a_turns_steps_stay_folded_until_its_line_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. + chat.update(cx, |chat, _| { + let mut rows = chat.timeline.clone(); + rows.extend([ + user_item("ask", "Run the tests"), + tool_call("call"), + item("thought", "thinking", Some("The suite is green.")), + item("reply", "message", Some("All tests pass.")), + ]); + chat.replace_timeline(rows); + }); + redraw(&chat, cx); + let line = bounds(cx, "turn-line"); + assert!( + cx.debug_bounds("tool-card").is_none() && cx.debug_bounds("thinking-title").is_none(), + "the steps start folded" + ); + let folded_reply = bounds(cx, "timeline-row-reply"); + + cx.simulate_click(line.center(), gpui::Modifiers::default()); + redraw(&chat, cx); + let call = bounds(cx, "tool-card"); + let thought = bounds(cx, "thinking-title"); + assert_eq!( + bounds(cx, "turn-line").origin, + line.origin, + "the line holds its place as its steps open" + ); + assert!( + call.top() >= line.bottom() && thought.top() >= call.bottom(), + "the steps open under the line, in order: {line:?}, {call:?}, {thought:?}" + ); + + cx.simulate_click(line.center(), gpui::Modifiers::default()); + redraw(&chat, cx); + assert!( + cx.debug_bounds("tool-card").is_none(), + "the steps fold again" + ); + assert_eq!( + bounds(cx, "timeline-row-reply").origin.y - bounds(cx, "turn-line").origin.y, + folded_reply.origin.y - line.origin.y, + "folded, the reply sits under the line as before" + ); + } + + #[gpui::test] + fn show_tool_call_details_opens_every_turn(cx: &mut TestAppContext) { + let _clock = Clock::start(); + let (chat, cx) = pane(cx, 0); + chat.update(cx, |chat, _| { + chat.tool_details = true; + chat.replace_timeline(vec![user_item("ask", "Run the tests"), tool_call("call")]); + }); + redraw(&chat, cx); + assert!( + bounds(cx, "tool-card").top() >= bounds(cx, "turn-line").bottom(), + "the setting shows the steps under the line without a click" + ); + } + + #[gpui::test] + fn the_line_keeps_its_place_when_the_turns_first_step_arrives(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 + // under the transcript. + chat.update(cx, |chat, _| { + chat.active_runs.insert("s1".into(), "run-1".into()); + chat.awaiting_first_token = true; + }); + redraw(&chat, cx); + let start = motion::ENTER.settle * 2; + clock.at(start); + redraw(&chat, cx); + let waiting = bounds(cx, "turn-line"); + let older = bounds(cx, "timeline-row-h29"); + chat.update(cx, |chat, cx| { + chat.handle_service_event( + run_event(maple_agent::agent::AgentRunEvent::TimelineItem(tool_call( + "call", + ))), + cx, + ); + }); + 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!( + tops[1].iter().all(|top| *top == older.origin.y), + "older rows hold still: {:?} then {:?}", + older.origin.y, + tops[1] + ); + } + + #[gpui::test] + fn a_turn_keeps_how_long_it_worked_less_the_wait_for_an_answer(cx: &mut TestAppContext) { + use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; + + let clock = Clock::start(); + let chat = screen(cx); + chat.update(cx, |chat, cx| { + chat.replace_timeline(vec![user_item("ask", "Push the branch")]); + chat.handle_service_event(run_event(AgentRunEvent::Started), cx); + chat.handle_service_event( + run_event(AgentRunEvent::TimelineItem(tool_call("call"))), + cx, + ); + // Four seconds in, Maple asks; the answer takes 26 more. + clock.at(Duration::from_secs(4)); + chat.handle_service_event( + AgentServiceEvent::Question { + session_id: "s1".into(), + request_id: "req-1".into(), + questions: vec![maple_agent::agent::AgentQuestion { + multi_select: false, + id: "q1".into(), + header: "Question".into(), + question: "Push to main?".into(), + options: Vec::new(), + permission: None, + }], + }, + cx, + ); + clock.at(Duration::from_secs(30)); + chat.handle_service_event( + AgentServiceEvent::QuestionResolved { + request_id: "req-1".into(), + }, + cx, + ); + clock.at(Duration::from_secs(37)); + chat.handle_service_event( + run_event(AgentRunEvent::Finished(AgentRunTerminal::Completed)), + cx, + ); + assert_eq!( + chat.turn_worked.get("call"), + Some(&Duration::from_secs(11)), + "the turn worked 4 s before the question and 7 s after the answer" + ); + }); + } + + #[gpui::test] + fn a_run_whose_rows_a_paged_back_view_missed_keeps_no_time(cx: &mut TestAppContext) { + use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; + + let clock = Clock::start(); + let chat = screen(cx); + chat.update(cx, |chat, cx| { + chat.replace_timeline(vec![user_item("ask", "Run the tests")]); + let row = |row| run_event(AgentRunEvent::TimelineItem(row)); + chat.handle_service_event(run_event(AgentRunEvent::Started), cx); + chat.handle_service_event(row(tool_call("first")), cx); + // Paged back in history, the view does not take in the queued + // message that starts the run's next turn. + chat.pages.after = true; + clock.at(Duration::from_secs(5)); + chat.handle_service_event(row(user_item("next", "Now lint")), cx); + clock.at(Duration::from_secs(9)); + chat.handle_service_event( + run_event(AgentRunEvent::Finished(AgentRunTerminal::Completed)), + cx, + ); + assert_eq!( + chat.turn_worked.get("first"), + None, + "the first turn is not charged for a turn the view never saw begin" + ); + }); + } + + #[gpui::test] + fn a_message_queued_into_a_run_ends_the_turn_before_it(cx: &mut TestAppContext) { + use maple_agent::agent::{AgentRunEvent, AgentRunTerminal}; + + let clock = Clock::start(); + let chat = screen(cx); + chat.update(cx, |chat, cx| { + chat.replace_timeline(vec![user_item("ask", "Run the tests")]); + let row = |row| run_event(AgentRunEvent::TimelineItem(row)); + chat.handle_service_event(run_event(AgentRunEvent::Started), cx); + chat.handle_service_event(row(tool_call("first")), cx); + // Five seconds in, the run takes up a queued message: the + // same run, the next turn. + clock.at(Duration::from_secs(5)); + chat.handle_service_event(row(user_item("next", "Now lint")), cx); + chat.handle_service_event(row(tool_call("second")), cx); + clock.at(Duration::from_secs(9)); + chat.handle_service_event( + run_event(AgentRunEvent::Finished(AgentRunTerminal::Completed)), + cx, + ); + assert_eq!( + chat.turn_worked.get("first"), + Some(&Duration::from_secs(5)), + "the first turn keeps its own time" + ); + assert_eq!( + chat.turn_worked.get("second"), + Some(&Duration::from_secs(4)), + "and the second starts from the message that began it" + ); + }); + } } diff --git a/apps/maple-agent/app/src/ui/chat/turn.rs b/apps/maple-agent/app/src/ui/chat/turn.rs new file mode 100644 index 000000000..7de8ac087 --- /dev/null +++ b/apps/maple-agent/app/src/ui/chat/turn.rs @@ -0,0 +1,825 @@ +//! The line a turn's steps fold under. +//! +//! 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. + +use std::time::{Duration, Instant}; + +use gpui::{Context, Div, SharedString, div, prelude::*, px}; +use maple_agent::agent::AgentTimelineItem; + +use super::ChatScreen; +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::theme; + +/// 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. +const RUN_TICK: Duration = Duration::from_secs(1); + +/// One drawing of the mark's M with the rest after it, and one pass of the +/// shine across the line's words. Only the words shine; the mark moves +/// instead. +const MARK_CYCLE: Duration = Duration::from_millis(2600); +/// The share of `MARK_CYCLE` the pulse spends drawing the M. The mark holds +/// still for what is left, about 0.6 s, before the next drawing. +const MARK_STROKE: f32 = 0.77; +const SHINE_CYCLE: Duration = Duration::from_millis(1900); + +/// What a transcript row is to its turn's line. +#[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. + Lead, + /// A later step, folded under the lead at this index. + Step(usize), +} + +/// Each loaded row's place in its turn, kept beside the timeline so no +/// frame regroups it. +#[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. + tail: Option, +} + +fn starts_turn(item: &AgentTimelineItem) -> bool { + item.item_type == "message" && item.role.as_deref() == Some("user") +} + +fn is_tool(item: &AgentTimelineItem) -> bool { + matches!(item.item_type.as_str(), "tool" | "toolCall") +} + +fn is_step(item: &AgentTimelineItem) -> bool { + if is_tool(item) { + // An unfinished list shows only in the card above the composer. + // Its row draws nothing, so it is no step to fold or to lead with. + return !has_tool_input(item, "todos") + || plan_entries(item).is_some_and(|plan| plan_finished(&plan)); + } + 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)) +} + +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.tail = None; + for item in timeline { + self.push(item); + } + } + + /// One row arrived at the end. + pub(super) fn push(&mut self, item: &AgentTimelineItem) { + let row = if starts_turn(item) { + self.tail = None; + TurnRow::Plain + } else if !is_step(item) { + TurnRow::Plain + } else if let Some(lead) = self.tail { + TurnRow::Step(lead) + } else { + self.tail = Some(self.rows.len()); + TurnRow::Lead + }; + self.rows.push(row); + } + + pub(super) fn row(&self, index: usize) -> TurnRow { + self.rows.get(index).copied().unwrap_or(TurnRow::Plain) + } + + pub(super) fn tail(&self) -> Option { + self.tail + } + + /// One past the last step of the turn led by the row at `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, + _ => {} + } + } + end + } +} + +/// How long a run has worked: the time since it began, less the time it +/// spent waiting on the user. +#[derive(Clone, Copy, Debug)] +pub(super) struct RunClock { + began: Instant, + waited: Duration, + waiting_since: Option, +} + +/// A run this window saw start, with its clock. +pub(super) struct TimedRun { + run_id: String, + /// `None` once the view missed some of the run's rows: it is still + /// the run it saw start, but it can no longer say a true time for it. + clock: Option, + /// The lead row of the turn the run is working on, once that turn has + /// a step: the row its time is kept under when the turn ends. + lead: Option, +} + +impl TimedRun { + /// The view did not take in a row of this run. Where its turns began + /// is lost, so it shows no time rather than a wrong one. + pub(super) fn stop_timing(&mut self) { + self.clock = None; + self.lead = None; + } +} + +impl RunClock { + fn new(now: Instant) -> Self { + Self { + began: now, + waited: Duration::ZERO, + waiting_since: None, + } + } + + fn worked(&self, now: Instant) -> Duration { + self.waiting_since + .unwrap_or(now) + .saturating_duration_since(self.began) + .saturating_sub(self.waited) + } + + /// Start counting again from `now`, for the run's next turn. A wait + /// under way carries on. + fn restart(&mut self, now: Instant) { + self.began = now; + self.waited = Duration::ZERO; + self.waiting_since = self.waiting_since.map(|_| now); + } + + /// A question for the user stops the clock; its answer starts it again. + fn set_waiting(&mut self, waiting: bool, now: Instant) { + match (waiting, self.waiting_since) { + (true, None) => self.waiting_since = Some(now), + (false, Some(since)) => { + self.waited += now.saturating_duration_since(since); + self.waiting_since = None; + } + _ => {} + } + } +} + +/// What the line says while its turn runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Phase { + Thinking, + Working, + Writing, + /// A question or a permission request waits on the user. + Waiting, +} + +impl Phase { + fn label(self) -> SharedString { + tr(match self { + Phase::Thinking => "chat-thinking-label", + Phase::Working => "chat-turn-working", + Phase::Writing => "chat-turn-writing", + Phase::Waiting => "chat-turn-waiting", + }) + } +} + +/// What a turn's line shows. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Line { + /// The turn is running. A run this window did not see start has no + /// clock, and its line shows no time. + Live { + phase: Phase, + worked: Option, + /// Loops hold still: the mark rests. + still: bool, + }, + /// The turn is over. `worked` is how long it took, when this window + /// timed it; a turn read back from history has none. + Done { worked: Option }, +} + +/// "Worked for 11s", "Worked for 1m 4s", or "Worked" for an untimed turn. +fn worked_label(messages: &MessageCache, worked: Option) -> SharedString { + let Some(worked) = worked else { + return tr("chat-turn-worked"); + }; + // Whole seconds, counted as the running time counts them, so the + // line never says more when it stops than it showed while running. + let seconds = worked.as_secs().max(1); + if seconds < 60 { + messages.get("chat-turn-worked-seconds", [("seconds", seconds.into())]) + } else { + messages.get( + "chat-turn-worked-minutes", + [ + ("minutes", (seconds / 60).into()), + ("seconds", (seconds % 60).into()), + ], + ) + } +} + +/// "6s" under a minute, then a clock like the subagent rows. A running +/// time counts whole seconds: tenths are too much movement on a line that +/// is on screen for the whole turn. +pub(super) fn live_elapsed(worked: Duration) -> String { + if worked.as_secs() >= 60 { + format_subagent_elapsed(worked) + } else { + format!("{}s", worked.as_secs()) + } +} + +#[derive(Clone, Copy)] +enum Mark { + /// The blocks along the M's stroke shrink and grow, one after another. + Working, + /// Nothing is running: the mark rests in the running tone. + Resting, + /// Maple waits on the user: the mark rests in coral. + Waiting, +} + +/// The stroke that draws the M, by (row, column): up the left side, through +/// the notch, and down the right side. The bottom edge is not part of the +/// letter, so the pulse never runs along it. +const MARK_PATH: [(usize, usize); 13] = [ + (4, 0), + (3, 0), + (2, 0), + (1, 0), + (0, 0), + (1, 1), + (2, 2), + (1, 3), + (0, 4), + (1, 4), + (2, 4), + (3, 4), + (4, 4), +]; + +/// How far the block at (`row`, `column`) has shrunk, 0 to 1, when a +/// working mark is `phase` through its cycle. The pulse enters at the +/// bottom left, leaves at the bottom right, and then every block rests +/// until the cycle starts again. Blocks off the stroke hold still. +fn mark_pulse(row: usize, column: usize, phase: f32) -> f32 { + /// How many blocks either side of its head the pulse reaches. + const REACH: f32 = 1.5; + let Some(index) = MARK_PATH.iter().position(|&at| at == (row, column)) else { + return 0.; + }; + // The head starts clear of the first block and ends clear of the last, + // so the pulse comes in and goes out whole. Past `MARK_STROKE` it is + // beyond every block. + let travel = MARK_PATH.len() as f32 - 1. + 2. * REACH; + let head = phase / MARK_STROKE * travel - REACH; + motion::smoothstep((1. - (index as f32 - head).abs() / REACH).max(0.)) +} + +/// The Maple mark on a 5 by 5 grid: a block with the notch of the M cut +/// from its top edge. `phase` is how far a working mark is through its +/// cycle. +fn maple_mark(mark: Mark, phase: f32) -> Div { + const SHAPE: [[bool; 5]; 5] = [ + [true, false, false, false, true], + [true, true, false, true, true], + [true; 5], + [true; 5], + [true; 5], + ]; + const CELL: gpui::Pixels = px(3.); + let resting: gpui::Hsla = gpui::rgb(theme::status_running()).into(); + let coral: gpui::Hsla = gpui::rgb(theme::accent_ink()).into(); + let mut grid = div() + .debug_selector(|| "turn-mark".to_string()) + .flex_none() + .flex() + .flex_col() + .gap(px(1.)); + for (row, cells) in SHAPE.iter().enumerate() { + let mut line = div().flex().gap(px(1.)); + for (column, on) in cells.iter().enumerate() { + // The box keeps its size so a shrinking block moves nothing. + let cell = div().size(CELL).flex().items_center().justify_center(); + let block = div().rounded(px(0.5)); + line = line.child(if !on { + cell + } else { + match mark { + Mark::Working => { + let level = mark_pulse(row, column, phase); + cell.child( + block + .size(CELL * (1. - 0.6 * level)) + .bg(resting) + .opacity(0.9), + ) + } + Mark::Resting => cell.child(block.size(CELL).bg(resting).opacity(0.9)), + Mark::Waiting => cell.child(block.size(CELL).bg(coral)), + } + }); + } + grid = grid.child(line); + } + 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); + let id = |part: &str| SharedString::from(format!("turn-{part}-{key}")); + let (label, mark, time) = match line { + Line::Live { + phase, + worked, + still, + } => { + let mark = match phase { + Phase::Waiting => Mark::Waiting, + _ if still => Mark::Resting, + _ => Mark::Working, + }; + // Beside "Waiting for you" the stopped time would read as + // how long the user has kept Maple waiting. + let time = worked.filter(|_| phase != Phase::Waiting).map(live_elapsed); + (phase.label(), mark, time) + } + Line::Done { worked } => (worked_label(messages, worked), Mark::Resting, None), + }; + let running = matches!(mark, Mark::Working); + let words = morph_text(id("words"), label.clone()); + let button = div() + .id(id("line")) + .debug_selector(|| "turn-line".to_string()) + .aria_label(label) + .h(px(32.)) + .flex() + .items_center() + .gap_2p5() + .text_sm() + .font_weight(gpui::FontWeight::MEDIUM) + // The shine carries the words while Maple works, so they rest + // dimmer under it. + .text_color(gpui::rgb(if running { + theme::text_muted() + } 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() + }) + .child(if running { + words.shine(SHINE_CYCLE, gpui::rgb(theme::text_heading())) + } else { + words + }) + .children(time.map(|time| { + div() + .debug_selector(|| "turn-time".to_string()) + .font_family(crate::assets::FONT_MONO) + .font_weight(gpui::FontWeight::NORMAL) + .text_xs() + .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(); + }), + ) +} + +impl ChatScreen { + /// Whether the run's line waits in the slot under the transcript: + /// nothing has come back yet, so no step can carry it. + pub(super) fn line_in_slot(&self) -> bool { + self.awaiting_first_token && self.is_run_active() && !self.has_send_feedback() + } + + /// Whether the run on screen is working on the turn led by the row at + /// `lead`. Until a new run's first row lands the last turn is an + /// 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) + && self.is_run_active() + && !self.awaiting_first_token + && !self.pages.after + && !self.pages.live_has_more + } + + /// The line of the turn led by the row at `lead`. + pub(super) fn turn_line(&self, lead: usize, still: bool) -> Line { + if self.turn_runs(lead) { + return self.live_line(still); + } + Line::Done { + worked: self + .timeline + .get(lead) + .and_then(|item| self.turn_worked.get(&item.id)) + .copied(), + } + } + + /// The line of the run on screen. + pub(super) fn live_line(&self, still: bool) -> Line { + let phase = if self.current_question().is_some() { + Phase::Waiting + } else { + match self.timeline.last() { + Some(item) if is_tool(item) => Phase::Working, + Some(item) if item.item_type == "message" && !starts_turn(item) => Phase::Writing, + _ => Phase::Thinking, + } + }; + let now = motion::now(); + Line::Live { + phase, + worked: self + .selected_session + .as_ref() + .and_then(|session| self.run_clocks.get(session)) + .and_then(|timed| timed.clock.as_ref()) + .map(|clock| clock.worked(now)), + still, + } + } + + /// 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 { + self.timeline + .get(lead) + .is_some_and(|item| self.tool_details != self.toggled_turns.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) { + 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()); + } + let open = self.turn_open(lead); + self.row_motion.disclose_turn(lead_id, open, motion::now()); + if !open { + self.keep_application_selection_shown(lead); + } else if self.list_state.is_following_tail() + && !self.turn_runs(lead) + && let Some((first, _, into)) = self.painted_rows.get() + && into >= px(0.) + { + // At its end the list names no row to hold, and would keep + // its tail in view and carry the clicked line away. Hold the + // first row on screen instead, so a finished turn's steps open + // under its line. A running turn keeps following, so its + // newest step stays in view. + self.list_state.scroll_to(gpui::ListOffset { + item_ix: first, + offset_in_item: into, + }); + } + self.list_state.remeasure_items(lead..self.turns.end(lead)); + cx.notify(); + } + + /// A run this window sees start gets a clock. Both the send that + /// started it and its first event report it; the second changes + /// nothing. + pub(super) fn run_began(&mut self, session_id: &str, run_id: &str, cx: &mut Context) { + if self + .run_clocks + .get(session_id) + .is_some_and(|timed| timed.run_id == run_id) + { + return; + } + self.run_clocks.insert( + session_id.to_owned(), + TimedRun { + run_id: run_id.to_owned(), + clock: Some(RunClock::new(motion::now())), + lead: None, + }, + ); + self.schedule_run_tick(cx); + } + + /// A row arrived at the end of the task while its run is timed. A + /// turn's first step is the row the turn's time is kept under. A + /// message from the user, queued or steering the run, ends the turn + /// before it, and the time starts again for the next. + pub(super) fn time_arrival(&mut self, session_id: &str, index: usize) { + let Some(timed) = self.run_clocks.get_mut(session_id) else { + return; + }; + let Some(item) = self.timeline.get(index) else { + return; + }; + let Some(clock) = timed.clock.as_mut() else { + return; + }; + if self.turns.row(index) == TurnRow::Lead { + timed.lead = Some(item.id.clone()); + } else if starts_turn(item) { + let now = motion::now(); + if let Some(lead) = timed.lead.take() { + self.turn_worked.insert(lead, clock.worked(now)); + } + clock.restart(now); + } + } + + /// Keep the clocks in step with the runs and the questions, wherever + /// either changed. A run that left `active_runs` stops its clock, and + /// 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) { + if self.run_clocks.is_empty() { + return; + } + let now = motion::now(); + let ended: Vec = self + .run_clocks + .iter() + .filter(|(session, timed)| self.active_runs.get(*session) != Some(&timed.run_id)) + .map(|(session, _)| session.clone()) + .collect(); + for session in ended { + let Some(timed) = self.run_clocks.remove(&session) else { + continue; + }; + // A run that ended before its turn had a step has no line to + // say the time on. + if self.is_selected(&session) + && let Some(clock) = timed.clock + && let Some(lead) = timed + .lead + .filter(|lead| self.timeline_index.contains_key(lead)) + { + self.turn_worked.insert(lead, clock.worked(now)); + } + } + let questions = &self.pending_questions; + for (session, timed) in &mut self.run_clocks { + let waiting = questions + .iter() + .any(|question| &question.session_id == session); + if let Some(clock) = timed.clock.as_mut() { + clock.set_waiting(waiting, now); + } + } + } + + /// 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 let Some(worked) = self.turn_worked.remove(old) { + self.turn_worked.insert(new.to_owned(), worked); + } + for timed in self.run_clocks.values_mut() { + if timed.lead.as_deref() == Some(old) { + timed.lead = Some(new.to_owned()); + } + } + } + + /// Paint once a second while a run is timed, so the time on its line + /// stays true where loops hold still: under reduced motion, and in a + /// window that is not active. The last run to end stops the timer. + fn schedule_run_tick(&self, cx: &mut Context) { + if self.run_clocks.is_empty() || self.run_tick_pending.replace(true) { + return; + } + cx.spawn(async move |entity, cx| { + cx.background_executor().timer(RUN_TICK).await; + entity + .update(cx, |this, cx| { + this.run_tick_pending.set(false); + if this.run_clocks.is_empty() { + return; + } + this.schedule_run_tick(cx); + if this.is_run_active() { + cx.notify(); + } + }) + .ok(); + }) + .detach(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn item(item_type: &str, role: Option<&str>) -> AgentTimelineItem { + AgentTimelineItem { + label: None, + persisted: None, + live: None, + truncated: None, + revision: 0, + id: String::new(), + item_type: item_type.into(), + role: role.map(str::to_owned), + title: None, + text: None, + status: None, + input: None, + output: None, + created_ms: 0, + merge: "replace".into(), + } + } + + #[test] + fn a_turn_folds_its_later_steps_under_its_first() { + let timeline = [ + item("message", Some("user")), + item("thinking", None), + item("message", Some("assistant")), + item("tool", None), + item("error", None), + item("message", Some("user")), + item("message", Some("assistant")), + item("toolCall", None), + ]; + let mut turns = Turns::default(); + turns.rebuild(&timeline); + let rows: Vec<_> = (0..timeline.len()).map(|index| turns.row(index)).collect(); + assert_eq!( + rows, + [ + TurnRow::Plain, + TurnRow::Lead, + TurnRow::Plain, + TurnRow::Step(1), + 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(7), 8); + assert_eq!(turns.tail(), Some(7)); + } + + #[test] + fn rows_arriving_one_by_one_group_like_a_snapshot() { + let timeline = [ + item("tool", None), + item("reasoning", None), + item("message", Some("user")), + item("message", Some("assistant")), + item("tool", None), + ]; + let mut snapshot = Turns::default(); + snapshot.rebuild(&timeline); + let mut live = Turns::default(); + for row in &timeline { + live.push(row); + } + assert_eq!(live.rows, snapshot.rows); + assert_eq!(live.tail, snapshot.tail); + // 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. + live.push(&item("message", Some("user"))); + assert_eq!(live.tail(), None); + } + + #[test] + fn the_clock_stops_while_a_question_waits() { + let began = Instant::now(); + let at = |seconds| began + Duration::from_secs(seconds); + let mut clock = RunClock::new(began); + clock.set_waiting(true, at(4)); + // Waiting: the time holds, however long the answer takes. + assert_eq!(clock.worked(at(30)), Duration::from_secs(4)); + // A second question while one waits does not restart the wait. + clock.set_waiting(true, at(10)); + clock.set_waiting(false, at(30)); + assert_eq!(clock.worked(at(37)), Duration::from_secs(11)); + } + + #[test] + fn a_running_time_counts_whole_seconds_then_reads_as_a_clock() { + assert_eq!(live_elapsed(Duration::from_millis(890)), "0s"); + assert_eq!(live_elapsed(Duration::from_millis(6_890)), "6s"); + assert_eq!(live_elapsed(Duration::from_millis(59_999)), "59s"); + assert_eq!(live_elapsed(Duration::from_secs(64)), "1:04"); + } + + /// The pulse draws the letter: it starts at the bottom left, ends at + /// the bottom right, never runs along the bottom edge, and then every + /// block rests before the next drawing. + #[test] + fn the_mark_draws_an_m_and_rests_before_the_next() { + let shrunk = |phase: f32| -> Vec<(usize, usize)> { + (0..5) + .flat_map(|row| (0..5).map(move |column| (row, column))) + .filter(|&(row, column)| mark_pulse(row, column, phase) > 0.5) + .collect() + }; + assert_eq!(shrunk(0.), [], "the pulse comes in from rest"); + let first = (1..100) + .map(|step| shrunk(step as f32 / 100.)) + .find(|blocks| !blocks.is_empty()); + assert_eq!(first, Some(vec![(4, 0)]), "it begins at the bottom left"); + let last = (1..100) + .rev() + .map(|step| shrunk(step as f32 / 100.)) + .find(|blocks| !blocks.is_empty()); + assert_eq!(last, Some(vec![(4, 4)]), "it ends at the bottom right"); + for step in 0..=100 { + let phase = step as f32 / 100.; + for column in 1..4 { + assert_eq!(mark_pulse(4, column, phase), 0., "bottom edge at {phase}"); + } + if phase >= MARK_STROKE { + assert_eq!(shrunk(phase), [], "the mark rests at {phase}"); + } + } + assert!( + MARK_CYCLE.mul_f32(1. - MARK_STROKE) >= Duration::from_millis(500), + "the rest is long enough to read as a pause" + ); + } +} diff --git a/apps/maple-agent/app/src/ui/morph_text.rs b/apps/maple-agent/app/src/ui/morph_text.rs index dc7b43ff5..90b9a06f5 100644 --- a/apps/maple-agent/app/src/ui/morph_text.rs +++ b/apps/maple-agent/app/src/ui/morph_text.rs @@ -7,6 +7,9 @@ //! One shaping per change and one tiny shaped run per letter per frame, //! only while a morph runs; at rest it paints a single line and asks for no //! frames. Reduced motion swaps the text at once. +//! +//! Text that reports work in progress can also carry a shine: a band of a +//! second colour that crosses the words on the shared loop clock. use std::time::{Duration, Instant}; @@ -25,6 +28,7 @@ pub struct MorphText { text: SharedString, color: Option, instant: bool, + shine: Option<(Duration, Hsla)>, } /// Morphing text in the surrounding text style; `id` keeps its state @@ -35,6 +39,7 @@ pub fn morph_text(id: impl Into, text: impl Into) -> Mo text: text.into(), color: None, instant: false, + shine: None, } } @@ -53,6 +58,23 @@ impl MorphText { self.instant = instant; self } + + /// Sweep a band of `color` across the words once every `cycle`. It + /// holds still when loops do: under reduced motion, and in a window + /// that is not active. + pub fn shine(mut self, cycle: Duration, color: impl Into) -> Self { + self.shine = Some((cycle, color.into())); + self + } +} + +/// How much of the shine a letter `at` of the way along the line takes +/// when the band is `phase` of the way through its pass. +fn shine_level(at: f32, phase: f32) -> f32 { + // The band enters and leaves past the ends of the line. + const REACH: f32 = 0.3; + let head = -REACH + phase * (1. + 2. * REACH); + crate::ui::motion::smoothstep((1. - (at - head).abs() / REACH).max(0.)) } /// One letter and where it sits from the line's start. @@ -295,32 +317,50 @@ impl Element for MorphText { let font_size = style.font_size.to_pixels(rem); let line_height = style.line_height_in_pixels(rem); let fallback = style.color; + // Where the band is this frame, while loops run. + let shine = self + .shine + .filter(|_| !crate::ui::motion::loops_paused(window, cx)) + .map(|(cycle, color)| (crate::ui::motion::phase(cycle), color)); let animating = window.with_element_state::(id, |state, window| { let state = state.unwrap_or_default(); let progress = state.progress(Instant::now()); let eased = progress.map(ease); let color = state.visual_color(eased, fallback); + // A letter `x` along the line takes the shine where the band is. + let tint = |x: Pixels| match shine { + Some((phase, shine)) if state.width > px(0.) => { + mix(color, shine, shine_level(x / state.width, phase)) + } + _ => color, + }; + let draw = |window: &mut Window, + cx: &mut App, + text: &SharedString, + runs: &[gpui::TextRun], + x, + y| { + window + .text_system() + .shape_line(text.clone(), font_size, runs, None) + .paint( + point(bounds.left() + x, bounds.top() + y), + line_height, + TextAlign::Left, + None, + window, + cx, + ) + .ok(); + }; let paint = |window: &mut Window, cx: &mut App, text: &SharedString, x, y, alpha: f32| { if alpha <= 0. { return; } let mut run = style.to_run(text.len()); - run.color = color.opacity(alpha); - let shaped = - window - .text_system() - .shape_line(text.clone(), font_size, &[run], None); - shaped - .paint( - point(bounds.left() + x, bounds.top() + y), - line_height, - TextAlign::Left, - None, - window, - cx, - ) - .ok(); + run.color = tint(x).opacity(alpha); + draw(window, cx, text, &[run], x, y); }; match (progress, &state.morph) { (Some(t), Some(morph)) if t < 1. => { @@ -349,6 +389,41 @@ impl Element for MorphText { } (true, state) } + _ if shine.is_some() => { + // The resting line's one layout, each glyph painted in + // its own tint. A text run per colour would split the + // shaping wherever the colour changes, so letters lose + // their kerning, and shift, as the band passes. + let layout = window.text_system().layout_line( + &state.text, + font_size, + &[style.to_run(state.text.len())], + None, + ); + let padding_top = (line_height - layout.ascent - layout.descent) / 2.; + let baseline = point(bounds.left(), bounds.top() + padding_top + layout.ascent); + for run in &layout.runs { + for glyph in &run.glyphs { + let origin = baseline + glyph.position; + if glyph.is_emoji { + window + .paint_emoji(origin, run.font_id, glyph.id, font_size) + .ok(); + } else { + window + .paint_glyph( + origin, + run.font_id, + glyph.id, + font_size, + tint(glyph.position.x), + ) + .ok(); + } + } + } + (false, state) + } _ => { paint(window, cx, &state.text, px(0.), px(0.), 1.); (false, state) @@ -357,6 +432,8 @@ impl Element for MorphText { }); if animating { window.request_animation_frame(); + } else if shine.is_some() { + crate::ui::motion::schedule_loop_frame(window, cx); } } } diff --git a/apps/maple-agent/app/translation-revisions/de.txt b/apps/maple-agent/app/translation-revisions/de.txt index fbc2d9b84..f2fd49ea9 100644 --- a/apps/maple-agent/app/translation-revisions/de.txt +++ b/apps/maple-agent/app/translation-revisions/de.txt @@ -398,6 +398,12 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-waiting 130514d0bacc91a7 +chat-turn-worked 5dcfb6d76e519bf9 +chat-turn-worked-minutes 9b13b6f2c1f967be +chat-turn-worked-seconds 4807eaf86de7008a +chat-turn-working e96e500129b24c76 +chat-turn-writing 99f475aed0d017b8 chat-unpin 4aee1206999bb9d1 chat-unpin-task b4d9f9b7b531c64a chat-untrust-project ff48514cda33c012 diff --git a/apps/maple-agent/app/translation-revisions/es.txt b/apps/maple-agent/app/translation-revisions/es.txt index fbc2d9b84..f2fd49ea9 100644 --- a/apps/maple-agent/app/translation-revisions/es.txt +++ b/apps/maple-agent/app/translation-revisions/es.txt @@ -398,6 +398,12 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-waiting 130514d0bacc91a7 +chat-turn-worked 5dcfb6d76e519bf9 +chat-turn-worked-minutes 9b13b6f2c1f967be +chat-turn-worked-seconds 4807eaf86de7008a +chat-turn-working e96e500129b24c76 +chat-turn-writing 99f475aed0d017b8 chat-unpin 4aee1206999bb9d1 chat-unpin-task b4d9f9b7b531c64a chat-untrust-project ff48514cda33c012 diff --git a/apps/maple-agent/app/translation-revisions/ko.txt b/apps/maple-agent/app/translation-revisions/ko.txt index fbc2d9b84..f2fd49ea9 100644 --- a/apps/maple-agent/app/translation-revisions/ko.txt +++ b/apps/maple-agent/app/translation-revisions/ko.txt @@ -398,6 +398,12 @@ chat-trust-description 1e3842500e30ef07 chat-trust-keep d6e02ad22aeeeba6 chat-trust-saved 92a4e34ef0b734ae chat-trust-title 4a6389783686eec6 +chat-turn-waiting 130514d0bacc91a7 +chat-turn-worked 5dcfb6d76e519bf9 +chat-turn-worked-minutes 9b13b6f2c1f967be +chat-turn-worked-seconds 4807eaf86de7008a +chat-turn-working e96e500129b24c76 +chat-turn-writing 99f475aed0d017b8 chat-unpin 4aee1206999bb9d1 chat-unpin-task b4d9f9b7b531c64a chat-untrust-project ff48514cda33c012 diff --git a/apps/maple-agent/docs/brand.md b/apps/maple-agent/docs/brand.md index bf3602174..9653791ce 100644 --- a/apps/maple-agent/docs/brand.md +++ b/apps/maple-agent/docs/brand.md @@ -196,7 +196,11 @@ the dark background. The 60 / 30 / 10 rule maps to: workspace and transcript on `bg_app`; sidebar, settings navigation, popups, and hover fills on Pebble; coral only on the send button, the composer border, focus rings, the new-task row, -selected menu items, and primary buttons. +selected menu items, and primary buttons. Status in the transcript stays +neutral with a coral glyph at most: the Maple mark on a turn's line is +Pebble (`status_running`), its blocks pulse one at a time along the M's stroke while +Maple works, and it rests in coral (`accent_ink`) only while Maple waits +for the user. ### Type diff --git a/apps/maple-agent/docs/motion.md b/apps/maple-agent/docs/motion.md index 3f5a6fdcf..548d5f802 100644 --- a/apps/maple-agent/docs/motion.md +++ b/apps/maple-agent/docs/motion.md @@ -71,8 +71,8 @@ of `app/src/ui/effort_slider.rs` and `app/src/ui/chat/effort.rs`, and they stay out of the tokens on purpose: nothing else should move like it. Press feedback is immediate (`.active()`), and focus rings appear at once. -Looping indicators (spinners, the waiting dots, the running ring) use the -shared 15 fps `ticker` clock and pause in background windows. +Looping indicators (spinners, a running turn's line, the running ring) use +the shared 15 fps `ticker` clock and pause in background windows. ## Where motion applies @@ -86,11 +86,12 @@ shared 15 fps `ticker` clock and pause in background windows. | 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 | — | -| 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 waiting dots share one slot under it | — | +| 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` | — | | Disclosed details (tool output, thinking) | fade in, `REVEAL` | immediate | | Streaming text | grows in place, no animation | — | -| Waiting dots | fade in, `REVEAL` | immediate | +| 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 to draw the M (up the left side, through the notch, down the right; never along the bottom), then the mark rests a moment before it draws again; 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 | | 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 | @@ -152,8 +153,10 @@ appear only after 300 ms, so fast loads never flash a spinner. - Transcript rows sit in a `gpui::list`, whose items lose element state when they scroll away. Their entrance is driven by the arrival time kept in view state, so a row animates once and never replays. A row that replaces the - slot under the transcript (the waiting dots, a sent message, a failed - send) opens from the slot's height, so nothing above it jumps. The sent + slot under the transcript (a turn's line, a sent message, a failed + send) opens from the slot's height, so nothing above it jumps. A turn's + first step draws the line itself: the line stays where the slot showed it + and only what is under it opens. The sent message's row takes over from its bubble by the key the transcript files the row under (`timeline_view_key`), which for a real host's rows is not the id the event names; test hand-offs with rows that carry a live or