opencrabs 0.3.54

The autonomous, self-improving AI agent. Single Rust binary. Every channel. Install with: cargo install opencrabs
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
//! Session list rendering
//!
//! Session manager view with navigation, renaming, and status indicators.

use super::super::app::App;
use super::utils::{format_token_count_raw, format_token_count_with_label};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Wrap},
};

/// On-brand palette for project badges — variations of orange, cyan, white,
/// and blue. Each project is mapped to one entry deterministically so the same
/// project always shows the same colour and different projects stay
/// distinguishable in the session list.
const PROJECT_BADGE_COLORS: &[Color] = &[
    Color::Rgb(215, 100, 20),  // crab orange
    Color::Rgb(235, 160, 70),  // amber
    Color::Rgb(80, 200, 200),  // cyan
    Color::Rgb(90, 200, 160),  // teal
    Color::Rgb(90, 160, 220),  // blue
    Color::Rgb(150, 190, 240), // light blue
    Color::Rgb(220, 220, 220), // soft white
    Color::Rgb(180, 210, 230), // pale blue-white
];

/// Pick a stable badge colour for `project_id` from [`PROJECT_BADGE_COLORS`].
fn project_badge_color(project_id: uuid::Uuid) -> Color {
    let idx = (project_id.as_u128() % PROJECT_BADGE_COLORS.len() as u128) as usize;
    PROJECT_BADGE_COLORS[idx]
}

/// Render the sessions list
pub(super) fn render_sessions(f: &mut Frame, app: &App, area: Rect) {
    let mut lines: Vec<Line> = Vec::new();

    // Compute filtered session indices based on search
    let visible_indices: Vec<usize> = if app.session_search.is_empty() {
        (0..app.sessions.len()).collect()
    } else {
        let search = app.session_search.to_lowercase();
        app.sessions
            .iter()
            .enumerate()
            .filter(|(_, s)| {
                let name = s.title.as_deref().unwrap_or("New Chat").to_lowercase();
                name.contains(&search)
            })
            .map(|(i, _)| i)
            .collect()
    };

    lines.push(Line::from(vec![
        Span::styled(
            "  [↑↓] ",
            Style::default()
                .fg(Color::Rgb(120, 120, 120))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Navigate  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[Enter] ",
            Style::default()
                .fg(Color::Rgb(120, 120, 120))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Select  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[N] ",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("New  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[R] ",
            Style::default()
                .fg(Color::Rgb(215, 100, 20))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Rename  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[D] ",
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::styled("Delete  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[F] ",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Files  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[P] ",
            Style::default()
                .fg(Color::Rgb(120, 120, 120))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Projects  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[|] ",
            Style::default()
                .fg(Color::Rgb(80, 200, 120))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Split H  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[_] ",
            Style::default()
                .fg(Color::Rgb(80, 200, 120))
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Split V  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[/] ",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled("Search  ", Style::default().fg(Color::Reset)),
        Span::styled(
            "[Esc] ",
            Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
        ),
        Span::styled("Back", Style::default().fg(Color::Reset)),
    ]));

    // Show hint when a pane is waiting for session assignment (just split)
    let has_unassigned = app
        .pane_manager
        .focused_pane()
        .is_some_and(|p| p.session_id.is_none());
    if has_unassigned {
        lines.push(Line::from(Span::styled(
            "  Select a session for the new pane (or N for new)",
            Style::default()
                .fg(Color::Rgb(80, 200, 120))
                .add_modifier(Modifier::BOLD),
        )));
    }

    // Show assign mode banner when assigning sessions to a project
    if let Some(project_id) = app.assigning_to_project {
        let project_name = app
            .project_name_cache
            .get(&project_id)
            .map(|s| s.as_str())
            .unwrap_or("project");
        lines.push(Line::from(vec![
            Span::styled(
                format!("  ASSIGNING TO: {} ", project_name),
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "[Enter] assign  [Esc] done",
                Style::default().fg(Color::Rgb(120, 120, 120)),
            ),
        ]));
    }
    lines.push(Line::from(""));

    // Search input line
    if app.session_search_active {
        lines.push(Line::from(vec![
            Span::styled("  🔍 ", Style::default().fg(Color::Cyan)),
            Span::styled(
                format!("{}", app.session_search),
                Style::default()
                    .fg(Color::Reset)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::styled(
                "  [type to filter]  [Enter] open  [Esc] clear",
                Style::default().fg(Color::DarkGray),
            ),
        ]));
        lines.push(Line::from(""));
    }

    // Track header line count for viewport scroll calculation
    let header_line_count = lines.len();

    if visible_indices.is_empty() && !app.session_search.is_empty() {
        lines.push(Line::from(Span::styled(
            "  No matching sessions",
            Style::default().fg(Color::DarkGray),
        )));
    }

    for (display_idx, &session_idx) in visible_indices.iter().enumerate() {
        let session = &app.sessions[session_idx];
        let is_selected = display_idx == app.selected_session_index;
        let is_current = app
            .current_session
            .as_ref()
            .map(|s| s.id == session.id)
            .unwrap_or(false);

        let is_renaming = is_selected && app.session_renaming;

        let prefix = if is_selected { "  > " } else { "    " };

        let name = session.title.as_deref().unwrap_or("New Chat");
        let created = session.created_at.format("%Y-%m-%d %H:%M");

        // Format session total usage (cumulative billing tokens)
        let history_label = format_token_count_with_label(session.token_count, "total");

        // For current session, show live context window usage with actual token counts
        let context_info = if is_current {
            if let Some(input_tok) = app.last_input_tokens {
                let pct = app.context_usage_percent();
                let ctx_label = format_token_count_raw(input_tok as i32);
                let max_label = format_token_count_raw(app.context_max_tokens as i32);
                format!(" [ctx: {}/{} {:.0}%]", ctx_label, max_label, pct)
            } else {
                " [ctx: –]".to_string()
            }
        } else {
            String::new()
        };

        let current_suffix = if is_current { " *" } else { "" };

        if is_renaming {
            // Show rename input
            lines.push(Line::from(vec![
                Span::styled(prefix, Style::default().fg(Color::Rgb(215, 100, 20))),
                Span::styled(
                    format!("{}", app.session_rename_buffer),
                    Style::default()
                        .fg(Color::Reset)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::styled(
                    format!(" - {}", created),
                    Style::default().fg(Color::DarkGray),
                ),
            ]));
        } else {
            // When in assign mode, highlight sessions already assigned to
            // target project in green so the user has clear visual feedback.
            let is_assigned_to_target = app
                .assigning_to_project
                .is_some_and(|pid| session.project_id == Some(pid));

            let name_style = if is_assigned_to_target {
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD)
            } else if is_selected {
                Style::default()
                    .fg(Color::Rgb(215, 100, 20))
                    .add_modifier(Modifier::BOLD)
            } else if is_current {
                Style::default().fg(Color::Gray)
            } else {
                Style::default().fg(Color::Reset)
            };

            let mut spans = vec![
                Span::styled(format!("{}{}", prefix, name), name_style),
                Span::styled(
                    format!(" - {} ", created),
                    Style::default().fg(Color::DarkGray),
                ),
            ];

            // Provider badge
            if let Some(ref prov) = session.provider_name {
                let model_label = session.model.as_deref().unwrap_or("default");
                spans.push(Span::styled(
                    format!(" [{}/{}]", prov, model_label),
                    Style::default().fg(Color::Rgb(120, 120, 120)),
                ));
            }

            // Project badge
            if let Some(pid) = session.project_id {
                let project_name = app
                    .project_name_cache
                    .get(&pid)
                    .map(|s| s.as_str())
                    .unwrap_or("?");
                spans.push(Span::styled(
                    format!(" {{.{}}}", project_name),
                    Style::default().fg(project_badge_color(pid)),
                ));
            }

            // Working directory badge
            if let Some(ref wd) = session.working_directory {
                let home_dir = dirs::home_dir()
                    .map(|h| h.to_string_lossy().to_string())
                    .unwrap_or_default();
                let short = if !home_dir.is_empty() && wd.starts_with(&home_dir) {
                    format!("~{}", &wd[home_dir.len()..])
                } else {
                    wd.clone()
                };
                spans.push(Span::styled(
                    format!(" {}", short),
                    Style::default().fg(Color::Rgb(100, 140, 180)),
                ));
                // Git branch badge (cyan)
                if let Some(branch) =
                    crate::utils::git_branch::current_branch(std::path::Path::new(wd))
                {
                    spans.push(Span::styled(
                        format!(" ({branch})"),
                        Style::default().fg(Color::Cyan),
                    ));
                }
            }

            // History size badge
            if session.token_count > 0 {
                spans.push(Span::styled(
                    format!(" {}", history_label),
                    Style::default().fg(Color::Rgb(100, 100, 100)),
                ));
            }

            // Status indicators for background sessions
            if app.processing_sessions.contains(&session.id) {
                let spinner_chars = ['', '', '', '', '', '', '', '', '', ''];
                let frame = app.animation_frame % spinner_chars.len();
                spans.push(Span::styled(
                    format!(" {}", spinner_chars[frame]),
                    Style::default().fg(Color::Rgb(215, 100, 20)),
                ));
            } else if app.sessions_with_pending_approval.contains(&session.id) {
                spans.push(Span::styled(
                    " !",
                    Style::default()
                        .fg(Color::Rgb(215, 100, 20))
                        .add_modifier(Modifier::BOLD),
                ));
            } else if app.sessions_with_unread.contains(&session.id) {
                spans.push(Span::styled("", Style::default().fg(Color::Cyan)));
            }

            // Context usage for current session
            if !context_info.is_empty() {
                let ctx_color = if app.last_input_tokens.is_some() {
                    let ctx_pct = app.context_usage_percent();
                    if ctx_pct > 80.0 {
                        Color::Red
                    } else if ctx_pct > 50.0 {
                        Color::Rgb(215, 100, 20)
                    } else {
                        Color::Cyan
                    }
                } else {
                    Color::DarkGray
                };
                spans.push(Span::styled(context_info, Style::default().fg(ctx_color)));
            }

            // Current marker
            if !current_suffix.is_empty() {
                spans.push(Span::styled(
                    current_suffix,
                    Style::default()
                        .fg(Color::Rgb(120, 120, 120))
                        .add_modifier(Modifier::BOLD),
                ));
            }

            // Pane indicator — show which pane this session is already in
            if app.pane_manager.is_split() {
                let pane_ids = app.pane_manager.pane_ids_in_order();
                if let Some(pos) = pane_ids.iter().position(|pid| {
                    app.pane_manager
                        .get(*pid)
                        .is_some_and(|p| p.session_id == Some(session.id))
                }) {
                    spans.push(Span::styled(
                        format!(" [pane {}]", pos + 1),
                        Style::default().fg(Color::Rgb(80, 200, 120)),
                    ));
                }
            }

            lines.push(Line::from(spans));
        }
    }

    // Viewport scroll: keep the selected session visible
    let visible_height = area.height.saturating_sub(2) as usize; // inside borders
    let selected_line = header_line_count + app.selected_session_index;
    let scroll = if selected_line >= visible_height {
        (selected_line.saturating_sub(visible_height) + 1) as u16
    } else {
        0u16
    };

    let sessions = Paragraph::new(lines)
        .block(Block::default().borders(Borders::ALL).title(" Sessions "))
        .wrap(Wrap { trim: false })
        .scroll((scroll, 0));

    f.render_widget(sessions, area);
}