workmux 0.1.215

An opinionated workflow tool that orchestrates git worktrees and tmux
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Formatting helpers for dashboard UI rendering.

use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Cell, Row};

/// Truncate a string to max_len characters, appending ellipsis if truncated.
pub fn truncate(s: &str, max_len: usize) -> String {
    if s.chars().count() > max_len {
        s.chars().take(max_len - 1).collect::<String>() + ""
    } else {
        s.to_string()
    }
}

use crate::config::StatusIcons;
use crate::git::GitStatus;
use crate::github::PrSummary;
use crate::multiplexer::AgentStatus;
use crate::nerdfont;
use crate::nerdfont::GitIcons;
use crate::ui::pr_status::{PrStatusOptions, format_pr_details as shared_format_pr_details};
use crate::workflow::types::AgentStatusSummary;

use super::super::ansi;
use super::super::spinner::SPINNER_FRAMES;
use super::theme::ThemePalette;

/// Spacing mode for agent status icon rendering.
pub enum AgentStatusFormat {
    /// Table cell: trailing space after each icon, spinner padded with spaces.
    TableCell,
    /// Detail line: single space separators between present statuses only.
    DetailLine,
}

struct AgentStatusCounts {
    working: usize,
    waiting: usize,
    done: usize,
}

fn count_agent_statuses(summary: &AgentStatusSummary) -> AgentStatusCounts {
    AgentStatusCounts {
        working: summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Working)
            .count(),
        waiting: summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Waiting)
            .count(),
        done: summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Done)
            .count(),
    }
}

/// Format agent status icons for dashboard table cells and detail lines.
pub fn format_agent_status_summary(
    summary: Option<&AgentStatusSummary>,
    icons: &StatusIcons,
    spinner_frame: u8,
    palette: &ThemePalette,
    mode: AgentStatusFormat,
) -> Vec<(String, Style)> {
    let Some(summary) = summary else {
        return if matches!(mode, AgentStatusFormat::TableCell) {
            vec![("-".to_string(), Style::default().fg(palette.dimmed))]
        } else {
            Vec::new()
        };
    };

    let counts = count_agent_statuses(summary);
    let spinner = SPINNER_FRAMES[spinner_frame as usize % SPINNER_FRAMES.len()];
    let separator_style = Style::default().fg(palette.text);
    let mut parts: Vec<(String, Style)> = Vec::new();
    let mut has_prior = false;

    if counts.working > 0 {
        let icon = icons.working();
        let base_style = Style::default().fg(palette.info);
        parts.extend(ansi::parse_tmux_styles(icon, base_style));
        match mode {
            AgentStatusFormat::TableCell => {
                parts.push((format!(" {} ", spinner), base_style));
            }
            AgentStatusFormat::DetailLine => {
                parts.push((format!(" {}", spinner), base_style));
            }
        }
        has_prior = true;
    }
    if counts.waiting > 0 {
        if matches!(mode, AgentStatusFormat::DetailLine) && has_prior {
            parts.push((" ".to_string(), separator_style));
        }
        let icon = icons.waiting();
        let base_style = Style::default().fg(palette.accent);
        parts.extend(ansi::parse_tmux_styles(icon, base_style));
        if matches!(mode, AgentStatusFormat::TableCell) {
            parts.push((" ".to_string(), base_style));
        }
        has_prior = true;
    }
    if counts.done > 0 {
        if matches!(mode, AgentStatusFormat::DetailLine) && has_prior {
            parts.push((" ".to_string(), separator_style));
        }
        let icon = icons.done();
        let base_style = Style::default().fg(palette.success);
        parts.extend(ansi::parse_tmux_styles(icon, base_style));
        if matches!(mode, AgentStatusFormat::TableCell) {
            parts.push((" ".to_string(), base_style));
        }
    }

    if parts.is_empty() && matches!(mode, AgentStatusFormat::TableCell) {
        parts.push(("-".to_string(), Style::default().fg(palette.dimmed)));
    }

    parts
}

/// Add diff icon and uncommitted (+N/-N) spans. Caller is responsible for
/// the leading separator if needed.
fn add_uncommitted_spans(
    spans: &mut Vec<(String, Style)>,
    status: &GitStatus,
    icons: &GitIcons,
    palette: &ThemePalette,
) {
    spans.push((icons.diff.to_string(), Style::default().fg(palette.accent)));

    if status.uncommitted_added > 0 {
        spans.push((" ".to_string(), Style::default()));
        spans.push((
            format!("+{}", status.uncommitted_added),
            Style::default().fg(palette.success),
        ));
    }
    if status.uncommitted_removed > 0 {
        spans.push((" ".to_string(), Style::default()));
        spans.push((
            format!("-{}", status.uncommitted_removed),
            Style::default().fg(palette.danger),
        ));
    }
}

/// Format git status for the Git column: base branch, diff stats, then indicators
/// Format: "→branch +N -M 󰏫 +X -Y 󰀪 ↑A ↓B"
/// When there are uncommitted changes that differ from total, branch totals are dimmed
pub fn format_git_status(
    status: Option<&GitStatus>,
    spinner_frame: u8,
    palette: &ThemePalette,
) -> Vec<(String, Style)> {
    let icons = nerdfont::git_icons();

    if let Some(status) = status {
        let mut spans: Vec<(String, Style)> = Vec::new();
        let has_uncommitted =
            status.uncommitted_added > 0 || status.uncommitted_removed > 0 || status.is_dirty;

        // Check if uncommitted equals total (all changes are uncommitted, nothing committed yet)
        let all_uncommitted = status.uncommitted_added == status.lines_added
            && status.uncommitted_removed == status.lines_removed;

        // Rebase indicator (shown first, before everything else)
        if status.is_rebasing {
            spans.push((
                icons.rebase.to_string(),
                Style::default().fg(palette.warning),
            ));
        }

        // Base branch (dimmed) - only show if not default (main/master)
        if !status.base_branch.is_empty()
            && status.base_branch != "main"
            && status.base_branch != "master"
        {
            spans.push((
                format!("{}", status.base_branch),
                Style::default().fg(palette.dimmed),
            ));
        }

        // Always dim branch totals (historical), always bright uncommitted (active work)
        // - Clean: dim branch totals only
        // - All uncommitted: icon + bright uncommitted only
        // - Mixed: dim branch totals + icon + bright uncommitted
        if has_uncommitted && all_uncommitted {
            // All changes are uncommitted - show icon + bright numbers only
            if !spans.is_empty() {
                spans.push((" ".to_string(), Style::default()));
            }
            add_uncommitted_spans(&mut spans, status, &icons, palette);
        } else {
            // Either clean or mixed - show dim branch totals
            if status.lines_added > 0 {
                if !spans.is_empty() {
                    spans.push((" ".to_string(), Style::default()));
                }
                spans.push((
                    format!("+{}", status.lines_added),
                    Style::default()
                        .fg(palette.success)
                        .add_modifier(Modifier::DIM),
                ));
            }
            if status.lines_removed > 0 {
                if !spans.is_empty() {
                    spans.push((" ".to_string(), Style::default()));
                }
                spans.push((
                    format!("-{}", status.lines_removed),
                    Style::default()
                        .fg(palette.danger)
                        .add_modifier(Modifier::DIM),
                ));
            }

            // If there are uncommitted changes, show icon + bright uncommitted
            if has_uncommitted {
                if !spans.is_empty() {
                    spans.push((" ".to_string(), Style::default()));
                }
                add_uncommitted_spans(&mut spans, status, &icons, palette);
            }
        }

        // Conflict indicator
        if status.has_conflict {
            if !spans.is_empty() {
                spans.push((" ".to_string(), Style::default()));
            }
            spans.push((
                icons.conflict.to_string(),
                Style::default().fg(palette.danger),
            ));
        }

        // Ahead/behind upstream
        if status.ahead > 0 {
            if !spans.is_empty() {
                spans.push((" ".to_string(), Style::default()));
            }
            spans.push((
                format!("{}", status.ahead),
                Style::default().fg(palette.info),
            ));
        }
        if status.behind > 0 {
            if !spans.is_empty() {
                spans.push((" ".to_string(), Style::default()));
            }
            spans.push((
                format!("{}", status.behind),
                Style::default().fg(palette.warning),
            ));
        }

        if spans.is_empty() {
            vec![("-".to_string(), Style::default().fg(palette.dimmed))]
        } else {
            spans
        }
    } else {
        // No status yet - show spinner
        let frame = SPINNER_FRAMES[spinner_frame as usize % SPINNER_FRAMES.len()];
        vec![(frame.to_string(), Style::default().fg(palette.dimmed))]
    }
}

/// Format PR status as styled spans for dashboard display
pub fn format_pr_status(
    pr: Option<&PrSummary>,
    show_check_counts: bool,
    spinner_frame: u8,
    palette: &ThemePalette,
) -> Vec<(String, Style)> {
    crate::ui::pr_status::format_pr_status(
        pr,
        PrStatusOptions {
            include_number: true,
            show_check_counts,
            none_placeholder: Some("-"),
            is_stale: false,
        },
        spinner_frame,
        palette,
    )
}

/// Returns minimal PR detail spans for the preview title.
/// - Pending: "◷ 12m" (dimmed)
/// - Failure: "× lint-check" (danger color)
/// - Success/None: empty
pub fn format_pr_details(
    pr: &PrSummary,
    spinner_frame: u8,
    palette: &ThemePalette,
) -> Vec<ratatui::text::Span<'static>> {
    shared_format_pr_details(pr, spinner_frame, palette)
}

/// Shared git/PR fetch state for resource table headers.
pub(crate) struct ResourceHeaderState<'a> {
    pub palette: &'a ThemePalette,
    pub spinner_frame: u8,
    pub git_fetching: bool,
    pub pr_fetching: bool,
}

/// Build the shared prefix columns for agent and worktree resource tables.
pub(crate) fn resource_table_header(
    state: ResourceHeaderState<'_>,
    show_pr_column: bool,
    trailing_columns: &[&'static str],
) -> Row<'static> {
    let git_header = build_column_header(
        "Git",
        state.git_fetching,
        state.spinner_frame,
        state.palette,
    );
    let header_style = Style::default().fg(state.palette.header).bold();
    let mut header_cells = vec![
        Cell::from("#").style(header_style),
        Cell::from("Project").style(header_style),
        Cell::from("Worktree").style(header_style),
        Cell::from(git_header),
    ];

    if show_pr_column {
        let pr_header =
            build_column_header("PR", state.pr_fetching, state.spinner_frame, state.palette);
        header_cells.push(Cell::from(pr_header));
    }

    for column in trailing_columns {
        header_cells.push(Cell::from(*column).style(header_style));
    }

    Row::new(header_cells).height(1)
}

/// Bordered panel block with dashboard header styling.
pub(crate) fn panel_block(
    title: impl Into<Line<'static>>,
    palette: &ThemePalette,
) -> Block<'static> {
    let title_style = Style::default()
        .fg(palette.header)
        .add_modifier(Modifier::BOLD);
    let border_style = Style::default().fg(palette.border);
    Block::bordered()
        .title(title)
        .title_style(title_style)
        .border_style(border_style)
}

/// Build a column header with optional spinner when data is being fetched.
pub fn build_column_header(
    name: &str,
    is_fetching: bool,
    spinner_frame: u8,
    palette: &ThemePalette,
) -> Line<'static> {
    if is_fetching {
        let frame = SPINNER_FRAMES[spinner_frame as usize % SPINNER_FRAMES.len()];
        Line::from(vec![
            Span::styled(
                format!("{} ", name),
                Style::default().fg(palette.header).bold(),
            ),
            Span::styled(frame.to_string(), Style::default().fg(palette.dimmed)),
        ])
    } else {
        Line::from(Span::styled(
            name.to_string(),
            Style::default().fg(palette.header).bold(),
        ))
    }
}

/// Convert vec of (string, style) pairs into a ratatui Line for table cell rendering.
pub fn spans_to_line(spans: Vec<(String, Style)>) -> Line<'static> {
    Line::from(
        spans
            .into_iter()
            .map(|(text, style)| Span::styled(text, style))
            .collect::<Vec<_>>(),
    )
}

/// Calculate column width from string items with min/max clamping.
pub fn calc_column_width(items: &[String], min: usize, max: usize, padding: usize) -> u16 {
    items
        .iter()
        .map(|s| s.chars().count())
        .max()
        .unwrap_or(min)
        .clamp(min, max)
        .saturating_add(padding) as u16
}

/// Create a style for a table row based on whether it's the current or main worktree.
pub fn make_row_style(is_current: bool, is_main: bool, palette: &ThemePalette) -> Style {
    if is_current {
        Style::default().fg(palette.current_worktree_fg)
    } else if is_main {
        Style::default().fg(palette.dimmed)
    } else {
        Style::default()
    }
}