quvyta-cli 0.1.0-alpha.4

A small coding agent in the terminal: chat with a model that reads, searches, edits and runs in one folder, and asks before it changes anything (alpha)
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
//! What the chat looks like: the conversation with what is streaming in and, at its end, the card
//! of an action waiting for an answer; under it the writing field.

use std::cell::RefCell;
use std::collections::HashMap;

use qframe::i18n;
use qframe::keymap::KeyChord;
use qframe::prelude::*;
use qframe::text;
use qframe::widgets::{CodeView, Language, LineMark, Markdown, ScrollView, Spinner, StatusLine, TextInput, ToastKind};
use serde_json::Value;

use super::{Live, Msg, Notice, Phase, QCli};
use crate::actions::{Action, ActionKind, Change, Preview};
use crate::conversation;
use crate::instructions::AGENTS_FILE;
use crate::provider::KeyError;

/// The id of the button that allows the action on the card.
pub const ALLOW: &str = "allow";

/// The id of the button that declines the action on the card.
pub const DENY: &str = "deny";

/// The id of the writing field.
pub const INPUT: &str = "input";

/// How many lines of an action's result are shown under it. The model reads all of it; the
/// person sees enough to follow along.
const RESULT_LINES: usize = 3;

/// How many of the last lines of a running command's output are shown while it runs.
const TAIL_LINES: usize = 5;

pub(super) fn view(app: &QCli, ui: &mut View<'_, Msg>) {
    AppShell::new()
        .header(|ui| header(app, ui))
        .body(|ui| {
            ui.column(|ui| {
                ui.add_with(ScrollView::new().follow_end(true), |ui| {
                    ui.column(|ui| {
                        transcript(app, ui);
                        app.answers.settle();
                        live(app, ui);
                        status(app, ui);
                        if let Phase::Asking { action, preview, ready, .. } = &app.phase {
                            card(ui, action, preview, *ready);
                            if !ready {
                                let shown = app.card;
                                ui.on_idle(super::QUIET, move |quiet| Msg::Quiet(shown, quiet));
                            }
                        }
                    })
                    .gap(1)
                    .padding(Padding::symmetric(1, 2));
                })
                .id(format!("conversation-{}", app.turn))
                .fill();
                input(app, ui);
            })
            .fill();
        })
        .footer(|ui| {
            ui.add(
                KeyHints::new()
                    .hint("enter", t!("keys.send"))
                    .action(Scope::App, "stop")
                    .action(Scope::App, "new")
                    .action(Scope::App, "provider")
                    .action_right(Scope::Global, "quit"),
            );
        })
        .show(ui);
    if let Some(form) = &app.form {
        form.view(ui);
    }
}

/// The top bar: qcli's name, the folder, and the model. When they do not all fit, the model goes
/// first, whole; then the folder is shortened in its middle, keeping its start and its end; the
/// name goes last, and is never cut.
fn header(app: &QCli, ui: &mut View<'_, Msg>) {
    let folder = app
        .workspace
        .root()
        .file_name()
        .map_or_else(|| app.workspace.root().display().to_string(), |name| name.to_string_lossy().into_owned());
    let name = t!("app.name");
    let model = if app.provider.model.is_empty() { t!("header.no-model") } else { app.provider.model.clone() };
    let room = ui.size().width.saturating_sub(2 * BAR_MARGIN);
    let (name_w, folder_w, model_w) = (text::width(&name), text::width(&folder), text::width(&model));
    let with_model = name_w + BAR_GAP + folder_w + 2 * BAR_GAP + model_w;
    let left_for_folder = room.saturating_sub(name_w + BAR_GAP);
    let (show_name, folder, show_model) = if with_model <= room {
        (true, folder, true)
    } else if left_for_folder >= FOLDER_AT_LEAST.min(folder_w) {
        (true, text::truncate_middle(&folder, left_for_folder).into_owned(), false)
    } else if room >= FOLDER_AT_LEAST.min(folder_w) {
        (false, text::truncate_middle(&folder, room).into_owned(), false)
    } else {
        (false, String::new(), false)
    };
    ui.row(|ui| {
        if show_name {
            ui.add(Text::new(name).bold().color("accent").no_wrap());
        }
        if !folder.is_empty() {
            ui.add(Text::new(folder).no_wrap());
        }
        if show_model {
            ui.spacer();
            ui.add(Text::new(model).role("secondary").no_wrap());
        }
    })
    .gap(BAR_GAP)
    .padding(Padding::symmetric(0, BAR_MARGIN));
}

/// The cells the top bar keeps free at each side.
const BAR_MARGIN: u16 = 2;

/// The cells between two parts of the top bar.
const BAR_GAP: u16 = 2;

/// The fewest cells a shortened folder name is shown in; shorter than this it says nothing.
const FOLDER_AT_LEAST: u16 = 8;

/// The conversation so far, as it was saved.
fn transcript(app: &QCli, ui: &mut View<'_, Msg>) {
    let messages = app.conversation.messages();
    if messages.is_empty() {
        let mut spans = vec![Span::new(t!("chat.empty"))];
        if app.agents {
            spans.push(Span::new(" "));
            spans.push(Span::new(t!("chat.agents", file = AGENTS_FILE)));
        }
        ui.add(Text::rich(spans).role("secondary"));
        return;
    }
    let results: HashMap<&str, (&str, bool)> = messages
        .iter()
        .flat_map(conversation::blocks)
        .filter(|block| block["type"] == "tool_result")
        .map(|block| {
            let text = block["content"].as_str().unwrap_or_default();
            (block["tool_use_id"].as_str().unwrap_or_default(), (text, block["is_error"] == true))
        })
        .collect();
    for message in messages {
        let from_person = message["role"] == "user";
        for block in conversation::blocks(message) {
            match block["type"].as_str().unwrap_or_default() {
                "text" if from_person => said(ui, block["text"].as_str().unwrap_or_default()),
                "text" => app.answers.draw(ui, block["text"].as_str().unwrap_or_default()),
                "thinking" => thinking(ui, block["thinking"].as_str().unwrap_or_default()),
                "tool_use" => {
                    let id = block["id"].as_str().unwrap_or_default();
                    call(app, ui, block, results.get(id).copied());
                }
                _ => {}
            }
        }
    }
}

fn said(ui: &mut View<'_, Msg>, text: &str) {
    ui.add_with(Panel::new(), |ui| {
        ui.add(Text::new(text)).selectable(true);
    });
}

fn answer(ui: &mut View<'_, Msg>, text: &str) {
    if !text.trim().is_empty() {
        ui.add(Markdown::new(text));
    }
}

/// The documents of the saved answers, kept from one frame to the next. The framework remembers
/// only the last few documents it parsed, and a conversation shows every answer it has on each
/// frame: past a handful of answers each of them was parsed and wrapped again on every frame,
/// every streamed piece and every key. An answer no longer drawn is let go at the frame's end.
#[derive(Default)]
pub(super) struct Answers(RefCell<HashMap<String, (Markdown, bool)>>);

impl Answers {
    fn draw(&self, ui: &mut View<'_, Msg>, text: &str) {
        if text.trim().is_empty() {
            return;
        }
        let mut answers = self.0.borrow_mut();
        let markdown = if let Some((markdown, drawn)) = answers.get_mut(text) {
            *drawn = true;
            markdown.clone()
        } else {
            let markdown = Markdown::new(text);
            answers.insert(text.to_owned(), (markdown.clone(), true));
            markdown
        };
        drop(answers);
        ui.add(markdown);
    }

    /// How many answers are kept.
    #[cfg(test)]
    pub(super) fn held(&self) -> usize {
        self.0.borrow().len()
    }

    /// Lets go of the answers this frame did not draw and readies the rest for the next frame.
    fn settle(&self) {
        self.0.borrow_mut().retain(|_, (_, drawn)| std::mem::replace(drawn, false));
    }
}

fn thinking(ui: &mut View<'_, Msg>, text: &str) {
    let text = text.trim();
    if !text.is_empty() {
        ui.add(Text::new(text).role("faint"));
    }
}

/// A tool call: what it did, the diff it showed when it asked, and the start of its result.
fn call(app: &QCli, ui: &mut View<'_, Msg>, block: &Value, result: Option<(&str, bool)>) {
    let name = block["name"].as_str().unwrap_or_default();
    let id = block["id"].as_str().unwrap_or_default();
    ui.column(|ui| {
        match Action::from_call(name, &block["input"]) {
            Ok(action) => ui.add(Text::rich([
                Span::new(verb(action.kind())).color("accent").bold(),
                Span::new(" "),
                Span::new(action.subject().to_owned()),
            ])),
            Err(_) => ui.add(Text::new(name.to_owned()).color("accent").bold()),
        };
        if let Some(Preview::Diff { path, lines }) = app.previews.get(id) {
            diff(ui, path, lines);
        }
        if let Some((text, is_error)) = result {
            outcome(ui, text, is_error);
        }
    });
}

fn verb(kind: ActionKind) -> String {
    match kind {
        ActionKind::Read => t!("action.read"),
        ActionKind::List => t!("action.list"),
        ActionKind::Search => t!("action.search"),
        ActionKind::Edit => t!("action.edit"),
        ActionKind::Run => t!("action.run"),
    }
}

fn diff(ui: &mut View<'_, Msg>, path: &str, lines: &[crate::actions::DiffLine]) {
    let code: Vec<&str> = lines.iter().map(|line| line.text.as_str()).collect();
    let marks = lines.iter().map(|line| match line.change {
        Change::Same => LineMark::Unchanged,
        Change::Added => LineMark::Added,
        Change::Removed => LineMark::Removed,
    });
    ui.add(CodeView::new(code.join("\n"), Language::from_file_name(path)).line_marks(marks).line_numbers(false));
}

fn outcome(ui: &mut View<'_, Msg>, text: &str, is_error: bool) {
    let lines: Vec<&str> = text.lines().collect();
    let mut shown = lines.iter().take(RESULT_LINES).copied().collect::<Vec<_>>().join("\n");
    if lines.len() > RESULT_LINES {
        shown.push('\n');
        shown.push_str(&t!("action.more", n = lines.len() - RESULT_LINES));
    }
    if shown.trim().is_empty() {
        shown = t!("action.empty");
    }
    if is_error {
        marked(ui, &shown, ToastKind::Danger);
    } else {
        ui.add(Text::new(shown).role("faint")).selectable(true);
    }
}

/// What is streaming in right now.
fn live(app: &QCli, ui: &mut View<'_, Msg>) {
    for piece in &app.live {
        match piece {
            Live::Thinking(text) => thinking(ui, text),
            Live::Text(text) => answer(ui, text),
            // The tool's verb in the screen's language, as the line reads once the call is done;
            // a name that is none of the five is shown as it came.
            Live::Call(name) => {
                let shown = ActionKind::of_tool(name).map_or_else(|| name.clone(), verb);
                ui.add(Text::new(shown).color("accent").bold());
            }
        }
    }
}

/// The spinner while something is going on, the notice when something went wrong, and what the
/// turn that is over has cost.
fn status(app: &QCli, ui: &mut View<'_, Msg>) {
    match &app.phase {
        // Shown only for a wait long enough to notice, as every loading indicator of the
        // ecosystem is: a quick reply never blinks one.
        Phase::Replying if app.live.is_empty() => {
            ui.add(Spinner::new().label(t!("status.waiting")).delayed(true));
        }
        Phase::Acting { action, .. } => {
            ui.add(Spinner::new().label(t!("status.acting", what = action.subject().to_owned())).delayed(true));
            // What a command has written so far, its last few lines, so a long build or test run
            // is seen going by rather than as a wheel that turns.
            let lines: Vec<&str> = app.tail.lines().collect();
            let last = lines[lines.len().saturating_sub(TAIL_LINES)..].join("\n");
            if !last.trim().is_empty() {
                ui.add(Text::new(last).role("faint"));
            }
        }
        _ => {}
    }
    if let Some(notice) = &app.notice {
        let (text, tone) = match notice {
            Notice::Provider(said) => (t!("notice.provider", said = said.clone()), ToastKind::Danger),
            Notice::Unset => (t!("notice.unset"), ToastKind::Warning),
            Notice::Key(KeyError::Unreadable { path, reason }) => (
                t!("provider.key-unreadable", path = path.display().to_string(), reason = reason.clone()),
                ToastKind::Danger,
            ),
            Notice::Key(KeyError::NotAKey { path }) => {
                (t!("provider.not-a-key", path = path.display().to_string()), ToastKind::Danger)
            }
            Notice::Stopped => (t!("notice.stopped"), ToastKind::Warning),
            Notice::Cut => (t!("notice.cut"), ToastKind::Warning),
            Notice::Rounds => (t!("notice.rounds", n = super::MAX_ROUNDS), ToastKind::Warning),
            Notice::Unsaved(reason) => (t!("notice.unsaved", reason = reason.clone()), ToastKind::Danger),
            Notice::Profile => (t!("notice.profile"), ToastKind::Info),
        };
        marked(ui, &text, tone);
    }
    // What the turn cost, under whatever it has to say. Faint, because the person asked a
    // question and this is the bill for it, not the next thing to read. The two numbers go
    // through the framework's own formatter, so one screen never writes a number two ways. A turn
    // that used no token says nothing: a provider that counted nothing said nothing worth
    // repeating.
    if matches!(app.phase, Phase::Idle) && app.tokens.any() {
        let said = t!(
            "status.tokens",
            read = i18n::number(app.tokens.read as f64, 0),
            written = i18n::number(app.tokens.written as f64, 0),
        );
        ui.add(Text::new(said).role("faint"));
    }
}

/// A line whose tone is not told by its colour alone: the framework's status line puts the tone's
/// sign in front of it, so a person who cannot tell the colours apart, or a terminal that has
/// few, still reads it.
fn marked(ui: &mut View<'_, Msg>, text: &str, tone: ToastKind) {
    ui.add(StatusLine::new(text).tone(tone)).selectable(true);
}

/// The writing field under the conversation. It steps aside while a card waits for an answer,
/// so the letters that answer the card cannot be typed into it by mistake.
fn input(app: &QCli, ui: &mut View<'_, Msg>) {
    if matches!(app.phase, Phase::Asking { .. }) {
        return;
    }
    ui.add(
        TextInput::new(app.draft.clone())
            .placeholder(t!("chat.placeholder"))
            .on_change(Msg::Draft)
            .on_submit(|_| Msg::Send),
    )
    .id(INPUT)
    .fill_width()
    .padding(Padding::symmetric(0, 2));
}

fn card(ui: &mut View<'_, Msg>, action: &Action, preview: &Preview, ready: bool) {
    let title = match action.kind() {
        ActionKind::Edit => t!("ask.edit", path = action.subject().to_owned()),
        _ => t!("ask.run"),
    };
    ui.add_with(Panel::new().title(title).selected(true), |ui| {
        match preview {
            Preview::Diff { path, lines } => diff(ui, path, lines),
            Preview::Command { command } => {
                ui.add(CodeView::new(command.clone(), Language::Shell).line_numbers(false));
            }
            Preview::Plain => {
                ui.add(Text::new(action.summary()));
            }
        }
        buttons(ui, ready);
    });
}

/// The two buttons under a card's preview. Each names the key its own keymap action answers to,
/// read from the keymap the way the hint bar reads it, so a person who moves a binding sees the
/// key on the card move with it. Until the card is `ready` both are dimmed and take no press.
fn buttons(ui: &mut View<'_, Msg>, ready: bool) {
    let keymap = ui.env().keymap();
    let allow = keymap.chords_for(Scope::App, "allow").first().map(KeyChord::label);
    let deny = keymap.chords_for(Scope::App, "deny").first().map(KeyChord::label);
    let mut allow_button = Button::new(t!("ask.allow")).variant("primary").on_press(Msg::Allow).disabled(!ready);
    if let Some(key) = allow.clone() {
        allow_button = allow_button.shortcut(key);
    }
    let mut deny_button = Button::new(t!("ask.deny")).on_press(Msg::Deny).disabled(!ready);
    if let Some(key) = deny.clone() {
        deny_button = deny_button.shortcut(key);
    }
    // Side by side when the row fits the card, one above the other when it does not, so a narrow
    // terminal never cuts the answer the person is being asked for.
    let wide = |label: &str, key: &Option<String>| {
        u32::from(text::width(label)) + key.as_ref().map_or(0, |key| u32::from(text::width(key)) + 3) + 6
    };
    let row = wide(&t!("ask.allow"), &allow) + wide(&t!("ask.deny"), &deny) + CARD_GAP + CARD_AROUND;
    let build = |ui: &mut View<'_, Msg>| {
        ui.add(allow_button).id(ALLOW);
        ui.add(deny_button).id(DENY);
    };
    if row <= u32::from(ui.size().width) {
        ui.row(build).gap(2);
    } else {
        ui.column(build);
    }
}

/// The cells between a card's two buttons.
const CARD_GAP: u32 = 2;

/// The cells the conversation's margins, the card's frame and the scroll bar take from a row of
/// the card.
const CARD_AROUND: u32 = 9;