From d8aa33252a1026fa6781342444a72232166a898b Mon Sep 17 00:00:00 2001 From: egor Date: Fri, 4 Dec 2026 23:11:01 +0500 Subject: [PATCH] fix(agent): smooth and isolate thinking animation --- Cargo.lock | 1 - THIRD_PARTY_NOTICES.txt | 6 +- crates/agent/src/panel.rs | 12 +- crates/agent/src/panel/chat.rs | 6 +- crates/agent/src/panel/layout.rs | 6 +- crates/agent/src/panel/lifecycle.rs | 2 +- crates/agent/src/panel/parts.rs | 44 +++- crates/agent/src/panel/tests/approvals.rs | 2 +- crates/agent/src/panel/tests/composer.rs | 2 +- .../panel/tests/composer/menu_stability.rs | 2 +- crates/agent/src/panel/tests/invalidation.rs | 100 ++++++++ crates/agent/src/panel/tests/mod.rs | 14 +- crates/agent/src/panel/tests/servers/menu.rs | 2 +- crates/agent/src/panel/tests/tool_input.rs | 2 +- crates/agent/src/panel/transcript.rs | 14 +- crates/ui/Cargo.toml | 1 - crates/ui/assets/animations/thinking.webp | Bin 9630 -> 0 bytes crates/ui/src/animations.rs | 231 ++++++++++++------ docs/architecture/feature.md | 10 +- 19 files changed, 347 insertions(+), 110 deletions(-) delete mode 100644 crates/ui/assets/animations/thinking.webp diff --git a/Cargo.lock b/Cargo.lock index a9ccbb06..3972a62b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6456,7 +6456,6 @@ version = "0.0.0" dependencies = [ "futures", "gpui-kit", - "image", "nocterm-core", "nocterm-design", "nocterm-explorer", diff --git a/THIRD_PARTY_NOTICES.txt b/THIRD_PARTY_NOTICES.txt index cd0007aa..8a3e63d7 100644 --- a/THIRD_PARTY_NOTICES.txt +++ b/THIRD_PARTY_NOTICES.txt @@ -2,9 +2,9 @@ Nocterm third-party licenses and notices ======================================== Generated by scripts/generate-license-notices.py using cargo-about 0.9.2. -Content SHA-256: 23f38964a59e4349ce78c3623d881bd996f343a217ad640e1f91906a7ef379de -Input fingerprint: 76076c89e8bd371a415fe064f1b773b52fb9e84437c9c85598cceb5abbb3f1e2 -Cargo.lock SHA-256 (release version masked): b33eec8e734dbb668401cb696d4cc21b59b8aeed795c149ed508e484bf5c34a7 +Content SHA-256: b533cd5e2e46230eb61c730ffdc816522be1c0cb727a17d2724167db73b8c667 +Input fingerprint: a5630f1f5613afb41b26855a566b5a838c0a83907151aee0db585a7f8c263aa1 +Cargo.lock SHA-256 (release version masked): d5ced87c994bda2f73b2114fe52f5466b93668a1325723121ec64e4323b06e5f Scope: runtime and build dependencies of Nocterm and its optional vault broker for Linux x86_64, Windows x86_64, macOS x86_64 and macOS arm64. diff --git a/crates/agent/src/panel.rs b/crates/agent/src/panel.rs index 75d79ae4..bd8ce2d3 100644 --- a/crates/agent/src/panel.rs +++ b/crates/agent/src/panel.rs @@ -95,7 +95,7 @@ impl AgentPanel { let composer = composer_view::ComposerView::new(window, cx); let menus = menu_view::MenuView::new(composer.focus(cx), window, cx); let history = history_column::HistoryColumn::new(window, cx); - let layout = layout::PanelLayout::new(layout, cx); + let layout = layout::PanelLayout::new(layout, window, cx); let messages = message_list::MessageList::new(images, cx); let subscriptions = Self::bind_panel(&host, &settings, window, cx); // Whatever the panel redraws for, its cached regions redraw too; thread changes @@ -455,6 +455,14 @@ impl AgentPanel { ) -> AnyElement { match kind { parts::PartKind::Transcript => self.render_transcript_part(cx), + parts::PartKind::Approvals => self + .current() + .and_then(|thread| self.render_approvals(&thread, window, cx)) + .unwrap_or_else(|| div().into_any_element()), + parts::PartKind::Status => self + .current() + .and_then(|thread| self.chat_status(&thread, cx)) + .unwrap_or_else(|| div().into_any_element()), parts::PartKind::Footer => self.render_footer(window, cx), parts::PartKind::Queue => self.render_queue_part(cx), } @@ -629,6 +637,8 @@ impl Render for AgentPanel { .min_w_0() .min_h_0() .child(self.layout.parts().transcript()) + .child(self.layout.parts().approvals()) + .child(self.layout.parts().status()) .child(self.layout.parts().footer(self.menus.current().is_some())) .into_any_element(); if self.layout.history() { diff --git a/crates/agent/src/panel/chat.rs b/crates/agent/src/panel/chat.rs index 7c06c137..ca03f3b7 100644 --- a/crates/agent/src/panel/chat.rs +++ b/crates/agent/src/panel/chat.rs @@ -10,7 +10,7 @@ use nocterm_ai::usage::{Breakdown, RateLimit}; use std::time::Duration; impl AgentPanel { - /// The open chat's footer: approvals, status, queue, commands and the composer. + /// The open chat's footer: queue, commands and the composer. pub(super) fn render_footer( &mut self, window: &mut Window, @@ -20,8 +20,6 @@ impl AgentPanel { return div().into_any_element(); }; let frame = super::composer_frame::ComposerFrame::read(&thread, cx); - let approvals = self.render_approvals(&thread, window, cx); - let status = self.chat_status(&thread, cx); let labels = attachments::AttachmentLabels::new(thread.read(cx).workspace_seat(), cx); let queue = (!thread.read(cx).composer().queue().is_empty()).then(|| self.layout.parts().queue()); @@ -30,8 +28,6 @@ impl AgentPanel { v_flex() .w_full() .min_w_0() - .children(approvals) - .children(status) .children(queue) .children(commands) .child(composer) diff --git a/crates/agent/src/panel/layout.rs b/crates/agent/src/panel/layout.rs index cb33a11f..9317ec48 100644 --- a/crates/agent/src/panel/layout.rs +++ b/crates/agent/src/panel/layout.rs @@ -91,7 +91,7 @@ pub(super) struct PanelLayout { parts: super::parts::PanelParts, } impl PanelLayout { - pub(super) fn new(layout: LayoutHandle, cx: &mut Context) -> Self { + pub(super) fn new(layout: LayoutHandle, window: &Window, cx: &mut Context) -> Self { let mut bindings = Vec::new(); let splits = [1, 0].map(|index| { let split = cx.new(|_| ResizableState::default()); @@ -112,6 +112,8 @@ impl PanelLayout { panel.on_shared_history_width_changed(value, cx) }); })); + let parts = super::parts::PanelParts::new(cx); + bindings.push(parts.observe_status_visibility(window)); Self { history: true, widened: None, @@ -121,7 +123,7 @@ impl PanelLayout { layout, _bindings: bindings, refresh: std::array::from_fn(|_| SplitRefresh::Idle), - parts: super::parts::PanelParts::new(cx), + parts, } } pub(super) fn history(&self) -> bool { diff --git a/crates/agent/src/panel/lifecycle.rs b/crates/agent/src/panel/lifecycle.rs index 7946f9ed..8f38b016 100644 --- a/crates/agent/src/panel/lifecycle.rs +++ b/crates/agent/src/panel/lifecycle.rs @@ -507,7 +507,7 @@ impl AgentPanel { let stamp = super::parts::transcript_stamp(loaded.read(cx)); let parts = self.layout.parts(); parts.transcript_changed(rows, stamp, cx); - parts.notify(super::parts::PartKind::Footer, cx); + parts.notify_chat_footer(cx); } self.schedule_history_redraw(cx); } diff --git a/crates/agent/src/panel/parts.rs b/crates/agent/src/panel/parts.rs index 01cbf57c..9f7b2549 100644 --- a/crates/agent/src/panel/parts.rs +++ b/crates/agent/src/panel/parts.rs @@ -3,19 +3,22 @@ //! Cached regions are reused unless they are notified. Any notify of the panel //! invalidates all of them, so state the panel changes stays correct by default; //! thread changes, typing and queue disclosure can target a single region. -//! The footer (approvals, status, queue, commands and composer) is cached to its +//! Approvals and animated status are independent siblings of the footer. +//! The footer (queue, commands and composer) is cached to its //! content while its pickers are closed. Open pickers keep their interaction state //! live instead of reusing a content-sized cache's deferred popup. use super::{AgentPanel, history::HistoryViewport}; use gpui_kit::{ App, AppContext as _, Context, Entity, IntoElement, Render, StyleRefinement, Styled, - WeakEntity, Window, div, + Subscription, WeakEntity, Window, div, }; use std::hash::{Hash, Hasher}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PartKind { Transcript, + Approvals, + Status, Footer, Queue, } @@ -48,6 +51,8 @@ impl Render for HistoryPart { pub(super) struct PanelParts { transcript: Entity, history: Entity, + approvals: Entity, + status: Entity, footer: Entity, queue: Entity, transcript_seen: Option, @@ -61,6 +66,8 @@ impl PanelParts { cx.new(|_| PanelPart { panel, kind }) }; let transcript = part(PartKind::Transcript); + let approvals = part(PartKind::Approvals); + let status = part(PartKind::Status); let footer = part(PartKind::Footer); let queue = part(PartKind::Queue); let history = cx.new(|_| HistoryPart { @@ -70,6 +77,8 @@ impl PanelParts { Self { transcript, history, + approvals, + status, footer, queue, transcript_seen: None, @@ -96,6 +105,27 @@ impl PanelParts { .min_w_0(), ) } + /// Approvals stay above the status and composer without being rebuilt by animation. + pub(super) fn approvals(&self) -> impl IntoElement + use<> { + self.approvals + .clone() + .cached_to_content(StyleRefinement::default().w_full()) + } + /// The animation owns layout-time element state (including its paced wake). + /// Do not use a content-sized replay cache here: its replay only preserves + /// prepaint/paint state, not an animation's layout-time state. The surrounding + /// panel remains cached and the expensive sibling regions are independent. + pub(super) fn status(&self) -> impl IntoElement + use<> { + self.status.clone() + } + /// Visibility is not focus. Repaint the status when a hidden window is + /// presented again, even if its cached last draw had no animation wake. + pub(super) fn observe_status_visibility(&self, window: &Window) -> Subscription { + let status = self.status.downgrade(); + window.observe_window_visibility(move |_, _, cx| { + let _ = status.update(cx, |_, cx| cx.notify()); + }) + } /// Open pickers must retain their keyed popup, hover and scroll state across frames. pub(super) fn footer(&self, picker_open: bool) -> impl IntoElement + use<> { if picker_open { @@ -107,7 +137,7 @@ impl PanelParts { .into_any_element() } } - /// Keep a static queue available to the status animation's footer redraws. + /// Keep a static queue available to composer redraws. pub(super) fn queue(&self) -> impl IntoElement + use<> { self.queue .clone() @@ -117,11 +147,19 @@ impl PanelParts { pub(super) fn invalidate(&self, cx: &mut App) { self.transcript.update(cx, |_, cx| cx.notify()); self.invalidate_history(cx); + self.notify_chat_footer(cx); + } + /// A chat semantic update may change all of its lower regions. + pub(super) fn notify_chat_footer(&self, cx: &mut App) { + self.notify(PartKind::Approvals, cx); + self.notify(PartKind::Status, cx); self.notify(PartKind::Footer, cx); } pub(super) fn notify(&self, kind: PartKind, cx: &mut App) { let part = match kind { PartKind::Transcript => &self.transcript, + PartKind::Approvals => &self.approvals, + PartKind::Status => &self.status, PartKind::Footer => { self.queue.update(cx, |_, cx| cx.notify()); &self.footer diff --git a/crates/agent/src/panel/tests/approvals.rs b/crates/agent/src/panel/tests/approvals.rs index bb28b0d1..9f0910f2 100644 --- a/crates/agent/src/panel/tests/approvals.rs +++ b/crates/agent/src/panel/tests/approvals.rs @@ -100,7 +100,7 @@ fn live_group_membership_and_revoked_registration_reject_stale_terminal_ids( icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![summary]))); + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![summary]))); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { workspace.set_connection_directory(directory.clone()) diff --git a/crates/agent/src/panel/tests/composer.rs b/crates/agent/src/panel/tests/composer.rs index 1c2b1fff..5d6377cf 100644 --- a/crates/agent/src/panel/tests/composer.rs +++ b/crates/agent/src/panel/tests/composer.rs @@ -23,7 +23,7 @@ fn attach_menu_lists_servers_under_their_folders(cx: &mut TestAppContext) { icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![ + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![ server("proxmox", Some("homelab")), server("backup", None), server("ai-server", Some("homelab")), diff --git a/crates/agent/src/panel/tests/composer/menu_stability.rs b/crates/agent/src/panel/tests/composer/menu_stability.rs index 56ae4c74..c1cda638 100644 --- a/crates/agent/src/panel/tests/composer/menu_stability.rs +++ b/crates/agent/src/panel/tests/composer/menu_stability.rs @@ -13,7 +13,7 @@ impl gpui_kit::Render for PanelHost { } fn many_servers(f: &Fixture, cx: &mut TestAppContext) -> Rc { - let directory = Rc::new(Directory(std::cell::RefCell::new( + let directory = Rc::new(Directory::new(std::cell::RefCell::new( (0..35) .map(|index| super::super::servers::summary(&format!("server-{index:02}"), None)) .collect(), diff --git a/crates/agent/src/panel/tests/invalidation.rs b/crates/agent/src/panel/tests/invalidation.rs index 1a067b00..3eec3b02 100644 --- a/crates/agent/src/panel/tests/invalidation.rs +++ b/crates/agent/src/panel/tests/invalidation.rs @@ -563,3 +563,103 @@ fn a_growing_draft_grows_the_cached_composer_below_the_transcript(cx: &mut TestA "the transcript gives way: {transcript:?} above {after:?}" ); } + +fn painted_thinking_tiles(f: &Fixture, cx: &mut TestAppContext) -> Vec { + cx.update_window(f.handle, |_, window, _| { + let scale = window.scale_factor(); + let indicator = window.find("agent-thinking").bounds(); + window + .painted_quads() + .into_iter() + .filter(|quad| { + let x = gpui_kit::px(quad.bounds.origin.x.0 / scale); + let y = gpui_kit::px(quad.bounds.origin.y.0 / scale); + indicator.contains(&gpui_kit::point(x, y)) + && (quad.bounds.size.width.0 / scale - 6.).abs() < 0.1 + && (quad.bounds.size.height.0 / scale - 6.).abs() < 0.1 + }) + .collect::>() + }) + .unwrap() +} + +fn advance_thinking_frame(f: &Fixture, cx: &mut TestAppContext, millis: u64) { + cx.executor() + .advance_clock(std::time::Duration::from_millis(millis)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); +} + +#[gpui_kit::test] +fn thinking_animation_does_not_rebuild_attachment_labels(cx: &mut TestAppContext) { + let f = fixture(cx); + let directory = Rc::new(Directory::new(Default::default())); + cx.update(|cx| { + f.workspace.update(cx, |workspace, _| { + workspace.set_connection_directory(directory.clone()); + }); + }); + new_chat(&f, cx); + let thread = cx.update(|cx| f.panel.read(cx).current().unwrap()); + thread.update(cx, |thread, cx| thread.send("Think".into(), cx)); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| { + window.activate_window(); + // Exclude the composer's independent 500ms cursor blink from the + // measurement; the visible thinking indicator does not require focus. + window.blur(cx); + window.render_frame(cx); + assert!(window.try_find("agent-thinking").is_some()); + }) + .unwrap(); + cx.run_until_parked(); + // Let the initial chat notifications and coalesced history update settle + // before counting steady-state animation work. + for _ in 0..4 { + advance_thinking_frame(&f, cx, 25); + } + let start = painted_thinking_tiles(&f, cx); + let before = directory.reads(); + for _ in 0..20 { + advance_thinking_frame(&f, cx, 25); + } + let reads = directory.reads() - before; + assert_eq!( + reads, 0, + "thinking animation must not rebuild attachment labels" + ); + let end = painted_thinking_tiles(&f, cx); + assert_eq!(start.len(), 3); + assert_eq!(end.len(), 3); + assert_ne!(start, end, "timed redraws must actually move the indicator"); + + cx.simulate_window_visibility_change(f.handle, gpui_kit::WindowVisibility::Hidden); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); + let hidden = painted_thinking_tiles(&f, cx); + advance_thinking_frame(&f, cx, 200); + assert_eq!( + hidden, + painted_thinking_tiles(&f, cx), + "hidden animation rests" + ); + cx.simulate_window_visibility_change(f.handle, gpui_kit::WindowVisibility::Visible); + cx.run_until_parked(); + cx.update_window(f.handle, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); + let restored = painted_thinking_tiles(&f, cx); + advance_thinking_frame(&f, cx, 200); + assert_ne!( + restored, + painted_thinking_tiles(&f, cx), + "visible window must resume the loop" + ); + complete_active(&f, cx); + cx.update_window(f.handle, |_, window, cx| { + window.draw(cx).clear(cx); + assert!(window.try_find("agent-thinking").is_none()); + }) + .unwrap(); +} diff --git a/crates/agent/src/panel/tests/mod.rs b/crates/agent/src/panel/tests/mod.rs index f64affe1..97095ce5 100644 --- a/crates/agent/src/panel/tests/mod.rs +++ b/crates/agent/src/panel/tests/mod.rs @@ -465,9 +465,21 @@ fn exchange(f: &Fixture, text: &str, answer: &str, cx: &mut TestAppContext) -> S session } -struct Directory(std::cell::RefCell>); +struct Directory( + std::cell::RefCell>, + std::cell::Cell, +); +impl Directory { + fn new(entries: std::cell::RefCell>) -> Self { + Self(entries, std::cell::Cell::new(0)) + } + fn reads(&self) -> usize { + self.1.get() + } +} impl nocterm_workspace::ConnectionDirectory for Directory { fn connections(&self, _: &App) -> Vec { + self.1.set(self.1.get() + 1); self.0.borrow().clone() } fn open( diff --git a/crates/agent/src/panel/tests/servers/menu.rs b/crates/agent/src/panel/tests/servers/menu.rs index 4104e52b..a30db28a 100644 --- a/crates/agent/src/panel/tests/servers/menu.rs +++ b/crates/agent/src/panel/tests/servers/menu.rs @@ -62,7 +62,7 @@ fn servers_with_the_same_display_name_keep_independent_attachment_choices(cx: &m db.name = "Same name".into(); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { - workspace.set_connection_directory(Rc::new(Directory(RefCell::new(vec![web, db])))) + workspace.set_connection_directory(Rc::new(Directory::new(RefCell::new(vec![web, db])))) }) }); new_chat(&f, cx); diff --git a/crates/agent/src/panel/tests/tool_input.rs b/crates/agent/src/panel/tests/tool_input.rs index 119d46f0..ddab9146 100644 --- a/crates/agent/src/panel/tests/tool_input.rs +++ b/crates/agent/src/panel/tests/tool_input.rs @@ -594,7 +594,7 @@ fn verified_destination_uses_the_connected_host_and_survives_rename_detach_and_r icon: None, flag: None, }; - let directory = Rc::new(Directory(std::cell::RefCell::new(vec![summary]))); + let directory = Rc::new(Directory::new(std::cell::RefCell::new(vec![summary]))); cx.update(|cx| { f.workspace.update(cx, |workspace, _| { workspace.set_connection_directory(directory.clone()) diff --git a/crates/agent/src/panel/transcript.rs b/crates/agent/src/panel/transcript.rs index d5c6387f..58af3ab4 100644 --- a/crates/agent/src/panel/transcript.rs +++ b/crates/agent/src/panel/transcript.rs @@ -1,7 +1,7 @@ //! An open chat: the transcript, the plan, pending approvals, the status //! line and the composer. use gpui_kit::{ - AnyElement, SharedString, TestSupportExt as _, + AnyElement, TestSupportExt as _, component::{ActiveTheme as _, h_flex, v_flex}, div, prelude::*, @@ -70,18 +70,10 @@ impl TranscriptView { .text_color(cx.theme().muted_foreground) .when(live, |row| { row.child(div().id("agent-thinking").test_support().child( - nocterm_ui::thinking_indicator( - SharedString::from(format!("agent-thinking-{id}")), - cx.theme().foreground, - ), + nocterm_ui::thinking_indicator(("agent-thinking", id), cx.theme().foreground), )) }) - .child(activity_text( - SharedString::from(format!("agent-live-status-{id}")), - text, - live, - cx, - )) + .child(activity_text("agent-status-label", text, false, cx)) .into_any_element() } } diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index a46ff87a..c3e43bea 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -26,7 +26,6 @@ nocterm-design.workspace = true nocterm-settings.workspace = true gpui-kit.workspace = true -image = { version = "0.25", default-features = false, features = ["webp"] } schemars.workspace = true serde_json.workspace = true serde.workspace = true diff --git a/crates/ui/assets/animations/thinking.webp b/crates/ui/assets/animations/thinking.webp deleted file mode 100644 index cc3b9d0f00a90c279d6a8d10c423515928704ad1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 9630 zcmd^_cTkhvw#Jjti}YTkH<6}vkPZ^*NCyFFiV~_6MI>|tq&MlkNL3_s2u(nwC?H)x zk)qO(ZgSs*!*`Eo?wz^+-*hp&A;gJRp#%x{AJuzO)%J2n3=6 zenqf9%DPY;eBjmjqpYi=K?uHhb^Z=U5C{VNpY}GeEFyv=q394r?REqd{8_bS3VCM4FPdAz*rv79DLbD_ie`B@S3qyLo+tQitay&Az8ow1*9J2 z9LY4uk;;yaxYIP`c<)hH{pZVrKVECdu;t3J z9bV@bW1#+wt|>#_eLOsPS{AIAqBWR0>k^$M{dA0+?FTd3I-5LqSGV8(`z+VK>4Uhw z47L&495-?~8)^uegI+H@g6m3_IE$MQE*U}WDkWs~#%db)Z5+zfXt7p)^?QKPmr|>? z*T@i8@;f8j-nwD(_?Z2818|dIw*=S;dJyPhKVD+?gAs{Gky87DdjN_u7%A-RVh!yz zIHinv_|QwNJluRln1Dt}#3->PkKiUPB39vp?z{W5k^_roUSY3n8*qDHLfY;|N-XJT zXD0-wBn28nsC|4AULklWn7N=Hd)u%hIxkMOX4GU!8wGJfz7NvUfqMUx{l;ywDo=+2 z)t}4)hjfJrSz&F5DGd=XDC?*eFR56HcOG1r$nBZ{~Vw6;rlZ2-==+J!xLd$S{tQ2^g2DI5XKwUW8cCGgf zWW(gxw*M|pvzonJhQTlqu3M*9P)oTj_dOB%_;Xel8pznJ%D?LL`rZMtyYz=ye=TKJ`3^{%z|R{|2YiMxynhqDR;CiU2i+ z;4=^@5%3EFvHnHS2CRs%0tDXDuH4Xsvj$l*r_|VX@6kz0mxnNak7rHet6BCB8DuS- z?vfpdstt2FM9m>!@`)^CpZ}<7K=LHo>w2W5fBv$bVppbM94ul_%2~-vku6;?z1}iU zR_|^U0o!rQH}B8@i+>c8Z=zR0?S_>3ri+(F(Db;%Z-9?WB=a*KC|7=M&| z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f~AAleDH0gt-dlA42p@D zQ8naKFJ?lzIck?kwe#S)vHF z9bD5lT`Mk1om~lMcX6$1Z{t0OYU`-_uMdwYIhUt~6bH+ZBzE5M!B*qUIULY)fZPEh z=^}Ssz`6)M2=IZVJ-MKUz?ljuE^Rg+F%VZ*7kyO^3*Wjvuy}VQS%wn* zh7R$!oA#Vdfudk5q4oTMn#NRO;?=Ip67*K1K>|e1wc6xYyB(3ZA?sMe&*y}IWC92Q z$#g-8=_Y`OOhjRf&EPIt@2CEa@|-`fqPXThBdXL6pOu50qghm7?;pe`L;88LUXqEQ z$%4PUIBT-4ld2sJ9aG|OHWz&`uG!le!dEkRoh2DBv@2NCIWlvc)7XrCHLhy{Gi3#wHFeLkfeBMpc-w>W9 z9pqwW`nJNTfV3f%6qjKrlfaZrQ=xPXOJ&)n^Nq z?%&;?Xe|;BEhmYJyPOP@pI7WqM4ncL^bey9LNAwq%^43q7@FxJas8y0e>IvKqe6Q%U{vBP+*O$Z{CfKM z_?_R+V-hv0VZl3Daf<+3(7vQqj|5p3o-*#>`)J0@yRX6dhI?Gc;kgB#uNDWa=>3C@ zxi~fkhxWwWn%Ea@lhd;*bz4wOwAjq`oM#RYQUKe(Ip>w#Kw&YStJaN;FhT#3bJ`a5+UC#JmDUf=+Rl z9o+Zm8s9XXXz}2FeJ5Am5Zq-noh_wdOhTHjy^Lz9(T*3L8SHc0ODPe7BMnZToNl#h zQHsY`2OJtbycf(6CyMOAsV&%cFUPq` zP+kWzQ}#29CQTA0B5YRvbqfO|=U4CrNePC80qbR9^dZJ?6kPmc0drOht(ZZi5c@_j zF-2aRfiP(j;^$HYbvB&t`SK#^@kB;9U&(pcRTuaJA0xoZ%mG yIurU;h3S%zj=7K+ad9e0um+U&g-^woX@rGr$&Z&|`ucx, color: Hsla) -> impl IntoElement { - let tint = Tint::from(color); - let source = ImageSource::Custom(Arc::new(move |window, cx: &mut App| { - window.use_asset::(&tint, cx) - })); - gpui_kit::img(source).id(id).flex_shrink_0().size(px(16.)) + ThinkingIndicator { + id: id.into(), + color, + } } -/// A colour as straight 8-bit BGRA, the image cache's pixel layout. -#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] -struct Tint([u8; 4]); +#[derive(IntoElement)] +struct ThinkingIndicator { + id: ElementId, + color: Hsla, +} -impl From for Tint { - fn from(color: Hsla) -> Self { - let rgba = color.to_rgb(); - let byte = |channel: f32| (channel.clamp(0., 1.) * 255.).round() as u8; - Self([byte(rgba.b), byte(rgba.g), byte(rgba.r), byte(rgba.a)]) +impl RenderOnce for ThinkingIndicator { + fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement { + let frame = ThinkingFrame { + phase: 0., + color: self.color, + }; + // An unfocused but visible window still plays. The toolkit respects the + // OS reduce-motion preference, and its timed wake belongs to the drawn view. + if window.is_visible() { + frame + .with_animation( + self.id, + Animation::new(CYCLE) + .repeat_synced() + .with_max_fps(UPDATES_PER_SECOND), + |mut frame, phase| { + frame.phase = phase; + frame + }, + ) + .into_any_element() + } else { + frame.into_any_element() + } } } -/// The thinking animation tinted to one colour. -enum ThinkingAnimation {} - -impl Asset for ThinkingAnimation { - type Source = Tint; - type Output = Result, ImageCacheError>; - - #[expect( - clippy::manual_async_fn, - reason = "an `async fn` future would borrow `App`, which is neither `Send` nor `'static`" - )] - fn load( - tint: Self::Source, - _: &mut App, - ) -> impl Future + Send + 'static { - async move { tinted(THINKING, tint).map(Arc::new) } - } +#[derive(IntoElement)] +struct ThinkingFrame { + phase: f32, + color: Hsla, } -/// Decodes the animated mask `bytes` with every pixel painted `tint`, -/// keeping the mask's coverage as alpha. -fn tinted(bytes: &[u8], tint: Tint) -> Result { - let mut decoder = WebPDecoder::new(Cursor::new(bytes)).map_err(image_error)?; - decoder - .set_background_color(Rgba([0, 0, 0, 0])) - .map_err(image_error)?; - let [b, g, r, a] = tint.0; - let mut frames = Vec::new(); - for frame in decoder.into_frames() { - let mut frame = frame.map_err(image_error)?; - for pixel in frame.buffer_mut().as_chunks_mut::<4>().0 { - let coverage = u16::from(pixel[3]) * u16::from(a) / 255; - *pixel = [b, g, r, coverage as u8]; - } - frames.push(frame); +impl RenderOnce for ThinkingFrame { + fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, (), window, _| { + for [x, y] in tiles(self.phase) { + window.paint_quad(quad( + Bounds::new(bounds.origin + point(px(x), px(y)), size(px(6.), px(6.))), + px(1.25), + self.color, + Edges::default(), + transparent_black(), + BorderStyle::default(), + )); + } + }, + ) + .size(px(16.)) + .flex_shrink_0() } - Ok(RenderImage::new(frames)) } -fn image_error(error: image::ImageError) -> ImageCacheError { - ImageCacheError::Image(Arc::new(error)) +/// A smoothstep gives each tile zero velocity at its endpoints. Consecutive +/// segments describe exactly the same occupied corners at the seam. +fn tiles(phase: f32) -> [[f32; 2]; 3] { + let step = phase.rem_euclid(1.) * 4.; + let gap = step.floor() as usize; + let next = (gap + 1) % 4; + let t = step.fract(); + let t = t * t * (3. - 2. * t); + let moving = std::array::from_fn(|axis| { + POSITIONS[next][axis] + (POSITIONS[gap][axis] - POSITIONS[next][axis]) * t + }); + [moving, POSITIONS[(gap + 2) % 4], POSITIONS[(gap + 3) % 4]] } #[cfg(test)] mod tests { - use super::{THINKING, Tint, tinted}; + use super::*; + use gpui_kit::{AppContext as _, Context, Render, TestAppContext, WindowHandle, div}; + + fn same_tiles(left: [[f32; 2]; 3], right: [[f32; 2]; 3]) -> bool { + left.iter().all(|a| { + right + .iter() + .any(|b| (a[0] - b[0]).abs() < 0.001 && (a[1] - b[1]).abs() < 0.001) + }) + } #[test] - fn thinking_indicator_animates_in_the_requested_colour() { - let black = tinted(THINKING, Tint::from(gpui_kit::black())).unwrap(); - assert!(black.frame_count() > 1); - let pixels = black.as_bytes(0).unwrap().as_chunks::<4>().0.iter(); - assert!(pixels.clone().any(|pixel| pixel[3] > 0)); - assert!(pixels.clone().any(|pixel| pixel[3] == 0)); - assert!(pixels.clone().all(|pixel| pixel[..3] == [0, 0, 0])); + fn thinking_tiles_are_continuous_at_every_corner_and_loop_seam() { + for boundary in [0.25, 0.5, 0.75, 1.] { + assert!(same_tiles(tiles(boundary - 0.0001), tiles(boundary))); + assert!(same_tiles(tiles(boundary), tiles(boundary + 0.0001))); + } + assert!(same_tiles(tiles(0.), tiles(1.))); + assert!(!same_tiles(tiles(0.), tiles(0.125))); + for index in 0..1600 { + let positions = tiles(index as f32 / 1600.); + for [x, y] in positions { + assert!((1.5..=8.5).contains(&x)); + assert!((1.5..=8.5).contains(&y)); + } + } + } + + struct Preview(bool); + impl Render for Preview { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + use gpui_kit::ParentElement as _; + div().children( + self.0 + .then(|| thinking_indicator("thinking", gpui_kit::white())), + ) + } + } + + fn painted(window: WindowHandle, cx: &mut TestAppContext) -> Vec { + cx.update_window(window.into(), |_, window, cx| { + window.draw(cx).clear(cx); + window.painted_quads() + }) + .unwrap() + } - let white = tinted(THINKING, Tint::from(gpui_kit::white())).unwrap(); - let pixels = white.as_bytes(0).unwrap().as_chunks::<4>().0.iter(); - assert!(pixels.clone().all(|pixel| pixel[..3] == [255, 255, 255])); + #[gpui_kit::test] + fn thinking_indicator_paints_three_quads_and_loops_without_focus(cx: &mut TestAppContext) { + let window = cx.open_window(size(px(100.), px(100.)), |_, _| Preview(true)); + cx.run_until_parked(); + window + .update(cx, |_, window, _| assert!(!window.is_window_active())) + .unwrap(); + let start = painted(window, cx); + assert_eq!(start.len(), 3); + cx.executor().advance_clock(Duration::from_millis(200)); + cx.run_until_parked(); + let middle = painted(window, cx); + assert_eq!(middle.len(), 3); + assert_ne!( + start, middle, + "visible window must animate without relying on OS focus" + ); + // A delayed draw is immediately back at the matching cycle phase. + cx.executor().advance_clock(CYCLE); + cx.run_until_parked(); + assert_eq!(painted(window, cx), middle); + cx.update(|cx| cx.set_reduce_motion(true)); + cx.run_until_parked(); + let static_frame = painted(window, cx); + cx.executor().advance_clock(Duration::from_millis(200)); + cx.run_until_parked(); + assert_eq!(painted(window, cx), static_frame); + window + .update(cx, |view, _, cx| { + view.0 = false; + cx.notify(); + }) + .unwrap(); + cx.run_until_parked(); + assert!(painted(window, cx).is_empty()); } } diff --git a/docs/architecture/feature.md b/docs/architecture/feature.md index 40293fcb..1acf80f4 100644 --- a/docs/architecture/feature.md +++ b/docs/architecture/feature.md @@ -741,9 +741,13 @@ each agent message's and expanded reasoning's parsed Markdown per row, so a row scrolled back into view keeps its parse. The chat document's transcript generation marks replacements. Within one generation, stream updates and reveal ticks let the row sanitize and parse just the appended text, unless an image marker crosses the -chunk boundary. PanelLayout keeps the panel's regions as cached views: the transcript, the -history and the footer (approvals, status, queue, commands and composer), which is -cached to its content and keeps its last height while reused. Any panel notify +chunk boundary. PanelLayout keeps separate views for the transcript, history, +approvals, status and footer (queue, commands and composer). The approval and +footer regions are cached to their content and retain their last +height while reused. The status stays live so its layout-time animation wake is +not discarded by content-sized replay. The thinking indicator paints three +time-based rounded quads; its paced redraw invalidates only the status region, +without rebuilding the composer or its attachment index. Any panel notify redraws every region; a change of the open chat redraws the transcript only when its rows or what they show changed, typing redraws the footer, and the coalesced redraw of other chats redraws the history only