Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-tui): shimmer, elapsed time and reduced-motion support
Akarshan Biswas88be469c2c3a
diff --git a/docs/src/pages/docs/agent/console.mdx b/docs/src/pages/docs/agent/console.mdxindex 616470a00..5e8481804 100644--- a/docs/src/pages/docs/agent/console.mdx+++ b/docs/src/pages/docs/agent/console.mdx@@ -63,7 +63,10 @@ Type while it's working and your message queues rather than being dropped - see### The working rowWhile a turn runs, the input row shows an action word that turns over every few seconds, with a π-sweeping back and forth along it, so a long turn does not read as a hung UI.+sweeping back and forth along it, so a long turn does not read as a hung UI. A brightness sweep+crosses the word, and after it come the turn's elapsed time (`12s`, `1m 05s`, `1h 02m`) and the+key that cancels it, <kbd>Esc</kbd>. On a narrow terminal the row drops the long hint first, then+the short one, then the elapsed time, so it always stays one line.Pick a different glyph from `/settings > wave`, or set it in `~/.jan/config.toml` directly:@@ -83,6 +86,25 @@ missing-character box - clear the field in `/settings` and save. That writes `wathe off switch. Pressing <kbd>x</kbd> on the row is the other direction: it removes the key, so thedefault π comes back.+### Motion++The working row, the `[thinking]` badge and a running tool row animate: a throbber turns and a+brightness sweep crosses the label. The sweep changes colour only, never width, so nothing beside+it moves. It is skipped on a 16-colour terminal, which has no shades in between to sweep through.++To hold everything still, set this in `~/.jan/config.toml`:++```toml+[tui]+animations = false+```++The throbber then shows a static `β’`, the wave glyph is dropped, and every label keeps its resting+colour. Jan also turns animations off at launch when the OS asks for reduced motion: on macOS+(System Settings > Accessibility > Display > Reduce motion) and on GNOME-family Linux desktops+(animations off). Windows is not detected yet, so use the key there. Restart Jan after changing+either.+### The prompt-cache hit rateProviders cache the front of a request, so a turn that reuses it costs a fraction of a cold one. Thediff --git a/src-tauri/src/core/agent/global_config.rs b/src-tauri/src/core/agent/global_config.rsindex 1adcbb7fd..ee3877723 100644--- a/src-tauri/src/core/agent/global_config.rs+++ b/src-tauri/src/core/agent/global_config.rs@@ -66,6 +66,12 @@ const GLOBAL_CONFIG_TEMPLATE: &str = r#"# Jan Agent global provider config.# # thread_retention_days / max_threads.# # Off by default: nothing is deleted#+# [tui]+# animations = false # hold the TUI still: no shimmer, a+# # static glyph for the throbber and the+# # wave. On by default; the OS reduce-+# # motion setting also turns it off+## [telemetry] # opt-in OpenTelemetry (OTLP) export of# enabled = true # usage metrics and events to YOUR# # collector (OTEL_EXPORTER_OTLP_* env);@@ -193,6 +199,10 @@ struct GlobalConfigToml {/// but a human appending to the file would not.#[serde(default, skip_serializing_if = "Vec::is_empty")]hooks: Vec<tauri_plugin_agent_tools::tools::hooks::HookEntry>,+ /// `[tui]` -- terminal UI display preferences that are not worth a root+ /// key each. A table, so declared after the plain values.+ #[serde(default, skip_serializing_if = "TuiSection::is_empty")]+ tui: TuiSection,/// `[telemetry]` -- opt-in OTLP export (`core::agent::otel`). A table, so/// declared after the plain values and before `providers`.#[serde(default, skip_serializing_if = "TelemetrySection::is_empty")]@@ -211,6 +221,20 @@ struct GlobalConfigToml {providers: HashMap<String, GlobalProviderEntry>,}+/// `[tui]` in `~/.jan/config.toml`. Each key is `None` when unset.+#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]+struct TuiSection {+ /// Animate the TUI (shimmer, throbbers, the wave). `None` = on.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ animations: Option<bool>,+}++impl TuiSection {+ fn is_empty(&self) -> bool {+ self.animations.is_none()+ }+}+/// `[experimental]` in `~/.jan/config.toml`. Each key is `None` when unset,/// which means off.#[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq)]@@ -414,6 +438,18 @@ pub(crate) fn mouse_enabled() -> bool {.unwrap_or(true)}+/// Whether the TUI animates (`[tui] animations` in `~/.jan/config.toml`),+/// defaulting to on. Off holds every animated element on its static fallback.+/// A display preference must never block startup, so an unreadable config+/// yields the default. CLI-only, like its sole caller.+#[cfg(feature = "cli")]+pub(crate) fn animations_enabled() -> bool {+ load_raw()+ .ok()+ .and_then(|config| config.tui.animations)+ .unwrap_or(true)+}+/// Whether the TUI may offer `/terminal-setup` at startup (`terminal_hint` in/// `~/.jan/config.toml`), defaulting to on. Declining the offer leaves no trace/// on disk -- the check reads the terminal's own config -- so this key is what@@ -985,6 +1021,30 @@ mod tests {});}+ #[cfg(feature = "cli")]+ #[test]+ fn animations_default_on_and_read_the_tui_table() {+ with_temp_home(|_| {+ assert!(animations_enabled(), "missing file -> animated");+ let path = ensure_global_config().expect("ensure");+ assert!(animations_enabled(), "scaffolded file -> animated");++ std::fs::write(&path, "[tui]\nanimations = false\n").unwrap();+ assert!(!animations_enabled());+ // A provider write keeps the table.+ set_provider("p", ProviderUpdate::default()).unwrap();+ assert!(!animations_enabled(), "survives a rewrite");+ std::fs::write(&path, "[tui]\nanimations = true\n").unwrap();+ assert!(animations_enabled());+ // A root key of the same name is not the switch.+ std::fs::write(&path, "animations = false\n").unwrap();+ assert!(animations_enabled(), "only [tui] animations counts");++ std::fs::write(&path, "not valid toml [[[").unwrap();+ assert!(animations_enabled(), "an unreadable config keeps the default");+ });+ }+#[test]fn mouse_defaults_on_and_reads_the_toml_key() {with_temp_home(|_| {diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex bce109482..b2fede546 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -36,6 +36,7 @@ use tokio::task::JoinHandle;mod find;mod highlight;mod markdown;+mod motion;mod theme;mod vibe_setting;@@ -6772,7 +6773,7 @@ impl App {/// by the render loop, so every animated row in a frame shows the same/// glyph and they turn together instead of drifting apart.fn spinner(&self) -> &'static str {- SPINNER[self.spinner_frame % SPINNER.len()]+ motion::spinner(self.spinner_frame, motion::mode())}/// Flush the current turn and return its text as the final assistant answer.@@ -9227,17 +9228,29 @@ fn trace_done_line() -> Line<'static> {/// they approved -- and the row does not re-lay itself out the instant the call/// resolves. The elapsed badge is dark rather than dim cyan: at the tail of a/// wrapped command it has to read as chrome, not as another argument.+///+/// While in flight the label also carries a brightness sweep (colour only, so+/// the wrap is the committed row's); the finished row is the plain one.fn running_group_rows(group: &ToolGroup, spinner_frame: usize, width: u16) -> Vec<Line<'static>> {- let frame = SPINNER[spinner_frame % SPINNER.len()];+ let mode = motion::mode();+ let label = Style::new().cyan().dim();let elapsed = group.started.elapsed().as_secs();- tool_row_lines(- frame,+ let rows = tool_row_lines(+ motion::spinner(spinner_frame, mode),Style::new().cyan(),&group.activity(),- Style::new().cyan().dim(),+ label,TOOL_ROW_RESERVE,width,Some((format!("({elapsed}s)"), Style::new().dark_gray())),+ );+ motion::shimmer_styled(+ rows,+ label,+ motion::Tint::Cyan,+ motion::frame_time(spinner_frame),+ mode,+ theme::Theme::current(),)}@@ -9317,7 +9330,7 @@ fn running_terminal_lines(width: u16,) -> Vec<Line<'static>> {let mut rows = shell_body_rows(command, output, width, SHELL_PANEL_GUTTER);- let frame = SPINNER[spinner_frame % SPINNER.len()];+ let frame = motion::spinner(spinner_frame, motion::mode());rows.push(Line::from(vec![Span::styled(format!("{frame} "), Style::new().cyan()),Span::styled(format!("{elapsed}s"), Style::new().dark_gray()),@@ -10299,6 +10312,7 @@ pub async fn run(// Under raw mode (so an OSC 11 reply is not echoed) but before the alternate// screen, so a query the terminal ignores leaves no stray bytes on the frame.theme::resolve_and_apply(theme_pref);+ motion::init(crate::core::agent::global_config::animations_enabled());// Deserializing syntect's syntax/theme dumps takes tens of milliseconds.// Doing it here, off the render loop, keeps the first code block of a// response from stalling a frame mid-stream. Spawned after the theme is@@ -10982,8 +10996,11 @@ async fn chat_loop<B: Backend>(// whole frames if a tick stalled (a burst of deltas / slow term).app.advance_spinner(Instant::now());// Animate the working-title spinner on the same cadence; the- // OSC 9999 payload is not re-sent, only the title frame.- app.agent_status.animate();+ // OSC 9999 payload is not re-sent, only the title frame. Held+ // on its current frame when motion is reduced.+ if motion::mode() == motion::MotionMode::Animated {+ app.agent_status.animate();+ }while event::poll(Duration::ZERO).unwrap_or(false) {match event::read() {Ok(Event::Key(key)) => {@@ -19150,7 +19167,7 @@ fn draw(f: &mut Frame, app: &mut App) {app.agent_detail.as_deref(),app.spinner(),);- f.render_widget(input_box(app), chunks[2]);+ f.render_widget(input_box(app, chunks[2].width), chunks[2]);f.render_widget(dock_line(app, chunks[3].width), chunks[3]);// The `/mcp` sign-in confirm lives here too: the picker path returns// before the overlay chain below, so without this the "open a browser?"@@ -19557,7 +19574,7 @@ fn draw(f: &mut Frame, app: &mut App) {if let Some(lines) = panel_lines {f.render_widget(Paragraph::new(lines), panel_area);}- f.render_widget(input_box(app).scroll((input_scroll, 0)), chunks[2]);+ f.render_widget(input_box(app, chunks[2].width).scroll((input_scroll, 0)), chunks[2]);f.render_widget(dock_line(app, chunks[3].width), chunks[3]);// A readout (`/context`, `/usage`) docks above the input box, where every// other prompt in this TUI lives -- `/login`, `/settings`, `/mcp`, the@@ -21247,45 +21264,19 @@ fn local_timestamp() -> String {chrono::Local::now().format("%Y-%m-%d %H:%M").to_string()}+/// Compact elapsed time: `12s`, `1m 05s`, `1h 02m`. The zero-padded second+/// field keeps the width steady within a minute, so text after it does not+/// jitter as the seconds tick.fn format_elapsed(secs: u64) -> String {if secs < 60 {format!("{secs}s")} else if secs < 3600 {- format!("{}m{:02}s", secs / 60, secs % 60)+ format!("{}m {:02}s", secs / 60, secs % 60)} else {- format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60)+ format!("{}h {:02}m", secs / 3600, (secs % 3600) / 60)}}-/// Frames the shimmer rests between sweeps, so the wave reads as a pulse-/// rather than a continuously scrolling band.-const SHIMMER_PAUSE: usize = 4;--/// Sweep a crest across `text`, one character per spinner frame: `palette` is-/// `[crest, trail, base]`, applied to the character under the crest, the one-/// behind it, and everything else.-///-/// Folded reasoning is the one stretch of a run that produces no output at all-/// -- no prose, no tool rows, nothing moving -- so the badge is the only thing-/// that can say the model is still going. The sweep animates in place, without-/// changing the text's width, so nothing to its left shifts as it runs.-fn shimmer_spans(text: &str, palette: [Style; 3], frame: usize) -> Vec<Span<'static>> {- let chars: Vec<char> = text.chars().collect();- let head = frame % (chars.len() + SHIMMER_PAUSE);- chars- .iter()- .enumerate()- .map(|(i, c)| {- let style = match head.checked_sub(i) {- Some(0) => palette[0],- Some(1) => palette[1],- _ => palette[2],- };- Span::styled(c.to_string(), style)- })- .collect()-}-/// Resolve the display label for `model`: the `provider/model` pair when the/// bare id maps to a configured provider (mirroring upstream resolution:/// an exact hit in a provider's `models` list, or a `<provider>/<model>`@@ -21451,15 +21442,17 @@ fn header_spans(app: &App) -> Vec<Span<'static>> {}spans.push(Span::raw(" "));if app.is_thinking() {+ // Folded reasoning is the one stretch of a run that puts nothing on+ // screen, so the badge carries the motion. Colour only: the brackets+ // and the word hold their cells.spans.push(Span::styled("[", style));- spans.extend(shimmer_spans(+ spans.extend(motion::shimmer(&status,- [- Style::new().yellow().bold(),- Style::new().yellow(),- Style::new().yellow().dim(),- ],- app.spinner_frame,+ style,+ motion::Tint::Yellow,+ motion::frame_time(app.spinner_frame),+ motion::mode(),+ theme::Theme::current(),));spans.push(Span::styled("]", style));} else {@@ -21855,7 +21848,82 @@ fn input_content_lines(input: &str, cursor: usize) -> Vec<Line<'static>> {.collect()}-fn input_box(app: &App) -> Paragraph<'static> {+/// The steer hint on the working row, longest first: the row drops to the next+/// one down when the terminal is too narrow, and to none at all past the last,+/// rather than letting the edge clip it mid-word. The key is the one+/// `handle_key` actually cancels a run on.+const WORKING_HINTS: [&str; 2] = [+ " (Esc to cancel, type to steer the agent)",+ " (Esc to cancel)",+];++/// The running row: throbber (or wave), action word, elapsed time and the+/// cancel hint, always one row. What does not fit `width` is dropped in order+/// of importance -- the long hint, then the short one, then the elapsed time --+/// so the row never wraps or changes height.+fn working_row(app: &App, width: u16) -> Line<'static> {+ let mode = motion::mode();+ // The spinner carries the fast motion; the action word turns over on a+ // slower cadence, cycling "working" synonyms -- or "thinking" synonyms in+ // orange while a reasoning block streams -- so the row reads alive without+ // shifting under the eye.+ let step = app.spinner_frame / WORD_ROTATE_FRAMES;+ let (word, style, tint) = if app.reasoning_open() {+ (+ THINKING_WORDS[step % THINKING_WORDS.len()],+ // Same theme-aware accent as markdown bold, so reasoning reads+ // consistently on light and dark terminals.+ Style::new().fg(theme::strong_accent()).italic(),+ motion::Tint::Accent,+ )+ } else {+ (+ WORKING_WORDS[step % WORKING_WORDS.len()],+ Style::new().dim().italic(),+ motion::Tint::Muted,+ )+ };+ // With `wave` set, the glyph travels along the action word in place of the+ // leading throbber: one moving thing per row, not two. Reduced motion+ // keeps the word and drops the traveller, so the row is as wide as it is+ // animated.+ let message = format!("{word}β¦");+ let lead = match (wave_glyph(), mode) {+ (Some(glyph), motion::MotionMode::Animated) => {+ wave_sweep_line(&message, &glyph, app.spinner_frame, style)+ }+ (Some(_), motion::MotionMode::Reduced) => Line::from(Span::styled(message, style)),+ (None, _) => Line::from(vec![+ Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),+ Span::styled(message, style),+ ]),+ };+ let mut spans = motion::shimmer_styled(+ vec![lead],+ style,+ tint,+ motion::frame_time(app.spinner_frame),+ mode,+ theme::Theme::current(),+ )+ .remove(0)+ .spans;+ let room = width as usize;+ let elapsed = app+ .run_started+ .map(|t| Span::styled(format!(" {}", format_elapsed(t.elapsed().as_secs())), Style::new().dim()))+ .filter(|e| spans_width(&spans) + e.width() <= room);+ if let Some(e) = elapsed {+ spans.push(e);+ }+ let used = spans_width(&spans);+ if let Some(hint) = WORKING_HINTS.iter().find(|h| used + h.len() <= room) {+ spans.push(Span::styled(*hint, Style::new().dim().italic()));+ }+ Line::from(spans)+}++fn input_box(app: &App, width: u16) -> Paragraph<'static> {let block = Block::default();if let Some(kind) = app.compacting.filter(|_| app.input.is_empty()) {// Compaction puts nothing in the transcript while it runs, so the input@@ -21897,45 +21965,7 @@ fn input_box(app: &App) -> Paragraph<'static> {} else if app.status == Status::Running && app.input.is_empty() {// Show queue status when running with empty inputif app.message_queue.is_empty() {- // The spinner carries the fast motion; the action word turns over- // on a slower cadence, cycling "working" synonyms -- or "thinking"- // synonyms in orange while a reasoning block streams -- so the row- // reads alive without shifting under the eye.- let step = app.spinner_frame / WORD_ROTATE_FRAMES;- let (word, style) = if app.reasoning_open() {- (- THINKING_WORDS[step % THINKING_WORDS.len()],- // Same theme-aware accent as markdown bold, so reasoning- // reads consistently on light and dark terminals.- Style::new().fg(theme::strong_accent()).italic(),- )- } else {- (- WORKING_WORDS[step % WORKING_WORDS.len()],- Style::new().dim().italic(),- )- };- // With `wave` set, the glyph travels along the action word in place- // of the leading throbber: one moving thing per row, not two.- let message = format!("{word}β¦");- let mut spans = Vec::with_capacity(6);- match wave_glyph() {- Some(glyph) => {- spans.extend(wave_sweep_line(&message, &glyph, app.spinner_frame, style).spans)- }- None => {- spans.push(Span::styled(- format!("{} ", app.spinner()),- Style::new().cyan(),- ));- spans.push(Span::styled(message, style));- }- }- spans.push(Span::styled(- " (Esc to cancel, type to steer the agent)",- Style::new().dim().italic(),- ));- Paragraph::new(Line::from(spans)).block(block)+ Paragraph::new(working_row(app, width)).block(block)} else {let n = app.message_queue.len();Paragraph::new(Line::from(vec![@@ -22695,7 +22725,7 @@ mod tests {assert_eq!(items.len(), 1);assert_eq!(items[0].value, "4242", "pid rides in value for the stop action");assert!(items[0].label.contains("sleep 9000"), "{}", items[0].label);- assert!(items[0].label.contains("1m05s"), "elapsed shown: {}", items[0].label);+ assert!(items[0].label.contains("1m 05s"), "elapsed shown: {}", items[0].label);}#[test]@@ -38479,42 +38509,144 @@ mod tests {}/// Folded reasoning puts nothing on screen, so the badge has to carry the- /// motion: a crest sweeps the word, one character per spinner frame, and- /// wraps back to the start after a pause.+ /// motion: a brightness sweep crosses the word with the text held still.+ /// Reduced motion keeps the badge's own flat style.#[test]- fn thinking_badge_shimmers_across_its_frames() {- use ratatui::style::{Modifier, Style};- let palette = [- Style::new().yellow().bold(),- Style::new().yellow(),- Style::new().yellow().dim(),- ];- let crest_at = |frame: usize| {- let spans = super::shimmer_spans("thinking", palette, frame);- // The text is intact and unmoved at every frame; only style changes.- let text: String = spans.iter().map(|s| s.content.as_ref()).collect::<String>();- assert_eq!(text, "thinking", "frame {frame} must not move the label");+ fn thinking_badge_shimmers_unless_motion_is_reduced() {+ use super::motion::{with_mode, MotionMode};+ let mut app = test_app();+ app.stream_reasoning = false;+ app.submit_user("hi".into());+ app.apply(StreamEvent::Token {+ text: "<think>pondering".into(),+ });+ assert!(app.is_thinking());+ let rgb = |spans: &[ratatui::text::Span<'static>]| {spans.iter()- .position(|s| s.style.add_modifier.contains(Modifier::BOLD))+ .any(|s| matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..))))};+ let text = |spans: &[ratatui::text::Span<'static>]| -> String {+ spans.iter().map(|s| s.content.as_ref()).collect()+ };+ let mut moved = false;+ let mut widths = std::collections::HashSet::new();+ for frame in 0..30 {+ app.spinner_frame = frame;+ let spans = with_mode(MotionMode::Animated, || header_spans(&app));+ assert!(text(&spans).contains("[thinking]"), "frame {frame}");+ widths.insert(spans_width(&spans));+ moved |= rgb(&spans);+ let still = with_mode(MotionMode::Reduced, || header_spans(&app));+ assert!(!rgb(&still), "reduced motion is static at frame {frame}");+ assert_eq!(text(&still), text(&spans), "same text in both modes");+ }+ assert!(moved, "the crest crossed the badge");+ assert_eq!(widths.len(), 1, "the header never changes width");+ }- assert_eq!(crest_at(0), Some(0));- assert_eq!(- crest_at(3),- Some(3),- "the crest advances one char per frame"- );- // Past the end of the word the crest is off-screen (the pause), then- // the cycle restarts.- assert_eq!(crest_at(8), None, "pause between sweeps");+ #[test]+ fn elapsed_time_is_compact() {+ use super::format_elapsed;+ assert_eq!(format_elapsed(0), "0s");+ assert_eq!(format_elapsed(12), "12s");+ assert_eq!(format_elapsed(59), "59s");+ assert_eq!(format_elapsed(60), "1m 00s");+ assert_eq!(format_elapsed(65), "1m 05s");+ assert_eq!(format_elapsed(3599), "59m 59s");+ assert_eq!(format_elapsed(3600), "1h 00m");+ assert_eq!(format_elapsed(3720), "1h 02m");+ }++ /// The working row carries the elapsed time and the cancel hint on one+ /// row, is exactly as wide in both motion modes, and sheds the hint, then+ /// the elapsed time, as the terminal narrows instead of wrapping.+ #[test]+ fn the_working_row_keeps_its_width_and_degrades_by_width() {+ use super::motion::{with_mode, MotionMode};+ let mut app = test_app();+ app.submit_user("go".into());+ app.run_started = Some(Instant::now() - Duration::from_secs(65));+ let text = |line: &Line<'static>| -> String {+ line.spans.iter().map(|s| s.content.as_ref()).collect()+ };+ for glyph in [None, Some("\u{1f44b}")] {+ with_wave_glyph(glyph, || {+ for frame in [0, 7, 19] {+ app.spinner_frame = frame;+ let moving = with_mode(MotionMode::Animated, || super::working_row(&app, 120));+ let still = with_mode(MotionMode::Reduced, || super::working_row(&app, 120));+ assert_eq!(+ spans_width(&moving.spans),+ spans_width(&still.spans),+ "glyph {glyph:?} frame {frame}: {:?} vs {:?}",+ text(&moving),+ text(&still)+ );+ assert!(text(&moving).contains("1m 05s"), "{}", text(&moving));+ assert!(text(&moving).contains("Esc to cancel, type to steer"));+ }+ });+ }+ app.spinner_frame = 0;+ with_wave_glyph(None, || {+ for width in 0..120u16 {+ let row = super::working_row(&app, width);+ let t = text(&row);+ if t.contains("cancel") || t.contains("1m 05s") {+ let w = spans_width(&row.spans);+ assert!(w <= width as usize, "optional parts must fit: {width}: {t}");+ }+ }+ // "<glyph> working... 1m 05s" is 17 cells; the short hint adds 16.+ let mid = text(&super::working_row(&app, 34));+ assert!(mid.contains("(Esc to cancel)") && !mid.contains("steer"), "{mid}");+ let narrow = text(&super::working_row(&app, 22));+ assert!(narrow.contains("1m 05s") && !narrow.contains("Esc"), "{narrow}");+ let tiny = text(&super::working_row(&app, 12));+ assert!(!tiny.contains("1m"), "{tiny}");+ });+ // Rendered: still one row in the input box.+ let rows = with_wave_glyph(None, || render_rows(&mut app, 40, 12));assert_eq!(- crest_at(8 + super::SHIMMER_PAUSE),- Some(0),- "sweep restarts"+ rows.iter().filter(|r| r.contains("Esc to cancel")).count(),+ 1,+ "{rows:#?}");}+ /// A running tool label shimmers and spins; reduced motion holds a static+ /// glyph and the plain label. Either way the text is the same.+ #[test]+ fn a_running_tool_row_animates_only_with_motion() {+ use super::motion::{with_mode, MotionMode, STATIC_GLYPH};+ let mut app = test_app();+ app.submit_user("go".into());+ app.apply(StreamEvent::ToolCall {+ id: "c1".into(),+ name: "grep".into(),+ args: json!({ "pattern": "needle" }),+ });+ let group = app.tool_group.as_ref().expect("open group");+ assert!(group.is_running());+ let rgb = |lines: &[Line<'static>]| {+ lines.iter().flat_map(|l| l.spans.iter()).any(|s| {+ matches!(s.style.fg, Some(ratatui::style::Color::Rgb(..)))+ })+ };+ let mut moved = false;+ for frame in 0..30 {+ let moving = with_mode(MotionMode::Animated, || running_group_rows(group, frame, 80));+ let still = with_mode(MotionMode::Reduced, || running_group_rows(group, frame, 80));+ let strip = |ls: &[Line<'static>]| lines_text(ls).replace(SPINNER[frame % SPINNER.len()], STATIC_GLYPH);+ assert_eq!(strip(&moving), lines_text(&still), "frame {frame}");+ assert!(lines_text(&still).contains(STATIC_GLYPH));+ assert!(!rgb(&still));+ moved |= rgb(&moving);+ }+ assert!(moved, "the label shimmered while in flight");+ }+/// The animation is scoped to the state that needs it: a folded, streaming/// reasoning block. Everything else keeps its flat badge.#[test]diff --git a/src-tauri/src/core/cli/tui/motion.rs b/src-tauri/src/core/cli/tui/motion.rsnew file mode 100644index 000000000..df549d481--- /dev/null+++ b/src-tauri/src/core/cli/tui/motion.rs@@ -0,0 +1,510 @@+//! The one place the TUI decides whether something moves.+//!+//! Every animated element -- the throbber, the brightness sweep on a status+//! word, the travelling `wave` glyph, a running tool row -- asks this module+//! for its frame and gets an explicit static fallback when motion is off. The+//! mode is resolved once at launch from `[tui] animations` in+//! `~/.jan/config.toml` and the OS reduce-motion preference, and is+//! process-wide for the same reason as the theme: the render helpers are free+//! functions with no session in hand.+//!+//! Animation is driven by the render loop's frame counter rather than the wall+//! clock, so every frame is a pure function of its inputs: a test passes a+//! frame and gets the same spans every time.++use std::sync::atomic::{AtomicBool, Ordering};+use std::time::Duration;++use ratatui::style::{Color, Modifier, Style};+use ratatui::text::{Line, Span};++use super::theme::{ColorDepth, Theme};++/// Whether the TUI animates or holds every element still.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum MotionMode {+ Animated,+ Reduced,+}++impl MotionMode {+ pub(super) fn from_animations_enabled(enabled: bool) -> Self {+ if enabled {+ Self::Animated+ } else {+ Self::Reduced+ }+ }+}++/// Process-wide "motion is reduced" flag. Animated until `init` says+/// otherwise, so a render before resolution (and every test) animates.+static REDUCED: AtomicBool = AtomicBool::new(false);++#[cfg(test)]+thread_local! {+ /// Per-test override, like `WAVE_GLYPH_OVERRIDE`: a test pins its own+ /// thread's mode instead of racing others on the shared flag.+ static MODE_OVERRIDE: std::cell::Cell<Option<MotionMode>> =+ const { std::cell::Cell::new(None) };+}++/// The resolved motion mode.+pub(super) fn mode() -> MotionMode {+ #[cfg(test)]+ {+ if let Some(over) = MODE_OVERRIDE.with(std::cell::Cell::get) {+ return over;+ }+ }+ if REDUCED.load(Ordering::Relaxed) {+ MotionMode::Reduced+ } else {+ MotionMode::Animated+ }+}++/// Run `f` with `mode` as this thread's motion mode.+#[cfg(test)]+pub(super) fn with_mode<T>(mode: MotionMode, f: impl FnOnce() -> T) -> T {+ MODE_OVERRIDE.with(|c| c.set(Some(mode)));+ let out = f();+ MODE_OVERRIDE.with(|c| c.set(None));+ out+}++/// Resolve the mode at launch: `animations = false` reduces motion outright;+/// otherwise the OS preference is read off the render thread and, if it asks+/// for less motion, reduces it when the answer lands. The OS can only take+/// motion away, never add it back over the config.+pub(crate) fn init(animations: bool) {+ let mode = MotionMode::from_animations_enabled(animations);+ REDUCED.store(mode == MotionMode::Reduced, Ordering::Relaxed);+ if mode == MotionMode::Animated {+ // A subprocess round trip (tens of ms) must not delay the first frame;+ // the worst case is a few animated frames before the switch.+ std::thread::spawn(|| {+ if os_prefers_reduced_motion() == Some(true) {+ REDUCED.store(true, Ordering::Relaxed);+ }+ });+ }+}++/// The OS reduce-motion preference, where it is readable without FFI: macOS+/// through `defaults`, a GNOME-family desktop through `gsettings`. `None`+/// elsewhere (Windows needs `SystemParametersInfo`, which is `unsafe` FFI) and+/// whenever the tool is missing or says nothing usable.+fn os_prefers_reduced_motion() -> Option<bool> {+ if cfg!(target_os = "macos") {+ read_command("defaults", &["read", "com.apple.universalaccess", "reduceMotion"])+ .and_then(|out| macos_reduce_motion(&out))+ } else if cfg!(all(unix, not(target_os = "macos"))) {+ read_command(+ "gsettings",+ &["get", "org.gnome.desktop.interface", "enable-animations"],+ )+ .and_then(|out| gnome_reduce_motion(&out))+ } else {+ None+ }+}++fn read_command(program: &str, args: &[&str]) -> Option<String> {+ let out = std::process::Command::new(program)+ .args(args)+ .stdin(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .output()+ .ok()?;+ out.status+ .success()+ .then(|| String::from_utf8_lossy(&out.stdout).into_owned())+}++/// `defaults read com.apple.universalaccess reduceMotion` prints `1` or `0`.+fn macos_reduce_motion(out: &str) -> Option<bool> {+ match out.trim() {+ "1" | "true" => Some(true),+ "0" | "false" => Some(false),+ _ => None,+ }+}++/// `gsettings get org.gnome.desktop.interface enable-animations` prints+/// `true` or `false`; animations off is the reduce-motion request.+fn gnome_reduce_motion(out: &str) -> Option<bool> {+ match out.trim() {+ "false" => Some(true),+ "true" => Some(false),+ _ => None,+ }+}++/// Shown in place of the Braille throbber when motion is reduced: one cell,+/// like every throbber frame, so nothing beside it shifts.+pub(super) const STATIC_GLYPH: &str = "\u{2022}";++/// The throbber frame for `frame`, or the static glyph when motion is reduced.+pub(super) fn spinner(frame: usize, mode: MotionMode) -> &'static str {+ match mode {+ MotionMode::Animated => super::SPINNER[frame % super::SPINNER.len()],+ MotionMode::Reduced => STATIC_GLYPH,+ }+}++/// Wall time a frame count stands for. The shimmer is timed off the render+/// loop's frame counter, so it is as deterministic as the throbber.+pub(super) fn frame_time(frame: usize) -> Duration {+ Duration::from_millis((frame as u64).saturating_mul(super::SPINNER_ADVANCE_MS))+}++/// The hue a sweep brightens: the text's resting colour approximated in RGB,+/// and the colour the crest peaks at. Characters outside the crest keep the+/// caller's own style untouched, so only the crest ever uses these values.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Tint {+ /// Dim default-foreground text: the working words.+ Muted,+ /// The orange reasoning accent: the thinking words.+ Accent,+ /// The cyan of a running tool label.+ Cyan,+ /// The yellow of the `[thinking]` badge.+ Yellow,+}++type Rgb = (u8, u8, u8);++impl Tint {+ /// `(rest, crest)`. A dark background brightens toward white; a light one+ /// deepens toward black, which is what reads as "brighter" on white.+ fn colors(self, light: bool) -> (Rgb, Rgb) {+ match (self, light) {+ (Tint::Muted, false) => ((128, 128, 128), (240, 240, 240)),+ (Tint::Muted, true) => ((140, 140, 140), (20, 20, 20)),+ (Tint::Accent, false) => ((255, 165, 0), (255, 235, 180)),+ (Tint::Accent, true) => ((180, 83, 9), (80, 30, 0)),+ (Tint::Cyan, false) => ((0, 160, 170), (190, 255, 255)),+ (Tint::Cyan, true) => ((0, 120, 130), (0, 40, 50)),+ (Tint::Yellow, false) => ((205, 205, 0), (255, 255, 200)),+ (Tint::Yellow, true) => ((150, 120, 0), (60, 45, 0)),+ }+ }+}++/// One full pass of the crest, start to end.+const SWEEP: Duration = Duration::from_millis(2000);+/// Half-width of the crest, in characters.+const BAND_HALF: f32 = 4.0;+/// Characters of empty run-up either side of the text, so the crest enters and+/// leaves smoothly and the text rests between passes.+const SWEEP_PAD: usize = 6;+/// Below this the crest is indistinguishable from the resting style, so the+/// character keeps the caller's style exactly.+const CREST_FLOOR: f32 = 0.05;++/// Crest strength (0..=1) at character `i` of a `len`-character text at time+/// `t`: a raised-cosine band that sweeps left to right once per `SWEEP`.+pub(super) fn crest(i: usize, len: usize, t: Duration) -> f32 {+ let period = len + 2 * SWEEP_PAD;+ let phase = (t.as_millis() % SWEEP.as_millis()) as f32 / SWEEP.as_millis() as f32;+ let head = phase * period as f32 - SWEEP_PAD as f32;+ let dist = (i as f32 - head).abs();+ if dist > BAND_HALF {+ 0.0+ } else {+ 0.5 * (1.0 + (std::f32::consts::PI * dist / BAND_HALF).cos())+ }+}++fn blend(from: Rgb, to: Rgb, t: f32) -> Rgb {+ let mix = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;+ (mix(from.0, to.0), mix(from.1, to.1), mix(from.2, to.2))+}++/// Whether a sweep may run at all. A 16-colour terminal has no in-between+/// shades, so a sweep there is a block of the nearest named colour jumping+/// across the word; the static style reads better.+fn may_shimmer(mode: MotionMode, theme: Theme) -> bool {+ mode == MotionMode::Animated && theme.depth != ColorDepth::Ansi16+}++/// The style of character `i` of `len` under a sweep at `t`.+fn crest_style(i: usize, len: usize, style: Style, tint: Tint, t: Duration, theme: Theme) -> Style {+ let level = crest(i, len, t);+ if level < CREST_FLOOR {+ return style;+ }+ let (rest, peak) = tint.colors(theme.light);+ let (r, g, b) = blend(rest, peak, level);+ style+ .remove_modifier(Modifier::DIM)+ .fg(theme.fit(Color::Rgb(r, g, b)))+}++/// `text` with a brightness sweep across it, one span per run of equal style.+/// Only colour changes: the text, and so the width, is identical at every `t`.+/// Reduced motion and 16-colour terminals get `text` in `style`, unchanged.+pub(super) fn shimmer(+ text: &str,+ style: Style,+ tint: Tint,+ t: Duration,+ mode: MotionMode,+ theme: Theme,+) -> Vec<Span<'static>> {+ if text.is_empty() {+ return Vec::new();+ }+ if !may_shimmer(mode, theme) {+ return vec![Span::styled(text.to_string(), style)];+ }+ let len = text.chars().count();+ runs(text.chars().enumerate().map(|(i, c)| {+ (c, crest_style(i, len, style, tint, t, theme))+ }))+}++/// Sweep every span of `lines` styled exactly `target` as one continuous text,+/// for a label that has already been wrapped across rows: the crest crosses+/// from one row into the next instead of restarting on each. Spans in any+/// other style (gutters, tags, suffixes) are left alone.+pub(super) fn shimmer_styled(+ lines: Vec<Line<'static>>,+ target: Style,+ tint: Tint,+ t: Duration,+ mode: MotionMode,+ theme: Theme,+) -> Vec<Line<'static>> {+ if !may_shimmer(mode, theme) {+ return lines;+ }+ let len: usize = lines+ .iter()+ .flat_map(|l| l.spans.iter())+ .filter(|s| s.style == target)+ .map(|s| s.content.chars().count())+ .sum();+ let mut at = 0usize;+ lines+ .into_iter()+ .map(|line| {+ let mut spans = Vec::with_capacity(line.spans.len());+ for span in line.spans {+ if span.style != target {+ spans.push(span);+ continue;+ }+ let start = at;+ at += span.content.chars().count();+ spans.extend(runs(span.content.chars().enumerate().map(|(k, c)| {+ (c, crest_style(start + k, len, target, tint, t, theme))+ })));+ }+ Line::from(spans).style(line.style)+ })+ .collect()+}++/// Fold styled characters into spans, merging neighbours of equal style so a+/// mostly-resting text costs a handful of spans rather than one per character.+pub(super) fn runs(chars: impl Iterator<Item = (char, Style)>) -> Vec<Span<'static>> {+ let mut out: Vec<Span<'static>> = Vec::new();+ let mut text = String::new();+ let mut current: Option<Style> = None;+ for (c, style) in chars {+ if current.is_some_and(|s| s != style) {+ out.push(Span::styled(std::mem::take(&mut text), current.unwrap_or_default()));+ }+ current = Some(style);+ text.push(c);+ }+ if let Some(style) = current {+ out.push(Span::styled(text, style));+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ const DARK_TC: Theme = Theme { light: false, depth: ColorDepth::Truecolor };++ fn text_of(spans: &[Span<'static>]) -> String {+ spans.iter().map(|s| s.content.as_ref()).collect()+ }++ fn per_char_styles(spans: &[Span<'static>]) -> Vec<Style> {+ spans+ .iter()+ .flat_map(|s| s.content.chars().map(move |_| s.style))+ .collect()+ }++ #[test]+ fn the_config_switch_maps_to_a_mode() {+ assert_eq!(MotionMode::from_animations_enabled(true), MotionMode::Animated);+ assert_eq!(MotionMode::from_animations_enabled(false), MotionMode::Reduced);+ }++ #[test]+ fn the_os_preference_parsers_read_only_clear_answers() {+ assert_eq!(macos_reduce_motion("1\n"), Some(true));+ assert_eq!(macos_reduce_motion("0\n"), Some(false));+ assert_eq!(macos_reduce_motion("does not exist"), None);+ assert_eq!(gnome_reduce_motion("false\n"), Some(true));+ assert_eq!(gnome_reduce_motion("true\n"), Some(false));+ assert_eq!(gnome_reduce_motion(""), None);+ }++ #[test]+ fn the_test_override_pins_the_mode() {+ assert_eq!(with_mode(MotionMode::Reduced, mode), MotionMode::Reduced);+ assert_eq!(with_mode(MotionMode::Animated, mode), MotionMode::Animated);+ }++ #[test]+ fn reduced_motion_holds_the_throbber_still() {+ let frames: Vec<&str> = (0..12).map(|f| spinner(f, MotionMode::Reduced)).collect();+ assert!(frames.iter().all(|g| *g == STATIC_GLYPH), "{frames:?}");+ assert_ne!(spinner(0, MotionMode::Animated), spinner(1, MotionMode::Animated));+ }++ /// The same time always yields the same frame, and the crest moves as+ /// time does.+ #[test]+ fn the_sweep_is_a_pure_function_of_time() {+ let style = Style::new().cyan();+ let at = |ms: u64| {+ shimmer("working", style, Tint::Cyan, Duration::from_millis(ms), MotionMode::Animated, DARK_TC)+ };+ assert_eq!(at(700), at(700), "deterministic");+ assert_eq!(at(700), at(700 + SWEEP.as_millis() as u64), "periodic");+ assert_ne!(per_char_styles(&at(500)), per_char_styles(&at(900)), "the crest moves");+ }++ /// Colour only: the text is intact at every point of the sweep.+ #[test]+ fn the_sweep_never_changes_the_text() {+ for ms in (0..2000).step_by(80) {+ let spans = shimmer(+ "thinking",+ Style::new().yellow(),+ Tint::Yellow,+ Duration::from_millis(ms),+ MotionMode::Animated,+ DARK_TC,+ );+ assert_eq!(text_of(&spans), "thinking", "t={ms}ms");+ }+ }++ /// The crest is brightest where it stands and fades to nothing outside+ /// the band, so characters away from it keep the caller's style exactly.+ #[test]+ fn the_crest_peaks_under_its_head_and_rests_elsewhere() {+ // Mid-sweep for a 8-char text: period 20, head at phase * 20 - 6.+ let t = Duration::from_millis(1000); // head = 10 - 6 = 4+ assert!((crest(4, 8, t) - 1.0).abs() < 1e-6);+ assert!(crest(3, 8, t) < 1.0 && crest(3, 8, t) > 0.0);+ assert_eq!(crest(0, 8, t), 0.0, "past the band");+ // At t=0 the head sits in the left run-up, off the text.+ assert!((0..8).all(|i| crest(i, 8, Duration::ZERO) == 0.0));++ let style = Style::new().cyan();+ let spans = shimmer("abcdefgh", style, Tint::Cyan, t, MotionMode::Animated, DARK_TC);+ let styles = per_char_styles(&spans);+ assert_eq!(styles[0], style, "outside the crest");+ assert_ne!(styles[4], style, "under the crest");+ assert!(matches!(styles[4].fg, Some(Color::Rgb(..))), "{:?}", styles[4]);+ }++ /// The crest lifts DIM so the brightening is visible on dimmed text.+ #[test]+ fn the_crest_lifts_dim() {+ let style = Style::new().dim().italic();+ let t = Duration::from_millis(1000);+ let spans = shimmer("abcdefgh", style, Tint::Muted, t, MotionMode::Animated, DARK_TC);+ let crest_style = per_char_styles(&spans)[4];+ assert!(!crest_style.add_modifier.contains(Modifier::DIM));+ assert!(crest_style.add_modifier.contains(Modifier::ITALIC));+ }++ #[test]+ fn reduced_motion_renders_the_static_style() {+ let style = Style::new().yellow().bold();+ for ms in [0, 500, 1000, 1500] {+ let spans = shimmer(+ "thinking",+ style,+ Tint::Yellow,+ Duration::from_millis(ms),+ MotionMode::Reduced,+ DARK_TC,+ );+ assert_eq!(spans, vec![Span::styled("thinking", style)]);+ }+ }++ #[test]+ fn a_16_colour_terminal_renders_the_static_style() {+ let theme = Theme { light: false, depth: ColorDepth::Ansi16 };+ let style = Style::new().cyan();+ let spans = shimmer(+ "working",+ style,+ Tint::Cyan,+ Duration::from_millis(1000),+ MotionMode::Animated,+ theme,+ );+ assert_eq!(spans, vec![Span::styled("working", style)]);+ }++ /// 256 colours still sweep, with every crest colour fitted to the palette.+ #[test]+ fn a_256_colour_sweep_emits_no_rgb() {+ let theme = Theme { light: true, depth: ColorDepth::Ansi256 };+ let spans = shimmer(+ "abcdefgh",+ Style::new(),+ Tint::Accent,+ Duration::from_millis(1000),+ MotionMode::Animated,+ theme,+ );+ assert!(spans.len() > 1, "still animates");+ assert!(spans.iter().all(|s| !matches!(s.style.fg, Some(Color::Rgb(..)))));+ }++ /// A wrapped label sweeps as one text: only spans in the target style+ /// change, and the rows keep their text.+ #[test]+ fn a_wrapped_label_sweeps_as_one_text() {+ let label = Style::new().cyan().dim();+ let gutter = Style::new().dark_gray();+ let lines = vec![+ Line::from(vec![Span::styled("| ", gutter), Span::styled("abcd", label)]),+ Line::from(vec![Span::styled("| ", gutter), Span::styled("efgh", label)]),+ ];+ let t = Duration::from_millis(1000); // head at char 4: the second row+ let out = shimmer_styled(lines.clone(), label, Tint::Cyan, t, MotionMode::Animated, DARK_TC);+ for (a, b) in lines.iter().zip(&out) {+ assert_eq!(text_of(&a.spans), text_of(&b.spans));+ assert_eq!(b.spans[0].style, gutter, "gutter untouched");+ }+ assert_ne!(per_char_styles(&out[1].spans[1..])[0], label, "crest on row two");++ let still = shimmer_styled(lines.clone(), label, Tint::Cyan, t, MotionMode::Reduced, DARK_TC);+ assert_eq!(still, lines);+ }++ #[test]+ fn frame_time_follows_the_throbber_cadence() {+ assert_eq!(frame_time(0), Duration::ZERO);+ assert_eq!(frame_time(10), Duration::from_millis(10 * super::super::SPINNER_ADVANCE_MS));+ }+}