opencrabs 0.3.57

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Tool call rendering
//!
//! Tool group display, inline approval dialogs, and approval policy menu.

use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};

/// Render a grouped tool call display (● bullet with tree lines)
pub(super) fn render_tool_group<'a>(
    lines: &mut Vec<Line<'a>>,
    group: &super::super::app::ToolCallGroup,
    is_active: bool,
    animation_frame: usize,
    content_width: usize,
) {
    // Header line: ● Processing: <tool> or ● N tool calls
    let header = if is_active {
        if let Some(last) = group.calls.last() {
            format!("Processing: {}", last.description)
        } else {
            "Processing".to_string()
        }
    } else {
        let count = group.calls.len();
        format!("{} tool call{}", count, if count == 1 { "" } else { "s" })
    };

    // Flash the dot while active (slow pulse: ~8 ticks on, ~8 ticks off = ~1.6s cycle)
    let dot = if is_active && (animation_frame / 8).is_multiple_of(2) {
        ""
    } else {
        ""
    };

    let mut header_spans = vec![Span::styled(
        format!("  {} {}", dot, header),
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )];
    header_spans.push(Span::styled(
        if group.expanded {
            " (ctrl+o to collapse)"
        } else {
            " (ctrl+o to expand)"
        },
        Style::default().fg(Color::Rgb(100, 100, 100)),
    ));
    lines.push(Line::from(header_spans));

    if group.expanded {
        // Show all calls with tree lines + full input + details
        let is_last_call = |i: usize| i == group.calls.len() - 1;
        for (i, call) in group.calls.iter().enumerate() {
            let connector = if is_last_call(i) { "└─" } else { "├─" };
            let continuation = if is_last_call(i) { "   " } else { "" };
            let in_flight = !call.completed;

            let header_style = if call.success || in_flight {
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC)
            } else {
                Style::default()
                    .fg(Color::Red)
                    .add_modifier(Modifier::ITALIC)
            };
            {
                let desc_line = Line::from(vec![
                    Span::styled(
                        format!("    {} ", connector),
                        Style::default().fg(Color::DarkGray),
                    ),
                    Span::styled(call.description.clone(), header_style),
                ]);
                for wrapped in
                    super::utils::wrap_line_with_padding(desc_line, content_width, "       ")
                {
                    lines.push(wrapped);
                }
            }

            // Show full tool input parameters (untruncated) below the header
            let safe_call_input = crate::utils::redact_tool_input(&call.tool_input);
            if !safe_call_input.is_null()
                && let Some(obj) = safe_call_input.as_object()
            {
                for (key, value) in obj.iter() {
                    // Key label
                    lines.push(Line::from(vec![
                        Span::styled(
                            format!("    {}  ", continuation),
                            Style::default().fg(Color::DarkGray),
                        ),
                        Span::styled(
                            format!("{}:", key),
                            Style::default()
                                .fg(Color::Rgb(100, 100, 100))
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]));
                    // Value — expand strings line by line, cap at 200 lines.
                    //
                    // Models periodically emit tool args where multi-line
                    // payloads use the literal escape sequence `\n`
                    // (backslash + n) instead of actual newline bytes —
                    // either because the args body got JSON-stringified
                    // once too many times, or because the model copied
                    // a Rust string literal verbatim into the arg slot.
                    // When that happens, `s.lines()` doesn't split (it
                    // only sees actual `\n`/`\r\n` chars), so the entire
                    // multi-line payload becomes one logical line that
                    // ratatui then wraps at the content width — visible
                    // as `chars. Cap is 40. Shorten it.",\n  opt,\n  ...`
                    // all run together with literal `\n` separators.
                    // Reported 2026-06-01 on a qwen Edit tool call where
                    // a 7-line `old_string` rendered as one wrapped
                    // soup. Unescape the common JSON-shape sequences
                    // before splitting.
                    let value_lines: Vec<String> = match value {
                        serde_json::Value::String(s) => unescape_display_string(s)
                            .lines()
                            .map(|l| l.to_string())
                            .collect(),
                        _ => vec![value.to_string()],
                    };
                    let total = value_lines.len();
                    for vline in value_lines.iter().take(200) {
                        let full_line = Line::from(vec![
                            Span::styled(
                                format!("    {}    ", continuation),
                                Style::default().fg(Color::DarkGray),
                            ),
                            Span::styled(
                                vline.clone(),
                                Style::default().fg(Color::Rgb(170, 170, 170)),
                            ),
                        ]);
                        for wrapped in
                            super::utils::wrap_line_with_padding(full_line, content_width, "  ")
                        {
                            lines.push(wrapped);
                        }
                    }
                    if total > 200 {
                        lines.push(Line::from(vec![
                            Span::styled(
                                format!("    {}    ", continuation),
                                Style::default().fg(Color::DarkGray),
                            ),
                            Span::styled(
                                format!("... ({} more lines)", total - 200),
                                Style::default()
                                    .fg(Color::Rgb(120, 120, 120))
                                    .add_modifier(Modifier::ITALIC),
                            ),
                        ]));
                    }
                }
            }

            // If the call is still in-flight, show a running indicator
            if in_flight {
                let spinner_frames = ["", "", "", "", "", "", "", "", "", ""];
                let frame = spinner_frames[animation_frame % spinner_frames.len()];
                lines.push(Line::from(vec![
                    Span::styled(
                        format!("    {}  {} ", continuation, frame),
                        Style::default().fg(Color::Rgb(120, 120, 120)),
                    ),
                    Span::styled("running...", Style::default().fg(Color::Rgb(215, 100, 20))),
                ]));
            } else {
                // Show tool output details (with secrets redacted)
                if let Some(ref details) = call.details {
                    let detail_lines =
                        collapse_build_output(&crate::utils::redact_secrets(details));
                    let default_detail_style = Style::default().fg(Color::Rgb(90, 90, 90));
                    for detail_line in detail_lines.iter().take(200) {
                        let line_style = if detail_line.starts_with("+ ") {
                            Style::default().fg(Color::Rgb(60, 185, 185))
                        } else if detail_line.starts_with("- ") {
                            Style::default().fg(Color::Rgb(220, 80, 80))
                        } else if detail_line.starts_with("@@ ") {
                            Style::default().fg(Color::Cyan)
                        } else {
                            default_detail_style
                        };
                        let full_line = Line::from(vec![
                            Span::styled(
                                format!("    {}  ", continuation),
                                Style::default().fg(Color::DarkGray),
                            ),
                            Span::styled(detail_line.clone(), line_style),
                        ]);
                        for wrapped in
                            super::utils::wrap_line_with_padding(full_line, content_width, "  ")
                        {
                            lines.push(wrapped);
                        }
                    }
                    if detail_lines.len() > 200 {
                        lines.push(Line::from(vec![
                            Span::styled(
                                format!("    {}  ", continuation),
                                Style::default().fg(Color::DarkGray),
                            ),
                            Span::styled(
                                format!("... ({} more lines)", detail_lines.len() - 200),
                                Style::default()
                                    .fg(Color::Rgb(120, 120, 120))
                                    .add_modifier(Modifier::ITALIC),
                            ),
                        ]));
                    }
                }
            }
        }
    } else {
        // Collapsed: show only the last call (rolling wheel effect)
        if let Some(last) = group.calls.last() {
            let style = if last.success {
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC)
            } else {
                Style::default()
                    .fg(Color::Red)
                    .add_modifier(Modifier::ITALIC)
            };
            {
                let desc_line = Line::from(vec![
                    Span::styled("    └─ ".to_string(), Style::default().fg(Color::DarkGray)),
                    Span::styled(last.description.clone(), style),
                ]);
                for wrapped in
                    super::utils::wrap_line_with_padding(desc_line, content_width, "       ")
                {
                    lines.push(wrapped);
                }
            }
        }
    }
}

/// Render an inline approval request or resolved approval
pub(super) fn render_inline_approval<'a>(
    lines: &mut Vec<Line<'a>>,
    approval: &super::super::app::ApprovalData,
    content_width: usize,
) {
    use super::super::app::ApprovalState;

    match &approval.state {
        ApprovalState::Pending => {
            // Header: brief description of what's being requested
            let desc = super::super::app::App::format_tool_description(
                &approval.tool_name,
                &approval.tool_input,
            );
            lines.push(Line::from(vec![
                Span::styled("  ", Style::default()),
                Span::styled(
                    desc,
                    Style::default()
                        .fg(Color::Reset)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));

            // Always show hint so users know V expands full details
            lines.push(Line::from(vec![Span::styled(
                if approval.show_details {
                    "  [V] collapse  [←→] navigate  [Enter] confirm"
                } else {
                    "  [V] expand full details  [←→] navigate  [Enter] confirm"
                },
                Style::default().fg(Color::Rgb(80, 80, 80)),
            )]));

            // Expanded details: show all params fully, no truncation
            let safe_approval_input = crate::utils::redact_tool_input(&approval.tool_input);
            if approval.show_details {
                if let Some(obj) = safe_approval_input.as_object() {
                    for (key, value) in obj.iter() {
                        lines.push(Line::from(vec![Span::styled(
                            format!("    {}:", key),
                            Style::default()
                                .fg(Color::DarkGray)
                                .add_modifier(Modifier::BOLD),
                        )]));
                        // Build owned lines so there are no borrow conflicts
                        let value_lines: Vec<String> = match value {
                            serde_json::Value::String(s) => {
                                s.lines().map(|l| l.to_string()).collect()
                            }
                            _ => vec![value.to_string()],
                        };
                        let total = value_lines.len();
                        for vline in value_lines.iter().take(60) {
                            let full_line = Line::from(vec![
                                Span::styled("      ", Style::default()),
                                Span::styled(
                                    vline.clone(),
                                    Style::default().fg(Color::Rgb(200, 200, 200)),
                                ),
                            ]);
                            for wrapped in
                                super::utils::wrap_line_with_padding(full_line, content_width, "  ")
                            {
                                lines.push(wrapped);
                            }
                        }
                        if total > 60 {
                            lines.push(Line::from(vec![
                                Span::styled("      ", Style::default()),
                                Span::styled(
                                    format!("... ({} more lines)", total - 60),
                                    Style::default()
                                        .fg(Color::Rgb(120, 120, 120))
                                        .add_modifier(Modifier::ITALIC),
                                ),
                            ]));
                        }
                    }
                }
                // Show capabilities if the tool declares any
                if !approval.capabilities.is_empty() {
                    lines.push(Line::from(vec![Span::styled(
                        "    capabilities:",
                        Style::default()
                            .fg(Color::DarkGray)
                            .add_modifier(Modifier::BOLD),
                    )]));
                    lines.push(Line::from(vec![
                        Span::styled("      ", Style::default()),
                        Span::styled(
                            approval.capabilities.join(", "),
                            Style::default().fg(Color::Rgb(215, 100, 20)),
                        ),
                    ]));
                }
                lines.push(Line::from(""));
            }

            // "Do you approve?" + vertical option list with ❯ selector
            // Order: Yes(0), Always(1), No(2)
            lines.push(Line::from(vec![Span::styled(
                "  Do you approve?",
                Style::default().fg(Color::DarkGray),
            )]));
            let options = [
                ("Yes", Color::Cyan),
                ("Always", Color::Rgb(215, 100, 20)),
                ("No", Color::Red),
            ];
            for (i, (label, color)) in options.iter().enumerate() {
                if i == approval.selected_option {
                    lines.push(Line::from(vec![
                        Span::styled(
                            format!("  {} ", "\u{276F}"),
                            Style::default().fg(*color).add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(
                            label.to_string(),
                            Style::default().fg(*color).add_modifier(Modifier::BOLD),
                        ),
                    ]));
                } else {
                    lines.push(Line::from(vec![
                        Span::styled("    ", Style::default()),
                        Span::styled(label.to_string(), Style::default().fg(Color::DarkGray)),
                    ]));
                }
            }
        }
        ApprovalState::Approved(_option) => {
            // Silently skip — tool execution is already shown in the tool group
        }
        ApprovalState::Denied(reason) => {
            let desc = super::super::app::App::format_tool_description(
                &approval.tool_name,
                &approval.tool_input,
            );
            let suffix = if reason.is_empty() {
                String::new()
            } else {
                format!(": {}", reason)
            };
            lines.push(Line::from(vec![Span::styled(
                format!("  {} -- denied{}", desc, suffix),
                Style::default()
                    .fg(Color::Red)
                    .add_modifier(Modifier::ITALIC),
            )]));
        }
    }
}

/// Collapse consecutive cargo build progress lines into a summary.
///
/// Lines like "Compiling foo v1.0", "Downloading crates...", "Checking bar v2.0"
/// are collapsed into a single summary line like "Compiled 47 crates".
/// Non-build lines (errors, warnings, test output) pass through unchanged.
pub(crate) fn collapse_build_output(details: &str) -> Vec<String> {
    let build_prefixes = [
        "   Compiling ",
        "   Checking ",
        "  Downloading ",
        "    Updating ",
        "   Documenting ",
        "     Running ",
        "       Fresh ",
        "    Fetching ",
        "  Downloaded ",
        "     Locking ",
        "   Packaging ",
    ];

    let mut result: Vec<String> = Vec::new();
    let mut build_count: usize = 0;
    let mut last_build_verb = "";

    let flush_build = |result: &mut Vec<String>, count: usize, verb: &str| {
        if count > 0 {
            let label = match verb {
                "Compiling" | "Checking" => "Compiled",
                "Downloading" | "Downloaded" | "Fetching" => "Downloaded",
                _ => "Processed",
            };
            result.push(format!("   {} {} crates", label, count));
        }
    };

    for line in details.lines() {
        let trimmed = line.trim_start();
        let is_build = build_prefixes.iter().any(|prefix| line.starts_with(prefix));
        // Also match "Finished" lines (e.g. "Finished `dev` profile")
        let is_finished = trimmed.starts_with("Finished ");

        if is_build {
            // Extract verb for grouping
            let verb = trimmed.split_whitespace().next().unwrap_or("");
            if build_count > 0 && verb != last_build_verb {
                flush_build(&mut result, build_count, last_build_verb);
                build_count = 0;
            }
            last_build_verb = verb;
            build_count += 1;
        } else {
            flush_build(&mut result, build_count, last_build_verb);
            build_count = 0;
            if !is_finished || result.is_empty() {
                result.push(line.to_string());
            } else {
                // Replace "Finished" with a cleaner version
                result.push(line.to_string());
            }
        }
    }
    flush_build(&mut result, build_count, last_build_verb);

    result
}

/// Render the /approve policy selector menu
pub(super) fn render_approve_menu<'a>(
    lines: &mut Vec<Line<'a>>,
    menu: &super::super::app::ApproveMenu,
    _content_width: usize,
) {
    use super::super::app::ApproveMenuState;

    match &menu.state {
        ApproveMenuState::Pending => {
            let gold = Color::Rgb(215, 100, 20);

            lines.push(Line::from(vec![Span::styled(
                "  TOOL APPROVAL POLICY",
                Style::default().fg(gold).add_modifier(Modifier::BOLD),
            )]));
            lines.push(Line::from(""));

            let options = [
                ("Approve-only", "Always ask before executing tools"),
                (
                    "Allow all (session)",
                    "Auto-approve all tools for this session",
                ),
                (
                    "Yolo mode",
                    "Execute everything without approval until reset",
                ),
            ];

            lines.push(Line::from(Span::styled(
                "  Select a policy:",
                Style::default().fg(Color::Gray),
            )));
            lines.push(Line::from(""));

            for (i, (label, desc)) in options.iter().enumerate() {
                let is_selected = i == menu.selected_option;
                let prefix = if is_selected { "\u{25b6} " } else { "  " };

                let style = if is_selected {
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(Color::Reset)
                };

                lines.push(Line::from(vec![
                    Span::raw("  "),
                    Span::styled(format!("{}{}", prefix, label), style),
                ]));

                if is_selected {
                    lines.push(Line::from(vec![
                        Span::raw("      "),
                        Span::styled(
                            *desc,
                            Style::default()
                                .fg(Color::DarkGray)
                                .add_modifier(Modifier::ITALIC),
                        ),
                    ]));
                }
            }

            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                "  [\u{2191}\u{2193}] Navigate  [Enter] Confirm  [Esc] Cancel",
                Style::default().fg(Color::DarkGray),
            )));
        }
        ApproveMenuState::Selected(choice) => {
            let (label, color) = match choice {
                0 => ("Approve-only", Color::Cyan),
                1 => ("Allow all (session)", Color::Rgb(215, 100, 20)),
                2 => ("Yolo mode", Color::Red),
                _ => ("Cancelled", Color::DarkGray),
            };
            lines.push(Line::from(vec![Span::styled(
                format!("  Policy set: {}", label),
                Style::default().fg(color).add_modifier(Modifier::ITALIC),
            )]));
        }
    }
}

/// Unescape common JSON-shape escape sequences in a tool-arg string
/// so the renderer can split on real newlines. Used when the model
/// emitted `"old_string": "fn foo()\\n{\\n}"` (literal backslash-n)
/// instead of `"old_string": "fn foo()\n{\n}"` (actual newline bytes).
///
/// Conservative replacement: only the sequences we KNOW would break
/// the line-by-line display when present as literal escapes. Doesn't
/// touch JSON-only escapes (`\u00XX`, `\/`) or anything that could
/// silently distort the meaning of code being edited. If the source
/// genuinely contains the two-char sequence `\n` (e.g. a Rust string
/// literal showing escape syntax in documentation), the resulting
/// false-positive is an actual newline in the preview — acceptable
/// trade-off since the preview is for human display, not editing.
pub(crate) fn unescape_display_string(s: &str) -> String {
    // Skip the work for the common case where no escapes are present.
    if !s.contains('\\') {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\\' {
            match chars.peek() {
                Some('n') => {
                    chars.next();
                    out.push('\n');
                }
                Some('t') => {
                    chars.next();
                    out.push_str("    ");
                }
                Some('r') => {
                    chars.next();
                    // Drop literal \r — multiline renderer treats \n as
                    // the only line separator, and a trailing \r would
                    // show as a control character on Linux/macOS.
                }
                Some('"') => {
                    chars.next();
                    out.push('"');
                }
                Some('\\') => {
                    chars.next();
                    out.push('\\');
                }
                _ => out.push(c),
            }
        } else {
            out.push(c);
        }
    }
    out
}