rpi-cli 0.35.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Startup session picker used by `-r` / `--resume`.

use std::io::IsTerminal;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseEventKind};
use rpi_tui::{
    Container, ProcessTerminal, SelectItem, SelectList, SelectListLayoutOptions, Spacer, Text,
    TuiAltScreen, TUI,
};

/// Select a project session and return its ID before the main harness is built.
///
/// Returns `Ok(None)` when the user cancels with Esc or Ctrl+C.
pub async fn select(cwd: &Path) -> Result<Option<String>, String> {
    let Some(path) = select_in_dir(cwd, &crate::session::default_session_dir(cwd)).await? else {
        return Ok(None);
    };
    crate::session::session_metadata_at(Path::new(&path))
        .map(|metadata| Some(metadata.id))
        .ok_or_else(|| format!("could not read selected session {path}"))
}

const RESUME_PICKER_MIN_PRIMARY_COLUMN_WIDTH: usize = 28;
const RESUME_PICKER_MAX_PRIMARY_COLUMN_WIDTH: usize = 72;

fn build_picker_view(items: Vec<SelectItem>) -> (Arc<Container>, Arc<SelectList>, Arc<Text>) {
    // Allow the primary column to expand up to 72 columns on wide terminals so
    // session names/previews are not clipped to the 32-column default, while
    // keeping a 28-column floor so 80-column terminals still have room for the
    // right-hand metadata (`just now · 5KB · <id>`).
    let mut list = SelectList::new(items, 12);
    list.set_layout(SelectListLayoutOptions {
        min_primary_column_width: Some(RESUME_PICKER_MIN_PRIMARY_COLUMN_WIDTH),
        max_primary_column_width: Some(RESUME_PICKER_MAX_PRIMARY_COLUMN_WIDTH),
        truncate_primary: None,
    });
    let list = Arc::new(list);
    let search = Arc::new(Text::new("  Filter: ", 0, 0));
    let root = Arc::new(Container::new());
    root.add_child(Arc::new(Text::new("Resume session", 2, 1)));
    root.add_child(Arc::new(Text::new(
        "  Type to filter · Tab: all projects · Enter to resume · Esc to cancel",
        0,
        0,
    )));
    root.add_child(Arc::new(Spacer::new(1)));
    root.add_child(search.clone());
    root.add_child(Arc::new(Spacer::new(1)));
    root.add_child(list.clone());
    (root, list, search)
}

pub(crate) async fn select_in_dir(cwd: &Path, dir: &Path) -> Result<Option<String>, String> {
    let cwd_text = cwd.to_string_lossy().into_owned();
    // Same default scope as the in-TUI `/session` picker: current project
    // first, All is an explicit Tab away (fork issue #13).
    let scope = crate::session::SessionScope::Project;
    let items = build_items(&cwd_text, dir, scope).await?;
    // Keep the picker open with zero rows: it advertises Tab for All, and a
    // fresh project must be able to reach sessions from other projects.
    // A non-TTY caller cannot drive the picker; keep the existing error-path
    // behaviour for tests and headless invocations.
    if items.is_empty() && !std::io::stdin().is_terminal() {
        return Err(format!(
            "no resumable sessions with messages for this project in {} (Tab in the picker lists all projects)",
            dir.display()
        ));
    }

    let (root, list, search) = build_picker_view(items);

    let tui = Arc::new(TuiAltScreen::new(
        Box::new(ProcessTerminal::new()),
        false,
        None,
    ));
    tui.set_layout_root(Some(root));
    // Short-lived selector, but the same native-pi frame throttle applies: its
    // keystroke bursts coalesce instead of repainting per keypress.
    tui.start_render_scheduler();
    tui.start_readerless();

    let input_tui = tui.clone();
    let input_list = list.clone();
    let input_search = search.clone();
    let input_scope = Arc::new(std::sync::Mutex::new(scope));
    let input_cwd_text = cwd_text.clone();
    let input_dir = dir.to_path_buf();
    let task = tokio::task::spawn_blocking(move || -> Result<Option<String>, String> {
        let mut state = ResumePickerState {
            cancelled: false,
            query: String::new(),
            scope: input_scope,
            list: input_list,
            search: input_search,
            cwd_text: input_cwd_text,
            dir: input_dir,
        };
        // The key loop lives on a blocking task with no runtime of its own;
        // `build_items` uses `spawn_blocking`, so drive it on a dedicated
        // current-thread runtime instead of blocking a worker of the caller's
        // multi-thread runtime.
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| format!("session picker runtime: {e}"))?;
        loop {
            match crossterm::event::poll(Duration::from_millis(100)) {
                Ok(true) => {}
                // Watchdog: a resize event can be missed, and this picker owns
                // no periodic tick of its own.
                Ok(false) => {
                    input_tui.ensure_size();
                    continue;
                }
                Err(e) => return Err(format!("could not read terminal input: {e}")),
            }
            let event = crossterm::event::read()
                .map_err(|e| format!("could not read terminal input: {e}"))?;
            match event {
                Event::Resize(..) => input_tui.note_resize(),
                other => {
                    if let Some(selected) = runtime.block_on(state.handle_event(other))? {
                        return Ok(Some(selected));
                    }
                    if state.cancelled {
                        return Ok(None);
                    }
                    input_tui.request_render(false);
                }
            }
        }
    });

    let result = task
        .await
        .map_err(|e| format!("session picker task failed: {e}"));
    tui.stop(Default::default());
    result?
}

/// Testable core of the startup picker's key loop (review #269). Keeping the
/// scope switch here lets a regression drive a bare Tab with real session
/// fixtures instead of depending on a terminal's global event queue.
struct ResumePickerState {
    query: String,
    scope: Arc<std::sync::Mutex<crate::session::SessionScope>>,
    list: Arc<SelectList>,
    search: Arc<Text>,
    cwd_text: String,
    dir: std::path::PathBuf,
    cancelled: bool,
}

impl ResumePickerState {
    /// `Ok(Some(id))` confirms a session, `Ok(None)` keeps waiting; `cancelled`
    /// distinguishes Esc/Ctrl+C from a still-open picker.
    async fn handle_event(&mut self, event: Event) -> Result<Option<String>, String> {
        match event {
            Event::Resize(..) => {}
            Event::Mouse(mouse) => {
                let code = match mouse.kind {
                    MouseEventKind::ScrollUp => Some(KeyCode::Up),
                    MouseEventKind::ScrollDown => Some(KeyCode::Down),
                    _ => None,
                };
                if let Some(code) = code {
                    self.list
                        .handle_key(KeyEvent::new(code, KeyModifiers::NONE));
                }
            }
            Event::Key(key) if key.kind != KeyEventKind::Release => {
                if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
                    self.cancelled = true;
                    return Ok(None);
                }
                match key.code {
                    KeyCode::Enter => {
                        return Ok(self.list.get_selected_item().map(|item| item.value));
                    }
                    KeyCode::Esc if self.query.is_empty() => {
                        self.cancelled = true;
                        return Ok(None);
                    }
                    KeyCode::Esc => {
                        self.query.clear();
                        self.list.set_filter("");
                    }
                    KeyCode::Tab if key.modifiers == KeyModifiers::NONE => {
                        let next = {
                            let mut current = self.scope.lock().unwrap();
                            let next = current.toggled();
                            *current = next;
                            next
                        };
                        let items = build_items(&self.cwd_text, &self.dir, next).await?;
                        self.list.set_items(items);
                        self.list.set_filter(&self.query);
                    }
                    KeyCode::Backspace => {
                        self.query.pop();
                        self.list.set_filter(&self.query);
                    }
                    KeyCode::Char(ch)
                        if !key
                            .modifiers
                            .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
                    {
                        self.query.push(ch);
                        self.list.set_filter(&self.query);
                    }
                    _ => self.list.handle_key(key),
                }
                self.search.set_text(format!("  Filter: {}", self.query));
            }
            _ => {}
        }
        Ok(None)
    }
}

/// Build picker rows for one scope. All rows carry their project cwd so the
/// All view stays attributable; the Project view lists only this cwd's
/// directory via the repo's own typed list API.
async fn build_items(
    cwd_text: &str,
    dir: &Path,
    scope: crate::session::SessionScope,
) -> Result<Vec<SelectItem>, String> {
    let metadata = crate::session::list_session_metadata_in_scope_in_dir(cwd_text, dir, scope)
        .await
        .map_err(|e| e.to_string())?;
    // Each summary opens + reads a (bounded) slice of the session file. That is
    // blocking file I/O over every saved session, so keep it off the async
    // runtime the TUI will later run on.
    let metas_for_summary = metadata.clone();
    let summaries = tokio::task::spawn_blocking(move || {
        metas_for_summary
            .iter()
            .map(|meta| crate::session::summarize_session_file(Path::new(&meta.path)))
            .collect::<Vec<_>>()
    })
    .await
    .map_err(|e| format!("session summary task failed: {e}"))?;
    let now_ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis()
        .min(i64::MAX as u128) as i64;
    let mut items: Vec<SelectItem> = Vec::new();
    for (meta, summary) in metadata.iter().zip(summaries.iter()) {
        if summary.empty {
            continue;
        }
        let file_name = Path::new(&meta.path)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(&meta.id);
        let label = crate::session::session_display_label(summary);
        let short_id = crate::session::short_session_id(&meta.id);
        let mut description = format!(
            "{} · {} · {}",
            format_modified_age(now_ms, meta.modified_at),
            crate::session::format_session_bytes(summary.bytes),
            short_id,
        );
        if scope == crate::session::SessionScope::All {
            description = format!("{} · {}", short_project_name(&meta.cwd), description);
        }
        items.push(
            SelectItem::new(&meta.path, &label)
                .with_description(&description)
                .with_search_text(&format!("{label} {short_id} {file_name}")),
        );
    }
    Ok(items)
}

/// Last path component of a project cwd, for a compact All-view tag.
fn short_project_name(cwd: &str) -> String {
    Path::new(cwd)
        .file_name()
        .and_then(|name| name.to_str())
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .unwrap_or_else(|| cwd.to_string())
}

fn format_modified_age(now_ms: i64, modified_ms: i64) -> String {
    let seconds = now_ms.saturating_sub(modified_ms).max(0) / 1000;
    match seconds {
        0..=59 => "just now".to_string(),
        60..=3_599 => format!("{}m ago", seconds / 60),
        3_600..=86_399 => format!("{}h ago", seconds / 3_600),
        _ => format!("{}d ago", seconds / 86_400),
    }
}

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

    /// Review #269: the startup `-r` picker must not early-return on an empty
    /// Project view. Drive the real key handler with a bare Tab against real
    /// session fixtures and assert the foreign session becomes selectable.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn review269_empty_project_can_browse_foreign_sessions() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("sessions");
        let cwd = tmp.path().join("fresh-project");
        let foreign_cwd = tmp.path().join("another-project");
        std::fs::create_dir_all(&cwd).unwrap();
        std::fs::create_dir_all(&foreign_cwd).unwrap();
        let foreign = crate::session::create_jsonl_session(&root, &foreign_cwd.to_string_lossy())
            .await
            .unwrap();
        foreign
            .append_message(rpi_agent::message::AgentMessage::from(
                rpi_ai::types::UserMessage::new("foreign project prompt", 42),
            ))
            .await
            .unwrap();
        let foreign_id = foreign.storage().metadata().id.clone();
        drop(foreign);

        let scope = crate::session::SessionScope::Project;
        let items = build_items(&cwd.to_string_lossy(), &root, scope)
            .await
            .unwrap();
        assert!(items.is_empty(), "the fresh project has no sessions");
        let list = Arc::new(SelectList::new(items, 12));
        let mut state = ResumePickerState {
            cancelled: false,
            query: String::new(),
            scope: Arc::new(std::sync::Mutex::new(scope)),
            list: list.clone(),
            search: Arc::new(Text::new("  Filter: ", 0, 0)),
            cwd_text: cwd.to_string_lossy().into_owned(),
            dir: root.clone(),
        };
        let tab = Event::Key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
        assert!(state.handle_event(tab).await.unwrap().is_none());
        assert_eq!(
            *state.scope.lock().unwrap(),
            crate::session::SessionScope::All
        );
        let selected = list.get_selected_item().expect("All must have a row");
        assert!(Path::new(&selected.value).is_absolute());
        assert_eq!(
            crate::session::session_metadata_at(Path::new(&selected.value))
                .unwrap()
                .id,
            foreign_id
        );
        assert!(
            selected
                .description
                .as_deref()
                .unwrap_or_default()
                .contains("another-project"),
            "All rows must carry their project tag: {selected:?}"
        );
        let enter = Event::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        assert_eq!(
            state.handle_event(enter).await.unwrap(),
            Some(selected.value)
        );
    }

    #[test]
    fn modified_age_is_compact_and_stable() {
        let now = 10 * 86_400_000;
        assert_eq!(format_modified_age(now, now - 20_000), "just now");
        assert_eq!(format_modified_age(now, now - 5 * 60_000), "5m ago");
        assert_eq!(format_modified_age(now, now - 3 * 3_600_000), "3h ago");
        assert_eq!(format_modified_age(now, now - 2 * 86_400_000), "2d ago");
    }

    #[test]
    fn label_falls_back_from_name_to_preview_to_marker() {
        use crate::session::{session_display_label, SessionSummary};
        let named = SessionSummary {
            name: Some("fix resume picker".into()),
            preview: Some("a different prompt".into()),
            ..Default::default()
        };
        assert_eq!(session_display_label(&named), "fix resume picker");

        let preview = SessionSummary {
            name: Some("   ".into()),
            preview: Some("读取下当前 rpi -r 命令".into()),
            ..Default::default()
        };
        assert_eq!(session_display_label(&preview), "读取下当前 rpi -r 命令");

        let bare = SessionSummary::default();
        assert_eq!(session_display_label(&bare), "(no messages)");
    }

    #[test]
    fn byte_and_id_formatting_is_compact() {
        use crate::session::{format_session_bytes, short_session_id};
        assert_eq!(format_session_bytes(512), "512B");
        assert_eq!(format_session_bytes(34 * 1024), "34KB");
        assert_eq!(format_session_bytes(1_258_291), "1.2MB");
        assert_eq!(
            short_session_id("01a0d919-6742-70db-a206-9f5ed4cf665a"),
            "01a0d919"
        );
        assert_eq!(short_session_id("abc"), "abc");
        assert_eq!(short_session_id("abcdefg中xyz"), "abcdefg中");
    }

    #[test]
    fn picker_header_lines_share_two_column_left_indent() {
        use rpi_tui::{strip_ansi, Component};

        let (root, _, _) = build_picker_view(vec![
            SelectItem::new("s1", "Demo session").with_description("just now · 5KB · demo-ric")
        ]);
        let rendered: Vec<String> = root
            .render(120)
            .into_iter()
            .map(|l| strip_ansi(&l))
            .collect();

        let title = rendered
            .iter()
            .find(|l| l.contains("Resume session"))
            .expect("title line must render");
        let hint = rendered
            .iter()
            .find(|l| l.contains("Type to filter"))
            .expect("hint line must render");
        let filter = rendered
            .iter()
            .find(|l| l.contains("Filter:"))
            .expect("filter line must render");

        let leading_spaces = |line: &str| line.chars().take_while(|&c| c == ' ').count();
        assert_eq!(leading_spaces(title), 2, "title indent: {title:?}");
        assert_eq!(leading_spaces(hint), 2, "hint indent: {hint:?}");
        assert_eq!(leading_spaces(filter), 2, "filter indent: {filter:?}");
    }

    #[test]
    fn narrow_terminal_preserves_right_hand_session_metadata() {
        use rpi_tui::{strip_ansi, Component};

        let (root, _, _) = build_picker_view(vec![
            SelectItem::new("s1", "Rich markdown layout audit session")
                .with_description("just now · 5KB · demo-ric"),
            SelectItem::new("s2", "Second follow-up check")
                .with_description("just now · 1KB · demo-sec"),
        ]);
        let rendered: Vec<String> = root
            .render(80)
            .into_iter()
            .map(|l| strip_ansi(&l))
            .collect();

        assert!(
            rendered
                .iter()
                .any(|l| l.contains("just now · 5KB · demo-ric")),
            "80-column picker must not clip short id metadata: {rendered:#?}"
        );
        assert!(
            rendered
                .iter()
                .any(|l| l.contains("just now · 1KB · demo-sec")),
            "80-column picker must not clip second row metadata: {rendered:#?}"
        );
    }
}