Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

233 KB
Raw Blame
use crate::quad::{
    HeapQuadAllocator, QuadClipRect, QuadTrait, TripleLayerQuadAllocator,
    TripleLayerQuadAllocatorTrait,
};
use crate::termwindow::sidebar_disclosure::{FolderChevrons, FolderKind};
use crate::termwindow::render::corners::{
    BOTTOM_LEFT_ROUNDED_CORNER, BOTTOM_RIGHT_ROUNDED_CORNER, TOP_LEFT_ROUNDED_CORNER,
    TOP_RIGHT_ROUNDED_CORNER,
};
use crate::termwindow::ui::icons::{distro_to_icon, BrandIcon, MaterialIcon, SvgIcon};
use crate::termwindow::ui::platform_chrome;
use crate::termwindow::ui::sidebar_jump::{CurrentRow, Fold, JumpList};
use crate::termwindow::ui::status_icon::UiStatusKind;
use crate::termwindow::ui::tokens::{
    CAPSULE_BORDER_WIDTH, SEE_THROUGH_BORDER_BOOST, SEE_THROUGH_SURFACE_ALPHA, SIDEBAR_ICON_GAP,
    SIDEBAR_INSET, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, SIDEBAR_RESIZE_HANDLE_WIDTH,
    SIDEBAR_ROW_GAP, SIDEBAR_ROW_RADIUS, SIDEBAR_TITLE_FADE_GAP, SIDEBAR_WIDTH_CELLS,
    WINDOW_TAB_FULLSCREEN_NEW_SESSION_EXTRA_HEIGHT, WINDOW_TAB_FULLSCREEN_NEW_SESSION_Y_OFFSET,
    WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_X, WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_Y_OFFSET,
    WINDOW_TAB_TOP_SPACER,
};
use crate::native_settings::{NativeThreadIcons, NativeThreadStatus};
use crate::termwindow::sidebar_make_way::shifts_for_move;
use crate::termwindow::{SidebarRowKind, UIItem, UIItemType};
use crate::thread_marks::{self, Mark};
use crate::ui::draw::DrawContext;
use crate::ui::{scale_ui_f32, scale_ui_usize, unscale_ui_usize, UiPalette};
use crate::utilsprites::RenderMetrics;
use crate::workspace_threads;
use anyhow::Context;
use mux::Mux;
use std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
use wezterm_font::LoadedFont;
use window::color::LinearRgba;
use window::{MouseEventKind as WMEK, RectF, WindowOps};

const SIDEBAR_SCROLLBAR_VISIBLE_MS: u64 = 900;
pub(crate) const SIDEBAR_SETTINGS_FOOTER_HEIGHT: usize = 72;
const SIDEBAR_SETTINGS_FADE_HEIGHT: usize = 52;
const SIDEBAR_LIST_BOTTOM_PADDING: usize = 65;
const SIDEBAR_SETTINGS_ROW_TOP_PADDING: usize = 4;
const SIDEBAR_SETTINGS_ROW_BOTTOM_PADDING: usize = 12;
const SIDEBAR_SETTINGS_ROW_SIDE_PADDING: usize = 16;
const SIDEBAR_SETTINGS_ICON_EXTRA_INSET: usize = 18;
const SIDEBAR_SETTINGS_ROW_LIFT: usize = 18;
const SIDEBAR_TOP_FADE_HEIGHT: usize = 32;
const WORKSPACE_GROUP_EXTRA_GAP: usize = 8;
const WORKSPACE_SECTION_LABEL_GAP: usize = 12;
/// Whether the sidebar footer carries its view-options button.
///
/// Parked: the menu behind it (group-by, the status filter, archived projects)
/// was not earning the footer slot it cost. Everything behind the button --
/// the menu, its handlers, the persisted filters -- is untouched, so flipping
/// this back on restores it. Note that while it is off the menu has no other
/// entry point, so a filter already persisted in
/// `workspace_sidebar_hidden_statuses` cannot be cleared from the UI.
const SHOW_SIDEBAR_VIEW_OPTIONS: bool = false;

/// The largest recording of a folder's rows kept for the next frame.
const FOLDER_ROWS_KEEP_BYTES: usize = 1 << 20;
/// The Workspaces heading, as the rows that glide know it.
const WORKSPACES_LABEL_KEY: &str = "section:workspaces";
/// The Pinned heading likewise, which never moves but can appear.
const PINNED_LABEL_KEY: &str = "section:pinned";

/// How far open a folder is drawn: where its animation has got to, or
/// settled where it is.
fn folder_open(chevrons: &FolderChevrons, kind: FolderKind, id: &str, collapsed: bool) -> f32 {
    chevrons
        .open_of(kind, id)
        .unwrap_or(if collapsed { 0.0 } else { 1.0 })
}
/// Room between New Thread's row and the list under it.
const TOP_ACTION_BOTTOM_GAP: usize = 16;

/// Diameter for every round sidebar action button, and the height of the
/// New Thread pill beside them. Also their corner radius, since they are all
/// fully rounded.
///
/// As tall as a thread row (`SESSION_ROW_MIN_HEIGHT`), so New Thread lines
/// up with the rows under it. The per-section buttons are additionally
/// clamped to `session_row_height - 8`, and so come out a little smaller
/// than the notification button.
const TOP_ACTION_MAX_HEIGHT: usize = 72;
const SESSION_ROW_MIN_HEIGHT: usize = 72;
/// How much further in from a row's end its status mark sits than its icons
/// from the start.
const SESSION_STATUS_END_CLEARANCE: usize = 6;
const SESSION_ACTION_MIN_SIZE: usize = 48;
const SESSION_ACTION_MAX_SIZE: usize = 52;
const SESSION_ACTION_ICON_INSET: usize = 12;
const SESSION_STATUS_DOT_SIZE: usize = 10;
/// The square a thread's mark sits in; the Agents panel and the hover
/// cards draw theirs at this size too.
/// A thread's program icons against the row's height: about the size
/// of a window tab's.
const SIDEBAR_ICON_SCALE: f32 = 0.7;
pub(crate) const SESSION_STATUS_ICON_SIZE: usize = 20;
const SESSION_STATUS_ACTIVE_ICON_SIZE: usize = 26;
const SPACE_DISCONNECTED_COLOR: LinearRgba = LinearRgba::with_components(0.86, 0.45, 0.12, 1.0);
const NOTIFICATION_BADGE_COLOR: LinearRgba = LinearRgba::with_components(0.96, 0.16, 0.22, 1.0);
const NOTIFICATION_BADGE_PULSE_DURATION: Duration = Duration::from_millis(1800);
const NOTIFICATION_BADGE_PULSE_COUNT: f32 = 3.0;
const NOTIFICATION_BADGE_FRAME_MS: u64 = 33;
const SIDEBAR_SECTION_ACTION_ICON_INSET: usize = 6;

/// Connection health of the active Space's mux client domain, as shown by
/// the sidebar indicator. A local Space reports its link to the session
/// host, and is always Connected without one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SpaceConnectionState {
    Connected,
    /// An attach is in flight (initial connect or manual re-attach); not an
    /// error state, so no alert icon and no Reconnect button.
    Connecting,
    /// Transport lost; the automatic retry loop is running.
    Reconnecting,
    /// Not connected and nothing is retrying (retry loop parked after
    /// sustained failure, domain detached, or never connected); the
    /// sidebar offers a Reconnect button.
    Disconnected,
}

#[derive(Debug, Clone, Copy)]
pub struct WorkspaceSidebarRect {
    pub x: usize,
    pub y: usize,
    pub width: usize,
    pub height: usize,
}

#[derive(Debug, Clone, Copy)]
pub struct WorkspaceSidebarScrollGeometry {
    pub track_x: usize,
    pub track_y: usize,
    pub track_width: usize,
    pub track_height: usize,
    pub thumb_y: f32,
    pub thumb_height: f32,
    pub max_scroll: f32,
}

#[derive(Debug, Clone, Copy)]
struct WorkspaceSidebarLayout {
    panel_x: usize,
    panel_y: usize,
    panel_width: usize,
    panel_height: usize,
    content_bottom: usize,
    settings_footer_y: usize,
    settings_footer_height: usize,
    row_height: usize,
    show_sidebar_toolbar: bool,
    space_menu_y: usize,
    space_menu_height: usize,
    /// Height of the "Reconnect" row below the Space menu; non-zero only
    /// while the Space's mux domain is Disconnected (a stable state — the
    /// row never flickers in and out on transient lag).
    reconnect_row_height: usize,
    top_action_y_offset: usize,
    top_action_height: usize,
    list_top: usize,
}

pub fn workspace_sidebar_width_for_metrics(render_metrics: &RenderMetrics, dpi: usize) -> usize {
    let min_width = scale_ui_usize(SIDEBAR_MIN_WIDTH, dpi);
    let max_width = scale_ui_usize(SIDEBAR_MAX_WIDTH, dpi);
    let default_width =
        (render_metrics.cell_size.width as usize * SIDEBAR_WIDTH_CELLS).max(min_width);
    crate::native_settings::workspace_sidebar_width()
        .map(|width| scale_ui_usize(width, dpi))
        .unwrap_or(default_width)
        .clamp(min_width, max_width)
}

/// What every thread row of one paint draws its icons and mark with,
/// worked out once for the paint: the sidebar's and the thread search's.
pub(crate) struct ThreadRowMarks {
    pub(crate) layout: NativeThreadIcons,
    pub(crate) status: NativeThreadStatus,
    /// The icons by workspace.
    icons: Rc<HashMap<String, Vec<crate::tab_icons::ResolvedIcon>>>,
    /// Each thread's workspace, by thread id.
    workspaces: HashMap<workspace_threads::WorkspaceThreadId, String>,
    /// The terminal's, for a thread with nothing running.
    terminal: crate::tab_icons::ResolvedIcon,
    pub(crate) count_font: Rc<LoadedFont>,
    pub(crate) count_metrics: RenderMetrics,
}

impl ThreadRowMarks {
    /// The icons of thread `thread_id`'s programs; for one with nothing
    /// running -- closed, or not yet opened -- the terminal it would open
    /// to.
    pub(crate) fn icons(&self, thread_id: &str, live: bool) -> &[crate::tab_icons::ResolvedIcon] {
        live.then(|| self.workspaces.get(thread_id))
            .flatten()
            .and_then(|workspace| self.icons.get(workspace))
            .filter(|icons| !icons.is_empty())
            .map(Vec::as_slice)
            .unwrap_or(std::slice::from_ref(&self.terminal))
    }
}

/// `top` laid over `bottom`.
pub(crate) fn over(top: LinearRgba, bottom: LinearRgba) -> LinearRgba {
    let alpha = top.3 + bottom.3 * (1.0 - top.3);
    if alpha <= 0.0 {
        return top;
    }
    let mix = |t: f32, b: f32| (t * top.3 + b * bottom.3 * (1.0 - top.3)) / alpha;
    LinearRgba::with_components(
        mix(top.0, bottom.0),
        mix(top.1, bottom.1),
        mix(top.2, bottom.2),
        alpha,
    )
}

/// Whether a program in the thread reported that it stopped on an error.
pub(crate) fn thread_has_errored_agent(thread_id: &str) -> bool {
    workspace_threads::thread_workspace_name(thread_id).is_some_and(|workspace| {
        crate::agent_status::any_agent_in_workspace(&workspace, |agent| {
            agent.state == crate::agent_status::AgentState::Error
        })
    })
}

fn centered_inner_start(origin: usize, outer: usize, inner: usize) -> usize {
    if inner <= outer {
        origin + (outer - inner) / 2
    } else {
        origin.saturating_sub((inner - outer) / 2)
    }
}

impl crate::TermWindow {
    pub(crate) fn acknowledge_active_workspace_thread_work(&self) -> bool {
        let mux = Mux::get();
        let Some(window) = mux.get_window(self.mux_window_id) else {
            return false;
        };
        workspace_threads::acknowledge_thread_work_for_workspace(window.get_workspace())
    }

    pub(crate) fn acknowledge_active_workspace_thread_work_deferred(&self) -> bool {
        let mux = Mux::get();
        let Some(window) = mux.get_window(self.mux_window_id) else {
            return false;
        };
        workspace_threads::acknowledge_thread_work_for_workspace_deferred(window.get_workspace())
    }

    /// The docked width, clamped. Not "the width right now": ask
    /// `workspace_sidebar_width` for what the terminal is laid out against
    /// and `workspace_sidebar_presented_width` for what is on screen.
    pub(crate) fn workspace_sidebar_docked_width(&self) -> usize {
        let min_width = scale_ui_usize(SIDEBAR_MIN_WIDTH, self.dimensions.dpi);
        self.workspace_sidebar_width
            .clamp(min_width, self.workspace_sidebar_max_width())
    }

    /// The width the TERMINAL is laid out against. Zero whenever the sidebar
    /// is collapsed, hover reveal or not: a hover must never reflow a PTY.
    /// Every consumer that decides where the terminal, the tab bar or a pane
    /// lives asks this one.
    pub fn workspace_sidebar_width(&self) -> usize {
        if let Some(width) = self.library_laid_out_width() {
            return width;
        }
        self.workspace_sidebar_sizing_width()
    }

    /// The width the terminal's SIZE is worked out against: the sidebar's,
    /// the Library open or not. The Library pushes the terminal aside, past
    /// the window's edge, rather than making it narrower, so its programs
    /// hear of no resize.
    pub(crate) fn workspace_sidebar_sizing_width(&self) -> usize {
        if self.workspace_sidebar_collapsed {
            0
        } else {
            self.workspace_sidebar_docked_width()
        }
    }

    /// The width the panel is DRAWN and HIT-TESTED at. Equal to
    /// `workspace_sidebar_width` while docked; the full docked width while a
    /// hover reveal is on screen, at which point the terminal behind it has
    /// not moved, and while it slides away after collapsing. Presentation
    /// and pointer routing only.
    pub(crate) fn workspace_sidebar_presented_width(&self) -> usize {
        if self.workspace_sidebar_is_presented() {
            self.workspace_sidebar_docked_width()
        } else {
            0
        }
    }

    /// Whether the panel is on screen at all, by any route: docked, a hover
    /// reveal, or on its way back into the edge.
    pub(crate) fn workspace_sidebar_is_presented(&self) -> bool {
        !self.workspace_sidebar_collapsed
            || self.workspace_sidebar_hover.is_presented()
            || self
                .sidebar_slides
                .closing(crate::termwindow::sidebar_slide::Side::Left)
    }

    pub fn workspace_sidebar_max_width(&self) -> usize {
        let min_width = scale_ui_usize(SIDEBAR_MIN_WIDTH, self.dimensions.dpi);
        scale_ui_usize(SIDEBAR_MAX_WIDTH, self.dimensions.dpi)
            .min((self.dimensions.pixel_width / 2).max(min_width))
    }

    pub fn set_workspace_sidebar_width(&mut self, width: usize) {
        let min_width = scale_ui_usize(SIDEBAR_MIN_WIDTH, self.dimensions.dpi);
        self.workspace_sidebar_width = width.clamp(min_width, self.workspace_sidebar_max_width());
    }

    pub fn persist_workspace_sidebar_width(&self) {
        let min_width = scale_ui_usize(SIDEBAR_MIN_WIDTH, self.dimensions.dpi);
        let max_width = scale_ui_usize(SIDEBAR_MAX_WIDTH, self.dimensions.dpi);
        let width = self.workspace_sidebar_width.clamp(min_width, max_width);
        let width = unscale_ui_usize(width, self.dimensions.dpi);
        if let Err(err) = crate::native_settings::save_workspace_sidebar_width(width) {
            log::warn!("failed to save workspace sidebar width: {err:#}");
        }
    }

    /// Toggle the panel, and remember the result so new windows inherit it.
    ///
    /// Reads [`Self::workspace_sidebar_is_presented`] rather than the collapsed
    /// flag, because during a hover reveal the two disagree: the panel is on
    /// screen while `workspace_sidebar_collapsed` is still true. The tab bar's
    /// button is labelled from the presented state
    /// ([`Self::workspace_sidebar_toggle_icon`]), so it reads "close" during a
    /// reveal — and toggling the flag from there *docked* the panel instead of
    /// closing it. Harmless while nothing persisted; once this writes the
    /// setting, brushing the left edge and clicking "close" would re-dock the
    /// sidebar for every window from then on.
    pub fn toggle_workspace_sidebar(&mut self) {
        // The Library is in its place: there is no sidebar to toggle, as the
        // titlebar's button says by hiding (`open_library`).
        if self.library_presented() {
            return;
        }
        let revealed = self.workspace_sidebar_hover.progress(Instant::now());
        let shown =
            workspace_sidebar_toggle_target(self.workspace_sidebar_collapsed, revealed.is_some());
        self.workspace_sidebar_swipe.cancel_immediately();
        self.clear_workspace_space_swipe_frame_transition();
        self.set_workspace_sidebar_shown(shown);
        match revealed.filter(|_| shown) {
            // Out over the terminal already, or on its way: the terminal
            // comes out from under it.
            Some(revealed) => {
                self.dock_revealed_sidebar(crate::termwindow::sidebar_slide::Side::Left, revealed);
            }
            None => {
                self.slide_sidebar(crate::termwindow::sidebar_slide::Side::Left, shown);
            }
        }
    }

    pub fn expand_workspace_sidebar(&mut self) {
        self.set_workspace_sidebar_shown(true);
        // Docked while on its way back: it comes out again from there.
        if self
            .sidebar_slides
            .closing(crate::termwindow::sidebar_slide::Side::Left)
        {
            self.slide_sidebar(crate::termwindow::sidebar_slide::Side::Left, true);
        }
    }

    /// Dock or collapse the panel and persist that choice.
    ///
    /// The write is skipped when nothing changed, which matters because the
    /// resize drag calls this on every pointer move.
    pub(crate) fn set_workspace_sidebar_shown(&mut self, shown: bool) {
        let collapsed = !shown;
        if self.workspace_sidebar_collapsed != collapsed {
            self.workspace_sidebar_collapsed = collapsed;
            crate::native_settings::save_workspace_sidebar_shown(shown);
        }
        if collapsed {
            self.workspace_sidebar_scratch = Default::default();
        }
        // Either way the hover machine must not act on the pointer still
        // sitting where it was: collapsing must not instantly re-reveal, and
        // docking makes the reveal moot. The native titlebar button also
        // disappears/reappears with this change, so its hover flag would
        // otherwise go stale (no exit event fires for a removed button).
        self.titlebar_sidebar_button_hovered = false;
        self.workspace_sidebar_hover.suppress_until_pointer_leaves();
    }

    pub(crate) fn workspace_sidebar_toggle_icon(&self) -> SvgIcon {
        // Keyed to the DOCKED state, not the transient hover reveal: while
        // the panel is only hover-previewed the button reads "open", telling
        // the truth about what a click does (pin it open).
        if self.workspace_sidebar_collapsed {
            SvgIcon::PanelLeftOpen
        } else {
            SvgIcon::PanelLeftClose
        }
    }

    pub fn tab_bar_left_edge(&self) -> usize {
        let border = self.get_os_border();
        border.left.get() as usize + self.workspace_sidebar_width()
    }

    /// The panel as presented — a hover reveal is included. Anything
    /// deriving terminal geometry wants `workspace_sidebar_width` instead.
    pub fn workspace_sidebar_rect(&self) -> Option<WorkspaceSidebarRect> {
        // A Library card is this sidebar, laid out in the card.
        if let Some(rect) = self.library_card_rect() {
            return Some(rect);
        }
        self.workspace_sidebar_rect_for_width(self.workspace_sidebar_presented_width())
    }

    fn workspace_sidebar_rect_for_width(&self, width: usize) -> Option<WorkspaceSidebarRect> {
        let border = self.get_os_border();
        let x = border.left.get() as usize;
        let y = border.top.get() as usize;
        let width = width.min(
            self.dimensions
                .pixel_width
                .saturating_sub((border.left + border.right).get() as usize),
        );
        let height = self
            .dimensions
            .pixel_height
            .saturating_sub(y + border.bottom.get() as usize);

        if width == 0 || height == 0 {
            return None;
        }

        Some(WorkspaceSidebarRect {
            x,
            y,
            width,
            height,
        })
    }

    /// The left-edge strip that arms a hover reveal, as (x, y, w, h) in
    /// window pixels. Computed against the docked rect so it exists while
    /// the panel does not.
    pub(crate) fn workspace_sidebar_hover_hot_zone(&self) -> Option<(usize, usize, usize, usize)> {
        let rect = self.workspace_sidebar_rect_for_width(self.workspace_sidebar_docked_width())?;
        // The traffic lights stay at the top-left when the window tab row
        // hides; off macOS the sidebar button does, in the pane bar there.
        let top_tab_bar_height = if cfg!(target_os = "macos") {
            self.tab_bar_pixel_height().unwrap_or(0.0)
        } else {
            self.window_top_left_chrome_height()
        }
        .ceil() as usize;
        crate::termwindow::sidebar_hover::hot_zone(
            rect.x,
            rect.y,
            rect.height,
            self.ui_px(crate::termwindow::ui::tokens::SIDEBAR_HOVER_HOT_ZONE_WIDTH),
            top_tab_bar_height,
        )
    }

    /// `section_gap`/`group_gap` arrive PRE-SCALED (`ui_px` of
    /// `WORKSPACE_SECTION_LABEL_GAP`/`WORKSPACE_GROUP_EXTRA_GAP`): this is an
    /// associated fn with no `&self` to scale with, and the paint loop adds
    /// the scaled values — adding the raw constants here over-counts every
    /// gap on any display whose ui scale is not exactly 1 (e.g. Linux 96dpi
    /// at 0.5), inflating max_scroll past the painted content.
    fn workspace_sidebar_list_height(
        chevrons: &FolderChevrons,
        view: &workspace_threads::WorkspaceThreadsView,
        shared_rows: usize,
        row_height: usize,
        row_gap: usize,
        section_gap: usize,
        group_gap: usize,
    ) -> usize {
        let mut height = 0usize;
        if !view.pinned_threads.is_empty() {
            height = height.saturating_add(row_height + row_gap);
            height = height.saturating_add(
                view.pinned_threads
                    .len()
                    .saturating_mul(row_height + row_gap),
            );
        }
        // The "Workspaces" section label row precedes the folder list only
        // when the Space has projects of its own (a refs-only Space renders
        // just its ref folders).
        if !view.projects.is_empty() {
            if !view.pinned_threads.is_empty() {
                height = height.saturating_add(section_gap);
            }
            height = height.saturating_add(row_height + row_gap);
        }
        // Folders — projects and ref groups interleaved — walk the SAME
        // display order the paint loop walks, or scroll math diverges from
        // the painted rows.
        for (folder_idx, folder) in view.display_order.iter().enumerate() {
            if folder_idx > 0 {
                height = height.saturating_add(group_gap);
            }
            height = height.saturating_add(row_height + row_gap);
            match folder {
                workspace_threads::SidebarFolder::Project(index) => {
                    if let Some(project) = view.projects.get(*index) {
                        let open = folder_open(
                            chevrons,
                            FolderKind::Project,
                            &project.id,
                            project.threads_collapsed,
                        );
                        height = height.saturating_add(
                            (project.threads.len().saturating_mul(row_height + row_gap) as f32
                                * open)
                                .round() as usize,
                        );
                    }
                }
                workspace_threads::SidebarFolder::RefGroup(index) => {
                    if let Some(group) = view.ref_groups.get(*index) {
                        let open = folder_open(
                            chevrons,
                            FolderKind::RefGroup,
                            &group.key,
                            group.collapsed,
                        );
                        height = height.saturating_add(
                            (group.threads.len().saturating_mul(row_height + row_gap) as f32
                                * open)
                                .round() as usize,
                        );
                    }
                }
            }
        }
        // "Shared with me": its label row, then a row per pane, after a
        // section gap when anything came before.
        if shared_rows > 0 {
            if height > 0 {
                height = height.saturating_add(section_gap);
            }
            height = height.saturating_add((shared_rows + 1).saturating_mul(row_height + row_gap));
        }
        height.saturating_sub(row_gap)
    }

    #[allow(clippy::too_many_arguments)]
    fn workspace_sidebar_scroll_height(
        chevrons: &FolderChevrons,
        view: &workspace_threads::WorkspaceThreadsView,
        shared_rows: usize,
        row_height: usize,
        row_gap: usize,
        section_gap: usize,
        group_gap: usize,
        viewport_height: usize,
    ) -> usize {
        let height = Self::workspace_sidebar_list_height(
            chevrons,
            view,
            shared_rows,
            row_height,
            row_gap,
            section_gap,
            group_gap,
        );
        if height > viewport_height {
            height.saturating_add(SIDEBAR_LIST_BOTTOM_PADDING)
        } else {
            height
        }
    }

    /// Apply the persisted view-options status filter. Must run everywhere a
    /// `WorkspaceThreadsView` feeds the sidebar (paint, scroll height, hit
    /// testing) or row math diverges from the painted rows.
    fn apply_workspace_thread_status_filter(
        &self,
        mut view: workspace_threads::WorkspaceThreadsView,
    ) -> workspace_threads::WorkspaceThreadsView {
        // This is the single choke point every sidebar consumer of the view
        // passes through (paint, scroll height, hit testing), so the runtime
        // collapse state of reference groups is stamped here — the three
        // row-math sites must all see the same collapsed flags.
        let space_id = self.workspace_sidebar_space_id().to_string();
        for group in &mut view.ref_groups {
            group.collapsed = self
                .thread_ref_groups_collapsed
                .contains(&format!("{space_id}::{}", group.key));
        }
        // Thread refs are a hand-curated list and are not filtered; the
        // filter below only touches the Space's own pinned/project rows.
        let hidden = crate::native_settings::workspace_sidebar_hidden_statuses()
            .iter()
            .filter_map(|key| workspace_threads::WorkspaceThreadWorkStatus::from_settings_key(key))
            .collect::<Vec<_>>();
        if !hidden.is_empty() {
            workspace_threads::filter_threads_view_by_status(&mut view, &hidden);
        }
        view
    }

    fn sidebar_thread_status_kind(
        &self,
        session: &workspace_threads::WorkspaceThreadView,
    ) -> Option<UiStatusKind> {
        match session.work_status {
            workspace_threads::WorkspaceThreadWorkStatus::Running => Some(UiStatusKind::Running),
            workspace_threads::WorkspaceThreadWorkStatus::NeedsAttention => {
                Some(UiStatusKind::NeedsAttention)
            }
            workspace_threads::WorkspaceThreadWorkStatus::FinishedUnseen => {
                Some(UiStatusKind::Done)
            }
            workspace_threads::WorkspaceThreadWorkStatus::Idle => None,
        }
    }

    /// Update this window's notification snapshot and return the expanding
    /// halo phase for a newly arrived notification. An initial snapshot does
    /// not pulse: notifications restored at startup are unread, but not new.
    fn workspace_notification_badge_pulse(
        &mut self,
        notifications: &[workspace_threads::ThreadWorkNotification],
    ) -> Option<f32> {
        let current = notifications
            .iter()
            .map(|notification| (notification.thread_id.clone(), notification.status))
            .collect::<HashMap<_, _>>();

        let has_new_notification = notification_snapshot_has_new_entry(
            self.workspace_notification_snapshot.as_ref(),
            &current,
        );
        let has_current_notifications = !current.is_empty();
        self.workspace_notification_snapshot = Some(current);

        if !has_current_notifications {
            self.workspace_notification_pulse_started_at = None;
            return None;
        }

        let now = Instant::now();
        if has_new_notification {
            self.workspace_notification_pulse_started_at = Some(now);
        }

        let started_at = self.workspace_notification_pulse_started_at?;
        let Some(phase) = notification_badge_pulse_phase(now.saturating_duration_since(started_at))
        else {
            self.workspace_notification_pulse_started_at = None;
            return None;
        };

        self.update_next_frame_time(Some(
            now + Duration::from_millis(NOTIFICATION_BADGE_FRAME_MS),
        ));
        Some(phase)
    }

    fn paint_workspace_notification_badge(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer: usize,
        action_x: usize,
        action_y: usize,
        action_size: usize,
        pulse_phase: Option<f32>,
    ) -> anyhow::Result<()> {
        let badge_size = self.ui_px(9).max(4);
        let badge_x = (action_x + action_size).saturating_sub(badge_size + self.ui_px(6));
        let badge_y = action_y + self.ui_px(6);

        if let Some(phase) = pulse_phase {
            // Keep the core visible and radiate a short, fading halo three
            // times. This attracts attention without a continuously blinking
            // control once the animation ends.
            let expansion = self.ui_f32(10.0) * phase;
            let halo_size = badge_size as f32 + expansion;
            let halo_x = badge_x as f32 + badge_size as f32 / 2.0 - halo_size / 2.0;
            let halo_y = badge_y as f32 + badge_size as f32 / 2.0 - halo_size / 2.0;
            self.fill_rounded_rectangle(
                layers,
                layer,
                euclid::rect(halo_x, halo_y, halo_size, halo_size),
                NOTIFICATION_BADGE_COLOR.mul_alpha(0.48 * (1.0 - phase)),
                halo_size / 2.0,
            )
            .context("sidebar notification badge pulse")?;
        }

        self.fill_rounded_rectangle(
            layers,
            layer,
            euclid::rect(
                badge_x as f32,
                badge_y as f32,
                badge_size as f32,
                badge_size as f32,
            ),
            NOTIFICATION_BADGE_COLOR,
            badge_size as f32 / 2.0,
        )
        .context("sidebar notification badge")
    }

    /// Connection health of a client-domain Space. While the Space is
    /// remote we keep a slow self-driven repaint tick going: a dead
    /// connection produces no output, so nothing else would repaint the
    /// indicator when the state flips. A local Space's link to the session
    /// host is checked by the status heartbeat instead (see
    /// `watch_space_connection_state`), so idle local windows stay idle.
    pub(crate) fn space_connection_state(&self, space_id: &str) -> SpaceConnectionState {
        let remote = workspace_threads::client_domain_for_space(space_id);
        let is_remote = remote.is_some();
        let Some(domain_name) = remote.or_else(crate::local_sessions::host_domain_name) else {
            return SpaceConnectionState::Connected;
        };
        self.domain_connection_state(&domain_name, is_remote)
    }

    /// Whether `space_id`'s server dropped and is being tried again on its
    /// own, between tries most of the time -- not one that looks connected
    /// and has only gone quiet.
    fn space_server_retrying(&self, space_id: &str) -> bool {
        workspace_threads::client_domain_for_space(space_id)
            .and_then(|name| Mux::get().get_domain_by_name(&name))
            .is_some_and(|domain| {
                domain
                    .downcast_ref::<wezterm_client::domain::ClientDomain>()
                    .is_some_and(|client| client.is_reconnecting())
            })
    }

    /// How the link to the server `domain_name` stands; `is_remote` for one
    /// on another machine, whose silence counts against it, and which the
    /// indicator showing it looks at again each second.
    pub(crate) fn domain_connection_state(
        &self,
        domain_name: &str,
        is_remote: bool,
    ) -> SpaceConnectionState {
        if is_remote {
            self.update_next_frame_time(Some(
                std::time::Instant::now() + std::time::Duration::from_secs(1),
            ));
        }
        self.domain_reach(domain_name, is_remote)
    }

    /// `domain_connection_state`, asking for no frame.
    pub(crate) fn domain_reach(&self, domain_name: &str, is_remote: bool) -> SpaceConnectionState {
        const SUSTAINED_LAG_MS: u64 = 5000;
        let mux = Mux::get();
        let Some(domain) = mux.get_domain_by_name(domain_name) else {
            // Not even registered: never connected in this session.
            return SpaceConnectionState::Disconnected;
        };
        if let Some(client) = domain.downcast_ref::<wezterm_client::domain::ClientDomain>() {
            // First connect (or manual re-attach) in progress: state() reads
            // Detached until finish_attach, which used to surface as
            // "Disconnected" with a Reconnect button while actively
            // connecting.
            if client.is_attaching() {
                return SpaceConnectionState::Connecting;
            }
            // The retry engine is between attempts. The backoff gap used to
            // read as Disconnected, so a VPN that wakes on the first packet
            // flashed a failure on every entry before attempt two succeeded.
            if client.is_attach_retrying() {
                return SpaceConnectionState::Connecting;
            }
            // The retry loop parked itself after two minutes of failures;
            // it waits for the sidebar Reconnect button.
            if client.is_reconnect_suspended() {
                return SpaceConnectionState::Disconnected;
            }
            // The reconnect loop knows immediately when the transport died
            // — pane tardiness below only trips after something is SENT on
            // a pane, so on its own it misses idle disconnects entirely.
            if client.is_reconnecting() {
                return SpaceConnectionState::Reconnecting;
            }
        }
        if domain.state() != mux::domain::DomainState::Attached {
            return SpaceConnectionState::Disconnected;
        }
        // Pane lag below measures the network to a server. One busy local
        // pane is not a broken link to the session host, and must not mark
        // every local Space as reconnecting.
        if !is_remote {
            return SpaceConnectionState::Connected;
        }
        // Attached but silent despite outstanding requests: transport not
        // (yet) declared dead. Panes report tardy after ~3s, which ordinary
        // latency spikes trip all the time; require a longer sustained
        // silence before alarming the user.
        let domain_id = domain.domain_id();
        if mux.iter_panes().iter().any(|pane| {
            pane.domain_id() == domain_id
                && crate::termwindow::render::pane::client_pane_lag_ms(pane.as_ref())
                    .map_or(false, |ms| ms >= SUSTAINED_LAG_MS)
        }) {
            SpaceConnectionState::Reconnecting
        } else {
            SpaceConnectionState::Connected
        }
    }

    /// Called from the status heartbeat: repaint only when the sidebar
    /// Space's connection state has changed since the last check. Remote
    /// Spaces already tick while their indicator is painted.
    pub(crate) fn watch_space_connection_state(&mut self) {
        let space_id = self.workspace_sidebar_space_id();
        if workspace_threads::client_domain_for_space(space_id).is_some() {
            return;
        }
        let state = self.space_connection_state(space_id);
        if self.watched_space_connection_state.replace(state) != Some(state) {
            if let Some(window) = self.window.as_ref() {
                window.invalidate();
            }
        }
    }

    /// `suppress_active` carries "a thread reference's workspace is on
    /// screen": the Space's own active-thread pointer is then stale for
    /// selection (ref activation never repoints it), so the Space's OWN rows
    /// must not paint as active next to the ref row that actually is. Ref
    /// rows always pass false. The suppression lives here, on the paint
    /// side, because `is_active` in the view data feeds other consumers —
    /// notably the status-filter exemption — that must keep seeing it.
    fn is_workspace_sidebar_thread_selected(
        &self,
        session: &workspace_threads::WorkspaceThreadView,
        suppress_active: bool,
    ) -> bool {
        if let Some(thread_id) = self.workspace_sidebar_pending_thread_selection.as_deref() {
            thread_id == session.id.as_str()
        } else {
            session.is_active && !suppress_active
        }
    }

    /// Whether something other than the Space's own threads is on screen, so
    /// that their active pointer is stale for `suppress_active` above.
    fn sidebar_own_active_is_stale(
        &self,
        view: &workspace_threads::WorkspaceThreadsView,
        active_workspace: &str,
    ) -> bool {
        view.ref_workspace_on_screen()
            || workspace_threads::is_share_view_workspace(active_workspace)
            || self.any_share_view_opening()
    }

    /// A thread at rest, in the status colours (`thread_marks`): the one
    /// the user is in, `current`, in green.
    fn sidebar_thread_dot_color(
        &self,
        session: &workspace_threads::WorkspaceThreadView,
        current: bool,
        foreground: LinearRgba,
    ) -> LinearRgba {
        if current {
            thread_marks::CURRENT_COLOR
        } else if !session.is_materialized {
            thread_marks::closed_color(foreground)
        } else if session.is_unread {
            thread_marks::unread_color(foreground)
        } else {
            thread_marks::OPEN_COLOR
        }
    }

    /// A thread's state in the status colours; the one the user is in,
    /// `current`, works in its own green.
    fn sidebar_thread_status_color(status: UiStatusKind, current: bool) -> LinearRgba {
        match status {
            UiStatusKind::Running if current => thread_marks::CURRENT_COLOR,
            UiStatusKind::Running => thread_marks::WORKING_COLOR,
            UiStatusKind::NeedsAttention => thread_marks::WAITING_COLOR,
            UiStatusKind::Done => thread_marks::FINISHED_COLOR,
        }
    }

    pub(crate) fn ui_px(&self, value: usize) -> usize {
        scale_ui_usize(value, self.dimensions.dpi)
    }

    pub(crate) fn ui_f32(&self, value: f32) -> f32 {
        scale_ui_f32(value, self.dimensions.dpi)
    }

    #[allow(clippy::too_many_arguments)]
    fn paint_sidebar_thread_status(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        session: &workspace_threads::WorkspaceThreadView,
        current: bool,
        x: usize,
        y: usize,
        row_height: usize,
        chrome: &UiPalette,
        foreground: LinearRgba,
    ) -> anyhow::Result<()> {
        let icon_y = y + ((row_height.saturating_sub(self.ui_px(SESSION_STATUS_ICON_SIZE))) / 2);
        if let Some(status) = self.sidebar_thread_status_kind(session) {
            // A thread one of whose programs stopped on an error is marked as
            // the Agents panel marks it: a red cross, not a wait.
            if status == UiStatusKind::NeedsAttention && thread_has_errored_agent(&session.id) {
                let size = self.ui_px(SESSION_STATUS_ICON_SIZE);
                return self.paint_ui_icon(
                    layers,
                    2,
                    SvgIcon::CircleX,
                    x,
                    centered_inner_start(y, row_height, size),
                    size,
                    chrome.danger,
                );
            }
            let status_size = if matches!(status, UiStatusKind::Running | UiStatusKind::Done) {
                self.ui_px(SESSION_STATUS_ACTIVE_ICON_SIZE)
            } else {
                self.ui_px(SESSION_STATUS_ICON_SIZE)
            };
            return self.paint_status_icon(
                layers,
                2,
                status,
                centered_inner_start(x, self.ui_px(SESSION_STATUS_ICON_SIZE), status_size),
                centered_inner_start(y, row_height, status_size),
                status_size,
                Self::sidebar_thread_status_color(status, current),
            );
        }

        let dot_offset = (self
            .ui_px(SESSION_STATUS_ICON_SIZE)
            .saturating_sub(self.ui_px(SESSION_STATUS_DOT_SIZE)))
            / 2;
        let dot_x = x + dot_offset;
        let dot_y = icon_y + dot_offset;
        self.fill_rounded_rectangle(
            layers,
            1,
            euclid::rect(
                dot_x as f32,
                dot_y as f32,
                self.ui_px(SESSION_STATUS_DOT_SIZE) as f32,
                self.ui_px(SESSION_STATUS_DOT_SIZE) as f32,
            ),
            self.sidebar_thread_dot_color(session, current, foreground),
            self.ui_px(SESSION_STATUS_DOT_SIZE) as f32 / 2.0,
        )
        .context("sidebar thread status dot")
    }

    /// What every thread row of one paint draws its icons and mark with.
    pub(crate) fn sidebar_thread_row_marks(&self) -> anyhow::Result<ThreadRowMarks> {
        let count_font = self
            .fonts
            .title_font_with_size_and_weight(
                crate::native_settings::sidebar_font_size(&crate::native_settings::load_shared())
                    * 0.55,
                700,
            )
            .context("sidebar thread count font")?;
        let count_metrics = RenderMetrics::with_font_metrics(&count_font.metrics());
        Ok(ThreadRowMarks {
            layout: crate::native_settings::sidebar_thread_icons(),
            status: crate::native_settings::sidebar_thread_status(),
            icons: thread_marks::icons_by_workspace(),
            workspaces: workspace_threads::thread_workspace_names(),
            terminal: crate::tab_icons::resolve_window_tab(),
            count_font,
            count_metrics,
        })
    }

    /// A thread row's program icons and the mark at its end. The icons go
    /// at `start_x`, or before the mark when they trail; the mark ends at
    /// `end_x`. With `show_end` false the row's buttons have the end, and
    /// neither the mark nor trailing icons are drawn. A `dimmed` row -- a
    /// ref whose machine is away -- has no mark: it cannot say what the
    /// thread is doing. `icons_at_end` is how present icons kept at the row's
    /// end are. Returns where the name starts and the right edge it must keep
    /// clear of.
    #[allow(clippy::too_many_arguments)]
    fn paint_sidebar_thread_marks(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        marks: &ThreadRowMarks,
        session: &workspace_threads::WorkspaceThreadView,
        start_x: usize,
        end_x: usize,
        y: usize,
        row_height: usize,
        surface: LinearRgba,
        show_end: bool,
        dimmed: bool,
        current: bool,
        icons_at_end: f32,
        chrome: &UiPalette,
        foreground: LinearRgba,
    ) -> anyhow::Result<(usize, usize)> {
        // In from the row's end rather than against the edge, and a little
        // further than the icons sit from its start, clear of the round end
        // of the highlight.
        let mark_x = end_x.saturating_sub(
            self.ui_px(SESSION_STATUS_ICON_SIZE)
                + self.ui_px(SIDEBAR_INSET)
                + self.ui_px(SESSION_STATUS_END_CLEARANCE),
        );
        let mut text_right = end_x;
        if show_end && !dimmed {
            self.paint_sidebar_thread_mark(
                layers,
                marks,
                session,
                current,
                mark_x,
                y,
                row_height,
                chrome,
                foreground,
            )?;
            text_right = mark_x;
        }
        let icons = marks.icons(&session.id, session.is_materialized);
        let diameter = (row_height as f32 * SIDEBAR_ICON_SCALE).round();
        let cy = y as f32 + row_height as f32 / 2.0;
        let gl_state = self.render_state.as_ref().unwrap();
        let ctx = DrawContext::new(gl_state, self.dimensions, &self.render_metrics);
        let style = thread_marks::IconStyle {
            surface,
            dark: chrome.is_dark(),
            count_font: &marks.count_font,
            count_metrics: &marks.count_metrics,
            count_color: chrome.secondary_text,
            opacity: if marks.layout == NativeThreadIcons::Trailing {
                icons_at_end
            } else {
                1.0
            },
        };
        if marks.layout == NativeThreadIcons::Trailing {
            if show_end {
                // Where a mark would be even when there is none, so a row
                // without one lines its icons up with the rest.
                let gap = self.ui_f32(SIDEBAR_ICON_GAP as f32 * 2.0);
                let left = thread_marks::draw_trailing(
                    &ctx,
                    layers,
                    icons,
                    mark_x as f32 - gap,
                    cy,
                    diameter,
                    &style,
                )?;
                text_right = left.max(0.0) as usize;
            }
            return Ok((start_x, text_right));
        }
        thread_marks::draw_slot(
            &ctx,
            layers,
            marks.layout,
            icons,
            start_x as f32,
            cy,
            diameter,
            &style,
        )?;
        let slot = thread_marks::slot_width(marks.layout, diameter).round() as usize;
        Ok((start_x + slot + self.ui_px(SIDEBAR_ICON_GAP), text_right))
    }

    /// The mark at a thread row's end, in the style Settings chose: the
    /// ring is the spinner and dots the sidebar always drew.
    #[allow(clippy::too_many_arguments)]
    fn paint_sidebar_thread_mark(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        marks: &ThreadRowMarks,
        session: &workspace_threads::WorkspaceThreadView,
        current: bool,
        x: usize,
        y: usize,
        row_height: usize,
        chrome: &UiPalette,
        foreground: LinearRgba,
    ) -> anyhow::Result<()> {
        if marks.status == NativeThreadStatus::Ring {
            return self.paint_sidebar_thread_status(
                layers,
                session,
                current,
                x,
                y,
                row_height,
                chrome,
                foreground,
            );
        }
        let (mark, color) = match self.sidebar_thread_status_kind(session) {
            Some(UiStatusKind::NeedsAttention) if thread_has_errored_agent(&session.id) => {
                (Mark::Failed, chrome.danger)
            }
            Some(status) => (
                match status {
                    UiStatusKind::Running => Mark::Working,
                    UiStatusKind::NeedsAttention => Mark::Waiting,
                    UiStatusKind::Done => Mark::Finished,
                },
                Self::sidebar_thread_status_color(status, current),
            ),
            None => (
                Mark::Still,
                self.sidebar_thread_dot_color(session, current, foreground),
            ),
        };
        let size = self.ui_px(SESSION_STATUS_ICON_SIZE) as f32;
        let top = (y as f32 + (row_height as f32 - size) / 2.0).round();
        self.paint_thread_mark(layers, marks.status, mark, x as f32, top, size, color)
            .context("sidebar thread mark")
    }

    /// A thread's or an agent's mark in `status`'s style, in the `size`
    /// square at `x`, `y`, moving while it works. The ring is the spinner
    /// and the status icons.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn paint_thread_mark(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        status: NativeThreadStatus,
        mark: Mark,
        x: f32,
        y: f32,
        size: f32,
        color: LinearRgba,
    ) -> anyhow::Result<()> {
        // A result waiting to be seen is a tick in every style: it is the
        // one state that asks to be looked at rather than waited on.
        // As large as the ring style draws it, the marks' own size being
        // too small for an outline icon.
        if mark == Mark::Finished {
            let tick = (size * 1.5).round();
            let inset = (tick - size) / 2.0;
            return self.paint_ui_icon(
                layers,
                2,
                SvgIcon::CircleCheck,
                (x - inset).max(0.0) as usize,
                (y - inset).max(0.0) as usize,
                tick as usize,
                color,
            );
        }
        if status == NativeThreadStatus::Ring {
            let icon = match mark {
                Mark::Working => {
                    let spinner = (size * 1.3).round();
                    let inset = (spinner - size) / 2.0;
                    return self.paint_spinning_ui_icon(
                        layers,
                        2,
                        SvgIcon::LoaderCircle,
                        (x - inset).max(0.0) as usize,
                        (y - inset).max(0.0) as usize,
                        spinner as usize,
                        color,
                    );
                }
                Mark::Waiting => SvgIcon::CircleAlert,
                Mark::Failed => SvgIcon::CircleX,
                Mark::Finished => SvgIcon::CircleCheck,
                Mark::Still => {
                    let dot = (size / 2.0).round();
                    let inset = (size - dot) / 2.0;
                    return self.fill_rounded_rectangle(
                        layers,
                        2,
                        euclid::rect(x + inset, y + inset, dot, dot),
                        color,
                        dot / 2.0,
                    );
                }
            };
            return self.paint_ui_icon(layers, 2, icon, x as usize, y as usize, size as usize, color);
        }
        let step = (mark == Mark::Working).then(|| {
            self.update_next_frame_time(Some(thread_marks::next_mark_step()));
            thread_marks::mark_step()
        });
        let gl_state = self.render_state.as_ref().unwrap();
        let ctx = DrawContext::new(gl_state, self.dimensions, &self.render_metrics);
        let draw = match status {
            NativeThreadStatus::Pulse => thread_marks::draw_pulse,
            NativeThreadStatus::Dots => thread_marks::draw_dots,
            _ => thread_marks::draw_pixels,
        };
        draw(&ctx, layers, mark, step, x, y, size, color)
    }

    /// Visual size of the expanded-sidebar toggle button; shares
    /// sidebar_toggle_size_px with the collapsed-state painter and the tab
    /// layout reservation so the control never changes size when the
    /// sidebar opens or closes.
    fn workspace_sidebar_toggle_visual_size(&self) -> usize {
        self.window_tab_chrome_params().sidebar_toggle_button_size()
    }

    pub(crate) fn workspace_sidebar_content_top(&self, panel_y: usize) -> usize {
        let tab_row_height = self.tab_bar_pixel_height().unwrap_or(0.0).ceil() as usize;
        platform_chrome::workspace_sidebar_content_top(
            panel_y,
            self.ui_px(SIDEBAR_INSET),
            tab_row_height,
            self.window_state,
            self.dimensions.dpi,
        )
    }

    /// How far below the panel's top edge the Space row sits.
    pub(crate) fn workspace_sidebar_space_row_offset(&self) -> usize {
        let mut offset = self.workspace_sidebar_content_top(0);
        if platform_chrome::workspace_sidebar_shows_toolbar(self.window_state) {
            offset += self.workspace_sidebar_toggle_visual_size() + self.ui_px(SIDEBAR_INSET);
        }
        offset
    }

    fn workspace_sidebar_layout(
        &self,
        rect: WorkspaceSidebarRect,
        ui_cell_height: usize,
        icon_size: usize,
    ) -> WorkspaceSidebarLayout {
        let panel_margin = 0usize;
        let panel_x = rect.x + panel_margin;
        let panel_y = rect.y + panel_margin;
        let panel_width = rect.width.saturating_sub(panel_margin * 2).max(1);
        let panel_height = rect.height.saturating_sub(panel_margin * 2).max(1);
        let settings_footer_height = self.ui_px(SIDEBAR_SETTINGS_FOOTER_HEIGHT).min(panel_height);
        let settings_footer_y = panel_y
            .saturating_add(panel_height)
            .saturating_sub(settings_footer_height);
        let content_bottom = (panel_y + panel_height.saturating_sub(self.ui_px(SIDEBAR_INSET)))
            .min(settings_footer_y.max(panel_y));
        let show_sidebar_toolbar =
            platform_chrome::workspace_sidebar_shows_toolbar(self.window_state);
        let sidebar_toolbar_uses_fullscreen_style =
            platform_chrome::workspace_sidebar_toolbar_uses_fullscreen_style(self.window_state);
        let row_height = (ui_cell_height.max(icon_size) + self.ui_px(SIDEBAR_INSET))
            .max(self.ui_px(SESSION_ROW_MIN_HEIGHT));
        let mut y = panel_y + self.workspace_sidebar_space_row_offset();
        let top_action_height = row_height
            .min(self.ui_px(TOP_ACTION_MAX_HEIGHT))
            .max(ui_cell_height + self.ui_px(SIDEBAR_INSET))
            + if sidebar_toolbar_uses_fullscreen_style {
                self.ui_px(WINDOW_TAB_FULLSCREEN_NEW_SESSION_EXTRA_HEIGHT)
            } else {
                0
            };
        let top_action_y_offset = if sidebar_toolbar_uses_fullscreen_style {
            self.ui_px(WINDOW_TAB_FULLSCREEN_NEW_SESSION_Y_OFFSET)
        } else {
            0
        };
        let space_menu_y = y;
        let space_menu_height = top_action_height + self.ui_px(6);
        y += space_menu_height + self.ui_px(SIDEBAR_INSET);
        // Connecting keeps the row (as a spinner) so the whole retry
        // sequence paints one stable row instead of flickering between
        // "row while disconnected" and "no row while an attempt runs".
        // A pill as tall as New Thread's under it, which it looks like. Also
        // while the server is being tried again on its own: to try now.
        let reconnect_state = self.space_connection_state(self.workspace_sidebar_space_id());
        let reconnect_row_height = if matches!(
            reconnect_state,
            SpaceConnectionState::Disconnected | SpaceConnectionState::Connecting
        ) || (reconnect_state == SpaceConnectionState::Reconnecting
            && self.space_server_retrying(self.workspace_sidebar_space_id()))
        {
            row_height
                .min(self.ui_px(TOP_ACTION_MAX_HEIGHT))
                .max(ui_cell_height + self.ui_px(SIDEBAR_INSET))
        } else {
            0
        };
        if reconnect_row_height > 0 {
            y += reconnect_row_height + self.ui_px(SIDEBAR_INSET);
        }
        let list_top =
            y + top_action_y_offset + top_action_height + self.ui_px(TOP_ACTION_BOTTOM_GAP);

        WorkspaceSidebarLayout {
            panel_x,
            panel_y,
            panel_width,
            panel_height,
            content_bottom,
            settings_footer_y,
            settings_footer_height,
            row_height,
            show_sidebar_toolbar,
            space_menu_y,
            space_menu_height,
            reconnect_row_height,
            top_action_y_offset,
            top_action_height,
            list_top,
        }
    }

    /// The row cell height the sidebar actually PAINTS with: the title font
    /// at the user's sidebar font size. Every consumer of
    /// `workspace_sidebar_layout` must use this — a plain `title_font()`
    /// here made scroll geometry and drag hot zones drift from the pixels
    /// whenever the sidebar font size was customized.
    fn workspace_sidebar_cell_height(&self) -> usize {
        self.fonts
            .title_font_with_size(crate::native_settings::sidebar_font_size(
                &crate::native_settings::load_shared(),
            ))
            .map(|font| {
                RenderMetrics::with_font_metrics(&font.metrics())
                    .cell_size
                    .height as usize
            })
            .unwrap_or(self.render_metrics.cell_size.height as usize)
    }

    /// The rows of the Space the sidebar is painted for. Painted for one
    /// this window is not in -- a card in the Library, a Space swiped to --
    /// nothing of the window's own workspace goes into them.
    pub(crate) fn workspace_sidebar_view(
        &self,
        active_workspace: &str,
        workspaces: &[String],
    ) -> workspace_threads::WorkspaceThreadsView {
        let space_id = self.workspace_sidebar_space_id();
        self.apply_workspace_thread_status_filter(workspace_threads::view_for_space(
            space_id,
            (space_id == self.active_space_id).then_some(active_workspace),
            workspaces,
            self.workspace_sidebar_show_archived,
        ))
    }

    pub fn workspace_sidebar_scroll_max(&self) -> f32 {
        let Some(rect) = self.workspace_sidebar_rect() else {
            return 0.0;
        };
        if !self.workspace_sidebar_is_presented() {
            return 0.0;
        }

        let ui_cell_height = self.workspace_sidebar_cell_height();
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
        let content_bottom = layout.content_bottom;
        let list_top = layout.list_top;
        let viewport_height = content_bottom.saturating_sub(list_top);
        if viewport_height == 0 {
            return 0.0;
        }

        let mux = Mux::get();
        // Use THIS window's own workspace, not the global active one: with
        // multiple windows open, a non-focused window must still highlight the
        // thread it is actually showing.
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let workspaces = mux.iter_workspaces();
        let view = self.workspace_sidebar_view(&active_workspace, &workspaces);
        let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
        let total_height = Self::workspace_sidebar_scroll_height(
            &self.folder_chevrons,
            &view,
            self.shared_with_us_rows(),
            layout.row_height,
            row_gap,
            self.ui_px(WORKSPACE_SECTION_LABEL_GAP),
            self.ui_px(WORKSPACE_GROUP_EXTRA_GAP),
            viewport_height,
        );
        total_height.saturating_sub(viewport_height) as f32
    }

    /// The vertical extent of the scrollable thread list itself — between
    /// the toolbar above and the footer below. This is the area row drags
    /// hit-test and autoscroll against; the panel background also covers
    /// the header strip and footer, so it must not be used for that.
    pub(crate) fn workspace_sidebar_list_viewport(&self) -> Option<(isize, isize)> {
        let rect = self.workspace_sidebar_rect()?;
        if !self.workspace_sidebar_is_presented() {
            return None;
        }
        let ui_cell_height = self.workspace_sidebar_cell_height();
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
        if layout.content_bottom <= layout.list_top {
            return None;
        }
        Some((layout.list_top as isize, layout.content_bottom as isize))
    }

    pub fn workspace_sidebar_scroll_geometry(&self) -> Option<WorkspaceSidebarScrollGeometry> {
        let rect = self.workspace_sidebar_rect()?;
        if !self.workspace_sidebar_is_presented() {
            return None;
        }

        let ui_cell_height = self.workspace_sidebar_cell_height();
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
        let content_bottom = layout.content_bottom;
        let list_top = layout.list_top;
        let viewport_height = content_bottom.saturating_sub(list_top);
        if viewport_height == 0 {
            return None;
        }

        let mux = Mux::get();
        // Use THIS window's own workspace, not the global active one: with
        // multiple windows open, a non-focused window must still highlight the
        // thread it is actually showing.
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let workspaces = mux.iter_workspaces();
        let view = self.workspace_sidebar_view(&active_workspace, &workspaces);
        let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
        let total_height = Self::workspace_sidebar_scroll_height(
            &self.folder_chevrons,
            &view,
            self.shared_with_us_rows(),
            layout.row_height,
            row_gap,
            self.ui_px(WORKSPACE_SECTION_LABEL_GAP),
            self.ui_px(WORKSPACE_GROUP_EXTRA_GAP),
            viewport_height,
        );
        let max_scroll = total_height.saturating_sub(viewport_height) as f32;
        if max_scroll <= 0.0 || total_height == 0 {
            return None;
        }

        let track_width = 4usize;
        let track_height = viewport_height.max(1);
        let thumb_height = ((viewport_height as f32 / total_height as f32) * track_height as f32)
            .clamp(28.0, track_height as f32);
        let travel = (track_height as f32 - thumb_height).max(1.0);
        let scroll_offset = self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
        let thumb_y = list_top as f32 + (scroll_offset / max_scroll) * travel;
        let track_x = layout
            .panel_x
            .saturating_add(layout.panel_width)
            .saturating_sub(self.ui_px(SIDEBAR_INSET) / 2 + track_width);

        Some(WorkspaceSidebarScrollGeometry {
            track_x,
            track_y: list_top,
            track_width,
            track_height,
            thumb_y,
            thumb_height,
            max_scroll,
        })
    }

    /// The "Disconnected — Reconnect" row under the Space menu. Painted
    /// twice per frame like the rest of the header: once in the normal
    /// header pass, and once in the post-list header repaint that covers
    /// scrolled content (which would otherwise mask it — everything in the
    /// first pass sits below the header scroll mask).
    #[allow(clippy::too_many_arguments)]
    fn paint_space_reconnect_row(
        &mut self,
        layers: &mut TripleLayerQuadAllocator,
        layer: usize,
        row_x: usize,
        y: usize,
        row_width: usize,
        row_height: usize,
        ui_font: &Rc<LoadedFont>,
        ui_metrics: RenderMetrics,
        ui_cell_height: usize,
        register_ui_item: bool,
    ) -> anyhow::Result<()> {
        // The domain-level retry flag covers every attach entry point; the
        // local set still bridges the click-to-spawn gap for the button.
        let reconnect_in_flight = self.space_connection_state(self.workspace_sidebar_space_id())
            == SpaceConnectionState::Connecting
            || crate::local_sessions::connection_domain_for_space(self.workspace_sidebar_space_id())
                .map_or(false, |name| {
                    self.space_reconnects_in_flight.contains(&name)
                });
        let hovered =
            !reconnect_in_flight && self.is_pointer_over_ui_rect(row_x, y, row_width, row_height);
        // New Thread's pill, the warning colour only in its icon and words.
        self.paint_sidebar_action_button(
            layers,
            layer,
            euclid::rect(row_x as f32, y as f32, row_width as f32, row_height as f32),
            self.chrome(),
            hovered,
            false,
        )
        .context("sidebar reconnect row")?;
        let reconnect_label = if reconnect_in_flight {
            crate::i18n::tr("sidebar-connecting")
        } else {
            crate::i18n::tr("sidebar-reconnect")
        };
        let row_icon_size = (ui_cell_height + self.ui_px(12))
            .clamp(self.ui_px(30), self.ui_px(36))
            .min(self.ui_px(32))
            .min(row_height.saturating_sub(14));
        let gap = self.ui_px(SIDEBAR_ICON_GAP) + 4;
        let row_text_max = row_width
            .saturating_sub(row_icon_size + gap + self.ui_px(SIDEBAR_INSET) * 2);
        let row_label = self
            .ellipsize_ui_text(ui_font, &reconnect_label, row_text_max)?
            .into_owned();
        let row_text_width = self
            .sidebar_text_width(ui_font, &row_label)?
            .ceil()
            .max(0.0) as usize;
        // Centred, as New Thread's are.
        let row_icon_x =
            row_x + row_width.saturating_sub(row_icon_size + gap + row_text_width) / 2;
        let row_icon_y = y + ((row_height.saturating_sub(row_icon_size)) / 2);
        if reconnect_in_flight {
            // The spinning painter also schedules the next repaint; the
            // static one would freeze the loader on frame zero.
            self.paint_spinning_ui_icon(
                layers,
                2,
                SvgIcon::LoaderCircle,
                row_icon_x,
                row_icon_y,
                row_icon_size,
                SPACE_DISCONNECTED_COLOR,
            )?;
        } else {
            self.paint_sidebar_icon(
                layers,
                SvgIcon::RotateCcw,
                row_icon_x,
                row_icon_y,
                row_icon_size,
                SPACE_DISCONNECTED_COLOR,
            )?;
        }
        let row_text_x = row_icon_x + row_icon_size + gap;
        self.paint_sidebar_text(
            layers,
            ui_font,
            ui_metrics,
            &row_label,
            row_text_x,
            y + ((row_height.saturating_sub(ui_cell_height)) / 2),
            row_text_width,
            SPACE_DISCONNECTED_COLOR,
        )?;
        if register_ui_item && !reconnect_in_flight {
            self.ui_items.push(UIItem {
                x: row_x,
                y,
                width: row_width,
                height: row_height,
                item_type: UIItemType::SpaceReconnect,
            });
        }
        Ok(())
    }

    pub fn paint_workspace_sidebar(
        &mut self,
        layers: &mut TripleLayerQuadAllocator,
    ) -> anyhow::Result<()> {
        // Clearing here is what keeps the recording honest: every exit below
        // this point either reached the row loop and recorded a real span, or
        // left this `None`. It can never describe an earlier paint.
        self.workspace_sidebar_list_quads = None;
        // The Library takes the sidebar's place, wherever it is painted.
        if self.library_presented() && !self.library_painting_sidebar() {
            return self.paint_library(layers);
        }
        let rect = match self.workspace_sidebar_rect() {
            Some(rect) => rect,
            None => return Ok(()),
        };

        let chrome = self.sidebar_chrome();
        let foreground = chrome.text;
        let sidebar_bg = self.sidebar_surface(chrome.workspace_sidebar_bg);
        let see_through = self.chrome_see_through();
        let sidebar_separator = chrome.separator;
        let selected_bg = chrome.sidebar_row_active_bg;
        let selected_border = chrome.sidebar_row_active_border;
        let active_fg = chrome.text;
        let muted_fg = chrome.secondary_text;
        let ui_font = self
            .fonts
            .title_font_with_size(crate::native_settings::sidebar_font_size(
                &crate::native_settings::load_shared(),
            ))
            .context("sidebar ui font")?;
        let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
        let row_marks = self.sidebar_thread_row_marks()?;
        // A row a drag has is painted where the pointer is, then on its way
        // into place, so it is not left here as well. Its hit rect stays:
        // the drop is aimed by those, not by where rows are drawn.
        let carried = self
            .sidebar_row_drag
            .as_ref()
            .filter(|drag| drag.active)
            .map(|drag| &drag.kind)
            .or(self.sidebar_row_landing.as_ref().map(|landing| &landing.what))
            .cloned();
        let thread_carried = |id: &str| {
            matches!(&carried, Some(SidebarRowKind::Thread { thread_id, .. }) if thread_id == id)
        };
        let folder_carried = |id: &str| {
            matches!(
                &carried,
                Some(SidebarRowKind::Project(key) | SidebarRowKind::RefGroup(key)) if key == id
            )
        };
        let ui_cell_height = ui_metrics.cell_size.height as usize;
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
        let panel_x = layout.panel_x;
        let panel_y = layout.panel_y;
        let panel_width = layout.panel_width;
        let panel_height = layout.panel_height;
        let content_bottom = layout.content_bottom;
        let settings_footer_y = layout.settings_footer_y;
        let settings_footer_height = layout.settings_footer_height;
        // Painted for a Library card: the card is the ground, rounded, and
        // the list is cut where the card ends rather than covered.
        let card = self.library_card_rect().is_some();

        if rect.y > 0 {
            // See-through, `paint_window_borders` paints this band, and a
            // second coat would show.
            if !see_through && !card {
                self.filled_rectangle(
                    layers,
                    0,
                    euclid::rect(rect.x as f32, 0.0, rect.width as f32, rect.y as f32),
                    sidebar_bg,
                )
                .context("sidebar header background")?;
            }
            self.ui_items.push(UIItem {
                x: rect.x,
                y: 0,
                width: rect.width,
                height: rect.y,
                item_type: UIItemType::WorkspaceSidebarBackground,
            });
        }
        if !card {
            self.filled_rectangle(
                layers,
                0,
                euclid::rect(
                    panel_x as f32,
                    panel_y as f32,
                    panel_width as f32,
                    panel_height as f32,
                ),
                sidebar_bg,
            )
            .context("sidebar background")?;
        }
        self.ui_items.push(UIItem {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
            item_type: UIItemType::WorkspaceSidebarBackground,
        });

        let session_row_height = layout.row_height;
        let item_x = panel_x + self.ui_px(SIDEBAR_INSET);
        let item_width = panel_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2 + 1);
        self.ui_items.push(UIItem {
            x: rect
                .x
                .saturating_add(rect.width)
                .saturating_sub(self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH) / 2),
            y: rect.y,
            width: self.ui_px(SIDEBAR_RESIZE_HANDLE_WIDTH),
            height: rect.height,
            item_type: UIItemType::WorkspaceSidebarResize,
        });

        if !self.workspace_sidebar_is_presented() {
            return Ok(());
        }

        let mux = Mux::get();
        // Use THIS window's own workspace, not the global active one: with
        // multiple windows open, a non-focused window must still highlight the
        // thread it is actually showing.
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let workspaces = mux.iter_workspaces();
        let view = self.workspace_sidebar_view(&active_workspace, &workspaces);
        // A ref row is showing its workspace, or a row of "Shared with me"
        // is: the Space's own rows must not paint a second active highlight
        // from their stale pointer.
        let suppress_own_active = self.sidebar_own_active_is_stale(&view, &active_workspace);

        let header_icon_size = icon_size.min(self.ui_px(32));
        let button_size = (header_icon_size + self.ui_px(8)).clamp(self.ui_px(32), self.ui_px(40));
        let header_y = self.workspace_sidebar_content_top(panel_y);
        let show_sidebar_toolbar = layout.show_sidebar_toolbar;
        let sidebar_toolbar_uses_fullscreen_style =
            platform_chrome::workspace_sidebar_toolbar_uses_fullscreen_style(self.window_state);
        let sidebar_toggle_size = self.workspace_sidebar_toggle_visual_size();
        // Mirror the collapsed-state toggle exactly: same left inset from
        // the window content edge (independent of the sidebar width — the
        // tab-bar path's leading_action_start_pixels returns 0 while the
        // sidebar is open, so it must not be used here) and the same
        // centering within the tab bar's content row.
        let border = self.get_os_border();
        let sidebar_toggle_x = if sidebar_toolbar_uses_fullscreen_style {
            panel_x + self.ui_px(WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_X)
        } else {
            border.left.get() as usize
                + platform_chrome::sidebar_toggle_left_inset_px(
                    self.dimensions.dpi,
                    self.window_state,
                )
        };
        let top_fancy_row = self.tab_bar_pixel_height().ok().map(|h| h.ceil() as usize);
        let sidebar_toggle_y = if sidebar_toolbar_uses_fullscreen_style {
            header_y + self.ui_px(WINDOW_TAB_FULLSCREEN_SIDEBAR_BUTTON_Y_OFFSET)
        } else if let Some(row_h) = top_fancy_row {
            // Same formula as the collapsed painter: centered within the
            // content row (full row minus the top spacer).
            let spacer = self.ui_px(WINDOW_TAB_TOP_SPACER).min(row_h);
            border.top.get() as usize
                + spacer
                + (row_h - spacer).saturating_sub(sidebar_toggle_size) / 2
        } else {
            header_y
        };
        let sidebar_toggle_icon_size = self
            .ui_px(platform_chrome::workspace_sidebar_toolbar_icon_size(
                self.window_state,
            ))
            .min(sidebar_toggle_size.saturating_sub(2));
        // A Library card has no toolbar either: set apart, as the footer is.
        let card_toolbar_start = layers.heap_mark().filter(|_| card);
        if show_sidebar_toolbar {
            let toggle_hovered = self.is_pointer_over_ui_rect(
                sidebar_toggle_x,
                sidebar_toggle_y,
                sidebar_toggle_size,
                sidebar_toggle_size,
            );
            if toggle_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    1,
                    euclid::rect(
                        sidebar_toggle_x as f32,
                        sidebar_toggle_y as f32,
                        sidebar_toggle_size as f32,
                        sidebar_toggle_size as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS),
                )
                .context("sidebar toolbar toggle button")?;
            }
            self.ui_items.push(UIItem {
                x: sidebar_toggle_x,
                y: sidebar_toggle_y,
                width: sidebar_toggle_size,
                height: sidebar_toggle_size,
                item_type: UIItemType::WorkspaceSidebarToggle,
            });
            self.paint_sidebar_icon(
                layers,
                self.workspace_sidebar_toggle_icon(),
                sidebar_toggle_x
                    + ((sidebar_toggle_size.saturating_sub(sidebar_toggle_icon_size)) / 2),
                sidebar_toggle_y
                    + ((sidebar_toggle_size.saturating_sub(sidebar_toggle_icon_size)) / 2),
                sidebar_toggle_icon_size,
                if toggle_hovered { foreground } else { muted_fg },
            )?;
        }
        if let (Some(start), Some(end)) = (card_toolbar_start, layers.heap_mark()) {
            self.mark_library_card_toolbar(start, end);
        }
        // One diameter for every round sidebar action button. It follows the
        // notification button, which is pinned to the New Thread row's height
        // because the two sit side by side -- so tying the section buttons to
        // the same number is what keeps the whole right-hand column one size.
        // Still clamped to its own row: a section button must not outgrow the
        // row it sits in.
        let section_button_size = layout
            .top_action_height
            .max(button_size)
            .min(session_row_height.saturating_sub(8));
        let active_project_id = view
            .projects
            .iter()
            .find(|project| project.is_active)
            .map(|project| project.id.clone());
        let top_action_y_offset = layout.top_action_y_offset;
        let top_action_total_width = item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2);
        let top_action_gap = self.ui_px(SIDEBAR_ICON_GAP) + 4;
        let top_action_height = layout.top_action_height;
        let space_menu_x = item_x + self.ui_px(SIDEBAR_INSET);
        let space_menu_y = layout.space_menu_y;
        let mut push_header_blank = |x: usize, y: usize, width: usize, height: usize| {
            if width > 0 && height > 0 {
                self.ui_items.push(UIItem {
                    x,
                    y,
                    width,
                    height,
                    item_type: UIItemType::WorkspaceSidebarHeaderBlank,
                });
            }
        };
        if space_menu_y > panel_y {
            if show_sidebar_toolbar {
                let header_bottom = space_menu_y;
                let toggle_bottom = sidebar_toggle_y.saturating_add(sidebar_toggle_size);
                push_header_blank(
                    panel_x,
                    panel_y,
                    panel_width,
                    sidebar_toggle_y.saturating_sub(panel_y),
                );
                push_header_blank(
                    panel_x,
                    toggle_bottom,
                    panel_width,
                    header_bottom.saturating_sub(toggle_bottom),
                );
                let toggle_band_y = sidebar_toggle_y.max(panel_y);
                let toggle_band_bottom = toggle_bottom.min(header_bottom);
                let toggle_band_height = toggle_band_bottom.saturating_sub(toggle_band_y);
                push_header_blank(
                    panel_x,
                    toggle_band_y,
                    sidebar_toggle_x.saturating_sub(panel_x),
                    toggle_band_height,
                );
                push_header_blank(
                    sidebar_toggle_x.saturating_add(sidebar_toggle_size),
                    toggle_band_y,
                    panel_x
                        .saturating_add(panel_width)
                        .saturating_sub(sidebar_toggle_x.saturating_add(sidebar_toggle_size)),
                    toggle_band_height,
                );
            } else {
                push_header_blank(panel_x, panel_y, panel_width, space_menu_y - panel_y);
            }
        }
        let space_menu_width = top_action_total_width;
        let space_menu_height = layout.space_menu_height;
        let space_menu_hovered = self.is_pointer_over_ui_rect(
            space_menu_x,
            space_menu_y,
            space_menu_width,
            space_menu_height,
        );
        if space_menu_hovered {
            self.fill_rounded_rectangle(
                layers,
                1,
                euclid::rect(
                    space_menu_x as f32,
                    space_menu_y as f32,
                    space_menu_width as f32,
                    space_menu_height as f32,
                ),
                chrome.sidebar_button_hover_bg,
                self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
            )
            .context("sidebar space menu button")?;
        }
        self.ui_items.push(UIItem {
            x: space_menu_x,
            y: space_menu_y,
            width: space_menu_width,
            height: space_menu_height,
            item_type: UIItemType::SpaceMenu,
        });
        let space_icon_size = header_icon_size.min(space_menu_height.saturating_sub(14));
        let space_icon_x = space_menu_x + self.ui_px(SIDEBAR_INSET);
        let space_icon_y = space_menu_y + ((space_menu_height.saturating_sub(space_icon_size)) / 2);
        let space_action_icon_size = space_icon_size.min(22);
        let space_action_icon_x = space_menu_x
            .saturating_add(space_menu_width)
            .saturating_sub(self.ui_px(SIDEBAR_INSET) + space_action_icon_size);
        let space_action_icon_y =
            space_menu_y + ((space_menu_height.saturating_sub(space_action_icon_size)) / 2);
        let space_text_right = space_menu_x
            .saturating_add(space_menu_width)
            .saturating_sub(self.ui_px(SIDEBAR_INSET) + space_action_icon_size + top_action_gap);
        let space_text_x = space_icon_x + space_icon_size + top_action_gap;
        let space_name =
            crate::workspace_threads::active_space_name(self.workspace_sidebar_space_id())
                .unwrap_or_else(|| crate::i18n::tr("sidebar-default-space"));
        let space_title = self.sidebar_space_title(self.workspace_sidebar_space_id(), &space_name);
        let space_label = self.ellipsize_ui_text(
            &ui_font,
            &space_title,
            space_text_right.saturating_sub(space_text_x),
        )?;
        let connection_state = self.space_connection_state(self.workspace_sidebar_space_id());
        // Swap the icon in place rather than adding text: the indicator
        // must not change the row's width or height, so transient lag
        // spikes can't make the sidebar layout jump.
        let (space_icon, space_icon_color) = match connection_state {
            SpaceConnectionState::Reconnecting | SpaceConnectionState::Disconnected => {
                (SvgIcon::CircleAlert, SPACE_DISCONNECTED_COLOR)
            }
            SpaceConnectionState::Connecting => (
                SvgIcon::LoaderCircle,
                if space_menu_hovered {
                    foreground
                } else {
                    muted_fg
                },
            ),
            SpaceConnectionState::Connected => (
                SvgIcon::Layers,
                if space_menu_hovered {
                    foreground
                } else {
                    muted_fg
                },
            ),
        };
        if connection_state == SpaceConnectionState::Connecting {
            self.paint_spinning_ui_icon(
                layers,
                2,
                space_icon,
                space_icon_x,
                space_icon_y,
                space_icon_size,
                space_icon_color,
            )?;
        } else {
            self.paint_sidebar_icon(
                layers,
                space_icon,
                space_icon_x,
                space_icon_y,
                space_icon_size,
                space_icon_color,
            )?;
        }
        self.paint_sidebar_text(
            layers,
            &ui_font,
            ui_metrics,
            space_label.as_ref(),
            space_text_x,
            space_menu_y + ((space_menu_height.saturating_sub(ui_cell_height)) / 2),
            space_text_right.saturating_sub(space_text_x),
            foreground,
        )?;
        self.paint_sidebar_icon(
            layers,
            SvgIcon::Ellipsis,
            space_action_icon_x,
            space_action_icon_y,
            space_action_icon_size,
            if space_menu_hovered {
                foreground
            } else {
                muted_fg
            },
        )?;
        let mut y = space_menu_y + space_menu_height + self.ui_px(SIDEBAR_INSET);
        if layout.reconnect_row_height > 0 {
            self.paint_space_reconnect_row(
                layers,
                1,
                item_x + self.ui_px(SIDEBAR_INSET),
                y,
                item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2),
                layout.reconnect_row_height,
                &ui_font,
                ui_metrics,
                ui_cell_height,
                true,
            )?;
            y += layout.reconnect_row_height + self.ui_px(SIDEBAR_INSET);
        }
        let top_action_x = item_x + self.ui_px(SIDEBAR_INSET);
        let top_action_y = y + top_action_y_offset;
        let notification_action_size = top_action_height;
        let notification_action_x = top_action_x
            .saturating_add(top_action_total_width)
            .saturating_sub(notification_action_size);
        let notification_action_y = top_action_y;
        let top_action_width =
            top_action_total_width.saturating_sub(notification_action_size + top_action_gap);
        let top_action_hovered = active_project_id.is_some()
            && self.is_pointer_over_ui_rect(
                top_action_x,
                top_action_y,
                top_action_width,
                top_action_height,
            );
        let notification_action_hovered = self.is_pointer_over_ui_rect(
            notification_action_x,
            notification_action_y,
            notification_action_size,
            notification_action_size,
        );
        self.paint_sidebar_action_button(
            layers,
            1,
            euclid::rect(
                top_action_x as f32,
                top_action_y as f32,
                top_action_width as f32,
                top_action_height as f32,
            ),
            chrome,
            top_action_hovered,
            false,
        )
        .context("sidebar add thread button")?;
        self.paint_sidebar_action_button(
            layers,
            1,
            euclid::rect(
                notification_action_x as f32,
                notification_action_y as f32,
                notification_action_size as f32,
                notification_action_size as f32,
            ),
            chrome,
            notification_action_hovered,
            false,
        )
        .context("sidebar notifications button")?;
        if let Some(project_id) = active_project_id.clone() {
            self.ui_items.push(UIItem {
                x: top_action_x,
                y: top_action_y,
                width: top_action_width,
                height: top_action_height,
                item_type: UIItemType::WorkspaceThreadNew(project_id),
            });
        }
        self.ui_items.push(UIItem {
            x: notification_action_x,
            y: notification_action_y,
            width: notification_action_size,
            height: notification_action_size,
            item_type: UIItemType::WorkspaceSidebarNotifications,
        });
        let top_action_icon_size = header_icon_size.min(top_action_height.saturating_sub(14));
        let top_action_text_max_width = top_action_width
            .saturating_sub(top_action_icon_size + top_action_gap + self.ui_px(SIDEBAR_INSET) * 2);
        let top_action_label_text = crate::i18n::tr("sidebar-new-thread");
        let top_action_label =
            self.ellipsize_ui_text(&ui_font, &top_action_label_text, top_action_text_max_width)?;
        let top_action_text_width = self
            .sidebar_text_width(&ui_font, top_action_label.as_ref())?
            .ceil()
            .max(0.0) as usize;
        let top_action_content_width =
            top_action_icon_size + top_action_gap + top_action_text_width;
        let top_action_content_x =
            top_action_x + top_action_width.saturating_sub(top_action_content_width) / 2;
        let top_action_icon_x = top_action_content_x;
        let top_action_icon_y =
            top_action_y + ((top_action_height.saturating_sub(top_action_icon_size)) / 2);
        let top_action_text_x = top_action_icon_x + top_action_icon_size + top_action_gap;
        let top_action_text_y =
            top_action_y + ((top_action_height.saturating_sub(ui_cell_height)) / 2);
        let top_action_fg = if active_project_id.is_some() {
            foreground
        } else {
            muted_fg
        };
        self.paint_sidebar_icon(
            layers,
            SvgIcon::SquarePen,
            top_action_icon_x,
            top_action_icon_y,
            top_action_icon_size,
            top_action_fg,
        )?;
        self.paint_sidebar_text(
            layers,
            &ui_font,
            ui_metrics,
            top_action_label.as_ref(),
            top_action_text_x,
            top_action_text_y,
            top_action_text_width,
            top_action_fg,
        )?;
        let notification_icon_size =
            top_action_icon_size.min(notification_action_size.saturating_sub(14));
        let notification_count = workspace_threads::pending_work_notification_count();
        let notifications = workspace_threads::pending_work_notifications();
        // Treat either snapshot as authoritative for this frame if work state
        // changes between the two short store reads.
        let has_notifications = notification_count > 0 || !notifications.is_empty();
        let notification_badge_pulse = self.workspace_notification_badge_pulse(&notifications);
        self.paint_sidebar_icon(
            layers,
            SvgIcon::Bell,
            notification_action_x
                + ((notification_action_size.saturating_sub(notification_icon_size)) / 2),
            notification_action_y
                + ((notification_action_size.saturating_sub(notification_icon_size)) / 2),
            notification_icon_size,
            if notification_action_hovered {
                foreground
            } else {
                muted_fg
            },
        )?;
        if has_notifications {
            self.paint_workspace_notification_badge(
                layers,
                2,
                notification_action_x,
                notification_action_y,
                notification_action_size,
                notification_badge_pulse,
            )
            .context("sidebar notification badge initial paint")?;
        }
        let list_top = layout.list_top;
        let row_gap = self.ui_px(SIDEBAR_ROW_GAP);
        // The live list only: a Library card or a Space swiped to is not the
        // list a row was taken out of, and shows its folders as they are.
        let rows_tracked = !card && self.workspace_sidebar_preview_space_id.is_none();
        let still_folders = FolderChevrons::default();
        let max_scroll = {
            let viewport_height = content_bottom.saturating_sub(list_top);
            let total_height = Self::workspace_sidebar_scroll_height(
                if rows_tracked {
                    &self.folder_chevrons
                } else {
                    &still_folders
                },
                &view,
                self.shared_with_us_rows(),
                session_row_height,
                row_gap,
                self.ui_px(WORKSPACE_SECTION_LABEL_GAP),
                self.ui_px(WORKSPACE_GROUP_EXTRA_GAP),
                viewport_height,
            );
            total_height.saturating_sub(viewport_height) as f32
        };
        if self.workspace_sidebar_preview_space_id.is_none() {
            self.advance_sidebar_jump_scroll(Instant::now());
        }
        let scroll_offset = self.workspace_sidebar_scroll_offset.clamp(0.0, max_scroll);
        if self.workspace_sidebar_preview_space_id.is_none() {
            // Writing the clamp back is what stops the sidebar staying scrolled
            // past the end after a list shrinks. It must not happen while
            // previewing a neighbouring Space: `max_scroll` then describes
            // *that* Space's extent, and a shorter one would drag the live
            // sidebar upward mid-gesture.
            self.workspace_sidebar_scroll_offset = scroll_offset;
        }
        let list_top_f = list_top as f32;
        let content_bottom_f = content_bottom as f32;
        let suppress_hover = carried.is_some()
            || self
                .current_mouse_event
                .as_ref()
                .is_some_and(|event| matches!(event.kind, WMEK::VertWheel(_) | WMEK::HorzWheel(_)));
        // Whether a row drawn from `top` shows, which a row moved aside may
        // when its place does not.
        let paints_at = |top: f32| {
            top + session_row_height as f32 > list_top_f && top < content_bottom_f
        };
        let mut virtual_y = 0usize;
        // Nothing glides while rows are moving for another reason.
        let rows_glide = rows_tracked
            && carried.is_none()
            && self.sidebar_make_way.is_idle()
            && !self.folder_chevrons.folding();
        if rows_tracked {
            let space = self.workspace_sidebar_space_id().to_string();
            self.sidebar_row_places.begin(&space, scroll_offset);
        }
        // The row of the thread this window shows, wherever it is, for the
        // pill that brings it back into sight.
        let mut current_row: Option<CurrentRow> = None;
        let thread_icon = |session: &workspace_threads::WorkspaceThreadView| {
            row_marks
                .icons(&session.id, session.is_materialized)
                .first()
                .cloned()
        };
        // A card in the Library and a Space swiped to are not the list the
        // numbers count down.
        let numbers = if card || self.workspace_sidebar_preview_space_id.is_some() {
            None
        } else {
            self.thread_number_rows(&view)?
        };
        // Everything from here until the end of the project loop scrolls with
        // `virtual_y`. A space-swipe slides exactly this stretch and leaves the
        // chrome painted before and after it standing.
        let list_quads_start = layers.heap_mark();

        if !view.pinned_threads.is_empty() {
            self.note_sidebar_row(
                PINNED_LABEL_KEY,
                "",
                virtual_y,
                virtual_y,
                0.0,
                rows_tracked,
                rows_glide,
            );
            let label_top = list_top_f + virtual_y as f32 - scroll_offset;
            let label_bottom = label_top + session_row_height as f32;
            let label_is_visible = label_bottom > list_top_f && label_top < content_bottom_f;
            if label_is_visible {
                let label_y = label_top.floor().max(0.0) as usize;
                let label_icon_size = header_icon_size.min(ui_cell_height).max(16);
                let label_icon_x = item_x + self.ui_px(SIDEBAR_INSET);
                let label_icon_y =
                    label_y + ((session_row_height.saturating_sub(label_icon_size)) / 2);
                let label_text_x = label_icon_x + label_icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::Pin,
                    label_icon_x,
                    label_icon_y,
                    label_icon_size,
                    muted_fg,
                )?;
                let section_label = crate::i18n::tr("sidebar-pinned");
                self.paint_sidebar_text(
                    layers,
                    &ui_font,
                    ui_metrics,
                    &section_label,
                    label_text_x,
                    label_y + ((session_row_height.saturating_sub(ui_cell_height)) / 2),
                    item_x
                        .saturating_add(item_width)
                        .saturating_sub(label_text_x + self.ui_px(SIDEBAR_INSET)),
                    muted_fg,
                )?;
            }
            virtual_y += session_row_height + row_gap;

            let pinned_x = item_x + self.ui_px(SIDEBAR_INSET);
            let pinned_width = item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2);
            let pinned_status_x = pinned_x + self.ui_px(SIDEBAR_INSET);
            for session in &view.pinned_threads {
                self.note_sidebar_row(
                    &session.id,
                    "",
                    virtual_y,
                    virtual_y,
                    0.0,
                    rows_tracked,
                    rows_glide,
                );
                let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                let row_bottom = row_top + session_row_height as f32;
                let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
                let y = (row_top + self.sidebar_make_way.shift_of(&session.id))
                    .floor()
                    .max(0.0) as usize;
                let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                let hit_bottom = row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                let hit_height = hit_bottom.saturating_sub(hit_y).max(1);
                if current_row.is_none()
                    && self.is_workspace_sidebar_thread_selected(session, suppress_own_active)
                {
                    current_row = Some(CurrentRow::new(virtual_y, None, thread_icon(session)));
                }

                if row_is_visible {
                    self.ui_items.push(UIItem {
                        x: pinned_x,
                        y: hit_y,
                        width: pinned_width,
                        height: hit_height,
                        item_type: UIItemType::WorkspaceThread(session.id.clone()),
                    });
                    let is_hovered = !suppress_hover
                        && self.is_pointer_over_ui_rect(
                            pinned_x,
                            y,
                            pinned_width,
                            session_row_height,
                        );
                    let is_renaming_session = self.is_renaming_sidebar_thread(&session.id);
                    let is_selected =
                        self.is_workspace_sidebar_thread_selected(session, suppress_own_active);
                    if is_selected {
                        let row_rect = euclid::rect(
                            pinned_x as f32,
                            y as f32,
                            pinned_width as f32,
                            session_row_height as f32,
                        );
                        self.paint_sidebar_selected_row(layers, row_rect, selected_bg, selected_border)
                            .context("sidebar selected pinned thread")?;
                    } else if is_hovered && !is_renaming_session {
                        self.fill_rounded_rectangle(
                            layers,
                            0,
                            euclid::rect(
                                pinned_x as f32,
                                y as f32,
                                pinned_width as f32,
                                session_row_height as f32,
                            ),
                            chrome.sidebar_row_hover_bg,
                            session_row_height as f32 / 2.0,
                        )
                        .context("sidebar hovered pinned thread")?;
                    }

                    let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                    let action_size = session_row_height.saturating_sub(8).clamp(
                        self.ui_px(SESSION_ACTION_MIN_SIZE),
                        self.ui_px(SESSION_ACTION_MAX_SIZE),
                    );
                    let delete_x = pinned_x
                        .saturating_add(pinned_width)
                        .saturating_sub(self.ui_px(SIDEBAR_INSET) + action_size);
                    let pin_x = delete_x.saturating_sub(action_size + 4);
                    let action_y = y + ((session_row_height.saturating_sub(action_size)) / 2);
                    let row_hovered = is_hovered && !is_renaming_session;
                    let number = numbers.as_ref().and_then(|numbers| numbers.of(&session.id));
                    // In a Library card a row takes its click whole
                    // (`push_library_card_items`): no buttons on it there.
                    // Nor under a number, where a click would find them
                    // unseen.
                    let shows_actions =
                        row_hovered && self.library_card_rect().is_none() && number.is_none();
                    let surface = if is_selected {
                        over(selected_bg, sidebar_bg)
                    } else if row_hovered {
                        over(chrome.sidebar_row_hover_bg, sidebar_bg)
                    } else {
                        sidebar_bg
                    };
                    let row_end = pinned_x
                        .saturating_add(pinned_width)
                        .saturating_sub(self.ui_px(SIDEBAR_INSET));
                    let (pinned_text_x, marks_right) = self.paint_sidebar_thread_marks(
                        layers,
                        &row_marks,
                        session,
                        pinned_status_x,
                        row_end,
                        y,
                        session_row_height,
                        surface,
                        !shows_actions,
                        false,
                        is_selected,
                        number.map_or(1.0, |number| number.icons_left()),
                        &chrome,
                        foreground,
                    )?;
                    let text_right = if shows_actions { pin_x } else { marks_right };
                    let title = self.sidebar_thread_title(&session.id, &session.name);
                    self.paint_thread_row_name(
                        layers,
                        &ui_font,
                        ui_metrics,
                        &title,
                        pinned_text_x,
                        text_y,
                        text_right.saturating_sub(pinned_text_x + self.ui_px(SIDEBAR_INSET)),
                        if is_selected { active_fg } else { foreground },
                        number,
                        row_end,
                        y,
                        session_row_height,
                        is_selected,
                        &chrome,
                    )?;

                    if shows_actions {
                        let affordances = vec![
                            (
                                pin_x,
                                UIItemType::WorkspaceThreadPin(session.id.clone()),
                                SvgIcon::PinOff,
                                "sidebar unpin pinned thread button",
                            ),
                            (
                                delete_x,
                                UIItemType::WorkspaceThreadDelete(session.id.clone()),
                                SvgIcon::Trash2,
                                "sidebar delete pinned thread button",
                            ),
                        ];
                        for (x, item_type, icon, _context_name) in affordances {
                            let hovered =
                                self.is_pointer_over_ui_rect(x, action_y, action_size, action_size);
                            self.ui_items.push(UIItem {
                                x,
                                y: action_y,
                                width: action_size,
                                height: action_size,
                                item_type,
                            });
                            let action_icon_size = action_size
                                .saturating_sub(self.ui_px(SESSION_ACTION_ICON_INSET))
                                .max(header_icon_size);
                            self.paint_sidebar_icon(
                                layers,
                                icon,
                                x + ((action_size.saturating_sub(action_icon_size)) / 2),
                                action_y + ((action_size.saturating_sub(action_icon_size)) / 2),
                                action_icon_size,
                                if hovered {
                                    foreground
                                } else {
                                    muted_fg.mul_alpha(0.88)
                                },
                            )?;
                        }
                    }
                }

                virtual_y += session_row_height + row_gap;
            }
        }

        if !view.projects.is_empty() {
            if !view.pinned_threads.is_empty() {
                virtual_y += self.ui_px(WORKSPACE_SECTION_LABEL_GAP);
            }
            self.note_sidebar_row(
                WORKSPACES_LABEL_KEY,
                "",
                virtual_y,
                virtual_y,
                0.0,
                rows_tracked,
                rows_glide,
            );
            let label_top = list_top_f + virtual_y as f32 - scroll_offset;
            let label_bottom = label_top + session_row_height as f32;
            let label_is_visible = label_bottom > list_top_f && label_top < content_bottom_f;
            if label_is_visible {
                let label_y = (label_top + self.sidebar_make_way.shift_of(WORKSPACES_LABEL_KEY))
                    .floor()
                    .max(0.0) as usize;
                let button_y =
                    label_y + ((session_row_height.saturating_sub(section_button_size)) / 2);
                let button_x = item_x
                    .saturating_add(item_width)
                    .saturating_sub(section_button_size + self.ui_px(SIDEBAR_INSET));
                let button_hovered = !suppress_hover
                    && self.is_pointer_over_ui_rect(
                        button_x,
                        button_y,
                        section_button_size,
                        section_button_size,
                    );
                self.paint_sidebar_text(
                    layers,
                    &ui_font,
                    ui_metrics,
                    &crate::i18n::tr("sidebar-workspaces"),
                    item_x + self.ui_px(SIDEBAR_INSET),
                    label_y + ((session_row_height.saturating_sub(ui_cell_height)) / 2),
                    button_x.saturating_sub(item_x + self.ui_px(SIDEBAR_INSET) * 2),
                    muted_fg,
                )?;
                self.paint_sidebar_icon_button(
                    layers,
                    1,
                    euclid::rect(
                        button_x as f32,
                        button_y as f32,
                        section_button_size as f32,
                        section_button_size as f32,
                    ),
                    chrome,
                    button_hovered,
                    false,
                )
                .context("sidebar new project button")?;
                self.ui_items.push(UIItem {
                    x: button_x,
                    y: button_y,
                    width: section_button_size,
                    height: section_button_size,
                    item_type: UIItemType::ProjectNew,
                });
                let section_icon_size = (header_icon_size + 4).min(
                    section_button_size
                        .saturating_sub(self.ui_px(SIDEBAR_SECTION_ACTION_ICON_INSET)),
                );
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::ProjectAdd,
                    button_x + ((section_button_size.saturating_sub(section_icon_size)) / 2),
                    button_y + ((section_button_size.saturating_sub(section_icon_size)) / 2),
                    section_icon_size,
                    if button_hovered { foreground } else { muted_fg },
                )?;
            }
            virtual_y += session_row_height + row_gap;
        }

        // Folders — projects and thread-ref groups — render interleaved in
        // the Space's display order, so a ref folder can sit anywhere among
        // the local ones. The height calc walks the same order.
        let group_space_id = self.workspace_sidebar_space_id().to_string();
        for (folder_idx, folder) in view.display_order.iter().enumerate() {
            if folder_idx > 0 {
                virtual_y += self.ui_px(WORKSPACE_GROUP_EXTRA_GAP);
            }
            if let workspace_threads::SidebarFolder::Project(folder_project_index) = folder {
                let Some(project) = view.projects.get(*folder_project_index) else {
                    continue;
                };
                let folder_place = virtual_y;
                let folder_glided = self.note_sidebar_row(
                    &project.id,
                    "",
                    folder_place,
                    folder_place,
                    0.0,
                    rows_tracked,
                    rows_glide,
                );
                let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                let row_bottom = row_top + session_row_height as f32;
                let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
                let folder_shift = self.sidebar_make_way.shift_of(&project.id);
                let row_paints = paints_at(row_top + folder_shift) && !folder_carried(&project.id);
                let y = (row_top + folder_shift).floor().max(0.0) as usize;
                let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                let hit_bottom = row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                let hit_height = hit_bottom.saturating_sub(hit_y).max(1);

                let disclosure_size = icon_size.min(22);
                let project_icon_x = item_x + self.ui_px(SIDEBAR_INSET);
                let project_text_x = project_icon_x + icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                let project_action_size =
                    section_button_size.min(session_row_height.saturating_sub(8));
                let project_action_x = item_x
                    .saturating_add(item_width)
                    .saturating_sub(project_action_size + self.ui_px(SIDEBAR_INSET));
                // The chevron sits by the add button, there under the pointer.
                let disclosure_x = project_action_x
                    .saturating_sub(disclosure_size + self.ui_px(SIDEBAR_INSET) / 2);
                let project_text_right = disclosure_x;

                if project.is_archived {
                    // A revealed archived row: dimmed, inert, no chevron and
                    // no "+" button. Its own UIItemType keeps it invisible
                    // to drag targeting, inline rename and folder reorder.
                    if row_is_visible {
                        self.ui_items.push(UIItem {
                            x: item_x,
                            y: hit_y,
                            width: item_width,
                            height: hit_height,
                            item_type: UIItemType::ArchivedProject(project.id.clone()),
                        });
                        let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
                        let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                        self.paint_sidebar_icon(
                            layers,
                            SvgIcon::Archive,
                            project_icon_x,
                            icon_y,
                            icon_size,
                            muted_fg,
                        )?;
                        let project_title = self.sidebar_project_title(&project.id, &project.name);
                        self.paint_sidebar_name(
                            layers,
                            &ui_font,
                            ui_metrics,
                            &project_title,
                            project_text_x,
                            text_y,
                            project_text_right
                                .saturating_sub(project_text_x + self.ui_px(SIDEBAR_INSET)),
                            muted_fg,
                        )?;
                    }
                    virtual_y += session_row_height + row_gap;
                    continue;
                }

                let row_hovered = !suppress_hover
                    && carried.is_none()
                    && self.is_pointer_over_ui_rect(item_x, hit_y, item_width, hit_height);
                let (chevron_shown, project_open) = if rows_tracked {
                    self.folder_chevrons.aim(
                        FolderKind::Project,
                        &project.id,
                        row_hovered,
                        !project.threads_collapsed,
                    )
                } else {
                    (0.0, if project.threads_collapsed { 0.0 } else { 1.0 })
                };
                if row_is_visible {
                    self.ui_items.push(UIItem {
                        x: item_x,
                        y: hit_y,
                        width: item_width,
                        height: hit_height,
                        item_type: UIItemType::Project(project.id.clone()),
                    });
                }

                let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
                let disclosure_y = y + ((session_row_height.saturating_sub(disclosure_size)) / 2);
                let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                if row_paints {
                    self.ui_items.push(UIItem {
                        x: disclosure_x,
                        y: disclosure_y,
                        width: disclosure_size,
                        height: disclosure_size,
                        item_type: UIItemType::ProjectToggleThreads(project.id.clone()),
                    });
                    let chevron_hovered = row_hovered
                        && self.is_pointer_over_ui_rect(
                            disclosure_x,
                            disclosure_y,
                            disclosure_size,
                            disclosure_size,
                        );
                    self.paint_folder_chevron(
                        layers,
                        (disclosure_x, disclosure_y, disclosure_size),
                        chevron_shown,
                        project_open,
                        if chevron_hovered { foreground } else { muted_fg },
                    )?;
                    self.paint_sidebar_project_icon(
                        layers,
                        project,
                        project_icon_x,
                        icon_y,
                        icon_size,
                        muted_fg,
                    )?;
                    let project_title = self.sidebar_project_title(&project.id, &project.name);
                    self.paint_sidebar_name(
                        layers,
                        &ui_font,
                        ui_metrics,
                        &project_title,
                        project_text_x,
                        text_y,
                        project_text_right
                            .saturating_sub(project_text_x + self.ui_px(SIDEBAR_INSET)),
                        muted_fg,
                    )?;
                }

                if row_paints {
                    let project_action_y =
                        y + ((session_row_height.saturating_sub(project_action_size)) / 2);
                    let project_action_hovered = !suppress_hover
                        && self.is_pointer_over_ui_rect(
                            project_action_x,
                            project_action_y,
                            project_action_size,
                            project_action_size,
                        );
                    self.paint_sidebar_icon_button(
                        layers,
                        1,
                        euclid::rect(
                            project_action_x as f32,
                            project_action_y as f32,
                            project_action_size as f32,
                            project_action_size as f32,
                        ),
                        chrome,
                        project_action_hovered,
                        false,
                    )
                    .context("sidebar new thread button")?;
                    // Not while rows are moving: it counts toward the extent
                    // of its folder, and it is drawn away from its place.
                    if carried.is_none() {
                        self.ui_items.push(UIItem {
                            x: project_action_x,
                            y: project_action_y,
                            width: project_action_size,
                            height: project_action_size,
                            item_type: UIItemType::WorkspaceThreadNew(project.id.clone()),
                        });
                    }
                    let action_icon_size = (header_icon_size + 4).min(
                        project_action_size
                            .saturating_sub(self.ui_px(SIDEBAR_SECTION_ACTION_ICON_INSET)),
                    );
                    // With the chevron, under the pointer only, unless
                    // Settings › Accessibility keeps the buttons showing.
                    let action_shown = if crate::native_settings::show_button_shapes() {
                        1.0
                    } else {
                        chevron_shown
                    };
                    if action_shown > 0.0 {
                        self.paint_sidebar_icon(
                            layers,
                            SvgIcon::CirclePlus,
                            project_action_x
                                + ((project_action_size.saturating_sub(action_icon_size)) / 2),
                            project_action_y
                                + ((project_action_size.saturating_sub(action_icon_size)) / 2),
                            action_icon_size,
                            if project.is_active || project_action_hovered {
                                foreground
                            } else {
                                muted_fg
                            }
                            .mul_alpha(action_shown),
                        )?;
                    }
                }

                virtual_y += session_row_height + row_gap;

                if project_open > 0.0 {
                    // Opening or closing, the rows fade with the folder and
                    // what follows moves by as much of them as is open.
                    let rows_start = virtual_y;
                    let into = &mut *layers;
                    let mut rows = std::mem::take(&mut self.sidebar_folder_rows);
                    rows.recycle();
                    let layers = &mut TripleLayerQuadAllocator::Heap(&mut rows);
                    // Lined up with the folder's icon, as pinned rows are.
                    let session_x = item_x + self.ui_px(SIDEBAR_INSET);
                    let session_width = item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2);
                    let session_status_x = session_x + self.ui_px(SIDEBAR_INSET);

                    for session in &project.threads {
                        // Within its folder: a folder moved as a whole moves
                        // its rows by its own shift.
                        self.note_sidebar_row(
                            &session.id,
                            &project.id,
                            virtual_y - folder_place,
                            virtual_y,
                            folder_glided,
                            rows_tracked,
                            rows_glide,
                        );
                        let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                        let row_bottom = row_top + session_row_height as f32;
                        let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
                        let row_shift = folder_shift + self.sidebar_make_way.shift_of(&session.id);
                        let row_paints = paints_at(row_top + row_shift)
                            && !thread_carried(&session.id)
                            && !folder_carried(&project.id);
                        let y = (row_top + row_shift).floor().max(0.0) as usize;
                        let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                        let hit_bottom =
                            row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                        let hit_height = hit_bottom.saturating_sub(hit_y).max(1);

                        let is_selected =
                            self.is_workspace_sidebar_thread_selected(session, suppress_own_active);
                        if is_selected && current_row.is_none() {
                            current_row =
                                Some(CurrentRow::new(virtual_y, None, thread_icon(session)));
                        }
                        if row_paints && is_selected {
                            let row_rect = euclid::rect(
                                session_x as f32,
                                y as f32,
                                session_width as f32,
                                session_row_height as f32,
                            );
                            self.paint_sidebar_selected_row(layers, row_rect, selected_bg, selected_border)
                                .context("sidebar selected thread")?;
                        }

                        let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                        if row_is_visible {
                            self.ui_items.push(UIItem {
                                x: session_x,
                                y: hit_y,
                                width: session_width,
                                height: hit_height,
                                item_type: UIItemType::WorkspaceThread(session.id.clone()),
                            });
                        }
                        if row_paints {
                            let is_hovered = !suppress_hover
                                && self.is_pointer_over_ui_rect(
                                    session_x,
                                    y,
                                    session_width,
                                    session_row_height,
                                );
                            let is_renaming_session = self.is_renaming_sidebar_thread(&session.id);
                            let action_size = session_row_height.saturating_sub(8).clamp(
                                self.ui_px(SESSION_ACTION_MIN_SIZE),
                                self.ui_px(SESSION_ACTION_MAX_SIZE),
                            );
                            let delete_x = session_x
                                .saturating_add(session_width)
                                .saturating_sub(self.ui_px(SIDEBAR_INSET) + action_size);
                            let pin_x = delete_x.saturating_sub(action_size + 4);
                            let action_y =
                                y + ((session_row_height.saturating_sub(action_size)) / 2);
                            if is_hovered && !is_selected && !is_renaming_session {
                                self.fill_rounded_rectangle(
                                    layers,
                                    0,
                                    euclid::rect(
                                        session_x as f32,
                                        y as f32,
                                        session_width as f32,
                                        session_row_height as f32,
                                    ),
                                    chrome.sidebar_row_hover_bg,
                                    session_row_height as f32 / 2.0,
                                )
                                .context("sidebar hovered thread")?;
                            }
                            let row_hovered = is_hovered && !is_renaming_session;
                            let number =
                                numbers.as_ref().and_then(|numbers| numbers.of(&session.id));
                            // As for a pinned thread: no buttons on a row in a
                            // Library card, or under a number.
                            let shows_actions = row_hovered
                                && self.library_card_rect().is_none()
                                && number.is_none();
                            let surface = if is_selected {
                                over(selected_bg, sidebar_bg)
                            } else if row_hovered {
                                over(chrome.sidebar_row_hover_bg, sidebar_bg)
                            } else {
                                sidebar_bg
                            };
                            let row_end = session_x
                                .saturating_add(session_width)
                                .saturating_sub(self.ui_px(SIDEBAR_INSET));
                            let (session_text_x, marks_right) = self.paint_sidebar_thread_marks(
                                layers,
                                &row_marks,
                                session,
                                session_status_x,
                                row_end,
                                y,
                                session_row_height,
                                surface,
                                !shows_actions,
                                false,
                                is_selected,
                                number.map_or(1.0, |number| number.icons_left()),
                                &chrome,
                                foreground,
                            )?;
                            let text_right = if shows_actions { pin_x } else { marks_right };
                            let text_width = text_right
                                .saturating_sub(session_text_x + self.ui_px(SIDEBAR_INSET));
                            let session_title =
                                self.sidebar_thread_title(&session.id, &session.name);
                            self.paint_thread_row_name(
                                layers,
                                &ui_font,
                                ui_metrics,
                                &session_title,
                                session_text_x,
                                text_y,
                                text_width,
                                if is_selected { active_fg } else { foreground },
                                number,
                                row_end,
                                y,
                                session_row_height,
                                is_selected,
                                &chrome,
                            )?;
                            if shows_actions {
                                let pin_icon = if session.is_pinned {
                                    SvgIcon::PinOff
                                } else {
                                    SvgIcon::Pin
                                };
                                for (x, item_type, icon, _context_name) in [
                                    (
                                        pin_x,
                                        UIItemType::WorkspaceThreadPin(session.id.clone()),
                                        pin_icon,
                                        "sidebar pin thread button",
                                    ),
                                    (
                                        delete_x,
                                        UIItemType::WorkspaceThreadDelete(session.id.clone()),
                                        SvgIcon::Trash2,
                                        "sidebar delete thread button",
                                    ),
                                ] {
                                    let hovered = self.is_pointer_over_ui_rect(
                                        x,
                                        action_y,
                                        action_size,
                                        action_size,
                                    );
                                    self.ui_items.push(UIItem {
                                        x,
                                        y: action_y,
                                        width: action_size,
                                        height: action_size,
                                        item_type,
                                    });
                                    let action_icon_size = action_size
                                        .saturating_sub(self.ui_px(SESSION_ACTION_ICON_INSET))
                                        .max(header_icon_size);
                                    self.paint_sidebar_icon(
                                        layers,
                                        icon,
                                        x + ((action_size.saturating_sub(action_icon_size)) / 2),
                                        action_y
                                            + ((action_size.saturating_sub(action_icon_size)) / 2),
                                        action_icon_size,
                                        if hovered {
                                            foreground
                                        } else {
                                            muted_fg.mul_alpha(0.88)
                                        },
                                    )?;
                                }
                            }
                        }

                        virtual_y += session_row_height + row_gap;
                    }
                    self.show_folder_rows(
                        into,
                        &rows,
                        project_open,
                        &mut virtual_y,
                        rows_start,
                        list_top_f + rows_start as f32 - scroll_offset + folder_shift,
                        (list_top_f, content_bottom_f),
                    )?;
                    if rows.resident_bytes() <= FOLDER_ROWS_KEEP_BYTES {
                        self.sidebar_folder_rows = rows;
                    }
                }
                if project.threads_collapsed && current_row.is_none() {
                    // Folded away: where it would be once its folder opens.
                    if let Some((index, session)) =
                        project.threads.iter().enumerate().find(|(_, session)| {
                            self.is_workspace_sidebar_thread_selected(session, suppress_own_active)
                        })
                    {
                        current_row = Some(CurrentRow::new(
                            virtual_y + index * (session_row_height + row_gap),
                            Some((
                                Fold::Project(project.id.clone()),
                                virtual_y.saturating_sub(session_row_height + row_gap),
                            )),
                            thread_icon(session),
                        ));
                    }
                }
            }

            // Reference groups render exactly like project folders: chevron,
            // link icon, origin-project name, then indented thread rows. The
            // link icon in the header is what tells a reference group apart
            // from a local project folder with the same name.
            if let workspace_threads::SidebarFolder::RefGroup(folder_group_index) = folder {
                let Some(group) = view.ref_groups.get(*folder_group_index) else {
                    continue;
                };
                let folder_place = virtual_y;
                let folder_glided = self.note_sidebar_row(
                    &group.key,
                    "",
                    folder_place,
                    folder_place,
                    0.0,
                    rows_tracked,
                    rows_glide,
                );
                let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                let row_bottom = row_top + session_row_height as f32;
                let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
                let folder_shift = self.sidebar_make_way.shift_of(&group.key);
                let row_paints = paints_at(row_top + folder_shift) && !folder_carried(&group.key);
                let y = (row_top + folder_shift).floor().max(0.0) as usize;
                // Hit rect clamped to the list viewport, like every other
                // full-width row: a header scrolled under the toolbar keeps
                // painting (masked) but must not swallow toolbar clicks.
                let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                let hit_bottom = row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                let hit_height = hit_bottom.saturating_sub(hit_y).max(1);

                let disclosure_size = icon_size.min(22);
                let group_icon_x = item_x + self.ui_px(SIDEBAR_INSET);
                let group_text_x = group_icon_x + icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                let icon_y = y + ((session_row_height.saturating_sub(icon_size)) / 2);
                let disclosure_y = y + ((session_row_height.saturating_sub(disclosure_size)) / 2);
                let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                let group_action_size =
                    section_button_size.min(session_row_height.saturating_sub(8));
                let group_action_x = item_x
                    .saturating_add(item_width)
                    .saturating_sub(group_action_size + self.ui_px(SIDEBAR_INSET));
                let disclosure_x = group_action_x
                    .saturating_sub(disclosure_size + self.ui_px(SIDEBAR_INSET) / 2);
                let row_hovered = !suppress_hover
                    && carried.is_none()
                    && self.is_pointer_over_ui_rect(item_x, hit_y, item_width, hit_height);
                let (chevron_shown, group_open) = if rows_tracked {
                    self.folder_chevrons.aim(
                        FolderKind::RefGroup,
                        &group.key,
                        row_hovered,
                        !group.collapsed,
                    )
                } else {
                    (0.0, if group.collapsed { 0.0 } else { 1.0 })
                };
                if row_is_visible {
                    let group_key = format!("{group_space_id}::{}", group.key);
                    // The hover tag carries the provenance the project-name
                    // header cannot: project names repeat across Spaces, so
                    // a local group names its origin Space, and a remote one
                    // leads with the machine. A dangling group's header IS
                    // the machine label already — nothing left to add.
                    let dangling = group
                        .threads
                        .first()
                        .is_some_and(|reference| reference.dangling);
                    let origin_tag = if dangling {
                        String::new()
                    } else if group.machine_is_local {
                        group.origin_space_name.clone()
                    } else if group.origin_space_name.is_empty()
                        // A remote Space often carries its host's name (the
                        // default for single-Space servers); "X · X" says
                        // nothing twice.
                        || group.origin_space_name == group.machine_label
                    {
                        group.machine_label.clone()
                    } else {
                        format!("{} · {}", group.machine_label, group.origin_space_name)
                    };
                    self.ui_items.push(UIItem {
                        x: item_x,
                        y: hit_y,
                        width: item_width,
                        height: hit_height,
                        item_type: UIItemType::ThreadRefGroupToggle {
                            key: group_key,
                            origin: origin_tag,
                        },
                    });
                }
                if row_paints {
                    // The whole row opens and closes the group, so the
                    // chevron only says which way it will go.
                    self.paint_folder_chevron(
                        layers,
                        (disclosure_x, disclosure_y, disclosure_size),
                        chevron_shown,
                        group_open,
                        muted_fg,
                    )?;
                    // A server folder is the server itself, not a link to
                    // threads picked one by one.
                    self.paint_sidebar_icon(
                        layers,
                        if group.server_folder {
                            SvgIcon::Server
                        } else {
                            SvgIcon::Link2
                        },
                        group_icon_x,
                        icon_y,
                        icon_size,
                        if group.attached {
                            muted_fg
                        } else {
                            muted_fg.mul_alpha(0.6)
                        },
                    )?;
                    // Header: the origin project's name, full width, exactly
                    // like a local folder. The machine it lives on is the
                    // row's hover tag — a permanent badge would eat the
                    // name's width on every row to answer a question the
                    // user asks once.
                    let header_fg = if group.attached {
                        muted_fg
                    } else {
                        muted_fg.mul_alpha(0.6)
                    };
                    let text_avail =
                        disclosure_x.saturating_sub(group_text_x + self.ui_px(SIDEBAR_INSET));
                    self.paint_sidebar_name(
                        layers,
                        &ui_font,
                        ui_metrics,
                        &group.label,
                        group_text_x,
                        text_y,
                        text_avail,
                        header_fg,
                    )?;

                    // The group "+": create a thread in the origin project
                    // and auto-reference it here — same affordance as the
                    // project "+", inert (and dimmed) while the origin
                    // machine is unreachable.
                    let group_action_y =
                        y + ((session_row_height.saturating_sub(group_action_size)) / 2);
                    let group_action_hovered = group.attached
                        && !suppress_hover
                        && self.is_pointer_over_ui_rect(
                            group_action_x,
                            group_action_y,
                            group_action_size,
                            group_action_size,
                        );
                    self.paint_sidebar_icon_button(
                        layers,
                        1,
                        euclid::rect(
                            group_action_x as f32,
                            group_action_y as f32,
                            group_action_size as f32,
                            group_action_size as f32,
                        ),
                        chrome,
                        group_action_hovered,
                        !group.attached,
                    )
                    .context("sidebar ref group new thread button")?;
                    if group.attached && carried.is_none() {
                        self.ui_items.push(UIItem {
                            x: group_action_x,
                            y: group_action_y,
                            width: group_action_size,
                            height: group_action_size,
                            item_type: UIItemType::ThreadRefGroupNewThread(group.key.clone()),
                        });
                    }
                    let action_icon_size = (header_icon_size + 4).min(
                        group_action_size
                            .saturating_sub(self.ui_px(SIDEBAR_SECTION_ACTION_ICON_INSET)),
                    );
                    // As a project's.
                    let action_shown = if crate::native_settings::show_button_shapes() {
                        1.0
                    } else {
                        chevron_shown
                    };
                    if action_shown > 0.0 {
                        self.paint_sidebar_icon(
                            layers,
                            SvgIcon::CirclePlus,
                            group_action_x
                                + ((group_action_size.saturating_sub(action_icon_size)) / 2),
                            group_action_y
                                + ((group_action_size.saturating_sub(action_icon_size)) / 2),
                            action_icon_size,
                            if group_action_hovered {
                                foreground
                            } else if group.attached {
                                muted_fg
                            } else {
                                muted_fg.mul_alpha(0.5)
                            }
                            .mul_alpha(action_shown),
                        )?;
                    }
                }
                virtual_y += session_row_height + row_gap;

                if group.collapsed && current_row.is_none() {
                    if let Some((index, reference)) =
                        group.threads.iter().enumerate().find(|(_, reference)| {
                            self.is_workspace_sidebar_thread_selected(&reference.thread, false)
                        })
                    {
                        current_row = Some(CurrentRow::new(
                            virtual_y + index * (session_row_height + row_gap),
                            Some((
                                Fold::RefGroup(format!("{group_space_id}::{}", group.key)),
                                virtual_y.saturating_sub(session_row_height + row_gap),
                            )),
                            thread_icon(&reference.thread),
                        ));
                    }
                }
                if group_open <= 0.0 {
                    continue;
                }
                // As with a project's rows: faded and folded as it opens
                // and closes.
                let rows_start = virtual_y;
                let into = &mut *layers;
                let mut rows = std::mem::take(&mut self.sidebar_folder_rows);
                rows.recycle();
                let layers = &mut TripleLayerQuadAllocator::Heap(&mut rows);
                let session_x = item_x + self.ui_px(SIDEBAR_INSET);
                let session_width = item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2);
                let session_status_x = session_x + self.ui_px(SIDEBAR_INSET);
                for reference in &group.threads {
                    let session = &reference.thread;
                    self.note_sidebar_row(
                        &session.id,
                        &group.key,
                        virtual_y - folder_place,
                        virtual_y,
                        folder_glided,
                        rows_tracked,
                        rows_glide,
                    );
                    let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                    let row_bottom = row_top + session_row_height as f32;
                    let row_is_visible = row_bottom > list_top_f && row_top < content_bottom_f;
                    let row_shift = folder_shift + self.sidebar_make_way.shift_of(&session.id);
                    let row_paints = paints_at(row_top + row_shift)
                        && !thread_carried(&session.id)
                        && !folder_carried(&group.key);
                    let y = (row_top + row_shift).floor().max(0.0) as usize;
                    let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                    let hit_bottom =
                        row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                    let hit_height = hit_bottom.saturating_sub(hit_y).max(1);
                    if current_row.is_none()
                        && self.is_workspace_sidebar_thread_selected(session, false)
                    {
                        current_row = Some(CurrentRow::new(virtual_y, None, thread_icon(session)));
                    }

                    if row_is_visible {
                        // A dangling ref has nothing to activate; it paints
                        // (greyed, removable) but registers no activation
                        // target.
                        if !reference.dangling {
                            self.ui_items.push(UIItem {
                                x: session_x,
                                y: hit_y,
                                width: session_width,
                                height: hit_height,
                                item_type: UIItemType::WorkspaceThread(session.id.clone()),
                            });
                        }
                    }
                    if row_paints {
                        let is_hovered = !suppress_hover
                            && self.is_pointer_over_ui_rect(
                                session_x,
                                y,
                                session_width,
                                session_row_height,
                            );
                        let is_selected = self.is_workspace_sidebar_thread_selected(session, false);
                        let dimmed = reference.dangling || !reference.origin_domain_attached;
                        if is_selected {
                            let row_rect = euclid::rect(
                                session_x as f32,
                                y as f32,
                                session_width as f32,
                                session_row_height as f32,
                            );
                            self.paint_sidebar_selected_row(layers, row_rect, selected_bg, selected_border)
                                .context("sidebar selected thread ref")?;
                        } else if is_hovered {
                            self.fill_rounded_rectangle(
                                layers,
                                0,
                                euclid::rect(
                                    session_x as f32,
                                    y as f32,
                                    session_width as f32,
                                    session_row_height as f32,
                                ),
                                chrome.sidebar_row_hover_bg,
                                session_row_height as f32 / 2.0,
                            )
                            .context("sidebar hovered thread ref")?;
                        }

                        let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                        let action_size = session_row_height.saturating_sub(8).clamp(
                            self.ui_px(SESSION_ACTION_MIN_SIZE),
                            self.ui_px(SESSION_ACTION_MAX_SIZE),
                        );
                        let delete_x = session_x
                            .saturating_add(session_width)
                            .saturating_sub(self.ui_px(SIDEBAR_INSET) + action_size);
                        let action_y = y + ((session_row_height.saturating_sub(action_size)) / 2);
                        let surface = if is_selected {
                            over(selected_bg, sidebar_bg)
                        } else if is_hovered {
                            over(chrome.sidebar_row_hover_bg, sidebar_bg)
                        } else {
                            sidebar_bg
                        };
                        let number = numbers.as_ref().and_then(|numbers| numbers.of(&session.id));
                        // A ref whose machine is away says nothing of what
                        // it is doing: it keeps its icons, not its mark.
                        let row_end = session_x
                            .saturating_add(session_width)
                            .saturating_sub(self.ui_px(SIDEBAR_INSET));
                        let (session_text_x, marks_right) = self.paint_sidebar_thread_marks(
                            layers,
                            &row_marks,
                            session,
                            session_status_x,
                            row_end,
                            y,
                            session_row_height,
                            surface,
                            !is_hovered || number.is_some(),
                            dimmed,
                            is_selected,
                            number.map_or(1.0, |number| number.icons_left()),
                            &chrome,
                            foreground,
                        )?;
                        // Only a reference can be taken out: a row a server
                        // folder shows, with none of its own, stays as long
                        // as the folder does. Nor is it to be hit unseen
                        // under a number.
                        let removable = is_hovered
                            && number.is_none()
                            && (!reference.server_folder
                                || workspace_threads::thread_ref_is_explicit(
                                    self.workspace_sidebar_space_id(),
                                    &session.id,
                                ));
                        let text_right = if removable { delete_x } else { marks_right };
                        let text_fg = if dimmed {
                            muted_fg.mul_alpha(0.7)
                        } else if is_selected {
                            active_fg
                        } else {
                            foreground
                        };
                        self.paint_thread_row_name(
                            layers,
                            &ui_font,
                            ui_metrics,
                            &session.name,
                            session_text_x,
                            text_y,
                            text_right.saturating_sub(session_text_x + self.ui_px(SIDEBAR_INSET)),
                            text_fg,
                            number,
                            row_end,
                            y,
                            session_row_height,
                            is_selected,
                            &chrome,
                        )?;

                        if removable {
                            // An X, not a trash can: removing a reference
                            // leaves the origin thread running untouched.
                            let hovered = self.is_pointer_over_ui_rect(
                                delete_x,
                                action_y,
                                action_size,
                                action_size,
                            );
                            self.ui_items.push(UIItem {
                                x: delete_x,
                                y: action_y,
                                width: action_size,
                                height: action_size,
                                item_type: UIItemType::WorkspaceThreadDelete(session.id.clone()),
                            });
                            let action_icon_size = action_size
                                .saturating_sub(self.ui_px(SESSION_ACTION_ICON_INSET))
                                .max(header_icon_size);
                            self.paint_sidebar_icon(
                                layers,
                                SvgIcon::X,
                                delete_x + ((action_size.saturating_sub(action_icon_size)) / 2),
                                action_y + ((action_size.saturating_sub(action_icon_size)) / 2),
                                action_icon_size,
                                if hovered {
                                    foreground
                                } else {
                                    muted_fg.mul_alpha(0.88)
                                },
                            )?;
                        }
                    }

                    virtual_y += session_row_height + row_gap;
                }
                self.show_folder_rows(
                    into,
                    &rows,
                    group_open,
                    &mut virtual_y,
                    rows_start,
                    list_top_f + rows_start as f32 - scroll_offset + folder_shift,
                    (list_top_f, content_bottom_f),
                )?;
                if rows.resident_bytes() <= FOLDER_ROWS_KEEP_BYTES {
                    self.sidebar_folder_rows = rows;
                }
            }
        }

        // The panes other accounts on this machine share with ours, after
        // everything of the Space's own; `workspace_sidebar_list_height`
        // counts them the same way. A row opens the pane in a new tab.
        // Under them, a line for each account whose ThinkTerm is another
        // version: what it shares cannot be watched, but it may share.
        let shared = self.shared_with_us().to_vec();
        let other_version = self.shared_with_us_other_version();
        if !shared.is_empty() || !other_version.is_empty() {
            if virtual_y > 0 {
                virtual_y += self.ui_px(WORKSPACE_SECTION_LABEL_GAP);
            }
            let label_icon_size = header_icon_size.min(ui_cell_height).max(16);
            let label_top = list_top_f + virtual_y as f32 - scroll_offset;
            let label_bottom = label_top + session_row_height as f32;
            if label_bottom > list_top_f && label_top < content_bottom_f {
                let label_y = label_top.floor().max(0.0) as usize;
                let label_icon_x = item_x + self.ui_px(SIDEBAR_INSET);
                let label_icon_y =
                    label_y + ((session_row_height.saturating_sub(label_icon_size)) / 2);
                let label_text_x = label_icon_x + label_icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::Share,
                    label_icon_x,
                    label_icon_y,
                    label_icon_size,
                    muted_fg,
                )?;
                self.paint_sidebar_text(
                    layers,
                    &ui_font,
                    ui_metrics,
                    &crate::i18n::tr("sidebar-shared-with-me"),
                    label_text_x,
                    label_y + ((session_row_height.saturating_sub(ui_cell_height)) / 2),
                    item_x
                        .saturating_add(item_width)
                        .saturating_sub(label_text_x + self.ui_px(SIDEBAR_INSET)),
                    muted_fg,
                )?;
            }
            virtual_y += session_row_height + row_gap;

            let row_x = item_x + self.ui_px(SIDEBAR_INSET);
            let row_width = item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2);
            for (index, row) in shared.iter().enumerate() {
                let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                let row_bottom = row_top + session_row_height as f32;
                if row_bottom > list_top_f && row_top < content_bottom_f {
                    let y = row_top.floor().max(0.0) as usize;
                    let hit_y = row_top.max(list_top_f).floor().max(0.0) as usize;
                    let hit_bottom =
                        row_bottom.min(content_bottom_f).ceil().max(hit_y as f32) as usize;
                    self.ui_items.push(UIItem {
                        x: row_x,
                        y: hit_y,
                        width: row_width,
                        height: hit_bottom.saturating_sub(hit_y).max(1),
                        item_type: UIItemType::SharedWithMe(index),
                    });
                    let hovered = !suppress_hover
                        && self.is_pointer_over_ui_rect(row_x, y, row_width, session_row_height);
                    // The one this window is watching is selected, as a
                    // thread on screen is, and from the click that opens it.
                    let opening = self.share_view_opening(&row.workspace);
                    let shown = opening || active_workspace == row.workspace;
                    let row_rect = euclid::rect(
                        row_x as f32,
                        y as f32,
                        row_width as f32,
                        session_row_height as f32,
                    );
                    if shown {
                        self.paint_sidebar_selected_row(layers, row_rect, selected_bg, selected_border)
                            .context("sidebar watched shared pane")?;
                    } else if hovered {
                        self.fill_rounded_rectangle(
                            layers,
                            0,
                            row_rect,
                            chrome.sidebar_row_hover_bg,
                            session_row_height as f32 / 2.0,
                        )
                        .context("sidebar hovered shared pane")?;
                    }
                    let icon_x = row_x + self.ui_px(SIDEBAR_INSET);
                    let icon_y = y + ((session_row_height.saturating_sub(label_icon_size)) / 2);
                    self.paint_sidebar_icon(
                        layers,
                        if opening {
                            SvgIcon::LoaderCircle
                        } else {
                            SvgIcon::Eye
                        },
                        icon_x,
                        icon_y,
                        label_icon_size,
                        if hovered || shown { foreground } else { muted_fg },
                    )?;
                    let text_x = icon_x + label_icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                    let text = if row.title.is_empty() {
                        row.owner.clone()
                    } else {
                        format!("{} · {}", row.owner, row.title)
                    };
                    self.paint_sidebar_text(
                        layers,
                        &ui_font,
                        ui_metrics,
                        &text,
                        text_x,
                        y + ((session_row_height.saturating_sub(ui_cell_height)) / 2),
                        row_x
                            .saturating_add(row_width)
                            .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET)),
                        foreground,
                    )?;
                }
                virtual_y += session_row_height + row_gap;
            }
            // Two lines each, counted as two rows: whose, then what to do,
            // which the sidebar's width would cut off after the name.
            let hint = crate::i18n::tr("sidebar-shared-other-version-hint");
            for line in &other_version {
                let row_top = list_top_f + virtual_y as f32 - scroll_offset;
                let row_bottom = row_top + (session_row_height * 2 + row_gap) as f32;
                if row_bottom > list_top_f && row_top < content_bottom_f {
                    let y = row_top.floor().max(0.0) as usize;
                    let icon_x = row_x + self.ui_px(SIDEBAR_INSET);
                    let icon_y = y + ((session_row_height.saturating_sub(label_icon_size)) / 2);
                    self.paint_sidebar_icon(
                        layers,
                        SvgIcon::CircleAlert,
                        icon_x,
                        icon_y,
                        label_icon_size,
                        muted_fg,
                    )?;
                    let text_x = icon_x + label_icon_size + self.ui_px(SIDEBAR_ICON_GAP);
                    let text_y = y + ((session_row_height.saturating_sub(ui_cell_height)) / 2);
                    let text_width = row_x
                        .saturating_add(row_width)
                        .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET));
                    self.paint_sidebar_text(
                        layers,
                        &ui_font,
                        ui_metrics,
                        line,
                        text_x,
                        text_y,
                        text_width,
                        muted_fg,
                    )?;
                    self.paint_sidebar_text(
                        layers,
                        &ui_font,
                        ui_metrics,
                        &hint,
                        text_x,
                        text_y + ui_cell_height + self.ui_px(2),
                        text_width,
                        muted_fg,
                    )?;
                }
                virtual_y += (session_row_height + row_gap) * 2;
            }
        }

        // A row scrolled under the header or the footer is cut off there,
        // and the list fades out towards the end it goes on past -- in the
        // rows' own alpha, so that it reads the same over a see-through
        // ground. Only a recording can be cut, so the callers record;
        // anything else gets covers painted over the ends instead.
        let list_height = content_bottom.saturating_sub(list_top);
        let list_fade = crate::quad::QuadEdgeFade {
            top: if scroll_offset > 0.0 {
                self.ui_px(SIDEBAR_TOP_FADE_HEIGHT).min(list_height / 2) as f32
            } else {
                0.0
            },
            bottom: if settings_footer_height > 0 && scroll_offset < max_scroll {
                self.ui_px(SIDEBAR_SETTINGS_FADE_HEIGHT).min(list_height / 2) as f32
            } else {
                0.0
            },
            ..Default::default()
        };
        let list_cut = match (list_quads_start, &mut *layers) {
            (Some(start), TripleLayerQuadAllocator::Heap(heap)) => {
                heap.cut_after(
                    &start,
                    crate::quad::QuadClipRect::from_top_left_pixels(
                        panel_x as f32,
                        list_top_f,
                        (panel_x + panel_width) as f32,
                        content_bottom_f,
                        &self.dimensions,
                    ),
                    list_fade,
                );
                true
            }
            _ => false,
        };
        self.workspace_sidebar_list_quads = list_quads_start.zip(layers.heap_mark());

        let header_mask_height = list_top.saturating_sub(panel_y);
        // Covers what the list left under the header, then paints the header
        // again over that. Not once the list is cut: the header painted first
        // is then the one in view, and a second coat of it would show.
        if header_mask_height > 0 && !list_cut {
            self.filled_rectangle(
                layers,
                2,
                euclid::rect(
                    panel_x as f32,
                    panel_y as f32,
                    panel_width as f32,
                    header_mask_height as f32,
                ),
                sidebar_bg,
            )
            .context("sidebar header scroll mask")?;
            if show_sidebar_toolbar {
                let toggle_hovered = self.is_pointer_over_ui_rect(
                    sidebar_toggle_x,
                    sidebar_toggle_y,
                    sidebar_toggle_size,
                    sidebar_toggle_size,
                );
                if toggle_hovered {
                    self.fill_rounded_rectangle(
                        layers,
                        2,
                        euclid::rect(
                            sidebar_toggle_x as f32,
                            sidebar_toggle_y as f32,
                            sidebar_toggle_size as f32,
                            sidebar_toggle_size as f32,
                        ),
                        chrome.sidebar_button_hover_bg,
                        self.ui_f32(SIDEBAR_ROW_RADIUS),
                    )
                    .context("sidebar toolbar toggle button repaint")?;
                }
                self.paint_sidebar_icon(
                    layers,
                    self.workspace_sidebar_toggle_icon(),
                    sidebar_toggle_x
                        + ((sidebar_toggle_size.saturating_sub(sidebar_toggle_icon_size)) / 2),
                    sidebar_toggle_y
                        + ((sidebar_toggle_size.saturating_sub(sidebar_toggle_icon_size)) / 2),
                    sidebar_toggle_icon_size,
                    if toggle_hovered { foreground } else { muted_fg },
                )?;
            }
            let space_menu_hovered = self.is_pointer_over_ui_rect(
                space_menu_x,
                space_menu_y,
                space_menu_width,
                space_menu_height,
            );
            if space_menu_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        space_menu_x as f32,
                        space_menu_y as f32,
                        space_menu_width as f32,
                        space_menu_height as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar space menu button repaint")?;
            }
            if connection_state == SpaceConnectionState::Connecting {
                self.paint_spinning_ui_icon(
                    layers,
                    2,
                    space_icon,
                    space_icon_x,
                    space_icon_y,
                    space_icon_size,
                    space_icon_color,
                )?;
            } else {
                self.paint_sidebar_icon(
                    layers,
                    space_icon,
                    space_icon_x,
                    space_icon_y,
                    space_icon_size,
                    space_icon_color,
                )?;
            }
            self.paint_sidebar_text(
                layers,
                &ui_font,
                ui_metrics,
                space_label.as_ref(),
                space_text_x,
                space_menu_y + ((space_menu_height.saturating_sub(ui_cell_height)) / 2),
                space_text_right.saturating_sub(space_text_x),
                foreground,
            )?;
            self.paint_sidebar_icon(
                layers,
                SvgIcon::Ellipsis,
                space_action_icon_x,
                space_action_icon_y,
                space_action_icon_size,
                if space_menu_hovered {
                    foreground
                } else {
                    muted_fg
                },
            )?;
            if layout.reconnect_row_height > 0 {
                self.paint_space_reconnect_row(
                    layers,
                    2,
                    item_x + self.ui_px(SIDEBAR_INSET),
                    space_menu_y + space_menu_height + self.ui_px(SIDEBAR_INSET),
                    item_width.saturating_sub(self.ui_px(SIDEBAR_INSET) * 2),
                    layout.reconnect_row_height,
                    &ui_font,
                    ui_metrics,
                    ui_cell_height,
                    false,
                )?;
            }
            let top_action_hovered = active_project_id.is_some()
                && self.is_pointer_over_ui_rect(
                    top_action_x,
                    top_action_y,
                    top_action_width,
                    top_action_height,
                );
            // The repaint over the scrolled list; it is what ends up visible,
            // so it has to use the same treatment as the layer-1 fill.
            self.paint_sidebar_action_button(
                layers,
                2,
                euclid::rect(
                    top_action_x as f32,
                    top_action_y as f32,
                    top_action_width as f32,
                    top_action_height as f32,
                ),
                chrome,
                top_action_hovered,
                false,
            )
            .context("sidebar add thread button repaint")?;
            let notification_action_hovered = self.is_pointer_over_ui_rect(
                notification_action_x,
                notification_action_y,
                notification_action_size,
                notification_action_size,
            );
            self.paint_sidebar_action_button(
                layers,
                2,
                euclid::rect(
                    notification_action_x as f32,
                    notification_action_y as f32,
                    notification_action_size as f32,
                    notification_action_size as f32,
                ),
                chrome,
                notification_action_hovered,
                false,
            )
            .context("sidebar notifications button repaint")?;
            let top_action_fg = if active_project_id.is_some() {
                foreground
            } else {
                muted_fg
            };
            self.paint_sidebar_icon(
                layers,
                SvgIcon::SquarePen,
                top_action_icon_x,
                top_action_icon_y,
                top_action_icon_size,
                top_action_fg,
            )?;
            self.paint_sidebar_text(
                layers,
                &ui_font,
                ui_metrics,
                top_action_label.as_ref(),
                top_action_text_x,
                top_action_text_y,
                top_action_text_width,
                top_action_fg,
            )?;
            self.paint_sidebar_icon(
                layers,
                SvgIcon::Bell,
                notification_action_x
                    + ((notification_action_size.saturating_sub(notification_icon_size)) / 2),
                notification_action_y
                    + ((notification_action_size.saturating_sub(notification_icon_size)) / 2),
                notification_icon_size,
                if notification_action_hovered {
                    foreground
                } else {
                    muted_fg
                },
            )?;
            if has_notifications {
                // The layer-2 header mask above covers the initial header
                // paint. Repaint the badge here too, after the button and bell,
                // so the unread indicator is actually visible.
                self.paint_workspace_notification_badge(
                    layers,
                    2,
                    notification_action_x,
                    notification_action_y,
                    notification_action_size,
                    notification_badge_pulse,
                )
                .context("sidebar notification badge repaint")?;
            }
        }

        let bottom_mask_height = panel_y
            .saturating_add(panel_height)
            .saturating_sub(content_bottom);
        if bottom_mask_height > 0 && !list_cut {
            self.filled_rectangle(
                layers,
                2,
                euclid::rect(
                    panel_x as f32,
                    content_bottom as f32,
                    panel_width as f32,
                    bottom_mask_height as f32,
                ),
                sidebar_bg,
            )
            .context("sidebar bottom scroll mask")?;
        }

        if settings_footer_height > 0 {
            // A Library card has no footer: what follows is set apart, for
            // the sidebar on its way into its card to let go of.
            if card {
                self.mark_library_card_footer(layers.heap_mark());
            }

            if !list_cut {
                self.filled_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        panel_x as f32,
                        settings_footer_y as f32,
                        panel_width as f32,
                        settings_footer_height as f32,
                    ),
                    sidebar_bg,
                )
                .context("sidebar settings footer background")?;
            }

            let settings_row_x = item_x + self.ui_px(SIDEBAR_SETTINGS_ROW_SIDE_PADDING);
            let settings_row_y = (settings_footer_y + self.ui_px(SIDEBAR_SETTINGS_ROW_TOP_PADDING))
                .saturating_sub(self.ui_px(SIDEBAR_SETTINGS_ROW_LIFT));
            let settings_row_width =
                item_width.saturating_sub(self.ui_px(SIDEBAR_SETTINGS_ROW_SIDE_PADDING) * 2);
            let settings_row_height = settings_footer_height
                .saturating_sub(
                    self.ui_px(SIDEBAR_SETTINGS_ROW_TOP_PADDING)
                        + self.ui_px(SIDEBAR_SETTINGS_ROW_BOTTOM_PADDING),
                )
                .max(1);
            let settings_action_size = settings_row_height.max(1);
            let footer_action_right = settings_row_x
                .saturating_add(settings_row_width)
                .saturating_sub(settings_action_size);
            let action_step = settings_action_size + self.ui_px(SIDEBAR_INSET) / 2;
            let settings_action_x = footer_action_right;
            let settings_action_y = settings_row_y;
            // Right to left: view options (parked), thread search, SSH hosts,
            // Live Overview — so the settings label stays the primary footer
            // action. With view options off, search takes its slot.
            let search_action_x = if SHOW_SIDEBAR_VIEW_OPTIONS {
                settings_action_x.saturating_sub(action_step)
            } else {
                footer_action_right
            };
            let search_action_y = settings_row_y;
            let ssh_action_x = search_action_x.saturating_sub(action_step);
            let ssh_action_y = settings_row_y;
            let overview_action_x = ssh_action_x.saturating_sub(action_step);
            let overview_action_y = settings_row_y;
            let search_action_hovered = self.is_pointer_over_ui_rect(
                search_action_x,
                search_action_y,
                settings_action_size,
                settings_action_size,
            );
            let ssh_action_hovered = self.is_pointer_over_ui_rect(
                ssh_action_x,
                ssh_action_y,
                settings_action_size,
                settings_action_size,
            );
            let overview_action_hovered = self.is_pointer_over_ui_rect(
                overview_action_x,
                overview_action_y,
                settings_action_size,
                settings_action_size,
            );
            let settings_body_width = overview_action_x
                .saturating_sub(settings_row_x)
                .saturating_sub(self.ui_px(SIDEBAR_INSET) / 2);
            // The Library's button, an icon on its own: settings live in the
            // Library now. Sized as the settings button was once its label
            // no longer fit, so the row keeps its shape.
            let settings_icon_probe = icon_size.min(settings_row_height.saturating_sub(8));
            let settings_body_width = (self.ui_px(SIDEBAR_SETTINGS_ICON_EXTRA_INSET) * 2
                + settings_icon_probe)
                .min(settings_body_width);
            let settings_hovered = self.is_pointer_over_ui_rect(
                settings_row_x,
                settings_row_y,
                settings_body_width,
                settings_row_height,
            );
            let settings_options_hovered = SHOW_SIDEBAR_VIEW_OPTIONS
                && self.is_pointer_over_ui_rect(
                    settings_action_x,
                    settings_action_y,
                    settings_action_size,
                    settings_action_size,
                );
            if settings_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        settings_row_x as f32,
                        settings_row_y as f32,
                        settings_body_width as f32,
                        settings_row_height as f32,
                    ),
                    chrome.sidebar_row_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar settings button hover")?;
            }
            self.ui_items.push(UIItem {
                x: settings_row_x,
                y: settings_row_y,
                width: settings_body_width,
                height: settings_row_height,
                item_type: UIItemType::Library(
                    crate::termwindow::ui::library::LibraryItem::Open,
                ),
            });
            if settings_options_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        settings_action_x as f32,
                        settings_action_y as f32,
                        settings_action_size as f32,
                        settings_action_size as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar settings view options hover")?;
            }
            if SHOW_SIDEBAR_VIEW_OPTIONS {
                self.ui_items.push(UIItem {
                    x: settings_action_x,
                    y: settings_action_y,
                    width: settings_action_size,
                    height: settings_action_size,
                    item_type: UIItemType::WorkspaceSidebarViewOptions,
                });
            }
            if search_action_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        search_action_x as f32,
                        search_action_y as f32,
                        settings_action_size as f32,
                        settings_action_size as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar thread search hover")?;
            }
            self.ui_items.push(UIItem {
                x: search_action_x,
                y: search_action_y,
                width: settings_action_size,
                height: settings_action_size,
                item_type: UIItemType::WorkspaceSidebarThreadSearch,
            });
            {
                let search_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::Search,
                    search_action_x + ((settings_action_size.saturating_sub(search_icon_size)) / 2),
                    search_action_y + ((settings_action_size.saturating_sub(search_icon_size)) / 2),
                    search_icon_size,
                    if search_action_hovered {
                        foreground
                    } else {
                        muted_fg
                    },
                )?;
            }
            if ssh_action_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        ssh_action_x as f32,
                        ssh_action_y as f32,
                        settings_action_size as f32,
                        settings_action_size as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar ssh hosts hover")?;
            }
            self.ui_items.push(UIItem {
                x: ssh_action_x,
                y: ssh_action_y,
                width: settings_action_size,
                height: settings_action_size,
                item_type: UIItemType::WorkspaceSidebarSshHosts,
            });
            {
                let ssh_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
                self.paint_sidebar_icon(
                    layers,
                    // Same globe the Space menu's "Add Remote Host" uses; a
                    // chain link never said "a machine somewhere else".
                    SvgIcon::Globe,
                    ssh_action_x + ((settings_action_size.saturating_sub(ssh_icon_size)) / 2),
                    ssh_action_y + ((settings_action_size.saturating_sub(ssh_icon_size)) / 2),
                    ssh_icon_size,
                    if ssh_action_hovered {
                        foreground
                    } else {
                        muted_fg
                    },
                )?;
            }
            if overview_action_hovered {
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        overview_action_x as f32,
                        overview_action_y as f32,
                        settings_action_size as f32,
                        settings_action_size as f32,
                    ),
                    chrome.sidebar_button_hover_bg,
                    self.ui_f32(SIDEBAR_ROW_RADIUS + 4.0),
                )
                .context("sidebar live overview hover")?;
            }
            self.ui_items.push(UIItem {
                x: overview_action_x,
                y: overview_action_y,
                width: settings_action_size,
                height: settings_action_size,
                item_type: UIItemType::WorkspaceSidebarLiveOverview,
            });
            {
                let overview_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::Grid2x2,
                    overview_action_x
                        + ((settings_action_size.saturating_sub(overview_icon_size)) / 2),
                    overview_action_y
                        + ((settings_action_size.saturating_sub(overview_icon_size)) / 2),
                    overview_icon_size,
                    if overview_action_hovered {
                        foreground
                    } else {
                        muted_fg
                    },
                )?;
            }
            let settings_icon_size = icon_size.min(settings_row_height.saturating_sub(8));
            let settings_icon_x = settings_row_x + self.ui_px(SIDEBAR_SETTINGS_ICON_EXTRA_INSET);
            let settings_icon_y =
                settings_row_y + ((settings_row_height.saturating_sub(settings_icon_size)) / 2);
            self.paint_sidebar_icon(
                layers,
                SvgIcon::LibraryBig,
                settings_icon_x,
                settings_icon_y,
                settings_icon_size,
                foreground,
            )?;
            // The update capsule, once dismissed, lives on as a dot on the
            // shoulder of the button that leads to settings, ringed in the
            // sidebar background so it reads on the icon rather than in it;
            // red when the install failed.
            // Where the dot goes is recorded either way: the capsule flies
            // there when it is dismissed.
            let dot = (settings_icon_size / 3).max(self.ui_px(5)) as f32;
            let dot_x = (settings_icon_x + settings_icon_size) as f32 - dot * 0.75;
            let dot_y = settings_icon_y as f32 - dot * 0.25;
            self.update_capsule.gear_dot_slot = Some((dot_x + dot / 2.0, dot_y + dot / 2.0, dot));
            if let Some(failed) = crate::termwindow::render::update_capsule::gear_dot() {
                let ring = dot + 2.0 * self.ui_f32(1.5);
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(
                        dot_x - (ring - dot) / 2.0,
                        dot_y - (ring - dot) / 2.0,
                        ring,
                        ring,
                    ),
                    self.sidebar_surface(chrome.workspace_sidebar_bg),
                    ring / 2.0,
                )
                .context("sidebar update dot ring")?;
                self.fill_rounded_rectangle(
                    layers,
                    2,
                    euclid::rect(dot_x, dot_y, dot, dot),
                    if failed { chrome.danger } else { chrome.accent },
                    dot / 2.0,
                )
                .context("sidebar update dot")?;
            }
            if SHOW_SIDEBAR_VIEW_OPTIONS {
                let settings_action_icon_size = settings_icon_size;
                self.paint_sidebar_icon(
                    layers,
                    SvgIcon::SlidersVertical,
                    settings_action_x
                        + ((settings_action_size.saturating_sub(settings_action_icon_size)) / 2),
                    settings_action_y
                        + ((settings_action_size.saturating_sub(settings_action_icon_size)) / 2),
                    settings_action_icon_size,
                    if settings_options_hovered {
                        foreground
                    } else {
                        muted_fg
                    },
                )?;
            }
        }

        // Over everything that covers the list, and not for a neighbouring
        // Space painted only to slide in.
        if self.workspace_sidebar_preview_space_id.is_none() {
            // Clear of the Settings row, which is lifted over the list.
            let list_bottom = if settings_footer_height > 0 {
                (settings_footer_y + self.ui_px(SIDEBAR_SETTINGS_ROW_TOP_PADDING))
                    .saturating_sub(self.ui_px(SIDEBAR_SETTINGS_ROW_LIFT))
                    .min(content_bottom)
            } else {
                content_bottom
            };
            self.paint_sidebar_jump(
                layers,
                current_row,
                JumpList {
                    x: panel_x,
                    width: panel_width,
                    top: list_top,
                    bottom: list_bottom.max(list_top),
                    scroll: scroll_offset,
                    max_scroll,
                    row_height: session_row_height,
                },
                &chrome,
            )?;
        }

        if self.workspace_sidebar_scrollbar_visible() {
            self.update_next_frame_time(self.workspace_sidebar_scrollbar_visible_until);
        }

        if self.workspace_sidebar_scrollbar_visible() {
            let Some(scroll) = self.workspace_sidebar_scroll_geometry() else {
                return Ok(());
            };

            let track_radius = scroll.track_width as f32 / 2.0;
            self.fill_rounded_rectangle(
                layers,
                2,
                euclid::rect(
                    scroll.track_x as f32,
                    scroll.track_y as f32,
                    scroll.track_width as f32,
                    scroll.track_height as f32,
                ),
                chrome.separator,
                track_radius,
            )
            .context("sidebar scroll track")?;

            self.fill_rounded_rectangle(
                layers,
                2,
                euclid::rect(
                    scroll.track_x as f32,
                    scroll.thumb_y,
                    scroll.track_width as f32,
                    scroll.thumb_height,
                ),
                chrome.scrollbar_thumb,
                track_radius,
            )
            .context("sidebar scroll thumb")?;

            let hit_slop = 6usize;
            self.ui_items.push(UIItem {
                x: scroll.track_x.saturating_sub(hit_slop),
                y: scroll.track_y,
                width: scroll.track_width + hit_slop * 2,
                height: scroll.track_height,
                item_type: UIItemType::WorkspaceSidebarScrollTrack,
            });
            self.ui_items.push(UIItem {
                x: scroll.track_x.saturating_sub(hit_slop),
                y: scroll.thumb_y.round().max(0.0) as usize,
                width: scroll.track_width + hit_slop * 2,
                height: scroll.thumb_height.round().max(1.0) as usize,
                item_type: UIItemType::WorkspaceSidebarScrollThumb,
            });
        }

        self.filled_rectangle(
            layers,
            2,
            euclid::rect(
                rect.x.saturating_add(rect.width).saturating_sub(1) as f32,
                0.0,
                1.0,
                rect.y.saturating_add(rect.height) as f32,
            ),
            sidebar_separator,
        )
        .context("sidebar right separator")?;

        Ok(())
    }

    pub(crate) fn show_workspace_sidebar_scrollbar(&mut self) {
        self.workspace_sidebar_scrollbar_visible_until = Some(
            std::time::Instant::now()
                + std::time::Duration::from_millis(SIDEBAR_SCROLLBAR_VISIBLE_MS),
        );
    }

    fn workspace_sidebar_scrollbar_visible(&self) -> bool {
        let actively_dragging = self.dragging.as_ref().is_some_and(|(item, _)| {
            matches!(
                item.item_type,
                UIItemType::WorkspaceSidebarScrollTrack | UIItemType::WorkspaceSidebarScrollThumb
            )
        });
        actively_dragging
            || self
                .workspace_sidebar_scrollbar_visible_until
                .is_some_and(|until| until > std::time::Instant::now())
    }

    /// A sidebar action button: circle or pill, with the same shadow and
    /// hairline border a selected sidebar row gets.
    ///
    /// Four call sites paint these (New Thread and the bell, each of which is
    /// also repainted on a higher layer over the scrolled list, plus the
    /// per-section add buttons), and they used to carry the radius and the
    /// fill separately. Keeping the treatment in one place is what stops one
    /// of them from staying a rounded square when the others become pills.
    pub(crate) fn paint_sidebar_action_button(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        chrome: UiPalette,
        hovered: bool,
        // `dimmed` is a button whose action is unavailable right now -- a
        // detached ref group's add button. It keeps its shape and place so
        // the column stays even, and fades instead of disappearing.
        dimmed: bool,
    ) -> anyhow::Result<()> {
        let radius = rect.height().min(rect.width()) / 2.0;
        let fade = if dimmed { 0.4 } else { 1.0 };
        self.paint_active_surface_shadow(layers, layer_num, rect, radius)?;
        self.fill_rounded_rectangle_with_border(
            layers,
            layer_num,
            rect,
            if hovered {
                chrome.sidebar_button_hover_bg
            } else {
                chrome.sidebar_button_bg.mul_alpha(fade)
            },
            chrome.sidebar_row_active_border.mul_alpha(fade),
            radius,
            CAPSULE_BORDER_WIDTH,
        )
    }

    /// The chrome the sidebar's list paints with. Over a see-through window
    /// its rows' highlights let some of what is behind it through, rather
    /// than standing over it as solid blocks.
    fn sidebar_chrome(&self) -> UiPalette {
        let mut chrome = self.chrome();
        if self.chrome_see_through() {
            for color in [
                &mut chrome.sidebar_row_hover_bg,
                &mut chrome.sidebar_row_pressed_bg,
                &mut chrome.sidebar_row_active_bg,
            ] {
                *color = color.mul_alpha(SEE_THROUGH_SURFACE_ALPHA);
            }
        }
        chrome
    }

    /// The highlight of a selected sidebar row, a pill. Over a see-through
    /// window there is no shadow under it to darken what shows through, and
    /// its edge is a ring, the clearer for it, drawn round the fill rather
    /// than under it.
    fn paint_sidebar_selected_row(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        rect: RectF,
        fill: LinearRgba,
        border: LinearRgba,
    ) -> anyhow::Result<()> {
        let radius = rect.height() / 2.0;
        if self.chrome_see_through() {
            let Some(gl_state) = self.render_state.as_ref() else {
                return Ok(());
            };
            let boost = SEE_THROUGH_BORDER_BOOST.min(1.0 / border.3.max(f32::EPSILON));
            return DrawContext::new(gl_state, self.dimensions, &self.render_metrics)
                .draw_rounded_frame(
                    layers,
                    0,
                    rect.min_x(),
                    rect.min_y(),
                    rect.width(),
                    rect.height(),
                    fill,
                    border.mul_alpha(boost),
                    radius,
                );
        }
        self.paint_active_surface_shadow(layers, 0, rect, radius)?;
        self.fill_rounded_rectangle_with_border(
            layers,
            0,
            rect,
            fill,
            border,
            radius,
            CAPSULE_BORDER_WIDTH,
        )
    }

    /// One of the sidebar's add buttons: an action button whose circle shows
    /// only under the pointer, unless Settings › Accessibility keeps button
    /// shapes.
    fn paint_sidebar_icon_button(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        chrome: UiPalette,
        hovered: bool,
        dimmed: bool,
    ) -> anyhow::Result<()> {
        if !hovered && !crate::native_settings::show_button_shapes() {
            return Ok(());
        }
        self.paint_sidebar_action_button(layers, layer_num, rect, chrome, hovered, dimmed)
    }

    pub(crate) fn fill_rounded_rectangle(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        color: LinearRgba,
        radius: f32,
    ) -> anyhow::Result<()> {
        self.fill_vertically_rounded_rectangle(layers, layer_num, rect, color, radius, true, true)
    }

    /// Fill a rectangle whose top and bottom corner pairs can be rounded
    /// independently. Scrollable surfaces use this to preserve the real edge's
    /// corners while keeping a viewport-created cut edge square.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn fill_vertically_rounded_rectangle(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        color: LinearRgba,
        radius: f32,
        round_top: bool,
        round_bottom: bool,
    ) -> anyhow::Result<()> {
        self.fill_rounded_rectangle_corners(
            layers,
            layer_num,
            rect,
            color,
            radius,
            RoundedCorners::vertical(round_top, round_bottom),
        )
    }

    /// Fill a rectangle rounding only the corners `corners` names.
    ///
    /// A surface clipped by a viewport passes the flags for the edges that are
    /// really its own: the cut edge then comes out square, so a half-scrolled
    /// tab reads as running under the boundary instead of as a genuinely
    /// narrower tab.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn fill_rounded_rectangle_corners(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        color: LinearRgba,
        radius: f32,
        corners: RoundedCorners,
    ) -> anyhow::Result<()> {
        let radius = snapped_rounded_corner_radius(rect, radius);
        // Sub-pixel radii round down to a 0px corner sprite (which panics when
        // building its pixmap), so fall back to a plain rectangle below ~1px.
        if !(radius >= 1.0) {
            self.filled_rectangle(layers, layer_num, rect, color)?;
            return Ok(());
        }

        let corner_size = euclid::size2(radius, radius);
        for (rounded, sprite, x, y) in [
            (
                corners.top_left,
                TOP_LEFT_ROUNDED_CORNER,
                rect.min_x(),
                rect.min_y(),
            ),
            (
                corners.top_right,
                TOP_RIGHT_ROUNDED_CORNER,
                rect.max_x() - radius,
                rect.min_y(),
            ),
            (
                corners.bottom_left,
                BOTTOM_LEFT_ROUNDED_CORNER,
                rect.min_x(),
                rect.max_y() - radius,
            ),
            (
                corners.bottom_right,
                BOTTOM_RIGHT_ROUNDED_CORNER,
                rect.max_x() - radius,
                rect.max_y() - radius,
            ),
        ] {
            if rounded {
                self.poly_quad(
                    layers,
                    layer_num,
                    euclid::point2(x, y),
                    sprite,
                    0,
                    corner_size,
                    color,
                )?
                .set_grayscale();
            } else {
                self.filled_rectangle(
                    layers,
                    layer_num,
                    euclid::rect(x, y, radius, radius),
                    color,
                )?;
            }
        }

        self.filled_rectangle(
            layers,
            layer_num,
            euclid::rect(
                rect.min_x() + radius,
                rect.min_y(),
                rect.width() - radius * 2.0,
                rect.height(),
            ),
            color,
        )?;
        self.filled_rectangle(
            layers,
            layer_num,
            euclid::rect(
                rect.min_x(),
                rect.min_y() + radius,
                radius,
                rect.height() - radius * 2.0,
            ),
            color,
        )?;
        self.filled_rectangle(
            layers,
            layer_num,
            euclid::rect(
                rect.max_x() - radius,
                rect.min_y() + radius,
                radius,
                rect.height() - radius * 2.0,
            ),
            color,
        )?;

        Ok(())
    }

    pub(crate) fn fill_rounded_rectangle_with_border(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        layer_num: usize,
        rect: RectF,
        fill: LinearRgba,
        border: LinearRgba,
        radius: f32,
        border_width: f32,
    ) -> anyhow::Result<()> {
        let border_width = border_width
            .max(0.0)
            .min(rect.width() / 2.0)
            .min(rect.height() / 2.0);
        if border_width <= 0.0 {
            return self.fill_rounded_rectangle(layers, layer_num, rect, fill, radius);
        }

        self.fill_rounded_rectangle(layers, layer_num, rect, border, radius)?;
        self.fill_rounded_rectangle(
            layers,
            layer_num,
            euclid::rect(
                rect.min_x() + border_width,
                rect.min_y() + border_width,
                (rect.width() - border_width * 2.0).max(0.0),
                (rect.height() - border_width * 2.0).max(0.0),
            ),
            fill,
            (radius - border_width).max(0.0),
        )
    }

    fn paint_sidebar_project_icon(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        project: &workspace_threads::ProjectView,
        x: usize,
        y: usize,
        size: usize,
        color: LinearRgba,
    ) -> anyhow::Result<()> {
        let remote_brand = if project.is_remote {
            project.distro.as_deref().and_then(distro_to_icon)
        } else {
            None
        };
        if let Some(brand) = remote_brand {
            // Detected remote OS: show its brand logo in full color.
            return self.paint_sidebar_brand_icon(layers, brand, x, y, size);
        }
        let icon = if project.is_remote {
            // Remote host without a detected OS: a globe marks it as
            // distinct from local folder projects in the mixed list.
            SvgIcon::Globe
        } else if project.threads_collapsed {
            SvgIcon::Folder
        } else {
            SvgIcon::FolderOpen
        };
        self.paint_sidebar_icon(layers, icon, x, y, size, color)
    }

    /// Send the rows around the one being dragged where the drop would
    /// leave them, the gap showing where it would land.
    pub(crate) fn aim_sidebar_make_way(&mut self) {
        let going = self.sidebar_make_way_shifts().unwrap_or_default();
        self.sidebar_make_way.aim(going);
    }

    fn sidebar_make_way_shifts(&self) -> Option<Vec<(String, f32)>> {
        let drag = self.sidebar_row_drag.as_ref().filter(|drag| drag.active)?;
        let before = drag.target.as_ref()?.before.as_deref();
        let rect = self.workspace_sidebar_rect()?;
        let ui_cell_height = self.workspace_sidebar_cell_height();
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        let layout = self.workspace_sidebar_layout(rect, ui_cell_height, icon_size);
        let row = layout.row_height + self.ui_px(SIDEBAR_ROW_GAP);

        let mux = Mux::get();
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let workspaces = mux.iter_workspaces();
        let view = self.workspace_sidebar_view(&active_workspace, &workspaces);

        match &drag.kind {
            SidebarRowKind::Thread {
                thread_id,
                project_id,
            } => {
                let own = view
                    .projects
                    .iter()
                    .map(|project| project.threads.iter().map(|t| t.id.as_str()).collect())
                    .find(|list: &Vec<&str>| list.contains(&thread_id.as_str()));
                if let Some(list) = own {
                    return Some(shifts_for_move(&list, thread_id, before, row as f32));
                }
                let refs =
                    workspace_threads::space_thread_refs_from(&self.active_space_id, project_id);
                let refs: Vec<&str> = refs.iter().map(String::as_str).collect();
                Some(shifts_for_move(&refs, thread_id, before, row as f32))
            }
            SidebarRowKind::Project(key) | SidebarRowKind::RefGroup(key) => {
                // A folder moves whole, past folders it takes up the room of.
                let folders: Vec<(&str, usize)> = view
                    .display_order
                    .iter()
                    .filter_map(|folder| match *folder {
                        workspace_threads::SidebarFolder::Project(index) => {
                            let project = view.projects.get(index)?;
                            let rows = if project.threads_collapsed {
                                0
                            } else {
                                project.threads.len()
                            };
                            (!project.is_archived).then_some((project.id.as_str(), rows))
                        }
                        workspace_threads::SidebarFolder::RefGroup(index) => {
                            let group = view.ref_groups.get(index)?;
                            let rows = if group.collapsed {
                                0
                            } else {
                                group.threads.len()
                            };
                            Some((group.key.as_str(), rows))
                        }
                    })
                    .collect();
                let rows = folders.iter().find(|(id, _)| id == key)?.1;
                let by = (rows + 1) * row + self.ui_px(WORKSPACE_GROUP_EXTRA_GAP);
                let list: Vec<&str> = folders.iter().map(|(id, _)| *id).collect();
                Some(shifts_for_move(&list, key, before, by as f32))
            }
        }
    }

    /// Where a row rests in the list as painted this frame.
    fn sidebar_row_rest(&self, kind: &SidebarRowKind) -> Option<(f32, f32)> {
        let space_prefix = format!("{}::", self.active_space_id);
        self.ui_items
            .iter()
            .find(|item| match (&item.item_type, kind) {
                (UIItemType::WorkspaceThread(id), SidebarRowKind::Thread { thread_id, .. }) => {
                    id == thread_id
                }
                (UIItemType::Project(id), SidebarRowKind::Project(project_id)) => id == project_id,
                (UIItemType::ThreadRefGroupToggle { key, .. }, SidebarRowKind::RefGroup(raw)) => {
                    key.strip_prefix(&space_prefix).unwrap_or(key.as_str()) == raw.as_str()
                }
                _ => false,
            })
            .map(|item| (item.x as f32, item.y as f32))
    }

    /// A thread's icon and name, for a row `height` tall with its top left
    /// at the origin: what a card torn off the row keeps of it.
    pub(crate) fn paint_thread_row_title(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        thread_id: &str,
        title: &str,
        width: usize,
        height: usize,
        surface: LinearRgba,
    ) -> anyhow::Result<()> {
        let chrome = self.chrome();
        let ui_font = self
            .fonts
            .title_font_with_size(crate::native_settings::sidebar_font_size(
                &crate::native_settings::load_shared(),
            ))
            .context("thread row title font")?;
        let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
        let inset = self.ui_px(SIDEBAR_INSET);
        let text_y = height.saturating_sub(ui_metrics.cell_size.height as usize) / 2;
        let mux = Mux::get();
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let view = self.workspace_sidebar_view(&active_workspace, &mux.iter_workspaces());
        let suppress_own_active = self.sidebar_own_active_is_stale(&view, &active_workspace);
        let Some((thread, dimmed, suppress_active)) =
            thread_row_in_view(&view, thread_id, suppress_own_active)
        else {
            return Ok(());
        };
        let marks = self.sidebar_thread_row_marks()?;
        let (text_x, marks_right) = self.paint_sidebar_thread_marks(
            layers,
            &marks,
            thread,
            inset + 2,
            width.saturating_sub(inset),
            0,
            height,
            surface,
            false,
            dimmed,
            self.is_workspace_sidebar_thread_selected(thread, suppress_active),
            1.0,
            &chrome,
            chrome.text,
        )?;
        self.paint_sidebar_name(
            layers,
            &ui_font,
            ui_metrics,
            title,
            text_x,
            text_y,
            marks_right.saturating_sub(text_x + inset),
            if dimmed {
                chrome.secondary_text.mul_alpha(0.7)
            } else {
                chrome.text
            },
        )
    }

    /// The row a reorder carries, laid out as the list lays it out, on a
    /// surface of its own: at rest most rows have none to lift. Its buttons
    /// stay behind: nothing on it can be pressed while it is carried. Let
    /// go of, it goes on to its place, and such a surface fades as it gets
    /// there, so that the row it becomes is no different.
    pub(crate) fn paint_sidebar_row_ghost(&mut self, now: Instant) -> anyhow::Result<()> {
        if self.paint_thread_tear_off(now)? {
            return Ok(());
        }
        let drag = self.sidebar_row_drag.as_ref().filter(|drag| drag.active);
        let (kind, title, grip, origin, landed) = if let Some(state) = drag {
            let window = (self.dimensions.pixel_width, self.dimensions.pixel_height);
            let origin = state.grip.origin(state.current, window);
            (state.kind.clone(), state.title.clone(), state.grip, origin, 0.0)
        } else if let Some(landing) = self.sidebar_row_landing.clone() {
            let Some(rest) = self.sidebar_row_rest(&landing.what) else {
                self.sidebar_row_landing = None;
                return Ok(());
            };
            let landed = landing.progress(now);
            let origin = landing.place(rest, now);
            // Its last frame here is the row's first frame back, or there
            // would be one with neither.
            if landed >= 1.0 {
                self.sidebar_row_landing = None;
            }
            self.update_next_frame_time(Some(now + Duration::from_millis(16)));
            (landing.what, landing.title, landing.grip, origin, landed)
        } else {
            return Ok(());
        };
        let Some(rect) = self.workspace_sidebar_rect() else {
            return Ok(());
        };
        let chrome = self.chrome();
        let ui_font = self
            .fonts
            .title_font_with_size(crate::native_settings::sidebar_font_size(
                &crate::native_settings::load_shared(),
            ))
            .context("sidebar row ghost font")?;
        let ui_metrics = RenderMetrics::with_font_metrics(&ui_font.metrics());
        let ui_cell_height = ui_metrics.cell_size.height as usize;
        let icon_size = (ui_cell_height + self.ui_px(12)).clamp(self.ui_px(30), self.ui_px(36));
        // Not the row's hit rect, which the list's ends cut.
        let height = self
            .workspace_sidebar_layout(rect, ui_cell_height, icon_size)
            .row_height;
        let grip = crate::termwindow::DragGrip { height, ..grip };
        let width = grip.width;
        let inset = self.ui_px(SIDEBAR_INSET);
        let text_y = height.saturating_sub(ui_cell_height) / 2;
        let surface = crate::termwindow::render::paint::drag_ghost_surface(
            chrome.sidebar_row_active_bg,
            self.sidebar_surface(chrome.workspace_sidebar_bg),
        );

        let mux = Mux::get();
        let active_workspace = self
            .current_mux_workspace()
            .unwrap_or_else(|| mux.active_workspace());
        let workspaces = mux.iter_workspaces();
        let view = self.workspace_sidebar_view(&active_workspace, &workspaces);
        let suppress_own_active = self.sidebar_own_active_is_stale(&view, &active_workspace);

        // Whether the row has a surface of its own to come down onto.
        let mut rests_selected = false;
        let mut content = HeapQuadAllocator::default();
        let mut layers = TripleLayerQuadAllocator::Heap(&mut content);
        // A folder header's name; says where its icon goes. Its chevron
        // shows only under the pointer, which a carried row is not under.
        let folder_row = |layers: &mut TripleLayerQuadAllocator,
                          fg: LinearRgba|
         -> anyhow::Result<(usize, usize)> {
            let icon_x = inset;
            let text_x = icon_x + icon_size + self.ui_px(SIDEBAR_ICON_GAP);
            self.paint_sidebar_name(
                layers,
                &ui_font,
                ui_metrics,
                &title,
                text_x,
                text_y,
                width.saturating_sub(text_x + inset),
                fg,
            )?;
            Ok((icon_x, height.saturating_sub(icon_size) / 2))
        };
        match &kind {
            SidebarRowKind::Thread { thread_id, .. } => {
                let row = thread_row_in_view(&view, thread_id, suppress_own_active);
                let Some((thread, dimmed, suppress_active)) = row else {
                    return Ok(());
                };
                rests_selected = self.is_workspace_sidebar_thread_selected(thread, suppress_active);
                let marks = self.sidebar_thread_row_marks()?;
                let (text_x, marks_right) = self.paint_sidebar_thread_marks(
                    &mut layers,
                    &marks,
                    thread,
                    inset + 2,
                    width.saturating_sub(inset),
                    0,
                    height,
                    surface,
                    true,
                    dimmed,
                    rests_selected,
                    1.0,
                    &chrome,
                    chrome.text,
                )?;
                self.paint_sidebar_name(
                    &mut layers,
                    &ui_font,
                    ui_metrics,
                    &title,
                    text_x,
                    text_y,
                    marks_right.saturating_sub(text_x + inset),
                    if dimmed {
                        chrome.secondary_text.mul_alpha(0.7)
                    } else {
                        chrome.text
                    },
                )?;
            }
            SidebarRowKind::Project(project_id) => {
                let Some(project) = view.projects.iter().find(|p| p.id == *project_id) else {
                    return Ok(());
                };
                let fg = chrome.secondary_text;
                let (x, y) = folder_row(&mut layers, fg)?;
                self.paint_sidebar_project_icon(&mut layers, project, x, y, icon_size, fg)?;
            }
            SidebarRowKind::RefGroup(key) => {
                let Some(group) = view.ref_groups.iter().find(|group| group.key == *key) else {
                    return Ok(());
                };
                let fg = if group.attached {
                    chrome.secondary_text
                } else {
                    chrome.secondary_text.mul_alpha(0.6)
                };
                let (x, y) = folder_row(&mut layers, fg)?;
                let icon = if group.server_folder {
                    SvgIcon::Server
                } else {
                    SvgIcon::Link2
                };
                self.paint_sidebar_icon(&mut layers, icon, x, y, icon_size, fg)?;
            }
        }
        drop(layers);

        let lifted = if rests_selected { 1.0 } else { 1.0 - landed };
        self.paint_drag_ghost(
            &content,
            origin,
            grip,
            surface.mul_alpha(lifted),
            chrome.sidebar_row_active_border.mul_alpha(lifted),
            lifted,
            height as f32 / 2.0,
        )
    }

    /// A folder's or a carried row's name: as a thread row's, it goes out
    /// when it is too long.
    #[allow(clippy::too_many_arguments)]
    fn paint_sidebar_name(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        font: &Rc<LoadedFont>,
        metrics: RenderMetrics,
        name: &str,
        x: usize,
        y: usize,
        width: usize,
        foreground: LinearRgba,
    ) -> anyhow::Result<()> {
        self.paint_title_fading_with(
            layers,
            font,
            &metrics,
            name,
            x,
            y,
            width,
            foreground,
            SIDEBAR_TITLE_FADE_GAP,
            |fade| fade,
        )
    }

    pub(crate) fn paint_sidebar_text(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        font: &Rc<LoadedFont>,
        metrics: RenderMetrics,
        text: &str,
        x: usize,
        y: usize,
        width: usize,
        foreground: LinearRgba,
    ) -> anyhow::Result<()> {
        if text.is_empty() || width == 0 {
            return Ok(());
        }

        let text = self.ellipsize_ui_text(font, text, width)?;
        if text.is_empty() {
            return Ok(());
        }

        self.paint_ui_title_text_cached(layers, font, &metrics, &text, x, y, width, foreground)?;
        Ok(())
    }

    pub(crate) fn ellipsize_ui_text<'a>(
        &self,
        font: &Rc<LoadedFont>,
        text: &'a str,
        width: usize,
    ) -> anyhow::Result<Cow<'a, str>> {
        let max_width = width as f32;
        if max_width <= 0.0 {
            return Ok(Cow::Borrowed(""));
        }

        // Shape the whole string ONCE via the shared shape cache, then measure
        // and cut from the cached glyph run. The previous implementation
        // re-measured a growing prefix grapheme-by-grapheme, each re-shaping the
        // string (`sidebar_text_width`), which was O(N^2) harfbuzz work per row
        // every frame and made the search list (long `display_path` names) crawl.
        let metrics = RenderMetrics::with_font_metrics(&font.metrics());
        let (shaped, _) = self.cached_ui_shape(font, &metrics, text)?;
        let total: f32 = shaped
            .iter()
            .map(|info| info.glyph.x_advance.get() as f32)
            .sum();
        if total <= max_width {
            return Ok(Cow::Borrowed(text));
        }

        const ELLIPSIS: &str = "...";
        let ellipsis_w = self.sidebar_text_width(font, ELLIPSIS)?;
        if ellipsis_w > max_width {
            // Not even the ellipsis fits; emit as many dots as do (matches the
            // previous degenerate fallback).
            let dot_w = self.sidebar_text_width(font, ".")?;
            let dots = if dot_w > 0.0 {
                ((max_width / dot_w).floor() as usize).min(ELLIPSIS.len())
            } else {
                0
            };
            return Ok(Cow::Owned(".".repeat(dots)));
        }

        // Keep the largest prefix (at a glyph-cluster boundary) that still
        // leaves room for the ellipsis.
        let budget = max_width - ellipsis_w;
        let glyphs: Vec<(f32, usize)> = shaped
            .iter()
            .map(|info| (info.glyph.x_advance.get() as f32, info.cluster))
            .collect();
        let cut_byte = ellipsize_cut_byte(&glyphs, text.len(), budget).min(text.len());

        // Checked whole, as it will be drawn; a run that cannot be measured
        // keeps the cut as made.
        Ok(Cow::Owned(crate::ui::draw::fit_ellipsized(
            text,
            cut_byte,
            max_width,
            |candidate| self.sidebar_text_width(font, candidate).unwrap_or(0.0),
        )))
    }

    pub(crate) fn sidebar_text_width(
        &self,
        font: &Rc<LoadedFont>,
        text: &str,
    ) -> anyhow::Result<f32> {
        // Route through the shared shape cache so repeated width queries (the
        // ellipsize fit-check, button sizing, etc.) become cache hits and stay
        // consistent with the cached painters. Metrics are derived from the font
        // exactly as the sidebar paint path does
        // (`RenderMetrics::with_font_metrics(&ui_font.metrics())`).
        let metrics = RenderMetrics::with_font_metrics(&font.metrics());
        self.cached_ui_text_advance(font, &metrics, text)
    }

    /// `id` is laid out at `place` in the live list, counted from the top of
    /// `within` (a folder's id, or "" for the list itself), and at `in_list`
    /// from the top of the list. Moved there by the list since the frame
    /// before, it glides from where it was; `carried` is how far its folder
    /// was just sent gliding. Returns how far it was sent itself.
    #[allow(clippy::too_many_arguments)]
    fn note_sidebar_row(
        &mut self,
        id: &str,
        within: &str,
        place: usize,
        in_list: usize,
        carried: f32,
        tracked: bool,
        glide: bool,
    ) -> f32 {
        if !tracked {
            return 0.0;
        }
        let moved = self.sidebar_row_places.note(
            id,
            within,
            place as f32,
            in_list as f32,
            carried,
        );
        match moved {
            Some(by) if glide => {
                self.sidebar_make_way.glide(id, by);
                by
            }
            _ => 0.0,
        }
    }

    /// A folder's rows, recorded apart: replayed as faded as the folder is
    /// closed, and the list after them pulled up by as much of them as is.
    ///
    /// Cut to as much of them as is open, from `top` on screen and within
    /// `list` (its top and bottom), so that the list coming up after them
    /// never runs over what is still fading.
    #[allow(clippy::too_many_arguments)]
    fn show_folder_rows(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        rows: &HeapQuadAllocator,
        open: f32,
        virtual_y: &mut usize,
        rows_start: usize,
        top: f32,
        list: (f32, f32),
    ) -> anyhow::Result<()> {
        if open >= 1.0 {
            return rows.apply_to(layers);
        }
        let height = (virtual_y.saturating_sub(rows_start) as f32 * open).round();
        *virtual_y = rows_start + height as usize;
        let clip_top = top.max(list.0);
        let clip_bottom = (top + height).min(list.1);
        if clip_bottom <= clip_top {
            return Ok(());
        }
        let clip = QuadClipRect::from_top_left_pixels(
            0.0,
            clip_top,
            self.dimensions.pixel_width as f32,
            clip_bottom,
            &self.dimensions,
        );
        rows.apply_to_clipped(layers, clip, open)
    }

    /// A folder's chevron by its add button: faded in as far as the pointer
    /// has brought it, turned as far as the folder has opened.
    fn paint_folder_chevron(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        (x, y, size): (usize, usize, usize),
        shown: f32,
        turned: f32,
        color: LinearRgba,
    ) -> anyhow::Result<()> {
        use crate::termwindow::sidebar_disclosure::{chevron_frame, CHEVRON_FRAMES};
        if shown <= 0.0 {
            return Ok(());
        }
        let left_offset = self.dimensions.pixel_width as f32 / 2.0;
        let top_offset = self.dimensions.pixel_height as f32 / 2.0;
        let gl_state = self.render_state.as_ref().unwrap();
        let sprite = gl_state
            .glyph_cache
            .borrow_mut()
            .cached_rotated_svg_icon(
                SvgIcon::ChevronRight,
                size,
                chevron_frame(turned),
                CHEVRON_FRAMES,
            )?
            .texture_coords();
        let color = color.mul_alpha(shown);
        let mut quad = layers.allocate(2)?;
        quad.set_position(
            x as f32 - left_offset,
            y as f32 - top_offset,
            x as f32 + size as f32 - left_offset,
            y as f32 + size as f32 - top_offset,
        );
        quad.set_texture(sprite);
        quad.set_fg_color(color);
        quad.set_alt_color_and_mix_value(color, 0.0);
        quad.set_hsv(None);
        quad.set_grayscale();
        Ok(())
    }

    pub(crate) fn paint_sidebar_icon(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        icon: SvgIcon,
        x: usize,
        y: usize,
        size: usize,
        color: LinearRgba,
    ) -> anyhow::Result<()> {
        let left_offset = self.dimensions.pixel_width as f32 / 2.0;
        let top_offset = self.dimensions.pixel_height as f32 / 2.0;
        let gl_state = self.render_state.as_ref().unwrap();
        let sprite = gl_state
            .glyph_cache
            .borrow_mut()
            .cached_svg_icon(icon, size)?
            .texture_coords();

        let mut quad = layers.allocate(2)?;
        quad.set_position(
            x as f32 - left_offset,
            y as f32 - top_offset,
            x as f32 + size as f32 - left_offset,
            y as f32 + size as f32 - top_offset,
        );
        quad.set_texture(sprite);
        quad.set_fg_color(color);
        quad.set_alt_color_and_mix_value(color, 0.0);
        quad.set_hsv(None);
        quad.set_grayscale();

        Ok(())
    }

    /// Paint a full-color brand/OS logo (the brand color is baked into the
    /// sprite, so unlike [`Self::paint_sidebar_icon`] it is not tinted).
    pub(crate) fn paint_sidebar_brand_icon(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        icon: BrandIcon,
        x: usize,
        y: usize,
        size: usize,
    ) -> anyhow::Result<()> {
        let left_offset = self.dimensions.pixel_width as f32 / 2.0;
        let top_offset = self.dimensions.pixel_height as f32 / 2.0;
        let gl_state = self.render_state.as_ref().unwrap();
        let sprite = gl_state
            .glyph_cache
            .borrow_mut()
            .cached_brand_icon(icon, size)?
            .texture_coords();

        let mut quad = layers.allocate(2)?;
        quad.set_position(
            x as f32 - left_offset,
            y as f32 - top_offset,
            x as f32 + size as f32 - left_offset,
            y as f32 + size as f32 - top_offset,
        );
        quad.set_texture(sprite);
        quad.set_hsv(None);
        quad.set_has_color(true);
        quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));

        Ok(())
    }

    pub(crate) fn paint_sidebar_material_icon(
        &self,
        layers: &mut TripleLayerQuadAllocator,
        icon: MaterialIcon,
        x: usize,
        y: usize,
        size: usize,
    ) -> anyhow::Result<()> {
        let left_offset = self.dimensions.pixel_width as f32 / 2.0;
        let top_offset = self.dimensions.pixel_height as f32 / 2.0;
        let gl_state = self.render_state.as_ref().unwrap();
        let sprite = gl_state
            .glyph_cache
            .borrow_mut()
            .cached_material_icon(icon, size)?
            .texture_coords();

        let mut quad = layers.allocate(2)?;
        quad.set_position(
            x as f32 - left_offset,
            y as f32 - top_offset,
            x as f32 + size as f32 - left_offset,
            y as f32 + size as f32 - top_offset,
        );
        quad.set_texture(sprite);
        quad.set_hsv(None);
        quad.set_has_color(true);
        quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));

        Ok(())
    }
}

/// Largest byte prefix (at a glyph-cluster boundary) whose cumulative advance
/// fits in `budget`. `glyphs` are `(advance_px, cluster)` pairs in visual order,
/// where `cluster` is the source byte offset of each glyph. Cutting at the
/// *next* glyph's cluster guarantees we never split a multi-byte character or a
/// shaped cluster. Used by `ellipsize_ui_text` to truncate in a single
/// shaping pass instead of re-shaping a growing prefix per grapheme.
fn ellipsize_cut_byte(glyphs: &[(f32, usize)], text_len: usize, budget: f32) -> usize {
    let mut acc = 0.0f32;
    let mut cut = 0usize;
    for idx in 0..glyphs.len() {
        let advance = glyphs[idx].0;
        if acc + advance > budget {
            break;
        }
        acc += advance;
        cut = glyphs.get(idx + 1).map(|next| next.1).unwrap_or(text_len);
    }
    cut
}

/// Corner sprites are cached at integral physical-pixel sizes. Keep the quad
/// geometry on that same grid so fractional radii cannot expose the joins
/// between the four corners and the center rectangles on 1x displays.
/// Which corners of a rounded rectangle actually get rounded.
///
/// A scrollable surface keeps the corners of its real edges and leaves a
/// viewport-created cut edge square. (A surface cut *horizontally* does not
/// need this: it is recorded at full width and clipped on replay, which both
/// gives the cut a hard edge and keeps the radius the one the full shape would
/// have had — see `paint_tab_capsule`.)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct RoundedCorners {
    pub top_left: bool,
    pub top_right: bool,
    pub bottom_left: bool,
    pub bottom_right: bool,
}

impl RoundedCorners {
    pub(crate) fn vertical(round_top: bool, round_bottom: bool) -> Self {
        Self {
            top_left: round_top,
            top_right: round_top,
            bottom_left: round_bottom,
            bottom_right: round_bottom,
        }
    }

}

fn snapped_rounded_corner_radius(rect: RectF, radius: f32) -> f32 {
    radius
        .min(rect.width() / 2.0)
        .min(rect.height() / 2.0)
        .floor()
}

fn notification_snapshot_has_new_entry(
    previous: Option<&HashMap<String, workspace_threads::WorkspaceThreadWorkStatus>>,
    current: &HashMap<String, workspace_threads::WorkspaceThreadWorkStatus>,
) -> bool {
    let Some(previous) = previous else {
        return false;
    };
    current
        .iter()
        .any(|(thread_id, status)| previous.get(thread_id) != Some(status))
}

fn notification_badge_pulse_phase(elapsed: Duration) -> Option<f32> {
    if elapsed >= NOTIFICATION_BADGE_PULSE_DURATION {
        return None;
    }
    let total_progress = elapsed.as_secs_f32() / NOTIFICATION_BADGE_PULSE_DURATION.as_secs_f32();
    Some((total_progress * NOTIFICATION_BADGE_PULSE_COUNT).fract())
}

/// A thread's row in `view`: the thread, whether it is dimmed, and whether its
/// selection is suppressed.
fn thread_row_in_view<'a>(
    view: &'a workspace_threads::WorkspaceThreadsView,
    thread_id: &str,
    suppress_own_active: bool,
) -> Option<(&'a workspace_threads::WorkspaceThreadView, bool, bool)> {
    let own = view
        .pinned_threads
        .iter()
        .chain(view.projects.iter().flat_map(|project| &project.threads))
        .find(|thread| thread.id == thread_id)
        .map(|thread| (thread, false, suppress_own_active));
    own.or_else(|| {
        view.ref_groups
            .iter()
            .flat_map(|group| &group.threads)
            .find(|reference| reference.thread.id == thread_id)
            .map(|reference| {
                let dimmed = reference.dangling || !reference.origin_domain_attached;
                (&reference.thread, dimmed, false)
            })
    })
}

/// The `shown` state a sidebar toggle should move to.
///
/// Split out from [`TermWindow::toggle_workspace_sidebar`] so the hover-reveal
/// case has one authoritative answer. The toggle acts on the DOCKED state: a
/// hover reveal is only a preview, so clicking the button there pins the
/// panel open instead of retracting it — matching its "open" icon, which is
/// keyed to the same state ([`TermWindow::workspace_sidebar_toggle_icon`]).
fn workspace_sidebar_toggle_target(collapsed: bool, _hover_presented: bool) -> bool {
    collapsed
}

#[cfg(test)]
mod tests {
    use super::{
        ellipsize_cut_byte, notification_badge_pulse_phase, notification_snapshot_has_new_entry,
        snapped_rounded_corner_radius, workspace_sidebar_toggle_target,
        NOTIFICATION_BADGE_PULSE_DURATION,
    };
    use crate::workspace_threads::WorkspaceThreadWorkStatus;
    use std::collections::HashMap;
    use std::time::Duration;

    /// The toggle acts on the DOCKED state and its icon is keyed to the same
    /// state. A hover reveal is only a preview: hovering the toggle button
    /// pops the panel out, and the click that follows must pin it open — a
    /// hover-then-click that merely retracted the panel would make the
    /// button do nothing useful while the panel is previewed.
    #[test]
    fn toggling_pins_a_hover_revealed_sidebar_open() {
        // (collapsed, hover_presented) -> shown
        assert!(
            !workspace_sidebar_toggle_target(false, false),
            "docked panel should collapse"
        );
        assert!(
            workspace_sidebar_toggle_target(true, false),
            "collapsed panel should dock"
        );
        assert!(
            workspace_sidebar_toggle_target(true, true),
            "hover-revealed panel should dock (pin open), not retract"
        );
        assert!(
            !workspace_sidebar_toggle_target(false, true),
            "docked panel should still collapse regardless of hover state"
        );
    }

    // Build (advance, cluster) pairs for an ASCII or per-char string where every
    // char is one glyph of `advance` px and the cluster is its byte offset.
    fn glyphs_per_char(text: &str, advance: f32) -> Vec<(f32, usize)> {
        text.char_indices()
            .map(|(byte, _)| (advance, byte))
            .collect()
    }

    #[test]
    fn cut_keeps_whole_prefix_when_everything_fits() {
        let text = "abcdef";
        let glyphs = glyphs_per_char(text, 10.0);
        // budget large enough for all 6 glyphs.
        assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 1000.0), text.len());
    }

    #[test]
    fn cut_stops_at_budget() {
        let text = "abcdef";
        let glyphs = glyphs_per_char(text, 10.0);
        // budget for ~3.5 glyphs -> keep 3 (bytes 0..3).
        assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 35.0), 3);
    }

    #[test]
    fn cut_never_splits_multibyte_chars() {
        // "ab你好cd": bytes a=0 b=1 你=2..5 好=5..8 c=8 d=9 (你/好 are 3 bytes each).
        let text = "ab你好cd";
        let glyphs = glyphs_per_char(text, 10.0);
        // Budget for 3 glyphs (a, b, 你) -> cut at byte 5 (start of 好), the
        // boundary AFTER the full multi-byte char, never inside it.
        let cut = ellipsize_cut_byte(&glyphs, text.len(), 35.0);
        assert_eq!(cut, 5);
        assert!(text.is_char_boundary(cut));
        assert_eq!(&text[..cut], "ab你");
    }

    #[test]
    fn cut_is_zero_when_nothing_fits() {
        let text = "abc";
        let glyphs = glyphs_per_char(text, 10.0);
        assert_eq!(ellipsize_cut_byte(&glyphs, text.len(), 5.0), 0);
    }

    #[test]
    fn rounded_corner_radius_matches_integral_corner_sprite_size() {
        let odd_height = euclid::rect(0.0, 0.0, 215.0, 33.0);
        let even_height = euclid::rect(0.0, 0.0, 215.0, 34.0);

        assert_eq!(snapped_rounded_corner_radius(odd_height, 999.0), 16.0);
        assert_eq!(snapped_rounded_corner_radius(even_height, 999.0), 17.0);
        assert_eq!(snapped_rounded_corner_radius(even_height, 10.75), 10.0);
    }

    #[test]
    fn notification_snapshot_ignores_initial_state_and_detects_replacements() {
        let current = HashMap::from([(
            "thread-a".to_string(),
            WorkspaceThreadWorkStatus::FinishedUnseen,
        )]);
        assert!(!notification_snapshot_has_new_entry(None, &current));
        assert!(!notification_snapshot_has_new_entry(
            Some(&current),
            &current
        ));

        // Total count is still one, but a different thread completed.
        let replacement = HashMap::from([(
            "thread-b".to_string(),
            WorkspaceThreadWorkStatus::FinishedUnseen,
        )]);
        assert!(notification_snapshot_has_new_entry(
            Some(&current),
            &replacement
        ));
    }

    #[test]
    fn notification_snapshot_detects_status_transition() {
        let attention = HashMap::from([(
            "thread-a".to_string(),
            WorkspaceThreadWorkStatus::NeedsAttention,
        )]);
        let finished = HashMap::from([(
            "thread-a".to_string(),
            WorkspaceThreadWorkStatus::FinishedUnseen,
        )]);
        assert!(notification_snapshot_has_new_entry(
            Some(&attention),
            &finished
        ));
    }

    #[test]
    fn notification_badge_pulses_three_times_then_stops() {
        assert_eq!(notification_badge_pulse_phase(Duration::ZERO), Some(0.0));
        assert_eq!(
            notification_badge_pulse_phase(NOTIFICATION_BADGE_PULSE_DURATION),
            None
        );

        // Halfway through each 600ms cycle, the expanding halo is halfway out.
        for elapsed_ms in [300, 900, 1500] {
            let phase = notification_badge_pulse_phase(Duration::from_millis(elapsed_ms)).unwrap();
            assert!((phase - 0.5).abs() < 0.001);
        }
    }
}