workmux 0.1.167

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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Worktree table rendering for the dashboard worktree view.

use ratatui::{
    Frame,
    layout::{Constraint, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span, Text},
    widgets::{Block, Cell, Paragraph, Row, Table},
};

use super::super::agent;
use super::super::app::App;
use super::super::spinner::SPINNER_FRAMES;
use super::format::{format_git_status, format_pr_status};

/// Render the worktree table in the given area.
pub fn render_worktree_table(f: &mut Frame, app: &mut App, area: Rect) {
    // Don't render headers for an empty table - avoids a visual blink
    // as column widths jump when data arrives on the next frame
    if app.worktrees.is_empty() {
        return;
    }

    let show_check_counts = app.config.dashboard.show_check_counts();

    // Only show PR column when at least one worktree has a PR
    let show_pr_column = app.worktrees.iter().any(|w| w.pr_info.is_some());

    // Check if git data is being refreshed
    let is_git_fetching = app
        .is_git_fetching
        .load(std::sync::atomic::Ordering::Relaxed);

    // Build Git header with spinner when fetching
    let git_header = if is_git_fetching {
        let spinner = SPINNER_FRAMES[app.spinner_frame as usize % SPINNER_FRAMES.len()];
        Line::from(vec![
            Span::styled("Git ", Style::default().fg(app.palette.header).bold()),
            Span::styled(spinner.to_string(), Style::default().fg(app.palette.dimmed)),
        ])
    } else {
        Line::from(Span::styled(
            "Git",
            Style::default().fg(app.palette.header).bold(),
        ))
    };

    let header_style = Style::default().fg(app.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 is_pr_fetching = app.is_pr_fetching();
        let pr_header = if is_pr_fetching {
            let spinner = SPINNER_FRAMES[app.spinner_frame as usize % SPINNER_FRAMES.len()];
            Line::from(vec![
                Span::styled("PR ", Style::default().fg(app.palette.header).bold()),
                Span::styled(spinner.to_string(), Style::default().fg(app.palette.dimmed)),
            ])
        } else {
            Line::from(Span::styled(
                "PR",
                Style::default().fg(app.palette.header).bold(),
            ))
        };
        header_cells.push(Cell::from(pr_header));
    }
    header_cells.extend([
        Cell::from("Mux").style(header_style),
        Cell::from("Age").style(header_style),
    ]);
    header_cells.push(Cell::from("Agent").style(header_style));
    let header = Row::new(header_cells).height(1);

    // Pre-compute row data
    let row_data: Vec<_> = app
        .worktrees
        .iter()
        .enumerate()
        .map(|(idx, wt)| {
            let jump_key = if idx < 9 {
                format!("{}", idx + 1)
            } else {
                String::new()
            };

            let project = agent::extract_project_name(&wt.path);

            // Main worktree: show branch name (handle is just the repo dir name)
            // Other worktrees: show branch inline when it differs from the handle
            let worktree_display = if wt.is_main {
                wt.branch.clone()
            } else if wt.branch != wt.handle {
                format!("{} \u{2192}{}", wt.handle, wt.branch)
            } else {
                wt.handle.clone()
            };

            // Git status
            let git_status = app.git_statuses.get(&wt.path);
            let git_spans = format_git_status(git_status, app.spinner_frame, &app.palette);

            // PR status (only computed if column is shown)
            let pr_spans = if show_pr_column {
                Some(format_pr_status(
                    wt.pr_info.as_ref(),
                    show_check_counts,
                    app.spinner_frame,
                    &app.palette,
                ))
            } else {
                None
            };

            // Agent status summary
            let agent_spans = if let Some(ref summary) = wt.agent_status {
                use crate::multiplexer::AgentStatus;
                let mut parts: Vec<(String, Style)> = Vec::new();
                let working = summary
                    .statuses
                    .iter()
                    .filter(|s| **s == AgentStatus::Working)
                    .count();
                let waiting = summary
                    .statuses
                    .iter()
                    .filter(|s| **s == AgentStatus::Waiting)
                    .count();
                let done = summary
                    .statuses
                    .iter()
                    .filter(|s| **s == AgentStatus::Done)
                    .count();

                if working > 0 {
                    let icon = app.config.status_icons.working();
                    let spinner = SPINNER_FRAMES[app.spinner_frame as usize % SPINNER_FRAMES.len()];
                    parts.push((
                        format!("{} {} ", icon, spinner),
                        Style::default().fg(app.palette.info),
                    ));
                }
                if waiting > 0 {
                    let icon = app.config.status_icons.waiting();
                    parts.push((
                        format!("{} ", icon),
                        Style::default().fg(app.palette.accent),
                    ));
                }
                if done > 0 {
                    let icon = app.config.status_icons.done();
                    parts.push((
                        format!("{} ", icon),
                        Style::default().fg(app.palette.success),
                    ));
                }
                if parts.is_empty() {
                    parts.push(("-".to_string(), Style::default().fg(app.palette.dimmed)));
                }
                parts
            } else {
                vec![("-".to_string(), Style::default().fg(app.palette.dimmed))]
            };

            let is_current = app.current_worktree.as_ref().is_some_and(|cwd| {
                if let (Ok(cwd_canonical), Ok(wt_canonical)) =
                    (cwd.canonicalize(), wt.path.canonicalize())
                {
                    cwd_canonical == wt_canonical
                } else {
                    wt.path == *cwd
                }
            });

            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            let age = wt
                .created_at
                .map(|ts| agent::format_age(now.saturating_sub(ts)));

            (
                jump_key,
                project,
                worktree_display,
                wt.is_main,
                is_current,
                git_spans,
                pr_spans,
                agent_spans,
                wt.has_mux_window,
                age,
            )
        })
        .collect();

    // Calculate dynamic column widths
    let max_project_width = row_data
        .iter()
        .map(|(_, p, _, _, _, _, _, _, _, _)| p.len())
        .max()
        .unwrap_or(5)
        .clamp(5, 20)
        + 2;

    let max_worktree_width = row_data
        .iter()
        .map(|(_, _, w, _, _, _, _, _, _, _)| w.len())
        .max()
        .unwrap_or(8)
        .max(8)
        + 1;

    let max_git_width = row_data
        .iter()
        .map(|(_, _, _, _, _, git, _, _, _, _)| {
            git.iter()
                .map(|(text, _)| text.chars().count())
                .sum::<usize>()
        })
        .max()
        .unwrap_or(4)
        .clamp(4, 30)
        + 1;

    let max_pr_width = if show_pr_column {
        row_data
            .iter()
            .filter_map(|(_, _, _, _, _, _, pr, _, _, _)| pr.as_ref())
            .map(|spans| {
                spans
                    .iter()
                    .map(|(text, _)| text.chars().count())
                    .sum::<usize>()
            })
            .max()
            .unwrap_or(4)
            .clamp(4, 16)
            + 1
    } else {
        0
    };

    let rows: Vec<Row> = row_data
        .into_iter()
        .map(
            |(
                jump_key,
                project,
                worktree_display,
                is_main,
                is_current,
                git_spans,
                pr_spans,
                agent_spans,
                has_mux_window,
                age,
            )| {
                let worktree_style = if is_current {
                    Style::default().fg(app.palette.current_worktree_fg)
                } else if is_main {
                    Style::default().fg(app.palette.dimmed)
                } else {
                    Style::default()
                };

                let git_line = Line::from(
                    git_spans
                        .into_iter()
                        .map(|(text, style)| Span::styled(text, style))
                        .collect::<Vec<_>>(),
                );

                let mux_cell = if has_mux_window {
                    Cell::from("\u{25cf}").style(Style::default().fg(app.palette.success))
                } else {
                    Cell::from("-").style(Style::default().fg(app.palette.dimmed))
                };

                let agent_line = Line::from(
                    agent_spans
                        .into_iter()
                        .map(|(text, style)| Span::styled(text, style))
                        .collect::<Vec<_>>(),
                );

                let age_cell = Cell::from(age.unwrap_or_default())
                    .style(Style::default().fg(app.palette.dimmed));

                let mut cells = vec![
                    Cell::from(jump_key).style(Style::default().fg(app.palette.keycap)),
                    Cell::from(project),
                    Cell::from(worktree_display).style(worktree_style),
                    Cell::from(git_line),
                ];

                if let Some(pr_spans) = pr_spans {
                    let pr_line = Line::from(
                        pr_spans
                            .into_iter()
                            .map(|(text, style)| Span::styled(text, style))
                            .collect::<Vec<_>>(),
                    );
                    cells.push(Cell::from(pr_line));
                }

                cells.extend([mux_cell, age_cell]);
                cells.push(Cell::from(agent_line));

                let row = Row::new(cells);
                if is_current {
                    row.style(Style::default().bg(app.palette.current_row_bg))
                } else {
                    row
                }
            },
        )
        .collect();

    let mut constraints = vec![
        Constraint::Length(2),                         // #
        Constraint::Length(max_project_width as u16),  // Project
        Constraint::Length(max_worktree_width as u16), // Worktree (+ branch when different)
        Constraint::Length(max_git_width as u16),      // Git
    ];
    if show_pr_column {
        constraints.push(Constraint::Length(max_pr_width as u16));
    }
    constraints.extend([
        Constraint::Length(4), // Mux
        Constraint::Length(4), // Age
    ]);
    constraints.push(Constraint::Fill(1)); // Agent

    let table = Table::new(rows, constraints)
        .header(header)
        .block(Block::default())
        .row_highlight_style(Style::default().bg(app.palette.highlight_row_bg))
        .highlight_symbol("> ");

    f.render_stateful_widget(table, area, &mut app.worktree_table_state);
}

/// Render the worktree preview: info panel (left) + styled git log (right).
pub fn render_worktree_preview(f: &mut Frame, app: &mut App, area: Rect) {
    let selected_worktree = app
        .worktree_table_state
        .selected()
        .and_then(|idx| app.worktrees.get(idx));

    // Split preview area into info panel (left) and git log (right)
    let chunks = Layout::horizontal([
        Constraint::Length(40), // Info panel: fixed width
        Constraint::Fill(1),    // Git log: remaining space
    ])
    .split(area);

    render_info_panel(f, app, chunks[0], selected_worktree);
    render_git_log(f, app, chunks[1], selected_worktree);
}

/// Render the info panel showing worktree metadata.
fn render_info_panel(
    f: &mut Frame,
    app: &App,
    area: Rect,
    worktree: Option<&crate::workflow::types::WorktreeInfo>,
) {
    let title_style = Style::default()
        .fg(app.palette.header)
        .add_modifier(Modifier::BOLD);
    let border_style = Style::default().fg(app.palette.border);
    let label_style = Style::default().fg(app.palette.dimmed);
    let text_style = Style::default().fg(app.palette.text);

    let title = if let Some(wt) = worktree {
        format!(" {} ", wt.handle)
    } else {
        " Info ".to_string()
    };

    let block = Block::bordered()
        .title(title)
        .title_style(title_style)
        .border_style(border_style);

    let Some(wt) = worktree else {
        let paragraph = Paragraph::new(Text::raw("(no worktree selected)")).block(block);
        f.render_widget(paragraph, area);
        return;
    };

    let mut lines: Vec<Line> = Vec::new();

    // Branch
    lines.push(Line::from(vec![
        Span::styled("Branch  ", label_style),
        Span::styled(&wt.branch, text_style),
    ]));

    // Git status details (base branch, ahead/behind, diff stats)
    let git_status = app.git_statuses.get(&wt.path);
    if let Some(status) = git_status {
        // Base branch + ahead/behind
        let mut base_spans = vec![Span::styled("Base    ", label_style)];
        if !status.base_branch.is_empty() {
            base_spans.push(Span::styled(&status.base_branch, text_style));
        } else {
            base_spans.push(Span::styled("main", text_style));
        }
        if status.ahead > 0 || status.behind > 0 {
            base_spans.push(Span::styled(" (", label_style));
            if status.ahead > 0 {
                base_spans.push(Span::styled(
                    format!("\u{2191}{}", status.ahead),
                    Style::default().fg(app.palette.info),
                ));
            }
            if status.ahead > 0 && status.behind > 0 {
                base_spans.push(Span::styled(" ", label_style));
            }
            if status.behind > 0 {
                base_spans.push(Span::styled(
                    format!("\u{2193}{}", status.behind),
                    Style::default().fg(app.palette.accent),
                ));
            }
            base_spans.push(Span::styled(")", label_style));
        }
        lines.push(Line::from(base_spans));

        // Committed diff stats
        if status.lines_added > 0 || status.lines_removed > 0 {
            let mut diff_spans = vec![Span::styled("Diff    ", label_style)];
            if status.lines_added > 0 {
                diff_spans.push(Span::styled(
                    format!("+{}", status.lines_added),
                    Style::default().fg(app.palette.success),
                ));
            }
            if status.lines_added > 0 && status.lines_removed > 0 {
                diff_spans.push(Span::styled(" ", text_style));
            }
            if status.lines_removed > 0 {
                diff_spans.push(Span::styled(
                    format!("-{}", status.lines_removed),
                    Style::default().fg(app.palette.danger),
                ));
            }
            diff_spans.push(Span::styled(" committed", label_style));
            lines.push(Line::from(diff_spans));
        }

        // Uncommitted changes
        if status.uncommitted_added > 0 || status.uncommitted_removed > 0 {
            let mut uc_spans = vec![Span::styled("        ", label_style)];
            if status.uncommitted_added > 0 {
                uc_spans.push(Span::styled(
                    format!("+{}", status.uncommitted_added),
                    Style::default().fg(app.palette.success),
                ));
            }
            if status.uncommitted_added > 0 && status.uncommitted_removed > 0 {
                uc_spans.push(Span::styled(" ", text_style));
            }
            if status.uncommitted_removed > 0 {
                uc_spans.push(Span::styled(
                    format!("-{}", status.uncommitted_removed),
                    Style::default().fg(app.palette.danger),
                ));
            }
            uc_spans.push(Span::styled(" uncommitted", label_style));
            lines.push(Line::from(uc_spans));
        }

        // Rebase indicator
        if status.is_rebasing {
            let git_icons = crate::nerdfont::git_icons();
            lines.push(Line::from(vec![
                Span::styled("        ", label_style),
                Span::styled(
                    format!("{} ", git_icons.rebase),
                    Style::default().fg(app.palette.warning),
                ),
                Span::styled("rebase in progress", label_style),
            ]));
        }

        // Conflict indicator
        if status.has_conflict {
            lines.push(Line::from(vec![
                Span::styled("        ", label_style),
                Span::styled(
                    "conflict with base",
                    Style::default().fg(app.palette.danger),
                ),
            ]));
        }
    }

    // PR info
    if let Some(ref pr) = wt.pr_info {
        let pr_icons = crate::nerdfont::pr_icons();
        let (icon, color) = if pr.is_draft {
            (pr_icons.draft, app.palette.dimmed)
        } else {
            match pr.state.as_str() {
                "OPEN" => (pr_icons.open, app.palette.success),
                "MERGED" => (pr_icons.merged, app.palette.accent),
                "CLOSED" => (pr_icons.closed, app.palette.danger),
                _ => ("?", app.palette.dimmed),
            }
        };
        let mut pr_spans = vec![
            Span::styled("PR      ", label_style),
            Span::styled(format!("#{} ", pr.number), Style::default().fg(color)),
            Span::styled(icon, Style::default().fg(color)),
        ];
        // Check status
        if let Some(ref checks) = pr.checks {
            use crate::github::CheckState;
            let check_icons = crate::nerdfont::check_icons();
            let (check_icon, check_color) = match checks {
                CheckState::Success => (check_icons.success.to_string(), app.palette.success),
                CheckState::Failure { .. } => (check_icons.failure.to_string(), app.palette.danger),
                CheckState::Pending { .. } => (check_icons.pending.to_string(), app.palette.accent),
            };
            pr_spans.push(Span::styled(" ", text_style));
            pr_spans.push(Span::styled(check_icon, Style::default().fg(check_color)));
        }
        lines.push(Line::from(pr_spans));

        // PR title (truncated to fit)
        let inner_width = area.width.saturating_sub(2) as usize; // border
        let title_max = inner_width.saturating_sub(8); // label width
        let truncated_title = if pr.title.len() > title_max {
            format!("{}...", &pr.title[..title_max.saturating_sub(3)])
        } else {
            pr.title.clone()
        };
        lines.push(Line::from(vec![
            Span::styled("        ", label_style),
            Span::styled(truncated_title, Style::default().fg(color)),
        ]));

        // Check detail: failing check name or pending elapsed time
        let detail_spans = super::format::format_pr_details(pr, app.spinner_frame, &app.palette);
        if !detail_spans.is_empty() {
            let mut line_spans = vec![Span::styled("        ", label_style)];
            line_spans.extend(detail_spans);
            lines.push(Line::from(line_spans));
        }
    }

    // Agent status
    if let Some(ref summary) = wt.agent_status {
        use crate::multiplexer::AgentStatus;
        let working = summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Working)
            .count();
        let waiting = summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Waiting)
            .count();
        let done = summary
            .statuses
            .iter()
            .filter(|s| **s == AgentStatus::Done)
            .count();

        let mut agent_spans = vec![Span::styled("Agent   ", label_style)];
        if working > 0 {
            let icon = app.config.status_icons.working();
            let spinner = SPINNER_FRAMES[app.spinner_frame as usize % SPINNER_FRAMES.len()];
            agent_spans.push(Span::styled(
                format!("{} {}", icon, spinner),
                Style::default().fg(app.palette.info),
            ));
        }
        if waiting > 0 {
            if working > 0 {
                agent_spans.push(Span::styled(" ", text_style));
            }
            let icon = app.config.status_icons.waiting();
            agent_spans.push(Span::styled(
                icon.to_string(),
                Style::default().fg(app.palette.accent),
            ));
        }
        if done > 0 {
            if working > 0 || waiting > 0 {
                agent_spans.push(Span::styled(" ", text_style));
            }
            let icon = app.config.status_icons.done();
            agent_spans.push(Span::styled(
                icon.to_string(),
                Style::default().fg(app.palette.success),
            ));
        }
        lines.push(Line::from(agent_spans));
    }

    // Mux window
    let mux_spans = vec![
        Span::styled("Mux     ", label_style),
        if wt.has_mux_window {
            Span::styled("\u{25cf} active", Style::default().fg(app.palette.success))
        } else {
            Span::styled("- none", Style::default().fg(app.palette.dimmed))
        },
    ];
    lines.push(Line::from(mux_spans));

    let paragraph = Paragraph::new(Text::from(lines)).block(block);
    f.render_widget(paragraph, area);
}

/// Render the styled git log panel.
fn render_git_log(
    f: &mut Frame,
    app: &App,
    area: Rect,
    worktree: Option<&crate::workflow::types::WorktreeInfo>,
) {
    let title_style = Style::default()
        .fg(app.palette.header)
        .add_modifier(Modifier::BOLD);
    let border_style = Style::default().fg(app.palette.border);

    let block = Block::bordered()
        .title(" Git Log ")
        .title_style(title_style)
        .border_style(border_style);

    let text = match (&app.worktree_preview, worktree) {
        (Some(log), Some(_)) if !log.trim().is_empty() => {
            let hash_style = Style::default().fg(app.palette.accent);
            let date_style = Style::default().fg(app.palette.dimmed);
            let msg_style = Style::default().fg(app.palette.text);

            let lines: Vec<Line> = log
                .lines()
                .map(|line| {
                    let parts: Vec<&str> = line.splitn(3, '\t').collect();
                    if parts.len() == 3 {
                        Line::from(vec![
                            Span::styled(parts[0], hash_style),
                            Span::styled("  ", date_style),
                            Span::styled(parts[1], date_style),
                            Span::styled("  ", msg_style),
                            Span::styled(parts[2], msg_style),
                        ])
                    } else {
                        // Fallback for lines that don't match format
                        Line::styled(line, msg_style)
                    }
                })
                .collect();
            Text::from(lines)
        }
        (None, Some(_)) => Text::raw(""),
        (Some(_), Some(_)) => Text::raw("(no commits)"),
        (_, None) => Text::raw(""),
    };

    let paragraph = Paragraph::new(text).block(block);
    f.render_widget(paragraph, area);
}