tam-cli 0.6.0

Terminal agent multiplexer — manage units of work, not just processes
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
//! The list: the chats' section, the section of the shells on main
//! checkouts, then a row per task under a header row per repository (or
//! chats and tasks together, the most urgent first, those shells last), a
//! row per member below a task with several, and a row per shell in a
//! worktree below its member. Its columns fit the width: the least useful
//! go first when it is narrow.

use ratatui::layout::{Constraint, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Cell, HighlightSpacing, Row as TableRow, Table, TableState};
use ratatui::Frame;
use tam_proto::{AgentInfo, AgentState, ShellInfo};

use crate::chat::{Chat, Closes};
use crate::task::{Member, Task, TaskStatus};

use super::app::{self, App, Branch, Order, Pick, Row};
use super::branch::Observation;
use super::fuzzy;
use super::theme;
use super::triage::{age, one_line};
use super::ui::{agent_detail_line, context_display, first_line, status_display, CONTEXT_GAUGE};

/// From this width on, a column says what each member waits on.
const NOTE_FROM: u16 = 100;
/// The note column's narrowest.
const NOTE_MIN: u16 = 20;
/// Task names this long are not cut while other columns can make room.
const TASK_WANTED: u16 = 20;
/// Between columns.
const SPACING: u16 = 1;
/// Left of the rows: the selected one's mark.
const MARK: u16 = 1;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Col {
    Status,
    /// Time in state.
    Age,
    Task,
    /// Shown when the list is not grouped by repository.
    Repo,
    /// Ahead, behind, uncommitted.
    Branch,
    Ctx,
    /// What the member waits on.
    Note,
}

/// Columns dropped first when the list is too narrow for them all.
const DROP_ORDER: [Col; 5] = [Col::Note, Col::Ctx, Col::Branch, Col::Repo, Col::Age];

impl Col {
    fn header(self) -> &'static str {
        match self {
            Col::Status => "STATUS",
            Col::Age | Col::Note => "",
            Col::Task => "TASK",
            Col::Repo => "REPO",
            Col::Branch => "BRANCH",
            Col::Ctx => "CTX",
        }
    }

    /// Fixed widths, so that the columns do not move as states change.
    fn fixed_width(self) -> Option<u16> {
        match self {
            Col::Status => Some(10),                    // "? question"
            Col::Age => Some(4),                        // "999d"
            Col::Ctx => Some(5 + CONTEXT_GAUGE as u16), // "100% " and the gauge
            _ => None,
        }
    }
}

/// Draw the rows of `app` (at least one) in `area`, keeping the selected
/// task's rows (its group's header when it is the first in it, its
/// members') in view.
pub fn render(frame: &mut Frame, area: Rect, app: &mut App) {
    let t = theme::get();
    // The first column marks the selected row.
    let width = area.width.saturating_sub(MARK);
    let now = crate::task::now();
    let rows = app.rows();
    let focused = app.focused_member().map(|(_, m)| m.id().to_string());
    let selected = app.pick();

    let mut cols = vec![Col::Status, Col::Age, Col::Task];
    if app.order == Order::Attention {
        cols.push(Col::Repo);
    }
    cols.extend([Col::Branch, Col::Ctx]);
    if width >= NOTE_FROM {
        cols.push(Col::Note);
    }
    let cell = |row: &Row, col| match *row {
        Row::Group(_) | Row::Chats | Row::Shells => Line::default(),
        Row::Chat(chat) => chat_cell(col, chat, app, now),
        Row::Shell { shell, tree } => shell_cell(col, shell, tree, app),
        Row::Task(task) => task_cell(col, task, app, now),
        Row::Member { task, member, last } => {
            let marked = focused.as_deref() == Some(member.id());
            member_cell(col, task, member, last, marked, app, now)
        }
    };
    let mut cells: Vec<Vec<Line<'static>>> = rows
        .iter()
        .map(|row| cols.iter().map(|&col| cell(row, col)).collect())
        .collect();

    let widths = fit(&mut cols, &mut cells, width);
    let task_width = cols
        .iter()
        .position(|&c| c == Col::Task)
        .map_or(0, |i| widths[i]);
    let note_width = width.saturating_sub(
        widths.iter().sum::<u16>() + SPACING * (cols.len() as u16).saturating_sub(1),
    );

    let header =
        TableRow::new(cols.iter().map(|c| Cell::from(c.header()))).style(Style::new().fg(t.muted));
    let table_rows: Vec<TableRow> = rows
        .iter()
        .zip(cells)
        .map(|(row, cells)| match row {
            Row::Group(task) => header_row(app::repo_group(task), width, cols.len(), app),
            Row::Chats => header_row("chats".into(), width, cols.len(), app),
            Row::Shells => header_row("shells".into(), width, cols.len(), app),
            // The name cut before its mark, never the mark.
            Row::Chat(chat) => TableRow::new(cols.iter().zip(cells).map(|(&col, line)| {
                Cell::from(match col {
                    Col::Task => chat_name(chat, app, now, task_width),
                    Col::Note => ellipsize(line, note_width),
                    _ => line,
                })
            })),
            _ => TableRow::new(cols.iter().zip(cells).map(|(&col, line)| {
                Cell::from(match col {
                    Col::Task => ellipsize(line, task_width),
                    Col::Note => ellipsize(line, note_width),
                    _ => line,
                })
            })),
        })
        .collect();

    let constraints: Vec<Constraint> = cols
        .iter()
        .zip(&widths)
        .map(|(&col, &w)| match col {
            Col::Note => Constraint::Fill(1),
            _ => Constraint::Length(w),
        })
        .collect();

    // The selected entry's rows, from its group's header when it is the
    // first in it, to a task's last member or shell.
    let selected_row = rows.iter().position(|r| match (r, &selected) {
        (Row::Task(t), Some(Pick::Task(name))) => t.name == *name,
        (Row::Chat(c), Some(Pick::Chat(id))) => c.info.id == *id,
        (Row::Shell { shell, .. }, Some(Pick::Shell(id))) => shell.id == *id,
        _ => false,
    });
    let block = selected_row.map(|i| {
        let header = i > 0 && matches!(rows[i - 1], Row::Group(_) | Row::Chats | Row::Shells);
        let start = if header { i - 1 } else { i };
        let below = match rows[i] {
            Row::Task(_) => rows[i + 1..]
                .iter()
                .take_while(|r| matches!(r, Row::Member { .. } | Row::Shell { tree: Some(_), .. }))
                .count(),
            _ => 0,
        };
        (start, i, i + 1 + below)
    });
    let height = area.height.saturating_sub(1) as usize;
    let mut offset = app.table_offset.min(rows.len().saturating_sub(height));
    if let Some((start, row, end)) = block {
        if start < offset {
            offset = start;
        } else if end > offset + height {
            // Taller than the list: from the task's row.
            offset = (end - height).min(row);
        }
    }
    // For the mouse: the entry (its index among the visible ones) and the
    // member each row is about.
    let mut index = 0;
    let mut task = 0;
    let row_tasks: Vec<Option<(usize, Option<String>)>> = rows
        .iter()
        .map(|row| match row {
            Row::Group(_) | Row::Chats | Row::Shells => None,
            Row::Task(_) => {
                task = index;
                index += 1;
                Some((task, None))
            }
            Row::Chat(_) | Row::Shell { .. } => {
                index += 1;
                Some((index - 1, None))
            }
            // Its task's: the shells between members are entries too.
            Row::Member { member, .. } => Some((task, Some(member.id().to_string()))),
        })
        .collect();
    drop(rows);

    let table = Table::new(table_rows, constraints)
        .header(header)
        .column_spacing(SPACING)
        .row_highlight_style(t.selection)
        .highlight_symbol(Line::styled(
            "▌",
            Style::new().fg(if t.rainbow {
                theme::rainbow(0, app.spin.unwrap_or(0) * 2)
            } else {
                t.accent
            }),
        ))
        .highlight_spacing(HighlightSpacing::Always);
    let mut state = TableState::new()
        .with_offset(offset)
        .with_selected(selected_row);
    frame.render_stateful_widget(table, area, &mut state);
    app.table_offset = state.offset();
    app.hits.list = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    app.hits.rows = row_tasks
        .into_iter()
        .skip(app.table_offset)
        .take(height)
        .collect();
}

/// A section's header row: its name (the repositories, `chats` or
/// `shells`), and a rule to the list's edge.
fn header_row(name: String, width: u16, cols: usize, app: &App) -> TableRow<'static> {
    let t = theme::get();
    let rule = (width as usize).saturating_sub(Span::raw(name.as_str()).width() + 1);
    let mut spans = vec![
        Span::styled(name, Style::new().fg(t.accent).add_modifier(Modifier::BOLD)),
        Span::raw(" "),
    ];
    if t.rainbow {
        let tick = app.spin.unwrap_or(0);
        spans.extend(theme::rainbow_spans(&"─".repeat(rule), tick, Style::new()));
    } else {
        spans.push(Span::styled("─".repeat(rule), Style::new().fg(t.subtle)));
    }
    TableRow::new([Cell::from(Line::from(spans)).column_span(cols as u16)])
}

/// A task's or member's name, the characters the filter matched
/// highlighted.
fn name_line(name: &str, query: &str, style: Style) -> Line<'static> {
    match fuzzy::fuzzy(query, name).filter(|m| !m.positions.is_empty()) {
        Some(m) => fuzzy::highlight(
            name,
            &m.positions,
            style,
            style.fg(theme::get().accent).add_modifier(Modifier::BOLD),
        ),
        None => Line::styled(name.to_string(), style),
    }
}

/// Column widths for `width` columns: drops the columns that do not fit
/// (from `cols` and each row of `cells`). The task column is as wide as
/// its longest name while there is room, and takes the room left when no
/// note column does.
fn fit(cols: &mut Vec<Col>, cells: &mut [Vec<Line<'static>>], width: u16) -> Vec<u16> {
    let natural = |cols: &[Col], cells: &[Vec<Line>], i: usize| {
        cols[i].fixed_width().unwrap_or_else(|| {
            cells
                .iter()
                .map(|row| row[i].width() as u16)
                .chain([cols[i].header().len() as u16])
                .max()
                .unwrap_or(0)
        })
    };
    let others = |cols: &[Col], cells: &[Vec<Line>]| {
        let mut sum = SPACING * (cols.len() as u16).saturating_sub(1);
        for (i, col) in cols.iter().enumerate() {
            sum += match col {
                Col::Task => 0,
                Col::Note => NOTE_MIN,
                _ => natural(cols, cells, i),
            };
        }
        sum
    };
    let task = cols
        .iter()
        .position(|&c| c == Col::Task)
        .expect("task column");
    let wanted = natural(cols, cells, task).min(TASK_WANTED);
    for drop in DROP_ORDER {
        if others(cols, cells) + wanted <= width {
            break;
        }
        if let Some(i) = cols.iter().position(|&c| c == drop) {
            cols.remove(i);
            for row in cells.iter_mut() {
                row.remove(i);
            }
        }
    }
    let room = width.saturating_sub(others(cols, cells));
    // The list fills its width: the note column takes what is left, else
    // the task column does (the columns after it sit at the right edge).
    let task_width = if cols.contains(&Col::Note) {
        natural(
            cols,
            cells,
            cols.iter().position(|&c| c == Col::Task).unwrap(),
        )
        .min(room)
    } else {
        room
    };
    (0..cols.len())
        .map(|i| match cols[i] {
            Col::Task => task_width,
            Col::Note => 0,
            _ => natural(cols, cells, i),
        })
        .collect()
}

/// A task's row: its only member's, or for a task with several, its name
/// alone: a status belongs to an agent, and the members' rows below have
/// theirs.
fn task_cell(col: Col, task: &Task, app: &App, now: u64) -> Line<'static> {
    if let [member] = &task.members[..] {
        return match col {
            Col::Task => name_line(&task.name, app.filter.value(), Style::new()),
            Col::Repo => Line::raw(member.info.repo.clone()),
            _ => member_cell(col, task, member, false, false, app, now),
        };
    }
    match col {
        Col::Task => name_line(
            &task.name,
            app.filter.value(),
            Style::new().add_modifier(Modifier::BOLD),
        ),
        Col::Repo => Line::raw(app::repo_group(task)),
        _ => Line::default(),
    }
}

/// A member's cells. `last`: the last of its task's members' rows;
/// `marked`: the member the keys act on.
fn member_cell(
    col: Col,
    task: &Task,
    member: &Member,
    last: bool,
    marked: bool,
    app: &App,
    now: u64,
) -> Line<'static> {
    let agent = member.agent_info.as_ref();
    match col {
        Col::Status => status_cell(task.member_status(member), app.spin),
        Col::Age => age_cell(task, member, now),
        Col::Task => {
            let tree = if last { "└" } else { "├" };
            let (mark, style) = if marked {
                ("▸", Style::new().add_modifier(Modifier::BOLD))
            } else {
                (" ", Style::new())
            };
            let mut line = name_line(&member.info.name, app.filter.value(), style);
            line.spans.splice(
                0..0,
                [
                    Span::styled(format!(" {tree}"), Style::new().fg(theme::get().subtle)),
                    Span::styled(mark, style),
                ],
            );
            line
        }
        Col::Repo => Line::default(),
        Col::Branch => branch_cell(member, app.branches.get(member.id())),
        Col::Ctx => agent
            .and_then(|a| a.context_percent)
            .map(context_display)
            .unwrap_or_default(),
        Col::Note => match agent {
            Some(agent) => agent_note(agent),
            None => match crate::health::problem(&member.info) {
                Some(problem) => Line::styled(problem, Style::new().fg(theme::get().bad)),
                None => Line::default(),
            },
        },
    }
}

/// A chat's cells: as a task's, its repository where a task has its branch
/// (in the REPO column attention first, the branch's then saying `chat`).
fn chat_cell(col: Col, chat: &Chat, app: &App, now: u64) -> Line<'static> {
    let dim = Style::new().fg(theme::get().muted);
    let agent = chat.agent.as_ref();
    match col {
        Col::Status => status_cell(chat.status(), app.spin),
        Col::Age => {
            let since = agent.and_then(|a| a.state_since).unwrap_or(chat.last());
            Line::styled(age(now.saturating_sub(since)), dim).right_aligned()
        }
        Col::Task => chat_name(chat, app, now, u16::MAX),
        Col::Repo => Line::raw(chat.info.repo.clone()),
        Col::Branch => match app.order {
            Order::Repo => Line::styled(chat.info.repo.clone(), dim),
            Order::Attention => Line::styled("chat", dim),
        },
        Col::Ctx => agent
            .and_then(|a| a.context_percent)
            .map(context_display)
            .unwrap_or_default(),
        // Without an agent: what it was last asked.
        Col::Note => match (agent, &chat.info.last_prompt) {
            (Some(agent), _) => agent_note(agent),
            (None, Some(prompt)) => Line::styled(one_line(prompt), dim),
            (None, None) => Line::default(),
        },
    }
}

/// A shell's cells: its name alone (no status, time or context: a shell has
/// none), on a branch below its member for one in a worktree. One on a main
/// checkout has its repository where a task has its branch (in the REPO
/// column attention first, the branch's then saying `shell`), as a chat.
fn shell_cell(col: Col, shell: &ShellInfo, tree: Option<Branch>, app: &App) -> Line<'static> {
    let t = theme::get();
    let dim = Style::new().fg(t.muted);
    let Some(tree) = tree else {
        return match col {
            Col::Task => Line::raw(shell.name()),
            Col::Repo => Line::raw(shell.repo.clone()),
            Col::Branch => match app.order {
                Order::Repo => Line::styled(shell.repo.clone(), dim),
                Order::Attention => Line::styled("shell", dim),
            },
            _ => Line::default(),
        };
    };
    if col != Col::Task {
        return Line::default();
    }
    // The task's branch going on past the member's row (in a task with
    // several), then the shell's own, as a member's.
    let trunk = match tree.member_last {
        None => "",
        Some(false) => " │",
        Some(true) => "  ",
    };
    let fork = if tree.last { "└" } else { "├" };
    Line::from(vec![
        Span::styled(format!("{trunk} {fork}"), Style::new().fg(t.subtle)),
        Span::raw(format!(" {}", shell.name())),
    ])
}

/// A chat's name (the user's, else Claude's title, else its id, dimmed),
/// in `width` columns, then its mark, never cut: `◔` (in its last day: the
/// name dimmed) or `∞` (kept).
fn chat_name(chat: &Chat, app: &App, now: u64, width: u16) -> Line<'static> {
    let t = theme::get();
    let info = &chat.info;
    let closes = Closes::of(info, now);
    let mark = match closes {
        _ if closes.last_day() => Some(Span::styled("◔", Style::new().fg(t.warn))),
        Closes::Kept => Some(Span::styled("∞", Style::new().fg(t.muted))),
        _ => None,
    };
    let untitled = info.name.is_none() && info.title.is_none();
    let style = if untitled || closes.last_day() {
        Style::new().fg(t.muted)
    } else {
        Style::new()
    };
    let name = name_line(&info.label(), app.filter.value(), style);
    let Some(mark) = mark else {
        return ellipsize(name, width);
    };
    let mut line = ellipsize(name, width.saturating_sub(2));
    line.spans.extend([Span::raw(" "), mark]);
    line
}

/// A status: its mark and name; a working agent's mark turns (`spin`: the
/// frame).
fn status_cell(status: TaskStatus, spin: Option<usize>) -> Line<'static> {
    const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
    let (text, color) = status_display(&status);
    if let (TaskStatus::Run, Some(frame)) = (status, spin) {
        let name = text.split_once(' ').map_or(text, |(_, name)| name);
        return Line::styled(
            format!("{} {name}", FRAMES[frame % FRAMES.len()]),
            Style::new().fg(if theme::get().rainbow {
                theme::rainbow(0, frame * 3)
            } else {
                color
            }),
        );
    }
    let style = Style::new().fg(color);
    match status {
        // What needs the user stands out.
        TaskStatus::Block | TaskStatus::Question | TaskStatus::Error | TaskStatus::Ready => {
            Line::styled(text, style.add_modifier(Modifier::BOLD))
        }
        _ => Line::styled(text, style),
    }
}

/// How long the member has been in its state: its agent's, else since the
/// task's last activity (idle for so long).
fn age_cell(task: &Task, member: &Member, now: u64) -> Line<'static> {
    let since = match &member.agent_info {
        Some(agent) => agent.state_since,
        None => task.last_activity,
    };
    match since {
        Some(since) => Line::styled(
            age(now.saturating_sub(since)),
            Style::new().fg(theme::get().muted),
        )
        .right_aligned(),
        None => Line::default(),
    }
}

/// The member's branch against the default branch: `↑` commits ahead, `↓`
/// behind, `*` paths with uncommitted changes, `=` none of them; `…` until
/// git was asked, `?` when it could not tell. Nothing for a gone worktree
/// (its status says so).
fn branch_cell(member: &Member, observation: Option<&Observation>) -> Line<'static> {
    let dim = Style::new().fg(theme::get().muted);
    if member.is_unhealthy() {
        return Line::default();
    }
    let state = match observation.and_then(|o| o.state.as_ref()) {
        None => return Line::styled("…", dim),
        Some(Err(_)) => return Line::styled("?", dim),
        Some(Ok(state)) => state,
    };
    let mut parts = Vec::new();
    if state.ahead > 0 {
        parts.push(Span::styled(
            format!("↑{}", state.ahead),
            Style::new().fg(theme::get().ok),
        ));
    }
    if state.behind > 0 {
        parts.push(Span::styled(format!("↓{}", state.behind), dim));
    }
    if state.uncommitted > 0 {
        parts.push(Span::styled(
            format!("*{}", state.uncommitted),
            Style::new().fg(theme::get().warn),
        ));
    }
    if parts.is_empty() {
        return Line::styled("=", dim);
    }
    let mut spans = Vec::new();
    for part in parts {
        if !spans.is_empty() {
            spans.push(Span::raw(" "));
        }
        spans.push(part);
    }
    Line::from(spans)
}

/// What an agent waits on, on one line: the permission or question, why
/// its turn failed or what auto mode refused, the start of its last
/// message.
fn agent_note(agent: &AgentInfo) -> Line<'static> {
    let dim = Style::new().fg(theme::get().muted);
    if let Some((text, color)) = agent_detail_line(agent.state, &agent.detail) {
        return Line::styled(one_line(&text), Style::new().fg(color));
    }
    match (&agent.detail.last_message, agent.state) {
        (Some(message), AgentState::Ready) => Line::styled(one_line(first_line(message)), dim),
        _ => Line::default(),
    }
}

/// `line` cut to `width` columns, ending with `…` when cut.
pub(super) fn ellipsize(line: Line<'static>, width: u16) -> Line<'static> {
    let width = width as usize;
    if line.width() <= width {
        return line;
    }
    let mut left = width.saturating_sub(1);
    let mut spans = Vec::new();
    let mut last_style = Style::new();
    for span in line.spans {
        last_style = span.style;
        let mut text = String::new();
        for c in span.content.chars() {
            let w = Span::raw(c.to_string()).width();
            if w > left {
                left = 0;
                break;
            }
            left -= w;
            text.push(c);
        }
        spans.push(Span::styled(text, span.style));
        if left == 0 {
            break;
        }
    }
    if width > 0 {
        spans.push(Span::styled("…", last_style));
    }
    Line::from(spans).style(line.style)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ellipsizing_keeps_styles_and_width() {
        let line = Line::from(vec![
            Span::raw("ab"),
            Span::styled("cdef", Style::new().fg(theme::get().bad)),
        ]);
        let cut = ellipsize(line.clone(), 4);
        assert_eq!(cut.width(), 4);
        assert_eq!(cut.to_string(), "abc…");
        assert_eq!(cut.spans.last().unwrap().style.fg, Some(theme::get().bad));
        assert_eq!(ellipsize(line.clone(), 6).to_string(), "abcdef");
        assert_eq!(ellipsize(Line::raw("漢字漢字"), 5).to_string(), "漢字…");
    }
}