返回 CodeWhale
motion.rs
根目录 / crates / tui / src / tui / ui / motion.rs
1 //! Redraw pacing: animation intervals, live-motion predicates, and the rail's
2 //! size budgets.
3 //!
4 //! Moved verbatim out of `ui.rs`.
5
6 use super::*;
7
8 /// Select a workbar panel from a keyboard shortcut and say what happened.
9 /// When the workbar is off the panel change is real but invisible, so the
10 /// status names that instead of implying something rendered.
11 pub(crate) fn rail_panel_shortcut(app: &mut App, panel: crate::tui::work_surface::RailPanel) {
12 crate::tui::work_surface::select_dock_panel(app, panel);
13 app.needs_redraw = true;
14 let mut message = format!("Workbar panel: {}", panel.as_setting());
15 if app.work_surface.placement == crate::tui::work_surface::WorkSurfacePlacement::Off {
16 message.push_str(" (workbar is off — /workbar top to show)");
17 }
18 app.show_command_result(message, StatusToastLevel::Info);
19 }
20
21 /// #3033: gate progress-driven repaints to at most one per 100ms.
22 ///
23 /// Returns whether the current `AgentProgress` event may request a redraw,
24 /// updating the last-redraw timestamp when it may. Data updates are never
25 /// throttled — only the repaint request is.
26 pub(crate) fn agent_progress_redraw_permitted(
27 last_redraw: &mut Option<Instant>,
28 now: Instant,
29 ) -> bool {
30 match *last_redraw {
31 Some(last) if now.duration_since(last) < Duration::from_millis(100) => false,
32 _ => {
33 *last_redraw = Some(now);
34 true
35 }
36 }
37 }
38
39 pub(crate) fn agent_progress_redraw_permitted_for_drain(
40 last_redraw: &mut Option<Instant>,
41 seen_agents: &mut HashSet<String>,
42 agent_id: &str,
43 now: Instant,
44 ) -> bool {
45 if !seen_agents.insert(agent_id.to_string()) {
46 return false;
47 }
48 agent_progress_redraw_permitted(last_redraw, now)
49 }
50
51 /// Rows the transcript can spare for the work rail this frame.
52 ///
53 /// Everything above the transcript is decoration relative to the transcript
54 /// itself, so the rail is paid out of what is *left over* after the fixed
55 /// chrome and the transcript's own floor — not out of a fraction of the
56 /// terminal, which at 24 rows would hand the rail half the screen.
57 ///
58 /// That floor moves. While the shell is fully idle the transcript is showing
59 /// the ocean, and the ocean does not draw at all below
60 /// [`AMBIENT_MIN_CHAT_HEIGHT`](crate::tui::underwater::AMBIENT_MIN_CHAT_HEIGHT)
61 /// rows — so on a 24-row terminal an always-on panel strip does not shrink
62 /// the water, it deletes it. Once there is real work on screen the floor
63 /// drops back to [`MIN_CHAT_HEIGHT`] and the rail gets its rows. Decorative
64 /// water yields to work; work never yields to decoration.
65 ///
66 /// `idle_empty` alone is not enough to charge that floor. It is an
67 /// app-state predicate — it knows the session is quiet, not that the terminal
68 /// can draw. [`empty_state_mark_visible`](crate::tui::underwater::empty_state_mark_visible)
69 /// also demands
70 /// [`AMBIENT_MIN_CHAT_WIDTH`](crate::tui::underwater::AMBIENT_MIN_CHAT_WIDTH)
71 /// columns, so on a narrow terminal charging the ambient floor would reserve
72 /// 16 rows for a mark that cannot render at any height and make the strip
73 /// yield for nothing.
74 ///
75 /// The row half of that gate is deliberately *not* mirrored here. It would be
76 /// a step down in terminal *height* — below the floor the rail would take the
77 /// rows, at the floor it would hand them back — and a strip that vanishes as
78 /// the terminal grows taller is the resize flicker this budget exists to
79 /// avoid. The swept axis must stay monotone.
80 ///
81 /// The column gate is a real trade, not a free one, and an earlier version of
82 /// this comment wrongly claimed otherwise. Widening past
83 /// `AMBIENT_MIN_CHAT_WIDTH` on a short-but-tall terminal can swap a strip for
84 /// the ocean in one column step. That is accepted deliberately: a horizontal
85 /// resize past 60 columns is a deliberate act with a visible payoff (the
86 /// water appears), whereas the height version fires while dragging the axis
87 /// the strip is measured in. Both cannot be monotone at once — charging the
88 /// floor is what buys the whale its rows, and something has to give.
89 /// `rail_strip_and_whale_swap_at_the_ambient_width` pins the swap so it stays
90 /// a decision rather than drifting into an accident.
91 ///
92 /// The composer is charged at a fixed floor rather than its measured height:
93 /// the real `composer_height` is itself computed from the strip height, and
94 /// feeding it back in here would close a loop that oscillates across a
95 /// resize instead of settling.
96 pub(crate) fn rail_row_budget(
97 app: &App,
98 terminal_width: u16,
99 terminal_height: u16,
100 idle_empty: bool,
101 ) -> u16 {
102 // An explicit work-bar choice takes priority over decorative empty-state
103 // space, just as real transcript content does. Otherwise Ctrl+] can be
104 // accepted while the ambient floor immediately hides its result.
105 let ambient_mark_can_draw = idle_empty
106 && !app.work_surface.explicit_view
107 && terminal_width >= crate::tui::underwater::AMBIENT_MIN_CHAT_WIDTH;
108 let chat_floor = if ambient_mark_can_draw {
109 crate::tui::underwater::AMBIENT_MIN_CHAT_HEIGHT
110 } else {
111 MIN_CHAT_HEIGHT
112 };
113 let composer_floor = crate::tui::composer_chrome::desired_height(
114 1,
115 0,
116 terminal_height,
117 app.composer_density,
118 crate::tui::widgets::composer_enclosure_enabled(app),
119 );
120 terminal_height
121 .saturating_sub(info_row_height_for(terminal_height))
122 // The merged Tideline footer is one row (spec §3: slots 6+8
123 // collapsed into it) — the shell no longer brackets the composer
124 // with two standing bands.
125 .saturating_sub(crate::tui::phase_strip::height())
126 .saturating_sub(composer_floor)
127 .saturating_sub(chat_floor)
128 }
129
130 /// The info line is one row under the posture row (spec §5b:
131 /// `Constraint::Length(1)`), at every terminal height. Shared so the rail
132 /// budget charges the same chrome the layout actually reserves.
133 pub(crate) fn info_row_height_for(_terminal_height: u16) -> u16 {
134 1
135 }
136
137 /// Column-axis twin of [`rail_row_budget`]: the columns a side rail must
138 /// leave the transcript.
139 pub(crate) fn rail_min_chat_width(idle_empty: bool) -> u16 {
140 if idle_empty {
141 crate::tui::underwater::AMBIENT_MIN_CHAT_WIDTH
142 } else {
143 0
144 }
145 }
146
147 fn working_clock_has_glow(app: &App) -> bool {
148 app.motion_policy().should_request_animation_frames()
149 && app.viewport.transcript_scroll.is_at_tail()
150 && app.viewport.working_glow_visible
151 && app.posture_bar == codewhale_runtime::config::ChromeRowPreset::Full
152 && !crate::tui::pet_watch::main_view(app)
153 && app.turn_started_at.is_some()
154 && app
155 .viewport
156 .ocean_caps
157 .is_some_and(|caps| caps.depth == codewhale_ratatui::color::ColorDepth::TrueColor)
158 && matches!(
159 crate::tui::underwater::ShellPhase::from_app(app),
160 crate::tui::underwater::ShellPhase::Working
161 | crate::tui::underwater::ShellPhase::Verifying
162 )
163 }
164
165 pub(crate) fn activity_sweep_allowed(app: &App) -> bool {
166 app.motion_policy().should_request_animation_frames()
167 && !app.effective_low_motion_for_status()
168 && app
169 .viewport
170 .ocean_caps
171 .is_some_and(|caps| caps.depth == codewhale_ratatui::color::ColorDepth::TrueColor)
172 && matches!(app.ui_theme.text_body, ratatui::style::Color::Rgb(..))
173 }
174
175 fn composer_border_lit(app: &App) -> bool {
176 app.turn_started_at.is_some()
177 && crate::tui::widgets::composer_enclosure_enabled(app)
178 && app.composer_display_input().trim().is_empty()
179 }
180
181 pub(crate) fn composer_border_breathes(app: &App) -> bool {
182 composer_border_lit(app)
183 && activity_sweep_allowed(app)
184 && !app.viewport.activity_sweep_visible
185 && app.viewport.transcript_scroll.is_at_tail()
186 && !decision_prompt_waiting(app)
187 && matches!(app.ui_theme.border, ratatui::style::Color::Rgb(..))
188 && matches!(app.ui_theme.status_working, ratatui::style::Color::Rgb(..))
189 }
190
191 pub(crate) fn composer_live_border(app: &App) -> Option<ratatui::style::Color> {
192 use codewhale_ratatui::tokens::{MOTION_DURATION_PANEL_MS, MOTION_LOOP_BREATHE_MS};
193 let started = app.turn_started_at.filter(|_| composer_border_lit(app))?;
194 if decision_prompt_waiting(app) {
195 return Some(app.ui_theme.accent_action);
196 }
197 let (border, lit) = (app.ui_theme.border, app.ui_theme.status_working);
198 if !matches!(
199 (border, lit),
200 (
201 ratatui::style::Color::Rgb(..),
202 ratatui::style::Color::Rgb(..)
203 )
204 ) {
205 return Some(lit);
206 }
207 let elapsed = started.elapsed();
208 let mut level = 0.5;
209 if composer_border_breathes(app) {
210 let since = elapsed.saturating_sub(std::time::Duration::from_millis(
211 codewhale_tui_kit::spinner::LIVE_MARKER_DELAY_MS,
212 ));
213 let phase =
214 (since.as_millis() % MOTION_LOOP_BREATHE_MS as u128) as f32 / MOTION_LOOP_BREATHE_MS;
215 let swing = 0.5 - 0.5 * (std::f32::consts::TAU * phase).cos();
216 level = 0.3 + (swing * 7.0).round() / 7.0 * 0.4;
217 }
218 if activity_sweep_allowed(app) {
219 let arrive = (elapsed.as_millis() as f32 / MOTION_DURATION_PANEL_MS).min(1.0);
220 level *= codewhale_ratatui::MotionEasing::EaseOut.apply(arrive);
221 }
222 Some(codewhale_ratatui::color::mix_oklab(border, lit, level))
223 }
224
225 fn activity_motion_visible(app: &App) -> bool {
226 activity_sweep_allowed(app)
227 && (app.viewport.activity_sweep_visible
228 || app.viewport.settle_flash_visible
229 || working_clock_has_glow(app)
230 || composer_border_breathes(app))
231 }
232
233 pub(crate) fn status_animation_interval_ms(app: &App) -> u64 {
234 if app.effective_low_motion_for_status() {
235 crate::tui::display_refresh::adaptive_animation_interval_ms(true)
236 } else if decision_prompt_waiting(app)
237 || !(app.is_loading
238 || app.is_compacting
239 || app.is_purging
240 || working_clock_has_glow(app)
241 || crate::tui::subagent_routing::running_agent_count(app) > 0)
242 {
243 UI_QUIET_STATUS_ANIMATION_MS
244 } else if activity_motion_visible(app) {
245 UI_ACTIVITY_ANIMATION_MS
246 } else {
247 // Keep the braille marker on its fixed 5 Hz table for width stability;
248 // only atmosphere uses the measured display cadence.
249 UI_STATUS_ANIMATION_MS
250 }
251 }
252
253 /// Tick interval for the water. `tier` is the draw cadence the frame limiter
254 /// enforces this frame: while only ambience moves, the tick lands exactly on
255 /// the atmosphere interval the limiter will draw at, so no wake asks for a
256 /// frame the limiter then holds. While a turn streams or the user types, the
257 /// limiter runs at the interactive cap and the authored ocean cadence rides
258 /// inside it unchanged.
259 pub(crate) fn underwater_animation_interval_ms(
260 app: &App,
261 tier: crate::tui::display_refresh::DrawCadenceTier,
262 ) -> u64 {
263 use crate::tui::display_refresh::DrawCadenceTier;
264 if app.effective_low_motion_for_status() || app.low_motion {
265 crate::tui::display_refresh::adaptive_animation_interval_ms(true)
266 } else if app.constrained_frame_rate {
267 UI_CONSTRAINED_UNDERWATER_ANIMATION_MS
268 } else if crate::tui::display_refresh::terminal_is_ghostty() {
269 UI_GHOSTTY_UNDERWATER_ANIMATION_MS
270 } else {
271 // Measured display Hz can raise atmosphere cadence on high-Hz
272 // panels; missing probe falls back to the ~8 fps floor.
273 let atmosphere = crate::tui::display_refresh::adaptive_animation_interval_ms(false);
274 match tier {
275 DrawCadenceTier::Atmosphere => atmosphere,
276 DrawCadenceTier::Interactive => atmosphere.min(UI_UNDERWATER_ANIMATION_MS),
277 }
278 }
279 }
280
281 /// Whether any underwater motion owner is actually visible in the transcript
282 /// host. This keeps the scheduler honest: only the explicit underwater
283 /// treatment earns a viewport budget, and obscured surfaces never request
284 /// frames.
285 #[must_use]
286 pub(crate) fn underwater_motion_surface_visible(
287 area: Option<Rect>,
288 underwater_atmosphere_enabled: bool,
289 deepsea_field_breathes: bool,
290 empty_water_visible: bool,
291 obscured: bool,
292 ) -> bool {
293 if obscured || !underwater_atmosphere_enabled {
294 return false;
295 }
296 area.is_some_and(|area| {
297 area.width > 0
298 && area.height > 0
299 && (deepsea_field_breathes
300 || (area.width >= crate::tui::ocean::AMBIENT_MIN_WIDTH
301 && area.height >= crate::tui::ocean::AMBIENT_MIN_HEIGHT)
302 || (empty_water_visible && crate::tui::underwater::empty_state_mark_visible(area)))
303 })
304 }
305
306 pub(crate) fn underwater_life_motion_requested(app: &App, obscured: bool, settled: bool) -> bool {
307 !obscured
308 && !settled
309 && crate::tui::underwater::ambient_life_motion_enabled(app)
310 && app.viewport.last_transcript_area.is_some_and(|area| {
311 area.width >= crate::tui::ocean::AMBIENT_MIN_WIDTH
312 && area.height >= crate::tui::ocean::AMBIENT_MIN_HEIGHT
313 })
314 }
315
316 pub(crate) fn animation_interval_ms(
317 app: &App,
318 status_motion: bool,
319 underwater_motion: bool,
320 tier: crate::tui::display_refresh::DrawCadenceTier,
321 ) -> u64 {
322 let underwater = underwater_animation_interval_ms(app, tier);
323 match (status_motion, underwater_motion) {
324 (true, true) => status_animation_interval_ms(app).min(underwater),
325 (true, false) => status_animation_interval_ms(app),
326 (false, true) => underwater,
327 (false, false) => underwater,
328 }
329 }
330
331 pub(crate) fn should_tick_status_animation(
332 app: &App,
333 has_running_agents: bool,
334 history_has_live_motion: bool,
335 active_cell_has_live_motion: bool,
336 translation_placeholder_has_live_motion: bool,
337 ) -> bool {
338 !matches!(app.motion_policy().mode(), MotionMode::Still)
339 && app.viewport.transcript_scroll.is_at_tail()
340 && (app.is_loading
341 || working_clock_has_glow(app)
342 || composer_border_breathes(app)
343 || app.viewport.settle_flash_visible
344 || has_running_agents
345 || app.is_compacting
346 || app.is_purging
347 || history_has_live_motion
348 || active_cell_has_live_motion
349 || translation_placeholder_has_live_motion
350 || visible_background_task_has_live_motion(app))
351 }
352
353 pub(crate) fn visible_background_task_has_live_motion(app: &App) -> bool {
354 app.work_surface.panel == crate::tui::work_surface::RailPanel::Tasks
355 && app.work_surface.last_area.is_some()
356 && app.task_panel.iter().any(|task| task.status == "running")
357 }
358
359 pub(crate) fn active_cell_has_live_motion(app: &App) -> bool {
360 app.active_cell
361 .as_ref()
362 .is_some_and(|active| active.entries().iter().any(HistoryCell::has_live_motion))
363 }
364
365 pub(crate) fn history_has_live_motion(history: &[HistoryCell]) -> bool {
366 history.iter().any(HistoryCell::has_live_motion)
367 }
368
368 lines RUST