collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
Documentation
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use ratatui::prelude::*;
use ratatui::widgets::Paragraph;

use crate::tui::state::{SwarmAgentStatus, UiState};
use crate::tui::theme::Theme;

/// Minimum terminal width to show the sidebar.
pub const SIDEBAR_MIN_WIDTH: u16 = 120;
/// Fixed sidebar column width.
pub const SIDEBAR_WIDTH: u16 = 36;

/// Render the right-side information panel.
pub fn render(state: &UiState, area: Rect, buf: &mut Buffer, working_dir: &str) {
    let theme = &state.theme;

    // Fill entire sidebar area with darker bg to visually distinguish it from chat.
    // Use ratatui's Block widget for efficient background fill instead of per-cell loop.
    ratatui::widgets::Block::default()
        .style(Style::default().bg(theme.bg_surface))
        .render(area, buf);

    // Content area: uniform 1-cell padding on all sides
    let pad = 1u16;
    let content_x = area.x + pad;
    let content_w = area.width.saturating_sub(pad * 2);
    if content_w == 0 {
        return;
    }

    // Reserve bottom 3 rows for project info (aligns with status bar rows).
    // Status bar takes Length(3) so sidebar bottom 3 rows = same visual area.
    const FOOTER_HEIGHT: u16 = 3;
    // Debug monitor (when enabled) is pinned above footer.
    // Base: 1 blank + 1 header + 7 data = 9 rows
    // Perf: 1 blank + 6 metrics + top tools (up to 3) = 10 rows
    let debug_height: u16 = if state.debug_mode {
        let base = 9u16;
        let has_perf = state.debug_monitor.tool_latency_avg_ms > 0.0
            || state.debug_monitor.api_latency_avg_ms > 0.0;
        if has_perf {
            base + 1 + 6 + state.debug_monitor.top_tools.len().min(3) as u16
        } else {
            base
        }
    } else {
        0
    };
    let bottom = area.y
        + area
            .height
            .saturating_sub(pad + FOOTER_HEIGHT + debug_height);

    let mut y = area.y + pad;

    // ── Context ─────────────────────────────────────────
    y = render_section_header("Context", y, content_x, content_w, buf, theme);

    let ctx_used = state.context_used_tokens;
    let ctx_max = state.context_max_tokens;
    let pct = if ctx_max > 0 {
        ((ctx_used as f64 / ctx_max as f64) * 100.0).min(100.0) as u32
    } else {
        0
    };

    let token_line = if ctx_used > 0 {
        format!(" {} tokens", ctx_used)
    } else {
        " 0 tokens".to_string()
    };
    y = render_dim_line(&token_line, y, content_x, content_w, buf, theme);
    y = render_dim_line(
        &format!(" {pct}% used"),
        y,
        content_x,
        content_w,
        buf,
        theme,
    );

    y = render_blank(y, content_x, content_w, buf, theme);

    // ── Hive ────────────────────────────────────────────
    if let Some(ref hive) = state.swarm_status {
        y = render_section_header(&hive.mode_label, y, content_x, content_w, buf, theme);
        y = render_dim_line(
            &format!(" Phase: {:?}", hive.phase),
            y,
            content_x,
            content_w,
            buf,
            theme,
        );
        // Record where agent list starts for click detection
        state.sidebar_swarm_agents_start_row.set(y);
        for entry in &hive.agents {
            if y >= bottom {
                break;
            }
            let (dot_color, status_label) = match &entry.status {
                SwarmAgentStatus::Pending => (theme.text_muted, "..."),
                SwarmAgentStatus::Running => (theme.accent, "run"),
                SwarmAgentStatus::Paused => (theme.warning, "PSE"),
                SwarmAgentStatus::Completed { success: true } => (theme.success, "OK"),
                SwarmAgentStatus::Completed { success: false } => (theme.error, "ERR"),
            };
            // Determine if this worker is currently attached
            let is_attached = matches!(
                &state.view_mode,
                crate::tui::state::ViewMode::WorkerAttached { agent_id } if *agent_id == entry.agent_id
            );
            let dot_area = Rect::new(content_x, y, 2, 1);
            let dot_icon = if is_attached { "" } else { "" };
            Paragraph::new(Span::styled(dot_icon, Style::default().fg(dot_color)))
                .render(dot_area, buf);
            let name_x = content_x + 2;
            let name_trunc = truncate(&entry.agent_id, 4); // e.g. "t1"
            // Show clickable hint (▸) for completed agents that have output
            let clickable = matches!(&entry.status, SwarmAgentStatus::Completed { .. })
                && !entry.output.is_empty();
            let name_style = if is_attached {
                Style::default().fg(theme.accent).bold()
            } else {
                Style::default().fg(theme.text_muted)
            };
            let label_area = Rect::new(name_x, y, content_w.saturating_sub(2), 1);
            Paragraph::new(vec![Line::from(vec![
                Span::styled(format!(" [{name_trunc}]"), name_style),
                Span::styled(
                    format!(" {status_label}"),
                    Style::default().fg(dot_color).add_modifier(Modifier::DIM),
                ),
                Span::styled(
                    if clickable {
                        ""
                    } else if is_attached {
                        ""
                    } else {
                        ""
                    },
                    Style::default()
                        .fg(if is_attached {
                            theme.accent
                        } else {
                            theme.text_muted
                        })
                        .add_modifier(Modifier::DIM),
                ),
            ])])
            .render(label_area, buf);
            y += 1;
            // Show task preview (what this agent is working on)
            if !entry.task_preview.is_empty() && y < bottom {
                let preview_trunc =
                    truncate(&entry.task_preview, (content_w as usize).saturating_sub(4));
                y = render_dim_line(
                    &format!("{preview_trunc}"),
                    y,
                    content_x,
                    content_w,
                    buf,
                    theme,
                );
            }
            // Per-agent token usage (only when debug mode and agent has token data)
            if state.debug_mode && (entry.input_tokens > 0 || entry.output_tokens > 0) && y < bottom
            {
                let tok_line = format!(
                    "   in:{} out:{} tools:{}",
                    format_number(entry.input_tokens),
                    format_number(entry.output_tokens),
                    entry.tool_calls,
                );
                y = render_dim_line(&tok_line, y, content_x, content_w, buf, theme);
            }
        }
        if !hive.pending_conflicts.is_empty() {
            y = render_dim_line(
                &format!(" {} conflicts", hive.pending_conflicts.len()),
                y,
                content_x,
                content_w,
                buf,
                theme,
            );
        }
        y = render_blank(y, content_x, content_w, buf, theme);
    }

    // ── MCP ─────────────────────────────────────────────
    if y >= bottom {
        // no space left above debug section; skip remaining sections
    } else if state.debug_mode && state.debug_monitor.mcp_memory_bytes > 0 {
        y = render_section_header_with_suffix(
            "MCP",
            &format_bytes(state.debug_monitor.mcp_memory_bytes),
            y,
            content_x,
            content_w,
            buf,
            theme,
        );
    } else {
        y = render_section_header("MCP", y, content_x, content_w, buf, theme);
    }

    if state.mcp_servers.is_empty() {
        y = render_dim_line(" No MCP configured", y, content_x, content_w, buf, theme);
    } else {
        for entry in &state.mcp_servers {
            if y >= bottom {
                break;
            }
            let is_active = state
                .active_mcp_server
                .as_deref()
                .is_some_and(|s| s == entry.name);
            let (dot_color, name_color, status_label) = if is_active {
                (theme.accent, theme.accent, "")
            } else {
                match entry.status {
                    crate::mcp::config::McpStatus::Available => {
                        (theme.success, theme.text_muted, "")
                    }
                    crate::mcp::config::McpStatus::Unavailable => {
                        (theme.error, theme.text_muted, "n/a")
                    }
                }
            };
            let dot_area = Rect::new(content_x, y, 2, 1);
            Paragraph::new(Span::styled("", Style::default().fg(dot_color)))
                .render(dot_area, buf);
            let name_x = content_x + 2;
            let avail_w = content_w.saturating_sub(2) as usize;
            let name_trunc = if status_label.is_empty() {
                truncate(&entry.name, avail_w)
            } else {
                truncate(&entry.name, avail_w.saturating_sub(status_label.len() + 2))
            };
            let label_area = Rect::new(name_x, y, content_w.saturating_sub(2), 1);
            let mut spans = vec![Span::styled(
                format!(" {name_trunc}"),
                Style::default().fg(name_color).add_modifier(Modifier::DIM),
            )];
            if !status_label.is_empty() {
                spans.push(Span::styled(
                    format!(" {status_label}"),
                    Style::default().fg(theme.error).add_modifier(Modifier::DIM),
                ));
            }
            Paragraph::new(vec![Line::from(spans)]).render(label_area, buf);
            y += 1;
        }
    }

    y = render_blank(y, content_x, content_w, buf, theme);

    // ── LSP ─────────────────────────────────────────────
    if y >= bottom {
        // no space left above debug section; skip
    } else if state.debug_mode && state.debug_monitor.lsp_memory_bytes > 0 {
        y = render_section_header_with_suffix(
            "LSP",
            &format_bytes(state.debug_monitor.lsp_memory_bytes),
            y,
            content_x,
            content_w,
            buf,
            theme,
        );
    } else {
        y = render_section_header("LSP", y, content_x, content_w, buf, theme);
    }
    if state.installed_lsp.is_empty() {
        y = render_dim_line(
            " No LSP servers detected",
            y,
            content_x,
            content_w,
            buf,
            theme,
        );
    } else {
        for lsp in &state.installed_lsp {
            if y >= bottom {
                break;
            }
            let is_running = state.running_lsp.contains(lsp);
            let dot_color = if is_running {
                theme.success
            } else {
                theme.text_muted
            };
            let text_color = if is_running {
                theme.text
            } else {
                theme.text_muted
            };
            let dot_area = Rect::new(content_x, y, 2, 1);
            Paragraph::new(Span::styled("", Style::default().fg(dot_color)))
                .render(dot_area, buf);
            let name_area = Rect::new(content_x + 2, y, content_w.saturating_sub(2), 1);
            Paragraph::new(Span::styled(
                format!(" {lsp}"),
                Style::default().fg(text_color),
            ))
            .render(name_area, buf);
            y += 1;
        }
    }

    y = render_blank(y, content_x, content_w, buf, theme);

    // ── Changed Files ────────────────────────────────────
    if y < bottom {
        y = render_section_header("Changed Files", y, content_x, content_w, buf, theme);

        // Record where file entries start for double-click hit testing.
        state.sidebar_files_start_row.set(y);
        *state.last_sidebar_area.borrow_mut() = area;

        if state.changed_files.is_empty() {
            render_dim_line(" No changes yet", y, content_x, content_w, buf, theme);
        } else {
            // Render pre-aggregated changed files (no per-frame computation)
            let all_lines: Vec<Line> = state
                .changed_files
                .iter()
                .map(|entry| {
                    let filename = std::path::Path::new(&entry.path)
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or(&entry.path);

                    let file_trunc = truncate(filename, (content_w as usize).saturating_sub(12));
                    let adds_text = format!("+{}", entry.additions);
                    let dels_text = format!("-{}", entry.deletions);

                    Line::from(vec![
                        Span::styled(format!(" {file_trunc}"), Style::default().fg(theme.text)),
                        Span::styled(" ".to_string(), Style::default()),
                        Span::styled(adds_text, Style::default().fg(theme.success)),
                        Span::styled(" ", Style::default()),
                        Span::styled(dels_text, Style::default().fg(theme.error)),
                    ])
                })
                .collect();

            let available_h = bottom.saturating_sub(y);
            let scroll = state
                .sidebar_scroll
                .min((all_lines.len() as u16).saturating_sub(available_h));
            let files_area = Rect::new(content_x, y, content_w, available_h);
            Paragraph::new(all_lines)
                .scroll((scroll, 0))
                .render(files_area, buf);
        }
    }

    // ── Debug Monitor (pinned above footer) ─────────────────
    if state.debug_mode {
        let mut dy = bottom;
        let dbg = &state.debug_monitor;
        let tgt = &state.debug_targets;

        dy = render_blank(dy, content_x, content_w, buf, theme);
        dy = render_section_header("Debug", dy, content_x, content_w, buf, theme);

        // Memory
        let mem_str = if dbg.memory_bytes >= 1_073_741_824 {
            format!(" mem  {:.1} GB", dbg.memory_bytes as f64 / 1_073_741_824.0)
        } else {
            format!(" mem  {:.1} MB", dbg.memory_bytes as f64 / 1_048_576.0)
        };
        dy = render_dim_line(&mem_str, dy, content_x, content_w, buf, theme);

        // CPU (color-coded by usage)
        let cpu_color = if dbg.cpu_percent > 80.0 {
            theme.error
        } else if dbg.cpu_percent > 50.0 {
            theme.warning
        } else {
            theme.text_muted
        };
        dy = render_colored_line(
            &format!(" cpu  {:.1}%", dbg.cpu_percent),
            dy,
            content_x,
            content_w,
            buf,
            cpu_color,
        );

        // Tokens in/out
        dy = render_dim_line(
            &format!(" in   {} tok", format_number(dbg.input_tokens)),
            dy,
            content_x,
            content_w,
            buf,
            theme,
        );
        dy = render_dim_line(
            &format!(" out  {} tok", format_number(dbg.output_tokens)),
            dy,
            content_x,
            content_w,
            buf,
            theme,
        );

        // Tool calls & API calls
        dy = render_dim_line(
            &format!(" tool {} calls", dbg.total_tool_calls),
            dy,
            content_x,
            content_w,
            buf,
            theme,
        );
        dy = render_dim_line(
            &format!(" api  {} calls", dbg.total_api_calls),
            dy,
            content_x,
            content_w,
            buf,
            theme,
        );

        // Active agents
        let agent_color = if dbg.active_agents > 1 {
            theme.accent
        } else {
            theme.text_muted
        };
        dy = render_colored_line(
            &format!(" agents {}", dbg.active_agents),
            dy,
            content_x,
            content_w,
            buf,
            agent_color,
        );

        // ── Performance metrics (shown once data exists) ──
        let has_perf = dbg.tool_latency_avg_ms > 0.0 || dbg.api_latency_avg_ms > 0.0;
        if has_perf {
            dy = render_blank(dy, content_x, content_w, buf, theme);

            // Tool latency avg/max — highlight if avg exceeds target
            let tl_color = if dbg.tool_latency_avg_ms > tgt.tool_latency_avg_ms as f64 {
                theme.warning
            } else {
                theme.text_muted
            };
            dy = render_colored_line(
                &format!(
                    " t.avg {} t.max {}",
                    format_duration_ms(dbg.tool_latency_avg_ms),
                    format_duration_ms(dbg.tool_latency_max_ms as f64)
                ),
                dy,
                content_x,
                content_w,
                buf,
                tl_color,
            );

            // API latency avg/max — highlight if avg exceeds target
            let al_color = if dbg.api_latency_avg_ms > tgt.api_latency_avg_ms as f64 {
                theme.warning
            } else {
                theme.text_muted
            };
            dy = render_colored_line(
                &format!(
                    " a.avg {} a.max {}",
                    format_duration_ms(dbg.api_latency_avg_ms),
                    format_duration_ms(dbg.api_latency_max_ms as f64)
                ),
                dy,
                content_x,
                content_w,
                buf,
                al_color,
            );

            // Tool success rate — highlight if below target
            let sr_color = if dbg.tool_success_rate < tgt.tool_success_rate {
                theme.warning
            } else {
                theme.text_muted
            };
            dy = render_colored_line(
                &format!(" ok {:.0}%", dbg.tool_success_rate),
                dy,
                content_x,
                content_w,
                buf,
                sr_color,
            );

            // Tokens per iteration — highlight if exceeds target
            let tpi_color = if dbg.tokens_per_iteration > tgt.tokens_per_iteration as f64 {
                theme.warning
            } else {
                theme.text_muted
            };
            dy = render_colored_line(
                &format!(" tok/i {}", format_number(dbg.tokens_per_iteration as u64)),
                dy,
                content_x,
                content_w,
                buf,
                tpi_color,
            );

            // Tools per iteration — highlight if exceeds target
            let ti_color = if dbg.tools_per_iteration > tgt.tools_per_iteration as f64 {
                theme.warning
            } else {
                theme.text_muted
            };
            dy = render_colored_line(
                &format!(" t/i   {:.1}", dbg.tools_per_iteration),
                dy,
                content_x,
                content_w,
                buf,
                ti_color,
            );

            // Top 3 most called tools
            for (name, count) in dbg.top_tools.iter().take(3) {
                let name_trunc = truncate(name, (content_w as usize).saturating_sub(8));
                dy = render_dim_line(
                    &format!("  {name_trunc} {count}"),
                    dy,
                    content_x,
                    content_w,
                    buf,
                    theme,
                );
            }
        }
    }

    // ── Footer: project path + version (bottom 3 rows, status-bar aligned) ──
    // Row: area.y + area.height - 3  → blank spacer (1-char gap instead of line)
    // Row: area.y + area.height - 2  → project path
    // Row: area.y + area.height - 1  → product name + version
    let footer_top = area.y + area.height.saturating_sub(FOOTER_HEIGHT);
    // Row 0 of footer is just a blank gap — no line drawn

    // Project path (last 2 path segments)
    let short_dir = {
        let path = std::path::Path::new(working_dir);
        let parts: Vec<&str> = path
            .components()
            .filter_map(|c| c.as_os_str().to_str())
            .collect();
        match parts.len() {
            0 => working_dir.to_string(),
            1 => parts[0].to_string(),
            n => format!("{}/{}", parts[n - 2], parts[n - 1]),
        }
    };
    let proj_area = Rect::new(content_x, footer_top + 1, content_w, 1); // blank row above = spacer
    Paragraph::new(Span::styled(
        truncate(&format!(" {short_dir}"), content_w as usize),
        Style::default().fg(theme.text_muted),
    ))
    .render(proj_area, buf);

    // Product name + version
    let ver_area = Rect::new(content_x, footer_top + 2, content_w, 1);
    Paragraph::new(Span::styled(
        format!(" collet v{}", env!("CARGO_PKG_VERSION")),
        Style::default()
            .fg(theme.border)
            .add_modifier(Modifier::DIM),
    ))
    .render(ver_area, buf);
}

// ── helpers ──────────────────────────────────────────────────────────────────

fn render_section_header(
    label: &str,
    y: u16,
    x: u16,
    w: u16,
    buf: &mut Buffer,
    theme: &Theme,
) -> u16 {
    let area = Rect::new(x, y, w, 1);
    Paragraph::new(Span::styled(
        format!(" {label}"),
        Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
    ))
    .render(area, buf);
    y + 1
}

/// Section header with an optional dim suffix (e.g. "MCP" + "142 MB").
fn render_section_header_with_suffix(
    label: &str,
    suffix: &str,
    y: u16,
    x: u16,
    w: u16,
    buf: &mut Buffer,
    theme: &Theme,
) -> u16 {
    let area = Rect::new(x, y, w, 1);
    Paragraph::new(Line::from(vec![
        Span::styled(
            format!(" {label}"),
            Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            format!("  {suffix}"),
            Style::default()
                .fg(theme.text_muted)
                .add_modifier(Modifier::DIM),
        ),
    ]))
    .render(area, buf);
    y + 1
}

fn render_dim_line(text: &str, y: u16, x: u16, w: u16, buf: &mut Buffer, theme: &Theme) -> u16 {
    let area = Rect::new(x, y, w, 1);
    Paragraph::new(Span::styled(
        truncate(text, w as usize),
        Style::default().fg(theme.text_muted),
    ))
    .render(area, buf);
    y + 1
}

/// Render a line with an explicit foreground color (for threshold highlighting).
fn render_colored_line(text: &str, y: u16, x: u16, w: u16, buf: &mut Buffer, color: Color) -> u16 {
    let area = Rect::new(x, y, w, 1);
    Paragraph::new(Span::styled(
        truncate(text, w as usize),
        Style::default().fg(color),
    ))
    .render(area, buf);
    y + 1
}

/// Format milliseconds as a compact duration string (e.g., "1.2s", "450ms").
fn format_duration_ms(ms: f64) -> String {
    if ms >= 1000.0 {
        format!("{:.1}s", ms / 1000.0)
    } else {
        format!("{:.0}ms", ms)
    }
}

fn render_blank(y: u16, _x: u16, _w: u16, _buf: &mut Buffer, _theme: &Theme) -> u16 {
    y + 1
}

/// Format byte count as compact string (e.g., "52M", "1.2G").
fn format_bytes(bytes: u64) -> String {
    if bytes >= 1_073_741_824 {
        format!("{:.1} GB", bytes as f64 / 1_073_741_824.0)
    } else {
        format!("{:.1} MB", bytes as f64 / 1_048_576.0)
    }
}

/// Format a number with K/M suffixes for compact display.
fn format_number(n: u64) -> String {
    if n >= 1_000_000 {
        format!("{:.1}M", n as f64 / 1_000_000.0)
    } else if n >= 1_000 {
        format!("{:.1}K", n as f64 / 1_000.0)
    } else {
        n.to_string()
    }
}

fn truncate(s: &str, max: usize) -> String {
    use unicode_width::UnicodeWidthChar;
    if max == 0 {
        return String::new();
    }
    let mut width = 0usize;
    let mut end = s.len();
    let mut cut = false;
    for (i, c) in s.char_indices() {
        let cw = c.width().unwrap_or(1);
        if width + cw > max.saturating_sub(1) {
            end = i;
            cut = true;
            break;
        }
        width += cw;
    }
    if cut {
        format!("{}", &s[..end])
    } else {
        s.to_string()
    }
}