curd-editor 0.22.0

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a Claude panel that uses your own claude command
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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The Claude panel: ask Claude about the project, or to change it.
//!
//! `curd` does not talk to Anthropic itself and never sees a login. It
//! runs the `claude` command the user has installed and signed in to
//! (their Claude subscription), once per question, the way the docs
//! describe for other programs: `claude -p ... --output-format stream-json`.
//! The command prints one JSON object per line as it works, which is read
//! here and shown in the panel.

use std::collections::HashMap;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::process::{Child, Command, Stdio};
use std::time::Instant;

use crossterm::style::Color;

use serde_json::{json, Value};

use crate::highlight::{self, LineState};
use crate::screen::{fit, widen, Decoration, Row, Span, Style, WIDE_PAD};
use crate::snippets::Language;

#[cfg(test)]
mod tests;

/// The tools Claude is refused while the panel is read-only.
const WRITING_TOOLS: &str = "Edit,Write,NotebookEdit,Bash";

/// The most characters shown of something Claude did.
const STEP_CHARS: usize = 70;

/// One question for Claude.
pub struct Request<'a> {
    pub prompt: &'a str,
    /// The conversation to carry on, if one was started.
    pub session: Option<&'a str>,
    /// Whether Claude may change files.
    pub can_edit: bool,
    /// Whether it may also run commands (builds, tests) in the project.
    pub can_run: bool,
    /// What the editor is showing, for Claude to know.
    pub context: &'a str,
    /// The model to use, if not the command's own choice: a short name
    /// such as `opus`, or a model's full name.
    pub model: Option<&'a str>,
}

/// The command line to run for `request`.
///
/// `setting` is the CURD_AGENT environment variable: "off" turns the panel
/// off, and anything else is used in place of `claude`.
pub fn command_line(setting: Option<&str>, request: &Request) -> Option<Vec<String>> {
    let program = match setting.map(str::trim) {
        Some("off") => return None,
        Some(custom) if !custom.is_empty() => custom,
        _ => "claude",
    };
    let mut words: Vec<String> = program.split_whitespace().map(String::from).collect();
    let mut add = |extra: &[&str]| words.extend(extra.iter().map(|word| word.to_string()));
    add(&["--print", request.prompt]);
    // With partial messages the answer arrives word by word.
    add(&["--output-format", "stream-json", "--verbose", "--include-partial-messages"]);
    if let Some(session) = request.session {
        add(&["--resume", session]);
    }
    if let Some(model) = request.model {
        add(&["--model", model]);
    }
    if request.can_edit {
        add(&["--permission-mode", "acceptEdits"]);
        if request.can_run {
            add(&["--allowedTools", "Bash"]);
        }
    } else {
        add(&["--disallowedTools", WRITING_TOOLS]);
    }
    if !request.context.is_empty() {
        add(&["--append-system-prompt", request.context]);
    }
    Some(words)
}

/// Starts `words` (a command and its arguments) in `dir`. Every line it
/// prints is passed to `forward`, and `None` when it has finished.
pub fn start(
    words: &[String],
    dir: &Path,
    forward: impl Fn(Option<String>) + Send + Clone + 'static,
) -> std::io::Result<Child> {
    let mut child = Command::new(&words[0])
        .args(&words[1..])
        .current_dir(dir)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;
    // What it says when it fails is passed on in the same form as the rest.
    if let Some(errors) = child.stderr.take() {
        let forward = forward.clone();
        std::thread::spawn(move || {
            for line in BufReader::new(errors).lines().map_while(Result::ok) {
                forward(Some(json!({"type": "stderr", "text": line}).to_string()));
            }
        });
    }
    if let Some(output) = child.stdout.take() {
        std::thread::spawn(move || {
            for line in BufReader::new(output).lines().map_while(Result::ok) {
                forward(Some(line));
            }
            forward(None);
        });
    }
    Ok(child)
}

/// Something one line of the command's output says.
#[derive(Debug, PartialEq)]
pub enum Update {
    /// The name of the conversation, for carrying it on later.
    Session(String),
    /// The model that is answering.
    Model(String),
    /// The next few words of the answer, as they are written.
    Partial(String),
    /// A finished piece of the answer.
    Text(String),
    /// Something Claude did: read a file, searched, edited.
    Step(String),
    /// A line the command printed about a problem.
    Problem(String),
    /// The answer is complete.
    Done,
    /// It ended without an answer, and why.
    Failed(String),
}

/// Reads one line of `stream-json` output. Lines that say nothing the
/// panel shows give no updates.
pub fn parse(line: &str) -> Vec<Update> {
    let Ok(message) = serde_json::from_str::<Value>(line) else {
        return Vec::new();
    };
    let text = |value: &Value| value.as_str().unwrap_or_default().to_string();
    let mut updates = Vec::new();
    if let Some(session) = message["session_id"].as_str() {
        updates.push(Update::Session(session.to_string()));
    }
    match message["type"].as_str() {
        Some("system") => {
            if let Some(model) = message["model"].as_str() {
                updates.push(Update::Model(model.to_string()));
            }
        }
        Some("assistant") => {
            for block in message["message"]["content"].as_array().into_iter().flatten() {
                match block["type"].as_str() {
                    Some("text") if !text(&block["text"]).trim().is_empty() => {
                        updates.push(Update::Text(text(&block["text"]).trim().to_string()));
                    }
                    Some("tool_use") => updates.push(Update::Step(step(block))),
                    _ => {}
                }
            }
        }
        Some("result") => {
            let failed = message["is_error"].as_bool().unwrap_or(false)
                || message["subtype"].as_str().is_some_and(|kind| kind != "success");
            updates.push(if failed {
                let why = text(&message["result"]);
                Update::Failed(if why.is_empty() { text(&message["subtype"]) } else { why })
            } else {
                Update::Done
            });
        }
        Some("stream_event") => {
            let delta = &message["event"]["delta"];
            if delta["type"].as_str() == Some("text_delta") {
                updates.push(Update::Partial(text(&delta["text"])));
            }
        }
        Some("stderr") => updates.push(Update::Problem(text(&message["text"]))),
        _ => {}
    }
    updates
}

/// A short description of a tool Claude used: its name and what on.
fn step(block: &Value) -> String {
    let name = block["name"].as_str().unwrap_or("tool");
    let input = &block["input"];
    let on = ["file_path", "path", "pattern", "command", "query", "url", "description"]
        .iter()
        .find_map(|key| input[*key].as_str())
        .unwrap_or_default();
    let on = on.lines().next().unwrap_or_default();
    format!("{name} {on}").trim_end().to_string()
}

/// A step as the panel shows it: files named from the project folder
/// `root` rather than the top of the disk, and not too long.
pub fn shorten(step: &str, root: &Path) -> String {
    let root = format!("{}/", root.display());
    step.replace(&root, "").chars().take(STEP_CHARS).collect()
}

// ---- Earlier conversations ------------------------------------------------
//
// The `claude` command keeps every conversation as a file of JSON lines,
// one folder per project, under `~/.claude/projects`. Reading them is how
// the panel lists the earlier conversations and shows one again; carrying
// one on is the command's own `--resume`.

/// The most earlier conversations listed.
const MAX_SESSIONS: usize = 50;
/// How many lines into a conversation its first question is looked for.
const TITLE_LINES: usize = 400;

/// An earlier conversation about the project.
#[derive(Debug, PartialEq)]
pub struct SessionInfo {
    pub id: String,
    /// The first thing that was asked in it.
    pub title: String,
    pub modified: SystemTime,
}

/// The folder where `claude` keeps the conversations about the project in
/// `root`: under `home`, named after the project's path with everything
/// but letters and digits turned into `-`.
pub fn sessions_dir(home: &Path, root: &Path) -> PathBuf {
    let name: String = root
        .to_string_lossy()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();
    home.join(".claude").join("projects").join(name)
}

/// What a line of a conversation file holds, as lines for the panel.
fn transcript_line(line: &str) -> Vec<(Who, String)> {
    let Ok(message) = serde_json::from_str::<Value>(line) else {
        return Vec::new();
    };
    // Notes the command wrote for itself, and its helpers' side talk.
    if message["isMeta"].as_bool() == Some(true) || message["isSidechain"].as_bool() == Some(true) {
        return Vec::new();
    }
    let content = &message["message"]["content"];
    let mut entries = Vec::new();
    let mut said = |who: Who, text: &str| {
        let text = text.trim();
        // Anything in <tags> was put there by a program, not typed.
        if !text.is_empty() && !text.starts_with('<') {
            entries.push((who, text.to_string()));
        }
    };
    match message["type"].as_str() {
        Some("user") => match content.as_str() {
            Some(text) => said(Who::You, text),
            None => {
                for block in content.as_array().into_iter().flatten() {
                    if block["type"].as_str() == Some("text") {
                        said(Who::You, block["text"].as_str().unwrap_or_default());
                    }
                }
            }
        },
        Some("assistant") => {
            for block in content.as_array().into_iter().flatten() {
                match block["type"].as_str() {
                    Some("text") => said(Who::Claude, block["text"].as_str().unwrap_or_default()),
                    Some("tool_use") => said(Who::Note, &step(block)),
                    _ => {}
                }
            }
        }
        _ => {}
    }
    entries
}

/// The earlier conversations kept in `dir`, newest first.
pub fn list_sessions(dir: &Path) -> Vec<SessionInfo> {
    let mut sessions: Vec<SessionInfo> = std::fs::read_dir(dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|item| {
            let path = item.path();
            let id = path.file_stem()?.to_str()?.to_string();
            if path.extension()?.to_str()? != "jsonl" {
                return None;
            }
            let modified = item.metadata().ok()?.modified().ok()?;
            let lines = BufReader::new(std::fs::File::open(&path).ok()?).lines();
            let title = lines
                .map_while(Result::ok)
                .take(TITLE_LINES)
                .flat_map(|line| transcript_line(&line))
                .find(|(who, _)| *who == Who::You)?
                .1;
            let title = title.lines().next().unwrap_or_default().to_string();
            Some(SessionInfo { id, title, modified })
        })
        .collect();
    sessions.sort_by_key(|session| std::cmp::Reverse(session.modified));
    sessions.truncate(MAX_SESSIONS);
    sessions
}

/// Everything said in conversation `id` kept in `dir`.
pub fn load_session(dir: &Path, id: &str) -> Vec<(Who, String)> {
    let Ok(file) = std::fs::File::open(dir.join(format!("{id}.jsonl"))) else {
        return Vec::new();
    };
    BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .flat_map(|line| transcript_line(&line))
        .collect()
}

/// How long ago `then` was, in a few characters: "5m", "3h", "12d".
pub fn age(then: SystemTime, now: SystemTime) -> String {
    let minutes = now.duration_since(then).map_or(0, |passed| passed.as_secs() / 60);
    match minutes {
        0 => "now".into(),
        1..60 => format!("{minutes}m"),
        60..1440 => format!("{}h", minutes / 60),
        _ => format!("{}d", minutes / 1440),
    }
}

// ---- What Claude changed --------------------------------------------------

/// Files bigger than this are watched for changes but not kept for undo.
const MAX_KEPT_BYTES: u64 = 512 * 1024;
/// The most the files kept for undo may take together.
const MAX_SNAPSHOT_BYTES: u64 = 32 * 1024 * 1024;

/// What happened to a file while Claude worked.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChangeKind {
    Created,
    Modified,
    Deleted,
}

#[derive(Debug, PartialEq)]
pub struct Change {
    /// The file, relative to the project folder.
    pub file: String,
    pub kind: ChangeKind,
}

/// One file as it was before Claude started.
struct Before {
    len: u64,
    modified: Option<SystemTime>,
    /// What was in it; `None` if it was too big to keep.
    content: Option<Vec<u8>>,
}

/// The project's files as they were before Claude started on an answer,
/// to tell afterwards what it changed and to be able to put it back.
pub struct Snapshot {
    root: PathBuf,
    files: HashMap<String, Before>,
}

impl Snapshot {
    /// Remembers `files` (relative to `root`) as they are now.
    pub fn take(root: &Path, files: &[String]) -> Self {
        let mut kept = 0;
        let mut before = HashMap::new();
        for file in files {
            let path = root.join(file);
            let Ok(data) = std::fs::metadata(&path) else {
                continue;
            };
            let fits = data.len() <= MAX_KEPT_BYTES && kept + data.len() <= MAX_SNAPSHOT_BYTES;
            let content = fits.then(|| std::fs::read(&path).ok()).flatten();
            kept += content.as_ref().map_or(0, |content| content.len() as u64);
            before.insert(
                file.clone(),
                Before {
                    len: data.len(),
                    modified: data.modified().ok(),
                    content,
                },
            );
        }
        Self {
            root: root.to_path_buf(),
            files: before,
        }
    }

    /// What is different now, given the project's files as they are now
    /// (`files`), in alphabetical order.
    pub fn changes(&self, files: &[String]) -> Vec<Change> {
        let mut changes = Vec::new();
        for file in files {
            let path = self.root.join(file);
            let kind = match self.files.get(file) {
                // Listed, but not there: nothing was made.
                None if !path.exists() => continue,
                None => ChangeKind::Created,
                Some(before) => {
                    let same = match (&before.content, std::fs::metadata(&path)) {
                        (Some(content), Ok(_)) => std::fs::read(&path).is_ok_and(|now| now == *content),
                        (None, Ok(data)) => {
                            data.len() == before.len && data.modified().ok() == before.modified
                        }
                        // Listed, but not there to look at: leave it be.
                        (_, Err(_)) => true,
                    };
                    if same {
                        continue;
                    }
                    ChangeKind::Modified
                }
            };
            changes.push(Change { file: file.clone(), kind });
        }
        for file in self.files.keys() {
            if !self.root.join(file).exists() {
                changes.push(Change { file: file.clone(), kind: ChangeKind::Deleted });
            }
        }
        changes.sort_by(|a, b| a.file.cmp(&b.file));
        changes
    }

    /// Puts the files of `changes` back the way they were: new ones are
    /// removed, the others get their old contents. Returns how many were
    /// put back and how many could not be (too big to have been kept).
    pub fn restore(&self, changes: &[Change]) -> (usize, usize) {
        let (mut restored, mut failed) = (0, 0);
        for change in changes {
            let path = self.root.join(&change.file);
            let done = match (change.kind, self.files.get(&change.file)) {
                (ChangeKind::Created, _) => std::fs::remove_file(&path).is_ok(),
                (_, Some(Before { content: Some(content), .. })) => {
                    let folder = path.parent().unwrap_or(&self.root);
                    std::fs::create_dir_all(folder).is_ok() && std::fs::write(&path, content).is_ok()
                }
                _ => false,
            };
            if done {
                restored += 1;
            } else {
                failed += 1;
            }
        }
        (restored, failed)
    }
}

/// One line saying what `changes` are: "Changed 2 files: a.rs, new b.rs".
pub fn describe(changes: &[Change]) -> String {
    let names: Vec<String> = changes
        .iter()
        .map(|change| match change.kind {
            ChangeKind::Created => format!("new {}", change.file),
            ChangeKind::Modified => change.file.clone(),
            ChangeKind::Deleted => format!("deleted {}", change.file),
        })
        .collect();
    let files = if changes.len() == 1 { "file" } else { "files" };
    format!("Changed {} {files}: {}", changes.len(), names.join(", "))
}

/// Who a line in the panel is from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Who {
    You,
    Claude,
    /// The editor itself: what Claude did, and problems.
    Note,
}

/// The panel under the text: the conversation so far and the line being
/// typed.
#[derive(Default)]
pub struct Panel {
    pub entries: Vec<(Who, String)>,
    /// The question being typed, and where the cursor is in it.
    pub input: String,
    cursor: usize,
    /// The questions asked before, oldest first, for the Up key.
    history: Vec<String>,
    /// Which of them is in `input`, while going through them.
    history_at: Option<usize>,
    pub session: Option<String>,
    /// The model asked for (`None`: the command's own choice), and the
    /// one that last answered, by its full name.
    pub model: Option<String>,
    pub answered_by: Option<String>,
    /// Files to go along with the next question, from the project folder.
    pub attached: Vec<String>,
    pub can_edit: bool,
    /// Whether it may also run commands. Only counts with `can_edit`.
    pub can_run: bool,
    /// True while Claude is working on an answer.
    pub running: bool,
    /// When it started on the answer.
    started: Option<Instant>,
    /// True while the last entry is an answer still being written.
    partial: bool,
    /// How many rows the view is scrolled up from the newest line.
    scroll: usize,
}

const SPINNER: [char; 10] = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
/// The most rows the question being typed takes.
const MAX_INPUT_ROWS: usize = 5;

const HINTS: [&str; 6] = [
    "Ask about this project and press Enter. Alt+Enter starts a new line.",
    "Type / for commands (model, new conversation, ...) and @ to attach a file.",
    "Text selected in the file is sent along with the question.",
    "Claude may change files. Alt+M: read only, or also run commands. Alt+U undoes.",
    "Ctrl+R lists the earlier conversations. Ctrl+N starts a new one.",
    "Esc goes back to the text. Alt+Z makes this panel bigger.",
];

impl Panel {
    /// A panel as the editor starts with: Claude may change files.
    pub fn new() -> Self {
        Self {
            can_edit: true,
            ..Self::default()
        }
    }

    pub fn say(&mut self, who: Who, text: impl Into<String>) {
        self.entries.push((who, text.into()));
        self.partial = false;
        // Something new: show it.
        self.scroll = 0;
    }

    /// Notes that Claude has started on an answer.
    pub fn start(&mut self) {
        self.running = true;
        self.started = Some(Instant::now());
    }

    /// Takes in what a line of output said. Returns true when the answer
    /// has ended, one way or the other.
    pub fn apply(&mut self, update: Update) -> bool {
        match update {
            Update::Session(session) => self.session = Some(session),
            Update::Model(model) => self.answered_by = Some(model),
            Update::Partial(words) => match self.entries.last_mut() {
                Some((Who::Claude, text)) if self.partial => text.push_str(&words),
                _ => {
                    self.say(Who::Claude, words);
                    self.partial = true;
                }
            },
            // The finished piece replaces what was shown while it was
            // being written.
            Update::Text(text) => {
                if self.partial {
                    self.entries.pop();
                }
                self.say(Who::Claude, text);
            }
            Update::Step(step) => self.say(Who::Note, step),
            Update::Problem(problem) => self.say(Who::Note, problem),
            Update::Done => self.running = false,
            Update::Failed(why) => {
                self.running = false;
                self.say(Who::Note, format!("Stopped: {why}"));
            }
        }
        !self.running
    }

    /// Alt+M: goes on to the next of what Claude may do. It may change
    /// files; then only read; then change files and run commands as well.
    pub fn next_mode(&mut self) {
        (self.can_edit, self.can_run) = match (self.can_edit, self.can_run) {
            (true, false) => (false, false),
            (false, _) => (true, true),
            (true, true) => (true, false),
        };
    }

    /// Shows an earlier conversation, to carry it on.
    pub fn resume(&mut self, id: String, entries: Vec<(Who, String)>) {
        self.entries = entries;
        self.session = Some(id);
        self.partial = false;
        self.scroll = 0;
    }

    /// Forgets the conversation, to start a new one.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.session = None;
        self.scroll = 0;
    }

    /// The last thing Claude said.
    pub fn last_answer(&self) -> Option<&str> {
        self.entries
            .iter()
            .rev()
            .find(|(who, _)| *who == Who::Claude)
            .map(|(_, text)| text.as_str())
    }

    /// Scrolls `rows` towards older lines (newer, when negative).
    pub fn scroll_by(&mut self, rows: isize) {
        self.scroll = (self.scroll as isize + rows).max(0) as usize;
    }

    // ---- The line being typed ------------------------------------------

    /// Where character `at` of the question starts, in bytes.
    fn byte(&self, at: usize) -> usize {
        self.input.char_indices().nth(at).map_or(self.input.len(), |(byte, _)| byte)
    }

    pub fn type_char(&mut self, c: char) {
        let at = self.byte(self.cursor);
        self.input.insert(at, c);
        self.cursor += 1;
    }

    /// Deletes the character before the cursor. On an empty line it takes
    /// off the file attached last.
    pub fn backspace(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            self.delete();
        } else if self.input.is_empty() {
            self.attached.pop();
        }
    }

    /// Attaches `file` to the next question, once.
    pub fn attach(&mut self, file: String) {
        if !self.attached.contains(&file) {
            self.attached.push(file);
        }
    }

    /// Puts `text` on the line in place of what is there.
    pub fn set_input(&mut self, text: &str) {
        self.input = text.to_string();
        self.cursor = self.input.chars().count();
    }

    /// The question as rows of at most `room` characters, and the row and
    /// column the cursor is at. Rows break where a line break was typed
    /// and where a row is full.
    fn input_rows(&self, room: usize) -> (Vec<String>, (usize, usize)) {
        let mut rows = vec![String::new()];
        let mut used = 0;
        let mut cursor = (0, 0);
        for (index, c) in self.input.chars().chain(std::iter::once('\0')).enumerate() {
            use unicode_width::UnicodeWidthChar;
            // Cells the character takes: two for a wide one, none for a
            // mark that joins the letter before it.
            let cells = c.width().unwrap_or(0);
            if used + cells.max(1) > room && c != '\n' {
                rows.push(String::new());
                used = 0;
            }
            if index == self.cursor {
                cursor = (rows.len() - 1, used);
            }
            match c {
                '\n' => {
                    rows.push(String::new());
                    used = 0;
                }
                c if cells > 0 => {
                    let row = rows.last_mut().unwrap();
                    row.push(c);
                    if cells == 2 {
                        row.push(WIDE_PAD);
                    }
                    used += cells;
                }
                _ => {}
            }
        }
        (rows, cursor)
    }

    /// How many rows at the bottom of a panel `width` wide and `height`
    /// tall the question takes, with the row above it.
    pub fn box_rows(&self, width: usize, height: usize) -> usize {
        let room = width.saturating_sub(3).max(1);
        let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
        self.input_rows(room).0.len().min(most) + (height >= 5) as usize
    }

    /// One row that says what the next question goes with: the model, and
    /// the attached files.
    fn status(&self) -> String {
        let model = match (&self.model, &self.answered_by) {
            (Some(model), _) => model.clone(),
            (None, Some(answered)) => answered.clone(),
            (None, None) => "default model".into(),
        };
        let files: String = self.attached.iter().map(|file| format!("  @{file}")).collect();
        format!(" {model}{files}")
    }

    /// Deletes the character under the cursor.
    pub fn delete(&mut self) {
        let at = self.byte(self.cursor);
        if at < self.input.len() {
            self.input.remove(at);
        }
    }

    /// Moves the cursor `step` characters right (left, when negative),
    /// staying inside the question.
    pub fn move_cursor(&mut self, step: isize) {
        let end = self.input.chars().count() as isize;
        self.cursor = (self.cursor as isize).saturating_add(step).clamp(0, end) as usize;
    }

    /// Puts an earlier question back on the line (`step` -1), or a later
    /// one (1); past the latest, the line is empty again.
    pub fn recall(&mut self, step: isize) {
        let count = self.history.len() as isize;
        let at = self.history_at.map_or(count, |at| at as isize) + step;
        if at < 0 || count == 0 {
            return;
        }
        self.history_at = (at < count).then_some(at as usize);
        self.input = self.history_at.map(|at| self.history[at].clone()).unwrap_or_default();
        self.cursor = self.input.chars().count();
    }

    /// Takes the question off the line to send it. `None` if it is empty.
    pub fn take_input(&mut self) -> Option<String> {
        let question = self.input.trim().to_string();
        if question.is_empty() {
            return None;
        }
        self.input.clear();
        self.cursor = 0;
        self.history_at = None;
        if self.history.last() != Some(&question) {
            self.history.push(question.clone());
        }
        Some(question)
    }

    // ---- Drawing -------------------------------------------------------

    /// The conversation as rows of `width` characters.
    fn lines(&self, width: usize) -> Vec<Row> {
        let mut lines: Vec<Row> = Vec::new();
        let plain = |style: Style, text: String| vec![Span::new(style, fit(&text, width))];
        for (who, text) in &self.entries {
            // An empty row sets each question apart from the answer before.
            if *who == Who::You && !lines.is_empty() {
                lines.push(plain(Style::Plain, String::new()));
            }
            let (style, first, rest) = match who {
                Who::You => (Style::Accent, "> ", "  "),
                Who::Note => (Style::Dim, "· ", "  "),
                Who::Claude => {
                    lines.extend(markdown(text, width));
                    continue;
                }
            };
            for (index, line) in wrap(&widen(text), width.saturating_sub(2)).into_iter().enumerate() {
                let prefix = if index == 0 { first } else { rest };
                lines.push(plain(style, format!("{prefix}{line}")));
            }
        }
        lines
    }

    /// The panel as `height` rows: a title, the conversation, a row
    /// saying what the question goes with, and the question being typed.
    /// Also where the cursor goes: column and row.
    pub fn render(&mut self, width: usize, height: usize, focused: bool) -> (Vec<Row>, (usize, usize)) {
        let state = if self.running {
            let waited = self.started.map_or(0, |started| started.elapsed().as_millis());
            let spinner = SPINNER[(waited / 120) as usize % SPINNER.len()];
            format!("{spinner} working {}s (Esc stops it)", waited / 1000)
        } else if self.can_edit && self.can_run {
            "may change files and run commands (Alt+M)".into()
        } else if self.can_edit {
            "may change files (Alt+M: read only)".into()
        } else {
            "read only (Alt+M: also run commands)".into()
        };
        let title_style = if focused { Style::Title } else { Style::Menu };
        let mut rows = vec![vec![Span::new(title_style, fit(&format!(" Claude · {state}"), width))]];

        // The question: as many rows as it needs, up to a few, keeping
        // the row with the cursor in view.
        let room = width.saturating_sub(3).max(1);
        let (question, (cursor_row, cursor_x)) = self.input_rows(room);
        let most = MAX_INPUT_ROWS.min(height.saturating_sub(3)).max(1);
        let from = (cursor_row + 1).saturating_sub(most);
        let question: Vec<&String> = question.iter().skip(from).take(most).collect();
        // The row above it only where there is room for some conversation.
        let status = (height >= 5) as usize;

        let body = height.saturating_sub(1 + status + question.len());
        let lines = self.lines(width);
        self.scroll = self.scroll.min(lines.len().saturating_sub(body));
        let first = lines.len().saturating_sub(body + self.scroll);
        let mut shown: Vec<Row> = lines.into_iter().skip(first).take(body).collect();
        if shown.is_empty() {
            let hints = HINTS.iter().take(body);
            shown.extend(hints.map(|hint| vec![Span::new(Style::Dim, fit(hint, width))]));
        }
        shown.resize(body, vec![Span::new(Style::Plain, fit("", width))]);
        rows.extend(shown);

        if status > 0 {
            rows.push(vec![Span::new(Style::FieldNote, fit(&self.status(), width))]);
        }
        let first_row = rows.len();
        for (index, row) in question.iter().enumerate() {
            let mark = if index + from == 0 { "> " } else { "  " };
            rows.push(vec![Span::new(Style::Field, fit(&format!("{mark}{row}"), width))]);
        }
        rows.truncate(height);
        let cursor = (2 + cursor_x, (first_row + cursor_row - from).min(height.saturating_sub(1)));
        (rows, cursor)
    }
}

// ---- The `/` commands ------------------------------------------------------

/// The commands of the user's own that the `claude` command knows: the
/// files in the `commands` folders and the folders in the `skills`
/// folders, under `.claude` in the project `root` and in `home`.
pub fn own_commands(home: &Path, root: &Path) -> Vec<String> {
    let mut names = Vec::new();
    for base in [root.join(".claude"), home.join(".claude")] {
        for (folder, wants_dir) in [("commands", false), ("skills", true)] {
            for item in std::fs::read_dir(base.join(folder)).into_iter().flatten().flatten() {
                let path = item.path();
                let is_command = !wants_dir && path.extension().is_some_and(|ext| ext == "md");
                let is_skill = wants_dir && path.is_dir();
                if let (true, Some(name)) = (is_command || is_skill, path.file_stem()) {
                    names.push(name.to_string_lossy().into_owned());
                }
            }
        }
    }
    names.sort();
    names.dedup();
    names
}

/// Breaks `text` into lines of at most `width` characters, at spaces where
/// it can.
pub fn wrap(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    for line in text.split('\n') {
        let chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
        let pieces = wrap_chars(&chars, width);
        lines.extend(pieces.iter().map(|piece| piece.iter().map(|(c, _)| *c).collect()));
    }
    lines
}

/// Breaks one line of styled characters into pieces of at most `width`,
/// at spaces where it can.
fn wrap_chars(chars: &[(char, Style)], width: usize) -> Vec<&[(char, Style)]> {
    let width = width.max(1);
    let mut pieces = Vec::new();
    let mut start = 0;
    while chars.len() - start > width {
        let limit = start + width;
        let cut = (start + 1..=limit).rev().find(|at| chars[*at].0 == ' ').unwrap_or(limit);
        pieces.push(&chars[start..cut]);
        start = cut + (chars[cut].0 == ' ') as usize;
    }
    pieces.push(&chars[start..]);
    pieces
}

/// Styled characters as one row of `width` characters, after `prefix`.
fn row_of(prefix: Option<Span>, chars: &[(char, Style)], width: usize) -> Row {
    let mut row: Row = prefix.into_iter().collect();
    let mut used: usize = row.iter().map(|span| span.text.chars().count()).sum();
    for (c, style) in chars {
        match row.last_mut() {
            Some(last) if last.style == *style => last.text.push(*c),
            _ => row.push(Span::new(*style, c.to_string())),
        }
    }
    used += chars.len();
    row.push(Span::new(Style::Plain, " ".repeat(width.saturating_sub(used))));
    row
}

/// The language a block of code is in, from the word after its opening
/// fence: ```rust.
fn fence_language(tag: &str) -> Option<Language> {
    let extension = match tag.trim().to_ascii_lowercase().as_str() {
        "rust" => "rs".into(),
        "python" => "py".into(),
        "javascript" | "typescript" => "js".into(),
        "c++" => "cpp".into(),
        "golang" => "go".into(),
        other => other.to_string(),
    };
    Language::from_path(&format!("code.{extension}"))
}

/// One line of ordinary text as styled characters: `code` in colour,
/// **bold** in bold, and the marks themselves left out.
fn inline(text: &str, base: Style) -> Vec<(char, Style)> {
    let code = Style::Colored(Color::Cyan);
    let chars: Vec<char> = text.chars().collect();
    let (mut in_code, mut bold) = (false, false);
    let mut styled = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        match chars[i] {
            '`' => in_code = !in_code,
            '*' if !in_code && chars.get(i + 1) == Some(&'*') => {
                bold = !bold;
                i += 1;
            }
            c if in_code => styled.push((c, code)),
            c if bold => styled.push((c, Style::Bold)),
            c => styled.push((c, base)),
        }
        i += 1;
    }
    styled
}

/// An answer as rows: Markdown the way a terminal can show it. Headings
/// are bold, list items get a bullet, and blocks of code are set apart by
/// a bar and coloured like code in the editor.
pub fn markdown(text: &str, width: usize) -> Vec<Row> {
    let mut rows = Vec::new();
    // Inside a block of code: its language, if known, and what the next
    // line starts inside of (a comment or string left open).
    let mut code: Option<(Option<Language>, LineState)> = None;
    for line in text.split('\n') {
        // One character per cell of the screen, so wide characters and
        // tabs keep the rows the right width.
        let line = &widen(line);
        if let Some(tag) = line.trim_start().strip_prefix("```") {
            code = match code {
                Some(_) => None,
                None => Some((fence_language(tag), LineState::Code)),
            };
            continue;
        }
        let Some((language, state)) = &mut code else {
            let trimmed = line.trim_start();
            let indent = &line[..line.len() - trimmed.len()];
            let heading = trimmed.trim_start_matches('#');
            let chars = if heading.len() < trimmed.len() && heading.starts_with(' ') {
                inline(heading.trim_start(), Style::Bold)
            } else if let Some(item) = trimmed.strip_prefix("- ").or(trimmed.strip_prefix("* ")) {
                inline(&format!("{indent}• {item}"), Style::Plain)
            } else {
                inline(line, Style::Plain)
            };
            for piece in wrap_chars(&chars, width) {
                rows.push(row_of(None, piece, width));
            }
            continue;
        };
        let mut chars: Vec<(char, Style)> = line.chars().map(|c| (c, Style::Plain)).collect();
        if let Some(language) = language {
            let mut tokens = Vec::new();
            *state = highlight::lex_line(line, *language, *state, &mut tokens);
            for token in tokens {
                let decoration = Decoration { kind: token.kind, ..Decoration::default() };
                let end = token.end.min(chars.len());
                for (_, style) in &mut chars[token.start.min(end)..end] {
                    *style = Style::Code(decoration);
                }
            }
        }
        for piece in wrap_chars(&chars, width.saturating_sub(2)) {
            rows.push(row_of(Some(Span::new(Style::Dim, "│ ")), piece, width));
        }
    }
    rows
}