diff --git a/src/app/background.rs b/src/app/background.rs index 7bcc650..c7df825 100644 --- a/src/app/background.rs +++ b/src/app/background.rs @@ -2,6 +2,18 @@ use super::*; +/// What a Claude session's row shows, given what Claude Code says it is doing, what the row showed before, and +/// whether the user is looking at it. A question is shown even to someone looking at it, since only they can answer; +/// a finished turn is shown only to someone who was elsewhere and clears once they look. +fn next_activity(working: bool, waiting: bool, before: Option, viewing: bool) -> Option { + match (working, waiting, before) { + (true, _, _) => Some(Activity::Working), + (false, true, _) => Some(Activity::Waiting), + (false, false, Some(Activity::Working | Activity::Attention)) if !viewing => Some(Activity::Attention), + _ => None, + } +} + impl Workspace { /// Startup reconciliation: scan Claude Code's records off the UI thread, then merge. pub fn start_scan(&mut self, cx: &mut Context) { @@ -46,21 +58,21 @@ impl Workspace { .detach(); } - /// While a session works, its sidebar dot pulses: the session list is redrawn a few times a second (with the + /// While a session works, its sidebar icon spins: the session list is redrawn many times a second (with the /// window's top level, which reuses the other cached parts). It stops once nothing works. - fn start_pulse(&mut self, cx: &mut Context) { - if self.pulsing { + fn start_spin(&mut self, cx: &mut Context) { + if self.spinning { return; } - self.pulsing = true; + self.spinning = true; cx.spawn(async move |this, cx| { loop { - cx.background_executor().timer(crate::panels::sidebar::PULSE_STEP).await; + cx.background_executor().timer(crate::panels::status_icon::SPIN_STEP).await; let working = this.update(cx, |ws, cx| { let working = ws.activity.values().any(|a| *a == Activity::Working); match &ws.session_list { Some(list) if working => list.update(cx, |_, cx| cx.notify()), - _ => ws.pulsing = working, + _ => ws.spinning = working, } working }); @@ -118,18 +130,12 @@ impl Workspace { let viewing = window_active && shown.as_deref() == Some(l.id.as_str()); let status = self.store.session(&l.id).and_then(|r| statuses.get(r.claude_id()?)); let working = status.map_or_else(|| view.is_working(), |s| s == "busy"); - match (working, self.activity.get(&l.id)) { - (true, _) => { - next.insert(l.id.clone(), Activity::Working); - } - (false, Some(Activity::Working)) if !viewing => { - flash |= !window_active; - next.insert(l.id.clone(), Activity::Attention); - } - (false, Some(Activity::Attention)) if !viewing => { - next.insert(l.id.clone(), Activity::Attention); - } - _ => {} + let waiting = status.is_some_and(|s| s == "waiting"); + let before = self.activity.get(&l.id).copied(); + let now = next_activity(working, waiting, before, viewing); + flash |= !window_active && before == Some(Activity::Working) && matches!(now, Some(Activity::Attention | Activity::Waiting)); + if let Some(now) = now { + next.insert(l.id.clone(), now); } } if next != self.activity { @@ -137,7 +143,7 @@ impl Workspace { cx.notify(); } if self.activity.values().any(|a| *a == Activity::Working) { - self.start_pulse(cx); + self.start_spin(cx); } if flash { platform::request_attention(window); @@ -287,3 +293,36 @@ impl Workspace { crate::updater::check(self, cx); } } + +#[cfg(test)] +mod tests { + use super::{Activity, next_activity}; + + #[test] + fn busy_is_working_whatever_came_before() { + for before in [None, Some(Activity::Working), Some(Activity::Waiting), Some(Activity::Attention)] { + assert_eq!(next_activity(true, false, before, true), Some(Activity::Working)); + assert_eq!(next_activity(true, false, before, false), Some(Activity::Working)); + } + } + + #[test] + fn a_question_shows_even_to_someone_looking_at_the_session() { + assert_eq!(next_activity(false, true, Some(Activity::Working), true), Some(Activity::Waiting)); + assert_eq!(next_activity(false, true, None, false), Some(Activity::Waiting)); + } + + #[test] + fn a_finished_turn_waits_to_be_seen_and_clears_once_looked_at() { + assert_eq!(next_activity(false, false, Some(Activity::Working), false), Some(Activity::Attention)); + assert_eq!(next_activity(false, false, Some(Activity::Attention), false), Some(Activity::Attention)); + assert_eq!(next_activity(false, false, Some(Activity::Working), true), None); + assert_eq!(next_activity(false, false, Some(Activity::Attention), true), None); + } + + #[test] + fn an_idle_session_nobody_is_owed_news_from_shows_nothing() { + assert_eq!(next_activity(false, false, None, false), None); + assert_eq!(next_activity(false, false, Some(Activity::Waiting), false), None); + } +} diff --git a/src/app/mod.rs b/src/app/mod.rs index 2a8edef..48c5f5a 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -223,7 +223,7 @@ pub enum Act { impl MenuItem { /// A plain entry: not dangerous, enabled, no hint, no separator above. pub fn new(label: impl Into, act: Act) -> Self { - Self { label: label.into(), hint: None, act, danger: false, disabled: false, separator_before: false, remove: None, icon: None } + Self { label: label.into(), hint: None, detail: None, act, danger: false, disabled: false, separator_before: false, remove: None, icon: None } } } @@ -231,6 +231,8 @@ pub struct MenuItem { pub label: String, /// Faint text on the right that is never cut, so a long `label` is shortened with "…" instead. pub hint: Option, + /// Faint second line under the label, for text too long to sit beside it (a project path). + pub detail: Option, pub act: Act, pub danger: bool, /// Shown greyed out and does nothing when clicked. @@ -312,9 +314,11 @@ pub enum Main { /// What a running Claude session is doing, as shown by its sidebar dot. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Activity { - /// Output is streaming (pulsing dot). + /// Output is streaming (spinning icon). Working, - /// Finished working while the user was looking elsewhere (orange dot). + /// Claude Code stopped to wait for the user, a question or a permission (question mark). + Waiting, + /// Finished working while the user was looking elsewhere (check mark). Attention, } @@ -478,10 +482,12 @@ pub struct Workspace { pub list_model: crate::panels::sidebar::ListModel, /// The sidebar row under the pointer, the only one built with its × or archive button. pub hovered_row: Option, + /// Running rows the pointer just left, whose × slot is still shrinking away (see `shrink_close_slot`). + pub unhovered_rows: std::collections::HashSet, /// The minute (Unix time / 60) of the last tick's redraw, see `tick`. pub tick_minute: i64, - /// The working dot's pulse is running, see `start_pulse`. - pub pulsing: bool, + /// The working icon's spin is running, see `start_spin`. + pub spinning: bool, /// When a drag last reordered the sidebar, see `pointer_moved`. pub last_swap: std::time::Instant, /// Attached issues and pull requests are asked about on GitHub from time to time, see `attached_sync.rs`. @@ -585,8 +591,9 @@ impl Workspace { session_list: None, list_model: Default::default(), hovered_row: None, + unhovered_rows: Default::default(), tick_minute: 0, - pulsing: false, + spinning: false, last_swap: std::time::Instant::now(), attached_sync: Default::default(), config_sync: Default::default(), diff --git a/src/main.rs b/src/main.rs index 15557c7..9ddeae7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -24,7 +24,7 @@ gpui_kit::assets::icon_assets!( AppIcons, [ WindowMinimize, WindowMaximize, WindowRestore, WindowClose, Archive, ArchiveRestore, ArrowDownToLine, ArrowLeft, Brackets, Check, ChevronDown, ChevronRight, - CircleCheck, CircleDot, CircleSlash, CircleX, Clock, Ellipsis, Eye, ExternalLink, File, FileText, Folder, FolderGit2, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, + CircleCheck, CircleDot, CircleDotDashed, CircleQuestionMark, CircleSlash, CircleSmall, CircleX, Clock, Ellipsis, Eye, ExternalLink, File, FileText, Folder, FolderGit2, FolderOpen, GitBranch, GitCommitHorizontal, GitMerge, GitPullRequest, GitPullRequestClosed, GitPullRequestDraft, HeartPlus, LoaderCircle, Lock, MessageSquare, FileCode, PanelBottom, PanelLeft, PanelRight, Pencil, RefreshCw, Search, Settings, Terminal, X ] diff --git a/src/panels/mod.rs b/src/panels/mod.rs index 590a8a0..418ae00 100644 --- a/src/panels/mod.rs +++ b/src/panels/mod.rs @@ -1,12 +1,13 @@ //! What Claudiu draws around the terminals. `workspace_view` is the root view (main area, overlays, toasts), `sidebar` //! and `inspector` are the two side panels, `editor_pane` is editor mode's files and editor, `widgets` holds the small -//! shared pieces. `theme` and `scale` set the look, and `glide` does the smooth scrolling. +//! shared pieces, `status_icon` the icon at the start of a session row. `theme` and `scale` set the look, and `glide` does the smooth scrolling. pub mod editor_pane; pub mod glide; pub mod inspector; pub mod scale; pub mod sidebar; +pub mod status_icon; pub mod theme; pub mod widgets; pub mod workspace_view; diff --git a/src/panels/sidebar.rs b/src/panels/sidebar.rs index d69b02b..7cc3d67 100644 --- a/src/panels/sidebar.rs +++ b/src/panels/sidebar.rs @@ -4,7 +4,7 @@ use std::time::{Duration, Instant}; use gpui::{ - Animation, AnimationExt, AnyElement, AppContext, DragMoveEvent, SharedString, WeakEntity, ease_out_quint, pulsating_between, ClickEvent, Context, Div, FontWeight, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render, + Animation, AnimationExt, AnyElement, AppContext, DragMoveEvent, SharedString, WeakEntity, ease_out_quint, ClickEvent, Context, Div, FontWeight, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, ParentElement, Pixels, Render, Stateful, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px, }; @@ -13,6 +13,7 @@ use crate::app::{Act, Activity, MenuItem, SideDrag, Workspace}; use crate::store::{ExternalState, Id, Project, SessionKind, SessionRecord, now}; use crate::panels::theme::{self, hsla}; use gpui_kit::assets::IconName; +use crate::panels::status_icon::{SessionDot, StatusIcon}; use crate::panels::widgets::{Trigger, ago, avatar, button, clawd, countdown, icon, icon_button, key_hint, meter, section_label, shortcut, tick}; pub const SIDEBAR_W: f32 = 284.0; @@ -25,10 +26,14 @@ const RECENT_LIMIT: usize = 12; #[derive(Clone, PartialEq)] struct Row { id: Id, - /// What the leading status dot shows. + /// What the leading status icon shows. dot: SessionDot, title: String, right: String, + /// The project's name, on the first line of a running session's row. + project: String, + /// The branch checked out in the session's own working tree, on the last line of a running session's row. + branch: Option, active: bool, dim: bool, running: bool, @@ -39,19 +44,6 @@ struct Row { scope: &'static str, } -/// The four states a sidebar session dot can show. -#[derive(Clone, Copy, PartialEq, Eq)] -enum SessionDot { - /// Claude finished while the row was not being watched. - Attention, - /// The process is running and streaming output. - Working, - /// Running and idle, with the user up to date. - Active, - /// The session is not running. - Inactive, -} - /// Drag payload: a running session row, dropped onto another to reorder. struct DragSession(Id); @@ -81,17 +73,24 @@ fn lifted(el: T) -> T { el.bg(hsla(theme::ROW_ACTIVE)).border_1().border_color(hsla(theme::TEXT_FAINT)) } -/// Height of a session row plus the gap between rows. -const ROW_PITCH: f32 = ROW_H + LIST_GAP; +/// Height of a running session's row plus the gap between rows. +const ROW_PITCH: f32 = RUNNING_ROW_H + LIST_GAP; /// Heights of the list's parts, fixed so where each one sits is known before anything is drawn (see `visible_items`). const ROW_H: f32 = 25.0; +/// A running session's row has three lines: project, title and branch. +/// Its lines are 14 + 17 + 14 px with 2 px gaps (see `render_row`), which leaves 5.5 px above and below. +const RUNNING_ROW_H: f32 = 60.0; const HEADER_H: f32 = 20.0; const NOTE_H: f32 = 24.0; const SPACER_H: f32 = 10.0; const LIST_GAP: f32 = 2.0; /// Drawn beyond each edge of the view. The list is rebuilt for every frame its offset moves, so one row is enough. -const OVERSCAN: f32 = ROW_H + LIST_GAP; +const OVERSCAN: f32 = RUNNING_ROW_H + LIST_GAP; const SLIDE_MS: u64 = 160; +const CLOSE_SLIDE_MS: u64 = 140; +/// Width of a row's close button, and the gap between a row's parts. +const CLOSE_W: f32 = 22.0; +const ROW_GAP: f32 = 7.0; /// A row or project block that just changed places: it starts `from` px away from its new slot and slides in. /// `epoch` makes each reorder a fresh animation. @@ -120,30 +119,6 @@ fn slid(el: impl IntoElement + gpui::Styled + 'static, id: &Id, slide: Option f32 { - let t = (elapsed.as_millis() % PULSE.as_millis()) as f32 / PULSE.as_millis() as f32; - pulsating_between(0.35, 1.0)(t) -} - -/// The leading status dot: a small circle whose fill (and, when working, pulse) says what the session is doing. -fn session_dot(state: SessionDot) -> AnyElement { - static START: std::sync::OnceLock = std::sync::OnceLock::new(); - let dot = match state { - SessionDot::Attention => div().size(px(7.0)).rounded_full().bg(hsla(theme::ACCENT)), - SessionDot::Working => div().size(px(7.0)).rounded_full().bg(hsla(0xc8c8c8)).opacity(pulse_opacity(START.get_or_init(Instant::now).elapsed())), - SessionDot::Active => div().size(px(7.0)).rounded_full().bg(hsla(theme::TEXT_DIM)), - SessionDot::Inactive => div().size(px(7.0)).rounded_full().border_1().border_color(hsla(0x3d3d43)), - }; - div().w(px(14.0)).h(px(14.0)).flex_none().flex().items_center().justify_center().child(dot).into_any_element() -} - /// Moves `v[from]` into the slot of `v[to]`, shifting the items in between. fn move_to(v: &mut [T], from: usize, to: usize) { if from < to { @@ -184,6 +159,7 @@ impl Item { Item::Header(..) | Item::Older { .. } => HEADER_H, Item::Note(_) => NOTE_H, Item::Spacer => SPACER_H, + Item::Session { row, .. } if row.running => RUNNING_ROW_H, Item::Session { .. } => ROW_H, } } @@ -227,6 +203,21 @@ fn reveal_label() -> &'static str { } impl Workspace { + /// Keeps a running row's × slot drawn while it shrinks away after the pointer left, then redraws the list without it. + fn shrink_close_slot(&mut self, key: SharedString, cx: &mut Context) { + self.unhovered_rows.insert(key.clone()); + cx.spawn(async move |this, cx| { + cx.background_executor().timer(Duration::from_millis(CLOSE_SLIDE_MS)).await; + let _ = this.update(cx, |ws, cx| { + ws.unhovered_rows.remove(&key); + if let Some(list) = &ws.session_list { + list.update(cx, |_, cx| cx.notify()); + } + }); + }) + .detach(); + } + /// True when the pointer is somewhere new. A list shifting under a still pointer (a session ending, say) makes /// GPUI re-send a move at the same spot; that must not reorder anything. /// @@ -260,26 +251,27 @@ impl Workspace { SessionDot::Inactive } else { match activity { + Some(Activity::Waiting) => SessionDot::Waiting, Some(Activity::Attention) => SessionDot::Attention, Some(Activity::Working) => SessionDot::Working, None => SessionDot::Active, } }; let stale = rec.claude.as_ref().is_some_and(|c| c.external == ExternalState::Missing); + let project = { + let p = self.project_name(rec.project_id.as_ref()); + if p.is_empty() { rec.cwd.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() } else { p } + }; + let branch = running + .then(|| rec.project_id.as_ref().and_then(|id| self.store.project(id)).and_then(|p| p.git.as_ref()).and_then(|g| g.branch_at(&rec.cwd)).map(str::to_string)) + .flatten(); Row { id: rec.id.clone(), dot, title: rec.display_title().to_string(), - right: if with_project { - let p = self.project_name(rec.project_id.as_ref()); - if p.is_empty() { - rec.cwd.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() - } else { - p - } - } else { - ago(rec.last_active, now()) - }, + right: if with_project && !running { project.clone() } else { ago(rec.last_active, now()) }, + project, + branch, active: self.selected.as_deref() == Some(rec.id.as_str()), dim: !running, running, @@ -292,7 +284,7 @@ impl Workspace { fn session_menu(&self, rec: &SessionRecord, running: bool) -> Vec { let mut items = vec![]; - let item = |label: &str, act: Act, danger: bool, sep: bool| MenuItem { label: label.into(), hint: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; + let item = |label: &str, act: Act, danger: bool, sep: bool| MenuItem { label: label.into(), hint: None, detail: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; if running { items.push(item("Switch to session", Act::Select(rec.id.clone()), false, false)); } else if rec.kind == SessionKind::Claude { @@ -320,7 +312,7 @@ impl Workspace { } fn project_menu(&self, p: &Project) -> Vec { - let item = |label: String, act: Act, danger: bool, sep: bool| MenuItem { label, hint: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; + let item = |label: String, act: Act, danger: bool, sep: bool| MenuItem { label, hint: None, detail: None, act, danger, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items = vec![item("New Claude session here".into(), Act::NewClaude { cwd: p.path.clone() }, false, false)]; if p.git.is_some() { items.push(item("GitHub issues & PRs".into(), Act::OpenGithub { cwd: p.path.clone() }, false, true)); @@ -371,21 +363,74 @@ impl Workspace { let close_id = id.clone(); let middle_id = id.clone(); let archive_id = id.clone(); - let dot = session_dot(row.dot); + let dot = StatusIcon::new(format!("dot-{}-{}", row.scope, id), row.dot); let key = gpui::SharedString::from(format!("row-{}-{}", row.scope, id)); // Only the row under the pointer gets its × or archive button; the others keep the space empty. Building a // hidden button on every row cost more than the rest of the row. let hovered = self.hovered_row.as_ref() == Some(&key); + let closing = !hovered && self.unhovered_rows.contains(&key); + let running = row.running; let ws = cx.entity().downgrade(); let hover_key = key.clone(); + let right_text = if row.archived { "archived".to_string() } else if row.stale { "stale".to_string() } else { row.right.clone() }; + let right_color = hsla(if row.stale { theme::WARN } else { theme::TEXT_FAINT }); + let title_color = hsla(if row.dim { theme::TEXT_DIM } else { theme::TEXT }); + let ellipsis = |el: Div| el.min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis(); + let content = if row.running { + // Project and age, then the title with the status icon, then the branch. + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .gap(px(2.0)) + .child( + div() + .flex() + .gap(px(6.0)) + .text_size(crate::panels::scale::px(11.0)) + .line_height(crate::panels::scale::px(14.0)) + .text_color(hsla(theme::TEXT_FAINT)) + .child(ellipsis(div().flex_1()).child(row.project.clone())) + .child(div().flex_none().text_color(right_color).child(right_text)), + ) + .child( + div() + .flex() + .items_center() + .gap(px(7.0)) + .child(ellipsis(div().flex_1()).text_size(crate::panels::scale::px(13.0)).line_height(crate::panels::scale::px(17.0)).text_color(title_color).child(row.title.clone())) + .child(dot), + ) + .children(row.branch.clone().map(|b| ellipsis(div()).text_size(crate::panels::scale::px(11.0)).line_height(crate::panels::scale::px(14.0)).text_color(hsla(theme::TEXT_FAINT)).child(b))) + .into_any_element() + } else { + div() + .flex_1() + .min_w_0() + .flex() + .items_center() + .gap(px(7.0)) + .child(dot) + .child(ellipsis(div().flex_1()).text_size(crate::panels::scale::px(13.0)).text_color(title_color).child(row.title.clone())) + .child(div().flex_none().max_w(px(96.0)).overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(crate::panels::scale::px(11.0)).text_color(right_color).child(right_text)) + .into_any_element() + }; div() .id(key) .group("row") .on_hover(move |inside, _window, cx| { let changed = ws - .update(cx, |ws, _| { + .update(cx, |ws, cx| { let now = if *inside { Some(hover_key.clone()) } else { ws.hovered_row.clone().filter(|k| *k != hover_key) }; - std::mem::replace(&mut ws.hovered_row, now.clone()) != now + let moved = std::mem::replace(&mut ws.hovered_row, now.clone()) != now; + if *inside { + return ws.unhovered_rows.remove(&hover_key) || moved; + } + if running { + ws.shrink_close_slot(hover_key.clone(), cx); + } + moved || running }) .unwrap_or(false); if changed { @@ -394,8 +439,8 @@ impl Workspace { }) .flex() .items_center() - .gap(px(7.0)) - .h(px(ROW_H)) + .gap(px(ROW_GAP)) + .h(px(if row.running { RUNNING_ROW_H } else { ROW_H })) .pl(px(if row.indent { 22.0 } else { 10.0 })) .pr(px(6.0)) .mx(px(5.0)) @@ -414,29 +459,7 @@ impl Workspace { } }), ) - .child(dot) - .child( - div() - .flex_1() - .min_w_0() - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .text_size(crate::panels::scale::px(13.0)) - .text_color(hsla(if row.dim { theme::TEXT_DIM } else { theme::TEXT })) - .child(row.title), - ) - .child( - div() - .flex_none() - .max_w(px(96.0)) - .overflow_hidden() - .whitespace_nowrap() - .text_ellipsis() - .text_size(crate::panels::scale::px(11.0)) - .text_color(hsla(if row.stale { theme::WARN } else { theme::TEXT_FAINT })) - .child(if row.archived { "archived".to_string() } else if row.stale { "stale".to_string() } else { row.right }), - ) + .child(content) .when(row.running, |d| { // A middle click ends a running session, like its ×. d.on_mouse_up( @@ -444,17 +467,35 @@ impl Workspace { cx.listener(move |ws, _: &gpui::MouseUpEvent, window, cx| ws.act(Act::CloseLive(middle_id.clone()), window, cx)), ) }) - .when(!hovered, |d| d.child(div().flex_none().size(px(22.0)))) - .when(hovered && row.running, |d| { + .when(!hovered && !row.running, |d| d.child(div().flex_none().size(px(22.0)))) + .when((hovered || closing) && row.running, |d| { + // The slot grows from nothing to the button's width, pushing the age to the left, and shrinks back + // the same way once the pointer leaves. Its margin cancels the row's gap when the slot is empty, so + // nothing jumps. + let slide_key = SharedString::from(format!("close-{}-{}-{close_id}", if closing { "hide" } else { "show" }, row.scope)); + let button = icon_button(gpui::SharedString::from(format!("close-{}-{close_id}", row.scope)), IconName::X) + // Shown by hover style: a list that scrolled under a still pointer leaves the old row marked. + // While shrinking away the pointer is outside the row, so it is simply shown. + .when(!closing, |b| b.invisible().group_hover("row", |s| s.visible())) + .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { + cx.stop_propagation(); + ws.act(Act::CloseLive(close_id.clone()), window, cx); + })); d.child( - // Still shown by hover style: a list that scrolled under a still pointer leaves the old row marked. - icon_button(gpui::SharedString::from(format!("close-{}-{close_id}", row.scope)), IconName::X) - .invisible() - .group_hover("row", |s| s.visible()) - .on_click(cx.listener(move |ws, _: &ClickEvent, window, cx| { - cx.stop_propagation(); - ws.act(Act::CloseLive(close_id.clone()), window, cx); - })), + div() + .flex() + .flex_none() + .justify_end() + .overflow_hidden() + .child(button) + .with_animation( + slide_key, + Animation::new(Duration::from_millis(CLOSE_SLIDE_MS)).with_easing(ease_out_quint()), + move |d, t| { + let open = if closing { 1.0 - t } else { t }; + d.w(px(CLOSE_W * open)).ml(px(-ROW_GAP * (1.0 - open))) + }, + ), ) }) .when(hovered && !row.running, |d| { @@ -631,7 +672,7 @@ impl Workspace { /// "+ Code session" with no project chosen: pick where it starts. fn new_session_menu(&self) -> Vec { - let item = |label: String, hint: Option, act: Act, disabled: bool, sep: bool| MenuItem { label, hint, act, danger: false, disabled, separator_before: sep, remove: None, icon: None }; + let item = |label: String, detail: Option, act: Act, disabled: bool, sep: bool| MenuItem { label, hint: None, detail, act, danger: false, disabled, separator_before: sep, remove: None, icon: None }; let mut items = vec![item("Start the session in…".into(), None, Act::Dismiss, true, false)]; items.extend(self.store.data.projects.iter().map(|p| item(p.name.clone(), Some(crate::panels::widgets::short_path(&p.path)), Act::NewClaude { cwd: p.path.clone() }, false, false))); items.push(item("Add project…".into(), None, Act::ImportProject, false, true)); @@ -664,7 +705,7 @@ impl Workspace { cx, move |ws, at, _w, cx| { let chosen = ws.project_filter().map(|p| p.id.clone()); - let item = |label: String, act: Act, sep: bool| MenuItem { label, hint: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; + let item = |label: String, act: Act, sep: bool| MenuItem { label, hint: None, detail: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items = vec![item(format!("{}All projects", tick(chosen.is_none())), Act::FilterProject(None), false)]; items.extend(ws.store.data.projects.iter().map(|p| item(format!("{}{}", tick(chosen.as_ref() == Some(&p.id)), p.name), Act::FilterProject(Some(p.id.clone())), false))); items.push(item("Add project…".into(), Act::ImportProject, true)); @@ -827,6 +868,7 @@ impl Workspace { let item = |label: String, hint: Option, act: Act, danger: bool, sep: bool| MenuItem { label, hint, + detail: None, act, danger, disabled: false, @@ -935,18 +977,30 @@ fn plan_label(plan: &str) -> String { #[cfg(test)] mod tests { - use super::{PULSE, is_reorder, move_to, pulse_opacity, visible_items}; - use std::time::Duration; + use super::{Item, ROW_H, RUNNING_ROW_H, Row, SessionDot, is_reorder, move_to, visible_items}; - #[test] - fn the_working_dot_fades_between_its_bounds_and_repeats_each_pulse() { - for ms in (0..2400).step_by(50) { - let o = pulse_opacity(Duration::from_millis(ms)); - assert!((0.35..=1.0).contains(&o), "{o} at {ms} ms"); - assert_eq!(o, pulse_opacity(Duration::from_millis(ms) + PULSE)); + fn row(running: bool) -> Row { + Row { + id: "s".into(), + dot: SessionDot::Active, + title: String::new(), + right: String::new(), + project: String::new(), + branch: None, + active: false, + dim: false, + running, + indent: false, + stale: false, + archived: false, + scope: "cur", } - // gpui's breathing curve: brightest a quarter of the way through, dimmest at three quarters. - assert!(pulse_opacity(PULSE / 4) > 0.99 && pulse_opacity(PULSE * 3 / 4) < 0.36); + } + + #[test] + fn a_running_session_gets_the_tall_row_and_a_recent_one_stays_short() { + assert_eq!(Item::Session { row: row(true), reorder: true }.height(), RUNNING_ROW_H); + assert_eq!(Item::Session { row: row(false), reorder: false }.height(), ROW_H); } #[test] diff --git a/src/panels/status_icon.rs b/src/panels/status_icon.rs new file mode 100644 index 0000000..febf79f --- /dev/null +++ b/src/panels/status_icon.rs @@ -0,0 +1,178 @@ +//! The status icon at the start of a session row: one Lucide circle per state, spinning while Claude works. When the +//! state changes, the old icon turns, shrinks and fades away while the new one does the same in reverse. + +use std::f32::consts::{FRAC_PI_2, TAU}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use gpui::{Animation, AnimationExt, AnyElement, App, Hsla, IntoElement, ParentElement, RenderOnce, SharedString, Styled, Window, div, ease_out_quint, px}; +use gpui_kit::assets::IconName; + +use crate::panels::theme::{self, hsla}; +use crate::panels::widgets::icon; + +/// What a session row's status icon shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SessionDot { + /// Claude Code is waiting for the user: a question or a permission. + Waiting, + /// Claude finished while the row was not being watched. + Attention, + /// The process is running and streaming output. + Working, + /// Running and idle, with the user up to date. + Active, + /// The session is not running. + Inactive, +} + +/// The icon's square, and how long one turn of the working icon takes. +const SLOT: f32 = 14.0; +const SPIN: Duration = Duration::from_millis(1600); +/// How often the working icon is redrawn (see `Workspace::start_spin`). A gpui animation would redraw the whole +/// window every frame for as long as any session works. +pub const SPIN_STEP: Duration = Duration::from_millis(40); +/// How long one icon takes to turn into the next. +const MORPH: Duration = Duration::from_millis(280); + +/// How far the working icon has turned `elapsed` into its spin, in radians; repeats every `SPIN`. +fn spin_angle(elapsed: Duration) -> f32 { + (elapsed.as_millis() % SPIN.as_millis()) as f32 / SPIN.as_millis() as f32 * TAU +} + +/// How one icon is drawn: its size and opacity as a fraction of the resting look, and an extra turn. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Look { + scale: f32, + opacity: f32, + turn: f32, +} + +impl Look { + const REST: Look = Look { scale: 1.0, opacity: 1.0, turn: 0.0 }; +} + +/// The old and the new icon `t` (0 to 1) of the way through a morph. The new one ends at `Look::REST`, so nothing +/// jumps when the morph is over and the plain icon takes its place. +fn morph_frame(t: f32) -> (Look, Look) { + let old = Look { scale: 1.0 - 0.6 * t, opacity: 1.0 - t, turn: t * FRAC_PI_2 }; + let new = Look { scale: 0.4 + 0.6 * t, opacity: t, turn: (t - 1.0) * FRAC_PI_2 }; + (old, new) +} + +/// One state's icon and color. `None` is the not-running ring, which is drawn rather than loaded. +fn icon_of(state: SessionDot) -> Option<(IconName, u32)> { + match state { + SessionDot::Waiting => Some((IconName::CircleQuestionMark, theme::WARN)), + SessionDot::Attention => Some((IconName::CircleCheck, theme::ACCENT)), + SessionDot::Working => Some((IconName::CircleDotDashed, 0xc8c8c8)), + SessionDot::Active => Some((IconName::CircleSmall, theme::TEXT_DIM)), + SessionDot::Inactive => None, + } +} + +/// `state` drawn with `look`, centered in the slot. +fn glyph(state: SessionDot, look: Look) -> AnyElement { + static START: OnceLock = OnceLock::new(); + let drawn = match icon_of(state) { + Some((name, color)) => { + let spin = if state == SessionDot::Working { spin_angle(START.get_or_init(Instant::now).elapsed()) } else { 0.0 }; + let color: Hsla = hsla(color).opacity(look.opacity); + icon(name, SLOT * look.scale).text_color(color).rotate(gpui::radians(spin + look.turn)).into_any_element() + } + None => div().size(px(7.0 * look.scale)).rounded_full().border_1().border_color(hsla(0x3d3d43).opacity(look.opacity)).into_any_element(), + }; + div().absolute().inset_0().flex().items_center().justify_center().child(drawn).into_any_element() +} + +/// What the icon showed last, kept across redraws so a change of state can be told from a redraw. +struct Memory { + shown: SessionDot, + /// The state before the last change, until `MORPH` after it. + from: Option, + changed: Instant, + /// Counts the changes, so each morph is a new animation. + epoch: u64, +} + +/// A row's status icon. `id` must be the same on every redraw of the row and differ between rows. +#[derive(IntoElement)] +pub struct StatusIcon { + id: SharedString, + state: SessionDot, +} + +impl StatusIcon { + pub fn new(id: impl Into, state: SessionDot) -> Self { + Self { id: id.into(), state } + } +} + +impl RenderOnce for StatusIcon { + fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement { + let Self { id, state } = self; + let memory = window.use_keyed_state(id.clone(), cx, move |_, _| Memory { shown: state, from: None, changed: Instant::now(), epoch: 0 }); + let (from, epoch) = memory.update(cx, |m, _| { + if m.shown != state { + m.from = Some(m.shown); + m.shown = state; + m.changed = Instant::now(); + m.epoch += 1; + } + (m.from.filter(|_| m.changed.elapsed() < MORPH), m.epoch) + }); + let slot = div().relative().flex_none().size(px(SLOT)); + match from { + None => slot.child(glyph(state, Look::REST)).into_any_element(), + Some(from) => slot + .with_animation( + SharedString::from(format!("{id}-morph-{epoch}")), + Animation::new(MORPH).with_easing(ease_out_quint()), + move |slot, t| { + let (old, new) = morph_frame(t); + slot.child(glyph(from, old)).child(glyph(state, new)) + }, + ) + .into_any_element(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_morph_starts_on_the_old_icon_and_ends_on_the_new_one_at_rest() { + let (old, new) = morph_frame(0.0); + assert_eq!(old, Look::REST); + assert_eq!(new.opacity, 0.0); + let (old, new) = morph_frame(1.0); + assert_eq!(old.opacity, 0.0); + assert_eq!(new, Look::REST); + } + + #[test] + fn halfway_through_both_icons_are_partly_visible() { + let (old, new) = morph_frame(0.5); + assert!(old.opacity > 0.0 && new.opacity > 0.0); + assert!(old.scale < 1.0 && new.scale < 1.0); + } + + #[test] + fn the_working_icon_turns_once_per_spin_and_repeats() { + assert_eq!(spin_angle(Duration::ZERO), 0.0); + let quarter = spin_angle(SPIN / 4); + assert!((quarter - FRAC_PI_2).abs() < 1e-3, "a quarter of the spin is {quarter} radians"); + let (early, later) = (spin_angle(Duration::from_millis(300)), spin_angle(Duration::from_millis(300) + SPIN * 3)); + assert!((early - later).abs() < 1e-4); + } + + #[test] + fn only_a_session_that_is_not_running_draws_a_ring_instead_of_an_icon() { + for state in [SessionDot::Waiting, SessionDot::Attention, SessionDot::Working, SessionDot::Active] { + assert!(icon_of(state).is_some(), "{state:?}"); + } + assert!(icon_of(SessionDot::Inactive).is_none()); + } +} diff --git a/src/panels/workspace_view.rs b/src/panels/workspace_view.rs index a31584b..3007bef 100644 --- a/src/panels/workspace_view.rs +++ b/src/panels/workspace_view.rs @@ -348,7 +348,7 @@ impl Workspace { .child(button("home-claude", "New", true).dropdown( cx, |ws, at, _w, cx| { - let item = |label: String, act: Act, sep: bool| crate::app::MenuItem { label, hint: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; + let item = |label: String, act: Act, sep: bool| crate::app::MenuItem { label, hint: None, detail: None, act, danger: false, disabled: false, separator_before: sep, remove: None, icon: None }; let mut items: Vec<_> = ws.store.data.projects.iter().map(|p| item(p.name.clone(), Act::NewClaude { cwd: p.path.clone() }, false)).collect(); let sep = !items.is_empty(); items.push(item("Add project…".into(), Act::ImportProject, sep)); @@ -398,7 +398,7 @@ impl Workspace { let color = if item.disabled { theme::TEXT_FAINT } else if item.danger { theme::DANGER } else { theme::TEXT }; let row = div() .id(gpui::SharedString::from(format!("menu-{i}"))) - .h(px(28.0)) + .h(px(if item.detail.is_some() { 42.0 } else { 28.0 })) .px(px(10.0)) .flex() .items_center() @@ -407,7 +407,15 @@ impl Workspace { .text_color(hsla(color)) .gap(px(8.0)) .group(gpui::SharedString::from(format!("menu-row-{i}"))) - .child(div().flex_1().min_w_0().overflow_hidden().whitespace_nowrap().text_ellipsis().child(item.label.clone())) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child(div().overflow_hidden().whitespace_nowrap().text_ellipsis().child(item.label.clone())) + .children(item.detail.clone().map(|d| div().overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(d))), + ) .children(item.icon.map(|name| icon(name, 12.0).text_color(hsla(theme::TEXT_FAINT)))) .children(item.hint.clone().map(|h| div().flex_none().text_size(crate::panels::scale::px(11.0)).text_color(hsla(theme::TEXT_FAINT)).child(h))) .children(item.remove.clone().map(|remove| {